From c49f5e7a2f04ec34bd587878adee93e7782cd41e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 30 Oct 2026 23:34:17 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20rewrite=20editor=20in=20Rus?= =?UTF-8?q?t=20and=20add=20media=20with=20live=20recording?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the TypeScript ProseMirror editor with a Rust wasm editor on a single Loro text document, and remove the bun build. Add media storage on the raw filesystem: uploads, Range serving, embeds, paste and drop, import rewriting and zip export. Add live audio recording. Takes are WebM/Opus with a permanent URL and stream over a dedicated socket, so a browser crash loses at most about the last second. A take can be continued later; its parts are joined with Symphonia and our own WebM writer. The server never edits a note. --- .cargo/config.toml | 2 + .gitignore | 5 +- Cargo.lock | 1453 +++- Cargo.toml | 51 +- assets/editor.css | 1147 +++- assets/editor.js | 16 - assets/editor.js.map | 37 - assets/loro-856987111b05.wasm | Bin 3595346 -> 0 bytes build.rs | 2 + crates/editor/Cargo.toml | 108 + crates/editor/src/core/commands.rs | 1390 ++++ crates/editor/src/core/doc.rs | 60 + crates/editor/src/core/history.rs | 89 + crates/editor/src/core/marks.rs | 151 + crates/editor/src/core/mod.rs | 11 + crates/editor/src/core/model.rs | 800 +++ crates/editor/src/core/pos.rs | 131 + crates/editor/src/core/tests.rs | 212 + crates/editor/src/core/testutil.rs | 113 + crates/editor/src/editor.rs | 917 +++ crates/editor/src/lib.rs | 189 + crates/editor/src/rules.rs | 188 + crates/editor/src/strings.rs | 24 + crates/editor/src/sync.rs | 480 ++ crates/editor/src/ui/clipboard.rs | 571 ++ crates/editor/src/ui/codeblock.rs | 800 +++ crates/editor/src/ui/floating.rs | 966 +++ crates/editor/src/ui/media.rs | 777 +++ crates/editor/src/ui/mod.rs | 170 + crates/editor/src/ui/notelinks.rs | 606 ++ crates/editor/src/ui/presence.rs | 399 ++ crates/editor/src/ui/toolbar.rs | 435 ++ crates/editor/src/view.rs | 1966 ++++++ crates/note-model/Cargo.toml | 10 + crates/note-model/src/blocks.rs | 763 +++ crates/note-model/src/flat.rs | 655 ++ crates/note-model/src/lang.rs | 321 + crates/note-model/src/lib.rs | 14 + crates/note-model/src/links.rs | 80 + crates/note-model/src/marks.rs | 39 + crates/note-model/src/render.rs | 302 + crates/note-model/src/schema.rs | 43 + crates/note-model/src/tree.rs | 24 + crates/note-model/src/write.rs | 74 + src/app.rs | 80 +- src/app/export_all.rs | 367 +- src/app/format.rs | 34 + src/app/import.rs | 226 +- src/app/media.rs | 449 ++ src/app/notebooks/notebook_id.rs | 16 +- src/app/notes.rs | 10 +- src/app/notes/note_id.rs | 136 +- src/app/notes/note_id/history.rs | 2 +- src/app/notes/note_id/ws.rs | 4 +- src/app/palette.rs | 18 +- src/app/pane.rs | 79 +- src/app/search.rs | 35 +- src/app/shell.rs | 20 +- src/app/trash.rs | 20 +- src/app/unfiled.rs | 13 +- src/editor_assets.rs | 60 + src/export.rs | 529 +- src/export/html.rs | 194 +- src/format.rs | 140 + src/hub.rs | 748 +- src/i18n.rs | 243 + src/import.rs | 496 +- src/main.rs | 15 +- src/matcher.rs | 281 +- src/media.rs | 321 + src/media/webm.rs | 389 ++ src/store.rs | 1659 ++++- src/store/directory.rs | 461 ++ src/zipout.rs | 117 + vendor/loro-internal/.gitignore | 1 + vendor/loro-internal/AGENTS.md | 121 + vendor/loro-internal/CLAUDE.md | 121 + vendor/loro-internal/Cargo.lock | 2060 ++++++ vendor/loro-internal/Cargo.toml | 374 + vendor/loro-internal/Cargo.toml.orig | 134 + vendor/loro-internal/Encoding.md | 25 + vendor/loro-internal/README.md | 5 + vendor/loro-internal/VERSION | 1 + .../benches/automerge-paper.json.gz | Bin 0 -> 901823 bytes vendor/loro-internal/benches/encode.rs | 398 ++ vendor/loro-internal/benches/event.rs | 48 + vendor/loro-internal/benches/jsonpath.rs | 317 + vendor/loro-internal/benches/list.rs | 119 + vendor/loro-internal/benches/map.rs | 85 + vendor/loro-internal/benches/pending.rs | 47 + .../loro-internal/benches/shallow_export.rs | 164 + vendor/loro-internal/benches/text_r.rs | 432 ++ vendor/loro-internal/benches/tree.rs | 166 + vendor/loro-internal/deno.json | 10 + vendor/loro-internal/deno.lock | 134 + .../docs/critical-version-spec.md | 705 ++ vendor/loro-internal/docs/diff_calc.md | 125 + .../docs/mergeable-container-id.md | 87 + .../loro-internal/examples/automerge_x100.rs | 41 + vendor/loro-internal/examples/encoding.rs | 155 + .../examples/encoding_parallel.rs | 90 + .../examples/encoding_refactored.rs | 115 + vendor/loro-internal/examples/event.rs | 66 + vendor/loro-internal/examples/list.rs | 23 + vendor/loro-internal/examples/many_actors.rs | 60 + vendor/loro-internal/examples/mem.rs | 110 + vendor/loro-internal/examples/obs.rs | 26 + vendor/loro-internal/examples/pending.rs | 33 + vendor/loro-internal/examples/state_size.rs | 127 + vendor/loro-internal/examples/tree.rs | 83 + .../proptest-regressions/dag/test.txt | 10 + vendor/loro-internal/scripts/fuzz.ts | 36 + vendor/loro-internal/scripts/mem.ts | 49 + vendor/loro-internal/scripts/run_mem.ts | 9 + vendor/loro-internal/src/allocation/bfs.rs | 386 ++ vendor/loro-internal/src/allocation/dfs.rs | 416 ++ vendor/loro-internal/src/allocation/mod.rs | 10 + vendor/loro-internal/src/arena.rs | 1037 +++ vendor/loro-internal/src/arena/str_arena.rs | 253 + vendor/loro-internal/src/awareness.rs | 873 +++ vendor/loro-internal/src/change.rs | 329 + vendor/loro-internal/src/change_meta.rs | 98 + vendor/loro-internal/src/configure.rs | 337 + vendor/loro-internal/src/container.rs | 314 + .../src/container/list/list_op.rs | 818 +++ .../loro-internal/src/container/list/mod.rs | 1 + .../src/container/map/map_content.rs | 42 + vendor/loro-internal/src/container/map/mod.rs | 3 + .../loro-internal/src/container/richtext.rs | 300 + .../src/container/richtext/config.rs | 133 + .../src/container/richtext/fugue_span.rs | 386 ++ .../src/container/richtext/richtext_state.rs | 3690 ++++++++++ .../richtext_state/insert_pos_cache_test.rs | 172 + .../src/container/richtext/str_slice.rs | 48 + .../src/container/richtext/style_range_map.rs | 690 ++ .../src/container/richtext/tinyvec.rs | 289 + .../src/container/richtext/tracker.rs | 896 +++ .../container/richtext/tracker/crdt_rope.rs | 953 +++ .../richtext/tracker/id_to_cursor.rs | 1222 ++++ .../src/container/tree/bool_rle_vec.rs | 442 ++ .../loro-internal/src/container/tree/mod.rs | 3 + .../src/container/tree/tree_ds.rs | 115 + .../src/container/tree/tree_op.rs | 75 + vendor/loro-internal/src/cursor.rs | 111 + vendor/loro-internal/src/dag.rs | 2024 ++++++ vendor/loro-internal/src/dag/iter.rs | 637 ++ vendor/loro-internal/src/dag/mermaid.rs | 320 + vendor/loro-internal/src/dag/test.excalidraw | 4334 ++++++++++++ vendor/loro-internal/src/dag/test.rs | 1467 ++++ vendor/loro-internal/src/delta.rs | 14 + vendor/loro-internal/src/delta/map.rs | 203 + vendor/loro-internal/src/delta/map_delta.rs | 315 + .../loro-internal/src/delta/movable_list.rs | 56 + vendor/loro-internal/src/delta/seq.rs | 950 +++ vendor/loro-internal/src/delta/text.rs | 298 + vendor/loro-internal/src/delta/tree.rs | 209 + vendor/loro-internal/src/diff/LICENSE | 201 + vendor/loro-internal/src/diff/diff_impl.rs | 857 +++ vendor/loro-internal/src/diff/mod.rs | 4 + vendor/loro-internal/src/diff_calc.rs | 2635 +++++++ vendor/loro-internal/src/diff_calc/counter.rs | 63 + .../src/diff_calc/tracker_texts.rs | 195 + .../src/diff_calc/tracker_values.rs | 128 + vendor/loro-internal/src/diff_calc/tree.rs | 725 ++ vendor/loro-internal/src/diff_calc/unknown.rs | 32 + vendor/loro-internal/src/encoding.rs | 658 ++ vendor/loro-internal/src/encoding/AGENTS.md | 42 + vendor/loro-internal/src/encoding/CLAUDE.md | 42 + vendor/loro-internal/src/encoding/arena.rs | 277 + .../src/encoding/fast_snapshot.rs | 629 ++ .../loro-internal/src/encoding/json_schema.rs | 1911 ++++++ .../src/encoding/outdated_encode_reordered.rs | 649 ++ .../src/encoding/shallow_snapshot.rs | 1979 ++++++ vendor/loro-internal/src/encoding/value.rs | 1535 +++++ .../src/encoding/value_register.rs | 52 + vendor/loro-internal/src/error.rs | 1 + vendor/loro-internal/src/estimated_size.rs | 27 + vendor/loro-internal/src/event.rs | 573 ++ vendor/loro-internal/src/fork.rs | 64 + vendor/loro-internal/src/fuzz.rs | 89 + vendor/loro-internal/src/handler.rs | 6099 +++++++++++++++++ .../loro-internal/src/handler/full_state.rs | 377 + .../src/handler/movable_list_apply_delta.rs | 361 + .../loro-internal/src/handler/text_update.rs | 149 + vendor/loro-internal/src/handler/tree.rs | 1197 ++++ vendor/loro-internal/src/history_cache.rs | 1070 +++ vendor/loro-internal/src/id.rs | 4 + vendor/loro-internal/src/jsonpath/ast.rs | 458 ++ vendor/loro-internal/src/jsonpath/errors.rs | 61 + .../loro-internal/src/jsonpath/jsonpath.pest | 110 + .../src/jsonpath/jsonpath_impl.rs | 1635 +++++ vendor/loro-internal/src/jsonpath/mod.rs | 10 + vendor/loro-internal/src/jsonpath/parser.rs | 708 ++ .../src/jsonpath/subscription.rs | 551 ++ vendor/loro-internal/src/kv_store.rs | 260 + vendor/loro-internal/src/lib.rs | 185 + vendor/loro-internal/src/lock.rs | 627 ++ vendor/loro-internal/src/loro.rs | 5041 ++++++++++++++ vendor/loro-internal/src/macros.rs | 98 + vendor/loro-internal/src/op.rs | 749 ++ vendor/loro-internal/src/op/content.rs | 470 ++ vendor/loro-internal/src/oplog.rs | 1759 +++++ .../loro-internal/src/oplog/change_store.rs | 3274 +++++++++ .../src/oplog/change_store/block_encode.rs | 1099 +++ .../oplog/change_store/block_meta_encode.rs | 247 + .../src/oplog/change_store/iter.rs | 139 + .../loro-internal/src/oplog/known_history.rs | 976 +++ vendor/loro-internal/src/oplog/loro_dag.rs | 1619 +++++ .../src/oplog/pending_changes.rs | 942 +++ vendor/loro-internal/src/parent.rs | 151 + vendor/loro-internal/src/pre_commit.rs | 69 + vendor/loro-internal/src/span.rs | 3 + vendor/loro-internal/src/state.rs | 2873 ++++++++ vendor/loro-internal/src/state/AGENTS.md | 68 + vendor/loro-internal/src/state/CLAUDE.md | 68 + vendor/loro-internal/src/state/analyzer.rs | 95 + .../src/state/container_store.rs | 1186 ++++ .../container_store/container_wrapper.rs | 843 +++ .../src/state/container_store/inner_store.rs | 821 +++ .../loro-internal/src/state/container_tree.rs | 269 + .../loro-internal/src/state/counter_state.rs | 145 + .../src/state/dead_containers_cache.rs | 391 ++ vendor/loro-internal/src/state/list_state.rs | 972 +++ vendor/loro-internal/src/state/map_state.rs | 721 ++ vendor/loro-internal/src/state/mergeable.rs | 93 + .../src/state/movable_list_state.rs | 2110 ++++++ .../loro-internal/src/state/richtext_state.rs | 1979 ++++++ vendor/loro-internal/src/state/tree_state.rs | 2274 ++++++ .../loro-internal/src/state/unknown_state.rs | 184 + .../loro-internal/src/state/value_decode.rs | 437 ++ vendor/loro-internal/src/subscription.rs | 232 + vendor/loro-internal/src/sync.rs | 178 + .../src/tests/import_atomicity.rs | 1091 +++ vendor/loro-internal/src/tests/mod.rs | 51 + vendor/loro-internal/src/tests/op_count.rs | 107 + vendor/loro-internal/src/tests/replay_base.rs | 723 ++ .../src/tests/text_arena_growth.rs | 184 + .../loro-internal/src/tests/undo_atomicity.rs | 123 + vendor/loro-internal/src/txn.rs | 1221 ++++ vendor/loro-internal/src/undo.rs | 1243 ++++ .../loro-internal/src/undo/atomicity_tests.rs | 141 + vendor/loro-internal/src/undo/movable_list.rs | 890 +++ vendor/loro-internal/src/utils/kv_wrapper.rs | 181 + vendor/loro-internal/src/utils/lazy.rs | 21 + vendor/loro-internal/src/utils/mod.rs | 6 + .../loro-internal/src/utils/query_by_len.rs | 200 + .../loro-internal/src/utils/string_slice.rs | 466 ++ .../loro-internal/src/utils/subscription.rs | 857 +++ vendor/loro-internal/src/utils/utf16.rs | 139 + vendor/loro-internal/src/value.rs | 1222 ++++ vendor/loro-internal/src/version.rs | 1221 ++++ vendor/loro-internal/src/version/frontiers.rs | 574 ++ vendor/loro-internal/tests/autocommit.rs | 78 + vendor/loro-internal/tests/contracts.rs | 14 + .../tests/contracts/event_diff.rs | 160 + .../loro-internal/tests/contracts/handler.rs | 179 + .../tests/contracts/jsonpath_value.rs | 172 + .../tests/contracts/public_doc.rs | 243 + .../tests/contracts/text_richtext_behavior.rs | 213 + .../tests/contracts/text_richtext_handler.rs | 266 + .../tests/contracts/tree_handler.rs | 119 + vendor/loro-internal/tests/ephemeral_store.rs | 94 + vendor/loro-internal/tests/fugue.rs | 90 + .../loro-internal/tests/handle_walk_memory.rs | 141 + .../tests/mergeable_cid_encoding.rs | 314 + .../tests/mergeable_container.rs | 19 + .../tests/mergeable_container/common.rs | 25 + .../tests/mergeable_container/convergence.rs | 285 + .../tests/mergeable_container/delete.rs | 383 ++ .../mergeable_container/discriminator.rs | 313 + .../mergeable_container/events_and_paths.rs | 266 + .../tests/mergeable_container/pending.rs | 53 + .../tests/mergeable_container/snapshot.rs | 357 + .../mergeable_container/type_conflict.rs | 182 + .../tests/mergeable_container/undo_redo.rs | 178 + vendor/loro-internal/tests/richtext.md | 98 + vendor/loro-internal/tests/richtext.rs | 426 ++ vendor/loro-internal/tests/test.rs | 1546 +++++ vendor/loro-internal/tests/tree.rs | 35 + vendor/loro-internal/tests/undo.rs | 281 + vendor/loro-internal/tests/unknown_parent.rs | 102 + web/build.ts | 48 - web/bun.lock | 58 - web/package.json | 23 - web/src/dom.ts | 76 - web/src/editing.ts | 294 - web/src/editor.css | 800 --- web/src/editor.ts | 394 -- web/src/floating.ts | 453 -- web/src/i18n.ts | 109 - web/src/noteLinks.ts | 334 - web/src/toolbar.ts | 279 - xtask/Cargo.toml | 16 + xtask/src/e2e.rs | 528 ++ xtask/src/main.rs | 232 + xtask/src/stress.rs | 756 ++ 296 files changed, 133050 insertions(+), 4182 deletions(-) create mode 100644 .cargo/config.toml delete mode 100644 assets/editor.js delete mode 100644 assets/editor.js.map delete mode 100644 assets/loro-856987111b05.wasm create mode 100644 crates/editor/Cargo.toml create mode 100644 crates/editor/src/core/commands.rs create mode 100644 crates/editor/src/core/doc.rs create mode 100644 crates/editor/src/core/history.rs create mode 100644 crates/editor/src/core/marks.rs create mode 100644 crates/editor/src/core/mod.rs create mode 100644 crates/editor/src/core/model.rs create mode 100644 crates/editor/src/core/pos.rs create mode 100644 crates/editor/src/core/tests.rs create mode 100644 crates/editor/src/core/testutil.rs create mode 100644 crates/editor/src/editor.rs create mode 100644 crates/editor/src/lib.rs create mode 100644 crates/editor/src/rules.rs create mode 100644 crates/editor/src/strings.rs create mode 100644 crates/editor/src/sync.rs create mode 100644 crates/editor/src/ui/clipboard.rs create mode 100644 crates/editor/src/ui/codeblock.rs create mode 100644 crates/editor/src/ui/floating.rs create mode 100644 crates/editor/src/ui/media.rs create mode 100644 crates/editor/src/ui/mod.rs create mode 100644 crates/editor/src/ui/notelinks.rs create mode 100644 crates/editor/src/ui/presence.rs create mode 100644 crates/editor/src/ui/toolbar.rs create mode 100644 crates/editor/src/view.rs create mode 100644 crates/note-model/Cargo.toml create mode 100644 crates/note-model/src/blocks.rs create mode 100644 crates/note-model/src/flat.rs create mode 100644 crates/note-model/src/lang.rs create mode 100644 crates/note-model/src/lib.rs create mode 100644 crates/note-model/src/links.rs create mode 100644 crates/note-model/src/marks.rs create mode 100644 crates/note-model/src/render.rs create mode 100644 crates/note-model/src/schema.rs create mode 100644 crates/note-model/src/tree.rs create mode 100644 crates/note-model/src/write.rs create mode 100644 src/app/format.rs create mode 100644 src/app/media.rs create mode 100644 src/editor_assets.rs create mode 100644 src/format.rs create mode 100644 src/media.rs create mode 100644 src/media/webm.rs create mode 100644 src/store/directory.rs create mode 100644 src/zipout.rs create mode 100644 vendor/loro-internal/.gitignore create mode 100644 vendor/loro-internal/AGENTS.md create mode 100644 vendor/loro-internal/CLAUDE.md create mode 100644 vendor/loro-internal/Cargo.lock create mode 100644 vendor/loro-internal/Cargo.toml create mode 100644 vendor/loro-internal/Cargo.toml.orig create mode 100644 vendor/loro-internal/Encoding.md create mode 100644 vendor/loro-internal/README.md create mode 100644 vendor/loro-internal/VERSION create mode 100644 vendor/loro-internal/benches/automerge-paper.json.gz create mode 100644 vendor/loro-internal/benches/encode.rs create mode 100644 vendor/loro-internal/benches/event.rs create mode 100644 vendor/loro-internal/benches/jsonpath.rs create mode 100644 vendor/loro-internal/benches/list.rs create mode 100644 vendor/loro-internal/benches/map.rs create mode 100644 vendor/loro-internal/benches/pending.rs create mode 100644 vendor/loro-internal/benches/shallow_export.rs create mode 100644 vendor/loro-internal/benches/text_r.rs create mode 100644 vendor/loro-internal/benches/tree.rs create mode 100644 vendor/loro-internal/deno.json create mode 100644 vendor/loro-internal/deno.lock create mode 100644 vendor/loro-internal/docs/critical-version-spec.md create mode 100644 vendor/loro-internal/docs/diff_calc.md create mode 100644 vendor/loro-internal/docs/mergeable-container-id.md create mode 100644 vendor/loro-internal/examples/automerge_x100.rs create mode 100644 vendor/loro-internal/examples/encoding.rs create mode 100644 vendor/loro-internal/examples/encoding_parallel.rs create mode 100644 vendor/loro-internal/examples/encoding_refactored.rs create mode 100644 vendor/loro-internal/examples/event.rs create mode 100644 vendor/loro-internal/examples/list.rs create mode 100644 vendor/loro-internal/examples/many_actors.rs create mode 100644 vendor/loro-internal/examples/mem.rs create mode 100644 vendor/loro-internal/examples/obs.rs create mode 100644 vendor/loro-internal/examples/pending.rs create mode 100644 vendor/loro-internal/examples/state_size.rs create mode 100644 vendor/loro-internal/examples/tree.rs create mode 100644 vendor/loro-internal/proptest-regressions/dag/test.txt create mode 100644 vendor/loro-internal/scripts/fuzz.ts create mode 100644 vendor/loro-internal/scripts/mem.ts create mode 100644 vendor/loro-internal/scripts/run_mem.ts create mode 100644 vendor/loro-internal/src/allocation/bfs.rs create mode 100644 vendor/loro-internal/src/allocation/dfs.rs create mode 100644 vendor/loro-internal/src/allocation/mod.rs create mode 100644 vendor/loro-internal/src/arena.rs create mode 100644 vendor/loro-internal/src/arena/str_arena.rs create mode 100644 vendor/loro-internal/src/awareness.rs create mode 100644 vendor/loro-internal/src/change.rs create mode 100644 vendor/loro-internal/src/change_meta.rs create mode 100644 vendor/loro-internal/src/configure.rs create mode 100644 vendor/loro-internal/src/container.rs create mode 100644 vendor/loro-internal/src/container/list/list_op.rs create mode 100644 vendor/loro-internal/src/container/list/mod.rs create mode 100644 vendor/loro-internal/src/container/map/map_content.rs create mode 100644 vendor/loro-internal/src/container/map/mod.rs create mode 100644 vendor/loro-internal/src/container/richtext.rs create mode 100644 vendor/loro-internal/src/container/richtext/config.rs create mode 100644 vendor/loro-internal/src/container/richtext/fugue_span.rs create mode 100644 vendor/loro-internal/src/container/richtext/richtext_state.rs create mode 100644 vendor/loro-internal/src/container/richtext/richtext_state/insert_pos_cache_test.rs create mode 100644 vendor/loro-internal/src/container/richtext/str_slice.rs create mode 100644 vendor/loro-internal/src/container/richtext/style_range_map.rs create mode 100644 vendor/loro-internal/src/container/richtext/tinyvec.rs create mode 100644 vendor/loro-internal/src/container/richtext/tracker.rs create mode 100644 vendor/loro-internal/src/container/richtext/tracker/crdt_rope.rs create mode 100644 vendor/loro-internal/src/container/richtext/tracker/id_to_cursor.rs create mode 100644 vendor/loro-internal/src/container/tree/bool_rle_vec.rs create mode 100644 vendor/loro-internal/src/container/tree/mod.rs create mode 100644 vendor/loro-internal/src/container/tree/tree_ds.rs create mode 100644 vendor/loro-internal/src/container/tree/tree_op.rs create mode 100644 vendor/loro-internal/src/cursor.rs create mode 100644 vendor/loro-internal/src/dag.rs create mode 100644 vendor/loro-internal/src/dag/iter.rs create mode 100644 vendor/loro-internal/src/dag/mermaid.rs create mode 100644 vendor/loro-internal/src/dag/test.excalidraw create mode 100644 vendor/loro-internal/src/dag/test.rs create mode 100644 vendor/loro-internal/src/delta.rs create mode 100644 vendor/loro-internal/src/delta/map.rs create mode 100644 vendor/loro-internal/src/delta/map_delta.rs create mode 100644 vendor/loro-internal/src/delta/movable_list.rs create mode 100644 vendor/loro-internal/src/delta/seq.rs create mode 100644 vendor/loro-internal/src/delta/text.rs create mode 100644 vendor/loro-internal/src/delta/tree.rs create mode 100644 vendor/loro-internal/src/diff/LICENSE create mode 100644 vendor/loro-internal/src/diff/diff_impl.rs create mode 100644 vendor/loro-internal/src/diff/mod.rs create mode 100644 vendor/loro-internal/src/diff_calc.rs create mode 100644 vendor/loro-internal/src/diff_calc/counter.rs create mode 100644 vendor/loro-internal/src/diff_calc/tracker_texts.rs create mode 100644 vendor/loro-internal/src/diff_calc/tracker_values.rs create mode 100644 vendor/loro-internal/src/diff_calc/tree.rs create mode 100644 vendor/loro-internal/src/diff_calc/unknown.rs create mode 100644 vendor/loro-internal/src/encoding.rs create mode 100644 vendor/loro-internal/src/encoding/AGENTS.md create mode 100644 vendor/loro-internal/src/encoding/CLAUDE.md create mode 100644 vendor/loro-internal/src/encoding/arena.rs create mode 100644 vendor/loro-internal/src/encoding/fast_snapshot.rs create mode 100644 vendor/loro-internal/src/encoding/json_schema.rs create mode 100644 vendor/loro-internal/src/encoding/outdated_encode_reordered.rs create mode 100644 vendor/loro-internal/src/encoding/shallow_snapshot.rs create mode 100644 vendor/loro-internal/src/encoding/value.rs create mode 100644 vendor/loro-internal/src/encoding/value_register.rs create mode 100644 vendor/loro-internal/src/error.rs create mode 100644 vendor/loro-internal/src/estimated_size.rs create mode 100644 vendor/loro-internal/src/event.rs create mode 100644 vendor/loro-internal/src/fork.rs create mode 100644 vendor/loro-internal/src/fuzz.rs create mode 100644 vendor/loro-internal/src/handler.rs create mode 100644 vendor/loro-internal/src/handler/full_state.rs create mode 100644 vendor/loro-internal/src/handler/movable_list_apply_delta.rs create mode 100644 vendor/loro-internal/src/handler/text_update.rs create mode 100644 vendor/loro-internal/src/handler/tree.rs create mode 100644 vendor/loro-internal/src/history_cache.rs create mode 100644 vendor/loro-internal/src/id.rs create mode 100644 vendor/loro-internal/src/jsonpath/ast.rs create mode 100644 vendor/loro-internal/src/jsonpath/errors.rs create mode 100644 vendor/loro-internal/src/jsonpath/jsonpath.pest create mode 100644 vendor/loro-internal/src/jsonpath/jsonpath_impl.rs create mode 100644 vendor/loro-internal/src/jsonpath/mod.rs create mode 100644 vendor/loro-internal/src/jsonpath/parser.rs create mode 100644 vendor/loro-internal/src/jsonpath/subscription.rs create mode 100644 vendor/loro-internal/src/kv_store.rs create mode 100644 vendor/loro-internal/src/lib.rs create mode 100644 vendor/loro-internal/src/lock.rs create mode 100644 vendor/loro-internal/src/loro.rs create mode 100644 vendor/loro-internal/src/macros.rs create mode 100644 vendor/loro-internal/src/op.rs create mode 100644 vendor/loro-internal/src/op/content.rs create mode 100644 vendor/loro-internal/src/oplog.rs create mode 100644 vendor/loro-internal/src/oplog/change_store.rs create mode 100644 vendor/loro-internal/src/oplog/change_store/block_encode.rs create mode 100644 vendor/loro-internal/src/oplog/change_store/block_meta_encode.rs create mode 100644 vendor/loro-internal/src/oplog/change_store/iter.rs create mode 100644 vendor/loro-internal/src/oplog/known_history.rs create mode 100644 vendor/loro-internal/src/oplog/loro_dag.rs create mode 100644 vendor/loro-internal/src/oplog/pending_changes.rs create mode 100644 vendor/loro-internal/src/parent.rs create mode 100644 vendor/loro-internal/src/pre_commit.rs create mode 100644 vendor/loro-internal/src/span.rs create mode 100644 vendor/loro-internal/src/state.rs create mode 100644 vendor/loro-internal/src/state/AGENTS.md create mode 100644 vendor/loro-internal/src/state/CLAUDE.md create mode 100644 vendor/loro-internal/src/state/analyzer.rs create mode 100644 vendor/loro-internal/src/state/container_store.rs create mode 100644 vendor/loro-internal/src/state/container_store/container_wrapper.rs create mode 100644 vendor/loro-internal/src/state/container_store/inner_store.rs create mode 100644 vendor/loro-internal/src/state/container_tree.rs create mode 100644 vendor/loro-internal/src/state/counter_state.rs create mode 100644 vendor/loro-internal/src/state/dead_containers_cache.rs create mode 100644 vendor/loro-internal/src/state/list_state.rs create mode 100644 vendor/loro-internal/src/state/map_state.rs create mode 100644 vendor/loro-internal/src/state/mergeable.rs create mode 100644 vendor/loro-internal/src/state/movable_list_state.rs create mode 100644 vendor/loro-internal/src/state/richtext_state.rs create mode 100644 vendor/loro-internal/src/state/tree_state.rs create mode 100644 vendor/loro-internal/src/state/unknown_state.rs create mode 100644 vendor/loro-internal/src/state/value_decode.rs create mode 100644 vendor/loro-internal/src/subscription.rs create mode 100644 vendor/loro-internal/src/sync.rs create mode 100644 vendor/loro-internal/src/tests/import_atomicity.rs create mode 100644 vendor/loro-internal/src/tests/mod.rs create mode 100644 vendor/loro-internal/src/tests/op_count.rs create mode 100644 vendor/loro-internal/src/tests/replay_base.rs create mode 100644 vendor/loro-internal/src/tests/text_arena_growth.rs create mode 100644 vendor/loro-internal/src/tests/undo_atomicity.rs create mode 100644 vendor/loro-internal/src/txn.rs create mode 100644 vendor/loro-internal/src/undo.rs create mode 100644 vendor/loro-internal/src/undo/atomicity_tests.rs create mode 100644 vendor/loro-internal/src/undo/movable_list.rs create mode 100644 vendor/loro-internal/src/utils/kv_wrapper.rs create mode 100644 vendor/loro-internal/src/utils/lazy.rs create mode 100644 vendor/loro-internal/src/utils/mod.rs create mode 100644 vendor/loro-internal/src/utils/query_by_len.rs create mode 100644 vendor/loro-internal/src/utils/string_slice.rs create mode 100644 vendor/loro-internal/src/utils/subscription.rs create mode 100644 vendor/loro-internal/src/utils/utf16.rs create mode 100644 vendor/loro-internal/src/value.rs create mode 100644 vendor/loro-internal/src/version.rs create mode 100644 vendor/loro-internal/src/version/frontiers.rs create mode 100644 vendor/loro-internal/tests/autocommit.rs create mode 100644 vendor/loro-internal/tests/contracts.rs create mode 100644 vendor/loro-internal/tests/contracts/event_diff.rs create mode 100644 vendor/loro-internal/tests/contracts/handler.rs create mode 100644 vendor/loro-internal/tests/contracts/jsonpath_value.rs create mode 100644 vendor/loro-internal/tests/contracts/public_doc.rs create mode 100644 vendor/loro-internal/tests/contracts/text_richtext_behavior.rs create mode 100644 vendor/loro-internal/tests/contracts/text_richtext_handler.rs create mode 100644 vendor/loro-internal/tests/contracts/tree_handler.rs create mode 100644 vendor/loro-internal/tests/ephemeral_store.rs create mode 100644 vendor/loro-internal/tests/fugue.rs create mode 100644 vendor/loro-internal/tests/handle_walk_memory.rs create mode 100644 vendor/loro-internal/tests/mergeable_cid_encoding.rs create mode 100644 vendor/loro-internal/tests/mergeable_container.rs create mode 100644 vendor/loro-internal/tests/mergeable_container/common.rs create mode 100644 vendor/loro-internal/tests/mergeable_container/convergence.rs create mode 100644 vendor/loro-internal/tests/mergeable_container/delete.rs create mode 100644 vendor/loro-internal/tests/mergeable_container/discriminator.rs create mode 100644 vendor/loro-internal/tests/mergeable_container/events_and_paths.rs create mode 100644 vendor/loro-internal/tests/mergeable_container/pending.rs create mode 100644 vendor/loro-internal/tests/mergeable_container/snapshot.rs create mode 100644 vendor/loro-internal/tests/mergeable_container/type_conflict.rs create mode 100644 vendor/loro-internal/tests/mergeable_container/undo_redo.rs create mode 100644 vendor/loro-internal/tests/richtext.md create mode 100644 vendor/loro-internal/tests/richtext.rs create mode 100644 vendor/loro-internal/tests/test.rs create mode 100644 vendor/loro-internal/tests/tree.rs create mode 100644 vendor/loro-internal/tests/undo.rs create mode 100644 vendor/loro-internal/tests/unknown_parent.rs delete mode 100644 web/build.ts delete mode 100644 web/bun.lock delete mode 100644 web/package.json delete mode 100644 web/src/dom.ts delete mode 100644 web/src/editing.ts delete mode 100644 web/src/editor.css delete mode 100644 web/src/editor.ts delete mode 100644 web/src/floating.ts delete mode 100644 web/src/i18n.ts delete mode 100644 web/src/noteLinks.ts delete mode 100644 web/src/toolbar.ts create mode 100644 xtask/Cargo.toml create mode 100644 xtask/src/e2e.rs create mode 100644 xtask/src/main.rs create mode 100644 xtask/src/stress.rs diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..5592118 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[alias] +xtask = "run -p xtask --" diff --git a/.gitignore b/.gitignore index 51fe5fb..be699c1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ /target -web/node_modules +/media/ *.db* +/assets/editor-*.js +/assets/editor-*.wasm +/assets/editor.manifest diff --git a/Cargo.lock b/Cargo.lock index 48d1d21..9ab89e4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -111,6 +111,12 @@ dependencies = [ "libc", ] +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + [[package]] name = "antithesis_sdk" version = "0.3.0" @@ -201,6 +207,17 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfdc70193dadb9d7287fa4b633f15f90c876915b31f6af17da307fc59c9859a8" +[[package]] +name = "ast_node" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eb025ef00a6da925cf40870b9c8d008526b6004ece399cb0974209720f0b194" +dependencies = [ + "quote", + "swc_macros_common", + "syn 2.0.119", +] + [[package]] name = "async-compression" version = "0.4.51" @@ -257,6 +274,21 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "beef" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1" + +[[package]] +name = "better_scoped_tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd228125315b132eed175bf47619ac79b945b26e56b848ba203ae4ea8603609" +dependencies = [ + "scoped-tls", +] + [[package]] name = "bigdecimal" version = "0.4.11" @@ -413,11 +445,24 @@ dependencies = [ "alloc-stdlib", ] +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "serde_core", +] + [[package]] name = "bumpalo" version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +dependencies = [ + "allocator-api2 0.2.21", +] [[package]] name = "bytemuck" @@ -451,6 +496,36 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "bytes-str" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dde6d05e75a31ec9610eb6446a6f0a10dd30ff5100d720fee4c7c7a9008b5ba" +dependencies = [ + "bytes", + "serde", +] + +[[package]] +name = "capacity_builder" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f2d24a6dcf0cd402a21b65d35340f3a49ff3475dc5fdac91d22d2733e6641c6" +dependencies = [ + "capacity_builder_macros", + "itoa", +] + +[[package]] +name = "capacity_builder_macros" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b4a6cae9efc04cc6cbb8faf338d2c497c165c83e74509cf4dbedea948bbf6e5" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "cc" version = "1.10.0" @@ -530,6 +605,32 @@ dependencies = [ "libloading", ] +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + [[package]] name = "cobs" version = "0.3.0" @@ -539,6 +640,17 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width 0.2.3", +] + [[package]] name = "compression-codecs" version = "0.4.46" @@ -596,12 +708,36 @@ dependencies = [ "version_check", ] +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "countme" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7704b5fdd17b18ae31c4c1da5a2e0305a2bf17b5249300a9ee9ed7b72114c636" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -704,6 +840,12 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "css_dataset" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25670139e591f1c2869eb8d0d977028f8d05e859132b4c874ecd02a00d3c9174" + [[package]] name = "ctr" version = "0.9.2" @@ -713,6 +855,68 @@ dependencies = [ "cipher", ] +[[package]] +name = "cxx" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8a02bfeba9074b2bbb39492c9b0908ec854f455a3cccdcde7a1de55e2315e40" +dependencies = [ + "cc", + "cxx-build", + "cxxbridge-cmd", + "cxxbridge-flags", + "cxxbridge-macro", + "foldhash 0.2.0", + "link-cplusplus", +] + +[[package]] +name = "cxx-build" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc2ac76997619d2d888b58ad79488f1c835de41ca4dd3dd7082acf4ecb0a50f" +dependencies = [ + "cc", + "codespan-reporting", + "indexmap", + "proc-macro2", + "quote", + "scratch", + "syn 3.0.9", +] + +[[package]] +name = "cxxbridge-cmd" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54a486ed16a3f2a053fe7f5b98db4c1a59846a23e8cb9e49f9d1bd48830d51a2" +dependencies = [ + "clap", + "codespan-reporting", + "indexmap", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "cxxbridge-flags" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c72569be94e2283764d334cd285980b747dbe221e27e315484eb6bcd93fa808a" + +[[package]] +name = "cxxbridge-macro" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "423e795284a7f7b3f843c956a5322c4bc497b60c2dd1a6339da10313cb18d575" +dependencies = [ + "indexmap", + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "darling" version = "0.20.11" @@ -788,12 +992,85 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + [[package]] name = "datasketches" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745" +[[package]] +name = "deno_ast" +version = "0.53.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f7c1384d87fc0a6439a065312fbef8f6ac6128689dbc2831b28b3a1d4f3a4e6" +dependencies = [ + "capacity_builder", + "deno_error", + "deno_media_type", + "deno_terminal", + "dprint-swc-ext", + "percent-encoding", + "serde", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_lexer", + "swc_ecma_parser", + "swc_eq_ignore_macros", + "text_lines", + "thiserror 2.0.21", + "unicode-width 0.2.3", + "url", +] + +[[package]] +name = "deno_error" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3007d3f1ea92ea503324ae15883aac0c2de2b8cf6fead62203ff6a67161007ab" +dependencies = [ + "deno_error_macro", + "libc", +] + +[[package]] +name = "deno_error_macro" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b565e60a9685cdf312c888665b5f8647ac692a7da7e058a5e2268a466da8eaf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "deno_media_type" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "debab24ecd9f4fd64aa42fb18a02dff20a97d5830b2b85b98ce70b509f790763" +dependencies = [ + "data-url", + "serde", + "url", +] + +[[package]] +name = "deno_terminal" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3ba8041ae7319b3ca6a64c399df4112badcbbe0868b4517637647614bede4be" +dependencies = [ + "once_cell", + "termcolor", +] + [[package]] name = "deranged" version = "0.5.9" @@ -853,12 +1130,147 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + [[package]] name = "downcast-rs" version = "2.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc" +[[package]] +name = "dprint-core" +version = "0.67.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c1d827947704a9495f705d6aeed270fa21a67f825f22902c28f38dc3af7a9ae" +dependencies = [ + "anyhow", + "bumpalo", + "hashbrown 0.15.5", + "indexmap", + "rustc-hash 2.1.3", + "serde", + "unicode-width 0.2.3", +] + +[[package]] +name = "dprint-core" +version = "0.69.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67359cea061dd052fca921d3589a9ce59bc16fa23bfb9d06d5c669a1dbd23915" +dependencies = [ + "bumpalo", + "hashbrown 0.15.5", + "indexmap", + "rustc-hash 2.1.3", + "serde", + "unicode-width 0.2.3", +] + +[[package]] +name = "dprint-core" +version = "0.71.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "670d3c17cf65d37f5324b4fc198993148beb8c44e56fa4fe3676dd3c033d4e8c" +dependencies = [ + "bumpalo", + "hashbrown 0.15.5", + "indexmap", + "rustc-hash 2.1.3", + "serde", + "unicode-width 0.2.3", +] + +[[package]] +name = "dprint-core-macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1675ad2b358481f3cc46202040d64ac7a36c4ade414a696df32e0e45421a6e9f" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "dprint-plugin-json" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ee8da2b2565012674667b147e1f672ec9e897695d4e4a418c63ce6468e466" +dependencies = [ + "dprint-core 0.69.1", + "dprint-core-macros", + "jsonc-parser", + "serde", + "text_lines", + "thiserror 2.0.21", +] + +[[package]] +name = "dprint-plugin-markdown" +version = "0.28.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f77690b7d85d149e7daea5bb83b55a1c7aefb8b9646c805ca70035fd74aa19" +dependencies = [ + "dprint-core 0.71.1", + "dprint-core-macros", + "serde", + "thiserror 2.0.21", + "unicode-width 0.2.3", +] + +[[package]] +name = "dprint-plugin-typescript" +version = "0.96.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90733c56ab425fc299c25ad81a5924bfc3c0050f25d865da742a6987b1255927" +dependencies = [ + "anyhow", + "capacity_builder", + "deno_ast", + "dprint-core 0.67.4", + "dprint-core-macros", + "percent-encoding", + "rustc-hash 2.1.3", + "serde", +] + +[[package]] +name = "dprint-swc-ext" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "661f154a87e7459f54a2f4a1c615661a416a822b4a9e3ad0491dce2bd080421f" +dependencies = [ + "allocator-api2 0.2.21", + "bumpalo", + "num-bigint", + "rustc-hash 2.1.3", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_lexer", + "swc_ecma_parser", + "text_lines", +] + +[[package]] +name = "editor" +version = "0.1.0" +dependencies = [ + "js-sys", + "loro", + "note-model", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "either" version = "1.19.0" @@ -1005,7 +1417,7 @@ checksum = "4e7f34442dbe69c60fe8eaf58a8cafff81a1f278816d8ab4db255b3bef4ac3c4" dependencies = [ "getrandom 0.3.4", "libm", - "siphasher", + "siphasher 1.0.4", ] [[package]] @@ -1043,6 +1455,12 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "foldhash" version = "0.2.0" @@ -1058,6 +1476,16 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "from_variant" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5ff35a391aef949120a0340d690269b3d9f63460a6106e99bd07b961f345ea9" +dependencies = [ + "swc_macros_common", + "syn 2.0.119", +] + [[package]] name = "fs4" version = "0.13.1" @@ -1230,12 +1658,36 @@ dependencies = [ "polyval", ] +[[package]] +name = "gimli" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" +dependencies = [ + "fallible-iterator", + "indexmap", + "stable_deref_trait", +] + [[package]] name = "glob" version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" +[[package]] +name = "globset" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f98b0d85522dc0a824cfebbc9594ff4a9b289c568bea0370319dfbdf20ccdd2d" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata", + "regex-syntax 0.8.11", +] + [[package]] name = "h2" version = "0.4.20" @@ -1273,6 +1725,27 @@ dependencies = [ "byteorder", ] +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", + "allocator-api2 0.2.21", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2 0.2.21", + "equivalent", + "foldhash 0.1.5", +] + [[package]] name = "hashbrown" version = "0.16.1" @@ -1281,7 +1754,9 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" dependencies = [ "allocator-api2 0.2.21", "equivalent", - "foldhash", + "foldhash 0.2.0", + "serde", + "serde_core", ] [[package]] @@ -1289,6 +1764,11 @@ name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2 0.2.21", + "equivalent", + "foldhash 0.2.0", +] [[package]] name = "heapless" @@ -1386,6 +1866,20 @@ dependencies = [ "windows-link", ] +[[package]] +name = "hstr" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83bb87e4b300d73412f6dcc7022ee7741452b51b155c2b06e5994d0770c2dbe2" +dependencies = [ + "hashbrown 0.14.5", + "new_debug_unreachable", + "once_cell", + "rustc-hash 2.1.3", + "serde", + "triomphe", +] + [[package]] name = "htmlescape" version = "0.3.1" @@ -1660,6 +2154,15 @@ dependencies = [ "zerovec", ] +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" +dependencies = [ + "rayon", +] + [[package]] name = "ident_case" version = "1.0.1" @@ -1710,6 +2213,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown 0.17.1", + "serde", + "serde_core", ] [[package]] @@ -1756,6 +2261,27 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "is-macro" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8267aa6001e25494f3015f9663bbd88a18240c74483afa5f0934a1b3e4c388e9" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.11.0" @@ -1783,6 +2309,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" @@ -1810,6 +2345,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonc-parser" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ecded084f9b9a718d39668a42657c32253663d1f6afb3fbb9134f0305f73f48" +dependencies = [ + "unicode-width 0.2.3", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -1828,6 +2372,12 @@ version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + [[package]] name = "lettre" version = "0.11.23" @@ -1882,6 +2432,15 @@ dependencies = [ "cc", ] +[[package]] +name = "link-cplusplus" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82" +dependencies = [ + "cc", +] + [[package]] name = "linkme" version = "0.3.37" @@ -1920,6 +2479,12 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + [[package]] name = "lock_api" version = "0.4.14" @@ -1935,6 +2500,29 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "logos" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf8b031682c67a8e3d5446840f9573eb7fe26efe7ec8d195c9ac4c0647c502f1" +dependencies = [ + "logos-derive", +] + +[[package]] +name = "logos-derive" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d849148dbaf9661a6151d1ca82b13bb4c4c128146a88d05253b38d4e2f496c" +dependencies = [ + "beef", + "fnv", + "proc-macro2", + "quote", + "regex-syntax 0.6.29", + "syn 1.0.109", +] + [[package]] name = "loom" version = "0.7.2" @@ -1999,8 +2587,6 @@ dependencies = [ [[package]] name = "loro-internal" version = "1.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e533c1688430aa4fcdd933f00861e331c169a4158ee6d27d054e0558892d447" dependencies = [ "append-only-bytes", "arref", @@ -2112,6 +2698,34 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ef0d4ed8669f8f8826eb00dc878084aa8f253506c4fd5e8f58f5bce72ddb97e" +[[package]] +name = "malva" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed54a855fc80dddeb3518c03d04a2bb06954955297ee514429935149e58eaa75" +dependencies = [ + "aho-corasick", + "itertools 0.14.0", + "memchr", + "raffia", + "tiny_pretty 0.4.5", +] + +[[package]] +name = "markup_fmt" +version = "0.27.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df2c4bb9a66c59714ba02c074187491e30daaf99127dcb287ce2aa8fa0c1a9fe" +dependencies = [ + "aho-corasick", + "anyhow", + "css_dataset", + "itertools 0.15.0", + "memchr", + "regex", + "tiny_pretty 0.4.5", +] + [[package]] name = "matchers" version = "0.2.0" @@ -2174,7 +2788,7 @@ checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" dependencies = [ "cfg-if", "miette-derive", - "unicode-width", + "unicode-width 0.1.14", ] [[package]] @@ -2247,16 +2861,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2195bf6aa996a481483b29d62a7663eed3fe39600c460e323f8ff41e90bdd89b" [[package]] -name = "nix" -version = "0.31.3" +name = "new_debug_unreachable" +version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" -dependencies = [ - "bitflags", - "cfg-if", - "cfg_aliases", - "libc", -] +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" [[package]] name = "nom" @@ -2283,6 +2891,13 @@ version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "610a5acd306ec67f907abe5567859a3c693fb9886eb1f012ab8f2a47bef3db51" +[[package]] +name = "note-model" +version = "0.1.0" +dependencies = [ + "loro", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -2314,6 +2929,7 @@ checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" dependencies = [ "num-integer", "num-traits", + "serde", ] [[package]] @@ -2509,6 +3125,48 @@ dependencies = [ "stacker", ] +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared", + "rand 0.8.8", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher 1.0.4", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -2596,6 +3254,17 @@ dependencies = [ "yansi", ] +[[package]] +name = "pretty_yaml" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f5db2b0044c0dae209c173c6049f210c9449092b07304c9c8b8d555c606e93e" +dependencies = [ + "rowan 0.16.1", + "tiny_pretty 0.2.1", + "yaml_parser", +] + [[package]] name = "prettyplease" version = "0.2.37" @@ -2640,16 +3309,35 @@ version = "0.1.0" dependencies = [ "anyhow", "blake3", + "bytes", + "crc32fast", + "dprint-plugin-json", + "dprint-plugin-markdown", + "dprint-plugin-typescript", + "flate2", + "hashbrown 0.17.1", + "http-body", "loro", + "malva", + "markup_fmt", + "note-model", + "pretty_yaml", + "prettyplease 0.3.0", "pulldown-cmark", "regex", + "regex-syntax 0.8.11", + "rustc-hash 2.1.3", "serde", "serde_json", + "sqlformat", + "symphonia", + "syn 3.0.9", + "taplo", + "thread-priority", "tokio", "topcoat", "turso", "uuid", - "zip", ] [[package]] @@ -2740,6 +3428,27 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" +[[package]] +name = "raffia" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a589c5611a5f7713bf0c13e949c4c791a359ff517a9f27552475b470e8873229" +dependencies = [ + "raffia_macro", + "smallvec", +] + +[[package]] +name = "raffia_macro" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ac21f5e4bc6b29ea5d5e691a9aa08b2b9fd8891f48a99157b9f02d8a48e1318" +dependencies = [ + "heck 0.5.0", + "quote", + "syn 2.0.119", +] + [[package]] name = "rand" version = "0.8.8" @@ -2884,7 +3593,7 @@ dependencies = [ "aho-corasick", "memchr", "regex-automata", - "regex-syntax", + "regex-syntax 0.8.11", ] [[package]] @@ -2895,9 +3604,21 @@ checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" dependencies = [ "aho-corasick", "memchr", - "regex-syntax", + "regex-syntax 0.8.11", ] +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + +[[package]] +name = "regex-syntax" +version = "0.6.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" + [[package]] name = "regex-syntax" version = "0.8.11" @@ -2928,6 +3649,31 @@ dependencies = [ "byteorder", ] +[[package]] +name = "rowan" +version = "0.15.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2441aaccb50f4267d4f0f58b21e0138e96a449f361ed57a2673a83c9bca0772" +dependencies = [ + "countme", + "hashbrown 0.14.5", + "memoffset", + "rustc-hash 1.1.0", + "text-size", +] + +[[package]] +name = "rowan" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417a3a9f582e349834051b8a10c8d71ca88da4211e4093528e36b9845f6b5f21" +dependencies = [ + "countme", + "hashbrown 0.14.5", + "rustc-hash 1.1.0", + "text-size", +] + [[package]] name = "rust-stemmers" version = "1.2.0" @@ -2938,6 +3684,12 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + [[package]] name = "rustc-hash" version = "1.1.0" @@ -3054,12 +3806,24 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "scratch" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2" + [[package]] name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +[[package]] +name = "seq-macro" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" + [[package]] name = "serde" version = "1.0.229" @@ -3271,6 +4035,12 @@ dependencies = [ "cc", ] +[[package]] +name = "siphasher" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" + [[package]] name = "siphasher" version = "1.0.4" @@ -3311,6 +4081,17 @@ dependencies = [ "serde", ] +[[package]] +name = "smartstring" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fb72c633efbaa2dd666986505016c32c3044395ceaf881518399d2f4127ee29" +dependencies = [ + "autocfg", + "static_assertions", + "version_check", +] + [[package]] name = "socket2" version = "0.6.5" @@ -3336,6 +4117,16 @@ dependencies = [ "lock_api", ] +[[package]] +name = "sqlformat" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0705994df478b895f05b8e290e0d46e53187b26f8d889d37b2a0881234922d94" +dependencies = [ + "unicode_categories", + "winnow 0.7.15", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -3355,19 +4146,55 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "string_enum" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae36a4951ca7bd1cfd991c241584a9824a70f6aff1e7d4f693fb3f2465e4030e" +dependencies = [ + "quote", + "swc_macros_common", + "syn 2.0.119", +] + [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "strum" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f" + [[package]] name = "strum" version = "0.26.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" dependencies = [ - "strum_macros", + "strum_macros 0.26.4", +] + +[[package]] +name = "strum_macros" +version = "0.24.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e385be0d24f186b4ce2f9982191e7101bb737312ad61c1f2f984f34bcf85d59" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "quote", + "rustversion", + "syn 1.0.109", ] [[package]] @@ -3389,12 +4216,205 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "swc_atoms" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ccbe2ecad10ad7432100f878a107b1d972a8aee83ca53184d00c23a078bb8a" +dependencies = [ + "hstr", + "once_cell", + "serde", +] + +[[package]] +name = "swc_common" +version = "17.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "259b675d633a26d24efe3802a9d88858c918e6e8f062d3222d3aa02d56a2cf4c" +dependencies = [ + "anyhow", + "ast_node", + "better_scoped_tls", + "bytes-str", + "either", + "from_variant", + "new_debug_unreachable", + "num-bigint", + "once_cell", + "rustc-hash 2.1.3", + "serde", + "siphasher 0.3.11", + "swc_atoms", + "swc_eq_ignore_macros", + "swc_visit", + "tracing", + "unicode-width 0.2.3", + "url", +] + +[[package]] +name = "swc_ecma_ast" +version = "18.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a573a0c72850dec8d4d8085f152d5778af35a2520c3093b242d2d1d50776da7c" +dependencies = [ + "bitflags", + "is-macro", + "num-bigint", + "once_cell", + "phf", + "rustc-hash 2.1.3", + "serde", + "string_enum", + "swc_atoms", + "swc_common", + "swc_visit", + "unicode-id-start", +] + +[[package]] +name = "swc_ecma_lexer" +version = "26.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e82f7747e052c6ff6e111fa4adeb14e33b46ee6e94fe5ef717601f651db48fc" +dependencies = [ + "bitflags", + "either", + "num-bigint", + "rustc-hash 2.1.3", + "seq-macro", + "serde", + "smallvec", + "smartstring", + "stacker", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_parser", + "tracing", +] + +[[package]] +name = "swc_ecma_parser" +version = "27.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f1a51af1a92cd4904c073b293e491bbc0918400a45d58227b34c961dd6f52d7" +dependencies = [ + "bitflags", + "either", + "num-bigint", + "phf", + "rustc-hash 2.1.3", + "seq-macro", + "serde", + "smartstring", + "stacker", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "tracing", +] + +[[package]] +name = "swc_eq_ignore_macros" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c16ce73424a6316e95e09065ba6a207eba7765496fed113702278b7711d4b632" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "swc_macros_common" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aae1efbaa74943dc5ad2a2fb16cbd78b77d7e4d63188f3c5b4df2b4dcd2faaae" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "swc_visit" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7df72a1be54e379864cebf04f26abb4d7ee637977f62f8ec8387233f7a27e88" +dependencies = [ + "either", +] + [[package]] name = "symlink" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" +[[package]] +name = "symphonia" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7edef6a96b696d4e0cab5ee9ebb7ca155ed95f30a6b45bbb8b97d2727f02424" +dependencies = [ + "lazy_static", + "symphonia-core", + "symphonia-format-mkv", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-common" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acc3fcc18ec9b8cdd48614e259c4cf0d27b71d41e5d9b120b42c5adab12d7c4" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-core" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c412864d599d4750d0c3d684d7e093ec05e5309681ef5252cc1096a437f6e0" +dependencies = [ + "bitflags", + "bytemuck", + "lazy_static", + "log", + "num-complex", + "smallvec", +] + +[[package]] +name = "symphonia-format-mkv" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d015c5c0558864665894b3f4cbd95e10abb01b9c868e751c72670f326a56360e" +dependencies = [ + "lazy_static", + "log", + "symphonia-common", + "symphonia-core", +] + +[[package]] +name = "symphonia-metadata" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83713a97705d77bdef7cdbc0768fd6e5a54e4cd7e48d60a806ae85639e2c87c6" +dependencies = [ + "lazy_static", + "log", + "regex-lite", + "smallvec", + "symphonia-core", +] + [[package]] name = "syn" version = "1.0.109" @@ -3543,7 +4563,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d60769b80ad7953d8a7b2c70cdfe722bbcdcac6bccc8ac934c40c034d866fc18" dependencies = [ "byteorder", - "regex-syntax", + "regex-syntax 0.8.11", "utf8-ranges", ] @@ -3599,6 +4619,27 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" +[[package]] +name = "taplo" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c221a50eef1a5493074f11ca1ed62bef28c05a4d925002944cc686b2e783a5b3" +dependencies = [ + "ahash", + "arc-swap", + "either", + "globset", + "itertools 0.10.5", + "logos", + "once_cell", + "rowan 0.15.19", + "serde", + "serde_json", + "thiserror 1.0.69", + "time", + "tracing", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -3612,6 +4653,30 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "text-size" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f18aa187839b2bdb1ad2fa35ead8c4c2976b64e4363c386d45ac0f7ee85c9233" + +[[package]] +name = "text_lines" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd5828de7deaa782e1dd713006ae96b3bee32d3279b79eb67ecf8072c059bcf" +dependencies = [ + "serde", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -3652,6 +4717,20 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "thread-priority" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d2e834949be5111506bb252643498af1514f600d9e1dceedaa42afae155b67f" +dependencies = [ + "bitflags", + "cfg-if", + "libc", + "log", + "rustversion", + "windows", +] + [[package]] name = "thread_local" version = "1.1.10" @@ -3691,6 +4770,21 @@ dependencies = [ "time-core", ] +[[package]] +name = "tiny_pretty" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650d82e943da333637be9f1567d33d605e76810a26464edfd7ae74f7ef181e95" + +[[package]] +name = "tiny_pretty" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58b2d5989bcee0f42e4efffdd6280defe2d0ea91ebbea29c7615412855ef75fa" +dependencies = [ + "unicode-width 0.2.3", +] + [[package]] name = "tinystr" version = "0.8.5" @@ -3768,7 +4862,7 @@ dependencies = [ "toml_datetime", "toml_parser", "toml_writer", - "winnow", + "winnow 1.0.4", ] [[package]] @@ -3789,7 +4883,7 @@ dependencies = [ "indexmap", "toml_datetime", "toml_parser", - "winnow", + "winnow 1.0.4", ] [[package]] @@ -3798,7 +4892,7 @@ version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ - "winnow", + "winnow 1.0.4", ] [[package]] @@ -3885,7 +4979,7 @@ dependencies = [ "elsa", "http", "pin-project-lite", - "siphasher", + "siphasher 1.0.4", "thiserror 2.0.21", "tokio", ] @@ -4172,7 +5266,7 @@ dependencies = [ "http", "memchr", "pin-project-lite", - "siphasher", + "siphasher 1.0.4", "smallvec", "topcoat-core", ] @@ -4322,6 +5416,16 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "triomphe" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d15f4f5898bcfc5d8a8e45ed30b2f108d710c1a2e5489dbf80e078f707181bc" +dependencies = [ + "serde", + "stable_deref_trait", +] + [[package]] name = "tungstenite" version = "0.29.0" @@ -4402,7 +5506,7 @@ dependencies = [ "rand 0.9.5", "rapidhash", "regex", - "regex-syntax", + "regex-syntax 0.8.11", "roaring", "rustc-hash 2.1.3", "rustix 1.1.6", @@ -4412,8 +5516,8 @@ dependencies = [ "simdutf8", "simsimd", "smallvec", - "strum", - "strum_macros", + "strum 0.26.3", + "strum_macros 0.26.4", "tantivy", "tempfile", "thiserror 2.0.21", @@ -4459,8 +5563,8 @@ dependencies = [ "bitflags", "memchr", "miette", - "strum", - "strum_macros", + "strum 0.26.3", + "strum_macros 0.26.4", "thiserror 2.0.21", "turso_macros", ] @@ -4544,12 +5648,6 @@ dependencies = [ "rand 0.9.5", ] -[[package]] -name = "typed-path" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" - [[package]] name = "typeid" version = "1.0.3" @@ -4607,6 +5705,12 @@ version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" +[[package]] +name = "unicode-id-start" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0825d2e09dcae814a4273c1e1435979d414ede25b2ee235b1545da6682483765" + [[package]] name = "unicode-ident" version = "1.0.27" @@ -4619,6 +5723,18 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "unicode_categories" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" + [[package]] name = "universal-hash" version = "0.5.1" @@ -4642,11 +5758,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" dependencies = [ "base64 0.23.1", + "cookie_store", "flate2", "log", "percent-encoding", "rustls", "rustls-pki-types", + "serde", + "serde_json", "ureq-proto", "utf8-zero", "webpki-roots", @@ -4664,6 +5783,19 @@ dependencies = [ "log", ] +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + [[package]] name = "utf16_iter" version = "1.0.5" @@ -4713,6 +5845,35 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "walrus" +version = "0.27.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5691aeb3546554822fe2c13d63149c26a027cd07d900a72c7c7f37f4321bfaea" +dependencies = [ + "anyhow", + "gimli", + "id-arena", + "leb128", + "log", + "rayon", + "walrus-macro", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "walrus-macro" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a9b0525d7ea6e5f906aca581a172e5c91b4c595290dfa8ad4a2bc9ffef33b44" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -4741,6 +5902,35 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-cli-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0724352b96c7779dcfd3f580b9e7e29beac8f4229c9a27cd2ea53e04f1cc65a" +dependencies = [ + "anyhow", + "base64 0.22.1", + "leb128", + "log", + "rustc-demangle", + "serde", + "serde_json", + "walrus", + "wasm-bindgen-shared", + "wasmparser", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.129" @@ -4773,6 +5963,79 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-encoder" +version = "0.245.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9dca005e69bf015e45577e415b9af8c67e8ee3c0e38b5b0add5aa92581ed5c" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-opt" +version = "0.116.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fd87a4c135535ffed86123b6fb0f0a5a0bc89e50416c942c5f0662c645f679c" +dependencies = [ + "anyhow", + "libc", + "strum 0.24.1", + "strum_macros 0.24.3", + "tempfile", + "thiserror 1.0.69", + "wasm-opt-cxx-sys", + "wasm-opt-sys", +] + +[[package]] +name = "wasm-opt-cxx-sys" +version = "0.116.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c57b28207aa724318fcec6575fe74803c23f6f266fce10cbc9f3f116762f12e" +dependencies = [ + "anyhow", + "cxx", + "cxx-build", + "wasm-opt-sys", +] + +[[package]] +name = "wasm-opt-sys" +version = "0.116.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a1cce564dc768dacbdb718fc29df2dba80bd21cb47d8f77ae7e3d95ceb98cbe" +dependencies = [ + "anyhow", + "cc", + "cxx", + "cxx-build", +] + +[[package]] +name = "wasmparser" +version = "0.245.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f08c9adee0428b7bddf3890fc27e015ac4b761cc608c822667102b8bfd6995e" +dependencies = [ + "bitflags", + "hashbrown 0.16.1", + "indexmap", + "semver", + "serde", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "web-time" version = "1.1.0" @@ -4820,12 +6083,42 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -4839,6 +6132,17 @@ dependencies = [ "windows-strings", ] +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + [[package]] name = "windows-implement" version = "0.60.2" @@ -4867,6 +6171,16 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + [[package]] name = "windows-result" version = "0.4.1" @@ -4928,6 +6242,15 @@ dependencies = [ "windows_x86_64_msvc", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -4976,6 +6299,15 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + [[package]] name = "winnow" version = "1.0.4" @@ -5012,12 +6344,34 @@ dependencies = [ "tap", ] +[[package]] +name = "xtask" +version = "0.1.0" +dependencies = [ + "anyhow", + "blake3", + "serde_json", + "ureq", + "wasm-bindgen-cli-support", + "wasm-opt", +] + [[package]] name = "xxhash-rust" version = "0.8.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7" +[[package]] +name = "yaml_parser" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71ebb04c72edf699612d543f6c421142527b85ac180156017fa26be49dc0762f" +dependencies = [ + "rowan 0.16.1", + "winnow 0.7.15", +] + [[package]] name = "yansi" version = "1.0.1" @@ -5129,23 +6483,6 @@ dependencies = [ "syn 3.0.9", ] -[[package]] -name = "zip" -version = "9.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec2e3161de27091f18a831d9494e9c53378a34833af5c1dda35ad85849da18d6" -dependencies = [ - "crc32fast", - "flate2", - "getrandom 0.4.3", - "indexmap", - "memchr", - "nix", - "typed-path", - "windows-sys 0.61.2", - "zopfli", -] - [[package]] name = "zlib-rs" version = "0.6.8" @@ -5158,18 +6495,6 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" -[[package]] -name = "zopfli" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] - [[package]] name = "zstd" version = "0.13.3" diff --git a/Cargo.toml b/Cargo.toml index 8e473c1..0031997 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,19 +3,68 @@ name = "project_note" version = "0.1.0" edition = "2024" +[workspace] +members = [".", "crates/note-model", "crates/editor", "xtask"] +resolver = "3" + +[workspace.lints.rust] +unsafe_code = "forbid" + +[lints] +workspace = true + [dependencies] +note-model = { path = "crates/note-model" } anyhow = "1.0.104" blake3 = "1.8.7" +bytes = "1.12.1" +http-body = "1.0.1" loro = "1.17.1" tokio = { version = "1.54.1", features = ["full"] } topcoat = { version = "0.11.0", features = ["anyhow", "asset", "discover", "font-fontsource", "fs", "tailwind", "ui", "websocket"] } turso = "0.8.3" uuid = { version = "1.29.0", features = ["v7"] } serde = { version = "1", features = ["derive"] } -zip = { version = "9.1.2", default-features = false, features = ["deflate"] } +flate2 = "1.1.10" +crc32fast = "1.5.3" pulldown-cmark = { version = "0.13.5", default-features = false } serde_json = "1.0.154" +symphonia = { version = "0.6.1", default-features = false, features = ["mkv"] } regex = "1.13.1" +regex-syntax = "0.8" +prettyplease = "0.3.0" +syn = { version = "3.0.9", features = ["full"] } +dprint-plugin-typescript = "0.96.1" +dprint-plugin-json = "0.25.2" +malva = "0.16.0" +markup_fmt = "0.27.6" +pretty_yaml = "0.6.0" +taplo = "0.14.0" +sqlformat = "0.5.0" +dprint-plugin-markdown = "0.28.2" +rustc-hash = "2.1.3" +hashbrown = "0.17.1" +thread-priority = "3.1.1" [build-dependencies] topcoat = { version = "0.11.0", default-features = false, features = ["tailwind"] } + +[profile.dev] +debug = "line-tables-only" + +[profile.release] +debug = "line-tables-only" + +# The wasm editor bundle (`cargo xtask editor`): smallest download. +[profile.editor] +inherits = "release" +opt-level = 3 +lto = "fat" +codegen-units = 1 +panic = "abort" +strip = true + +# Upstream 1.17.1 counts the remaining text per span when decoding a richtext +# snapshot (quadratic in marks); vendor/loro-internal bounds that count. +[patch.crates-io] +loro-internal = { path = "vendor/loro-internal" } diff --git a/assets/editor.css b/assets/editor.css index bf2822e..c5f4a50 100644 --- a/assets/editor.css +++ b/assets/editor.css @@ -1 +1,1146 @@ -.ProseMirror{position:relative;word-wrap:break-word;white-space:pre-wrap;white-space:break-spaces;-webkit-font-variant-ligatures:none;font-variant-ligatures:none;font-feature-settings:"liga" 0}.ProseMirror pre{white-space:pre-wrap}.ProseMirror li{position:relative}.ProseMirror-hideselection *::selection{background:0 0}.ProseMirror-hideselection *::selection{background:0 0}.ProseMirror-hideselection{caret-color:transparent}.ProseMirror [draggable][contenteditable=false]{user-select:text}.ProseMirror-selectednode{outline:2px solid #8cf}li.ProseMirror-selectednode{outline:none}li.ProseMirror-selectednode:after{content:"";position:absolute;pointer-events:none;border:2px solid #8cf;inset:-2px -2px -2px -32px}img.ProseMirror-separator{display:inline!important;border:none!important;margin:0!important}.ProseMirror-gapcursor{display:none;pointer-events:none;position:absolute}.ProseMirror-gapcursor:after{content:"";display:block;position:absolute;animation:1.1s steps(2,start) infinite ProseMirror-cursor-blink;border-top:1px solid #000;width:20px;top:-2px}@keyframes ProseMirror-cursor-blink{to{visibility:hidden}}.ProseMirror-focused .ProseMirror-gapcursor{display:block}.sr-only{position:absolute;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;width:1px;height:1px;margin:-1px;padding:0}.keycaps{display:inline-flex;vertical-align:middle;align-items: center;gap:3px;margin-inline-start:6px}.keycap{display:inline-flex;border:1px solid var(--border,#e3e5ea);background:var(--keycap-bg,#fff);color:var(--muted-foreground,#5b6270);font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);font-variant-numeric:tabular-nums;border-bottom-width:2px;border-radius:6px;justify-content:center;align-items: center;min-width:18px;height:18px;padding:0 4px;font-size:11px;font-weight:500;line-height:1}.tip{position:absolute;z-index:40;display:flex;border:1px solid var(--border,#e3e5ea);background:var(--popover,#fff);color:var(--popover-foreground,#16181d);box-shadow:var(--shadow-float,0 8px 24px #0000001f);font-family:var(--font-sans,"Atkinson Hyperlegible Next",sans-serif);white-space:nowrap;pointer-events:none;opacity:0;border-radius:10px;flex-wrap:wrap;align-items: center;gap:2px;max-width:240px;padding:4px 6px 4px 8px;transition:opacity .15s ease-out,transform .15s ease-out;font-size:12px;font-weight:500;line-height:16px;top:calc(100% + 6px);left:50%;transform:translate(-50%,-2px)}.tip .keycaps{margin-inline-start:4px}.tip-reason{display:none;color:var(--muted-foreground,#5b6270);flex-basis:100%;font-weight:400}.editor-toolbar-btn:disabled .tip-reason{display:block}.editor-toolbar-btn:hover .tip,.bubble-btn:hover .tip{opacity:1;transition-delay:.3s;transform:translate(-50%)}.editor-toolbar-btn:focus-visible .tip{opacity:1;transition-delay:.3s;transform:translate(-50%)}.bubble-btn:focus-visible .tip{opacity:1;transition-delay:.3s;transform:translate(-50%)}.bubble .tip{top:auto;bottom:calc(100% + 6px)}#sync-status{display:inline-flex;border:1px solid var(--border,#e3e5ea);background:var(--card,#fff);color:var(--muted-foreground,#5b6270);font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);white-space:nowrap;border-radius:999px;align-items: center;gap:6px;height:24px;padding:0 10px 0 8px;transition:color .15s ease-out;font-size:12px;font-weight:400;line-height:16px}#sync-status:before{content:"";background:currentColor;border-radius:50%;flex:none;width:6px;height:6px}#sync-status[data-state=saved]{color:var(--ok,#1f7a4d)}#sync-status[data-state=saving]{color:var(--muted-foreground,#5b6270)}#sync-status[data-state=local],#sync-status[data-state=reconnecting]{color:var(--warn,#9a5b00)}#note-header{container:note-header/inline-size}.editor-toolbar{display:flex;flex-wrap:nowrap;flex:none;align-items: center;gap:2px}.editor-toolbar-group{display:flex;align-items: center;gap:2px}.editor-toolbar-group+.editor-toolbar-group:before{content:"";background:var(--border,#e3e5ea);width:1px;height:16px;margin:0 4px}@container note-header (width<=879px){.note-crumb-notebook{display:none}}@container note-header (width<=779px){.editor-toolbar-group[data-group=blocks]{display:none}}@container note-header (width<=619px){.editor-toolbar-btn[data-command=h1],.editor-toolbar-btn[data-command=h2],.editor-toolbar-btn[data-command=h3]{display:none}}@container note-header (width<=559px){#sync-status{gap:0;padding:0 8px;font-size:0}}@container note-header (width<=469px){.editor-toolbar-group[data-group=history]{display:none}}@container note-header (width<=419px){.editor-toolbar-btn[data-command=paragraph],.editor-toolbar-group[data-group=headings]{display:none}.note-crumb{min-width:6rem}}.editor-toolbar-btn{position:relative;display:inline-grid;color:var(--muted-foreground,#5b6270);cursor:pointer;background:0 0;border:0;border-radius:6px;place-items: center;width:28px;height:28px;margin:0;padding:0;transition:background-color .15s ease-out,color .15s ease-out}.editor-toolbar-icon{display:grid;place-items: center}.editor-toolbar-icon svg{display:block}.editor-toolbar-btn:hover:not(:disabled){background:var(--sidebar-accent,#e3e6eb);color:var(--foreground,#16181d)}.editor-toolbar-btn[aria-pressed=true]{background:var(--active-row,#d9ebd3);color:var(--active-row-foreground,#1f3d22)}.editor-toolbar-btn:disabled{opacity:.4;cursor:not-allowed}.editor-toolbar-btn:focus-visible{outline:2px solid var(--ring,#8a5a00);outline-offset:2px}.bubble-btn:focus-visible{outline:2px solid var(--ring,#8a5a00);outline-offset:2px}.btn:focus-visible{outline:2px solid var(--ring,#8a5a00);outline-offset:2px}.link-input:focus-visible{outline:2px solid var(--ring,#8a5a00);outline-offset:2px}.slash-item:focus-visible{outline:2px solid var(--ring,#8a5a00);outline-offset:2px}.bubble,.popover{position:fixed;z-index:50;color:var(--popover-foreground,#16181d);background:var(--popover,#fff);border:1px solid var(--border,#e3e5ea);box-shadow:var(--shadow-float,0 8px 24px #0000001f);font-family:var(--font-sans,"Atkinson Hyperlegible Next",sans-serif);border-radius:10px;font-size:14px;line-height:20px}.bubble[hidden],.popover[hidden],.link-view[hidden],.link-edit[hidden],.link-error[hidden]{display:none}.bubble{display:flex;align-items: center;gap:2px;padding:4px}.bubble-btn{position:relative;display:inline-grid;color:var(--foreground,#16181d);font-family:var(--font-sans,"Atkinson Hyperlegible Next",sans-serif);cursor:pointer;background:0 0;border:0;border-radius:6px;place-items: center;min-width:28px;height:28px;margin:0;padding:0 6px;transition:background-color .15s ease-out;font-size:13px;font-weight:700;line-height:1}.bubble-btn:hover:not(:disabled){background:var(--sidebar-accent,#e3e6eb)}.bubble-btn[aria-pressed=true]{background:var(--active-row,#d9ebd3)}.bubble-btn:disabled{opacity:.4;cursor:not-allowed}.bubble-btn[data-command=italic] .bubble-glyph{font-style:italic;font-weight:500}.bubble-btn[data-command=bold] .bubble-glyph{font-weight:800}.bubble-btn[data-command=code] .bubble-glyph{font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);font-size:12px;font-weight:500}.link-popover{box-sizing:border-box;width:min(360px,100vw - 16px);padding:10px}.link-row{display:flex;gap:6px}.link-input{border:1px solid var(--border,#e3e5ea);background:var(--card,#fff);color:var(--foreground,#16181d);font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);border-radius:6px;flex:1;min-width:0;height:32px;padding:0 10px;font-size:13px}.link-input[aria-invalid=true]{border-color:var(--bad,#b3261e)}.link-input::placeholder{color:var(--muted-foreground,#5b6270)}.link-error{color:var(--bad,#b3261e);margin:6px 0 0;font-size:12px;line-height:16px}.link-actions{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}.link-view{display:grid;gap:2px}.link-href{display:block;color:var(--link,#8a5a00);font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);overflow-wrap:anywhere;font-size:13px;line-height:18px}.btn{display:inline-flex;border:1px solid var(--border,#e3e5ea);background:var(--card,#fff);color:var(--foreground,#16181d);font-family:var(--font-sans,"Atkinson Hyperlegible Next",sans-serif);cursor:pointer;border-radius:6px;align-items: center;gap:6px;height:28px;padding:0 10px;transition:background-color .15s ease-out;font-size:13px;font-weight:500;line-height:1}.btn:hover:not(:disabled){background:var(--sidebar-accent,#e3e6eb)}.btn:disabled{opacity:.45;cursor:not-allowed}.btn-primary{background:var(--primary,#f2b600);color:var(--primary-foreground,#16181d);border-color:#0000}.btn-primary:hover:not(:disabled){background:var(--primary,#f2b600);opacity:.9}.btn-primary .keycaps{margin-inline-start:2px}.btn-primary .keycap{border-color:#0000;border-bottom-color:color-mix(in srgb,var(--primary-foreground,#16181d)35%,transparent);color:inherit;background:0 0}.slash-menu{box-sizing:border-box;width:264px;max-width:calc(100vw - 16px);padding:4px}.slash-list{overflow-y:auto;max-height:288px}.slash-item{display:flex;color:var(--foreground,#16181d);cursor:pointer;border-radius:6px;justify-content:space-between;align-items: center;gap:12px;min-height:32px;padding:0 8px}.slash-item[aria-selected=true]{background:var(--active-row,#d9ebd3)}.slash-item .keycaps{margin-inline-start:0}.slash-empty{color:var(--muted-foreground,#5b6270);padding:8px;font-size:13px}.slash-footer{display:flex;border-top:1px solid var(--border,#e3e5ea);color:var(--muted-foreground,#5b6270);font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);flex-wrap:wrap;align-items: center;gap:2px;margin-top:4px;padding:6px 8px 2px;font-size:11px;line-height:16px}.slash-footer .keycaps{margin-inline-start:0}.note-menu .slash-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}#editor{box-sizing:border-box;max-width:calc(68ch + 48px);margin:0 auto;padding:32px 24px 30vh}#editor .ProseMirror{outline:none;color:var(--foreground,#16181d);caret-color:var(--foreground,#16181d);font-family:var(--font-sans,"Atkinson Hyperlegible Next",sans-serif);overflow-wrap:break-word;word-wrap:break-word;font-variant-ligatures:common-ligatures;max-width:68ch;min-height:60vh;margin:0 auto;font-size:17px;line-height:1.65}#editor .ProseMirror:focus{outline:none}#editor .ProseMirror:focus-visible{outline:none}#editor .ProseMirror>*+*{margin-top:.75em}#editor .ProseMirror ::selection,#editor .ProseMirror::selection{background:var(--mark,#ffe08a);color:var(--foreground,#16181d)}#editor .ProseMirror p{margin:0}#editor .ProseMirror p.is-placeholder:before{content:attr(data-placeholder);float:left;color:var(--muted-foreground,#5b6270);pointer-events:none;height:0}#editor .ProseMirror h1,#editor .ProseMirror h2,#editor .ProseMirror h3{color:var(--foreground,#16181d);letter-spacing:-.01em;margin:0;font-weight:700}#editor .ProseMirror>*+h1,#editor .ProseMirror>*+h2,#editor .ProseMirror>*+h3{margin-top:1.4em}#editor .ProseMirror h1{font-size:30px;line-height:36px}#editor .ProseMirror h2{font-size:23px;line-height:30px}#editor .ProseMirror h3{font-size:19px;line-height:26px}#editor .ProseMirror ul,#editor .ProseMirror ol{margin:0;padding-left:1.6em}#editor .ProseMirror ul{list-style:disc}#editor .ProseMirror ol{list-style:decimal}#editor .ProseMirror ul ul{list-style:circle}#editor .ProseMirror ul ul ul{list-style:square}#editor .ProseMirror li{margin:.2em 0}#editor .ProseMirror li::marker{color:var(--muted-foreground,#5b6270)}#editor .ProseMirror li>p+p,#editor .ProseMirror li>*+ul,#editor .ProseMirror li>*+ol{margin-top:.2em}#editor .ProseMirror blockquote{border-left:3px solid var(--border,#e3e5ea);color:var(--muted-foreground,#5b6270);margin:0;padding:2px 0 2px 16px}#editor .ProseMirror code{border:1px solid var(--border,#e3e5ea);background:var(--background,#f5f6f8);color:var(--foreground,#16181d);font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);border-radius:6px;padding:1px 5px;font-size:.88em}#editor .ProseMirror pre{border:1px solid var(--border,#e3e5ea);background:var(--background,#f5f6f8);color:var(--foreground,#16181d);font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);overflow-x:auto;white-space:pre;border-radius:10px;margin:0;padding:12px 14px;font-size:14px;line-height:22px}#editor .ProseMirror pre code{font-size:inherit;background:0 0;border:0;border-radius:0;padding:0}#editor .ProseMirror mark{background:var(--mark,#ffe08a);color:inherit;border-radius:3px;padding:0 .1em}#editor .ProseMirror a{color:var(--link,#8a5a00);text-decoration-line:underline;text-decoration-thickness:1px;text-decoration-color:color-mix(in srgb,var(--link,#8a5a00)45%,transparent);text-underline-offset:3px;cursor:pointer}#editor .ProseMirror a:hover{text-decoration-color:var(--link,#8a5a00)}#editor .ProseMirror a[href^="/notes/"]{background:color-mix(in srgb,var(--link,#8a5a00)12%,transparent);text-decoration-line:none;box-decoration-break:clone;-webkit-box-decoration-break:clone;border-radius:4px;padding:0 .2em}#editor .ProseMirror a[href^="/notes/"]:hover{text-decoration-line:underline}#editor .ProseMirror hr{border:0;border-top:1px solid var(--border,#e3e5ea);margin:2em 0}#editor .ProseMirror hr.ProseMirror-selectednode{outline:2px solid var(--ring,#8a5a00);outline-offset:4px;border-radius:2px}.ProseMirror-loro-cursor{position:relative;word-break:normal;pointer-events:none;border-left:2px solid;margin-left:-1px;margin-right:-1px}.ProseMirror-loro-cursor>div{position:absolute;color:#fff;font-family:var(--font-mono,"Atkinson Hyperlegible Mono",ui-monospace,monospace);white-space:nowrap;user-select:none;border-radius:4px 4px 4px 0;padding:0 5px;font-size:11px;font-weight:500;line-height:16px;top:-1.5em;left:-2px}.loro-selection{border-radius:2px}@media (prefers-reduced-motion:reduce){.editor-toolbar-btn,.bubble-btn,.btn,.tip,#sync-status{transition-duration:0s!important;transition-delay:0s!important}}@media (forced-colors:active){.editor-toolbar-btn[aria-pressed=true],.bubble-btn[aria-pressed=true],.slash-item[aria-selected=true]{outline:2px solid canvastext}} +/* from prosemirror-view/style/prosemirror.css (MIT) */ +.ProseMirror { + position: relative; +} + +.ProseMirror { + word-wrap: break-word; + white-space: pre-wrap; + white-space: break-spaces; + -webkit-font-variant-ligatures: none; + font-variant-ligatures: none; + font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */ +} + +.ProseMirror pre { + white-space: pre-wrap; +} + +.ProseMirror li { + position: relative; +} + +.ProseMirror-hideselection *::selection { background: transparent; } +.ProseMirror-hideselection *::-moz-selection { background: transparent; } +.ProseMirror-hideselection { caret-color: transparent; } + +/* See https://code.haverbeke.berlin/prosemirror/prosemirror/issues/1421#issuecomment-1759320191 */ +.ProseMirror [draggable][contenteditable=false] { user-select: text } + +.ProseMirror-selectednode { + outline: 2px solid #8cf; +} + +/* Make sure li selections wrap around markers */ + +li.ProseMirror-selectednode { + outline: none; +} + +li.ProseMirror-selectednode:after { + content: ""; + position: absolute; + left: -32px; + right: -2px; top: -2px; bottom: -2px; + border: 2px solid #8cf; + pointer-events: none; +} + +/* Protect against generic img rules */ + +img.ProseMirror-separator { + display: inline !important; + border: none !important; + margin: 0 !important; +} + +/* from prosemirror-gapcursor/style/gapcursor.css (MIT) */ +.ProseMirror-gapcursor { + display: none; + pointer-events: none; + position: absolute; +} + +.ProseMirror-gapcursor:after { + content: ""; + display: block; + position: absolute; + top: -2px; + width: 20px; + border-top: 1px solid black; + animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite; +} + +@keyframes ProseMirror-cursor-blink { + to { + visibility: hidden; + } +} + +.ProseMirror-focused .ProseMirror-gapcursor { + display: block; +} + +/* + * Editor styles, tokens only ("Graphite & Highlighter", see styles.css). Light/dark is + * handled by the theme variables themselves. Fallbacks are the light values. + * Type: Atkinson Hyperlegible Next (UI and body), Atkinson Hyperlegible Mono (meta, keycaps, code). + */ + +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +/* ---- Keycaps (every visible command shows its shortcut as these) ---- */ + +.keycaps { + display: inline-flex; + align-items: center; + gap: 3px; + margin-inline-start: 6px; + vertical-align: middle; +} + +.keycap { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 18px; + height: 18px; + padding: 0 4px; + border: 1px solid var(--border, #e3e5ea); + border-bottom-width: 2px; + border-radius: 6px; + background: var(--keycap-bg, #ffffff); + color: var(--muted-foreground, #5b6270); + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 11px; + font-weight: 500; + line-height: 1; + font-variant-numeric: tabular-nums; +} + +/* ---- Tooltips (toolbar and bubble buttons) ---- */ + +.tip { + position: absolute; + top: calc(100% + 6px); + left: 50%; + z-index: 40; + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 2px; + max-width: 240px; + padding: 4px 6px 4px 8px; + border: 1px solid var(--border, #e3e5ea); + border-radius: 10px; + background: var(--popover, #ffffff); + color: var(--popover-foreground, #16181d); + box-shadow: var(--shadow-float, 0 8px 24px rgb(0 0 0 / 0.12)); + font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); + font-size: 12px; + font-weight: 500; + line-height: 16px; + white-space: nowrap; + pointer-events: none; + opacity: 0; + transform: translate(-50%, -2px); + transition: + opacity 150ms ease-out, + transform 150ms ease-out; +} + +.tip .keycaps { + margin-inline-start: 4px; +} + +.tip-reason { + display: none; + flex-basis: 100%; + color: var(--muted-foreground, #5b6270); + font-weight: 400; +} + +.editor-toolbar-btn:disabled .tip-reason { + display: block; +} + +.editor-toolbar-btn:hover .tip, +.editor-toolbar-btn:focus-visible .tip, +.bubble-btn:hover .tip, +.bubble-btn:focus-visible .tip { + opacity: 1; + transform: translate(-50%, 0); + transition-delay: 300ms; +} + +.bubble .tip { + top: auto; + bottom: calc(100% + 6px); +} + +/* ---- Sync status pill (in the note header's #sync-slot) ---- */ + +#sync-status { + display: inline-flex; + align-items: center; + gap: 6px; + height: 24px; + padding: 0 10px 0 8px; + border: 1px solid var(--border, #e3e5ea); + border-radius: 999px; + background: var(--card, #ffffff); + color: var(--muted-foreground, #5b6270); + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 12px; + font-weight: 400; + line-height: 16px; + white-space: nowrap; + /* No transition: the pill changes while the user types, and animating it costs frames. */ + contain: layout paint; +} + +#sync-status::before { + content: ""; + width: 6px; + height: 6px; + border-radius: 50%; + background: currentColor; + flex: none; +} + +#sync-status .labels { + display: inline-grid; +} + +#sync-status .labels > span { + grid-area: 1 / 1; + visibility: hidden; +} + +#sync-status[data-state="saved"] [data-label="saved"], +#sync-status[data-state="saving"] [data-label="saving"], +#sync-status[data-state="connecting"] [data-label="connecting"], +#sync-status[data-state="reconnecting"] [data-label="reconnecting"], +#sync-status[data-state="local"] [data-label="local"] { + visibility: visible; +} + +#sync-status[data-state="saved"] { + color: var(--ok, #1f7a4d); +} + +#sync-status[data-state="saving"] { + color: var(--muted-foreground, #5b6270); +} + +#sync-status[data-state="local"], +#sync-status[data-state="reconnecting"] { + color: var(--warn, #9a5b00); +} + +/* ---- Note header: one row, the formatting toolbar sits inside it ---- */ + +#note-header { + container: note-header / inline-size; +} + +/* ---- Toolbar: compact, icons only, one line (groups drop out when the row is narrow) ---- */ + +.editor-toolbar { + display: flex; + flex: 0 0 auto; + flex-wrap: nowrap; + align-items: center; + gap: 2px; +} + +.editor-toolbar-group { + display: flex; + align-items: center; + gap: 2px; +} + +.editor-toolbar-group + .editor-toolbar-group::before { + content: ""; + width: 1px; + height: 16px; + margin: 0 4px; + background: var(--border, #e3e5ea); +} + +/* Lower-priority commands leave the bar as the header narrows, so the title keeps + at least 8rem. They stay reachable through the slash menu (/) and markdown shortcuts. */ +@container note-header (max-width: 879px) { + .note-crumb-notebook { + display: none; + } +} + +@container note-header (max-width: 779px) { + .editor-toolbar-group[data-group="blocks"] { + display: none; + } +} + +@container note-header (max-width: 619px) { + .editor-toolbar-btn[data-command="h1"], + .editor-toolbar-btn[data-command="h2"], + .editor-toolbar-btn[data-command="h3"] { + display: none; + } +} + +@container note-header (max-width: 559px) { + #sync-status { + gap: 0; + padding: 0 8px; + font-size: 0; + } +} + +@container note-header (max-width: 469px) { + .editor-toolbar-group[data-group="history"] { + display: none; + } +} + +@container note-header (max-width: 419px) { + .editor-toolbar-btn[data-command="paragraph"], + .editor-toolbar-group[data-group="headings"] { + display: none; + } + .note-crumb { + min-width: 6rem; + } +} + +.editor-toolbar-btn { + position: relative; + display: inline-grid; + place-items: center; + width: 28px; + height: 28px; + margin: 0; + padding: 0; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--muted-foreground, #5b6270); + cursor: pointer; + transition: + background-color 150ms ease-out, + color 150ms ease-out; +} + +.editor-toolbar-icon { + display: grid; + place-items: center; +} + +.editor-toolbar-icon svg { + display: block; +} + +.editor-toolbar-btn:hover:not(:disabled) { + background: var(--sidebar-accent, #e3e6eb); + color: var(--foreground, #16181d); +} + +.editor-toolbar-btn[aria-pressed="true"] { + background: var(--active-row, #d9ebd3); + color: var(--active-row-foreground, #1f3d22); +} + +/* Recording: the record button turns the destructive token while the mic is live. */ +.editor-toolbar-btn[data-recording="true"], +.editor-toolbar-btn[data-recording="true"]:hover:not(:disabled) { + background: var(--destructive, #b3261e); + color: var(--destructive-foreground, #ffffff); +} + +.editor-rec-time { + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 11px; + font-variant-numeric: tabular-nums; + color: var(--muted-foreground, #5b6270); +} + +.editor-rec-time[hidden] { + display: none; +} + +.editor-media-status { + min-width: 0; + overflow: hidden; + font-size: 11px; + color: var(--destructive, #b3261e); + text-overflow: ellipsis; + white-space: nowrap; +} + +.editor-toolbar-btn:disabled { + opacity: 0.4; + cursor: not-allowed; +} + +.editor-toolbar-btn:focus-visible, +.bubble-btn:focus-visible, +.btn:focus-visible, +.link-input:focus-visible, +.slash-item:focus-visible { + outline: 2px solid var(--ring, #8a5a00); + outline-offset: 2px; +} + +/* ---- Floating surfaces: bubble, link popover, slash menu ---- */ + +.bubble, +.popover { + position: fixed; + z-index: 50; + color: var(--popover-foreground, #16181d); + background: var(--popover, #ffffff); + border: 1px solid var(--border, #e3e5ea); + border-radius: 10px; + box-shadow: var(--shadow-float, 0 8px 24px rgb(0 0 0 / 0.12)); + font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); + font-size: 14px; + line-height: 20px; +} + +.bubble[hidden], +.popover[hidden], +.link-view[hidden], +.link-edit[hidden], +.link-error[hidden] { + display: none; +} + +.bubble { + display: flex; + align-items: center; + gap: 2px; + padding: 4px; +} + +.bubble-btn { + position: relative; + display: inline-grid; + place-items: center; + min-width: 28px; + height: 28px; + margin: 0; + padding: 0 6px; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--foreground, #16181d); + font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); + font-size: 13px; + font-weight: 700; + line-height: 1; + cursor: pointer; + transition: background-color 150ms ease-out; +} + +.bubble-btn:hover:not(:disabled) { + background: var(--sidebar-accent, #e3e6eb); +} + +.bubble-btn[aria-pressed="true"] { + background: var(--active-row, #d9ebd3); +} + +.bubble-btn:disabled { + opacity: 0.4; + cursor: not-allowed; +} + +.bubble-btn[data-command="italic"] .bubble-glyph { + font-style: italic; + font-weight: 500; +} + +.bubble-btn[data-command="bold"] .bubble-glyph { + font-weight: 800; +} + +.bubble-btn[data-command="code"] .bubble-glyph { + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 12px; + font-weight: 500; +} + +.link-popover { + width: min(360px, calc(100vw - 16px)); + box-sizing: border-box; + padding: 10px; +} + +.link-row { + display: flex; + gap: 6px; +} + +.link-input { + flex: 1; + min-width: 0; + height: 32px; + padding: 0 10px; + border: 1px solid var(--border, #e3e5ea); + border-radius: 6px; + background: var(--card, #ffffff); + color: var(--foreground, #16181d); + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 13px; +} + +.link-input[aria-invalid="true"] { + border-color: var(--bad, #b3261e); +} + +.link-input::placeholder { + color: var(--muted-foreground, #5b6270); +} + +.link-error { + margin: 6px 0 0; + color: var(--bad, #b3261e); + font-size: 12px; + line-height: 16px; +} + +.link-actions { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 8px; +} + +.link-view { + display: grid; + gap: 2px; +} + +.link-href { + display: block; + color: var(--link, #8a5a00); + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 13px; + line-height: 18px; + overflow-wrap: anywhere; +} + +.btn { + display: inline-flex; + align-items: center; + gap: 6px; + height: 28px; + padding: 0 10px; + border: 1px solid var(--border, #e3e5ea); + border-radius: 6px; + background: var(--card, #ffffff); + color: var(--foreground, #16181d); + font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); + font-size: 13px; + font-weight: 500; + line-height: 1; + cursor: pointer; + transition: background-color 150ms ease-out; +} + +.btn:hover:not(:disabled) { + background: var(--sidebar-accent, #e3e6eb); +} + +.btn:disabled { + opacity: 0.45; + cursor: not-allowed; +} + +.btn-primary { + border-color: transparent; + background: var(--primary, #f2b600); + color: var(--primary-foreground, #16181d); +} + +.btn-primary:hover:not(:disabled) { + background: var(--primary, #f2b600); + opacity: 0.9; +} + +.btn-primary .keycaps { + margin-inline-start: 2px; +} + +.btn-primary .keycap { + border-color: transparent; + border-bottom-color: color-mix(in srgb, var(--primary-foreground, #16181d) 35%, transparent); + background: transparent; + color: inherit; +} + +.slash-menu { + width: 264px; + max-width: calc(100vw - 16px); + box-sizing: border-box; + padding: 4px; +} + +.slash-list { + max-height: 288px; + overflow-y: auto; +} + +.slash-item { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + min-height: 32px; + padding: 0 8px; + border-radius: 6px; + color: var(--foreground, #16181d); + cursor: pointer; +} + +.slash-item[aria-selected="true"] { + background: var(--active-row, #d9ebd3); +} + +.slash-item .keycaps { + margin-inline-start: 0; +} + +.slash-empty { + padding: 8px; + color: var(--muted-foreground, #5b6270); + font-size: 13px; +} + +.slash-footer { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 2px; + margin-top: 4px; + padding: 6px 8px 2px; + border-top: 1px solid var(--border, #e3e5ea); + color: var(--muted-foreground, #5b6270); + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 11px; + line-height: 16px; +} + +.slash-footer .keycaps { + margin-inline-start: 0; +} + +/* Note suggestions: long titles are cut with an ellipsis */ + +.note-menu .slash-label { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* ---- Editor surface ---- */ + +#editor { + max-width: calc(68ch + 48px); + margin: 0 auto; + padding: 32px 24px 30vh; + box-sizing: border-box; +} + +#editor .ProseMirror { + min-height: 60vh; + max-width: 68ch; + margin: 0 auto; + outline: none; + color: var(--foreground, #16181d); + caret-color: var(--foreground, #16181d); + font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); + font-size: 17px; + line-height: 1.65; + overflow-wrap: break-word; + word-wrap: break-word; + font-variant-ligatures: common-ligatures; +} + +#editor .ProseMirror:focus, +#editor .ProseMirror:focus-visible { + outline: none; +} + +/* Top-level blocks sit in pages (view.rs); spacing runs across page boundaries. + :where keeps the specificity of the plain `.ProseMirror > * + *` rules. */ +#editor .ProseMirror :where(.pm-page) > * + *, +#editor .ProseMirror :where(.pm-page + .pm-page) > :where(:first-child) { + margin-top: 0.75em; +} + +#editor .ProseMirror ::selection, +#editor .ProseMirror::selection { + background: var(--mark, #ffe08a); + color: var(--foreground, #16181d); +} + +#editor .ProseMirror p { + margin: 0; +} + +/* Embedded media: images scale to the column, audio and video are their own blocks. */ +#editor .ProseMirror img { + max-width: 100%; +} + +#editor .ProseMirror audio.note-media { + display: block; + width: 100%; + max-width: 32rem; +} + +#editor .ProseMirror video.note-media { + display: block; + max-width: 100%; +} + +/* A recording take: its audio and continue button, until the take is live or lost. Then the + label stands in for both. The state is an attribute, so the editor never rebuilds the span. */ +#editor .ProseMirror span.note-take { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; +} + +#editor .ProseMirror span.note-take audio { + flex: 1 1 16rem; + max-width: 32rem; +} + +#editor .ProseMirror span.note-take .note-take-continue { + font: inherit; + font-size: 0.875rem; + padding: 0.25rem 0.625rem; + border: 1px solid var(--border, #d4d7de); + border-radius: 0.375rem; + background: var(--background, #fff); + color: var(--foreground, #1f2330); + cursor: pointer; +} + +#editor .ProseMirror span.note-take[data-take-state="live"] > audio, +#editor .ProseMirror span.note-take[data-take-state="live"] > .note-take-continue, +#editor .ProseMirror span.note-take[data-take-state="lost"] > audio, +#editor .ProseMirror span.note-take[data-take-state="lost"] > .note-take-continue { + display: none; +} + +#editor .ProseMirror span.note-take[data-take-state="live"]::before, +#editor .ProseMirror span.note-take[data-take-state="lost"]::before { + color: var(--muted-foreground, #5b6270); + font-size: 0.875rem; +} + +#editor .ProseMirror span.note-take[data-take-state="live"]::before { + content: attr(data-recording-label); +} + +#editor .ProseMirror span.note-take[data-take-state="lost"]::before { + content: attr(data-lost-label); +} + +/* Placeholder: shown by the placeholder decoration while the note is empty. */ +#editor .ProseMirror p.is-placeholder::before { + content: attr(data-placeholder); + float: left; + height: 0; + color: var(--muted-foreground, #5b6270); + pointer-events: none; +} + +/* Headings: 30/36, 23/30, 19/26, all bold. */ +#editor .ProseMirror h1, +#editor .ProseMirror h2, +#editor .ProseMirror h3 { + margin: 0; + color: var(--foreground, #16181d); + font-weight: 700; + letter-spacing: -0.01em; +} + +#editor .ProseMirror :where(.pm-page) > * + h1, +#editor .ProseMirror :where(.pm-page) > * + h2, +#editor .ProseMirror :where(.pm-page) > * + h3, +#editor .ProseMirror :where(.pm-page + .pm-page) > h1:where(:first-child), +#editor .ProseMirror :where(.pm-page + .pm-page) > h2:where(:first-child), +#editor .ProseMirror :where(.pm-page + .pm-page) > h3:where(:first-child) { + margin-top: 1.4em; +} + +#editor .ProseMirror h1 { + font-size: 30px; + line-height: 36px; +} + +#editor .ProseMirror h2 { + font-size: 23px; + line-height: 30px; +} + +#editor .ProseMirror h3 { + font-size: 19px; + line-height: 26px; +} + +/* Lists */ + +#editor .ProseMirror ul, +#editor .ProseMirror ol { + margin: 0; + padding-left: 1.6em; +} + +#editor .ProseMirror ul { + list-style: disc; +} + +#editor .ProseMirror ol { + list-style: decimal; +} + +#editor .ProseMirror ul ul { + list-style: circle; +} + +#editor .ProseMirror ul ul ul { + list-style: square; +} + +#editor .ProseMirror li { + margin: 0.2em 0; +} + +#editor .ProseMirror li::marker { + color: var(--muted-foreground, #5b6270); +} + +#editor .ProseMirror li > p + p, +#editor .ProseMirror li > * + ul, +#editor .ProseMirror li > * + ol { + margin-top: 0.2em; +} + +/* A list or quote cut by a page boundary (view.rs): the part on the later page has + pm-cont, the earlier part pm-more; together they look like one element. */ +#editor .ProseMirror .pm-page > .pm-cont, +#editor .ProseMirror li.pm-cont, +#editor .ProseMirror .pm-cont > li:first-child { + margin-top: 0; +} + +#editor .ProseMirror li.pm-cont { + list-style-type: none; +} + +#editor .ProseMirror li.pm-more { + margin-bottom: 0; +} + +#editor .ProseMirror blockquote.pm-cont { + padding-top: 0; +} + +#editor .ProseMirror blockquote.pm-more { + padding-bottom: 0; +} + +/* Quote */ + +#editor .ProseMirror blockquote { + margin: 0; + padding: 2px 0 2px 16px; + border-left: 3px solid var(--border, #e3e5ea); + color: var(--muted-foreground, #5b6270); +} + +/* Code: mono on the background token, hairline border */ + +#editor .ProseMirror code { + padding: 1px 5px; + border: 1px solid var(--border, #e3e5ea); + border-radius: 6px; + background: var(--background, #f5f6f8); + color: var(--foreground, #16181d); + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 0.88em; +} + +#editor .ProseMirror pre { + margin: 0; + padding: 12px 14px; + border: 1px solid var(--border, #e3e5ea); + border-radius: 10px; + background: var(--background, #f5f6f8); + color: var(--foreground, #16181d); + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 14px; + line-height: 22px; + overflow-x: auto; + white-space: pre; +} + +#editor .ProseMirror pre code { + display: block; + padding: 0; + border: 0; + border-radius: 0; + background: none; + font-size: inherit; +} + +/* Long code blocks render as line chunks (view.rs); off-screen ones skip layout, + sized by their line count until first shown. */ +#editor .ProseMirror .code-chunk { + content-visibility: auto; + contain-intrinsic-size: auto none auto calc(var(--lines) * 22px); +} + +/* A chunk far from the viewport is an empty placeholder of its height. */ +#editor .ProseMirror .code-chunk:empty { + height: calc(var(--lines) * 22px); +} + +/* Code blocks: a header bar (ui/codeblock.rs) sits over the top 34px of each pre */ + +#editor .ProseMirror pre { + padding-top: 46px; +} + +.code-layer { + position: absolute; + inset: 0; + pointer-events: none; +} + +.code-layer[hidden] { + display: none; +} + +.code-head { + position: absolute; + box-sizing: border-box; + display: flex; + align-items: center; + gap: 4px; + height: 34px; + padding: 0 6px 0 10px; + border-bottom: 1px solid var(--border, #e3e5ea); + border-radius: 9px 9px 0 0; + background: color-mix(in srgb, var(--foreground, #16181d) 3%, transparent); + color: var(--muted-foreground, #5b6270); + font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); + font-size: 12px; + pointer-events: auto; +} + +.code-head[hidden] { + display: none; +} + +.code-lang { + min-width: 0; + max-width: 14rem; + height: 24px; + margin: 0; + padding: 0 4px; + border: 0; + border-radius: 6px; + background: transparent; + color: inherit; + font: inherit; + cursor: pointer; +} + +.code-lang:hover { + background: var(--sidebar-accent, #e3e6eb); + color: var(--foreground, #16181d); +} + +.code-lang option { + background: var(--background, #f5f6f8); + color: var(--foreground, #16181d); +} + +.code-spacer { + flex: 1; + min-width: 4px; +} + +.code-status { + min-width: 0; + overflow: hidden; + font-size: 11px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.code-btn { + display: inline-grid; + place-items: center; + flex: none; + width: 24px; + height: 24px; + margin: 0; + padding: 0; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--muted-foreground, #5b6270); + cursor: pointer; + transition: + background-color 150ms ease-out, + color 150ms ease-out; +} + +.code-btn svg { + display: block; +} + +.code-btn:hover:not(:disabled) { + background: var(--sidebar-accent, #e3e6eb); + color: var(--foreground, #16181d); +} + +.code-btn[aria-pressed="true"] { + background: var(--active-row, #d9ebd3); + color: var(--active-row-foreground, #1f3d22); +} + +.code-btn:disabled { + opacity: 0.4; + cursor: not-allowed; +} + +.code-btn:focus-visible, +.code-lang:focus-visible { + outline: 2px solid var(--ring, #8a5a00); + outline-offset: 2px; +} + +/* Marks: search-style highlight */ + +#editor .ProseMirror mark { + padding: 0 0.1em; + border-radius: 3px; + background: var(--mark, #ffe08a); + color: inherit; +} + +/* Links: accent ink with a quiet underline */ + +#editor .ProseMirror a { + color: var(--link, #8a5a00); + text-decoration-line: underline; + text-decoration-thickness: 1px; + text-decoration-color: color-mix(in srgb, var(--link, #8a5a00) 45%, transparent); + text-underline-offset: 3px; + cursor: pointer; +} + +#editor .ProseMirror a:hover { + text-decoration-color: var(--link, #8a5a00); +} + +/* Note links (href /notes/): a tinted chip, underlined only on hover */ + +#editor .ProseMirror a[href^="/notes/"] { + padding: 0 0.2em; + border-radius: 4px; + background: color-mix(in srgb, var(--link, #8a5a00) 12%, transparent); + text-decoration-line: none; + box-decoration-break: clone; + -webkit-box-decoration-break: clone; +} + +#editor .ProseMirror a[href^="/notes/"]:hover { + text-decoration-line: underline; +} + +/* Horizontal rule */ + +#editor .ProseMirror hr { + margin: 2em 0; + border: 0; + border-top: 1px solid var(--border, #e3e5ea); +} + +#editor .ProseMirror hr.ProseMirror-selectednode { + outline: 2px solid var(--ring, #8a5a00); + outline-offset: 4px; + border-radius: 2px; +} + +/* ---- Remote cursors and selections (loro-prosemirror classes) ---- */ + +.ProseMirror-loro-cursor { + position: relative; + margin-left: -1px; + margin-right: -1px; + /* border-color is set inline per user */ + border-left: 2px solid; + word-break: normal; + pointer-events: none; +} + +/* Name label in the user's color, mono 11px. */ +.ProseMirror-loro-cursor > div { + position: absolute; + top: -1.5em; + left: -2px; + padding: 0 5px; + border-radius: 4px 4px 4px 0; + /* background-color is set inline per user */ + color: #ffffff; + font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); + font-size: 11px; + font-weight: 500; + line-height: 16px; + white-space: nowrap; + user-select: none; +} + +.loro-selection { + border-radius: 2px; +} + +@media (prefers-reduced-motion: reduce) { + .editor-toolbar-btn, + .bubble-btn, + .btn, + .tip { + transition-duration: 0ms !important; + transition-delay: 0ms !important; + } +} + +@media (forced-colors: active) { + .editor-toolbar-btn[aria-pressed="true"], + .bubble-btn[aria-pressed="true"], + .slash-item[aria-selected="true"] { + outline: 2px solid CanvasText; + } +} diff --git a/assets/editor.js b/assets/editor.js deleted file mode 100644 index 3b07f42..0000000 --- a/assets/editor.js +++ /dev/null @@ -1,16 +0,0 @@ -var ri=["Map","List","MovableList","Text","Tree","Counter"];function Ro(t,e){if(typeof t!=="object"||t===null||Array.isArray(t))throw Error("Invalid toContainerTree options");for(let n of Object.keys(t))if(n!=="text"&&!(e&&n==="roots"))throw Error("Unknown toContainerTree option: "+n);if(e&&t.roots!==void 0&&!Array.isArray(t.roots))throw Error("roots must be an array");return t}function Lo(t,e,n){return{cid:t.cid,start:e,totalLength:n,items:t.value}}function Po(t,e,n){return{type:ri[t],cid:e,value:n}}function Bo(t,e,n){return"cid:"+e+"@"+t+":"+ri[n]}function zo(t,e){return"cid:root-"+t+":"+ri[e]}function Fo(t){return{type:"Value",value:t}}function Vo(t){return t.slice()}function Wo(t,e,n){Object.defineProperty(t,e,{value:n,enumerable:!0,writable:!0,configurable:!0})}function qo(t,e,n){Object.defineProperty(t,e,{value:n,enumerable:!0,writable:!0,configurable:!0})}var a,tt=Array(128).fill(void 0);tt.push(void 0,null,!0,!1);function x(t){return tt[t]}var M=0,An=null;function Ze(){if(An===null||An.byteLength===0)An=new Uint8Array(a.memory.buffer);return An}var ur=typeof TextEncoder<"u"?new TextEncoder("utf-8"):{encode:()=>{throw Error("TextEncoder not available")}},kc=typeof ur.encodeInto==="function"?function(t,e){return ur.encodeInto(t,e)}:function(t,e){let n=ur.encode(t);return e.set(n),{read:t.length,written:n.length}};function q(t,e,n){if(n===void 0){let l=ur.encode(t),c=e(l.length,1)>>>0;return Ze().subarray(c,c+l.length).set(l),M=l.length,c}let r=t.length,i=e(r,1)>>>0,o=Ze(),s=0;for(;s127)break;o[i+s]=l}if(s!==r){if(s!==0)t=t.slice(s);i=n(i,r,r=s+t.length*3,1)>>>0;let l=Ze().subarray(i+s,i+r),c=kc(t,l);s+=c.written,i=n(i,r,s,1)>>>0}return M=s,i}var De=null;function u(){if(De===null||De.buffer.detached===!0||De.buffer.detached===void 0&&De.buffer!==a.memory.buffer)De=new DataView(a.memory.buffer);return De}var En=tt.length;function w(t){if(En===tt.length)tt.push(tt.length+1);let e=En;return En=tt[e],tt[e]=t,e}function gt(t,e){try{return t.apply(this,e)}catch(n){a.__wbindgen_exn_store(w(n))}}var Xo=typeof TextDecoder<"u"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};if(typeof TextDecoder<"u")Xo.decode();function it(t,e){return t=t>>>0,Xo.decode(Ze().subarray(t,t+e))}function xc(t){if(t<132)return;tt[t]=En,En=t}function _(t){let e=x(t);return xc(t),e}function Te(t,e){return t=t>>>0,Ze().subarray(t/1,t/1+e)}function K(t){return t===void 0||t===null}var Uo=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>{a.__wbindgen_export_4.get(t.dtor)(t.a,t.b)});function $o(t,e,n,r){let i={a:t,b:e,cnt:1,dtor:n},o=(...s)=>{i.cnt++;let l=i.a;i.a=0;try{return r(l,i.b,...s)}finally{if(--i.cnt===0)a.__wbindgen_export_4.get(i.dtor)(l,i.b),Uo.unregister(i);else i.a=l}};return o.original=i,Uo.register(o,i,i),o}function hi(t){let e=typeof t;if(e=="number"||e=="boolean"||t==null)return`${t}`;if(e=="string")return`"${t}"`;if(e=="symbol"){let i=t.description;if(i==null)return"Symbol";else return`Symbol(${i})`}if(e=="function"){let i=t.name;if(typeof i=="string"&&i.length>0)return`Function(${i})`;else return"Function"}if(Array.isArray(t)){let i=t.length,o="[";if(i>0)o+=hi(t[0]);for(let s=1;s1)r=n[1];else return toString.call(t);if(r=="Object")try{return"Object("+JSON.stringify(t)+")"}catch(i){return"Object"}if(t instanceof Error)return`${t.name}: ${t.message} -${t.stack}`;return r}function Nn(t,e){let n=e(t.length*1,1)>>>0;return Ze().set(t,n/1),M=t.length,n}function fr(){a.callPendingEvents()}function pi(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M;return a.isValidContainerId(e,n)!==0}function Wt(t,e){let n=e(t.length*4,4)>>>0,r=u();for(let i=0;i>>0;let n=u(),r=[];for(let i=t;i"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_awarenesswasm_free(t>>>0,1));var Jo=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_changemodifier_free(t>>>0,1));class tn{static __wrap(t){t=t>>>0;let e=Object.create(tn.prototype);return e.__wbg_ptr=t,Jo.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Jo.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_changemodifier_free(t,0)}setMessage(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M,r=a.changemodifier_setMessage(this.__wbg_ptr,e,n);return tn.__wrap(r)}setTimestamp(t){let e=a.changemodifier_setTimestamp(this.__wbg_ptr,t);return tn.__wrap(e)}}var jo=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_cursor_free(t>>>0,1));class Tt{static __wrap(t){t=t>>>0;let e=Object.create(Tt.prototype);return e.__wbg_ptr=t,jo.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,jo.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_cursor_free(t,0)}containerId(){let t=a.cursor_containerId(this.__wbg_ptr);return _(t)}pos(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.cursor_pos(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}kind(){let t=a.cursor_kind(this.__wbg_ptr);return _(t)}side(){let t=a.cursor_side(this.__wbg_ptr);return _(t)}static decode(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Nn(t,a.__wbindgen_malloc),s=M;a.cursor_decode(i,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Tt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}encode(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.cursor_encode(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=Te(t,e).slice();return a.__wbindgen_free(t,e*1,1),n}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var Ho=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_ephemeralstorewasm_free(t>>>0,1));class Dn{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Ho.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_ephemeralstorewasm_free(t,0)}getAllStates(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.ephemeralstorewasm_getAllStates(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}removeOutdated(){a.ephemeralstorewasm_removeOutdated(this.__wbg_ptr)}subscribeLocalUpdates(t){let e=a.ephemeralstorewasm_subscribeLocalUpdates(this.__wbg_ptr,w(t));return _(e)}get(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M,r=a.ephemeralstorewasm_get(this.__wbg_ptr,e,n);return _(r)}constructor(t){let e=a.ephemeralstorewasm_new(t);return this.__wbg_ptr=e>>>0,Ho.register(this,this.__wbg_ptr,this),this}set(t,e){let n=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),r=M;a.ephemeralstorewasm_set(this.__wbg_ptr,n,r,w(e))}keys(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.ephemeralstorewasm_keys(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),n}finally{a.__wbindgen_add_to_stack_pointer(16)}}apply(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16),i=Nn(t,a.__wbindgen_malloc),o=M;a.ephemeralstorewasm_apply(r,this.__wbg_ptr,i,o);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}delete(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M;a.ephemeralstorewasm_delete(this.__wbg_ptr,e,n)}encode(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.ephemeralstorewasm_encode(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=Te(e,n).slice();return a.__wbindgen_free(e,n*1,1),r}finally{a.__wbindgen_add_to_stack_pointer(16)}}isEmpty(){return a.ephemeralstorewasm_isEmpty(this.__wbg_ptr)!==0}encodeAll(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.ephemeralstorewasm_encodeAll(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=Te(t,e).slice();return a.__wbindgen_free(t,e*1,1),n}finally{a.__wbindgen_add_to_stack_pointer(16)}}subscribe(t){let e=a.ephemeralstorewasm_subscribe(this.__wbg_ptr,w(t));return _(e)}}var ii=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_lorocounter_free(t>>>0,1));class Re{static __wrap(t){t=t>>>0;let e=Object.create(Re.prototype);return e.__wbg_ptr=t,ii.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,ii.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_lorocounter_free(t,0)}toContainerTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_toContainerTree(i,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isAttached(){return a.lorocounter_isAttached(this.__wbg_ptr)!==0}getAttached(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_getAttached(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getShallowValue(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_getShallowValue(r,this.__wbg_ptr);var t=u().getFloat64(r+0,!0),e=u().getInt32(r+8,!0),n=u().getInt32(r+12,!0);if(n)throw _(e);return t}finally{a.__wbindgen_add_to_stack_pointer(16)}}get id(){let t=a.lorocounter_id(this.__wbg_ptr);return _(t)}constructor(){let t=a.lorocounter_new();return this.__wbg_ptr=t>>>0,ii.register(this,this.__wbg_ptr,this),this}kind(){let t=a.lorocounter_kind(this.__wbg_ptr);return _(t)}parent(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_parent(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_getShallowValue(r,this.__wbg_ptr);var t=u().getFloat64(r+0,!0),e=u().getInt32(r+8,!0),n=u().getInt32(r+12,!0);if(n)throw _(e);return t}finally{a.__wbindgen_add_to_stack_pointer(16)}}decrement(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_decrement(r,this.__wbg_ptr,t);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get value(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_getShallowValue(r,this.__wbg_ptr);var t=u().getFloat64(r+0,!0),e=u().getInt32(r+8,!0),n=u().getInt32(r+12,!0);if(n)throw _(e);return t}finally{a.__wbindgen_add_to_stack_pointer(16)}}increment(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_increment(r,this.__wbg_ptr,t);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}subscribe(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorocounter_subscribe(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var oi=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_lorodoc_free(t>>>0,1));class Pt{static __wrap(t){t=t>>>0;let e=Object.create(Pt.prototype);return e.__wbg_ptr=t,oi.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,oi.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_lorodoc_free(t,0)}applyDiff(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_applyDiff(i,this.__wbg_ptr,w(t),K(e)?0:w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isShallow(){return a.lorodoc_isShallow(this.__wbg_ptr)!==0}changeCount(){return a.lorodoc_changeCount(this.__wbg_ptr)>>>0}getByPath(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.lorodoc_getByPath(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getCounter(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getCounter(i,this.__wbg_ptr,Nt(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Re.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}isDetached(){return a.lorodoc_isDetached(this.__wbg_ptr)!==0}get peerIdStr(){let t=a.lorodoc_peerIdStr(this.__wbg_ptr);return _(t)}setPeerId(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_setPeerId(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getCursorPos(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);en(t,Tt),a.lorodoc_getCursorPos(i,this.__wbg_ptr,t.__wbg_ptr);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}hasContainer(t){return a.lorodoc_hasContainer(this.__wbg_ptr,w(t))!==0}importBatch(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_importBatch(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}cmpFrontiers(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16),s=Wt(t,a.__wbindgen_malloc),l=M,c=Wt(e,a.__wbindgen_malloc),d=M;a.lorodoc_cmpFrontiers(o,this.__wbg_ptr,s,l,c,d);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}debugHistory(){a.lorodoc_debugHistory(this.__wbg_ptr)}static fromSnapshot(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Nn(t,a.__wbindgen_malloc),s=M;a.lorodoc_fromSnapshot(i,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Pt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getChangeAt(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getChangeAt(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}oplogVersion(){let t=a.lorodoc_oplogVersion(this.__wbg_ptr);return Dt.__wrap(t)}getMovableList(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getMovableList(i,this.__wbg_ptr,Nt(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Le.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}frontiersToVV(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Wt(t,a.__wbindgen_malloc),s=M;a.lorodoc_frontiersToVV(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Dt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getAllChanges(){let t=a.lorodoc_getAllChanges(this.__wbg_ptr);return _(t)}oplogFrontiers(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_oplogFrontiers(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}vvToFrontiers(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);en(t,Dt),a.lorodoc_vvToFrontiers(i,this.__wbg_ptr,t.__wbg_ptr);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}shallowSinceVV(){let t=a.lorodoc_shallowSinceVV(this.__wbg_ptr);return Dt.__wrap(t)}configTextStyle(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_configTextStyle(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getOpsInChange(t){try{let s=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getOpsInChange(s,this.__wbg_ptr,w(t));var e=u().getInt32(s+0,!0),n=u().getInt32(s+4,!0),r=u().getInt32(s+8,!0),i=u().getInt32(s+12,!0);if(i)throw _(r);var o=te(e,n).slice();return a.__wbindgen_free(e,n*4,4),o}finally{a.__wbindgen_add_to_stack_pointer(16)}}getShallowValue(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getShallowValue(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}checkoutToLatest(){try{let n=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_checkoutToLatest(n,this.__wbg_ptr);var t=u().getInt32(n+0,!0),e=u().getInt32(n+4,!0);if(e)throw _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}cmpWithFrontiers(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Wt(t,a.__wbindgen_malloc),s=M;a.lorodoc_cmpWithFrontiers(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return e}finally{a.__wbindgen_add_to_stack_pointer(16)}}exportJsonInIdSpan(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_exportJsonInIdSpan(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}subscribeJsonpath(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16),s=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),l=M;a.lorodoc_subscribeJsonpath(o,this.__wbg_ptr,s,l,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}deleteRootContainer(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_deleteRootContainer(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}exportJsonUpdates(t,e,n){try{let s=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_exportJsonUpdates(s,this.__wbg_ptr,w(t),w(e),K(n)?16777215:n?1:0);var r=u().getInt32(s+0,!0),i=u().getInt32(s+4,!0),o=u().getInt32(s+8,!0);if(o)throw _(i);return _(r)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getContainerById(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getContainerById(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getPendingTxnLength(){return a.lorodoc_getPendingTxnLength(this.__wbg_ptr)>>>0}importJsonUpdates(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_importJsonUpdates(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}importUpdateBatch(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_importBatch(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}setDetachedEditing(t){a.lorodoc_setDetachedEditing(this.__wbg_ptr,t)}setRecordTimestamp(t){a.lorodoc_setRecordTimestamp(this.__wbg_ptr,t)}subscribePreCommit(t){let e=a.lorodoc_subscribePreCommit(this.__wbg_ptr,w(t));return _(e)}findIdSpansBetween(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16),s=Wt(t,a.__wbindgen_malloc),l=M,c=Wt(e,a.__wbindgen_malloc),d=M;a.lorodoc_findIdSpansBetween(o,this.__wbg_ptr,s,l,c,d);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getChangeAtLamport(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16),s=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),l=M;a.lorodoc_getChangeAtLamport(o,this.__wbg_ptr,s,l,e);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getPathToContainer(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getPathToContainer(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}exportPendingUpdates(){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_exportPendingUpdates(i,this.__wbg_ptr);var t=u().getInt32(i+0,!0),e=u().getInt32(i+4,!0),n=u().getInt32(i+8,!0),r=u().getInt32(i+12,!0);if(r)throw _(n);let o;if(t!==0)o=Te(t,e).slice(),a.__wbindgen_free(t,e*1,1);return o}finally{a.__wbindgen_add_to_stack_pointer(16)}}getChangedContainersIn(t,e){try{let l=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getChangedContainersIn(l,this.__wbg_ptr,w(t),e);var n=u().getInt32(l+0,!0),r=u().getInt32(l+4,!0),i=u().getInt32(l+8,!0),o=u().getInt32(l+12,!0);if(o)throw _(i);var s=te(n,r).slice();return a.__wbindgen_free(n,r*4,4),s}finally{a.__wbindgen_add_to_stack_pointer(16)}}getDeepValueWithID(){let t=a.lorodoc_getDeepValueWithID(this.__wbg_ptr);return _(t)}setNextCommitOrigin(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M;a.lorodoc_setNextCommitOrigin(this.__wbg_ptr,e,n)}getUncommittedOpsAsJson(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getUncommittedOpsAsJson(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}setNextCommitMessage(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M;a.lorodoc_setNextCommitMessage(this.__wbg_ptr,e,n)}setNextCommitOptions(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_setNextCommitOptions(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}shallowSinceFrontiers(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_shallowSinceFrontiers(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}subscribeLocalUpdates(t){let e=a.lorodoc_subscribeLocalUpdates(this.__wbg_ptr,w(t));return _(e)}travelChangeAncestors(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Wt(t,a.__wbindgen_malloc),s=M;a.lorodoc_travelChangeAncestors(i,this.__wbg_ptr,o,s,w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}clearNextCommitOptions(){a.lorodoc_clearNextCommitOptions(this.__wbg_ptr)}configDefaultTextStyle(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_configDefaultTextStyle(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getDecodedValueCacheLimit(){return a.lorodoc_getDecodedValueCacheLimit(this.__wbg_ptr)>>>0}setChangeMergeInterval(t){a.lorodoc_setChangeMergeInterval(this.__wbg_ptr,t)}setNextCommitTimestamp(t){a.lorodoc_setNextCommitTimestamp(this.__wbg_ptr,t)}setHideEmptyRootContainers(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_setHideEmptyRootContainers(r,this.__wbg_ptr,t);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isDetachedEditingEnabled(){return a.lorodoc_isDetachedEditingEnabled(this.__wbg_ptr)!==0}setDecodedValueCacheLimit(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_setDecodedValueCacheLimit(r,this.__wbg_ptr,t);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}subscribeFirstCommitFromPeer(t){let e=a.lorodoc_subscribeFirstCommitFromPeer(this.__wbg_ptr,w(t));return _(e)}constructor(){let t=a.lorodoc_new();return this.__wbg_ptr=t>>>0,oi.register(this,this.__wbg_ptr,this),this}diff(t,e,n){try{let s=a.__wbindgen_add_to_stack_pointer(-16),l=Wt(t,a.__wbindgen_malloc),c=M,d=Wt(e,a.__wbindgen_malloc),f=M;a.lorodoc_diff(s,this.__wbg_ptr,l,c,d,f,K(n)?16777215:n?1:0);var r=u().getInt32(s+0,!0),i=u().getInt32(s+4,!0),o=u().getInt32(s+8,!0);if(o)throw _(i);return _(r)}finally{a.__wbindgen_add_to_stack_pointer(16)}}fork(){let t=a.lorodoc_fork(this.__wbg_ptr);return Pt.__wrap(t)}attach(){a.lorodoc_attach(this.__wbg_ptr)}commit(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_commit(r,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}detach(){a.lorodoc_detach(this.__wbg_ptr)}export(t){try{let s=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_export(s,this.__wbg_ptr,w(t));var e=u().getInt32(s+0,!0),n=u().getInt32(s+4,!0),r=u().getInt32(s+8,!0),i=u().getInt32(s+12,!0);if(i)throw _(r);var o=Te(e,n).slice();return a.__wbindgen_free(e,n*1,1),o}finally{a.__wbindgen_add_to_stack_pointer(16)}}import(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Nn(t,a.__wbindgen_malloc),s=M;a.lorodoc_import(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}forkAt(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Wt(t,a.__wbindgen_malloc),s=M;a.lorodoc_forkAt(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Pt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getMap(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getMap(i,this.__wbg_ptr,Nt(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return St.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}opCount(){return a.lorodoc_opCount(this.__wbg_ptr)>>>0}get peerId(){let t=a.lorodoc_peerId(this.__wbg_ptr);return BigInt.asUintN(64,t)}toJSON(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_toJSON(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}version(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_version(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return Dt.__wrap(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}checkout(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16),i=Wt(t,a.__wbindgen_malloc),o=M;a.lorodoc_checkout(r,this.__wbg_ptr,i,o);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getList(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getList(i,this.__wbg_ptr,Nt(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return ee.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}getText(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getText(i,this.__wbg_ptr,Nt(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Rt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}getTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_getTree(i,this.__wbg_ptr,Nt(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return me.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}frontiers(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_frontiers(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}JSONPath(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.lorodoc_JSONPath(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}revertTo(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16),i=Wt(t,a.__wbindgen_malloc),o=M;a.lorodoc_revertTo(r,this.__wbg_ptr,i,o);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}subscribe(t){let e=a.lorodoc_subscribe(this.__wbg_ptr,w(t));return _(e)}toContainerTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_toContainerTree(i,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toContainerTreeJson(t){let e,n;try{let d=a.__wbindgen_add_to_stack_pointer(-16);a.lorodoc_toContainerTreeJson(d,this.__wbg_ptr,K(t)?0:w(t));var r=u().getInt32(d+0,!0),i=u().getInt32(d+4,!0),o=u().getInt32(d+8,!0),s=u().getInt32(d+12,!0),l=r,c=i;if(s)throw l=0,c=0,_(o);return e=l,n=c,it(l,c)}finally{a.__wbindgen_add_to_stack_pointer(16),a.__wbindgen_free(e,n,1)}}}var si=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_lorolist_free(t>>>0,1));class ee{static __wrap(t){t=t>>>0;let e=Object.create(ee.prototype);return e.__wbg_ptr=t,si.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,si.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_lorolist_free(t,0)}isAttached(){return a.lorolist_isAttached(this.__wbg_ptr)!==0}getAttached(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_getAttached(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}pushContainer(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_pushContainer(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getRangeValue(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_getRangeValue(o,this.__wbg_ptr,t,e);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}insertContainer(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_insertContainer(o,this.__wbg_ptr,t,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getShallowValue(){let t=a.lorolist_getShallowValue(this.__wbg_ptr);return _(t)}getDeepValueWithID(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_getDeepValueWithID(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getRangeDeepValueWithID(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_getRangeDeepValueWithID(o,this.__wbg_ptr,t,e);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get id(){let t=a.lorolist_id(this.__wbg_ptr);return _(t)}get(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_get(i,this.__wbg_ptr,t);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}constructor(){let t=a.lorolist_new();return this.__wbg_ptr=t>>>0,si.register(this,this.__wbg_ptr,this),this}pop(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_pop(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}kind(){let t=a.lorolist_kind(this.__wbg_ptr);return _(t)}push(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_push(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}clear(){try{let n=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_clear(n,this.__wbg_ptr);var t=u().getInt32(n+0,!0),e=u().getInt32(n+4,!0);if(e)throw _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}delete(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_delete(i,this.__wbg_ptr,t,e);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}insert(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_insert(i,this.__wbg_ptr,t,w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get length(){return a.lorolist_length(this.__wbg_ptr)>>>0}parent(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_parent(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getIdAt(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_getIdAt(i,this.__wbg_ptr,t);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){let t=a.lorolist_toJSON(this.__wbg_ptr);return _(t)}toArray(){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_toArray(o,this.__wbg_ptr);var t=u().getInt32(o+0,!0),e=u().getInt32(o+4,!0),n=u().getInt32(o+8,!0),r=u().getInt32(o+12,!0);if(r)throw _(n);var i=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),i}finally{a.__wbindgen_add_to_stack_pointer(16)}}getCursor(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_getCursor(o,this.__wbg_ptr,t,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return n===0?void 0:Tt.__wrap(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isDeleted(){return a.lorolist_isDeleted(this.__wbg_ptr)!==0}subscribe(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_subscribe(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toContainerTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_toContainerTree(i,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toContainerTreeSlice(t,e,n){try{let s=a.__wbindgen_add_to_stack_pointer(-16);a.lorolist_toContainerTreeSlice(s,this.__wbg_ptr,t,e,K(n)?0:w(n));var r=u().getInt32(s+0,!0),i=u().getInt32(s+4,!0),o=u().getInt32(s+8,!0);if(o)throw _(i);return _(r)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var li=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_loromap_free(t>>>0,1));class St{static __wrap(t){t=t>>>0;let e=Object.create(St.prototype);return e.__wbg_ptr=t,li.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,li.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_loromap_free(t,0)}isAttached(){return a.loromap_isAttached(this.__wbg_ptr)!==0}getAttached(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_getAttached(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getLastEditor(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M,r=a.loromap_getLastEditor(this.__wbg_ptr,e,n);return _(r)}setContainer(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16),s=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),l=M;a.loromap_setContainer(o,this.__wbg_ptr,s,l,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getShallowValue(){let t=a.loromap_getShallowValue(this.__wbg_ptr);return _(t)}ensureMergeableMap(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_ensureMergeableMap(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return St.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}ensureMergeableList(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_ensureMergeableList(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return ee.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}ensureMergeableText(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_ensureMergeableText(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Rt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}ensureMergeableTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_ensureMergeableTree(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return me.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getDeepValueWithID(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_getDeepValueWithID(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getOrCreateContainer(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16),s=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),l=M;a.loromap_getOrCreateContainer(o,this.__wbg_ptr,s,l,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}ensureMergeableCounter(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_ensureMergeableCounter(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Re.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}ensureMergeableMovableList(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_ensureMergeableMovableList(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Le.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get id(){let t=a.loromap_id(this.__wbg_ptr);return _(t)}get(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_get(i,this.__wbg_ptr,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}constructor(){let t=a.loromap_new();return this.__wbg_ptr=t>>>0,li.register(this,this.__wbg_ptr,this),this}keys(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_keys(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),n}finally{a.__wbindgen_add_to_stack_pointer(16)}}kind(){let t=a.loromap_kind(this.__wbg_ptr);return _(t)}get size(){return a.loromap_size(this.__wbg_ptr)>>>0}clear(){try{let n=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_clear(n,this.__wbg_ptr);var t=u().getInt32(n+0,!0),e=u().getInt32(n+4,!0);if(e)throw _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}delete(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16),i=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),o=M;a.loromap_delete(r,this.__wbg_ptr,i,o);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}set(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.loromap_set(i,this.__wbg_ptr,o,s,w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}parent(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_parent(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}values(){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_values(o,this.__wbg_ptr);var t=u().getInt32(o+0,!0),e=u().getInt32(o+4,!0),n=u().getInt32(o+8,!0),r=u().getInt32(o+12,!0);if(r)throw _(n);var i=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),i}finally{a.__wbindgen_add_to_stack_pointer(16)}}entries(){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_entries(o,this.__wbg_ptr);var t=u().getInt32(o+0,!0),e=u().getInt32(o+4,!0),n=u().getInt32(o+8,!0),r=u().getInt32(o+12,!0);if(r)throw _(n);var i=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),i}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){let t=a.loromap_toJSON(this.__wbg_ptr);return _(t)}isDeleted(){return a.loromap_isDeleted(this.__wbg_ptr)!==0}subscribe(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_subscribe(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toContainerTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromap_toContainerTree(i,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var ai=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_loromovablelist_free(t>>>0,1));class Le{static __wrap(t){t=t>>>0;let e=Object.create(Le.prototype);return e.__wbg_ptr=t,ai.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,ai.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_loromovablelist_free(t,0)}isAttached(){return a.loromovablelist_isAttached(this.__wbg_ptr)!==0}getCreatorAt(t){let e=a.loromovablelist_getCreatorAt(this.__wbg_ptr,t);return _(e)}getAttached(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_getAttached(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}setContainer(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_setContainer(o,this.__wbg_ptr,t,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getLastMoverAt(t){let e=a.loromovablelist_getLastMoverAt(this.__wbg_ptr,t);return _(e)}pushContainer(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_pushContainer(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getLastEditorAt(t){let e=a.loromovablelist_getLastEditorAt(this.__wbg_ptr,t);return _(e)}getRangeValue(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_getRangeValue(o,this.__wbg_ptr,t,e);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}insertContainer(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_insertContainer(o,this.__wbg_ptr,t,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getShallowValue(){let t=a.loromovablelist_getShallowValue(this.__wbg_ptr);return _(t)}getDeepValueWithID(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_getDeepValueWithID(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getRangeDeepValueWithID(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_getRangeDeepValueWithID(o,this.__wbg_ptr,t,e);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get id(){let t=a.loromovablelist_id(this.__wbg_ptr);return _(t)}get(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_get(i,this.__wbg_ptr,t);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}move(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_move(i,this.__wbg_ptr,t,e);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}constructor(){let t=a.loromovablelist_new();return this.__wbg_ptr=t>>>0,ai.register(this,this.__wbg_ptr,this),this}pop(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_pop(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}set(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_set(i,this.__wbg_ptr,t,w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}kind(){let t=a.loromovablelist_kind(this.__wbg_ptr);return _(t)}push(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_push(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}clear(){try{let n=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_clear(n,this.__wbg_ptr);var t=u().getInt32(n+0,!0),e=u().getInt32(n+4,!0);if(e)throw _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}delete(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_delete(i,this.__wbg_ptr,t,e);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}insert(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_insert(i,this.__wbg_ptr,t,w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get length(){return a.loromovablelist_length(this.__wbg_ptr)>>>0}parent(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_parent(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){let t=a.loromovablelist_toJSON(this.__wbg_ptr);return _(t)}toArray(){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_toArray(o,this.__wbg_ptr);var t=u().getInt32(o+0,!0),e=u().getInt32(o+4,!0),n=u().getInt32(o+8,!0),r=u().getInt32(o+12,!0);if(r)throw _(n);var i=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),i}finally{a.__wbindgen_add_to_stack_pointer(16)}}getCursor(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_getCursor(o,this.__wbg_ptr,t,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return n===0?void 0:Tt.__wrap(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isDeleted(){return a.loromovablelist_isDeleted(this.__wbg_ptr)!==0}subscribe(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_subscribe(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toContainerTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_toContainerTree(i,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toContainerTreeSlice(t,e,n){try{let s=a.__wbindgen_add_to_stack_pointer(-16);a.loromovablelist_toContainerTreeSlice(s,this.__wbg_ptr,t,e,K(n)?0:w(n));var r=u().getInt32(s+0,!0),i=u().getInt32(s+4,!0),o=u().getInt32(s+8,!0);if(o)throw _(i);return _(r)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var ci=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_lorotext_free(t>>>0,1));class Rt{static __wrap(t){t=t>>>0;let e=Object.create(Rt.prototype);return e.__wbg_ptr=t,ci.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,ci.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_lorotext_free(t,0)}applyDelta(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_applyDelta(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}convertPos(t,e,n){let r=q(e,a.__wbindgen_malloc,a.__wbindgen_realloc),i=M,o=q(n,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M,l=a.lorotext_convertPos(this.__wbg_ptr,t,r,i,o,s);return _(l)}deleteUtf8(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_deleteUtf8(i,this.__wbg_ptr,t,e);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getEditorOf(t){let e=a.lorotext_getEditorOf(this.__wbg_ptr,t);return _(e)}insertUtf8(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(e,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.lorotext_insertUtf8(i,this.__wbg_ptr,t,o,s);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isAttached(){return a.lorotext_isAttached(this.__wbg_ptr)!==0}sliceDelta(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_sliceDelta(o,this.__wbg_ptr,t,e);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getAttached(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_getAttached(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}updateByLine(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.lorotext_updateByLine(i,this.__wbg_ptr,o,s,w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}sliceDeltaUtf8(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_sliceDeltaUtf8(o,this.__wbg_ptr,t,e);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getShallowValue(){let t,e;try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_getShallowValue(i,this.__wbg_ptr);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);return t=n,e=r,it(n,r)}finally{a.__wbindgen_add_to_stack_pointer(16),a.__wbindgen_free(t,e,1)}}getDeepValueWithID(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_getDeepValueWithID(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get id(){let t=a.lorotext_id(this.__wbg_ptr);return _(t)}constructor(){let t=a.lorotext_new();return this.__wbg_ptr=t>>>0,ci.register(this,this.__wbg_ptr,this),this}iter(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_iter(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}kind(){let t=a.lorotext_kind(this.__wbg_ptr);return _(t)}mark(t,e,n){try{let o=a.__wbindgen_add_to_stack_pointer(-16),s=q(e,a.__wbindgen_malloc,a.__wbindgen_realloc),l=M;a.lorotext_mark(o,this.__wbg_ptr,w(t),s,l,w(n));var r=u().getInt32(o+0,!0),i=u().getInt32(o+4,!0);if(i)throw _(r)}finally{a.__wbindgen_add_to_stack_pointer(16)}}push(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16),i=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),o=M;a.lorotext_push(r,this.__wbg_ptr,i,o);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}slice(t,e){let n,r;try{let f=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_slice(f,this.__wbg_ptr,t,e);var i=u().getInt32(f+0,!0),o=u().getInt32(f+4,!0),s=u().getInt32(f+8,!0),l=u().getInt32(f+12,!0),c=i,d=o;if(l)throw c=0,d=0,_(s);return n=c,r=d,it(c,d)}finally{a.__wbindgen_add_to_stack_pointer(16),a.__wbindgen_free(n,r,1)}}delete(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_delete(i,this.__wbg_ptr,t,e);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}insert(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(e,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.lorotext_insert(i,this.__wbg_ptr,t,o,s);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get length(){return a.lorotext_length(this.__wbg_ptr)>>>0}parent(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_parent(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}splice(t,e,n){let r,i;try{let h=a.__wbindgen_add_to_stack_pointer(-16),p=q(n,a.__wbindgen_malloc,a.__wbindgen_realloc),m=M;a.lorotext_splice(h,this.__wbg_ptr,t,e,p,m);var o=u().getInt32(h+0,!0),s=u().getInt32(h+4,!0),l=u().getInt32(h+8,!0),c=u().getInt32(h+12,!0),d=o,f=s;if(c)throw d=0,f=0,_(l);return r=d,i=f,it(d,f)}finally{a.__wbindgen_add_to_stack_pointer(16),a.__wbindgen_free(r,i,1)}}unmark(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(e,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.lorotext_unmark(i,this.__wbg_ptr,w(t),o,s);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}update(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;a.lorotext_update(i,this.__wbg_ptr,o,s,w(e));var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}charAt(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_charAt(i,this.__wbg_ptr,t);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return String.fromCodePoint(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){let t=a.lorotext_toJSON(this.__wbg_ptr);return _(t)}toDelta(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_toDelta(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getCursor(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_getCursor(o,this.__wbg_ptr,t,w(e));var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return n===0?void 0:Tt.__wrap(n)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isDeleted(){return a.lorotext_isDeleted(this.__wbg_ptr)!==0}subscribe(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_subscribe(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toString(){let t,e;try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_toString(i,this.__wbg_ptr);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);return t=n,e=r,it(n,r)}finally{a.__wbindgen_add_to_stack_pointer(16),a.__wbindgen_free(t,e,1)}}toContainerTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotext_toContainerTree(i,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var di=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_lorotree_free(t>>>0,1));class me{static __wrap(t){t=t>>>0;let e=Object.create(me.prototype);return e.__wbg_ptr=t,di.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,di.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_lorotree_free(t,0)}createNode(t,e){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_createNode(o,this.__wbg_ptr,Nt(t),K(e)?4294967297:e>>>0);var n=u().getInt32(o+0,!0),r=u().getInt32(o+4,!0),i=u().getInt32(o+8,!0);if(i)throw _(r);return Zt.__wrap(n)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}isAttached(){return a.lorotree_isAttached(this.__wbg_ptr)!==0}getAttached(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_getAttached(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getNodeByID(t){try{let e=a.lorotree_getNodeByID(this.__wbg_ptr,Nt(t));return e===0?void 0:Zt.__wrap(e)}finally{tt[mt++]=void 0}}isNodeDeleted(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_isNodeDeleted(i,this.__wbg_ptr,Nt(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return e!==0}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}getShallowValue(){let t=a.lorotree_getShallowValue(this.__wbg_ptr);return _(t)}getDeepValueWithID(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_getDeepValueWithID(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}enableFractionalIndex(t){a.lorotree_enableFractionalIndex(this.__wbg_ptr,t)}disableFractionalIndex(){a.lorotree_disableFractionalIndex(this.__wbg_ptr)}isFractionalIndexEnabled(){return a.lorotree_isFractionalIndexEnabled(this.__wbg_ptr)!==0}get id(){let t=a.lorotree_id(this.__wbg_ptr);return _(t)}move(t,e,n){try{let o=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_move(o,this.__wbg_ptr,Nt(t),Nt(e),K(n)?4294967297:n>>>0);var r=u().getInt32(o+0,!0),i=u().getInt32(o+4,!0);if(i)throw _(r)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0,tt[mt++]=void 0}}constructor(){let t=a.lorotree_new();return this.__wbg_ptr=t>>>0,di.register(this,this.__wbg_ptr,this),this}kind(){let t=a.lorotree_kind(this.__wbg_ptr);return _(t)}nodes(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_nodes(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),n}finally{a.__wbindgen_add_to_stack_pointer(16)}}roots(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_roots(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=te(t,e).slice();return a.__wbindgen_free(t,e*4,4),n}finally{a.__wbindgen_add_to_stack_pointer(16)}}delete(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_delete(r,this.__wbg_ptr,Nt(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}parent(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_parent(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){let t=a.lorotree_toJSON(this.__wbg_ptr);return _(t)}has(t){try{return a.lorotree_has(this.__wbg_ptr,Nt(t))!==0}finally{tt[mt++]=void 0}}toArray(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_toArray(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getNodes(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_getNodes(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isDeleted(){return a.lorotree_isDeleted(this.__wbg_ptr)!==0}subscribe(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_subscribe(i,this.__wbg_ptr,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toContainerTree(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotree_toContainerTree(i,this.__wbg_ptr,K(t)?0:w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var Ko=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_lorotreenode_free(t>>>0,1));class Zt{static __wrap(t){t=t>>>0;let e=Object.create(Zt.prototype);return e.__wbg_ptr=t,Ko.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Ko.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_lorotreenode_free(t,0)}__getClassname(){let t,e;try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode___getClassname(i,this.__wbg_ptr);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);return t=n,e=r,it(n,r)}finally{a.__wbindgen_add_to_stack_pointer(16),a.__wbindgen_free(t,e,1)}}creationId(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_creationId(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}isDeleted(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_isDeleted(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return t!==0}finally{a.__wbindgen_add_to_stack_pointer(16)}}moveBefore(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);en(t,Zt),a.lorotreenode_moveBefore(r,this.__wbg_ptr,t.__wbg_ptr);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}createNode(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_createNode(i,this.__wbg_ptr,K(t)?4294967297:t>>>0);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Zt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}getLastMoveId(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_getLastMoveId(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_toJSON(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}fractionalIndex(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_fractionalIndex(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}get id(){let t=a.lorotreenode_id(this.__wbg_ptr);return _(t)}move(t,e){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_move(i,this.__wbg_ptr,Nt(t),K(e)?4294967297:e>>>0);var n=u().getInt32(i+0,!0),r=u().getInt32(i+4,!0);if(r)throw _(n)}finally{a.__wbindgen_add_to_stack_pointer(16),tt[mt++]=void 0}}get data(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_data(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return St.__wrap(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}index(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_index(r,this.__wbg_ptr);var t=u().getFloat64(r+0,!0),e=u().getInt32(r+8,!0),n=u().getInt32(r+12,!0);if(n)throw _(e);return t===4294967297?void 0:t}finally{a.__wbindgen_add_to_stack_pointer(16)}}parent(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.lorotreenode_parent(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return t===0?void 0:Zt.__wrap(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}creator(){let t=a.lorotreenode_creator(this.__wbg_ptr);return _(t)}children(){let t=a.lorotreenode_children(this.__wbg_ptr);return _(t)}moveAfter(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);en(t,Zt),a.lorotreenode_moveAfter(r,this.__wbg_ptr,t.__wbg_ptr);var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}var Yo=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_undomanager_free(t>>>0,1));class nn{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Yo.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_undomanager_free(t,0)}groupStart(){try{let n=a.__wbindgen_add_to_stack_pointer(-16);a.undomanager_groupStart(n,this.__wbg_ptr);var t=u().getInt32(n+0,!0),e=u().getInt32(n+4,!0);if(e)throw _(t)}finally{a.__wbindgen_add_to_stack_pointer(16)}}topRedoValue(){let t=a.undomanager_topRedoValue(this.__wbg_ptr);return _(t)}topUndoValue(){let t=a.undomanager_topUndoValue(this.__wbg_ptr);return _(t)}setMaxUndoSteps(t){a.undomanager_setMaxUndoSteps(this.__wbg_ptr,t)}setMergeInterval(t){a.undomanager_setMergeInterval(this.__wbg_ptr,t)}addExcludeOriginPrefix(t){let e=q(t,a.__wbindgen_malloc,a.__wbindgen_realloc),n=M;a.undomanager_addExcludeOriginPrefix(this.__wbg_ptr,e,n)}constructor(t,e){en(t,Pt);let n=a.undomanager_new(t.__wbg_ptr,w(e));return this.__wbg_ptr=n>>>0,Yo.register(this,this.__wbg_ptr,this),this}peer(){let t=a.undomanager_peer(this.__wbg_ptr);return _(t)}redo(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.undomanager_redo(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return t!==0}finally{a.__wbindgen_add_to_stack_pointer(16)}}undo(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.undomanager_undo(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=u().getInt32(r+8,!0);if(n)throw _(e);return t!==0}finally{a.__wbindgen_add_to_stack_pointer(16)}}clear(){a.undomanager_clear(this.__wbg_ptr)}pause(){a.undomanager_pause(this.__wbg_ptr)}resume(){a.undomanager_resume(this.__wbg_ptr)}canRedo(){return a.undomanager_canRedo(this.__wbg_ptr)!==0}canUndo(){return a.undomanager_canUndo(this.__wbg_ptr)!==0}groupEnd(){a.undomanager_groupEnd(this.__wbg_ptr)}isPaused(){return a.undomanager_isPaused(this.__wbg_ptr)!==0}setOnPop(t){a.undomanager_setOnPop(this.__wbg_ptr,w(t))}clearRedo(){a.undomanager_clearRedo(this.__wbg_ptr)}clearUndo(){a.undomanager_clearUndo(this.__wbg_ptr)}setOnPush(t){a.undomanager_setOnPush(this.__wbg_ptr,w(t))}}var ui=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((t)=>a.__wbg_versionvector_free(t>>>0,1));class Dt{static __wrap(t){t=t>>>0;let e=Object.create(Dt.prototype);return e.__wbg_ptr=t,ui.register(e,e.__wbg_ptr,e),e}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,ui.unregister(this),t}free(){let t=this.__destroy_into_raw();a.__wbg_versionvector_free(t,0)}get(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.versionvector_get(i,this.__wbg_ptr,w(t));var e=u().getFloat64(i+0,!0),n=u().getInt32(i+8,!0),r=u().getInt32(i+12,!0);if(r)throw _(n);return e===4294967297?void 0:e}finally{a.__wbindgen_add_to_stack_pointer(16)}}constructor(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.versionvector_new(i,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return this.__wbg_ptr=e>>>0,ui.register(this,this.__wbg_ptr,this),this}finally{a.__wbindgen_add_to_stack_pointer(16)}}static decode(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16),o=Nn(t,a.__wbindgen_malloc),s=M;a.versionvector_decode(i,o,s);var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Dt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}encode(){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.versionvector_encode(r,this.__wbg_ptr);var t=u().getInt32(r+0,!0),e=u().getInt32(r+4,!0),n=Te(t,e).slice();return a.__wbindgen_free(t,e*1,1),n}finally{a.__wbindgen_add_to_stack_pointer(16)}}length(){return a.versionvector_length(this.__wbg_ptr)>>>0}remove(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.versionvector_remove(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}setEnd(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.versionvector_setEnd(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}compare(t){en(t,Dt);let e=a.versionvector_compare(this.__wbg_ptr,t.__wbg_ptr);return e===4294967297?void 0:e}setLast(t){try{let r=a.__wbindgen_add_to_stack_pointer(-16);a.versionvector_setLast(r,this.__wbg_ptr,w(t));var e=u().getInt32(r+0,!0),n=u().getInt32(r+4,!0);if(n)throw _(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}toJSON(){let t=a.versionvector_toJSON(this.__wbg_ptr);return _(t)}static parseJSON(t){try{let i=a.__wbindgen_add_to_stack_pointer(-16);a.versionvector_parseJSON(i,w(t));var e=u().getInt32(i+0,!0),n=u().getInt32(i+4,!0),r=u().getInt32(i+8,!0);if(r)throw _(n);return Dt.__wrap(e)}finally{a.__wbindgen_add_to_stack_pointer(16)}}}async function Sc(t,e){if(typeof Response==="function"&&t instanceof Response){if(typeof WebAssembly.instantiateStreaming==="function")try{return await WebAssembly.instantiateStreaming(t,e)}catch(r){if(t.headers.get("Content-Type")!="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",r);else throw r}let n=await t.arrayBuffer();return await WebAssembly.instantiate(n,e)}else{let n=await WebAssembly.instantiate(t,e);if(n instanceof WebAssembly.Instance)return{instance:n,module:t};else return n}}function Cc(){let t={};return t.wbg={},t.wbg.__wbg_String_8f0eb39a4a4c2f66=function(e,n){let r=String(x(n)),i=q(r,a.__wbindgen_malloc,a.__wbindgen_realloc),o=M;u().setInt32(e+4,o,!0),u().setInt32(e+0,i,!0)},t.wbg.__wbg_apply_36be6a55257c99bf=function(){return gt(function(e,n,r){let i=x(e).apply(x(n),x(r));return w(i)},arguments)},t.wbg.__wbg_apply_eb9e9b97497f91e4=function(){return gt(function(e,n,r){let i=Reflect.apply(x(e),x(n),x(r));return w(i)},arguments)},t.wbg.__wbg_buffer_609cc3eee51ed158=function(e){let n=x(e).buffer;return w(n)},t.wbg.__wbg_call_672a4d21634d4a24=function(){return gt(function(e,n){let r=x(e).call(x(n));return w(r)},arguments)},t.wbg.__wbg_call_7cccdd69e0791ae2=function(){return gt(function(e,n,r){let i=x(e).call(x(n),x(r));return w(i)},arguments)},t.wbg.__wbg_call_833bed5770ea2041=function(){return gt(function(e,n,r,i){let o=x(e).call(x(n),x(r),x(i));return w(o)},arguments)},t.wbg.__wbg_call_b8adc8b1d0a0d8eb=function(){return gt(function(e,n,r,i,o){let s=x(e).call(x(n),x(r),x(i),x(o));return w(s)},arguments)},t.wbg.__wbg_changemodifier_new=function(e){let n=tn.__wrap(e);return w(n)},t.wbg.__wbg_crypto_574e78ad8b13b65f=function(e){let n=x(e).crypto;return w(n)},t.wbg.__wbg_cursor_new=function(e){let n=Tt.__wrap(e);return w(n)},t.wbg.__wbg_done_769e5ede4b31c67b=function(e){return x(e).done},t.wbg.__wbg_entries_3265d4158b33e5dc=function(e){let n=Object.entries(x(e));return w(n)},t.wbg.__wbg_entries_c8a90a7ed73e84ce=function(e){let n=x(e).entries();return w(n)},t.wbg.__wbg_error_428bae4e36b351e3=function(e,n){console.error(it(e,n))},t.wbg.__wbg_from_2a5d3e218e67aa85=function(e){let n=Array.from(x(e));return w(n)},t.wbg.__wbg_getOwnPropertySymbols_97eebed6fe6e08be=function(e){let n=Object.getOwnPropertySymbols(x(e));return w(n)},t.wbg.__wbg_getRandomValues_b8f5dbd5f3995a9e=function(){return gt(function(e,n){x(e).getRandomValues(x(n))},arguments)},t.wbg.__wbg_get_67b2ba62fc30de12=function(){return gt(function(e,n){let r=Reflect.get(x(e),x(n));return w(r)},arguments)},t.wbg.__wbg_get_b9b93047fe3cf45b=function(e,n){let r=x(e)[n>>>0];return w(r)},t.wbg.__wbg_getindex_5b00c274b05714aa=function(e,n){return x(e)[n>>>0]},t.wbg.__wbg_getwithrefkey_1dc361bd10053bfe=function(e,n){let r=x(e)[x(n)];return w(r)},t.wbg.__wbg_instanceof_ArrayBuffer_e14585432e3737fc=function(e){let n;try{n=x(e)instanceof ArrayBuffer}catch(i){n=!1}return n},t.wbg.__wbg_instanceof_Map_f3469ce2244d2430=function(e){let n;try{n=x(e)instanceof Map}catch(i){n=!1}return n},t.wbg.__wbg_instanceof_Object_7f2dcef8f78644a4=function(e){let n;try{n=x(e)instanceof Object}catch(i){n=!1}return n},t.wbg.__wbg_instanceof_Uint8Array_17156bcf118086a9=function(e){let n;try{n=x(e)instanceof Uint8Array}catch(i){n=!1}return n},t.wbg.__wbg_isArray_a1eab7e0d067391b=function(e){return Array.isArray(x(e))},t.wbg.__wbg_isSafeInteger_343e2beeeece1bb0=function(e){return Number.isSafeInteger(x(e))},t.wbg.__wbg_iterator_9a24c88df860dc65=function(){return w(Symbol.iterator)},t.wbg.__wbg_length_a446193dc22c12f8=function(e){return x(e).length},t.wbg.__wbg_length_e2d2a49132c1b256=function(e){return x(e).length},t.wbg.__wbg_log_0cc1b7768397bcfe=function(e,n,r,i,o,s,l,c){let d,f;try{d=e,f=n,console.log(it(e,n),it(r,i),it(o,s),it(l,c))}finally{a.__wbindgen_free(d,f,1)}},t.wbg.__wbg_log_882f657276590a29=function(e,n){console.log(it(e,n))},t.wbg.__wbg_log_cb9e190acc5753fb=function(e,n){let r,i;try{r=e,i=n,console.log(it(e,n))}finally{a.__wbindgen_free(r,i,1)}},t.wbg.__wbg_lorocounter_new=function(e){let n=Re.__wrap(e);return w(n)},t.wbg.__wbg_lorolist_new=function(e){let n=ee.__wrap(e);return w(n)},t.wbg.__wbg_loromap_new=function(e){let n=St.__wrap(e);return w(n)},t.wbg.__wbg_loromovablelist_new=function(e){let n=Le.__wrap(e);return w(n)},t.wbg.__wbg_lorotext_new=function(e){let n=Rt.__wrap(e);return w(n)},t.wbg.__wbg_lorotree_new=function(e){let n=me.__wrap(e);return w(n)},t.wbg.__wbg_lorotreenode_new=function(e){let n=Zt.__wrap(e);return w(n)},t.wbg.__wbg_mark_7438147ce31e9d4b=function(e,n){performance.mark(it(e,n))},t.wbg.__wbg_measure_fb7825c11612c823=function(){return gt(function(e,n,r,i){let o,s,l,c;try{o=e,s=n,l=r,c=i,performance.measure(it(e,n),it(r,i))}finally{a.__wbindgen_free(o,s,1),a.__wbindgen_free(l,c,1)}},arguments)},t.wbg.__wbg_msCrypto_a61aeb35a24c1329=function(e){let n=x(e).msCrypto;return w(n)},t.wbg.__wbg_new_405e22f390576ce2=function(){return w({})},t.wbg.__wbg_new_5e0be73521bc8c17=function(){return w(new Map)},t.wbg.__wbg_new_78feb108b6472713=function(){return w([])},t.wbg.__wbg_new_a12002a7f91c75be=function(e){let n=new Uint8Array(x(e));return w(n)},t.wbg.__wbg_new_c68d7209be747379=function(e,n){let r=Error(it(e,n));return w(r)},t.wbg.__wbg_newnoargs_105ed471475aaf50=function(e,n){let r=Function(it(e,n));return w(r)},t.wbg.__wbg_newwithbyteoffsetandlength_d97e637ebe145a9a=function(e,n,r){let i=new Uint8Array(x(e),n>>>0,r>>>0);return w(i)},t.wbg.__wbg_newwithlength_a381634e90c276d4=function(e){let n=new Uint8Array(e>>>0);return w(n)},t.wbg.__wbg_newwithlength_c4c419ef0bc8a1f8=function(e){let n=Array(e>>>0);return w(n)},t.wbg.__wbg_next_25feadfc0913fea9=function(e){let n=x(e).next;return w(n)},t.wbg.__wbg_next_6574e1a8a62d1055=function(){return gt(function(e){let n=x(e).next();return w(n)},arguments)},t.wbg.__wbg_node_905d3e251edff8a2=function(e){let n=x(e).node;return w(n)},t.wbg.__wbg_now_2b509d5c9d429404=function(){return Date.now()},t.wbg.__wbg_ownKeys_3930041068756f1f=function(){return gt(function(e){let n=Reflect.ownKeys(x(e));return w(n)},arguments)},t.wbg.__wbg_process_dc0fbacc7c1c06f7=function(e){let n=x(e).process;return w(n)},t.wbg.__wbg_push_737cfc8c1432c2c6=function(e,n){return x(e).push(x(n))},t.wbg.__wbg_randomFillSync_ac0988aba3254290=function(){return gt(function(e,n){x(e).randomFillSync(_(n))},arguments)},t.wbg.__wbg_require_60cc747a6bc5215a=function(){return gt(function(){let e=Nc.require;return w(e)},arguments)},t.wbg.__wbg_resolve_4851785c9c5f573d=function(e){let n=Promise.resolve(x(e));return w(n)},t.wbg.__wbg_set_37837023f3d740e8=function(e,n,r){x(e)[n>>>0]=_(r)},t.wbg.__wbg_set_3f1d0b984ed272ed=function(e,n,r){x(e)[_(n)]=_(r)},t.wbg.__wbg_set_65595bdd868b3009=function(e,n,r){x(e).set(x(n),r>>>0)},t.wbg.__wbg_set_8fc6bf8a5b1071d1=function(e,n,r){let i=x(e).set(x(n),x(r));return w(i)},t.wbg.__wbg_set_bb8cecf6a62b9f46=function(){return gt(function(e,n,r){return Reflect.set(x(e),x(n),x(r))},arguments)},t.wbg.__wbg_stateBinary_bcc49261f5205b9f=function(e,n){let r=Vo(Te(e,n));return w(r)},t.wbg.__wbg_stateCid_ddf7fe40691e2c8f=function(e,n,r){let i=Bo(x(e),n,r);return w(i)},t.wbg.__wbg_stateContainer_8b73508686ecac7f=function(e,n,r){let i=Po(e,x(n),_(r));return w(i)},t.wbg.__wbg_stateIndex_985e23155ddc5679=function(){return gt(function(e,n,r){Wo(x(e),n>>>0,x(r))},arguments)},t.wbg.__wbg_stateOptions_234376ac96321e68=function(){return gt(function(e,n){let r=Ro(_(e),n!==0);return w(r)},arguments)},t.wbg.__wbg_stateRootCid_92a320b321ddff0a=function(e,n,r){let i=zo(it(e,n),r);return w(i)},t.wbg.__wbg_stateSet_9c75457bd566f749=function(){return gt(function(e,n,r){qo(x(e),x(n),x(r))},arguments)},t.wbg.__wbg_stateSlice_4573448d6dfd609f=function(e,n,r){let i=Lo(_(e),n>>>0,r>>>0);return w(i)},t.wbg.__wbg_stateValue_32a9721f28b53795=function(e){let n=Fo(_(e));return w(n)},t.wbg.__wbg_static_accessor_GLOBAL_88a902d13a557d07=function(){let e=typeof global>"u"?null:global;return K(e)?0:w(e)},t.wbg.__wbg_static_accessor_GLOBAL_THIS_56578be7e9f832b0=function(){let e=typeof globalThis>"u"?null:globalThis;return K(e)?0:w(e)},t.wbg.__wbg_static_accessor_SELF_37c5d418e4bf5819=function(){let e=typeof self>"u"?null:self;return K(e)?0:w(e)},t.wbg.__wbg_static_accessor_WINDOW_5de37043a91a9c40=function(){let e=typeof window>"u"?null:window;return K(e)?0:w(e)},t.wbg.__wbg_subarray_aa9065fa9dc5df96=function(e,n,r){let i=x(e).subarray(n>>>0,r>>>0);return w(i)},t.wbg.__wbg_then_44b73946d2fb3e7d=function(e,n){let r=x(e).then(x(n));return w(r)},t.wbg.__wbg_value_cd1ffa7b1ab794f1=function(e){let n=x(e).value;return w(n)},t.wbg.__wbg_versions_c01dfd4722a88165=function(e){let n=x(e).versions;return w(n)},t.wbg.__wbg_versionvector_new=function(e){let n=Dt.__wrap(e);return w(n)},t.wbg.__wbg_warn_5d1fd3858772ca54=function(e,n){console.warn(it(e,n))},t.wbg.__wbindgen_as_number=function(e){return+x(e)},t.wbg.__wbindgen_bigint_from_i64=function(e){return w(e)},t.wbg.__wbindgen_bigint_from_u64=function(e){let n=BigInt.asUintN(64,e);return w(n)},t.wbg.__wbindgen_bigint_get_as_i64=function(e,n){let r=x(n),i=typeof r==="bigint"?r:void 0;u().setBigInt64(e+8,K(i)?BigInt(0):i,!0),u().setInt32(e+0,!K(i),!0)},t.wbg.__wbindgen_boolean_get=function(e){let n=x(e);return typeof n==="boolean"?n?1:0:2},t.wbg.__wbindgen_cb_drop=function(e){let n=_(e).original;if(n.cnt--==1)return n.a=0,!0;return!1},t.wbg.__wbindgen_closure_wrapper295=function(e,n,r){let i=$o(e,n,16,Ic);return w(i)},t.wbg.__wbindgen_closure_wrapper551=function(e,n,r){let i=$o(e,n,16,vc);return w(i)},t.wbg.__wbindgen_debug_string=function(e,n){let r=hi(x(n)),i=q(r,a.__wbindgen_malloc,a.__wbindgen_realloc),o=M;u().setInt32(e+4,o,!0),u().setInt32(e+0,i,!0)},t.wbg.__wbindgen_error_new=function(e,n){let r=Error(it(e,n));return w(r)},t.wbg.__wbindgen_in=function(e,n){return x(e)in x(n)},t.wbg.__wbindgen_is_array=function(e){return Array.isArray(x(e))},t.wbg.__wbindgen_is_bigint=function(e){return typeof x(e)==="bigint"},t.wbg.__wbindgen_is_function=function(e){return typeof x(e)==="function"},t.wbg.__wbindgen_is_null=function(e){return x(e)===null},t.wbg.__wbindgen_is_object=function(e){let n=x(e);return typeof n==="object"&&n!==null},t.wbg.__wbindgen_is_string=function(e){return typeof x(e)==="string"},t.wbg.__wbindgen_is_undefined=function(e){return x(e)===void 0},t.wbg.__wbindgen_jsval_eq=function(e,n){return x(e)===x(n)},t.wbg.__wbindgen_jsval_loose_eq=function(e,n){return x(e)==x(n)},t.wbg.__wbindgen_memory=function(){let e=a.memory;return w(e)},t.wbg.__wbindgen_number_get=function(e,n){let r=x(n),i=typeof r==="number"?r:void 0;u().setFloat64(e+8,K(i)?0:i,!0),u().setInt32(e+0,!K(i),!0)},t.wbg.__wbindgen_number_new=function(e){return w(e)},t.wbg.__wbindgen_object_clone_ref=function(e){let n=x(e);return w(n)},t.wbg.__wbindgen_object_drop_ref=function(e){_(e)},t.wbg.__wbindgen_rethrow=function(e){throw _(e)},t.wbg.__wbindgen_string_get=function(e,n){let r=x(n),i=typeof r==="string"?r:void 0;var o=K(i)?0:q(i,a.__wbindgen_malloc,a.__wbindgen_realloc),s=M;u().setInt32(e+4,s,!0),u().setInt32(e+0,o,!0)},t.wbg.__wbindgen_string_new=function(e,n){let r=it(e,n);return w(r)},t.wbg.__wbindgen_throw=function(e,n){throw Error(it(e,n))},t.wbg.__wbindgen_typeof=function(e){let n=typeof x(e);return w(n)},t}function Oc(t,e){}function Mc(t,e){return a=t.exports,Go.__wbindgen_wasm_module=e,De=null,An=null,a.__wbindgen_start(),a}async function Go(t){if(a!==void 0)return a;if(typeof t<"u")if(Object.getPrototypeOf(t)===Object.prototype)({module_or_path:t}=t);else console.warn("using deprecated parameters for the initialization function; pass a single object instead");if(typeof t>"u")t=new URL("loro_wasm_bg.wasm",import.meta.url);let e=Cc();if(typeof t==="string"||typeof Request==="function"&&t instanceof Request||typeof URL==="function"&&t instanceof URL)t=fetch(t);Oc(e);let{instance:n,module:r}=await Sc(await t,e);return Mc(n,r)}var _i=Go,fi=Symbol("loroContainerId");function Ac(t){let e=t.prototype,n=Object.getOwnPropertyDescriptor(e,"id"),r=n&&n.get,i=Object.getOwnPropertyDescriptor(e,"__destroy_into_raw"),o=i&&i.value;if(!r||!i||!o)throw Error("Unexpected wasm-bindgen container wrapper shape");Object.defineProperty(e,"id",{...n,get(){if(this.__wbg_ptr===0)return r.call(this);let s=this[fi];if(s!==void 0)return s;let l=r.call(this);try{Object.defineProperty(this,fi,{configurable:!0,value:l})}catch{}return l}}),Object.defineProperty(e,"__destroy_into_raw",{...i,value(){try{delete this[fi]}catch{}return o.call(this)}})}function Ec(t){let e=t.prototype,n=Object.getOwnPropertyDescriptor(e,"kind"),r=n&&n.value;if(typeof r!=="function")throw Error("Unexpected wasm-bindgen container wrapper shape");let i;Object.defineProperty(e,"kind",{...n,value(){if(this.__wbg_ptr===0)return r.call(this);if(i===void 0)i=r.call(this);return i}})}for(let t of[St,Rt,ee,me,Le,Re])Ac(t),Ec(t);var Tc=["Map","Text","List","Tree","MovableList","Counter"];function Rc(t){return pi(t)}function ie(t){if(typeof t!=="object"||t==null)return!1;let e=Object.getPrototypeOf(t);if(e==null||typeof e!=="object"||typeof e.kind!=="function")return!1;return Tc.includes(t.kind())}class gi{constructor(t=30000){this.inner=new Dn(t),this.timeout=t}apply(t){this.inner.apply(t),this.startTimerIfNotEmpty()}set(t,e){this.inner.set(t,e),this.startTimerIfNotEmpty()}delete(t){this.inner.delete(t)}get(t){return this.inner.get(t)}getAllStates(){return this.inner.getAllStates()}encode(t){return this.inner.encode(t)}encodeAll(){return this.inner.encodeAll()}keys(){return this.inner.keys()}destroy(){clearInterval(this.timer)}subscribe(t){return this.inner.subscribe(t)}subscribeLocalUpdates(t){return this.inner.subscribeLocalUpdates(t)}startTimerIfNotEmpty(){if(this.inner.isEmpty()||this.timer!=null)return;this.timer=setInterval(()=>{if(this.inner.removeOutdated(),this.inner.isEmpty())clearInterval(this.timer),this.timer=void 0},this.timeout/2)}}Pt.prototype.toJsonWithReplacer=function(t){let e=new Set,n=this,r=(s,l)=>{if(typeof l==="string"){if(Rc(l)&&!e.has(l)){e.add(l);let d=n.getContainerById(l);if(d==null)throw Error(`ContainerID not found: ${l}`);let f=t(s,d);if(f===d){let h=d.getShallowValue();if(typeof h==="object")return i(h);return h}if(ie(f))throw Error("Using new container is not allowed in toJsonWithReplacer");if(typeof f==="object"&&f!=null)return i(f);return f}}if(typeof l==="object"&&l!=null)return i(l);let c=t(s,l);if(ie(c))throw Error("Using new container is not allowed in toJsonWithReplacer");return c},i=(s)=>{if(Array.isArray(s))return s.map((c,d)=>r(d,c)).filter((c)=>c!==void 0);let l={};for(let[c,d]of Object.entries(s)){let f=r(c,d);if(f!==void 0)l[c]=f}return l},o=n.getShallowValue();return i(o)};var Qo=Symbol("loro.callPendingEventsWrapped");function Lc(t,e){let n=Object.getOwnPropertyDescriptor(t,e);if(!n||typeof n.value!=="function")return;let r=n.value;if(r[Qo])return;let i=function(...o){let s;try{return s=r.apply(this,o),s}finally{if(s&&typeof s.then==="function")s.finally(()=>{fr()});else fr()}};i[Qo]=!0,Object.defineProperty(t,e,{...n,value:i})}function mi(t,e){for(let n of e)Lc(t,n)}mi(Pt.prototype,["setDetachedEditing","attach","detach","fork","forkAt","checkoutToLatest","checkout","commit","getCursorPos","revertTo","export","exportJsonUpdates","exportJsonInIdSpan","importJsonUpdates","import","importUpdateBatch","importBatch","travelChangeAncestors","getChangedContainersIn","diff","applyDiff","setPeerId"]);mi(Dn.prototype,["set","delete","apply","removeOutdated"]);mi(nn.prototype,["undo","redo"]);function kt(t){this.content=t}kt.prototype={constructor:kt,find:function(t){for(var e=0;e>1}};kt.from=function(t){if(t instanceof kt)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new kt(e)};var bi=kt;function ds(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let i=t.child(r),o=e.child(r);if(i==o){n+=i.nodeSize;continue}if(!i.sameMarkup(o))return n;if(i.isText&&i.text!=o.text){let s=i.text,l=o.text,c=0;for(;s[c]==l[c];c++)n++;if(c&&c0&&p>0&&d[h-1]==f[p-1])h--,p--,n--,r--;if(h&&p&&h=56320&&t<57344}function hs(t){return t>=55296&&t<56320}class k{constructor(t,e){if(this.content=t,this.size=e||0,e==null)for(let n=0;nt&&n(l,r+s,i||null,o)!==!1&&l.content.size){let d=s+1;l.nodesBetween(Math.max(0,t-d),Math.min(l.content.size,e-d),n,r+d)}s=c}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,e,n,r){let i="",o=!0;return this.nodesBetween(t,e,(s,l)=>{let c=s.isText?s.text.slice(Math.max(t,l)-l,e-l):!s.isLeaf?"":r?typeof r==="function"?r(s):r:s.type.spec.leafText?s.type.spec.leafText(s):"";if(s.isBlock&&(s.isLeaf&&c||s.isTextblock)&&n)if(o)o=!1;else i+=n;i+=c},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let e=this.lastChild,n=t.firstChild,r=this.content.slice(),i=0;if(e.isText&&e.sameMarkup(n))r[r.length-1]=e.withText(e.text+n.text),i=1;for(;it)for(let i=0,o=0;ot){if(oe)if(s.isText)s=s.cut(Math.max(0,t-o),Math.min(s.text.length,e-o));else s=s.cut(Math.max(0,t-o-1),Math.min(s.content.size,e-o-1));n.push(s),r+=s.nodeSize}o=l}return new k(n,r)}cutByIndex(t,e){if(t==e)return k.empty;if(t==0&&e==this.content.length)return this;return new k(this.content.slice(t,e))}replaceChild(t,e){let n=this.content[t];if(n==e)return this;let r=this.content.slice(),i=this.size+e.nodeSize-n.nodeSize;return r[t]=e,new k(r,i)}addToStart(t){return new k([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new k(this.content.concat(t),this.size+t.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let e=0;ethis.size||t<0)throw RangeError(`Position ${t} outside of fragment (${this})`);for(let e=0,n=0;;e++){let r=this.child(e),i=n+r.nodeSize;if(i>=t){if(i==t)return hr(e+1,i);return hr(e,n)}n=i}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map((t)=>t.toJSON()):null}static fromJSON(t,e){if(!e)return k.empty;if(!Array.isArray(e))throw RangeError("Invalid input for Fragment.fromJSON");return k.fromArray(e.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return k.empty;let e,n=0;for(let r=0;rthis.type.rank){if(!e)e=t.slice(0,r);e.push(this),n=!0}if(e)e.push(i)}}if(!e)e=t.slice();if(!n)e.push(this);return e}removeFromSet(t){for(let e=0;en.type.rank-r.type.rank),e}}J.none=[];class ze extends Error{}class I{constructor(t,e,n){this.content=t,this.openStart=e,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,e){let n=_s(this.content,t+this.openStart,e,this.openStart+1,this.openEnd+1);return n&&new I(n,this.openStart,this.openEnd)}removeBetween(t,e){return new I(ps(this.content,t+this.openStart,e+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};if(this.openStart>0)t.openStart=this.openStart;if(this.openEnd>0)t.openEnd=this.openEnd;return t}static fromJSON(t,e){if(!e)return I.empty;let n=e.openStart||0,r=e.openEnd||0;if(typeof n!="number"||typeof r!="number")throw RangeError("Invalid input for Slice.fromJSON");return new I(k.fromJSON(t,e.content),n,r)}static maxOpen(t,e=!0){let n=0,r=0;for(let i=t.firstChild;i&&!i.isLeaf&&(e||!i.type.spec.isolating);i=i.firstChild)n++;for(let i=t.lastChild;i&&!i.isLeaf&&(e||!i.type.spec.isolating);i=i.lastChild)r++;return new I(t,n,r)}}I.empty=new I(k.empty,0,0);function ps(t,e,n){let{index:r,offset:i}=t.findIndex(e),o=t.maybeChild(r),{index:s,offset:l}=t.findIndex(n);if(i==e||o.isText){if(l!=n&&!t.child(s).isText)throw RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=s)throw RangeError("Removing non-flat range");return t.replaceChild(r,o.copy(ps(o.content,e-i-1,n-i-1)))}function _s(t,e,n,r,i,o){let{index:s,offset:l}=t.findIndex(e),c=t.maybeChild(s);if(l==e||c.isText){if(o&&r<=0&&i<=0&&!o.canReplace(s,s,n))return null;return t.cut(0,e).append(n).append(t.cut(e))}let d=_s(c.content,e-l-1,n,s==0?r-1:0,s==t.childCount-1?i-1:0,c);return d&&t.replaceChild(s,c.copy(d))}function Pc(t,e,n){if(n.openStart>t.depth)throw new ze("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new ze("Inconsistent open depths");return gs(t,e,n,0)}function gs(t,e,n,r){let i=t.index(r),o=t.node(r);if(i==e.index(r)&&r=0&&t.isText&&t.sameMarkup(e[n]))e[n]=t.withText(e[n].text+t.text);else e.push(t)}function Rn(t,e,n,r){let i=(e||t).node(n),o=0,s=e?e.index(n):i.childCount;if(t){if(o=t.index(n),t.depth>n)o++;else if(t.textOffset)Pe(t.nodeAfter,r),o++}for(let l=o;li&&yi(t,e,i+1),s=r.depth>i&&yi(n,r,i+1),l=[];if(Rn(null,t,i,l),o&&s&&e.index(i)==n.index(i))ms(o,s),Pe(Be(o,bs(t,e,n,r,i+1)),l);else{if(o)Pe(Be(o,mr(t,e,i+1)),l);if(Rn(e,n,i,l),s)Pe(Be(s,mr(n,r,i+1)),l)}return Rn(r,null,i,l),new k(l)}function mr(t,e,n){let r=[];if(Rn(null,t,n,r),t.depth>n){let i=yi(t,e,n+1);Pe(Be(i,mr(t,e,n+1)),r)}return Rn(e,null,n,r),new k(r)}function Bc(t,e){let n=e.depth-t.openStart,i=e.node(n).copy(t.content);for(let o=n-1;o>=0;o--)i=e.node(o).copy(k.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class Pn{constructor(t,e,n){this.pos=t,this.path=e,this.parentOffset=n,this.depth=e.length/3-1}resolveDepth(t){if(t==null)return this.depth;if(t<0)return this.depth+t;return t}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(t){return this.path[this.resolveDepth(t)*3]}index(t){return this.path[this.resolveDepth(t)*3+1]}indexAfter(t){return t=this.resolveDepth(t),this.index(t)+(t==this.depth&&!this.textOffset?0:1)}start(t){return t=this.resolveDepth(t),t==0?0:this.path[t*3-1]+1}end(t){return t=this.resolveDepth(t),this.start(t)+this.node(t).content.size}before(t){if(t=this.resolveDepth(t),!t)throw RangeError("There is no position before the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]}after(t){if(t=this.resolveDepth(t),!t)throw RangeError("There is no position after the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]+this.path[t*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let t=this.parent,e=this.index(this.depth);if(e==t.childCount)return null;let n=this.pos-this.path[this.path.length-1],r=t.child(e);return n?t.child(e).cut(n):r}get nodeBefore(){let t=this.index(this.depth),e=this.pos-this.path[this.path.length-1];if(e)return this.parent.child(t).cut(0,e);return t==0?null:this.parent.child(t-1)}posAtIndex(t,e){e=this.resolveDepth(e);let n=this.path[e*3],r=e==0?0:this.path[e*3-1]+1;for(let i=0;i0;e--)if(this.start(e)<=t&&this.end(e)>=t)return e;return 0}blockRange(t=this,e){if(t.pos=0;n--)if(t.pos<=this.end(n)&&(!e||e(this.node(n))))return new on(this,t,n);return null}sameParent(t){return this.pos-this.parentOffset==t.pos-t.parentOffset}max(t){return t.pos>this.pos?t:this}min(t){return t.pos=0&&e<=t.content.size))throw RangeError("Position "+e+" out of range");let n=[],r=0,i=e;for(let o=t;;){let{index:s,offset:l}=o.content.findIndex(i),c=i-l;if(n.push(o,s,r+l),!c)break;if(o=o.child(s),o.isText)break;i=c-1,r+=l+1}return new Pn(e,n,i)}static resolveCached(t,e){let n=Zo.get(t);if(n)for(let i=0;it)this.nodesBetween(t,e,(i)=>{if(n.isInSet(i.marks))r=!0;return!r});return r}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let t=this.type.name;if(this.content.size)t+="("+this.content.toStringInner()+")";return ys(this.marks,t)}contentMatchAt(t){let e=this.type.contentMatch.matchFragment(this.content,0,t);if(!e)throw Error("Called contentMatchAt on a node with invalid content");return e}canReplace(t,e,n=k.empty,r=0,i=n.childCount){let o=this.contentMatchAt(t).matchFragment(n,r,i),s=o&&o.matchFragment(this.content,e);if(!s||!s.validEnd)return!1;for(let l=r;le.type.name)}`);this.content.forEach((e)=>e.check())}toJSON(){let t={type:this.type.name};for(let e in this.attrs){t.attrs=this.attrs;break}if(this.content.size)t.content=this.content.toJSON();if(this.marks.length)t.marks=this.marks.map((e)=>e.toJSON());return t}static fromJSON(t,e){if(!e)throw RangeError("Invalid input for Node.fromJSON");let n=void 0;if(e.marks){if(!Array.isArray(e.marks))throw RangeError("Invalid mark data for Node.fromJSON");n=e.marks.map(t.markFromJSON)}if(e.type=="text"){if(typeof e.text!="string")throw RangeError("Invalid text node in JSON");return t.text(e.text,n)}let r=k.fromJSON(t,e.content);return t.nodeType(e.type).create(e.attrs,r,n)}}qt.prototype.text=void 0;class br extends qt{constructor(t,e,n,r){super(t,e,null,r);if(!n)throw RangeError("Empty text nodes are not allowed");this.text=n}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);return ys(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(t,e){return this.text.slice(t,e)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new br(this.type,this.attrs,this.text,t)}withText(t){if(t==this.text)return this;return new br(this.type,this.attrs,t,this.marks)}cut(t=0,e=this.text.length){if(t==0&&e==this.text.length)return this;return this.withText(this.text.slice(t,e))}eq(t){return this.sameMarkup(t)&&this.text==t.text}toJSON(){let t=super.toJSON();return t.text=this.text,t}}function ys(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}function ts(t,e,n,r){for(let i in e)if(!(i in t))throw RangeError(`Unsupported attribute ${i} for ${n} of type ${r}`);for(let i in t)if(t[i].validate)t[i].validate(e[i])}class Fe{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,e){let n=new ks(t,e);if(n.next==null)return Fe.empty;let r=xs(n);if(n.next)n.err("Unexpected trailing text");let i=jc(Jc(r));return Hc(i,n),i}matchType(t){for(let e=0;ec.createAndFill()));for(let c=0;c=this.next.length)throw RangeError(`There's no ${t}th edge in this content match`);return this.next[t]}toString(){let t=[];function e(n){t.push(n);for(let r=0;r{let i=r+(n.validEnd?"*":" ")+" ";for(let o=0;o"+t.indexOf(n.next[o].next);return i}).join(` -`)}}Fe.empty=new Fe(!0);class ks{constructor(t,e){if(this.string=t,this.nodeTypes=e,this.inline=null,this.pos=0,this.tokens=t.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]=="")this.tokens.pop();if(this.tokens[0]=="")this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(t){return this.next==t&&(this.pos++||!0)}err(t){throw SyntaxError(t+" (in content expression '"+this.string+"')")}}function xs(t){let e=[];do e.push(Vc(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function Vc(t){let e=[];do e.push(Wc(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function Wc(t){let e=$c(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else if(t.eat("{"))e=qc(t,e);else break;return e}function es(t){if(/\D/.test(t.next))t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function qc(t,e){let n=es(t),r=n;if(t.eat(","))if(t.next!="}")r=es(t);else r=-1;if(!t.eat("}"))t.err("Unclosed braced range");return{type:"range",min:n,max:r,expr:e}}function Uc(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let i=[];for(let o in n){let s=n[o];if(s.isInGroup(e))i.push(s)}if(i.length==0)t.err("No node type or group '"+e+"' found");return i}function $c(t){if(t.eat("(")){let e=xs(t);if(!t.eat(")"))t.err("Missing closing paren");return e}else if(!/\W/.test(t.next)){let e=Uc(t,t.next).map((n)=>{if(t.inline==null)t.inline=n.isInline;else if(t.inline!=n.isInline)t.err("Mixing inline and block content");return{type:"name",value:n}});return t.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}else t.err("Unexpected token '"+t.next+"'")}function Jc(t){let e=[[]];return i(o(t,0),n()),e;function n(){return e.push([])-1}function r(s,l,c){let d={term:c,to:l};return e[s].push(d),d}function i(s,l){s.forEach((c)=>c.to=l)}function o(s,l){if(s.type=="choice")return s.exprs.reduce((c,d)=>c.concat(o(d,l)),[]);else if(s.type=="seq")for(let c=0;;c++){let d=o(s.exprs[c],l);if(c==s.exprs.length-1)return d;i(d,l=n())}else if(s.type=="star"){let c=n();return r(l,c),i(o(s.expr,c),c),[r(c)]}else if(s.type=="plus"){let c=n();return i(o(s.expr,l),c),i(o(s.expr,c),c),[r(c)]}else if(s.type=="opt")return[r(l)].concat(o(s.expr,l));else if(s.type=="range"){let c=l;for(let d=0;d{t[s].forEach(({term:l,to:c})=>{if(!l)return;let d;for(let f=0;f{if(!d)i.push([l,d=[]]);if(d.indexOf(f)==-1)d.push(f)})})});let o=e[r.join(",")]=new Fe(r.indexOf(t.length-1)>-1);for(let s=0;s-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let t in this.attrs)if(this.attrs[t].isRequired)return!0;return!1}compatibleContent(t){return this==t||this.contentMatch.compatible(t.contentMatch)}computeAttrs(t){if(!t&&this.defaultAttrs)return this.defaultAttrs;else return Ss(this.attrs,t)}create(t=null,e,n){if(this.isText)throw Error("NodeType.create can't construct text nodes");return new qt(this,this.computeAttrs(t),k.from(e),J.setFrom(n))}createChecked(t=null,e,n){return e=k.from(e),this.checkContent(e),new qt(this,this.computeAttrs(t),e,J.setFrom(n))}createAndFill(t=null,e,n){if(t=this.computeAttrs(t),e=k.from(e),e.size){let o=this.contentMatch.fillBefore(e);if(!o)return null;e=o.append(e)}let r=this.contentMatch.matchFragment(e),i=r&&r.fillBefore(k.empty,!0);if(!i)return null;return new qt(this,t,e.append(i),J.setFrom(n))}validContent(t){let e=this.contentMatch.matchFragment(t);if(!e||!e.validEnd)return!1;for(let n=0;n-1}allowsMarks(t){if(this.markSet==null)return!0;for(let e=0;en[i]=new wr(i,e,o));let r=e.spec.topNode||"doc";if(!n[r])throw RangeError("Schema is missing its top node type ('"+r+"')");if(!n.text)throw RangeError("Every schema needs a 'text' type");for(let i in n.text.attrs)throw RangeError("The text node type should not have attributes");return n}}function Kc(t,e,n){let r=n.split("|");return(i)=>{let o=i===null?"null":typeof i;if(r.indexOf(o)<0)throw RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${o}`)}}class Os{constructor(t,e,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,"default"),this.default=n.default,this.validate=typeof n.validate=="string"?Kc(t,e,n.validate):n.validate}get isRequired(){return!this.hasDefault}}class zn{constructor(t,e,n,r){this.name=t,this.rank=e,this.schema=n,this.spec=r,this.attrs=Cs(t,r.attrs),this.excluded=null;let i=vs(this.attrs);this.instance=i?new J(this,i):null}create(t=null){if(!t&&this.instance)return this.instance;return new J(this,Ss(this.attrs,t))}static compile(t,e){let n=Object.create(null),r=0;return t.forEach((i,o)=>n[i]=new zn(i,r++,e,o)),n}removeFromSet(t){for(var e=0;e-1}}class sn{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let e=this.spec={};for(let r in t)e[r]=t[r];e.nodes=bi.from(t.nodes),e.marks=bi.from(t.marks||{}),this.nodes=wr.compile(this.spec.nodes,this),this.marks=zn.compile(this.spec.marks,this);let n=Object.create(null);for(let r in this.nodes){if(r in this.marks)throw RangeError(r+" can not be both a node and a mark");let i=this.nodes[r],o=i.spec.content||"",s=i.spec.marks;if(i.contentMatch=n[o]||(n[o]=Fe.parse(o,this.nodes)),i.inlineContent=i.contentMatch.inlineContent,i.spec.linebreakReplacement){if(this.linebreakReplacement)throw RangeError("Multiple linebreak nodes defined");if(!i.isInline||!i.isLeaf)throw RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=i}i.markSet=s=="_"?null:s?rs(this,s.split(" ")):s==""||!i.inlineContent?[]:null}for(let r in this.marks){let i=this.marks[r],o=i.spec.excludes;i.excluded=o==null?[i]:o==""?[]:rs(this,o.split(" "))}this.nodeFromJSON=(r)=>qt.fromJSON(this,r),this.markFromJSON=(r)=>J.fromJSON(this,r),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(t,e=null,n,r){if(typeof t=="string")t=this.nodeType(t);else if(!(t instanceof wr))throw RangeError("Invalid node type: "+t);else if(t.schema!=this)throw RangeError("Node type from different schema used ("+t.name+")");return t.createChecked(e,n,r)}text(t,e){let n=this.nodes.text;return new br(n,n.defaultAttrs,t,J.setFrom(e))}mark(t,e){if(typeof t=="string")t=this.marks[t];return t.create(e)}nodeType(t){let e=this.nodes[t];if(!e)throw RangeError("Unknown node type: "+t);return e}}function rs(t,e){let n=[];for(let r=0;r-1)n.push(s=c)}if(!s)throw SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}function Yc(t){return t.tag!=null}function Xc(t){return t.style!=null}class rn{constructor(t,e){this.schema=t,this.rules=e,this.tags=[],this.styles=[];let n=this.matchedStyles=[];e.forEach((r)=>{if(Yc(r))this.tags.push(r);else if(Xc(r)){let i=/[^=]*/.exec(r.style)[0];if(n.indexOf(i)<0)n.push(i);this.styles.push(r)}}),this.normalizeLists=!this.tags.some((r)=>{if(!/^(ul|ol)\b/.test(r.tag)||!r.node)return!1;let i=t.nodes[r.node];return i.contentMatch.matchType(i)})}parse(t,e={}){let n=new xi(this,e,!1);return n.addAll(t,J.none,e.from,e.to),n.finish()}parseSlice(t,e={}){let n=new xi(this,e,!0);return n.addAll(t,J.none,e.from,e.to),I.maxOpen(n.finish())}matchTag(t,e,n){for(let r=n?this.tags.indexOf(n)+1:0;rt.length&&(s.charCodeAt(t.length)!=61||s.slice(t.length+1)!=e))continue;if(o.getAttrs){let l=o.getAttrs(e);if(l===!1)continue;o.attrs=l||void 0}return o}}static schemaRules(t){let e=[];function n(r){let i=r.priority==null?50:r.priority,o=0;for(;o{if(n(o=ss(o)),!(o.mark||o.ignore||o.clearMark))o.mark=r})}for(let r in t.nodes){let i=t.nodes[r].spec.parseDOM;if(i)i.forEach((o)=>{if(n(o=ss(o)),!(o.node||o.ignore||o.mark))o.node=r})}return e}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new rn(t,rn.schemaRules(t)))}}var Ms={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Gc={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},As={ol:!0,ul:!0},Bn=1,ki=2,Ln=4;function is(t,e,n){if(e!=null)return(e?Bn:0)|(e==="full"?ki:0);return t&&t.whitespace=="pre"?Bn|ki:n&~Ln}class Tn{constructor(t,e,n,r,i,o){this.type=t,this.attrs=e,this.marks=n,this.solid=r,this.options=o,this.content=[],this.activeMarks=J.none,this.match=i||(o&Ln?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let e=this.type.contentMatch.fillBefore(k.from(t));if(e)this.match=this.type.contentMatch.matchFragment(e);else{let n=this.type.contentMatch,r;if(r=n.findWrapping(t.type))return this.match=n,r;else return null}}return this.match.findWrapping(t.type)}finish(t){if(!(this.options&Bn)){let n=this.content[this.content.length-1],r;if(n&&n.isText&&(r=/[ \t\r\n\u000c]+$/.exec(n.text))){let i=n;if(n.text.length==r[0].length)this.content.pop();else this.content[this.content.length-1]=i.withText(i.text.slice(0,i.text.length-r[0].length))}}let e=k.from(this.content);if(!t&&this.match)e=e.append(this.match.fillBefore(k.empty,!0));return this.type?this.type.create(this.attrs,e,this.marks):e}inlineContext(t){if(this.type)return this.type.inlineContent;if(this.content.length)return this.content[0].isInline;return t.parentNode&&!Ms.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class xi{constructor(t,e,n){this.parser=t,this.options=e,this.isOpen=n,this.open=0,this.localPreserveWS=!1;let r=e.topNode,i,o=is(null,e.preserveWhitespace,0)|(n?Ln:0);if(r)i=new Tn(r.type,r.attrs,J.none,!0,e.topMatch||r.type.contentMatch,o);else if(n)i=new Tn(null,null,J.none,!0,null,o);else i=new Tn(t.schema.topNodeType,null,J.none,!0,null,o);this.nodes=[i],this.find=e.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(t,e){if(t.nodeType==3)this.addTextNode(t,e);else if(t.nodeType==1)this.addElement(t,e)}addTextNode(t,e){let n=t.nodeValue,r=this.top,i=r.options&ki?"full":this.localPreserveWS||(r.options&Bn)>0,{schema:o}=this.parser;if(i==="full"||r.inlineContext(t)||/[^ \t\r\n\u000c]/.test(n)){if(!i){if(n=n.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(n)&&this.open==this.nodes.length-1){let s=r.content[r.content.length-1],l=t.previousSibling;if(!s||l&&l.nodeName=="BR"||s.isText&&/[ \t\r\n\u000c]$/.test(s.text))n=n.slice(1)}}else if(i==="full")n=n.replace(/\r\n?/g,` -`);else if(o.linebreakReplacement&&/[\r\n]/.test(n)&&this.top.findWrapping(o.linebreakReplacement.create())){let s=n.split(/\r?\n|\r/);for(let l=0;l!l.clearMark(c));else e=e.concat(this.parser.schema.marks[l.mark].create(l.attrs));if(l.consuming===!1)s=l;else break}}return e}addElementByRule(t,e,n,r){let i,o;if(e.node){if(o=this.parser.schema.nodes[e.node],!o.isLeaf){let l=this.enter(o,e.attrs||null,n,e.preserveWhitespace);if(l)i=!0,n=l}else if(!this.insertNode(o.create(e.attrs),n,t.nodeName=="BR"))this.leafFallback(t,n)}else{let l=this.parser.schema.marks[e.mark];n=n.concat(l.create(e.attrs))}let s=this.top;if(o&&o.isLeaf)this.findInside(t);else if(r)this.addElement(t,n,r);else if(e.getContent)this.findInside(t),e.getContent(t,this.parser.schema).forEach((l)=>this.insertNode(l,n,!1));else{let l=t;if(typeof e.contentElement=="string")l=t.querySelector(e.contentElement);else if(typeof e.contentElement=="function")l=e.contentElement(t);else if(e.contentElement)l=e.contentElement;this.findAround(t,l,!0),this.addAll(l,n),this.findAround(t,l,!1)}if(i&&this.sync(s))this.open--}addAll(t,e,n,r){let i=n||0;for(let o=n?t.childNodes[n]:t.firstChild,s=r==null?null:t.childNodes[r];o!=s;o=o.nextSibling,++i)this.findAtPoint(t,i),this.addDOM(o,e);this.findAtPoint(t,i)}findPlace(t,e,n){let r,i;for(let o=this.open,s=0;o>=0;o--){let l=this.nodes[o],c=l.findWrapping(t);if(c&&(!r||r.length>c.length+s)){if(r=c,i=l,!c.length)break}if(l.solid){if(n)break;s+=2}}if(!r)return null;this.sync(i);for(let o=0;o{if(o.type?o.type.allowsMarkType(c.type):ls(c.type,t))return l=c.addToSet(l),!1;return!0}),this.nodes.push(new Tn(t,e,l,r,null,s)),this.open++,n}closeExtra(t=!1){let e=this.nodes.length-1;if(e>this.open){for(;e>this.open;e--)this.nodes[e-1].content.push(this.nodes[e].finish(t));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(t){for(let e=this.open;e>=0;e--)if(this.nodes[e]==t)return this.open=e,!0;else if(this.localPreserveWS)this.nodes[e].options|=Bn;return!1}get currentPos(){this.closeExtra();let t=0;for(let e=this.open;e>=0;e--){let n=this.nodes[e].content;for(let r=n.length-1;r>=0;r--)t+=n[r].nodeSize;if(e)t++}return t}findAtPoint(t,e){if(this.find){for(let n=0;n-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let e=t.split("/"),n=this.options.context,r=!this.isOpen&&(!n||n.parent.type==this.nodes[0].type),i=-(n?n.depth+1:0)+(r?0:1),o=(s,l)=>{for(;s>=0;s--){let c=e[s];if(c==""){if(s==e.length-1||s==0)continue;for(;l>=i;l--)if(o(s-1,l))return!0;return!1}else{let d=l>0||l==0&&r?this.nodes[l].type:n&&l>=i?n.node(l-i).type:null;if(!d||d.name!=c&&!d.isInGroup(c))return!1;l--}}return!0};return o(e.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let e=t.depth;e>=0;e--){let n=t.node(e).contentMatchAt(t.indexAfter(e)).defaultType;if(n&&n.isTextblock&&n.defaultAttrs)return n}for(let e in this.parser.schema.nodes){let n=this.parser.schema.nodes[e];if(n.isTextblock&&n.defaultAttrs)return n}}}function Qc(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;if(r&&As.hasOwnProperty(r)&&n)n.appendChild(e),e=n;else if(r=="li")n=e;else if(r)n=null}}function Zc(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function ss(t){let e={};for(let n in t)e[n]=t[n];return e}function ls(t,e){let n=e.schema.nodes;for(let r in n){let i=n[r];if(!i.allowsMarkType(t))continue;let o=[],s=(l)=>{o.push(l);for(let c=0;c{if(i.length||o.marks.length){let s=0,l=0;while(s=0;r--){let i=this.serializeMark(t.marks[r],t.isInline,e);if(i)(i.contentDOM||i.dom).appendChild(n),n=i.dom}return n}serializeMark(t,e,n={}){let r=this.marks[t.type.name];return r&&_r(pr(n),r(t,e),null,t.attrs)}static renderSpec(t,e,n=null,r){if(typeof e=="string")return{dom:t.createTextNode(e)};return _r(t,e,n,r)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new Ve(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let e=as(t.nodes);if(!e.text)e.text=(n)=>n.text;return e}static marksFromSchema(t){return as(t.marks)}}function as(t){let e={};for(let n in t){let r=t[n].spec.toDOM;if(r)e[n]=r}return e}function pr(t){return t.document||window.document}var cs=new WeakMap;function td(t){let e=cs.get(t);if(e===void 0)cs.set(t,e=ed(t));return e}function ed(t){let e=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string"){if(!e)e=[];e.push(r)}else for(let i=0;i-1)throw RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let s=i.indexOf(" ");if(s>0)n=i.slice(0,s),i=i.slice(s+1);let l,c=n?t.createElementNS(n,i):t.createElement(i),d=e[1],f=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){f=2;for(let h in d)if(d[h]!=null){let p=h.indexOf(" ");if(p>0)c.setAttributeNS(h.slice(0,p),h.slice(p+1),d[h]);else if(h=="style"&&c.style)c.style.cssText=d[h];else c.setAttribute(h,d[h])}}for(let h=f;hf)throw RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else if(typeof p=="string")c.appendChild(t.createTextNode(p));else{let{dom:m,contentDOM:g}=_r(t,p,n,r);if(c.appendChild(m),g){if(l)throw RangeError("Multiple content holes");l=g}}}return{dom:c,contentDOM:l}}var Rs=65535,Ls=Math.pow(2,16);function nd(t,e){return t+e*Ls}function Es(t){return t&Rs}function rd(t){return(t-(t&Rs))/Ls}var Ps=1,Bs=2,yr=4,zs=8;class kr{constructor(t,e,n){this.pos=t,this.delInfo=e,this.recover=n}get deleted(){return(this.delInfo&zs)>0}get deletedBefore(){return(this.delInfo&(Ps|yr))>0}get deletedAfter(){return(this.delInfo&(Bs|yr))>0}get deletedAcross(){return(this.delInfo&yr)>0}}class Bt{constructor(t,e=!1){if(this.ranges=t,this.inverted=e,!t.length&&Bt.empty)return Bt.empty}recover(t){let e=0,n=Es(t);if(!this.inverted)for(let r=0;rt)break;let c=this.ranges[s+i],d=this.ranges[s+o],f=l+c;if(t<=f){let h=!c?e:t==l?-1:t==f?1:e,p=l+r+(h<0?0:d);if(n)return p;let m=t==(e<0?l:f)?null:nd(s/3,t-l),g=0;if(c){if(g|=t==l?Bs:t==f?Ps:yr,e<0?t!=l:t!=f)g|=zs}return new kr(p,g,m)}r+=d-c}return n?t+r:new kr(t+r,0,null)}touches(t,e){let n=0,r=Es(e),i=this.inverted?2:1,o=this.inverted?1:2;for(let s=0;st)break;let c=this.ranges[s+i],d=l+c;if(t<=d&&s==r*3)return!0;n+=this.ranges[s+o]-c}return!1}forEach(t){let e=this.inverted?2:1,n=this.inverted?1:2;for(let r=0,i=0;r=0;e--){let r=t.getMirror(e);this.appendMap(t._maps[e].invert(),r!=null&&r>e?n-r-1:void 0)}}invert(){let t=new xr;return t.appendMappingInverted(this),t}map(t,e=1){if(this.mirror)return this._map(t,e,!0);for(let n=this.from;ni&&l{if(!o.isAtom||!s.type.allowsMarkType(this.mark.type))return o;return o.mark(this.mark.addToSet(o.marks))},r),e.openStart,e.openEnd);return ct.fromReplace(t,this.from,this.to,i)}invert(t){let e=[];return t.nodesBetween(this.from,this.to,(n,r)=>{if(n.isInline&&n.isAtom){let i=this.mark.addToSet(n.marks);if(!J.sameSet(i,n.marks)){let o=Math.max(this.from,r),s=Math.min(this.to,r+n.nodeSize);Ir(se,o,s,this.mark,e);for(let l of n.marks)if(!l.isInSet(i))Ir(oe,o,s,l,e)}}}),e.length==1?e[0]:new We(e)}map(t){let e=t.map(this.from,1),n=t.map(this.to,-1);if(e>=n)return null;return new oe(e,n,this.mark)}merge(t){if(t instanceof oe&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from)return new oe(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark);return null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,e){if(typeof e.from!="number"||typeof e.to!="number")throw RangeError("Invalid input for AddMarkStep.fromJSON");return new oe(e.from,e.to,t.markFromJSON(e.mark))}}ht.jsonID("addMark",oe);class se extends ht{constructor(t,e,n){super();this.from=t,this.to=e,this.mark=n}apply(t){let e=t.slice(this.from,this.to),n=new I(Ci(e.content,(r)=>r.mark(this.mark.removeFromSet(r.marks)),t),e.openStart,e.openEnd);return ct.fromReplace(t,this.from,this.to,n)}invert(t){let e=[];return t.nodesBetween(this.from,this.to,(n,r)=>{if(n.isInline&&n.isAtom&&this.mark.isInSet(n.marks))Ir(oe,Math.max(this.from,r),Math.min(this.to,r+n.nodeSize),this.mark,e)}),e.length==1?e[0]:new We(e)}map(t){let e=t.map(this.from,1),n=t.map(this.to,-1);if(e>=n)return null;return new se(e,n,this.mark)}merge(t){if(t instanceof se&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from)return new se(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark);return null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,e){if(typeof e.from!="number"||typeof e.to!="number")throw RangeError("Invalid input for RemoveMarkStep.fromJSON");return new se(e.from,e.to,t.markFromJSON(e.mark))}}ht.jsonID("removeMark",se);function Ir(t,e,n,r,i){let o=i.length?i[i.length-1]:null;if(o&&o instanceof t&&o.to==e&&o.mark.eq(r))i[i.length-1]=new t(o.from,n,r);else i.push(new t(e,n,r))}class We extends ht{constructor(t){super();this.steps=t}apply(t){for(let e of this.steps){let n=e.apply(t);if(!n.doc)return n;t=n.doc}return new ct(t,null)}invert(t){return new We(this.steps.map((e)=>e.invert(t)))}map(t){let e=[];for(let n of this.steps){let r=n.map(t);if(r)e.push(r)}return e.length?new We(e):null}toJSON(){return{stepType:"markSet",steps:this.steps.map((t)=>t.toJSON())}}static fromJSON(t,e){if(!Array.isArray(e.steps)||!e.steps.every((n)=>n.stepType=="addMark"||n.stepType=="removeMark"))throw RangeError("Invalid JSON for MarkSetStep");return new We(e.steps.map((n)=>ht.fromJSON(t,n)))}}ht.jsonID("markSet",We);class be extends ht{constructor(t,e){super();this.pos=t,this.mark=e}apply(t){let e=t.nodeAt(this.pos);if(!e)return ct.fail("No node at mark step's position");let n=e.type.create(e.attrs,null,this.mark.addToSet(e.marks));return ct.fromReplace(t,this.pos,this.pos+1,new I(k.from(n),0,e.isLeaf?0:1))}invert(t){let e=t.nodeAt(this.pos);if(e){let n=this.mark.addToSet(e.marks);if(n.length==e.marks.length){for(let r=0;rn.pos)return null;return new ft(e.pos,n.pos,r,i,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};if(this.slice.size)t.slice=this.slice.toJSON();if(this.structure)t.structure=!0;return t}static fromJSON(t,e){if(typeof e.from!="number"||typeof e.to!="number"||typeof e.gapFrom!="number"||typeof e.gapTo!="number"||typeof e.insert!="number")throw RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new ft(e.from,e.to,e.gapFrom,e.gapTo,I.fromJSON(t,e.slice),e.insert,!!e.structure)}}ht.jsonID("replaceAround",ft);function Si(t,e,n){let r=t.resolve(e),i=n-e,o=r.depth;while(i>0&&o>0&&r.indexAfter(o)==r.node(o).childCount)o--,i--;if(i>0){let s=r.node(o).maybeChild(r.indexAfter(o));while(i>0){if(!s||s.isLeaf)return!0;s=s.firstChild,i--}}return!1}function id(t,e,n,r){let i=[];t.doc.nodesBetween(e,n,(o,s,l)=>{if(!o.isInline)return;let c=o.marks;if(!r.isInSet(c)&&l.type.allowsMarkType(r.type)){let d=Math.max(s,e),f=Math.min(s+o.nodeSize,n);Ir(oe,d,f,r,i)}}),i.forEach((o)=>t.step(o))}function od(t,e,n,r){let i=[],o=0;t.doc.nodesBetween(e,n,(s,l)=>{if(!s.isInline||!s.isAtom)return;o++;let c=null;if(r instanceof zn){let d=s.marks,f;while(f=r.isInSet(d))(c||(c=[])).push(f),d=f.removeFromSet(d)}else if(r){if(r.isInSet(s.marks))c=[r]}else c=s.marks;if(c&&c.length){let d=Math.min(l+s.nodeSize,n);for(let f=0;ft.step(new se(s.from,s.to,s.style)))}function Oi(t,e,n,r=n.contentMatch,i=!0){let o=t.doc.nodeAt(e),s=[],l=e+1;for(let c=0;c=0;c--)t.step(s[c])}function sd(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function Ue(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,i=0,o=0;;--r){let s=t.$from.node(r),l=t.$from.index(r)+i,c=t.$to.indexAfter(r)-o;if(rn;g--)if(b||r.index(g)>0)b=!0,f=k.from(r.node(g).copy(f)),h++;else c--;let p=k.empty,m=0;for(let g=o,b=!1;g>n;g--)if(b||i.after(g+1)=0;s--){if(r.size){let l=n[s].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=k.from(n[s].type.create(n[s].attrs,r))}let{start:i,end:o}=e;t.step(new ft(i,o,i,o,new I(r,0,0),n.length,!0))}function ud(t,e,n,r,i){if(!r.isTextblock)throw RangeError("Type given to setBlockType should be a textblock");let o=t.steps.length;t.doc.nodesBetween(e,n,(s,l)=>{let c=typeof i=="function"?i(s):i;if(s.isTextblock&&!s.hasMarkup(r,c)&&fd(t.doc,t.mapping.slice(o).map(l),r)){let d=null;if(r.schema.linebreakReplacement){let m=r.whitespace=="pre",g=!!r.contentMatch.matchType(r.schema.linebreakReplacement);if(m&&!g)d=!1;else if(!m&&g)d=!0}if(d===!1)Vs(t,s,l,o);Oi(t,t.mapping.slice(o).map(l,1),r,void 0,d===null);let f=t.mapping.slice(o),h=f.map(l,1),p=f.map(l+s.nodeSize,1);if(t.step(new ft(h,p,h+1,p-1,new I(k.from(r.create(c,null,s.marks)),0,0),1,!0)),d===!0)Fs(t,s,l,o);return!1}})}function Fs(t,e,n,r){e.forEach((i,o)=>{if(i.isText){let s,l=/\r?\n|\r/g;while(s=l.exec(i.text)){let c=t.mapping.slice(r).map(n+1+o+s.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function Vs(t,e,n,r){e.forEach((i,o)=>{if(i.type==i.type.schema.linebreakReplacement){let s=t.mapping.slice(r).map(n+1+o);t.replaceWith(s,s+1,e.type.schema.text(` -`))}})}function fd(t,e,n){let r=t.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,n)}function hd(t,e,n,r,i){let o=t.doc.nodeAt(e);if(!o)throw RangeError("No node at given position");if(!n)n=o.type;let s=n.create(r,null,i||o.marks);if(o.isLeaf)return t.replaceWith(e,e+o.nodeSize,s);if(!n.validContent(o.content))throw RangeError("Invalid content for node type "+n.name);t.step(new ft(e,e+o.nodeSize,e+1,e+o.nodeSize-1,new I(k.from(s),0,0),1,!0))}function we(t,e,n=1,r){let i=t.resolve(e),o=i.depth-n,s=r&&r[r.length-1]||i.parent;if(o<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!s.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let d=i.depth-1,f=n-2;d>o;d--,f--){let h=i.node(d),p=i.index(d);if(h.type.spec.isolating)return!1;let m=h.content.cutByIndex(p,h.childCount),g=r&&r[f+1];if(g)m=m.replaceChild(0,g.type.create(g.attrs));let b=r&&r[f]||h;if(!h.canReplace(p+1,h.childCount)||!b.type.validContent(m))return!1}let l=i.indexAfter(o),c=r&&r[0];return i.node(o).canReplaceWith(l,l,c?c.type:i.node(o+1).type)}function pd(t,e,n=1,r){let i=t.doc.resolve(e),o=k.empty,s=k.empty;for(let l=i.depth,c=i.depth-n,d=n-1;l>c;l--,d--){o=k.from(i.node(l).copy(o));let f=r&&r[d];s=k.from(f?f.type.create(f.attrs,s):i.node(l).copy(s))}t.step(new ut(e,e,new I(o.append(s),n,n),!0))}function $e(t,e){let n=t.resolve(e),r=n.index();return gd(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function _d(t,e){if(!e.content.size)t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:r}=t.type.schema;for(let i=0;i=0;i--){let o=r.index(i);if(r.node(i).canReplaceWith(o,o,n))return r.before(i+1);if(o>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let o=r.indexAfter(i);if(r.node(i).canReplaceWith(o,o,n))return r.after(i+1);if(o=0;s--){let l=s==r.depth?0:r.pos<=(r.start(s+1)+r.end(s+1))/2?-1:1,c=r.index(s)+(l>0?1:0),d=r.node(s),f=!1;if(o==1)f=d.canReplace(c,c,i);else{let h=d.contentMatchAt(c).findWrapping(i.firstChild.type);f=h&&d.canReplaceWith(c,c,h[0])}if(f)return l==0?r.pos:l<0?r.before(s+1):r.after(s+1)}return null}function Sr(t,e,n=e,r=I.empty){if(e==n&&!r.size)return null;let i=t.resolve(e),o=t.resolve(n);if(Ws(i,o,r))return new ut(e,n,r);return new qs(i,o,r).fit()}function Ws(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class qs{constructor(t,e,n){this.$from=t,this.$to=e,this.unplaced=n,this.frontier=[],this.placed=k.empty;for(let r=0;r<=t.depth;r++){let i=t.node(r);this.frontier.push({type:i.type,match:i.contentMatchAt(t.indexAfter(r))})}for(let r=t.depth;r>0;r--)this.placed=k.from(t.node(r).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){while(this.unplaced.size){let c=this.findFittable();if(c)this.placeNodes(c);else this.openMore()||this.dropNode()}let t=this.mustMoveInline(),e=this.placed.size-this.depth-this.$from.depth,n=this.$from,r=this.close(t<0?this.$to:n.doc.resolve(t));if(!r)return null;let i=this.placed,o=n.depth,s=r.depth;while(o&&s&&i.childCount==1)i=i.firstChild.content,o--,s--;let l=new I(i,o,s);if(t>-1)return new ft(n.pos,t,this.$to.pos,this.$to.end(),l,e);if(l.size||n.pos!=this.$to.pos)return new ut(n.pos,r.pos,l);return null}findFittable(){let t=this.unplaced.openStart;for(let e=this.unplaced.content,n=0,r=this.unplaced.openEnd;n1)r=0;if(i.type.spec.isolating&&r<=n){t=n;break}e=i.content}for(let e=1;e<=2;e++)for(let n=e==1?t:this.unplaced.openStart;n>=0;n--){let r,i=null;if(n)i=Ds(this.unplaced.content,n-1).firstChild,r=i.content;else r=this.unplaced.content;let o=r.firstChild;for(let s=this.depth;s>=0;s--){let{type:l,match:c}=this.frontier[s],d,f=null;if(e==1&&(o?c.matchType(o.type)||(f=c.fillBefore(k.from(o),!1)):i&&l.compatibleContent(i.type)))return{sliceDepth:n,frontierDepth:s,parent:i,inject:f};else if(e==2&&o&&(d=c.findWrapping(o.type)))return{sliceDepth:n,frontierDepth:s,parent:i,wrap:d};if(i&&c.matchType(i.type))break}}}openMore(){let{content:t,openStart:e,openEnd:n}=this.unplaced;if(Ts(t,-1)<=e)return!1;if(this.unplaced.size>1&&Ts(t,1)>n)n++;return this.unplaced=new I(t,e+1,n),!0}dropNode(){let{content:t,openStart:e,openEnd:n}=this.unplaced,r=Ds(t,e);if(r.childCount<=1&&e>0){let i=t.size-e<=e+r.size;this.unplaced=new I(Fn(t,e-1,1),e-1,i?e-1:n)}else this.unplaced=new I(Fn(t,e,1),e,n)}placeNodes({sliceDepth:t,frontierDepth:e,parent:n,inject:r,wrap:i}){while(this.depth>e)this.closeFrontierNode();if(i)for(let g=0;g1||l==0||g.content.size)f=b,d.push(Us(g.mark(h.allowedMarks(g.marks)),c==1?l:0,c==s.childCount?p:-1))}let m=c==s.childCount;if(!m)p=-1;if(this.placed=Vn(this.placed,e,k.from(d)),this.frontier[e].match=f,m&&p<0&&n&&n.type==this.frontier[this.depth].type&&this.frontier.length>1)this.closeFrontierNode();for(let g=0,b=s;g1&&r==this.$to.end(--n))++r;return r}findCloseLevel(t){t:for(let e=Math.min(this.depth,t.depth);e>=0;e--){let{match:n,type:r}=this.frontier[e],i=e=0;s--){let{match:l,type:c}=this.frontier[s],d=vi(t,s,c,l,!0);if(!d||d.childCount)continue t}return{depth:e,fit:o,move:i?t.doc.resolve(t.after(e+1)):t}}}close(t){let e=this.findCloseLevel(t);if(!e)return null;while(this.depth>e.depth)this.closeFrontierNode();if(e.fit.childCount)this.placed=Vn(this.placed,e.depth,e.fit);t=e.move;for(let n=e.depth+1;n<=t.depth;n++){let r=t.node(n),i=r.type.contentMatch.fillBefore(r.content,!0,t.index(n));this.openFrontierNode(r.type,r.attrs,i)}return t}openFrontierNode(t,e=null,n){let r=this.frontier[this.depth];r.match=r.match.matchType(t),this.placed=Vn(this.placed,this.depth,k.from(t.create(e,n))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let e=this.frontier.pop().match.fillBefore(k.empty,!0);if(e.childCount)this.placed=Vn(this.placed,this.frontier.length,e)}}function Fn(t,e,n){if(e==0)return t.cutByIndex(n,t.childCount);return t.replaceChild(0,t.firstChild.copy(Fn(t.firstChild.content,e-1,n)))}function Vn(t,e,n){if(e==0)return t.append(n);return t.replaceChild(t.childCount-1,t.lastChild.copy(Vn(t.lastChild.content,e-1,n)))}function Ds(t,e){for(let n=0;n1)r=r.replaceChild(0,Us(r.firstChild,e-1,r.childCount==1?n-1:0));if(e>0){if(r=t.type.contentMatch.fillBefore(r).append(r),n<=0)r=r.append(t.type.contentMatch.matchFragment(r).fillBefore(k.empty,!0))}return t.copy(r)}function vi(t,e,n,r,i){let o=t.node(e),s=i?t.indexAfter(e):t.index(e);if(s==o.childCount&&!n.compatibleContent(o.type))return null;let l=r.fillBefore(o.content,!0,s);return l&&!wd(n,o.content,s)?l:null}function wd(t,e,n){for(let r=n;r0;p--,m--){let g=i.node(p).type.spec;if(g.defining||g.definingAsContext||g.isolating)break;if(s.indexOf(p)>-1)l=p;else if(i.before(p)==m)s.splice(1,0,-p)}let c=s.indexOf(l),d=[],f=r.openStart;for(let p=r.content,m=0;;m++){let g=p.firstChild;if(d.push(g),m==r.openStart)break;p=g.content}for(let p=f-1;p>=0;p--){let m=d[p],g=yd(m.type);if(g&&!m.sameMarkup(i.node(Math.abs(l)-1)))f=p;else if(g||!m.type.isTextblock)break}for(let p=r.openStart;p>=0;p--){let m=(p+f+1)%(r.openStart+1),g=d[m];if(!g)continue;for(let b=0;b=0;p--){if(t.replace(e,n,r),t.steps.length>h)break;let m=s[p];if(m<0)continue;e=i.before(m),n=o.after(m)}}function $s(t,e,n,r,i){if(er){let o=i.contentMatchAt(0),s=o.fillBefore(t).append(t);t=s.append(o.matchFragment(s).fillBefore(k.empty,!0))}return t}function xd(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let i=bd(t.doc,e,r.type);if(i!=null)e=n=i}t.replaceRange(e,n,new I(k.from(r),0,0))}function Id(t,e,n){let r=t.doc.resolve(e),i=t.doc.resolve(n);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let s=r.sharedDepth(n),l=!1;for(let c=r.depth;c>s;c--)if(r.node(c).type.spec.isolating)l=!0;for(let c=i.depth;c>s;c--)if(i.node(c).type.spec.isolating)l=!0;if(!l){for(let c=r.depth;c>0&&e==r.start(c);c--)e=r.before(c);for(let c=i.depth;c>0&&n==i.start(c);c--)n=i.before(c);r=t.doc.resolve(e),i=t.doc.resolve(n)}}let o=Js(r,i);for(let s=0;s0&&(c||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return t.delete(r.before(l),i.after(l))}for(let s=1;s<=r.depth&&s<=i.depth;s++)if(e-r.start(s)==r.depth-s&&n>r.end(s)&&i.end(s)-n!=i.depth-s&&r.start(s-1)==i.start(s-1)&&r.node(s-1).canReplace(r.index(s-1),i.index(s-1)))return t.delete(r.before(s),n);t.delete(e,n)}function Js(t,e){let n=[],r=Math.min(t.depth,e.depth);for(let i=r;i>=0;i--){let o=t.start(i);if(oe.pos+(e.depth-i)||t.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;if(o==e.start(i)||i==t.depth&&i==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==o-1)n.push(i)}return n}class ln extends ht{constructor(t,e,n){super();this.pos=t,this.attr=e,this.value=n}apply(t){let e=t.nodeAt(this.pos);if(!e)return ct.fail("No node at attribute step's position");let n=Object.create(null);for(let i in e.attrs)n[i]=e.attrs[i];n[this.attr]=this.value;let r=e.type.create(n,null,e.marks);return ct.fromReplace(t,this.pos,this.pos+1,new I(k.from(r),0,e.isLeaf?0:1))}getMap(){return Bt.empty}invert(t){return new ln(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let e=t.mapResult(this.pos,1);return e.deletedAfter?null:new ln(e.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,e){if(typeof e.pos!="number"||typeof e.attr!="string")throw RangeError("Invalid input for AttrStep.fromJSON");return new ln(e.pos,e.attr,e.value)}}ht.jsonID("attr",ln);class Wn extends ht{constructor(t,e){super();this.attr=t,this.value=e}apply(t){let e=Object.create(null);for(let r in t.attrs)e[r]=t.attrs[r];e[this.attr]=this.value;let n=t.type.create(e,t.content,t.marks);return ct.ok(n)}getMap(){return Bt.empty}invert(t){return new Wn(this.attr,t.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(t,e){if(typeof e.attr!="string")throw RangeError("Invalid input for DocAttrStep.fromJSON");return new Wn(e.attr,e.value)}}ht.jsonID("docAttr",Wn);var an=class extends Error{};an=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n};an.prototype=Object.create(Error.prototype);an.prototype.constructor=an;an.prototype.name="TransformError";class Mi{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new xr}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let e=this.maybeStep(t);if(e.failed)throw new an(e.failed);return this}maybeStep(t){let e=t.apply(this.doc);if(!e.failed)this.addStep(t,e.doc);return e}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,e=-1e9;for(let n=0;n{t=Math.min(t,s),e=Math.max(e,l)})}return t==1e9?null:{from:t,to:e}}addStep(t,e){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=e}replace(t,e=t,n=I.empty){let r=Sr(this.doc,t,e,n);if(r)this.step(r);return this}replaceWith(t,e,n){return this.replace(t,e,new I(k.from(n),0,0))}delete(t,e){return this.replace(t,e,I.empty)}insert(t,e){return this.replaceWith(t,t,e)}replaceRange(t,e,n){return kd(this,t,e,n),this}replaceRangeWith(t,e,n){return xd(this,t,e,n),this}deleteRange(t,e){return Id(this,t,e),this}lift(t,e){return ld(this,t,e),this}join(t,e=1){return md(this,t,e),this}wrap(t,e){return dd(this,t,e),this}setBlockType(t,e=t,n,r=null){return ud(this,t,e,n,r),this}setNodeMarkup(t,e,n=null,r){return hd(this,t,e,n,r),this}setNodeAttribute(t,e,n){return this.step(new ln(t,e,n)),this}setDocAttribute(t,e){return this.step(new Wn(t,e)),this}addNodeMark(t,e){return this.step(new be(t,e)),this}removeNodeMark(t,e){let n=this.doc.nodeAt(t);if(!n)throw RangeError("No node at position "+t);if(e instanceof J){if(e.isInSet(n.marks))this.step(new qe(t,e))}else{let r=n.marks,i,o=[];while(i=e.isInSet(r))o.push(new qe(t,i)),r=i.removeFromSet(r);for(let s=o.length-1;s>=0;s--)this.step(o[s])}return this}split(t,e=1,n){return pd(this,t,e,n),this}addMark(t,e,n){return id(this,t,e,n),this}removeMark(t,e,n){return od(this,t,e,n),this}clearIncompatible(t,e,n){return Oi(this,t,e,n),this}}var Ai=Object.create(null);class F{constructor(t,e,n){this.$anchor=t,this.$head=e,this.ranges=n||[new qn(t.min(e),t.max(e))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let t=this.ranges;for(let e=0;e=0;i--){let o=e<0?dn(t.node(0),t.node(i),t.before(i+1),t.index(i),e,n):dn(t.node(0),t.node(i),t.after(i+1),t.index(i)+1,e,n);if(o)return o}return null}static near(t,e=1){return this.findFrom(t,e)||this.findFrom(t,-e)||new Ct(t.node(0))}static atStart(t){return dn(t,t,0,0,1)||new Ct(t)}static atEnd(t){return dn(t,t,t.content.size,t.childCount,-1)||new Ct(t)}static fromJSON(t,e){if(!e||!e.type)throw RangeError("Invalid input for Selection.fromJSON");let n=Ai[e.type];if(!n)throw RangeError(`No selection type ${e.type} defined`);return n.fromJSON(t,e)}static jsonID(t,e){if(t in Ai)throw RangeError("Duplicate use of selection JSON ID "+t);return Ai[t]=e,e.prototype.jsonID=t,e}getBookmark(){return R.between(this.$anchor,this.$head).getBookmark()}}F.prototype.visible=!0;class qn{constructor(t,e){this.$from=t,this.$to=e}}var js=!1;function Hs(t){if(!js&&!t.parent.inlineContent)js=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")")}class R extends F{constructor(t,e=t){Hs(t),Hs(e);super(t,e)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,e){let n=t.resolve(e.map(this.head));if(!n.parent.inlineContent)return F.near(n);let r=t.resolve(e.map(this.anchor));return new R(r.parent.inlineContent?r:n,n)}replace(t,e=I.empty){if(super.replace(t,e),e==I.empty){let n=this.$from.marksAcross(this.$to);if(n)t.ensureMarks(n)}}eq(t){return t instanceof R&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new Mr(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,e){if(typeof e.anchor!="number"||typeof e.head!="number")throw RangeError("Invalid input for TextSelection.fromJSON");return new R(t.resolve(e.anchor),t.resolve(e.head))}static create(t,e,n=e){let r=t.resolve(e);return new this(r,n==e?r:t.resolve(n))}static between(t,e,n){let r=t.pos-e.pos;if(!n||r)n=r>=0?1:-1;if(!e.parent.inlineContent){let i=F.findFrom(e,n,!0)||F.findFrom(e,-n,!0);if(i)e=i.$head;else return F.near(e,n)}if(!t.parent.inlineContent){if(r==0)t=e;else if(t=(F.findFrom(t,-n,!0)||F.findFrom(t,n,!0)).$anchor,t.pos0?0:1);i>0?s=0;s+=i){let l=e.child(s);if(!l.isAtom){let c=dn(t,l,n+i,i<0?l.childCount:0,i,o);if(c)return c}else if(!o&&T.isSelectable(l))return T.create(t,n-(i<0?l.nodeSize:0));n+=l.nodeSize*i}return null}function Ks(t,e,n){let r=t.steps.length-1;if(r{if(s==null)s=f}),t.setSelection(F.near(t.doc.resolve(s),n))}var Ys=1,Cr=2,Xs=4;class Qs extends Mi{constructor(t){super(t.doc);this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=t.selection,this.storedMarks=t.storedMarks}get selection(){if(this.curSelectionFor0}setStoredMarks(t){return this.storedMarks=t,this.updated|=Cr,this}ensureMarks(t){if(!J.sameSet(this.storedMarks||this.selection.$from.marks(),t))this.setStoredMarks(t);return this}addStoredMark(t){return this.ensureMarks(t.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(t){return this.ensureMarks(t.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Cr)>0}addStep(t,e){super.addStep(t,e),this.updated=this.updated&~Cr,this.storedMarks=null}setTime(t){return this.time=t,this}replaceSelection(t){return this.selection.replace(this,t),this}replaceSelectionWith(t,e=!0){let n=this.selection;if(e)t=t.mark(this.storedMarks||(n.empty?n.$from.marks():n.$from.marksAcross(n.$to)||J.none));return n.replaceWith(this,t),this}deleteSelection(){return this.selection.replace(this),this}insertText(t,e,n){let r=this.doc.type.schema;if(e==null){if(!t)return this.deleteSelection();return this.replaceSelectionWith(r.text(t),!0)}else{if(n==null)n=e;if(!t)return this.deleteRange(e,n);let i=this.storedMarks;if(!i){let o=this.doc.resolve(e);i=n==e?o.marks():o.marksAcross(this.doc.resolve(n))}if(this.replaceRangeWith(e,n,r.text(t,i)),!this.selection.empty&&this.selection.to==e+t.length)this.setSelection(F.near(this.selection.$to));return this}}setMeta(t,e){return this.meta[typeof t=="string"?t:t.key]=e,this}getMeta(t){return this.meta[typeof t=="string"?t:t.key]}get isGeneric(){for(let t in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Xs,this}get scrolledIntoView(){return(this.updated&Xs)>0}}function Gs(t,e){return!e||!t?t:t.bind(e)}class un{constructor(t,e,n){this.name=t,this.init=Gs(e.init,n),this.apply=Gs(e.apply,n)}}var Sd=[new un("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new un("selection",{init(t,e){return t.selection||F.atStart(e.doc)},apply(t){return t.selection}}),new un("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new un("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class Or{constructor(t,e){if(this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=Sd.slice(),e)e.forEach((n)=>{if(this.pluginsByKey[n.key])throw RangeError("Adding different instances of a keyed plugin ("+n.key+")");if(this.plugins.push(n),this.pluginsByKey[n.key]=n,n.spec.state)this.fields.push(new un(n.key,n.spec.state,n))})}}class ye{constructor(t){this.config=t}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(t){return this.applyTransaction(t).state}filterTransaction(t,e=-1){for(let n=0;nn.toJSON());if(t&&typeof t=="object")for(let n in t){if(n=="doc"||n=="selection")throw RangeError("The JSON fields `doc` and `selection` are reserved");let r=t[n],i=r.spec.state;if(i&&i.toJSON)e[n]=i.toJSON.call(r,this[r.key])}return e}static fromJSON(t,e,n){if(!e)throw RangeError("Invalid input for EditorState.fromJSON");if(!t.schema)throw RangeError("Required config field 'schema' missing");let r=new Or(t.schema,t.plugins),i=new ye(r);return r.fields.forEach((o)=>{if(o.name=="doc")i.doc=qt.fromJSON(t.schema,e.doc);else if(o.name=="selection")i.selection=F.fromJSON(i.doc,e.selection);else if(o.name=="storedMarks"){if(e.storedMarks)i.storedMarks=e.storedMarks.map(t.schema.markFromJSON)}else{if(n)for(let s in n){let l=n[s],c=l.spec.state;if(l.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(e,s)){i[o.name]=c.fromJSON.call(l,t,e[s],i);return}}i[o.name]=o.init(t,i)}}),i}}function Zs(t,e,n){for(let r in t){let i=t[r];if(i instanceof Function)i=i.bind(e);else if(r=="handleDOMEvents")i=Zs(i,e,{});n[r]=i}return n}class st{constructor(t){if(this.spec=t,this.props={},t.props)Zs(t.props,this,this.props);this.key=t.key?t.key.key:tl("plugin")}getState(t){return t[this.key]}}var Ei=Object.create(null);function tl(t){if(t in Ei)return t+"$"+ ++Ei[t];return Ei[t]=0,t+"$"}class fn{constructor(t="key"){this.key=tl(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}var bt=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},gn=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e},Pi=null,ae=function(t,e,n){let r=Pi||(Pi=document.createRange());return r.setEnd(t,n==null?t.nodeValue.length:n),r.setStart(t,e||0),r},Cd=function(){Pi=null},Xe=function(t,e,n,r){return n&&(el(t,e,n,r,-1)||el(t,e,n,r,1))},Od=/^(img|br|input|textarea|hr)$/i;function el(t,e,n,r,i){var o;for(;;){if(t==n&&e==r)return!0;if(e==(i<0?0:It(t))){let s=t.parentNode;if(!s||!E(s)||Xn(t)||Od.test(t.nodeName)||t.contentEditable=="false")return!1;e=bt(t)+(i<0?0:1),t=s}else if(E(t)){let s=t.childNodes[e+(i<0?-1:0)];if(E(s)&&s.contentEditable=="false")if((o=s.pmViewDesc)===null||o===void 0?void 0:o.ignoreForSelection)e+=i;else return!1;else t=s,e=i<0?It(t):0}else return!1}}function It(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function E(t){return t.nodeType==1}function pt(t){return t.nodeType==3}function Ge(t,e){return e?t.contains(E(e)?e:e.parentNode):!1}function Md(t,e){for(;;){if(pt(t)&&e)return t;if(E(t)&&e>0){if(t.contentEditable=="false")return null;t=t.childNodes[e-1],e=It(t)}else if(t.parentNode&&!Xn(t))e=bt(t),t=t.parentNode;else return null}}function Ad(t,e){for(;;){if(pt(t)&&e2),Ut=mn||(ne?/Mac/.test(ne.platform):!1),Tl=ne?/Win/.test(ne.platform):!1,ce=/Android \d/.test(Me),Lr=!!nl&&"webkitFontSmoothing"in nl.documentElement.style,Td=Lr?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function Rd(t){let e=t.defaultView&&t.defaultView.visualViewport;if(e)return{left:0,right:e.width,top:0,bottom:e.height};return{left:0,right:t.documentElement.clientWidth,top:0,bottom:t.documentElement.clientHeight}}function le(t,e){return typeof t=="number"?t:t[e]}function Ld(t){let e=t.getBoundingClientRect(),n=e.width/t.offsetWidth||1,r=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*n,top:e.top,bottom:e.top+t.clientHeight*r}}function rl(t,e,n){if(!Vi(e)&&e.left==0)return;let r=t.someProp("scrollThreshold")||0,i=t.someProp("scrollMargin")||5,o=t.dom.ownerDocument;for(let s=n||t.dom;;){if(!s)break;if(!E(s)){s=gn(s);continue}let l=s==o.body,c=l?Rd(o):Ld(s),d=0,f=0;if(e.topc.bottom-le(r,"bottom"))f=e.bottom-e.top>c.bottom-c.top?e.top+le(i,"top")-c.top:e.bottom-c.bottom+le(i,"bottom");if(e.leftc.right-le(r,"right"))d=e.right-c.right+le(i,"right");if(d||f)if(l)o.defaultView.scrollBy(d,f);else{let p=s.scrollLeft,m=s.scrollTop;if(f)s.scrollTop+=f;if(d)s.scrollLeft+=d;let g=s.scrollLeft-p,b=s.scrollTop-m;e={left:e.left-g,top:e.top-b,right:e.right-g,bottom:e.bottom-b}}let h=l?"fixed":getComputedStyle(s).position;if(/^(fixed|sticky)$/.test(h))break;s=h=="absolute"?s.offsetParent:gn(s)}}function Pd(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),r,i;for(let o=(e.left+e.right)/2,s=n+1;s=n-20){r=l,i=c.top;break}}return{refDOM:r,refTop:i,stack:Rl(t.dom)}}function Rl(t){let e=[],n=t.ownerDocument;for(let r=t;r;r=gn(r))if(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t==n)break;return e}function Bd({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;Ll(n,r==0?0:r-e)}function Ll(t,e){for(let n=0;n=l){s=Math.max(g.bottom,s),l=Math.min(g.top,l);let b=g.left>e.left?g.left-e.left:g.right=(g.left+g.right)/2?1:0);continue}}else if(g.top>e.top&&!c&&g.left<=e.left&&g.right>=e.left)c=f,d={left:Math.max(g.left,Math.min(g.right,e.left)),top:g.top};if(!n&&(e.left>=g.right&&e.top>=g.top||e.left>=g.left&&e.top>=g.bottom))o=h+1}}if(!n&&c)n=c,i=d,r=0;if(n&&pt(n))return Fd(n,i);if(!n||r)return{node:t,offset:o};return Pl(n,i)}function Fd(t,e){let n=t.nodeValue.length,r=document.createRange(),i;for(let o=0;o=(s.left+s.right)/2?1:0)};break}}return r.detach(),i||{node:t,offset:0}}function Hi(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function Vd(t,e){let n=t.parentNode;if(n&&/^li$/i.test(n.nodeName)&&e.left(s.left+s.right)/2?1:-1}return t.docView.posFromDOM(r,i,o)}function qd(t,e,n,r){let i=-1;for(let o=e,s=!1;;){if(o==t.dom)break;let l=t.docView.nearestDesc(o,!0),c;if(!l)return null;if(E(l.dom)&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((c=l.dom.getBoundingClientRect()).width||c.height)){if(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)){if(!s&&c.left>r.left||c.top>r.top)i=l.posBefore;else if(!s&&c.right-1?i:t.docView.posFromDOM(e,n,-1)}function Bl(t,e,n){let r=t.childNodes.length;if(r&&n.tope.top)i++}}let d;if(Lr&&i&&E(r)&&E(d=r.childNodes[i-1])&&d.contentEditable=="false"&&d.getBoundingClientRect().top>=e.top)i--;if(r==t.dom&&i==r.childNodes.length-1&&E(r.lastChild)&&e.top>r.lastChild.getBoundingClientRect().bottom)l=t.state.doc.content.size;else if(i==0||!E(r)||r.childNodes[i-1].nodeName!="BR")l=qd(t,r,i,e)}if(l==null)l=Wd(t,s,e);let c=t.docView.nearestDesc(s,!0);return{pos:l,inside:c?c.posAtStart-c.border:-1}}function Vi(t){return t.top=0&&i==r.nodeValue.length)c--,f=1;else if(n<0)c--;else d++;return Un(ke(ae(r,c,d),f),f<0)}if(!t.state.doc.resolve(e-(o||0)).parent.inlineContent){if(o==null&&i&&(n<0||i==It(r))){let c=r.childNodes[i-1];if(E(c))return Di(c.getBoundingClientRect(),!1)}if(o==null&&i=0)}if(o==null&&i&&(n<0||i==It(r))){let c=r.childNodes[i-1],d=pt(c)?ae(c,It(c)-(s?0:1)):E(c)&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return Un(ke(d,1),!1)}if(o==null&&i=0)}function Un(t,e){if(t.width==0)return t;let n=e?t.left:t.right;return{top:t.top,bottom:t.bottom,left:n,right:n}}function Di(t,e){if(t.height==0)return t;let n=e?t.top:t.bottom;return{top:n,bottom:n,left:t.left,right:t.right}}function Fl(t,e,n){let r=t.state,i=t.root.activeElement;if(r!=e)t.updateState(e);if(i!=t.dom)t.focus();try{return n()}finally{if(r!=e)t.updateState(r);if(i!=t.dom&&i)i.focus()}}function Jd(t,e,n){let r=e.selection,i=n=="up"?r.$from:r.$to;return Fl(t,e,()=>{let{node:o}=t.docView.domFromPos(i.pos,n=="up"?-1:1);for(;;){let l=t.docView.nearestDesc(o,!0);if(!l)break;if(l.node.isBlock){o=l.contentDOM||l.dom;break}o=l.dom.parentNode}let s=zl(t,i.pos,1);for(let l=o.firstChild;l;l=l.nextSibling){let c;if(E(l))c=l.getClientRects();else if(pt(l))c=ae(l,0,l.nodeValue.length).getClientRects();else continue;for(let d=0;df.top+1&&(n=="up"?s.top-f.top>(f.bottom-s.top)*2:f.bottom-s.bottom>(s.bottom-f.top)*2))return!1}}return!0})}var jd=/[\u0590-\u08ac]/;function Hd(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,o=!i,s=i==r.parent.content.size,l=t.domSelection();if(!l)return r.pos==r.start()||r.pos==r.end();if(!jd.test(r.parent.textContent)||!l.modify)return n=="left"||n=="backward"?o:s;return Fl(t,e,()=>{let{focusNode:c,focusOffset:d,anchorNode:f,anchorOffset:h}=t.domSelectionRange(),p=l.caretBidiLevel;l.modify("move",n,"character");let m=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:g,focusOffset:b}=t.domSelectionRange(),y=g&&!Ge(m,g)||c==g&&d==b;try{if(l.collapse(f,h),c&&(c!=f||d!=h)&&l.extend)l.extend(c,d)}catch(S){}if(p!=null)l.caretBidiLevel=p;return y})}var il=null,ol=null,sl=!1;function Kd(t,e,n){if(il==e&&ol==n)return sl;return il=e,ol=n,sl=n=="up"||n=="down"?Jd(t,e,n):Hd(t,e,n)}var $t=0,ll=1,je=2,Yt=3;class bn{constructor(t,e,n,r){this.parent=t,this.children=e,this.dom=n,this.contentDOM=r,this.dirty=$t,n.pmViewDesc=this}matchesWidget(t){return!1}matchesMark(t){return!1}matchesNode(t,e,n){return!1}matchesHack(t){return!1}parseRule(t){return null}stopEvent(t){return!1}get size(){let t=0;for(let e=0;ebt(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM)){let i=t.compareDocumentPosition(this.contentDOM);if(i&16)r=e>Array.from(t.childNodes).findIndex((o)=>o.contains(this.contentDOM));else r=!(i&4)}else if(this.dom.firstChild){if(e==0)for(let i=t;;i=i.parentNode){if(i==this.dom){r=!1;break}if(i.previousSibling)break}if(r==null&&e==t.childNodes.length)for(let i=t;;i=i.parentNode){if(i==this.dom){r=!0;break}if(i.nextSibling)break}}return(r==null?n>0:r)?this.posAtEnd:this.posAtStart}nearestDesc(t,e=!1){for(let n=!0,r=t;r;r=r.parentNode){let i=this.getDesc(r),o;if(i&&(!e||i.node))if(n&&(o=i.nodeDOM)&&!(E(o)?Ge(o,t):o==t))n=!1;else return i}}getDesc(t){let e=t.pmViewDesc;for(let n=e;n;n=n.parent)if(n==this)return e}posFromDOM(t,e,n){for(let r=t;r;r=r.parentNode){let i=this.getDesc(r);if(i)return i.localPosFromDOM(t,e,n)}return-1}descAt(t){for(let e=0,n=0;et){r=t-i;break}i=s}if(r)return this.children[n].domFromPos(r-this.children[n].border,e);for(;n>0;n--){let i=this.children[n-1];if(i.size||!(i instanceof Yi||i instanceof Ki&&i.side>=0))break}if(e<=0){let i,o=!0;for(;;n--,o=!1)if(i=n?this.children[n-1]:null,!i||i.dom.parentNode==this.contentDOM)break;if(i&&e&&o&&!i.border&&!i.domAtom)return i.domFromPos(i.size,e);return{node:this.contentDOM,offset:i?bt(i.dom)+1:0}}else{let i,o=!0;for(;;n++,o=!1)if(i=n=d&&e<=c-l.border&&l.node&&l.contentDOM&&this.contentDOM.contains(l.contentDOM))return l.parseRange(t,e,d);t=o;for(let f=s;f>0;f--){let h=this.children[f-1];if(h.size&&h.dom.parentNode==this.contentDOM&&!h.emptyChildAt(1)){r=bt(h.dom)+1;break}t-=h.size}if(r==-1)r=0}if(r>-1&&(c>e||s==this.children.length-1)){e=c;for(let d=s+1;dm&&oe){let m=s;s=l,l=m}let p=document.createRange();p.setEnd(l.node,l.offset),p.setStart(s.node,s.offset),c.removeAllRanges(),c.addRange(p)}}ignoreMutation(t){return!this.contentDOM&&t.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,e){for(let n=0,r=0;r=n:tn){let s=n+i.border,l=o-i.border;if(t>=s&&e<=l){if(this.dirty=t==n||e==o?je:ll,t==s&&e==l&&(i.contentLost||i.dom.parentNode!=this.contentDOM))i.dirty=Yt;else i.markDirty(t-s,e-s);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?je:Yt}n=o}this.dirty=je}markParentsDirty(){let t=1;for(let e=this.parent;e;e=e.parent,t++){let n=t==1?je:ll;if(e.dirty{if(!i)return r;if(i.parent)return i.parent.posBeforeChild(i)});if(!e.type.spec.raw){let s=E(o)?o:document.createElement("span");if(s!=o)s.appendChild(o),o=s;if(!s.hasAttribute("contenteditable"))s.contentEditable="false";s.classList.add("ProseMirror-widget")}super(t,[],o,null);this.widget=e,this.widget=e,i=this}matchesWidget(t){return this.dirty==$t&&t.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(t){let e=this.widget.spec.stopEvent;return e?e(t):!1}ignoreMutation(t){return t.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class Vl extends bn{constructor(t,e,n,r){super(t,[],e,null);this.textDOM=n,this.text=r}get size(){return this.text.length}localPosFromDOM(t,e){if(t!=this.textDOM)return this.posAtStart+(e?this.size:0);return this.posAtStart+e}domFromPos(t){return{node:this.textDOM,offset:t}}ignoreMutation(t){return t.type==="characterData"&&t.target.nodeValue==t.oldValue}}class Se extends bn{constructor(t,e,n,r,i){super(t,[],n,r);this.mark=e,this.spec=i}static create(t,e,n,r){let i=r.nodeViews[e.type.name],o=i&&i(e,r,n);if(!o||!o.dom)o=Ve.renderSpec(document,e.type.spec.toDOM(e,n),null,e.attrs);return new Se(t,e,o.dom,o.contentDOM||o.dom,o)}parseRule(){if(this.dirty&Yt||this.mark.type.spec.reparseInView)return null;return{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=Yt&&this.mark.eq(t)}markDirty(t,e){if(super.markDirty(t,e),this.dirty!=$t){let n=this.parent;while(!n.node)n=n.parent;if(n.dirty0)i=qi(i,0,t,n);for(let s=0;s{if(!l)return o;if(l.parent)return l.parent.posBeforeChild(l)},n,r),d=c&&c.dom,f=c&&c.contentDOM;if(e.isText){if(!d)d=document.createTextNode(e.text);else if(!pt(d))throw RangeError("Text must be rendered as a DOM text node")}else if(!d)({dom:d,contentDOM:f}=Ve.renderSpec(document,e.type.spec.toDOM(e),null,e.attrs));if(!f&&!e.isText&&d.nodeName!="BR"){if(!d.hasAttribute("contenteditable"))d.contentEditable="false";if(e.type.spec.draggable)d.draggable=!0}let h=d;if(d=$l(d,n,e),c)return l=new Wl(t,e,n,r,d,f||null,h,c);else if(e.isText)return new Pr(t,e,n,r,d,h);else return new Ce(t,e,n,r,d,f||null,h)}parseRule(t){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre")e.preserveWhitespace="full";if(!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}if(!e.contentElement){let n=t&&t.find((r)=>E(r)&&t.indexOf(r.parentNode)<0&&this.dom.contains(r));if(n)e.contentElement=n;else e.getContent=()=>k.empty}}return e}matchesNode(t,e,n){return this.dirty==$t&&t.eq(this.node)&&Ar(e,this.outerDeco)&&n.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(t,e){let n=this.node.inlineContent,r=e,i=t.composing?this.localCompositionInfo(t,e):null,o=i&&i.pos>-1?i:null,s=i&&i.pos<0,l=new Jl(this,o&&o.node,t),c=this.node.inlineContent,d=c&&this.node.isBlock;if(Qd(this.node,this.innerDeco,(f,h,p)=>{if(f.spec.marks)l.syncToMarks(f.spec.marks,n,t,h);else if(f.type.side>=0&&!p)l.syncToMarks(h==this.node.childCount?J.none:this.node.child(h).marks,n,t,h);l.placeWidget(f,t,r)},(f,h,p,m)=>{if(l.syncToMarks(f.marks,n,t,m),d&&f.isAtom&&!f.isText)l.addHackNode("IMG",l.top);let g;if(l.findNodeMatch(f,h,p,m));else if(s&&t.state.selection.from>r&&t.state.selection.to-1&&l.updateNodeAt(f,h,p,g,t));else if(l.updateNextNode(f,h,p,t,m,r));else l.addNode(f,h,p,t,r);if(r+=f.nodeSize,c)d=f.isAtom&&!f.isText}),l.syncToMarks([],n,t,0),this.node.isTextblock)l.addTextblockHacks();if(l.destroyRest(),l.changed||this.dirty==je){if(o)this.protectLocalComposition(t,o);if(ql(this.contentDOM,this.children,t),mn)Zd(this.dom)}}localCompositionInfo(t,e){let{from:n,to:r}=t.state.selection;if(!(t.state.selection instanceof R)||ne+this.node.content.size)return null;let i=t.input.compositionNode;if(!i||!this.dom.contains(i.parentNode))return null;if(this.node.inlineContent){let o=i.nodeValue,s=tu(this.node.content,o,n-e,r-e);return s<0?null:{node:i,pos:s,text:o}}else return{node:i,pos:-1,text:""}}protectLocalComposition(t,{node:e,pos:n,text:r}){if(this.getDesc(e))return;let i=e;for(;;i=i.parentNode){if(i.parentNode==this.contentDOM)break;while(i.previousSibling)i.parentNode.removeChild(i.previousSibling);while(i.nextSibling)i.parentNode.removeChild(i.nextSibling);if(i.pmViewDesc)i.pmViewDesc=void 0}let o=new Vl(this,i,e,r);t.input.compositionNodes.push(o),this.children=qi(this.children,n,n+r.length,t,o)}update(t,e,n,r){if(this.dirty==Yt||!t.sameMarkup(this.node))return!1;return this.updateInner(t,e,n,r),!0}updateInner(t,e,n,r){if(this.updateOuterDeco(e),this.node=t,this.innerDeco=n,this.contentDOM)this.updateChildren(r,this.posAtStart);this.dirty=$t}updateOuterDeco(t){if(Ar(t,this.outerDeco))return;let e=!E(this.nodeDOM),n=this.dom;if(this.dom=Ul(this.dom,this.nodeDOM,Wi(this.outerDeco,this.node,e),Wi(t,this.node,e)),this.dom!=n)n.pmViewDesc=void 0,this.dom.pmViewDesc=this;this.outerDeco=t}selectNode(){if(E(this.nodeDOM)){if(this.nodeDOM.classList.add("ProseMirror-selectednode"),this.contentDOM||!this.node.type.spec.draggable)this.nodeDOM.draggable=!0}}deselectNode(){if(E(this.nodeDOM)){if(this.nodeDOM.classList.remove("ProseMirror-selectednode"),this.contentDOM||!this.node.type.spec.draggable)this.nodeDOM.removeAttribute("draggable")}}get domAtom(){return this.node.isAtom}}function al(t,e,n,r,i){$l(r,e,t);let o=new Ce(void 0,t,e,n,r,r,r);if(o.contentDOM)o.updateChildren(i,0);return o}class Pr extends Ce{constructor(t,e,n,r,i,o){super(t,e,n,r,i,null,o)}parseRule(){let t=this.nodeDOM.parentNode;while(t&&t!=this.dom&&!t.pmIsDeco)t=t.parentNode;return{skip:t||!0}}update(t,e,n,r){if(this.dirty==Yt||this.dirty!=$t&&!this.inParent()||!t.sameMarkup(this.node))return!1;if(this.updateOuterDeco(e),(this.dirty!=$t||t.text!=this.node.text)&&t.text!=this.nodeDOM.nodeValue){if(this.nodeDOM.nodeValue=t.text,r.trackWrites==this.nodeDOM)r.trackWrites=null}return this.node=t,this.dirty=$t,!0}inParent(){let t=this.parent.contentDOM;for(let e=this.nodeDOM;e;e=e.parentNode)if(e==t)return!0;return!1}domFromPos(t){return{node:this.nodeDOM,offset:t}}localPosFromDOM(t,e,n){if(t==this.nodeDOM)return this.posAtStart+Math.min(e,this.node.text.length);return super.localPosFromDOM(t,e,n)}ignoreMutation(t){return t.type!="characterData"&&t.type!="selection"}slice(t,e,n){let r=this.node.cut(t,e),i=document.createTextNode(r.text);return new Pr(this.parent,r,this.outerDeco,this.innerDeco,i,i)}markDirty(t,e){if(super.markDirty(t,e),this.dom!=this.nodeDOM&&(t==0||e==this.nodeDOM.nodeValue.length))this.dirty=Yt}get domAtom(){return!1}isText(t){return this.node.text==t}}class Yi extends bn{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==$t&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Wl extends Ce{constructor(t,e,n,r,i,o,s,l){super(t,e,n,r,i,o,s);this.spec=l}update(t,e,n,r){if(this.dirty==Yt)return!1;if(this.spec.update&&(this.node.type==t.type||this.spec.multiType)){let i=this.spec.update(t,e,n);if(i)this.updateInner(t,e,n,r);return i}else if(!this.contentDOM&&!t.isLeaf)return!1;else return super.update(t,e,n,r)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(t,e,n,r){this.spec.setSelection?this.spec.setSelection(t,e,n.root):super.setSelection(t,e,n,r)}destroy(){if(this.spec.destroy)this.spec.destroy();super.destroy()}stopEvent(t){return this.spec.stopEvent?this.spec.stopEvent(t):!1}ignoreMutation(t){return this.spec.ignoreMutation?this.spec.ignoreMutation(t):super.ignoreMutation(t)}}function ql(t,e,n){let r=t.firstChild,i=!1;for(let o=0;o>1,s=Math.min(o,t.length);while(i-1){if(l>this.index)this.changed=!0,this.destroyBetween(this.index,l);this.top=this.top.children[this.index]}else{let d=Se.create(this.top,t[o],e,n);this.top.children.splice(this.index,0,d),this.top=d,this.changed=!0}this.index=0,o++}}findNodeMatch(t,e,n,r){let i=-1,o;if(r>=this.preMatch.index&&(o=this.preMatch.matches[r-this.preMatch.index]).parent==this.top&&o.matchesNode(t,e,n))i=this.top.children.indexOf(o,this.index);else for(let s=this.index,l=Math.min(this.top.children.length,s+5);s0){let l;for(;;)if(r){let d=n.children[r-1];if(d instanceof Se)n=d,r=d.children.length;else{l=d,r--;break}}else if(n==e)break t;else r=n.parent.children.indexOf(n),n=n.parent;let c=l.node;if(!c)continue;if(c!=t.child(i-1))break;--i,o.set(l,i),s.push(l)}return{index:i,matched:o,matches:s.reverse()}}function Gd(t,e){return t.type.side-e.type.side}function Qd(t,e,n,r){let i=e.locals(t),o=0;if(i.length==0){for(let d=0;do)l.push(i[s++]);let g=o+p.nodeSize;if(p.isText){let y=g;if(s!y.inline):l.slice();r(p,b,e.forChild(o,p),m),o=g}}function Zd(t){if(t.nodeName=="UL"||t.nodeName=="OL"){let e=t.style.cssText;t.style.cssText=e+"; list-style: square !important",window.getComputedStyle(t).listStyle,t.style.cssText=e}}function tu(t,e,n,r){for(let i=0,o=0;i=n){if(o>=r&&c.slice(r-e.length-l,r-l)==e)return r-e.length;let d=l=0&&d+e.length+l>=n)return l+d;if(n==r&&c.length>=r+e.length-l&&c.slice(r-l,r-l+e.length)==e)return r}}return-1}function qi(t,e,n,r,i){let o=[];for(let s=0,l=0;s=n||f<=e)o.push(c);else{if(dn)o.push(c.slice(n-d,c.size,r))}}return o}function Xi(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let i=t.docView.nearestDesc(n.focusNode),o=i&&i.size==0,s=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(s<0)return null;let l=r.resolve(s),c,d;if(Rr(n)){c=s;while(i&&!i.node)i=i.parent;if(i&&i.node.isAtom&&T.isSelectable(i.node)&&i.parent&&!(i.node.isInline&&Ed(n.focusNode,n.focusOffset,i.dom))){let h=i.posBefore;d=new T(s==h?l:r.resolve(h))}else if(zt&&e=="key"&&s>t.state.selection.to&&E(n.focusNode)&&n.focusOffset==n.focusNode.childNodes.length&&i&&i.posAtStart>t.state.selection.to)for(let h=n.focusNode;;h=h.parentNode){if(getComputedStyle(h).overflow!="visible"){d=F.findFrom(r.resolve(i.posAtStart),1);break}if(h==i.dom||h.nextSibling||!h.parentNode||!E(h.parentNode))break}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let h=s,p=s;for(let m=0;m{if(n.anchorNode!=r||n.anchorOffset!=i)e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{if(!jl(t)||t.state.selection.visible)t.dom.classList.remove("ProseMirror-hideselection")},20)})}function nu(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";if(r)e.collapse(n.parentNode,bt(n)+1);else e.collapse(n,0);if(!r&&!t.state.selection.visible&&Lt&&ve<=11)n.disabled=!0,n.disabled=!1}function Hl(t,e){if(e instanceof T){let n=t.docView.descAt(e.from);if(n!=t.lastSelectedViewDesc){if(hl(t),n)n.selectNode();t.lastSelectedViewDesc=n}}else hl(t)}function hl(t){if(t.lastSelectedViewDesc){if(t.lastSelectedViewDesc.parent)t.lastSelectedViewDesc.deselectNode();t.lastSelectedViewDesc=void 0}}function Gi(t,e,n,r){return t.someProp("createSelectionBetween",(i)=>i(t,e,n))||R.between(e,n,r)}function pl(t){if(t.editable&&!t.hasFocus())return!1;return Kl(t)}function Kl(t){let e=t.domSelectionRange();if(!e.anchorNode)return!1;try{return Ge(t.dom,e.anchorNode)&&(t.editable||Ge(t.dom,e.focusNode))}catch(n){return!1}}function ru(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Xe(e.node,e.offset,n.anchorNode,n.anchorOffset)}function Ui(t,e){let{$anchor:n,$head:r}=t.selection,i=e>0?n.max(r):n.min(r),o=!i.parent.inlineContent?i:i.depth?t.doc.resolve(e>0?i.after():i.before()):null;return o&&F.findFrom(o,e)}function xe(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function _l(t,e,n){let r=t.state.selection;if(r instanceof R){if(n.indexOf("s")>-1){let{$head:i}=r,o=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!o||o.isText||!o.isLeaf)return!1;let s=t.state.doc.resolve(i.pos+o.nodeSize*(e<0?-1:1));return xe(t,new R(r.$anchor,s))}else if(!r.empty)return!1;else if(t.endOfTextblock(e>0?"forward":"backward")){let i=Ui(t.state,e);if(i&&i instanceof T)return xe(t,i);return!1}else if(!Ut||n.indexOf("m")<0){let i=r.$head,o=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,s;if(!o||o.isText)return!1;let l=e<0?i.pos-o.nodeSize:i.pos;if(!(o.isAtom||(s=t.docView.descAt(l))&&!s.contentDOM))return!1;if(T.isSelectable(o))return xe(t,new T(e<0?t.state.doc.resolve(i.pos-o.nodeSize):i));else return xe(t,new R(t.state.doc.resolve(e<0?l:l+o.nodeSize)))}}else if(r instanceof T&&r.node.isInline)return xe(t,new R(e>0?r.$to:r.$from));else{let i=Ui(t.state,e);if(i)return xe(t,i);return!1}}function jn(t,e){let n=t.pmViewDesc;return n?n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR"):E(t)&&t.contentEditable=="false"}function pn(t,e){return e<0?iu(t):ou(t)}function iu(t){let e=t.domSelectionRange(),{focusNode:n,focusOffset:r}=e;if(!n)return;let i,o,s=!1;if(zt&&E(n)&&r0){if(!E(n))break;let l=n.childNodes[r-1];if(jn(l,-1))i=n,o=--r;else if(pt(l))n=l,r=n.nodeValue.length;else break}else if(Yl(n))break;else{let l=n.previousSibling;while(l&&jn(l,-1))i=n.parentNode,o=bt(l),l=l.previousSibling;if(!l){if(n=n.parentNode,n==t.dom)break;r=0}else n=l,r=It(n)}if(s)$i(t,n,r);else if(i)$i(t,i,o)}function ou(t){let e=t.domSelectionRange(),{focusNode:n,focusOffset:r}=e;if(!n)return;let i=It(n),o,s;for(;;)if(r{if(t.state==o)ue(t)},50)}function gl(t,e){let n=t.state.doc.resolve(e);if(!(wt||Tl)&&n.parent.inlineContent){let o=t.coordsAtPos(e);if(e>n.start()){let s=t.coordsAtPos(e-1),l=(s.top+s.bottom)/2;if(l>o.top&&l1)return s.lefto.top&&l1)return s.left>o.left?"ltr":"rtl"}}let r=t.dom;for(let o=n.depth;o>0;o--)if(n.node(o).isBlock){r=t.nodeDOM(n.before(o))||r;break}return getComputedStyle(r).direction=="rtl"?"rtl":"ltr"}function ml(t,e,n){let r=t.state.selection;if(r instanceof R&&!r.empty||n.indexOf("s")>-1)return!1;if(Ut&&n.indexOf("m")>-1)return!1;let{$from:i,$to:o}=r;if(!i.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let s=Ui(t.state,e);if(s&&s instanceof T)return xe(t,s)}if(!i.parent.inlineContent){let s=e<0?i:o,l=r instanceof Ct?F.near(s,e):F.findFrom(s,e);return l?xe(t,l):!1}return!1}function bl(t,e){if(!(t.state.selection instanceof R))return!0;let{$head:n,$anchor:r,empty:i}=t.state.selection;if(!n.sameParent(r))return!0;if(!i)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let o=!n.textOffset&&(e<0?n.nodeBefore:n.nodeAfter);if(o&&!o.isText){let s=t.state.tr;if(e<0)s.delete(n.pos-o.nodeSize,n.pos);else s.delete(n.pos,n.pos+o.nodeSize);return t.dispatch(s),!0}return!1}function wl(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function au(t){if(!vt||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(e&&E(e)&&n==0&&e.firstChild&&E(e.firstChild)&&e.firstChild.contentEditable=="false"){let r=e.firstChild;wl(t,r,"true"),setTimeout(()=>wl(t,r,"false"),20)}return!1}function cu(t){let e="";if(t.ctrlKey)e+="c";if(t.metaKey)e+="m";if(t.altKey)e+="a";if(t.shiftKey)e+="s";return e}function du(t,e){let n=e.keyCode,r=cu(e);if(n==8||Ut&&n==72&&r=="c")return bl(t,-1)||pn(t,-1);else if(n==46&&!e.shiftKey||Ut&&n==68&&r=="c")return bl(t,1)||pn(t,1);else if(n==13||n==27)return!0;else if(n==37||Ut&&n==66&&r=="c"){let i=n==37?gl(t,t.state.selection.from)=="ltr"?-1:1:-1;return _l(t,i,r)||pn(t,i)}else if(n==39||Ut&&n==70&&r=="c"){let i=n==39?gl(t,t.state.selection.from)=="ltr"?1:-1:1;return _l(t,i,r)||pn(t,i)}else if(n==38||Ut&&n==80&&r=="c")return ml(t,-1,r)||pn(t,-1);else if(n==40||Ut&&n==78&&r=="c")return au(t)||ml(t,1,r)||pn(t,1);else if(r==(Ut?"m":"c")&&(n==66||n==73||n==89||n==90))return!0;return!1}function Qi(t,e){t.someProp("transformCopied",(m)=>{e=m(e,t)});let n=[],{content:r,openStart:i,openEnd:o}=e;while(i>1&&o>1&&r.childCount==1&&r.firstChild.childCount==1){i--,o--;let m=r.firstChild;n.push(m.type.name,m.attrs!=m.type.defaultAttrs?m.attrs:null),r=m.content}let s=t.someProp("clipboardSerializer")||Ve.fromSchema(t.state.schema),l=ea(),c=l.createElement("div");c.appendChild(s.serializeFragment(r,{document:l}));let d=c.firstChild,f,h=0;while(d&&E(d)&&(f=ta[d.nodeName.toLowerCase()])){for(let m=f.length-1;m>=0;m--){let g=l.createElement(f[m]);while(c.firstChild)g.appendChild(c.firstChild);c.appendChild(g),h++}d=c.firstChild}if(d&&E(d))d.setAttribute("data-pm-slice",`${i} ${o}${h?` -${h}`:""} ${JSON.stringify(n)}`);let p=t.someProp("clipboardTextSerializer",(m)=>m(e,t))||e.content.textBetween(0,e.content.size,` - -`);return{dom:c,text:p,slice:e}}function Xl(t,e,n,r,i){let o=i.parent.type.spec.code,s,l;if(!n&&!e)return null;let c=!!e&&(r||o||!n);if(c){if(t.someProp("transformPastedText",(p)=>{e=p(e,o||r,t)}),o)return l=new I(k.from(t.state.schema.text(e.replace(/\r\n?/g,` -`))),0,0),t.someProp("transformPasted",(p)=>{l=p(l,t,!0)}),l;let h=t.someProp("clipboardTextParser",(p)=>p(e,i,r,t));if(h)l=h;else{let p=i.marks(),{schema:m}=t.state,g=Ve.fromSchema(m);s=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach((b)=>{let y=s.appendChild(document.createElement("p"));if(b)y.appendChild(g.serializeNode(m.text(b,p)))})}}else if(t.someProp("transformPastedHTML",(h)=>{n=h(n,t)}),s=pu(n),Lr)_u(s);let d=s&&s.querySelector("[data-pm-slice]"),f=d&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(d.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let h=+f[3];h>0;h--){let p=s.firstChild;while(p&&!E(p))p=p.nextSibling;if(!p)break;s=p}if(!l)l=(t.someProp("clipboardParser")||t.someProp("domParser")||rn.fromSchema(t.state.schema)).parseSlice(s,{preserveWhitespace:!!(c||f),context:i,ruleFromNode(p){if(p.nodeName=="BR"&&!p.nextSibling&&p.parentNode&&!uu.test(p.parentNode.nodeName))return{ignore:!0};return null}});if(f)l=gu(yl(l,+f[1],+f[2]),f[4]);else if(l=I.maxOpen(fu(l.content,i),!0),l.openStart||l.openEnd){let h=0,p=0;for(let m=l.content.firstChild;h{l=h(l,t,c)}),l}var uu=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function fu(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let i=e.node(n).contentMatchAt(e.index(n)),o,s=[];if(t.forEach((l)=>{if(!s)return;let c=i.findWrapping(l.type),d;if(!c)return s=null;if(d=s.length&&o.length&&Ql(c,o,l,s[s.length-1],0))s[s.length-1]=d;else{if(s.length)s[s.length-1]=Zl(s[s.length-1],o.length);let f=Gl(l,c);s.push(f),i=i.matchType(f.type),o=c}}),s)return k.from(s)}return t}function Gl(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,k.from(t));return t}function Ql(t,e,n,r,i){if(i1)o=0;if(i=n)l=e<0?s.contentMatchAt(0).fillBefore(l,o<=i).append(l):l.append(s.contentMatchAt(s.childCount).fillBefore(k.empty,!0));return t.replaceChild(e<0?0:t.childCount-1,s.copy(l))}function yl(t,e,n){if(en})}return $n.createHTML(t)}function pu(t){let e=/^(\s*]*>)*/.exec(t);if(e)t=t.slice(e[0].length);let n=ea(),r=n.body,i=/<([a-z][^>\s]+)/i.exec(t),o;if(o=i&&ta[i[1].toLowerCase()])t=o.map((s)=>"<"+s+">").join("")+t+o.map((s)=>"").reverse().join("");if(r.innerHTML=hu(t),o)for(let s=0;s=0;l-=2){let c=n.nodes[r[l]];if(!c||c.hasRequiredAttrs())break;try{i=k.from(c.create(r[l+1],i))}catch(d){break}o++,s++}return new I(i,o,s)}var Ot={},Mt={},mu={touchstart:!0,touchmove:!0};class na{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-200000000,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function bu(t){for(let e in Ot){let n=Ot[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=(r)=>{if(yu(t,r)&&!Zi(t,r)&&(t.editable||!(r.type in Mt)))n(t,r)},mu[e]?{passive:!0}:void 0)}if(vt)t.dom.addEventListener("input",()=>null);ji(t)}function de(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function wu(t){if(t.input.mouseDown)t.input.mouseDown.done();t.domObserver.stop();for(let e in t.input.eventHandlers)t.dom.removeEventListener(e,t.input.eventHandlers[e]);clearTimeout(t.input.composingTimeout),clearTimeout(t.input.lastIOSEnterFallbackTimeout)}function ji(t){t.someProp("handleDOMEvents",(e)=>{for(let n in e)if(!t.input.eventHandlers[n])t.dom.addEventListener(n,t.input.eventHandlers[n]=(r)=>Zi(t,r))})}function Zi(t,e){return t.someProp("handleDOMEvents",(n)=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function yu(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let n=e.target;n!=t.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(e))return!1;return!0}function ku(t,e){if(!Zi(t,e)&&Ot[e.type]&&(t.editable||!(e.type in Mt)))Ot[e.type](t,e)}Mt.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,la(t))return;if(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),ce&&wt&&n.keyCode==13)return;if(n.keyCode!=229)t.domObserver.forceFlush();if(mn&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();t.input.lastIOSEnter=r,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{if(t.input.lastIOSEnter==r)t.someProp("handleKeyDown",(i)=>i(t,Je(13,"Enter"))),t.input.lastIOSEnter=0},200)}else if(t.someProp("handleKeyDown",(r)=>r(t,n))||du(t,n))n.preventDefault();else de(t,"key")};Mt.keyup=(t,e)=>{if(e.keyCode==16)t.input.shiftKey=!1};Mt.keypress=(t,e)=>{let n=e;if(la(t)||!n.charCode||n.ctrlKey&&!n.altKey||Ut&&n.metaKey)return;if(t.someProp("handleKeyPress",(i)=>i(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof R)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(n.charCode),o=()=>t.state.tr.insertText(i).scrollIntoView();if(!/[\r\n]/.test(i)&&!t.someProp("handleTextInput",(s)=>s(t,r.$from.pos,r.$to.pos,i,o)))t.dispatch(o());n.preventDefault()}};function Gn(t){return{left:t.clientX,top:t.clientY}}function xu(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function to(t,e,n,r,i){if(r==-1)return!1;let o=t.state.doc.resolve(r);for(let s=o.depth+1;s>0;s--)if(t.someProp(e,(l)=>s>o.depth?l(t,n,o.nodeAfter,o.before(s),i,!0):l(t,n,o.node(s),o.before(s),i,!1)))return!0;return!1}function Qn(t,e,n){if(!t.focused)t.focus();if(t.state.selection.eq(e))return;let r=t.state.tr.setSelection(e);r.setMeta("pointer",!0),t.dispatch(r)}function Iu(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;if(r&&r.isAtom&&T.isSelectable(r))return Qn(t,new T(n)),!0;return!1}function vu(t,e){if(e==-1)return!1;let n=t.state.selection,r,i;if(n instanceof T)r=n.node;let o=t.state.doc.resolve(e);for(let s=o.depth+1;s>0;s--){let l=s>o.depth?o.nodeAfter:o.node(s);if(T.isSelectable(l)){if(r&&n.$from.depth>0&&s>=n.$from.depth&&o.before(n.$from.depth+1)==n.$from.pos)i=o.before(n.$from.depth);else i=o.before(s);break}}if(i!=null)return Qn(t,T.create(t.state.doc,i)),!0;else return!1}function Su(t,e,n,r,i){return to(t,"handleClickOn",e,n,r)||t.someProp("handleClick",(o)=>o(t,e,r))||(i?vu(t,n):Iu(t,n))}function Cu(t,e,n,r){return to(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",(i)=>i(t,e,r))}function Ou(t,e,n,r){return to(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",(i)=>i(t,e,r))||Mu(t,n,r)}function Mu(t,e,n){if(n.button!=0)return!1;let r=ra(t,e,!0),i=t.state.doc;if(!r)return!1;if(Qn(t,r),r instanceof R&&i.eq(t.state.doc))t.input.mouseDown=new sa(t,r);return!0}function ra(t,e,n){let r=t.state.doc;if(e==-1)return r.inlineContent?R.create(r,0,r.content.size):null;let i=r.resolve(e);for(let o=i.depth+1;o>0;o--){let s=o>i.depth?i.nodeAfter:i.node(o),l=i.before(o);if(s.inlineContent)return R.create(r,l+1,l+1+s.content.size);else if(n&&T.isSelectable(s))return T.create(r,l)}return null}function eo(t){return Er(t)}var ia=Ut?"metaKey":"ctrlKey";Ot.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=eo(t),i=Date.now(),o="singleClick";if(i-t.input.lastClick.time<500&&xu(n,t.input.lastClick)&&!n[ia]&&t.input.lastClick.button==n.button){if(t.input.lastClick.type=="singleClick")o="doubleClick";else if(t.input.lastClick.type=="doubleClick")o="tripleClick"}if(t.input.lastClick={time:i,x:n.clientX,y:n.clientY,type:o,button:n.button},t.input.mouseDown)t.input.mouseDown.done();let s=t.posAtCoords(Gn(n));if(!s)return;if(o=="singleClick")t.input.mouseDown=new oa(t,s,n,!!r);else if((o=="doubleClick"?Cu:Ou)(t,s.pos,s.inside,n))n.preventDefault();else de(t,"pointer")};class no{constructor(t){this.view=t,this.mightDrag=null,t.root.addEventListener("mouseup",this.up=this.up.bind(this)),t.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(t){this.done()}move(t){if(t.buttons==0)this.done()}done(){if(this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this)this.view.input.mouseDown=null}delaySelUpdate(){return!1}}class oa extends no{constructor(t,e,n,r){super(t);this.pos=e,this.event=n,this.flushed=r,this.delayedSelectionSync=!1,this.startDoc=t.state.doc,this.selectNode=!!n[ia],this.allowDefault=n.shiftKey;let i,o;if(e.inside>-1)i=t.state.doc.nodeAt(e.inside),o=e.inside;else{let d=t.state.doc.resolve(e.pos);i=d.parent,o=d.depth?d.before():0}let s=r?null:n.target,l=s?t.docView.nearestDesc(s,!0):null;this.target=l&&E(l.nodeDOM)?l.nodeDOM:null;let{selection:c}=t.state;if(n.button==0&&(i.type.spec.draggable&&i.type.spec.selectable!==!1||c instanceof T&&c.from<=o&&c.to>o))this.mightDrag={node:i,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&zt&&!this.target.hasAttribute("contentEditable"))};if(this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)){if(this.view.domObserver.stop(),this.mightDrag.addAttr)this.target.draggable=!0;if(this.mightDrag.setUneditable)setTimeout(()=>{if(this.view.input.mouseDown==this)this.target.setAttribute("contentEditable","false")},20);this.view.domObserver.start()}de(t,"pointer")}done(){if(super.done(),this.mightDrag&&this.target){if(this.view.domObserver.stop(),this.mightDrag.addAttr)this.target.removeAttribute("draggable");if(this.mightDrag.setUneditable)this.target.removeAttribute("contentEditable");this.view.domObserver.start()}if(this.delayedSelectionSync)setTimeout(()=>{if(!this.view.isDestroyed)ue(this.view)})}up(t){if(this.done(),!this.view.dom.contains(t.target))return;let e=this.pos;if(this.view.state.doc!=this.startDoc)e=this.view.posAtCoords(Gn(t));if(this.updateAllowDefault(t),this.allowDefault||!e)de(this.view,"pointer");else if(Su(this.view,e.pos,e.inside,t,this.selectNode))t.preventDefault();else if(t.button==0&&(this.flushed||vt&&this.mightDrag&&!this.mightDrag.node.isAtom||wt&&!this.view.state.selection.visible&&Math.min(Math.abs(e.pos-this.view.state.selection.from),Math.abs(e.pos-this.view.state.selection.to))<=2))Qn(this.view,F.near(this.view.state.doc.resolve(e.pos))),t.preventDefault();else de(this.view,"pointer")}move(t){this.updateAllowDefault(t),de(this.view,"pointer"),super.move(t)}updateAllowDefault(t){if(!this.allowDefault&&(Math.abs(this.event.x-t.clientX)>4||Math.abs(this.event.y-t.clientY)>4))this.allowDefault=!0}delaySelUpdate(){if(!this.allowDefault)return!1;return this.delayedSelectionSync=!0,!0}}class sa extends no{constructor(t,e){super(t);this.startSelection=e,this.startDoc=t.state.doc}move(t){if(t.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}t.preventDefault(),de(this.view,"pointer");let e=this.view.posAtCoords(Gn(t)),n=e&&ra(this.view,e.inside,!1);if(!n)return;let{doc:r}=this.view.state,i=this.startSelection,[o,s]=n.from{t.input.lastTouch=Date.now(),eo(t),de(t,"pointer")};Ot.touchmove=(t)=>{t.input.lastTouch=Date.now(),de(t,"pointer")};Ot.contextmenu=(t)=>eo(t);function la(t,e){if(t.composing)return!0;if(vt&&Math.abs(Date.now()-t.input.compositionEndedAt)<500)return t.input.compositionEndedAt=-200000000,!0;return!1}var Au=ce?5000:-1;Mt.compositionstart=Mt.compositionupdate=(t)=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof R&&e.selection.empty&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some((r)=>r.type.spec.inclusive===!1)||wt&&Tl&&Eu(t)))t.markCursor=t.state.storedMarks||n.marks(),Er(t,!0),t.markCursor=null;else if(Er(t,!e.selection.empty),zt&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=t.domSelectionRange();for(let{focusNode:i,focusOffset:o}=r;i&&E(i)&&o!=0;){let s=o<0?i.lastChild:i.childNodes[o-1];if(!s)break;if(pt(s)){let l=t.domSelection();if(l)l.collapse(s,s.nodeValue.length);break}else i=s,o=-1}}t.input.composing=!0}aa(t,Au)};function Eu(t){let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(!e||!E(e)||n>=e.childNodes.length)return!1;let r=e.childNodes[n];return E(r)&&r.contentEditable=="false"}Mt.compositionend=(t,e)=>{if(t.composing){if(t.input.composing=!1,t.input.compositionEndedAt=Date.now(),t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.badSafariComposition)t.domObserver.forceFlush();else if(t.input.compositionPendingChanges)Promise.resolve().then(()=>t.domObserver.flush());t.input.compositionID++,aa(t,20)}};function aa(t,e){if(clearTimeout(t.input.composingTimeout),e>-1)t.input.composingTimeout=setTimeout(()=>Er(t),e)}function ca(t){if(t.composing)t.input.composing=!1,t.input.compositionEndedAt=Date.now();while(t.input.compositionNodes.length>0)t.input.compositionNodes.pop().markParentsDirty()}function Nu(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=Md(e.focusNode,e.focusOffset),r=Ad(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let i=r.pmViewDesc,o=t.domObserver.lastChangedTextNode;if(n==o||r==o)return o;if(!i||!i.isText(r.nodeValue))return r;else if(t.input.compositionNode==r){let s=n.pmViewDesc;if(!(!s||!s.isText(n.nodeValue)))return r}}return n||r}function Er(t,e=!1){if(ce&&t.domObserver.flushingSoon>=0)return;if(t.domObserver.forceFlush(),ca(t),e||t.docView&&t.docView.dirty){let n=Xi(t),r=t.state.selection;if(n&&!n.eq(r))t.dispatch(t.state.tr.setSelection(n));else if((t.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent)t.dispatch(t.state.tr.deleteSelection());else t.updateState(t.state);return!0}return!1}function Du(t,e){if(!t.dom.parentNode)return;let n=t.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(e),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{if(n.parentNode)n.parentNode.removeChild(n);t.focus()},50)}var Hn=Lt&&ve<15||mn&&Td<604;Ot.copy=Mt.cut=(t,e)=>{let n=e,r=t.state.selection,i=n.type=="cut";if(r.empty)return;let o=Hn?null:n.clipboardData,s=r.content(),{dom:l,text:c}=Qi(t,s);if(o)n.preventDefault(),o.clearData(),o.setData("text/html",l.innerHTML),o.setData("text/plain",c);else Du(t,l);if(i)t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Tu(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function Ru(t,e){if(!t.dom.parentNode)return;let n=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,r=t.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));if(!n)r.contentEditable="true";r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{if(t.focus(),r.parentNode)r.parentNode.removeChild(r);if(n)Kn(t,r.value,null,i,e);else Kn(t,r.textContent,r.innerHTML,i,e)},50)}function Kn(t,e,n,r,i){let o=Xl(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",(c)=>c(t,i,o||I.empty)))return!0;if(!o)return!1;let s=Tu(o),l=s?t.state.tr.replaceSelectionWith(s,r):t.state.tr.replaceSelection(o);return t.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function da(t){let e=t.getData("text/plain")||t.getData("Text");if(e)return e;let n=t.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Mt.paste=(t,e)=>{let n=e;if(t.composing&&!ce)return;let r=Hn?null:n.clipboardData,i=t.input.shiftKey&&t.input.lastKeyCode!=45;if(r&&Kn(t,da(r),r.getData("text/html"),i,n))n.preventDefault();else Ru(t,n)};class ro{constructor(t,e,n){this.slice=t,this.move=e,this.node=n}}var Lu=Ut?"altKey":"ctrlKey";function ua(t,e){let n;return t.someProp("dragCopies",(r)=>{n=n||r(e)}),n!=null?!n:!e[Lu]}Ot.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r)r.done();if(!n.dataTransfer)return;let i=t.state.selection,o=i.empty?null:t.posAtCoords(Gn(n)),s;if(o&&o.pos>=i.from&&o.pos<=(i instanceof T?i.to-1:i.to));else if(r&&r.mightDrag)s=T.create(t.state.doc,r.mightDrag.pos);else if(n.target&&E(n.target)){let h=t.docView.nearestDesc(n.target,!0);if(h&&h.node.type.spec.draggable&&h!=t.docView)s=T.create(t.state.doc,h.posBefore)}let l=(s||t.state.selection).content(),{dom:c,text:d,slice:f}=Qi(t,l);if(!n.dataTransfer.files.length||!wt||Dl>120)n.dataTransfer.clearData();if(n.dataTransfer.setData(Hn?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",!Hn)n.dataTransfer.setData("text/plain",d);t.dragging=new ro(f,ua(t,n),s)};Ot.dragend=(t)=>{let e=t.dragging;window.setTimeout(()=>{if(t.dragging==e)t.dragging=null},50)};Mt.dragover=Mt.dragenter=(t,e)=>e.preventDefault();Mt.drop=(t,e)=>{try{Pu(t,e,t.dragging)}finally{t.dragging=null}};function Pu(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(Gn(e));if(!r)return;let i=t.state.doc.resolve(r.pos),o=n&&n.slice;if(o)t.someProp("transformPasted",(m)=>{o=m(o,t,!1)});else o=Xl(t,da(e.dataTransfer),Hn?null:e.dataTransfer.getData("text/html"),!1,i);let s=!!(n&&ua(t,e));if(t.someProp("handleDrop",(m)=>m(t,e,o||I.empty,s))){e.preventDefault();return}if(!o)return;e.preventDefault();let l=o?vr(t.state.doc,i.pos,o):i.pos;if(l==null)l=i.pos;let c=t.state.tr;if(s){let{node:m}=n;if(m)m.replace(c);else c.deleteSelection()}let d=c.mapping.map(l),f=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,h=c.doc;if(f)c.replaceRangeWith(d,d,o.content.firstChild);else c.replaceRange(d,d,o);if(c.doc.eq(h))return;let p=c.doc.resolve(d);if(f&&T.isSelectable(o.content.firstChild)&&p.nodeAfter&&p.nodeAfter.sameMarkup(o.content.firstChild))c.setSelection(new T(p));else{let m=c.mapping.map(l);c.mapping.maps[c.mapping.maps.length-1].forEach((g,b,y,S)=>m=S),c.setSelection(Gi(t,p,c.doc.resolve(m)))}t.focus(),t.dispatch(c.setMeta("uiEvent","drop"))}Ot.focus=(t)=>{if(t.input.lastFocus=Date.now(),!t.focused)t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout(()=>{if(t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange()))ue(t)},20)};Ot.blur=(t,e)=>{let n=e;if(t.focused){if(t.domObserver.stop(),t.dom.classList.remove("ProseMirror-focused"),t.domObserver.start(),n.relatedTarget&&t.dom.contains(n.relatedTarget))t.domObserver.currentSelection.clear();t.focused=!1}};Ot.beforeinput=(t,e)=>{if(ce&&e.inputType=="deleteContentBackward"){t.domObserver.flushSoon();let{domChangeCount:r}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=r)return;if(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",(o)=>o(t,Je(8,"Backspace"))))return;let{$cursor:i}=t.state.selection;if(i&&i.pos>0)t.dispatch(t.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let t in Mt)Ot[t]=Mt[t];function Yn(t,e){if(t==e)return!0;for(let n in t)if(t[n]!==e[n])return!1;for(let n in e)if(!(n in t))return!1;return!0}class Nr{constructor(t){this.frag=t,this.index=0,this.off=0}nodeAt(t){while(this.off<=t&&this.index=o?null:new _t(i,o,this)}valid(t,e){return e.from=t&&(!i||i(s.spec)))n.push(s.copy(s.from+r,s.to+r))}for(let o=0;ot){let s=this.children[o]+1;this.children[o+2].findInner(t-s,e-s,n,r+s,i)}}map(t,e,n){if(this==xt||t.maps.length==0)return this;return this.mapInner(t,e,0,0,n||Ke)}mapInner(t,e,n,r,i){let o;if(this.local.length){let s=new Nr(e.content);for(let l=0;l{let c=l+n,d;if(!(d=ha(e,s,c)))return;if(!r)r=this.children.slice();while(is&&f.to=t){if(this.children[s]==t)n=this.children[s+2];break}let i=t+1,o=i+e.content.size;for(let s=0;si&&l.type instanceof Oe){let c=Math.max(i,l.from)-i,d=Math.min(o,l.to)-i;if(cr.map(t,e,Ke));return Ie.from(n)}forChild(t,e){if(e.isLeaf)return G.empty;let n=[];for(let r=0;re instanceof G)?t:t.reduce((e,n)=>e.concat(n instanceof G?n:n.members),[]))}}forEachSet(t){for(let e=0;e{let y=b-g-(m-p);for(let S=0;SL+f-h)continue;let U=l[S]+f-h;if(m>=U)l[S+1]=p<=U?-2:-1;else if(p>=f&&y)l[S]+=y,l[S+1]+=y}h+=y}),f=n.maps[d].map(f,-1)}let c=!1;for(let d=0;d=r.content.size){c=!0;continue}let p=n.map(t[d+1]+o,-1),m=p-i,{index:g,offset:b}=r.content.findIndex(h),y=r.maybeChild(g);if(y&&b==h&&b+y.nodeSize==m){let S=l[d+2].mapInner(n,y,f+1,t[d]+o+1,s);if(S!=xt)l[d]=h,l[d+1]=m,l[d+2]=S;else l[d+1]=-2,c=!0}else c=!0}if(c){let d=zu(l,t,e,n,i,o,s),f=Tr(d,r,0,s);e=f.local;for(let h=0;hn&&s.to{let d=ha(t,l,c+n);if(d){o=!0;let f=Tr(d,l,n+c+1,r);if(f!=xt)i.push(c,c+l.nodeSize,f)}});let s=fa(o?pa(t):t,-n).sort(Ye);if(s.length){let l=new Nr(e.content);for(let c=0;c0)e++;t.splice(e,0,n)}function Ri(t){let e=[];if(t.someProp("decorations",(n)=>{let r=n(t.state);if(r&&r!=xt)e.push(r)}),t.cursorWrapper)e.push(G.create(t.state.doc,[t.cursorWrapper.deco]));return Ie.from(e)}var Fu={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Vu=Lt&&ve<=11;class _a{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(t){this.anchorNode=t.anchorNode,this.anchorOffset=t.anchorOffset,this.focusNode=t.focusNode,this.focusOffset=t.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(t){return t.anchorNode==this.anchorNode&&t.anchorOffset==this.anchorOffset&&t.focusNode==this.focusNode&&t.focusOffset==this.focusOffset}}class ga{constructor(t,e){if(this.view=t,this.handleDOMChange=e,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new _a,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver((n)=>{for(let r=0;rr.type=="childList"&&r.removedNodes.length||r.type=="characterData"&&r.oldValue.length>r.target.nodeValue.length))this.flushSoon();else if(vt&&t.composing&&n.some((r)=>r.type=="childList"&&r.target.nodeName=="TR"))t.input.badSafariComposition=!0,this.flushSoon();else this.flush()}),Vu)this.onCharData=(n)=>{this.queue.push({target:n.target,type:"characterData",oldValue:n.prevValue}),this.flushSoon()};this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){if(this.flushingSoon<0)this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20)}forceFlush(){if(this.flushingSoon>-1)window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush()}start(){if(this.observer)this.observer.takeRecords(),this.observer.observe(this.view.dom,Fu);if(this.onCharData)this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData);this.connectSelection()}stop(){if(this.observer){let t=this.observer.takeRecords();if(t.length){for(let e=0;ethis.flush(),20)}this.observer.disconnect()}if(this.onCharData)this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData);this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(!pl(this.view))return;if(this.suppressingSelectionUpdates)return ue(this.view);if(Lt&&ve<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&Xe(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset))return this.flushSoon()}this.flush()}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(t){if(!t.focusNode)return!0;let e=new Set,n;for(let i=t.focusNode;i;i=gn(i))e.add(i);for(let i=t.anchorNode;i;i=gn(i))if(e.has(i)){n=i;break}let r=n&&this.view.docView.nearestDesc(n);if(r&&r.ignoreMutation({type:"selection",target:pt(n)?n.parentNode:n}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let t of this.observer.takeRecords())this.queue.push(t);return this.queue}flush(){let{view:t}=this;if(!t.docView||this.flushingSoon>-1)return;let e=this.pendingRecords();if(e.length)this.queue=[];let n,r=!1;if(!this.suppressingSelectionUpdates&&pl(t))n=t.domSelectionRange(),r=!this.currentSelection.eq(n)&&!this.ignoreSelectionChange(n);let i=-1,o=-1,s=!1,l=[];if(t.editable)for(let d=0;dd.nodeName=="BR")&&(t.input.lastKeyCode==8||t.input.lastKeyCode==46||wt&&(t.composing||t.input.compositionEndedAt>Date.now()-50)&&e.some((d)=>d.type=="childList"&&d.removedNodes.length))){for(let d of l)if(d.nodeName=="BR"&&d.parentNode){let f=d.nextSibling;while(f&&E(f)){if(f.contentEditable=="false"){d.parentNode.removeChild(d);break}f=f.firstChild}}}else if(zt&&l.length){let d=l.filter((f)=>f.nodeName=="BR");if(d.length==2){let[f,h]=d;if(f.parentNode&&f.parentNode.parentNode==h.parentNode)h.remove();else f.remove()}else{let{focusNode:f}=this.currentSelection;for(let h of d){let p=h.parentNode;if(p&&p.nodeName=="LI"&&(!f||Uu(t,f)!=p))h.remove()}}}let c=null;if(i<0&&r&&t.input.lastFocus>Date.now()-200&&Math.max(t.input.lastTouch,t.input.lastClick.time)-1||r){if(i>-1)t.docView.markDirty(i,o),Wu(t);if(t.input.badSafariComposition)t.input.badSafariComposition=!1,$u(t,l);if(this.handleDOMChange(i,o,s,l),t.docView&&t.docView.dirty)t.updateState(t.state);else if(n&&!this.currentSelection.eq(n))ue(t);if(n)this.currentSelection.set(n)}}registerMutation(t,e){if(e.indexOf(t.target)>-1)return null;let n=this.view.docView.nearestDesc(t.target);if(t.type=="attributes"&&(n==this.view.docView||t.attributeName=="contenteditable"||t.attributeName=="style"&&!t.oldValue&&!t.target.getAttribute("style")))return null;if(!n||n.ignoreMutation(t))return null;if(t.type=="childList"){for(let d=0;do;S--){let L=i.childNodes[S-1],U=L.pmViewDesc;if(L.nodeName=="BR"&&!U){s=S;break}if(!U||U.size)break}let p=t.state.doc,m=t.someProp("domParser")||rn.fromSchema(t.state.schema),g=p.resolve(l),b=null,y=m.parse(i,{topNode:g.parent,topMatch:g.parent.contentMatchAt(g.index()),topOpen:!0,from:o,to:s,preserveWhitespace:g.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:ju(r),context:g});if(f&&f[0].pos!=null){let S=f[0].pos,L=f[1]&&f[1].pos;if(L==null)L=S;b={anchor:S+l,head:L+l}}return{doc:y,sel:b,from:l,to:c}}var ju=(t)=>(e)=>{let n=e.pmViewDesc;if(n)return n.parseRule(t);else if(e.nodeName=="BR"&&e.parentNode){if(vt&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||vt&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},Hu=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function Ku(t,e,n,r,i){let o=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let z=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,Y=Xi(t,z);if(Y&&!t.state.selection.eq(Y)){if(wt&&ce&&t.input.lastKeyCode===13&&Date.now()-100P(t,Je(13,"Enter"))))return;let Z=t.state.tr.setSelection(Y);if(z=="pointer")Z.setMeta("pointer",!0);else if(z=="key")Z.scrollIntoView();if(o)Z.setMeta("composition",o);t.dispatch(Z)}return}let s=t.state.doc.resolve(e),l=s.sharedDepth(n);e=s.before(l+1),n=t.state.doc.resolve(n).after(l+1);let c=t.state.selection,d=Ju(t,e,n,i),f=t.state.doc,h=f.slice(d.from,d.to),p,m;if(t.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ce)&&i.some((z)=>E(z)&&!Hu.test(z.nodeName))&&(!g||g.endA>=g.endB)&&t.someProp("handleKeyDown",(z)=>z(t,Je(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!g)if(r&&c instanceof R&&!c.empty&&c.$head.sameParent(c.$anchor)&&!t.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))g={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let z=Sl(t,t.state.doc,d.sel);if(z&&!z.eq(t.state.selection)){let Y=t.state.tr.setSelection(z);if(o)Y.setMeta("composition",o);t.dispatch(Y)}}return}if(t.state.selection.fromt.state.selection.from&&g.start<=t.state.selection.from+2&&t.state.selection.from>=d.from)g.start=t.state.selection.from;else if(g.endA=t.state.selection.to-2&&t.state.selection.to<=d.to)g.endB+=t.state.selection.to-g.endA,g.endA=t.state.selection.to}if(Lt&&ve<=11&&g.endB==g.start+1&&g.endA==g.start&&g.start>d.from&&d.doc.textBetween(g.start-d.from-1,g.start-d.from+1)=="  ")g.start--,g.endA--,g.endB--;let b=d.doc.resolveNoCache(g.start-d.from),y=d.doc.resolveNoCache(g.endB-d.from),S=f.resolve(g.start),L=b.sameParent(y)&&b.parent.inlineContent&&S.end()>=g.endA;if((mn&&t.input.lastIOSEnter>Date.now()-225&&(!L||i.some((z)=>z.nodeName=="DIV"||z.nodeName=="P"))||!L&&Gu(d.doc,b.pos,y.pos))&&t.someProp("handleKeyDown",(z)=>z(t,Je(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>g.start&&(L?g.endA>g.start&&g.endB==g.start:Xu(f,g.start,g.endA,b,y))&&t.someProp("handleKeyDown",(z)=>z(t,Je(8,"Backspace")))){if(ce&&wt)t.domObserver.suppressSelectionUpdates();return}if(wt&&g.endB==g.start)t.input.lastChromeDelete=Date.now();if(ce&&!L&&b.start()!=y.start()&&y.parentOffset==0&&b.depth==y.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==g.endA)g.endB-=2,y=d.doc.resolveNoCache(g.endB-d.from),setTimeout(()=>{t.someProp("handleKeyDown",function(z){return z(t,Je(13,"Enter"))})},20);let U=g.start,et=g.endA,at=(z)=>{let Y=z||t.state.tr.replace(U,et,d.doc.slice(g.start-d.from,g.endB-d.from));if(d.sel){let Z=Sl(t,Y.doc,d.sel);if(Z&&!(wt&&t.composing&&Z.empty&&(g.start!=g.endB||t.input.lastChromeDeleteue(t),20);let z=at(t.state.tr.delete(U,et)),Y=f.resolve(g.start).marksAcross(f.resolve(g.endA));if(Y)z.ensureMarks(Y);t.dispatch(z)}else if(g.endA==g.endB&&(Ft=Yu(b.parent.content.cut(b.parentOffset,y.parentOffset),S.parent.content.cut(S.parentOffset,g.endA-S.start())))){let z=at(t.state.tr);if(Ft.type=="add")z.addMark(U,et,Ft.mark);else z.removeMark(U,et,Ft.mark);t.dispatch(z)}else if(b.parent.child(b.index()).isText&&b.index()==y.index()-(y.textOffset?0:1)){let z=b.parent.textBetween(b.parentOffset,y.parentOffset),Y=()=>at(t.state.tr.insertText(z,U,et));if(!t.someProp("handleTextInput",(Z)=>Z(t,U,et,z,Y)))t.dispatch(Y())}else t.dispatch(at());else t.dispatch(at())}function Sl(t,e,n){if(Math.max(n.anchor,n.head)>e.content.size)return null;return Gi(t,e.resolve(n.anchor),e.resolve(n.head))}function Yu(t,e){let n=t.firstChild.marks,r=e.firstChild.marks,i=n,o=r,s,l,c;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&o.length==1)l=o[0],s="remove",c=(f)=>f.mark(l.removeFromSet(f.marks));else return null;let d=[];for(let f=0;fn||Li(s,!0,!1){if(o.isTextblock&&s>=e&&s0&&(e||t.indexAfter(r)==t.node(r).childCount))r--,i++,e=!1;if(n){let o=t.node(r).maybeChild(t.indexAfter(r));while(o&&!o.isLeaf)o=o.firstChild,i++}return i}function Qu(t,e,n,r,i){let o=t.findDiffStart(e,n),s=n+t.size,l=n+e.size;if(o==null)return null;let{a:c,b:d}=t.findDiffEnd(e,s,l);if(i=="end"){let f=Math.max(0,o-Math.min(c,d));r-=c+f-o}if(c=c?o-r:0;o-=f,d=o+(d-c),c=o}else if(d=d?o-r:0;o-=f,c=o+(c-d),d=o}return{start:o,endA:c,endB:d}}class Zn{constructor(t,e){if(this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new na,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=e,this.state=e.state,this.directPlugins=e.plugins||[],this.directPlugins.forEach(El),this.dispatch=this.dispatch.bind(this),this.dom=t&&t.mount||document.createElement("div"),t){if(t.appendChild)t.appendChild(this.dom);else if(typeof t=="function")t(this.dom);else if(t.mount)this.mounted=!0}this.editable=Ml(this),Ol(this),this.nodeViews=Al(this),this.docView=al(this.state.doc,Cl(this),Ri(this),this.dom,this),this.domObserver=new ga(this,(n,r,i,o)=>Ku(this,n,r,i,o)),this.domObserver.start(),bu(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let t=this._props;this._props={};for(let e in t)this._props[e]=t[e];this._props.state=this.state}return this._props}update(t){if(t.handleDOMEvents!=this._props.handleDOMEvents)ji(this);let e=this._props;if(this._props=t,t.plugins)t.plugins.forEach(El),this.directPlugins=t.plugins;this.updateStateInner(t.state,e)}setProps(t){let e={};for(let n in this._props)e[n]=this._props[n];e.state=this.state;for(let n in t)e[n]=t[n];this.update(e)}updateState(t){this.updateStateInner(t,this._props)}updateStateInner(t,e){var n;let r=this.state,i=!1,o=!1;if(t.storedMarks&&this.composing)ca(this),o=!0;this.state=t;let s=r.plugins!=t.plugins||this._props.plugins!=e.plugins;if(s||this._props.plugins!=e.plugins||this._props.nodeViews!=e.nodeViews){let p=Al(this);if(tf(p,this.nodeViews))this.nodeViews=p,i=!0}if(s||e.handleDOMEvents!=this._props.handleDOMEvents)ji(this);this.editable=Ml(this),Ol(this);let l=Ri(this),c=Cl(this),d=r.plugins!=t.plugins&&!r.doc.eq(t.doc)?"reset":t.scrollToSelection>r.scrollToSelection?"to selection":"preserve",f=i||!this.docView.matchesNode(t.doc,c,l);if(f||!t.selection.eq(r.selection))o=!0;let h=d=="preserve"&&o&&this.dom.style.overflowAnchor==null&&Pd(this);if(o){this.domObserver.stop();let p=f&&(Lt||wt)&&!this.composing&&!r.selection.empty&&!t.selection.empty&&Zu(r.selection,t.selection);if(f){let g=wt?this.trackWrites=this.domSelectionRange().focusNode:null;if(this.composing)this.input.compositionNode=Nu(this);if(i||!this.docView.update(t.doc,c,l,this))this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=al(t.doc,c,l,this.dom,this);if(g&&(!this.trackWrites||!this.dom.contains(this.trackWrites)))p=!0}let m=this.input.mouseDown;if(p||!(m&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&ru(this)&&m.delaySelUpdate()))ue(this,p);else Hl(this,t.selection),this.domObserver.setCurSelection();this.domObserver.start()}if(this.updatePluginViews(r),((n=this.dragging)===null||n===void 0?void 0:n.node)&&!r.doc.eq(t.doc))this.updateDraggedNode(this.dragging,r);if(d=="reset")this.dom.scrollTop=0;else if(d=="to selection")this.scrollToSelection();else if(h)Bd(h)}scrollToSelection(){let t=this.domSelectionRange().focusNode;if(!t||!Ge(this.dom,t));else if(this.someProp("handleScrollToSelection",(e)=>e(this)));else if(this.state.selection instanceof T){let e=this.docView.domAfterPos(this.state.selection.from);if(E(e))rl(this,e.getBoundingClientRect(),t)}else rl(this,this.coordsAtPos(this.state.selection.head,1),t)}destroyPluginViews(){let t;while(t=this.pluginViews.pop())if(t.destroy)t.destroy()}updatePluginViews(t){if(!t||t.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let e=0;e0&&ie.ownerDocument.getSelection();return this._root=e}}return t||document}updateRoot(){this._root=null}posAtCoords(t){return Ud(this,t)}coordsAtPos(t,e=1){return zl(this,t,e)}domAtPos(t,e=0){return this.docView.domFromPos(t,e)}nodeDOM(t){let e=this.docView.descAt(t);return e?e.nodeDOM:null}posAtDOM(t,e,n=-1){let r=this.docView.posFromDOM(t,e,n);if(r==null)throw RangeError("DOM position not inside the editor");return r}endOfTextblock(t,e){return Kd(this,e||this.state,t)}pasteHTML(t,e){return Kn(this,"",t,!1,e||new ClipboardEvent("paste"))}pasteText(t,e){return Kn(this,t,null,!0,e||new ClipboardEvent("paste"))}serializeForClipboard(t){return Qi(this,t)}destroy(){if(!this.docView)return;if(wu(this),this.destroyPluginViews(),this.mounted)this.docView.update(this.state.doc,[],Ri(this),this),this.dom.textContent="";else if(this.dom.parentNode)this.dom.parentNode.removeChild(this.dom);this.docView.destroy(),this.docView=null,Cd()}get isDestroyed(){return this.docView==null}dispatchEvent(t){return ku(this,t)}domSelectionRange(){let t=this.dom.isConnected!==!1&&this.domSelection();if(!t)return{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0};return vt&&this.root.nodeType===11&&Nd(this.dom.ownerDocument)==this.dom&&qu(this,t)||t}domSelection(){return this.root.getSelection()}}Zn.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;if(e)e.call(this,t);else this.updateState(this.state.apply(t))};function Cl(t){let e=Object.create(null);if(e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",(n)=>{if(typeof n=="function")n=n(t.state);if(n){for(let r in n)if(r=="class")e.class+=" "+n[r];else if(r=="style")e.style=(e.style?e.style+";":"")+n[r];else if(!e[r]&&r!="contenteditable"&&r!="nodeName")e[r]=String(n[r])}}),!e.translate)e.translate="no";return[_t.node(0,t.state.doc.content.size,e)]}function Ol(t){if(t.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),t.cursorWrapper={dom:e,deco:_t.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function Ml(t){return!t.someProp("editable",(e)=>e(t.state)===!1)}function Zu(t,e){let n=Math.min(t.$anchor.sharedDepth(t.head),e.$anchor.sharedDepth(e.head));return t.$anchor.start(n)!=e.$anchor.start(n)}function Al(t){let e=Object.create(null);function n(r){for(let i in r)if(!Object.prototype.hasOwnProperty.call(e,i))e[i]=r[i]}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function tf(t,e){let n=0,r=0;for(let i in t){if(t[i]!=e[i])return!0;n++}for(let i in e)r++;return n!=r}function El(t){if(t.spec.state||t.spec.filterTransaction||t.spec.appendTransaction)throw RangeError("Plugins passed directly to the view must not have a state component")}var so=Symbol("Equality");var nf=Object.keys;var lo=(t)=>nf(t).length;var ma=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var wn=(t,e)=>{if(t===e)return!0;if(t==null||e==null||t.constructor!==e.constructor&&(t.constructor||Object)!==(e.constructor||Object))return!1;if(t[so]!=null)return t[so](e);switch(t.constructor){case ArrayBuffer:t=new Uint8Array(t),e=new Uint8Array(e);case Uint8Array:{if(t.byteLength!==e.byteLength)return!1;for(let n=0;n{let n=0,r=0;while(n0&&of.test(t[n-1]))n--;while(r+n0&&sf.test(t[t.length-r]))r--;return{index:n,remove:t.length-n-r,insert:e.slice(n,e.length-r)}},ba=lf;var uo="doc",af="attributes",fo="children";var er=new WeakMap;function cf(t,e,n,r){let i=n.doc,o=r?t.getContainerById(r):t.getMap(uo),s=!1;if(o.get("nodeName")==null)t.commit(),s=!0,o.set("nodeName",i.type.name);if(tr(o,i,e),s)t.commit({origin:"sys:init"});else t.commit({origin:"loroSyncPlugin"})}function ho(t,e,n){let r=n.get(e.id)??null;if(r!=null)return r;if(e instanceof St){let i=qr(e),o=or(e),s=e.get("nodeName");if(s==null||typeof s!=="string")throw Error("Invalid nodeName");let l=o.toArray().flatMap((c)=>ho(t,c,n)).filter((c)=>c!==null);try{r=t.node(s,i.toJSON(),l),er.set(r,e.id)}catch(c){console.error(c)}}else if(e instanceof Rt){r=[];for(let i of e.toDelta()){if(i.insert==null)continue;try{let o=[];for(let[s,l]of Object.entries(i.attributes??{})){let c=Sa(l);o.push(t.mark(s,c??void 0))}r.push(t.text(i.insert,o))}catch(o){console.error(o)}}}else throw Error("Invalid LoroType");if(r!=null){if(!Array.isArray(r))er.set(r,e.id);n.set(e.id,r)}else n.delete(e.id);return r}function ao(t,e,n,r){return Array.isArray(n)?df(t,e,n,r):pf(t,e,n,r)}function df(t,e,n,r){let i=t.insertContainer(e??t.length,new Rt).getAttached(),o=n.map((s)=>({insert:s.text,attributes:va(s.marks)}));return i.applyDelta(o),r.set(i.id,n),i}function uf(t,e,n){n.set(t.id,e);let r=e.map((c)=>({insert:c.text,attributes:va(c.marks)})),{insert:i,remove:o,index:s}=ba(t.toString(),r.map((c)=>c.insert).join(""));if(o>0)t.delete(s,o);if(i.length)t.insert(s,i);let l=ff(t.toDelta(),r);if(l!=null)t.applyDelta(l)}function ff(t,e){let n=[],r=0,i=0,o=0,s=0;while(r0){let f=hf(l.attributes??{},c.attributes);n.push(f!=null?{retain:d,attributes:f}:{retain:d})}if(i+=d,i===l.insert.length)r+=1,i=0;if(s+=d,s===c.insert.length)o+=1,s=0}while(n.length>0&&n[n.length-1].attributes==null)n.pop();return n.length>0?n:null}function hf(t,e){let n=null;for(let[r,i]of Object.entries(e))if(!wn(t[r],i))n=n??{},n[r]=i;for(let r of Object.keys(t))if(!(r in e)&&t[r]!=null)n=n??{},n[r]=null;return n}function va(t){let e={};for(let n of t)e[n.type.name]=n.attrs;return e}function Sa(t){if(t!=null&&typeof t==="object"&&!Array.isArray(t)&&!(t instanceof Uint8Array))return t;return null}function Ca(t,e){let n=t.toDelta();return n.length===e.length&&n.every((r,i)=>r.insert===e[i].text&&Object.keys(r.attributes||{}).length===e[i].marks.length&&e[i].marks.every((o)=>{let s=Sa((r.attributes||{})[o.type.name]);return s!=null&&po(s,o.attrs)}))}function nr(t,e){if(t instanceof St){if(Array.isArray(e)||!Br(t,e))return!1;let n=or(t),r=Wr(e);return n.length===r.length&&po(qr(t).toJSON(),e.attrs)&&r.every((i,o)=>nr(n.get(o),i))}return t instanceof Rt&&Array.isArray(e)&&Ca(t,e)}function po(t,e){let n=Object.keys(t).filter((i)=>t[i]!==null),r=n.length===Object.keys(e).filter((i)=>e[i]!==null).length;for(let i=0;r&&i{if(r.isText){if(n==null)n=[],e.push(n);n.push(r)}else e.push(r),n=null}),e}function wa(t,e,n){let r=or(t),i=r.length,o=Wr(e),s=o.length,l=Math.min(i,s),c=0,d=0,f=!1;for(;cao(s,null,l,r)),er.set(n,i.id),r.set(i.id,n),i}function tr(t,e,n){if(n.set(t.id,e),er.set(e,t.id),!Br(t,e))throw Error("node name mismatch!");_f(t,e,n),gf(t,e,n)}function qr(t){return t.getOrCreateContainer(af,new St)}function _f(t,e,n){let r=qr(t),i=new Set(r.keys()),o=e.attrs;for(let[s,l]of Object.entries(o)){if(l!==null){if(!wn(r.get(s),l))r.set(s,l)}else r.delete(s);i.delete(s)}for(let s of i)r.delete(s)}function or(t){return t.getOrCreateContainer(fo,new ee)}function gf(t,e,n){let r=or(t),i=r.length,o=Wr(e),s=o.length,l=Math.min(s,i),c=0,d=0;for(;c0&&s-c-d>0){let h=r.get(c),p=o[c],m=r.get(i-d-1),g=o[s-d-1];if(h instanceof Rt&&Array.isArray(p)){if(!Ca(h,p))uf(h,p,n);c+=1}else{let b=h instanceof St&&Br(h,p),y=m instanceof St&&Br(m,g);if(b&&y){let S=wa(h,p,n),L=wa(m,g,n);if(S.foundMappedChild&&!L.foundMappedChild)y=!1;else if(L.foundMappedChild&&!S.foundMappedChild)b=!1;else if(S.factor0)r.toArray().slice(c,c+f).filter(ie).forEach((h)=>n.delete(h.id)),r.delete(c,f);if(c+dao(r,c+p,h,n))}function mf(t,e,n){for(let r of e.events){let i=t.getContainerById(r.target);n.delete(i.id);let o=i.parent();while(o)n.delete(o.id),o=o.parent()}}function bf(t,e,n){let r=t.state.doc,i=r.content.size;if(e<0||e>i||n!=null&&(n<0||n>i))return;let o=r.resolve(e),s=n!=null?r.resolve(n):void 0,l=R.between(o,s||o);t.dispatch(t.state.tr.setSelection(l))}var yt=new fn("loro-sync"),wf=(t,e,n)=>{let r=n.getSelection||((l)=>l.selection),i=n.createSelection||((l)=>({class:"loro-selection","data-peer":l,style:"background-color: rgba(228, 208, 102, 0.5)"})),o=n.createCursor||((l)=>{let c=e.getAll()[l],d=document.createElement("span");d.classList.add("ProseMirror-loro-cursor"),d.setAttribute("style",`border-color: ${c?.user?.color??l.slice(0,6)}`);let f=document.createElement("div");f.setAttribute("style",`background-color: ${c?.user?.color??l.slice(0,6)}`),f.insertBefore(document.createTextNode(c?.user?.name??l.slice(0,6)),null);let h=document.createTextNode("⁠"),p=document.createTextNode("⁠");return d.insertBefore(h,null),d.insertBefore(f,null),d.insertBefore(p,null),d}),s=new st({key:t,state:{init(l,c){return ya(c,e,s,i,o)},apply(l,c,d,f){let h=yt.getState(f),p=l.getMeta(t);if(h&&h.changedBy!=="local"||p&&p.presenceUpdated)return ya(f,e,s,i,o);return c.map(l.mapping,l.doc)}},props:{decorations:(l)=>s.getState(l)},view:(l)=>{let c=(h)=>{if(h!=="local")setTimeout(()=>{if(l.isDestroyed)return;let p=l.state.tr;p.setMeta(t,{presenceUpdated:!0}),l.dispatch(p)},0)},d=()=>{let h=yt.getState(l.state),p=e.getLocal();if(h?.doc==null)return;let m=l.state.doc;if(l.hasFocus()){let{anchor:g,focus:b}=Fr(m,r(l.state),h);if(p==null||!co(p.anchor,g)||!co(p.focus,b))e.setLocal({user:n.user,anchor:g,focus:b})}else if(p?.focus!=null)e.setLocal({})},f=e.subscribe(c);return l.dom.addEventListener("focusin",d),l.dom.addEventListener("focusout",d),{update:d,destroy:()=>{l.dom.removeEventListener("focusin",d),l.dom.removeEventListener("focusout",d),f(),e.setLocal({})}}}});return s};function ya(t,e,n,r,i){let o=e.getAll(),s=[],l=yt.getState(t);if(!l)return G.create(t.doc,[]);let c=l.doc,d=c.peerIdStr;for(let[f,h]of Object.entries(o)){if(f===d)continue;if(!h.anchor||!h.focus)continue;let[p,m]=Vr(h.focus,c,l.mapping);if(s.push(_t.widget(p,i(f))),!co(h.anchor,h.focus)){let[g,b]=Vr(h.anchor,c,l.mapping);if(s.push(_t.inline(Math.min(g,p),Math.max(g,p),r(f))),m||b){let y=e.getLocal();e.setLocal({...y?.user&&{user:y.user},anchor:b||h.anchor,focus:m||h.focus})}}else if(m){let g=e.getLocal();e.setLocal({...g?.user&&{user:g.user},focus:m,anchor:m})}}return G.create(t.doc,s)}function Fr(t,e,n){let r=ka(t,e.anchor,n.doc,n.mapping);return{anchor:r,focus:e.head==e.anchor?r:ka(t,e.head,n.doc,n.mapping)}}function yf(t,e){for(let[n,r]of t.entries())if(r===e)return n}function ka(t,e,n,r){let i=t.resolve(e),o=i.node(i.depth),s=i.parentOffset,l=er.get(o)??yf(r,o);if(!l){if(e>1)console.error("Cannot find the loroNode");return}let c=n.getMap(l).get(fo);if(c.length==0)return c.getCursor(0);let d=s,f=0;while(d>=0&&f{i+=p.nodeSize});else if(h!=null)i+=h.nodeSize;else console.error(d,c.toJSON())}o=s.id,s=s.parent()?.parent(),i+=1}else throw Error("Unreachable code")}return[i,l]}function co(t,e){if(!t&&!e)return!0;if(!t||!e)return!1;let n=t.pos(),r=e.pos();return n?.peer===r?.peer&&n?.counter===r?.counter&&t.containerId()===e.containerId()}var xa=new WeakSet;function kf(t){return Object.fromEntries(Object.entries(t.marks).map(([e,n])=>[e,{expand:n.spec.inclusive!==!1?"after":"none"}]))}function Oa(t,e){if(xa.has(t))return;xa.add(t),t.configTextStyle(kf(e))}var rr=new fn("loro-undo"),Ma=(t)=>new st({key:yt,props:{editable:(e)=>yt.getState(e)?.snapshot==null},state:{init:(e,n)=>(Oa(t.doc,n.schema),{doc:t.doc,mapping:t.mapping??new Map,changedBy:"local",containerId:t.containerId}),apply:(e,n,r,i)=>{let o=e.getMeta(yt),s=rr.getState(r);if(o?.type==="non-local-updates")n.changedBy="import";else n.changedBy="local";switch(o?.type){case"doc-changed":if(!s?.isUndoing.current)cf(n.doc,n.mapping,i,t.containerId);break;case"update-state":n={...n,...o.state},n.doc.commit({origin:"sys:init",timestamp:Date.now()});break;default:break}return n}},appendTransaction:(e,n,r)=>{if(e.some((i)=>i.docChanged))return r.tr.setMeta(yt,{type:"doc-changed"});return null},view:(e)=>{let n=setTimeout(()=>xf(e),0);return{update:(r,i)=>{},destroy:()=>{clearTimeout(n)}}}});function xf(t){if(t.isDestroyed)return;let e=yt.getState(t.state),n=e.docSubscription;if(n?.(),e.containerId)n=e.doc.getContainerById(e.containerId).subscribe((o)=>{Ia(t,o)});else n=e.doc.subscribe((o)=>Ia(t,o));let r=e.containerId?e.doc.getContainerById(e.containerId):e.doc.getMap(uo),i=new Map;if(r.size===0){let o=t.state.tr.delete(0,t.state.doc.content.size);o.setMeta(yt,{type:"update-state",state:{mapping:i,docSubscription:n,snapshot:null}}),t.dispatch(o)}else{let o=t.state.schema,s=ho(o,r,i),l=t.state.tr.replace(0,t.state.doc.content.size,new I(k.from(s),0,0));l.setMeta(yt,{type:"update-state",state:{mapping:i,docSubscription:n,snapshot:null}}),t.dispatch(l)}}function Ia(t,e){if(t.isDestroyed)return;let n=yt.getState(t.state);if(n.changedBy=e.by,e.by==="local"&&e.origin!=="undo")return;let r=n.mapping;mf(n.doc,e,r);let i=ho(t.state.schema,n.containerId?n.doc.getContainerById(n.containerId):n.doc.getMap(uo),r),{anchor:o,focus:s}=Fr(t.state.doc,t.state.selection,n),l=t.state.tr.replace(0,t.state.doc.content.size,new I(k.from(i),0,0));if(l.setMeta(yt,{type:"non-local-updates"}),t.dispatch(l),o==null)return;setTimeout(()=>{Aa(t,o,s)})}function Aa(t,e,n){if(t.isDestroyed)return;let r=yt.getState(t.state);if(!r)return;let{doc:i,mapping:o}=r,s=Vr(e,i,o)[0],l=n&&Vr(n,i,o)[0];if(s==null)return;bf(t,s,l)}function ir(t){return ir=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ir(t)}function If(t,e){if(ir(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(ir(r)!="object")return r;throw TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function vf(t){var e=If(t,"string");return ir(e)=="symbol"?e:e+""}function Sf(t,e,n){return(e=vf(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var Ea=class extends gi{constructor(t,e){super(e);Sf(this,"peer",void 0),this.peer=t}setLocal(t){if(!t.anchor&&!t.focus&&!t.user){this.delete(this.peer);return}this.set(this.peer,{anchor:t.anchor?.encode()??null,focus:t.focus?.encode()??null,user:t.user??null})}getLocal(){let t=this.get(this.peer);if(!t)return;return{anchor:t.anchor?Tt.decode(t.anchor):void 0,focus:t.focus?Tt.decode(t.focus):void 0,user:t.user??void 0}}getAll(){let t={};for(let[e,n]of Object.entries(this.getAllStates())){if(!n)continue;t[e]={anchor:n.anchor?Tt.decode(n.anchor):void 0,focus:n.focus?Tt.decode(n.focus):void 0,user:n.user??void 0}}return t}subscribeBy(t){return super.subscribe((e)=>t(e.by))}},Cf=new fn("loro-ephemeral-cursor"),Na=(t,e)=>wf(Cf,Of(t),e),Of=(t)=>({getAll:()=>t.getAll(),getLocal:()=>t.getLocal(),setLocal:(e)=>t.setLocal(e),subscribe:(e)=>t.subscribeBy(e)});var $p=new fn("loro-cursor");var Da=(t)=>{let e=t.undoManager||new nn(t.doc,{}),n={anchor:null,focus:null};return new st({key:rr,state:{init:(r,i)=>(Oa(t.doc,i.schema),e.addExcludeOriginPrefix("sys:init"),{undoManager:e,canUndo:e.canUndo(),canRedo:e.canRedo(),isUndoing:{current:!1}}),apply:(r,i,o,s)=>{let l=rr.getState(o),c=yt.getState(o);if(!l||!c)return i;let d=l.undoManager.canUndo(),f=l.undoManager.canRedo();{let{anchor:h,focus:p}=Fr(o.doc,o.selection,c);n={anchor:h??null,focus:p??null}}return{...i,canUndo:d,canRedo:f}}},view:(r)=>(e.setOnPush((i,o)=>{if(yt.getState(r.state)?.doc==null)return{value:null,cursors:[]};let s=[],l=n;if(!i){let c=yt.getState(r.state);if(c){let{anchor:d,focus:f}=Fr(r.state.doc,r.state.selection,c);l.anchor=d||null,l.focus=f||null}}if(l.anchor)s.push(l.anchor);if(l.focus)s.push(l.focus);return{value:null,cursors:s}}),e.setOnPop((i,o,s)=>{if(yt.getState(r.state)?.doc==null)return;let l=o.cursors[0],c=o.cursors[1];if(l==null)return;setTimeout(()=>{Aa(r,l,c)},0)}),{destroy:()=>{e.setOnPop(),e.setOnPush()}})})};var _o=(t,e)=>{let n=rr.getState(t);if(!n)return!1;if(!e)return n.undoManager.canUndo();return n.isUndoing.current=!0,setTimeout(()=>{n.isUndoing.current=!1},0),n.undoManager.undo()},Ur=(t,e)=>{let n=rr.getState(t);if(!n)return!1;if(!e)return n.undoManager.canRedo();return n.isUndoing.current=!0,setTimeout(()=>{n.isUndoing.current=!1},0),n.undoManager.redo()};var Mf=["p",0],Af=["blockquote",0],Ef=["hr"],Nf=["pre",["code",0]],Df=["br"],Tf={doc:{content:"block+"},paragraph:{content:"inline*",group:"block",parseDOM:[{tag:"p"}],toDOM(){return Mf}},blockquote:{content:"block+",group:"block",defining:!0,parseDOM:[{tag:"blockquote"}],toDOM(){return Af}},horizontal_rule:{group:"block",parseDOM:[{tag:"hr"}],toDOM(){return Ef}},heading:{attrs:{level:{default:1,validate:"number"}},content:"inline*",group:"block",defining:!0,parseDOM:[{tag:"h1",attrs:{level:1}},{tag:"h2",attrs:{level:2}},{tag:"h3",attrs:{level:3}},{tag:"h4",attrs:{level:4}},{tag:"h5",attrs:{level:5}},{tag:"h6",attrs:{level:6}}],toDOM(t){return["h"+ +t.attrs.level,0]}},code_block:{content:"text*",marks:"",group:"block",code:!0,defining:!0,parseDOM:[{tag:"pre",preserveWhitespace:"full"}],toDOM(){return Nf}},text:{group:"inline"},image:{inline:!0,attrs:{src:{validate:"string"},alt:{default:null,validate:"string|null"},title:{default:null,validate:"string|null"}},group:"inline",draggable:!0,parseDOM:[{tag:"img[src]",getAttrs(t){return{src:t.getAttribute("src"),title:t.getAttribute("title"),alt:t.getAttribute("alt")}}}],toDOM(t){let{src:e,alt:n,title:r}=t.attrs;return["img",{src:e,alt:n,title:r}]}},hard_break:{inline:!0,group:"inline",selectable:!1,parseDOM:[{tag:"br"}],toDOM(){return Df}}},Rf=["em",0],Lf=["strong",0],Pf=["code",0],Bf={link:{attrs:{href:{validate:"string"},title:{default:null,validate:"string|null"}},inclusive:!1,parseDOM:[{tag:"a[href]",getAttrs(t){return{href:t.getAttribute("href"),title:t.getAttribute("title")}}}],toDOM(t){let{href:e,title:n}=t.attrs;return["a",{href:e,title:n},0]}},em:{parseDOM:[{tag:"i"},{tag:"em"},{style:"font-style=italic"},{style:"font-style=normal",clearMark:(t)=>t.type.name=="em"}],toDOM(){return Rf}},strong:{parseDOM:[{tag:"strong"},{tag:"b",getAttrs:(t)=>t.style.fontWeight!="normal"&&null},{style:"font-weight=400",clearMark:(t)=>t.type.name=="strong"},{style:"font-weight",getAttrs:(t)=>/^(bold(er)?|[5-9]\d{2,})$/.test(t)&&null}],toDOM(){return Lf}},code:{code:!0,parseDOM:[{tag:"code"}],toDOM(){return Pf}}},$r=new sn({nodes:Tf,marks:Bf});var zf=["ol",0],Ff=["ul",0],Vf=["li",0],Wf={attrs:{order:{default:1,validate:"number"}},parseDOM:[{tag:"ol",getAttrs(t){return{order:t.hasAttribute("start")?+t.getAttribute("start"):1}}}],toDOM(t){return t.attrs.order==1?zf:["ol",{start:t.attrs.order},0]}},qf={parseDOM:[{tag:"ul"}],toDOM(){return Ff}},Uf={parseDOM:[{tag:"li"}],toDOM(){return Vf},defining:!0};function go(t,e){let n={};for(let r in t)n[r]=t[r];for(let r in e)n[r]=e[r];return n}function Ta(t,e,n){return t.append({ordered_list:go(Wf,{content:"list_item+",group:n}),bullet_list:go(qf,{content:"list_item+",group:n}),list_item:go(Uf,{content:e})})}function Ra(t,e=null){return function(n,r){let{$from:i,$to:o}=n.selection,s=i.blockRange(o);if(!s)return!1;let l=r?n.tr:null;if(!$f(l,s,t,e))return!1;if(r)r(l.scrollIntoView());return!0}}function $f(t,e,n,r=null){let i=!1,o=e,s=e.$from.doc;if(e.depth>=2&&e.$from.node(e.depth-1).type.compatibleContent(n)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let c=s.resolve(e.start-2);if(o=new on(c,c,e.depth),e.endIndex=0;f--)o=k.from(n[f].type.create(n[f].attrs,o));t.step(new ft(e.start-(r?2:0),e.end,e.start,e.end,new I(o,0,0),n.length,!0));let s=0;for(let f=0;f=i.depth-3;S--)h=k.from(i.node(S).copy(h));let m=i.indexAfter(-1){if(y>-1)return!1;if(S.isTextblock&&S.content.size==0)y=L+1}),y>-1)b.setSelection(F.near(b.doc.resolve(y)));r(b.scrollIntoView())}return!0}let c=o.pos==i.end()?l.contentMatchAt(0).defaultType:null,d=n.tr.delete(i.pos,o.pos),f=c?[e?{type:t,attrs:e}:null,{type:c}]:void 0;if(!we(d.doc,i.pos,2,f))return!1;if(r)r(d.split(i.pos,2,f).scrollIntoView());return!0}}function Jr(t){return function(e,n){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,(s)=>s.childCount>0&&s.firstChild.type==t);if(!o)return!1;if(!n)return!0;if(r.node(o.depth-1).type==t)return jf(e,n,t,o);else return Hf(e,n,o)}}function jf(t,e,n,r){let i=t.tr,o=r.end,s=r.$to.end(r.depth);if(ob;g--)m-=i.child(g).nodeSize,r.delete(m-1,m+1);let o=r.doc.resolve(n.start),s=o.nodeAfter;if(r.mapping.map(n.end)!=n.start+o.nodeAfter.nodeSize)return!1;let l=n.startIndex==0,c=n.endIndex==i.childCount,d=o.node(-1),f=o.index(-1);if(!d.canReplace(f+(l?0:1),f+1,s.content.append(c?k.empty:k.from(i))))return!1;let h=o.pos,p=h+s.nodeSize;return r.step(new ft(h-(l?1:0),p+(c?1:0),h+1,p-1,new I((l?k.empty:k.from(i.copy(k.empty))).append(c?k.empty:k.from(i.copy(k.empty))),l?0:1,c?0:1),l?0:1)),e(r.scrollIntoView()),!0}function Pa(t){return function(e,n){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,(d)=>d.childCount>0&&d.firstChild.type==t);if(!o)return!1;let s=o.startIndex;if(s==0)return!1;let l=o.parent,c=l.child(s-1);if(c.type!=t)return!1;if(n){let d=c.lastChild&&c.lastChild.type==l.type,f=k.from(d?t.create():null),h=new I(k.from(t.create(null,k.from(l.type.create(null,f)))),d?3:1,0),{start:p,end:m}=o;n(e.tr.step(new ft(p-(d?3:1),m,p,m,h,1,!0)).scrollIntoView())}return!0}}var fe={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},jr={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},Kf=typeof navigator<"u"&&/Mac/.test(navigator.platform),Yf=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(ot=0;ot<10;ot++)fe[48+ot]=fe[96+ot]=String(ot);var ot;for(ot=1;ot<=24;ot++)fe[ot+111]="F"+ot;var ot;for(ot=65;ot<=90;ot++)fe[ot]=String.fromCharCode(ot+32),jr[ot]=String.fromCharCode(ot);var ot;for(sr in fe)if(!jr.hasOwnProperty(sr))jr[sr]=fe[sr];var sr;function Ba(t){var e=Kf&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||Yf&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?jr:fe)[t.keyCode]||t.key||"Unidentified";if(n=="Esc")n="Escape";if(n=="Del")n="Delete";if(n=="Left")n="ArrowLeft";if(n=="Up")n="ArrowUp";if(n=="Right")n="ArrowRight";if(n=="Down")n="ArrowDown";return n}var Xf=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),Gf=typeof navigator<"u"&&/Win/.test(navigator.platform);function Qf(t){let e=t.split(/-(?!$)/),n=e[e.length-1];if(n=="Space")n=" ";let r,i,o,s;for(let l=0;l{if(t.selection.empty)return!1;if(e)e(t.tr.deleteSelection().scrollIntoView());return!0};function th(t,e){let{$cursor:n}=t.selection;if(!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0))return null;return n}var eh=(t,e,n)=>{let r=th(t,n);if(!r)return!1;let i=Va(r);if(!i){let s=r.blockRange(),l=s&&Ue(s);if(l==null)return!1;if(e)e(t.tr.lift(s,l).scrollIntoView());return!0}let o=i.nodeBefore;if(Ua(t,i,e,-1))return!0;if(r.parent.content.size==0&&(kn(o,"end")||T.isSelectable(o)))for(let s=r.depth;;s--){let l=Sr(t.doc,r.before(s),r.after(s),I.empty);if(l&&l.slice.size1)break}if(o.isAtom&&i.depth==r.depth-1){if(e)e(t.tr.delete(i.pos-o.nodeSize,i.pos).scrollIntoView());return!0}return!1};function kn(t,e,n=!1){for(let r=t;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}var nh=(t,e,n)=>{let{$head:r,empty:i}=t.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;o=Va(r)}let s=o&&o.nodeBefore;if(!s||!T.isSelectable(s))return!1;if(e)e(t.tr.setSelection(T.create(t.doc,o.pos-s.nodeSize)).scrollIntoView());return!0};function Va(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){if(t.index(e)>0)return t.doc.resolve(t.before(e+1));if(t.node(e).type.spec.isolating)break}return null}function rh(t,e){let{$cursor:n}=t.selection;if(!n||(e?!e.endOfTextblock("forward",t):n.parentOffset{let r=rh(t,n);if(!r)return!1;let i=Wa(r);if(!i)return!1;let o=i.nodeAfter;if(Ua(t,i,e,1))return!0;if(r.parent.content.size==0&&(kn(o,"start")||T.isSelectable(o))){let s=Sr(t.doc,r.before(),r.after(),I.empty);if(s&&s.slice.size{let{$head:r,empty:i}=t.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):r.parentOffset=0;e--){let n=t.node(e);if(t.index(e)+1{let{$from:n,$to:r}=t.selection,i=n.blockRange(r),o=i&&Ue(i);if(o==null)return!1;if(e)e(t.tr.lift(i,o).scrollIntoView());return!0},sh=(t,e)=>{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;if(e)e(t.tr.insertText(` -`).scrollIntoView());return!0};function yo(t){for(let e=0;e{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let i=n.node(-1),o=n.indexAfter(-1),s=yo(i.contentMatchAt(o));if(!s||!i.canReplaceWith(o,o,s))return!1;if(e){let l=n.after(),c=t.tr.replaceWith(l,l,s.createAndFill());c.setSelection(F.near(c.doc.resolve(l),1)),e(c.scrollIntoView())}return!0},ah=(t,e)=>{let n=t.selection,{$from:r,$to:i}=n;if(n instanceof Ct||r.parent.inlineContent||i.parent.inlineContent)return!1;let o=yo(i.parent.contentMatchAt(i.indexAfter()));if(!o||!o.isTextblock)return!1;if(e){let s=(!r.parentOffset&&i.index(){let{$cursor:n}=t.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let o=n.before();if(we(t.doc,o)){if(e)e(t.tr.split(o).scrollIntoView());return!0}}let r=n.blockRange(),i=r&&Ue(r);if(i==null)return!1;if(e)e(t.tr.lift(r,i).scrollIntoView());return!0};function dh(t){return(e,n)=>{if(e.selection instanceof T&&e.selection.node.isBlock){let{$from:m}=e.selection;if(!m.parentOffset||!we(e.doc,m.pos))return!1;if(n)n(e.tr.split(m.pos).scrollIntoView());return!0}if(!e.selection.$from.depth)return!1;let r=e.tr;if(!e.selection.empty&&(e.selection instanceof R||e.selection instanceof Ct))r.deleteSelection();let{$from:i}=r.selection,o=r.steps.length,s=[],l,c,d=!1,f=!1;for(let m=i.depth;;m--)if(i.node(m).isBlock){d=i.end(m)==i.pos+(i.depth-m),f=i.start(m)==i.pos-(i.depth-m),c=yo(i.node(m-1).contentMatchAt(i.indexAfter(m-1)));let b=t&&t(i.parent,d,i);s.unshift(b||(d&&c?{type:c}:null)),l=m;break}else{if(m==1)return!1;s.unshift(null)}let h=i.pos,p=we(r.doc,h,s.length,s);if(!p)s[0]=c?{type:c}:null,p=we(r.doc,h,s.length,s);if(!p)return!1;if(r.split(h,s.length,s),!d&&f&&i.node(l).type!=c){let m=r.mapping.slice(o),g=m.map(i.before(l)),b=r.doc.resolve(g);if(c&&i.node(l-1).canReplaceWith(b.index(),b.index()+1,c))r.setNodeMarkup(m.map(i.before(l)),c)}if(n)n(r.scrollIntoView());return!0}}var uh=dh();var fh=(t,e)=>{if(e)e(t.tr.setSelection(new Ct(t.doc)));return!0};function hh(t,e,n){let{nodeBefore:r,nodeAfter:i}=e,o=e.index();if(!r||!i||!r.type.compatibleContent(i.type))return!1;if(!r.content.size&&e.parent.canReplace(o-1,o)){if(n)n(t.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView());return!0}if(!e.parent.canReplace(o,o+1)||!(i.isTextblock||$e(t.doc,e.pos)))return!1;if(n)n(t.tr.join(e.pos).scrollIntoView());return!0}function Ua(t,e,n,r){let{nodeBefore:i,nodeAfter:o}=e,s,l,c=i.type.spec.isolating||o.type.spec.isolating;if(!c&&hh(t,e,n))return!0;let d=!c&&e.parent.canReplace(e.index(),e.index()+1);if(d&&(s=(l=i.contentMatchAt(i.childCount)).findWrapping(o.type))&&l.matchType(s[0]||o.type).validEnd){if(n){let m=e.pos+o.nodeSize,g=k.empty;for(let S=s.length-1;S>=0;S--)g=k.from(s[S].create(null,g));g=k.from(i.copy(g));let b=t.tr.step(new ft(e.pos-1,m,e.pos,m,new I(g,1,0),s.length,!0)),y=b.doc.resolve(m+2*s.length);if(y.nodeAfter&&y.nodeAfter.type==i.type&&$e(b.doc,y.pos))b.join(y.pos);n(b.scrollIntoView())}return!0}let f=o.type.spec.isolating||r>0&&c?null:F.findFrom(e,1),h=f&&f.$from.blockRange(f.$to),p=h&&Ue(h);if(p!=null&&p>=e.depth){if(n)n(t.tr.lift(h,p).scrollIntoView());return!0}if(d&&kn(o,"start",!0)&&kn(i,"end")){let m=i,g=[];for(;;){if(g.push(m),m.isTextblock)break;m=m.lastChild}let b=o,y=1;for(;!b.isTextblock;b=b.firstChild)y++;if(m.canReplace(m.childCount,m.childCount,b.content)){if(n){let S=k.empty;for(let U=g.length-1;U>=0;U--)S=k.from(g[U].copy(S));let L=t.tr.step(new ft(e.pos-g.length,e.pos+o.nodeSize,e.pos+y,e.pos+o.nodeSize-y,new I(S,g.length,0),0,!0));n(L.scrollIntoView())}return!0}}return!1}function $a(t){return function(e,n){let r=e.selection,i=t<0?r.$from:r.$to,o=i.depth;while(i.node(o).isInline){if(!o)return!1;o--}if(!i.node(o).isTextblock)return!1;if(n)n(e.tr.setSelection(R.create(e.doc,t<0?i.start(o):i.end(o))));return!0}}var ph=$a(-1),_h=$a(1);function Ja(t,e=null){return function(n,r){let{$from:i,$to:o}=n.selection,s=i.blockRange(o),l=s&&cn(s,t,e);if(!l)return!1;if(r)r(n.tr.wrap(s,l).scrollIntoView());return!0}}function ko(t,e=null){return function(n,r){let i=!1;for(let o=0;o{if(i)return!1;if(!c.isTextblock||c.hasMarkup(t,e))return;if(c.type==t)i=!0;else{let f=n.doc.resolve(d),h=f.index();i=f.parent.canReplaceWith(h,h+1,t)}})}if(!i)return!1;if(r){let o=n.tr;for(let s=0;s{if(l||!r&&c.isAtom&&c.isInline&&d>=o.pos&&d+c.nodeSize<=s.pos)return!1;l=c.inlineContent&&c.type.allowsMarkType(n)}),l)return!0}return!1}function mh(t){let e=[];for(let n=0;n{if(o.isAtom&&o.content.size&&o.isInline&&s>=r.pos&&s+o.nodeSize<=i.pos){if(s+1>r.pos)e.push(new qn(r,r.doc.resolve(s+1)));return r=r.doc.resolve(s+1+o.content.size),!1}}),r.poss.doc.rangeHasMark(m.$from.pos,m.$to.pos,t));else h=!f.every((m)=>{let g=!1;return p.doc.nodesBetween(m.$from.pos,m.$to.pos,(b,y,S)=>{if(g)return!1;g=!t.isInSet(b.marks)&&!!S&&S.type.allowsMarkType(t)&&!(b.isText&&/^\s*$/.test(b.textBetween(Math.max(0,m.$from.pos-y),Math.min(b.nodeSize,m.$to.pos-y))))}),!g});for(let m=0;me[i]??r):n}class Jt{constructor(t,e,n={}){this.match=t,this.match=t,this.handler=typeof e=="string"?xh(e):e,this.undoable=n.undoable!==!1,this.inCode=n.inCode||!1,this.inCodeMark=n.inCodeMark!==!1}}function xh(t){return function(e,n,r,i){let o=t;if(n[1]){let s=n[0].lastIndexOf(n[1]);o+=n[0].slice(s+n[1].length),r+=s;let l=r-i;if(l>0)o=n[0].slice(s-l,s)+o,r=i}return e.tr.insertText(o,r,i)}}var Ih=500;function Ya({rules:t}){let e=new st({state:{init(){return null},apply(n,r){let i=n.getMeta(this);if(i)return i;return n.selectionSet||n.docChanged?null:r}},props:{handleTextInput(n,r,i,o){return Ka(n,r,i,o,t,e)},handleDOMEvents:{compositionend:(n)=>{setTimeout(()=>{let{$cursor:r}=n.state.selection;if(r)Ka(n,r.pos,r.pos,"",t,e)})}}},isInputRules:!0});return e}function Ka(t,e,n,r,i,o){if(t.composing)return!1;let s=t.state,l=s.doc.resolve(e),c=l.parent.textBetween(Math.max(0,l.parentOffset-Ih),l.parentOffset,null,"")+r;for(let d=0;dg.type.spec.code))continue;if(l.parent.type.spec.code){if(!f.inCode)continue}else if(f.inCode==="only")continue;let h=f.match.exec(c);if(!h||h[0].length{if(b.isInline&&b.marks.some((y)=>y.type.spec.code))g=!0}),g)continue}let m=f.handler(s,h,p,n);if(!m)continue;if(f.undoable)m.setMeta(o,{transform:m,from:e,to:n,text:r});return t.dispatch(m),!0}return!1}var Xa=(t,e)=>{let n=t.plugins;for(let r=0;r=0;c--)s.step(l.steps[c].invert(l.docs[c]));if(o.text){let c=s.doc.resolve(o.from).marks();s.replaceWith(o.from,o.to,t.schema.text(o.text,c))}else s.delete(o.from,o.to);e(s)}return!0}}return!1},u_=new Jt(/--$/,"—",{inCodeMark:!1}),f_=new Jt(/\.\.\.$/,"…",{inCodeMark:!1}),h_=new Jt(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(")$/,"“",{inCodeMark:!1}),p_=new Jt(/"$/,"”",{inCodeMark:!1}),__=new Jt(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(')$/,"‘",{inCodeMark:!1}),g_=new Jt(/'$/,"’",{inCodeMark:!1});function Hr(t,e,n=null,r){return new Jt(t,(i,o,s,l)=>{let c=n instanceof Function?n(o):n,d=i.tr.delete(s,l),f=d.doc.resolve(s),h=f.blockRange(),p=h&&cn(h,e,c);if(!p)return null;d.wrap(h,p);let m=d.doc.resolve(s-1).nodeBefore;if(m&&m.type==e&&$e(d.doc,s-1)&&(!r||r(o,m)))d.join(s-1);return d})}function Io(t,e,n=null){return new Jt(t,(r,i,o,s)=>{let l=r.doc.resolve(o),c=n instanceof Function?n(i):n;if(!l.node(-1).canReplaceWith(l.index(-1),l.indexAfter(-1),e))return null;return r.tr.delete(o,s).setBlockType(o,o,e,c)})}function Ga(t={}){return new st({view(e){return new Qa(e,t)}})}class Qa{constructor(t,e){var n;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,this.lastDragEvent=null,this.width=(n=e.width)!==null&&n!==void 0?n:1,this.color=e.color===!1?void 0:e.color||"black",this.class=e.class,this.handlers=["dragover","dragend","drop","dragleave"].map((r)=>{let i=(o)=>{this[r](o)};return t.dom.addEventListener(r,i),{name:r,handler:i}})}destroy(){this.setCursor(null),this.handlers.forEach(({name:t,handler:e})=>this.editorView.dom.removeEventListener(t,e))}update(t,e){if(this.cursorPos!=null&&e.doc!=t.state.doc)if(this.lastDragEvent){let n=this.computeTarget(this.lastDragEvent);if(n==this.cursorPos)this.updateOverlay();else this.setCursor(n)}else this.updateOverlay()}setCursor(t){if(t==this.cursorPos)return;if(this.cursorPos=t,t==null)this.element.parentNode.removeChild(this.element),this.element=null;else this.updateOverlay()}updateOverlay(){let t=this.editorView.state.doc.resolve(this.cursorPos),e=!t.parent.inlineContent,n,r=this.editorView.dom,i=r.getBoundingClientRect(),o=i.width/r.offsetWidth,s=i.height/r.offsetHeight;if(e){let{nodeBefore:f,nodeAfter:h}=t;if(f||h){let p=this.editorView.nodeDOM(this.cursorPos-(f?f.nodeSize:0));if(p){let m=p.getBoundingClientRect(),g=f?m.bottom:m.top;if(f&&h)g=(g+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2;let b=this.width/2*s;n={left:m.left,right:m.right,top:g-b,bottom:g+b}}}}if(!n){let f=this.editorView.coordsAtPos(this.cursorPos),h=this.width/2*o;n={left:f.left-h,right:f.left+h,top:f.top,bottom:f.bottom}}let l=this.editorView.dom.offsetParent;if(!this.element){if(this.element=l.appendChild(document.createElement("div")),this.class)this.element.className=this.class;if(this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color)this.element.style.backgroundColor=this.color}this.element.classList.toggle("prosemirror-dropcursor-block",e),this.element.classList.toggle("prosemirror-dropcursor-inline",!e);let c,d;if(!l||l==document.body&&getComputedStyle(l).position=="static")c=-pageXOffset,d=-pageYOffset;else{let f=l.getBoundingClientRect(),h=f.width/l.offsetWidth,p=f.height/l.offsetHeight;c=f.left-l.scrollLeft*h,d=f.top-l.scrollTop*p}this.element.style.left=(n.left-c)/o+"px",this.element.style.top=(n.top-d)/s+"px",this.element.style.width=(n.right-n.left)/o+"px",this.element.style.height=(n.bottom-n.top)/s+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}computeTarget(t){let e=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),n=e&&e.inside>=0&&this.editorView.state.doc.nodeAt(e.inside),r=n&&n.type.spec.disableDropCursor,i=typeof r=="function"?r(this.editorView,e,t):r;if(!e||i)return null;let o=e.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let s=vr(this.editorView.state.doc,o,this.editorView.dragging.slice);if(s!=null)o=s}return o}dragover(t){if(!this.editorView.editable)return;this.lastDragEvent=t;let e=this.computeTarget(t);if(e!=null)this.setCursor(e),this.scheduleRemoval(5000)}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(t){if(!this.editorView.dom.contains(t.relatedTarget))this.setCursor(null)}}class lt extends F{constructor(t){super(t,t)}map(t,e){let n=t.resolve(e.map(this.head));return lt.valid(n)?new lt(n):F.near(n)}content(){return I.empty}eq(t){return t instanceof lt&&t.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(t,e){if(typeof e.pos!="number")throw RangeError("Invalid input for GapCursor.fromJSON");return new lt(t.resolve(e.pos))}getBookmark(){return new vo(this.anchor)}static valid(t){let e=t.parent;if(e.inlineContent||!vh(t)||!Sh(t))return!1;let n=e.type.spec.allowGapCursor;if(n!=null)return n;let r=e.contentMatchAt(t.index()).defaultType;return r&&r.isTextblock}static findGapCursorFrom(t,e,n=!1){t:for(;;){if(!n&<.valid(t))return t;let r=t.pos,i=null;for(let o=t.depth;;o--){let s=t.node(o);if(e>0?t.indexAfter(o)0){i=s.child(e>0?t.indexAfter(o):t.index(o)-1);break}else if(o==0)return null;r+=e;let l=t.doc.resolve(r);if(lt.valid(l))return l}for(;;){let o=e>0?i.firstChild:i.lastChild;if(!o){if(i.isAtom&&!i.isText&&!T.isSelectable(i)){t=t.doc.resolve(r+i.nodeSize*e),n=!1;continue t}break}i=o,r+=e;let s=t.doc.resolve(r);if(lt.valid(s))return s}return null}}}lt.prototype.visible=!1;lt.findFrom=lt.findGapCursorFrom;F.jsonID("gapcursor",lt);class vo{constructor(t){this.pos=t}map(t){return new vo(t.map(this.pos))}resolve(t){let e=t.resolve(this.pos);return lt.valid(e)?new lt(e):F.near(e)}}function Za(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function vh(t){for(let e=t.depth;e>=0;e--){let n=t.index(e),r=t.node(e);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(n-1);;i=i.lastChild){if(i.childCount==0&&!i.inlineContent||Za(i.type))return!0;if(i.inlineContent)return!1}}return!0}function Sh(t){for(let e=t.depth;e>=0;e--){let n=t.indexAfter(e),r=t.node(e);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(n);;i=i.firstChild){if(i.childCount==0&&!i.inlineContent||Za(i.type))return!0;if(i.inlineContent)return!1}}return!0}function tc(){return new st({props:{decorations:Ah,createSelectionBetween(t,e,n){return e.pos==n.pos&<.valid(n)?new lt(n):null},handleClick:Oh,handleKeyDown:Ch,handleDOMEvents:{beforeinput:Mh}}})}var Ch=bo({ArrowLeft:Kr("horiz",-1),ArrowRight:Kr("horiz",1),ArrowUp:Kr("vert",-1),ArrowDown:Kr("vert",1)});function Kr(t,e){let n=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,i,o){let s=r.selection,l=e>0?s.$to:s.$from,c=s.empty;if(s instanceof R){if(!o.endOfTextblock(n)||l.depth==0)return!1;c=!1,l=r.doc.resolve(e>0?l.after():l.before())}let d=lt.findGapCursorFrom(l,e,c);if(!d)return!1;if(i)i(r.tr.setSelection(new lt(d)));return!0}}function Oh(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!lt.valid(r))return!1;let i=t.posAtCoords({left:n.clientX,top:n.clientY});if(i&&i.inside>-1&&T.isSelectable(t.state.doc.nodeAt(i.inside)))return!1;return t.dispatch(t.state.tr.setSelection(new lt(r))),!0}function Mh(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof lt))return!1;let{$from:n}=t.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(t.state.schema.nodes.text);if(!r)return!1;let i=k.empty;for(let s=r.length-1;s>=0;s--)i=k.from(r[s].createAndFill(null,i));let o=t.state.tr.replace(n.pos,n.pos,new I(i,0,0));return o.setSelection(R.near(o.doc.resolve(n.pos+1))),t.dispatch(o),!1}function Ah(t){if(!(t.selection instanceof lt))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",G.create(t.doc,[_t.widget(t.selection.head,e,{key:"gapcursor"})])}function re(t,e){let{from:n,to:r,empty:i,$from:o}=t.selection;if(i)return!!e.isInSet(t.storedMarks||o.marks());return t.doc.rangeHasMark(n,r,e)}function _e(t,e,n){let r=t.selection.$from.parent;if(r.type!==e)return!1;return!n||Object.keys(n).every((i)=>r.attrs[i]===n[i])}function lr(t,e){let{$from:n}=t.selection;for(let r=n.depth;r>0;r--){let i=n.node(r);if(e(i))return{node:i,pos:n.before(r)}}return null}function So(t,e,n){return new Jt(t,(r,i,o,s)=>{let l=i[1];if(!l)return null;let c=o+i[0].length-n-l.length,d=c+l.length,f=c-n,h=r.tr;return h.delete(d,s),h.delete(f,c),h.addMark(f,f+l.length,e.create()),h.removeStoredMark(e),h})}function Yr(t,e,n){let r=t.resolve(e);if(!r.parent.inlineContent)return null;let i=r.start(),o=null;return r.parent.forEach((s,l)=>{if(o)return;let c=i+l,d=c+s.nodeSize,f=n.isInSet(s.marks);if(f&&c<=e&&e<=d)o={from:c,to:d,mark:f}}),o}function ec(t){let e=t.trim();if(!e)return null;if(/^(javascript|data|vbscript):/i.test(e.replace(/[\s\x00-\x1f]/g,"")))return null;if(/^[a-z][a-z\d+.-]*:/i.test(e)||e.startsWith("/")||e.startsWith("#"))return e;return`https://${e}`}function nc(t,e){let{paragraph:n,heading:r,code_block:i,blockquote:o,horizontal_rule:s,bullet_list:l,ordered_list:c,list_item:d}=t.nodes,{strong:f,em:h,code:p,link:m}=t.marks,g=ko(n),b=(P,V)=>(j,X)=>_e(j,P,V)?g(j,X):ko(P,V)(j,X),y=(P)=>(V,j)=>{let X=lr(V,(nt)=>nt.type===l||nt.type===c);if(!X)return Ra(P)(V,j);if(X.node.type===P)return Jr(d)(V,j);if(j)j(V.tr.setNodeMarkup(X.pos,P));return!0},S=(P,V)=>lr(P,(j)=>j.type===o)?qa(P,V):Ja(o)(P,V),L=(P,V,j)=>{let{$from:X,empty:nt}=P.selection,Vt=nt&&Yr(P.doc,P.selection.from,m)!==null,ge=!nt&&X.parent.inlineContent&&X.parent.type.allowsMarkType(m);if(!Vt&&!ge)return!1;if(V&&j)e.requestLink(j);return!0},U=(P,V)=>{let{$from:j}=P.selection;if(j.parent.type.spec.code)return!1;if(!V)return!0;let X=P.tr.replaceSelectionWith(s.create());if(!X.selection.$from.parent.inlineContent){let nt=X.selection.from;X.insert(nt,n.create()),X.setSelection(R.create(X.doc,nt+1))}return V(X.scrollIntoView()),!0},et=new Jt(/^---$/,(P,V,j,X)=>{let nt=P.doc.resolve(j),Vt=nt.depth;if(Vt<1||nt.parent.type.spec.code)return null;let ge=nt.index(Vt-1),Cn=nt.node(Vt-1),D=k.from([s.create(),n.create()]);if(!Cn.canReplace(ge,ge+1,D))return null;let A=nt.before(),N=P.tr.replaceWith(A,nt.after(),[s.create(),n.create()]);return N.setSelection(R.create(N.doc,A+s.create().nodeSize+1)),N}),at=0,Ft=new st({props:{transformPastedHTML(P){return P.replace(/\s(?:style|class)\s*=\s*("[^"]*"|'[^']*')/gi,"")},handleKeyDown(P,V){if((V.metaKey||V.ctrlKey)&&V.shiftKey&&V.key.toLowerCase()==="v")at=Date.now()+1000;return!1},handlePaste(P,V){if(Date.now()>at)return!1;at=0;let j=V.clipboardData?.getData("text/plain");if(!j)return!1;return P.pasteText(j),!0}}}),z=yn({"Mod-Alt-0":g,"Mod-Alt-1":b(r,{level:1}),"Mod-Alt-2":b(r,{level:2}),"Mod-Alt-3":b(r,{level:3}),"Mod-Shift-8":y(l),"Mod-Shift-9":y(c),"Mod-k":L,"Mod-e":pe(p),Backspace:Xa}),Y=Ya({rules:[Io(/^(#{1,3})\s$/,r,(P)=>({level:P[1].length})),Io(/^```$/,i),Hr(/^\s*([-*])\s$/,l),Hr(/^(\d+)\.\s$/,c,(P)=>({order:Number(P[1])}),(P,V)=>V.childCount+V.attrs.order===Number(P[1])),Hr(/^\s*>\s$/,o),So(/\*\*([^*]+)\*\*$/,f,2),So(/(?:^|[^*])\*([^*]+)\*$/,h,1),So(/`([^`]+)`$/,p,1),et]}),Z=new st({props:{decorations(P){let{doc:V}=P,j=V.firstChild;if(V.childCount!==1||!j||j.type!==n||j.content.size>0)return null;return G.create(V,[_t.node(0,j.nodeSize,{class:"is-placeholder","data-placeholder":C("placeholder")})])}}});return{plugins:[Ft,z,Y,Ga({color:"var(--primary)",width:2}),tc(),Z],paragraph:g,heading:(P)=>b(r,{level:P}),codeBlock:b(i),bold:pe(f),italic:pe(h),inlineCode:pe(p),link:L,bulletList:y(l),orderedList:y(c),blockquote:S,horizontalRule:U}}var Co=/Mac|iPhone|iPad|iPod/.test(navigator.platform||navigator.userAgent),Q=Co?"⌘":"Ctrl",Qe=Co?"⇧":"Shift",Xt=Co?"⌥":"Alt";function B(t,e={},...n){let r=document.createElement(t);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return r.append(...n),r}function Gt(...t){return B("span",{class:"keycaps","aria-hidden":"true"},...t.map((e)=>B("kbd",{class:"keycap"},e)))}function Xr(t,e,n){let r=[B("span",{class:"tip-label"},t)];if(e.length)r.push(Gt(...e));if(n)r.push(B("span",{class:"tip-reason"},n));return B("span",{class:"tip","aria-hidden":"true",role:"presentation"},...r)}function xn(t,e,n){let r=t.coordsAtPos(e),i=t.coordsAtPos(n);return{top:Math.min(r.top,i.top),bottom:Math.max(r.bottom,i.bottom),left:Math.min(r.left,i.left),right:Math.max(r.right,i.right)}}var Ae=8;function In(t,e,n){let{offsetWidth:r,offsetHeight:i}=t,o=e.top-i-Ae,s=e.bottom+Ae,l;if(n==="above")l=o>=Ae?o:s;else l=s+i<=window.innerHeight-Ae?s:o;let c=(e.left+e.right)/2,d=Math.min(Math.max(c-r/2,Ae),window.innerWidth-r-Ae);t.style.top=`${Math.max(l,Ae)}px`,t.style.left=`${Math.max(d,Ae)}px`}var Eh=120;function Gr(t){return!!t&&t.startsWith("/notes/")}function Nh(t,e){let{selection:n}=t;if(!(n instanceof R)||!n.empty)return null;let r=n.$from;if(!r.parent.isTextblock||r.parent.type.spec.code)return null;if(e.isInSet(t.storedMarks||r.marks()))return null;let i=r.parent.textBetween(0,r.parentOffset,void 0,` -`),o=/\[\[([^\[\]\n]*)$/.exec(i);if(!o)return null;return{from:r.pos-o[0].length,query:o[1]}}function Dh(t){if(!Array.isArray(t))return[];return t.filter((e)=>typeof e==="object"&&e!==null&&typeof e.id==="string"&&typeof e.title==="string")}async function Th(t){let e=await fetch("/notes/quick",{method:"POST",body:new URLSearchParams({title:t})});if(!e.ok)throw Error(`quick ${e.status}`);let n=(await e.text()).trim();if(!n)throw Error("empty note id");return n}function rc(t,e){let n=t.marks.link,r=t.marks.code,i=e.currentNoteId,o=null,s=null,l=null,c=[],d=!1,f=[],h=0,p=!1,m,g=null,b=B("div",{class:"popover slash-menu note-menu",role:"presentation"});b.hidden=!0;let y=B("div",{class:"slash-list",role:"listbox","aria-label":C("noteMenu")}),S=B("div",{class:"slash-footer","aria-hidden":"true"},Gt("↑","↓"),` ${C("navigate")} `,Gt("↵"),` ${C("insert")} `,Gt("Esc"),` ${C("close")}`);b.append(y,S),b.addEventListener("mousedown",(D)=>D.preventDefault());function L(D){if(D.kind==="create")return D.title;return D.hit.title.trim()||C("untitled")}function U(D){return D.kind==="create"?C("createNote",{q:D.title}):L(D)}function et(D){let A=c.map((jt)=>({kind:"note",hit:jt})),N=D.trim(),rt=c.some((jt)=>jt.title.trim().toLowerCase()===N.toLowerCase());if(N&&!rt)A.push({kind:"create",title:N});return A}function at(){clearTimeout(m),g?.abort(),g=null}function Ft(){at(),s=null,f=[],c=[],d=!1,h=0,b.hidden=!0,o?.dom.removeAttribute("aria-activedescendant")}async function z(D){let A=new AbortController;g=A;try{let N=await fetch(`/notes/titles.json?q=${encodeURIComponent(D)}`,{signal:A.signal,headers:{accept:"application/json"}});if(!N.ok)throw Error(`titles ${N.status}`);let rt=await N.json();if(A.signal.aborted)return;c=Dh(rt).filter((jt)=>jt.id!==i)}catch(N){if(A.signal.aborted)return;console.error("note search failed",N),c=[]}if(g===A)g=null;d=!0,V()}function Y(D){at(),d=!1,m=setTimeout(()=>void z(D),Eh)}function Z(){if(!o)return;let D=y.querySelectorAll(".slash-item");D.forEach((N,rt)=>N.setAttribute("aria-selected",String(rt===h)));let A=D[h];if(A)o.dom.setAttribute("aria-activedescendant",A.id),A.scrollIntoView({block:"nearest"})}function P(D){h=D,Z()}function V(){if(!o||!s)return;if(f=et(s.query),h>=f.length)h=0;if(f.length===0){y.replaceChildren(...d?[B("div",{class:"slash-empty",role:"presentation"},C("noNotesFound"))]:[]),o.dom.removeAttribute("aria-activedescendant");return}y.replaceChildren(...f.map((D,A)=>{let N=B("div",{class:"slash-item",role:"option",id:`note-opt-${A}`,"aria-selected":String(A===h)},B("span",{class:"slash-label"},U(D)));return N.addEventListener("mouseenter",()=>P(A)),N.addEventListener("click",()=>Vt(D)),N})),Z()}function j(D){if(!s)return;In(b,xn(D,s.from,D.state.selection.from),"below")}function X(D,A,N,rt,jt){let Et=D.state.tr.replaceWith(A,N,t.text(rt,[n.create({href:`/notes/${jt}`})])),Ht=A+rt.length;Et.insert(Ht,t.text(" ")),Et.setSelection(R.create(Et.doc,Ht+1)),Et.setStoredMarks([]),D.dispatch(Et.scrollIntoView()),D.focus()}async function nt(D,A,N,rt){let jt=D.state.doc.textBetween(A,N);p=!0;let Et;try{Et=await Th(rt)}catch(ni){console.error("note create failed",ni);return}finally{p=!1}let Ht=o;if(!Ht)return;let On=Ht.state.selection;if(!On.empty||On.from!==N||Ht.state.doc.textBetween(A,N)!==jt)return;X(Ht,A,N,rt,Et)}function Vt(D){let A=o;if(!A||!s||p)return;let{from:N}=s,rt=A.state.selection.from;if(D.kind==="note"){X(A,N,rt,L(D),D.hit.id);return}nt(A,N,rt,D.title)}function ge(D){o=D;let A=Nh(D.state,r);if(!A){l=null,Ft();return}if(A.from===l){Ft();return}let N=!s||A.from!==s.from||A.query!==s.query;if(s=A,N)h=0,Y(A.query);if(b.hidden=!1,N)V();j(D)}return{plugins:[new st({props:{handleKeyDown(D,A){if(!s)return!1;let N=f.length;if(A.key==="Escape")return l=s.from,Ft(),!0;if(A.key==="ArrowDown"&&N)return P((h+1)%N),!0;if(A.key==="ArrowUp"&&N)return P((h-1+N)%N),!0;if((A.key==="Enter"||A.key==="Tab")&&N){if(!p)Vt(f[h]);return!0}return!1},handleDOMEvents:{click(D,A){if(!(A.ctrlKey||A.metaKey))return!1;let rt=A.target?.closest?.("a")?.getAttribute("href");if(!rt||!Gr(rt))return!1;return A.preventDefault(),location.assign(rt),!0}}},view(D){o=D,document.body.append(b);let A=()=>{if(o)j(o)};return window.addEventListener("scroll",A,{capture:!0,passive:!0}),window.addEventListener("resize",A),{update(N){ge(N)},destroy(){window.removeEventListener("scroll",A,{capture:!0}),window.removeEventListener("resize",A),at(),b.remove(),o=null}}}})]}}function Rh(t){let{selection:e}=t;if(!(e instanceof R)||!e.empty)return null;let n=e.$from;if(!n.parent.isTextblock||n.parent.type.spec.code)return null;let r=n.parent.textBetween(0,n.parentOffset,void 0,` -`),i=/(?:^|\s)\/([^\s/]*)$/.exec(r);if(!i)return null;return{from:n.pos-i[1].length-1,query:i[1]}}function Lh(t,e,n,r){let i=null;return t.doc.nodesBetween(e,n,(o)=>{if(i!==null)return!1;let s=r.isInSet(o.marks);if(s)i=String(s.attrs.href);return i===null}),i}function ic(t,e){let{strong:n,em:r,code:i,link:o}=t.marks,{heading:s}=t.nodes,l=null,c=!1,d=null,f=null,h="",p=0,m=[],g=null,b=[{id:"bold",label:C("bold"),glyph:"B",keys:[Q,"B"],run:e.bold,active:(v)=>re(v,n)},{id:"italic",label:C("italic"),glyph:"I",keys:[Q,"I"],run:e.italic,active:(v)=>re(v,r)},{id:"code",label:C("inlineCode"),glyph:"",keys:[Q,"E"],run:e.inlineCode,active:(v)=>re(v,i)},{id:"link",label:C("link"),glyph:"Link",keys:[Q,"K"],run:e.link,active:(v)=>re(v,o)},{id:"h1",label:C("heading1"),glyph:"H1",keys:[Q,Xt,"1"],run:e.heading(1),active:(v)=>_e(v,s,{level:1})},{id:"h2",label:C("heading2"),glyph:"H2",keys:[Q,Xt,"2"],run:e.heading(2),active:(v)=>_e(v,s,{level:2})},{id:"h3",label:C("heading3"),glyph:"H3",keys:[Q,Xt,"3"],run:e.heading(3),active:(v)=>_e(v,s,{level:3})}],y=B("div",{class:"bubble",role:"toolbar","aria-label":C("bubbleLabel")});y.hidden=!0;let S=b.map((v)=>{let O=B("button",{type:"button",class:"bubble-btn","aria-label":v.label,"data-command":v.id},B("span",{class:"bubble-glyph","aria-hidden":"true"},v.glyph),Xr(v.label,v.keys));return O.addEventListener("click",()=>{if(!l)return;if(v.run(l.state,l.dispatch,l),v.id!=="link")l.focus()}),y.append(O),{btn:O,item:v}});y.addEventListener("mousedown",(v)=>v.preventDefault());let L=B("div",{class:"popover link-popover",role:"dialog","aria-label":C("linkDialog")});L.hidden=!0;let U=B("form",{class:"link-edit",novalidate:""}),et=B("input",{type:"text",class:"link-input",inputmode:"url",autocomplete:"off",autocapitalize:"off",spellcheck:"false",placeholder:"https://","aria-label":C("linkUrl"),"aria-describedby":"link-error"}),at=B("p",{class:"link-error",id:"link-error",role:"alert"});at.hidden=!0;let Ft=B("button",{type:"submit",class:"btn btn-primary"},C("apply"),Gt("↵")),z=B("button",{type:"button",class:"btn"},C("remove")),Y=B("button",{type:"button",class:"btn"},C("open"));U.append(B("div",{class:"link-row"},et,Ft),at,B("div",{class:"link-actions"},z,Y));let Z=B("div",{class:"link-view",role:"menu","aria-label":C("linkMenu")}),P=B("span",{class:"link-href"}),V=B("button",{type:"button",class:"btn",role:"menuitem"},C("edit")),j=B("button",{type:"button",class:"btn",role:"menuitem"},C("remove")),X=B("button",{type:"button",class:"btn",role:"menuitem"},C("open"));Z.append(P,B("div",{class:"link-actions",role:"none"},V,j,X)),L.append(U,Z);function nt(v){if(!d)return;if(d=null,L.hidden=!0,v)l?.focus()}function Vt(v,O,W,H){Et();let dt=Lh(v.state,O,W,o);d={from:O,to:W,mode:H,href:dt},L.hidden=!1,U.hidden=H!=="edit",Z.hidden=H!=="view",at.hidden=!0,et.removeAttribute("aria-invalid"),et.value=dt??"",P.textContent=dt??"";for(let Kt of[z,Y,j,X])Kt.disabled=dt===null,Kt.title=dt===null?C("linkNeedsLink"):"";if(Mn(v),H==="edit")et.focus(),et.select();else V.focus()}function ge(v){let O=v.state.selection,W=O.empty?Yr(v.state.doc,O.from,o):{from:O.from,to:O.to};if(!W)return;Vt(v,W.from,W.to,"edit")}U.addEventListener("submit",(v)=>{if(v.preventDefault(),!d||!l)return;let O=ec(et.value);if(!O){at.textContent=C("linkInvalid"),at.hidden=!1,et.setAttribute("aria-invalid","true"),et.focus();return}let{from:W,to:H}=d;nt(!1),l.dispatch(l.state.tr.removeMark(W,H,o).addMark(W,H,o.create({href:O}))),l.focus()});function Cn(){if(!d||!l)return;let{from:v,to:O}=d;nt(!1),l.dispatch(l.state.tr.removeMark(v,O,o)),l.focus()}function D(){if(!d?.href)return;if(Gr(d.href)){location.assign(d.href);return}window.open(d.href,"_blank","noopener,noreferrer")}z.addEventListener("click",Cn),j.addEventListener("click",Cn),Y.addEventListener("click",D),X.addEventListener("click",D),V.addEventListener("click",()=>{if(l&&d)Vt(l,d.from,d.to,"edit")}),L.addEventListener("keydown",(v)=>{if(v.key==="Escape"){v.preventDefault(),v.stopPropagation(),nt(!0);return}if((v.key==="ArrowDown"||v.key==="ArrowUp")&&!Z.hidden){let O=[V,j,X].filter((Kt)=>!Kt.disabled),W=O.indexOf(document.activeElement),H=v.key==="ArrowDown"?1:-1,dt=O[(W+H+O.length)%O.length];if(dt)v.preventDefault(),dt.focus()}});let A=[{id:"text",label:C("paragraph"),keywords:"text paragraph p",keys:[Q,Xt,"0"],run:e.paragraph},{id:"h1",label:C("heading1"),keywords:"heading title h1",keys:[Q,Xt,"1"],run:e.heading(1)},{id:"h2",label:C("heading2"),keywords:"heading subtitle h2",keys:[Q,Xt,"2"],run:e.heading(2)},{id:"h3",label:C("heading3"),keywords:"heading h3",keys:[Q,Xt,"3"],run:e.heading(3)},{id:"bullets",label:C("bulletList"),keywords:"list ul bullet unordered",keys:[Q,Qe,"8"],run:e.bulletList},{id:"ordered",label:C("numberedList"),keywords:"list ol number ordered",keys:[Q,Qe,"9"],run:e.orderedList},{id:"quote",label:C("quote"),keywords:"blockquote quote",keys:[">"],run:e.blockquote},{id:"codeblock",label:C("codeBlock"),keywords:"code pre fence",keys:["```"],run:e.codeBlock},{id:"divider",label:C("divider"),keywords:"hr rule line divider",keys:["---"],run:e.horizontalRule}],N=B("div",{class:"popover slash-menu",role:"presentation"});N.hidden=!0;let rt=B("div",{class:"slash-list",role:"listbox","aria-label":C("blockMenu")}),jt=B("div",{class:"slash-footer","aria-hidden":"true"},Gt("↑","↓"),` ${C("navigate")} `,Gt("↵"),` ${C("insert")} `,Gt("Esc"),` ${C("close")}`);N.append(rt,jt),N.addEventListener("mousedown",(v)=>v.preventDefault());function Et(){f=null,N.hidden=!0,l?.dom.removeAttribute("aria-activedescendant")}function Ht(){if(!l||f===null)return;let v=h.toLowerCase();if(m=A.filter((W)=>!v||W.label.toLowerCase().includes(v)||W.keywords.split(" ").some((H)=>H.startsWith(v))),p>=m.length)p=0;if(m.length===0){rt.replaceChildren(B("div",{class:"slash-empty",role:"presentation"},C("noMatches"))),l.dom.removeAttribute("aria-activedescendant");return}rt.replaceChildren(...m.map((W,H)=>{let dt=B("div",{class:"slash-item",role:"option",id:`slash-opt-${W.id}`,"aria-selected":String(H===p)},B("span",{class:"slash-label"},W.label),Gt(...W.keys));return dt.addEventListener("click",()=>On(W)),dt}));let O=m[p];l.dom.setAttribute("aria-activedescendant",`slash-opt-${O.id}`),rt.querySelector(`#slash-opt-${O.id}`)?.scrollIntoView({block:"nearest"})}function On(v){let O=l;if(!O||f===null)return;let W=f,H=O.state.selection.from;Et(),O.dispatch(O.state.tr.delete(W,H)),v.run(O.state,O.dispatch,O),O.focus()}function ni(v){let O=Rh(v.state);if(!O){g=null,Et();return}if(O.from===g||d){Et();return}if(O.from!==f||O.query!==h)p=0;f=O.from,h=O.query,N.hidden=!1,Ht()}function To(v){let O=v.state.selection;return O instanceof R&&!O.empty&&!v.composing&&!c&&d===null}function Mn(v){l=v;let O=v.state,W=To(v);if(y.hidden=!W,W){for(let{btn:H,item:dt}of S){let Kt=dt.active(O);H.dataset.active=String(Kt),H.setAttribute("aria-pressed",String(Kt)),H.disabled=!dt.run(O)}In(y,xn(v,O.selection.from,O.selection.to),"above")}if(d)In(L,xn(v,d.from,d.to),"above");if(f!==null&&!N.hidden)In(N,xn(v,f,O.selection.from),"below")}return{plugins:[new st({props:{handleKeyDown(v,O){if(f!==null){let W=m.length;if(O.key==="ArrowDown"&&W)return p=(p+1)%W,Ht(),!0;if(O.key==="ArrowUp"&&W)return p=(p-1+W)%W,Ht(),!0;if(O.key==="Enter"&&W)return On(m[p]),!0;if(O.key==="Escape")return g=f,Et(),!0}if(O.key==="Escape"&&To(v))return c=!0,Mn(v),!0;return!1},handleClick(v,O,W){let dt=W.target?.closest?.("a");if(!dt)return!1;if((W.ctrlKey||W.metaKey)&&Gr(dt.getAttribute("href")))return!1;let Kt=Yr(v.state.doc,O,o);if(Kt)Vt(v,Kt.from,Kt.to,"view");return!1}},view(v){l=v,document.body.append(y,L,N);let O=()=>{if(l)Mn(l)},W=(H)=>{if(d&&!L.contains(H.target))nt(!1)};return window.addEventListener("scroll",O,{capture:!0,passive:!0}),window.addEventListener("resize",O),document.addEventListener("mousedown",W,!0),Mn(v),{update(H,dt){if(!dt.selection.eq(H.state.selection))c=!1;if(d&&H.state.doc!==dt.doc)nt(!1);ni(H),Mn(H)},destroy(){window.removeEventListener("scroll",O,{capture:!0}),window.removeEventListener("resize",O),document.removeEventListener("mousedown",W,!0),y.remove(),L.remove(),N.remove(),l=null}}}})],openLink:ge}}var At={undo:'',redo:'',paragraph:'',h1:'',h2:'',h3:'',bold:'',italic:'',code:'',link:'',bullets:'',ordered:'',quote:'',codeBlock:'',rule:''};function Ph(t,e,n){let{paragraph:r,heading:i,code_block:o,blockquote:s,bullet_list:l,ordered_list:c}=t.nodes,{strong:d,em:f,code:h,link:p}=t.marks,m=(b)=>({id:`h${b}`,label:C(`heading${b}`),keys:[Q,Xt,String(b)],icon:b===1?At.h1:b===2?At.h2:At.h3,run:e.heading(b),isActive:(y)=>_e(y,i,{level:b})}),g=(b)=>(y)=>lr(y,(S)=>S.type===b)!==null;return[{id:"undo",label:C("undo"),keys:[Q,"Z"],icon:At.undo,run:n.undo},{id:"redo",label:C("redo"),keys:[Q,Qe,"Z"],icon:At.redo,run:n.redo},"|",{id:"paragraph",label:C("paragraph"),keys:[Q,Xt,"0"],icon:At.paragraph,run:e.paragraph,isActive:(b)=>_e(b,r)},m(1),m(2),m(3),"|",{id:"bold",label:C("bold"),keys:[Q,"B"],icon:At.bold,run:e.bold,isActive:(b)=>re(b,d)},{id:"italic",label:C("italic"),keys:[Q,"I"],icon:At.italic,run:e.italic,isActive:(b)=>re(b,f)},{id:"code",label:C("inlineCode"),keys:[Q,"E"],icon:At.code,run:e.inlineCode,isActive:(b)=>re(b,h)},{id:"link",label:C("link"),keys:[Q,"K"],icon:At.link,run:e.link,isActive:(b)=>re(b,p)},"|",{id:"bullets",label:C("bulletList"),keys:[Q,Qe,"8"],icon:At.bullets,run:e.bulletList,isActive:g(l)},{id:"ordered",label:C("numberedList"),keys:[Q,Qe,"9"],icon:At.ordered,run:e.orderedList,isActive:g(c)},{id:"quote",label:C("quote"),keys:[">"],icon:At.quote,run:e.blockquote,isActive:(b)=>lr(b,(y)=>y.type===s)!==null},{id:"codeblock",label:C("codeBlock"),keys:["```"],icon:At.codeBlock,run:e.codeBlock,isActive:(b)=>_e(b,o)},{id:"rule",label:C("divider"),keys:["---"],icon:At.rule,run:e.horizontalRule}]}var oc=["history","headings","marks","blocks"];function sc(t,e,n,r){let i=document.getElementById("editor-toolbar");if(!i)i=document.createElement("div"),i.id="editor-toolbar",t.before(i);i.classList.add("editor-toolbar"),i.setAttribute("role","toolbar"),i.setAttribute("aria-label",C("toolbarLabel"));let o=null,s=[],l=B("div",{class:"editor-toolbar-group","data-group":oc[0]});i.append(l);let c=0;for(let p of Ph(e,n,r)){if(p==="|"){c+=1,l=B("div",{class:"editor-toolbar-group","data-group":oc[c]}),i.append(l);continue}let m=B("button",{type:"button",class:"editor-toolbar-btn","aria-label":p.label,"aria-keyshortcuts":Bh(p.keys),"data-command":p.id,tabindex:"-1"},B("span",{class:"editor-toolbar-icon","aria-hidden":"true"}),Xr(p.label,p.keys,C("unavailable")));m.querySelector(".editor-toolbar-icon").innerHTML=``,m.disabled=!0,m.addEventListener("click",()=>{if(!o)return;p.run(o.state,o.dispatch,o),o.focus()}),l.append(m),s.push({btn:m,item:p,enabled:!1})}i.addEventListener("mousedown",(p)=>p.preventDefault());let d=()=>s.map((p)=>p.btn).filter((p)=>!p.disabled),f=(p)=>{for(let{btn:m}of s)m.tabIndex=m===p?0:-1};i.addEventListener("keydown",(p)=>{let m=d();if(!m.length)return;let g=m.indexOf(document.activeElement),b;if(p.key==="ArrowRight")b=m[(g+1+m.length)%m.length];else if(p.key==="ArrowLeft")b=m[(g-1+m.length)%m.length];else if(p.key==="Home")b=m[0];else if(p.key==="End")b=m[m.length-1];if(!b)return;p.preventDefault(),f(b),b.focus()});let h=(p)=>{for(let g of s)if(g.enabled=!!g.item.run(p),g.btn.disabled=!g.enabled,g.item.isActive){let b=g.item.isActive(p);g.btn.dataset.active=String(b),g.btn.setAttribute("aria-pressed",String(b))}let m=s.find((g)=>g.btn.tabIndex===0&&!g.btn.disabled)?.btn??d()[0];if(m)f(m)};return new st({view(p){return o=p,h(p.state),{update(m){h(m.state)},destroy(){o=null}}}})}function Bh(t){let e={Ctrl:"Control","⌘":"Meta",Shift:"Shift","⇧":"Shift",Alt:"Alt","⌥":"Alt"};return t.map((n)=>e[n]??n).join("+")}await _i({module_or_path:new URL("/loro-856987111b05.wasm",location.origin)});var dc=1,Oo=2,Mo=3,zh={...$r.spec.nodes.get("code_block"),attrs:{language:{default:null}},parseDOM:[{tag:"pre",preserveWhitespace:"full",getAttrs:(t)=>({language:t.dataset.language||null})}],toDOM:(t)=>["pre",t.attrs.language?{"data-language":t.attrs.language}:{},["code",0]]},Qt=new sn({nodes:Ta($r.spec.nodes.update("code_block",zh),"paragraph block*","block"),marks:$r.spec.marks});function Fh(){let e=null;try{let n=sessionStorage.getItem("project-note-peer");if(n)e=JSON.parse(n)}catch{e=null}if(!e){let n=1000+Math.floor(Math.random()*9000),r=Math.floor(Math.random()*360);e={name:`user-${n}`,color:`hsl(${r} 70% 45%)`};try{sessionStorage.setItem("project-note-peer",JSON.stringify(e))}catch{}}return e}var vn=document.getElementById("editor");if(!vn)throw Error("#editor element not found");var uc=vn.dataset.noteId??"",Vh=vn.dataset.noteTitle?.trim()||document.querySelector("header span.truncate")?.textContent?.trim()||"Note",Ne=new Pt,Wh=Fh(),cr=new Ea(Ne.peerIdStr),lc=tp(vn),qh=ep();function Uh(t){let n=cr.getAll()[t]?.user?.color??"currentColor";return{class:"loro-selection","data-peer":t,style:`background-color: color-mix(in srgb, ${n} 28%, transparent)`}}var No=nc(Qt,{requestLink:(t)=>fc.openLink(t)}),fc=ic(Qt,No),$h=sc(vn,Qt,No,{undo:_o,redo:Ur}),Jh=rc(Qt,{currentNoteId:uc}),jh=yn({Enter:La(Qt.nodes.list_item),Tab:Pa(Qt.nodes.list_item),"Shift-Tab":Jr(Qt.nodes.list_item),"Mod-b":pe(Qt.marks.strong),"Mod-i":pe(Qt.marks.em),"Mod-`":pe(Qt.marks.code)}),Hh=ye.create({schema:Qt,plugins:[Ma({doc:Ne}),Da({doc:Ne}),yn({"Mod-z":_o,"Mod-y":Ur,"Shift-Mod-z":Ur}),...fc.plugins,...Jh.plugins,jh,...No.plugins,yn(Ha),$h,Na(cr,{user:Wh,createSelection:Uh})]}),Zr=null,ti=null;function ac(){if(Zr||!ti)return;let t=Ne.oplogVersion(),e=ti.compare(t);if(e===void 0||e>0)return;Zr=new Zn(vn,{state:Hh,attributes:{role:"textbox","aria-multiline":"true","aria-label":Vh}})}var Kh=`${location.protocol==="https:"?"wss":"ws"}://${location.host}/notes/${encodeURIComponent(uc)}/ws`,hc=500,Yh=5000,Ee=null,Qr=hc,ei=!1;function Xh(t,e){let n=new Uint8Array(e.length+1);return n[0]=t,n.set(e,1),n}function pc(){return Ee!==null&&Ee.readyState===WebSocket.OPEN}function dr(t,e){if(pc())Ee.send(Xh(t,e))}var Gh={connecting:"statusConnecting",reconnecting:"statusReconnecting",saved:"statusSaved",saving:"statusSaving",local:"statusLocal"},_c=!1,gc=!1,ar=!1,Do=!1,Ao,Eo;function Qh(){if(navigator.onLine===!1)return"local";if(!_c)return gc?"reconnecting":"connecting";return Do?"saving":"saved"}function Sn(){let t=Qh();lc.dataset.state=t,lc.textContent=C(Gh[t])}function Zh(){if(!ar)ar=!0,clearTimeout(Ao),Ao=setTimeout(()=>{if(ar)Do=!0,Sn()},1500);clearTimeout(Eo),Eo=setTimeout(mc,300)}function mc(){if(!ar)return;if(pc()&&Ee.bufferedAmount>0){Eo=setTimeout(mc,100);return}ar=!1,clearTimeout(Ao),Do=!1,Sn()}function cc(t){if(_c=t,t)gc=!0;Sn()}function tp(t){let e=document.getElementById("sync-status");if(!e){e=document.createElement("span"),e.id="sync-status";let n=document.getElementById("sync-slot");if(n)n.append(e);else t.before(e)}return e}function ep(){let t=B("div",{class:"sr-only",role:"status","aria-live":"polite"});return document.body.append(t),t}function bc(t){qh.textContent=t}window.addEventListener("offline",()=>{Sn(),bc(C("announceOffline"))});window.addEventListener("online",()=>{Sn(),bc(C("announceOnline"))});Ne.subscribeLocalUpdates((t)=>{dr(Oo,t),Zh()});cr.subscribeLocalUpdates((t)=>{if(ei)dr(Mo,t)});function np(t){if(typeof t==="string")return;let e=new Uint8Array(t);if(e.length===0)return;let n=e[0],r=e.subarray(1);switch(n){case dc:{let i=Dt.decode(r),o=Ne.export({mode:"update",from:i});if(dr(Oo,o),!ei)ei=!0,dr(Mo,cr.encodeAll());if(!ti)ti=i,ac();break}case Oo:try{Ne.import(r),ac()}catch(i){console.error("failed to import update",i)}break;case Mo:try{cr.apply(r)}catch(i){console.error("failed to apply presence",i)}break;default:console.warn("unknown frame tag",n)}}function wc(){let t=new WebSocket(Kh);t.binaryType="arraybuffer",Ee=t,t.onopen=()=>{Qr=hc,cc(!0),ei=!1,dr(dc,Ne.oplogVersion().encode())},t.onmessage=(e)=>np(e.data),t.onerror=()=>{t.close()},t.onclose=()=>{if(Ee===t)Ee=null;if(yc)return;cc(!1),setTimeout(wc,Qr),Qr=Math.min(Qr*2,Yh)}}var yc=!1;window.addEventListener("note:detach",()=>{yc=!0,Ee?.close(),Zr?.destroy(),Zr=null});Sn();wc(); - -//# debugId=0E2F6C17ACB8E4C864756E2164756E21 -//# sourceMappingURL=editor.js.map diff --git a/assets/editor.js.map b/assets/editor.js.map deleted file mode 100644 index aa38022..0000000 --- a/assets/editor.js.map +++ /dev/null @@ -1,37 +0,0 @@ -{ - "version": 3, - "sources": ["../web/node_modules/loro-crdt/web/snippets/loro-wasm-974365e04a0511fb/inline0.js", "../web/node_modules/loro-crdt/web/loro_wasm.js", "../web/node_modules/loro-crdt/web/index.js", "../web/node_modules/orderedmap/dist/index.js", "../web/node_modules/prosemirror-model/dist/index.js", "../web/node_modules/prosemirror-transform/dist/index.js", "../web/node_modules/prosemirror-state/dist/index.js", "../web/node_modules/prosemirror-view/dist/index.js", "../web/node_modules/lib0/trait/equality.js", "../web/node_modules/lib0/object.js", "../web/node_modules/lib0/function.js", "../web/node_modules/lib0/diff.js", "../web/node_modules/loro-prosemirror/dist/index.js", "../web/node_modules/prosemirror-schema-basic/dist/index.js", "../web/node_modules/prosemirror-schema-list/dist/index.js", "../web/node_modules/w3c-keyname/index.js", "../web/node_modules/prosemirror-keymap/dist/index.js", "../web/node_modules/prosemirror-commands/dist/index.js", "../web/src/i18n.ts", "../web/node_modules/prosemirror-inputrules/dist/index.js", "../web/node_modules/prosemirror-dropcursor/dist/index.js", "../web/node_modules/prosemirror-gapcursor/dist/index.js", "../web/src/editing.ts", "../web/src/dom.ts", "../web/src/noteLinks.ts", "../web/src/floating.ts", "../web/src/toolbar.ts", "../web/src/editor.ts"], - "sourcesContent": [ - "\nconst kinds = ['Map', 'List', 'MovableList', 'Text', 'Tree', 'Counter'];\nexport function stateOptions(options, document) {\n if (typeof options !== 'object' || options === null || Array.isArray(options)) throw new Error('Invalid toContainerTree options');\n for (const key of Object.keys(options)) {\n if (key !== 'text' && !(document && key === 'roots')) throw new Error('Unknown toContainerTree option: ' + key);\n }\n if (document && options.roots !== undefined && !Array.isArray(options.roots)) throw new Error('roots must be an array');\n return options;\n}\nexport function stateSlice(node, start, totalLength) { return {cid:node.cid, start, totalLength, items:node.value}; }\nexport function stateContainer(kind, cid, value) { return {type: kinds[kind], cid, value}; }\nexport function stateCid(peer,counter,kind) { return 'cid:'+counter+'@'+peer+':'+kinds[kind]; }\nexport function stateRootCid(name,kind) { return 'cid:root-'+name+':'+kinds[kind]; }\nexport function stateValue(value) { return {type: 'Value', value}; }\nexport function stateBinary(bytes) { return bytes.slice(); }\nexport function stateIndex(array, index, value) { Object.defineProperty(array, index, {value, enumerable: true, writable: true, configurable: true}); }\nexport function stateSet(object, key, value) { Object.defineProperty(object, key, {value, enumerable: true, writable: true, configurable: true}); }\n", - "import { stateBinary, stateCid, stateContainer, stateIndex, stateOptions, stateRootCid, stateSet, stateSlice, stateValue } from './snippets/loro-wasm-974365e04a0511fb/inline0.js';\n\nlet wasm;\n\nconst heap = new Array(128).fill(undefined);\n\nheap.push(undefined, null, true, false);\n\nfunction getObject(idx) { return heap[idx]; }\n\nlet WASM_VECTOR_LEN = 0;\n\nlet cachedUint8ArrayMemory0 = null;\n\nfunction getUint8ArrayMemory0() {\n if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {\n cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachedUint8ArrayMemory0;\n}\n\nconst cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder('utf-8') : { encode: () => { throw Error('TextEncoder not available') } } );\n\nconst encodeString = (typeof cachedTextEncoder.encodeInto === 'function'\n ? function (arg, view) {\n return cachedTextEncoder.encodeInto(arg, view);\n}\n : function (arg, view) {\n const buf = cachedTextEncoder.encode(arg);\n view.set(buf);\n return {\n read: arg.length,\n written: buf.length\n };\n});\n\nfunction passStringToWasm0(arg, malloc, realloc) {\n\n if (realloc === undefined) {\n const buf = cachedTextEncoder.encode(arg);\n const ptr = malloc(buf.length, 1) >>> 0;\n getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);\n WASM_VECTOR_LEN = buf.length;\n return ptr;\n }\n\n let len = arg.length;\n let ptr = malloc(len, 1) >>> 0;\n\n const mem = getUint8ArrayMemory0();\n\n let offset = 0;\n\n for (; offset < len; offset++) {\n const code = arg.charCodeAt(offset);\n if (code > 0x7F) break;\n mem[ptr + offset] = code;\n }\n\n if (offset !== len) {\n if (offset !== 0) {\n arg = arg.slice(offset);\n }\n ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;\n const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);\n const ret = encodeString(arg, view);\n\n offset += ret.written;\n ptr = realloc(ptr, len, offset, 1) >>> 0;\n }\n\n WASM_VECTOR_LEN = offset;\n return ptr;\n}\n\nlet cachedDataViewMemory0 = null;\n\nfunction getDataViewMemory0() {\n if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {\n cachedDataViewMemory0 = new DataView(wasm.memory.buffer);\n }\n return cachedDataViewMemory0;\n}\n\nlet heap_next = heap.length;\n\nfunction addHeapObject(obj) {\n if (heap_next === heap.length) heap.push(heap.length + 1);\n const idx = heap_next;\n heap_next = heap[idx];\n\n heap[idx] = obj;\n return idx;\n}\n\nfunction handleError(f, args) {\n try {\n return f.apply(this, args);\n } catch (e) {\n wasm.__wbindgen_exn_store(addHeapObject(e));\n }\n}\n\nconst cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } );\n\nif (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); };\n\nfunction getStringFromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));\n}\n\nfunction dropObject(idx) {\n if (idx < 132) return;\n heap[idx] = heap_next;\n heap_next = idx;\n}\n\nfunction takeObject(idx) {\n const ret = getObject(idx);\n dropObject(idx);\n return ret;\n}\n\nfunction getArrayU8FromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);\n}\n\nfunction isLikeNone(x) {\n return x === undefined || x === null;\n}\n\nconst CLOSURE_DTORS = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(state => {\n wasm.__wbindgen_export_4.get(state.dtor)(state.a, state.b)\n});\n\nfunction makeMutClosure(arg0, arg1, dtor, f) {\n const state = { a: arg0, b: arg1, cnt: 1, dtor };\n const real = (...args) => {\n // First up with a closure we increment the internal reference\n // count. This ensures that the Rust closure environment won't\n // be deallocated while we're invoking it.\n state.cnt++;\n const a = state.a;\n state.a = 0;\n try {\n return f(a, state.b, ...args);\n } finally {\n if (--state.cnt === 0) {\n wasm.__wbindgen_export_4.get(state.dtor)(a, state.b);\n CLOSURE_DTORS.unregister(state);\n } else {\n state.a = a;\n }\n }\n };\n real.original = state;\n CLOSURE_DTORS.register(real, state, state);\n return real;\n}\n\nfunction debugString(val) {\n // primitive types\n const type = typeof val;\n if (type == 'number' || type == 'boolean' || val == null) {\n return `${val}`;\n }\n if (type == 'string') {\n return `\"${val}\"`;\n }\n if (type == 'symbol') {\n const description = val.description;\n if (description == null) {\n return 'Symbol';\n } else {\n return `Symbol(${description})`;\n }\n }\n if (type == 'function') {\n const name = val.name;\n if (typeof name == 'string' && name.length > 0) {\n return `Function(${name})`;\n } else {\n return 'Function';\n }\n }\n // objects\n if (Array.isArray(val)) {\n const length = val.length;\n let debug = '[';\n if (length > 0) {\n debug += debugString(val[0]);\n }\n for(let i = 1; i < length; i++) {\n debug += ', ' + debugString(val[i]);\n }\n debug += ']';\n return debug;\n }\n // Test for built-in\n const builtInMatches = /\\[object ([^\\]]+)\\]/.exec(toString.call(val));\n let className;\n if (builtInMatches && builtInMatches.length > 1) {\n className = builtInMatches[1];\n } else {\n // Failed to match the standard '[object ClassName]'\n return toString.call(val);\n }\n if (className == 'Object') {\n // we're a user defined class or Object\n // JSON.stringify avoids problems with cycles, and is generally much\n // easier than looping through ownProperties of `val`.\n try {\n return 'Object(' + JSON.stringify(val) + ')';\n } catch (_) {\n return 'Object';\n }\n }\n // errors\n if (val instanceof Error) {\n return `${val.name}: ${val.message}\\n${val.stack}`;\n }\n // TODO we could test for more things here, like `Set`s and `Map`s.\n return className;\n}\n/**\n * Get the version of Loro\n * @returns {string}\n */\nexport function LORO_VERSION() {\n let deferred1_0;\n let deferred1_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.LORO_VERSION(retptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n deferred1_0 = r0;\n deferred1_1 = r1;\n return getStringFromWasm0(r0, r1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n}\n\nfunction passArray8ToWasm0(arg, malloc) {\n const ptr = malloc(arg.length * 1, 1) >>> 0;\n getUint8ArrayMemory0().set(arg, ptr / 1);\n WASM_VECTOR_LEN = arg.length;\n return ptr;\n}\n/**\n * Decode the metadata of the import blob.\n *\n * This method is useful to get the following metadata of the import blob:\n *\n * - startVersionVector\n * - endVersionVector\n * - startTimestamp\n * - endTimestamp\n * - mode\n * - changeNum\n * @param {Uint8Array} blob\n * @param {boolean} check_checksum\n * @returns {ImportBlobMetadata}\n */\nexport function decodeImportBlobMeta(blob, check_checksum) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(blob, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.decodeImportBlobMeta(retptr, ptr0, len0, check_checksum);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n}\n\nexport function callPendingEvents() {\n wasm.callPendingEvents();\n}\n\n/**\n * Redacts sensitive content in JSON updates within the specified version range.\n *\n * This function allows you to share document history while removing potentially sensitive content.\n * It preserves the document structure and collaboration capabilities while replacing content with\n * placeholders according to these redaction rules:\n *\n * - Preserves delete and move operations\n * - Replaces text insertion content with the Unicode replacement character\n * - Substitutes list and map insert values with null\n * - Maintains structure of child containers\n * - Replaces text mark values with null\n * - Preserves map keys and text annotation keys\n *\n * @param {Object|string} jsonUpdates - The JSON updates to redact (object or JSON string)\n * @param {Object} versionRange - Version range defining what content to redact,\n * format: { peerId: [startCounter, endCounter], ... }\n * @returns {Object} The redacted JSON updates\n * @param {string | JsonSchema} json_updates\n * @param {any} version_range\n * @returns {JsonSchema}\n */\nexport function redactJsonUpdates(json_updates, version_range) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.redactJsonUpdates(retptr, addHeapObject(json_updates), addHeapObject(version_range));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n}\n\n/**\n * Returns whether `value` is a syntactically valid container ID.\n * @param {string} value\n * @returns {boolean}\n */\nexport function isValidContainerId(value) {\n const ptr0 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.isValidContainerId(ptr0, len0);\n return ret !== 0;\n}\n\nexport function run() {\n wasm.run();\n}\n\nfunction passArrayJsValueToWasm0(array, malloc) {\n const ptr = malloc(array.length * 4, 4) >>> 0;\n const mem = getDataViewMemory0();\n for (let i = 0; i < array.length; i++) {\n mem.setUint32(ptr + 4 * i, addHeapObject(array[i]), true);\n }\n WASM_VECTOR_LEN = array.length;\n return ptr;\n}\n/**\n * @param {({ peer: PeerID, counter: number })[]} frontiers\n * @returns {Uint8Array}\n */\nexport function encodeFrontiers(frontiers) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(frontiers, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.encodeFrontiers(retptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v2 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v2;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {{ peer: PeerID, counter: number }[]}\n */\nexport function decodeFrontiers(bytes) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.decodeFrontiers(retptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n}\n\n/**\n * Enable debug info of Loro\n */\nexport function setDebug() {\n wasm.setDebug();\n}\n\nlet stack_pointer = 128;\n\nfunction addBorrowedObject(obj) {\n if (stack_pointer == 1) throw new Error('out of js stack');\n heap[--stack_pointer] = obj;\n return stack_pointer;\n}\n\nfunction _assertClass(instance, klass) {\n if (!(instance instanceof klass)) {\n throw new Error(`expected instance of ${klass.name}`);\n }\n}\n\nfunction getArrayJsValueFromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n const mem = getDataViewMemory0();\n const result = [];\n for (let i = ptr; i < ptr + 4 * len; i += 4) {\n result.push(takeObject(mem.getUint32(i, true)));\n }\n return result;\n}\nfunction __wbg_adapter_58(arg0, arg1, arg2) {\n wasm._dyn_core_ed718c3d60ebd546___ops__function__FnMut_______Output______as_wasm_bindgen_cfd5deec16e3bd1c___closure__WasmClosure___describe__invoke___wasm_bindgen_cfd5deec16e3bd1c___JsValue_____(arg0, arg1, addHeapObject(arg2));\n}\n\nfunction __wbg_adapter_61(arg0, arg1) {\n wasm._dyn_core_ed718c3d60ebd546___ops__function__FnMut_____Output______as_wasm_bindgen_cfd5deec16e3bd1c___closure__WasmClosure___describe__invoke______(arg0, arg1);\n}\n\nconst AwarenessWasmFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_awarenesswasm_free(ptr >>> 0, 1));\n/**\n * `Awareness` is a structure that tracks the ephemeral state of peers.\n *\n * It can be used to synchronize cursor positions, selections, and the names of the peers.\n *\n * The state of a specific peer is expected to be removed after a specified timeout. Use\n * `remove_outdated` to eliminate outdated states.\n */\nexport class AwarenessWasm {\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n AwarenessWasmFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_awarenesswasm_free(ptr, 0);\n }\n /**\n * Get the state of all peers.\n * @returns {{[peer in PeerID]: unknown}}\n */\n getAllStates() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.awarenesswasm_getAllStates(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the timestamp of the state of a given peer.\n * @param {number | bigint | `${number}`} peer\n * @returns {number | undefined}\n */\n getTimestamp(peer) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-32);\n wasm.awarenesswasm_getTimestamp(retptr, this.__wbg_ptr, addHeapObject(peer));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r2 = getDataViewMemory0().getFloat64(retptr + 8 * 1, true);\n var r4 = getDataViewMemory0().getInt32(retptr + 4 * 4, true);\n var r5 = getDataViewMemory0().getInt32(retptr + 4 * 5, true);\n if (r5) {\n throw takeObject(r4);\n }\n return r0 === 0 ? undefined : r2;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(32);\n }\n }\n /**\n * Sets the state of the local peer.\n * @param {any} value\n */\n setLocalState(value) {\n wasm.awarenesswasm_setLocalState(this.__wbg_ptr, addHeapObject(value));\n }\n /**\n * Remove the states of outdated peers.\n * @returns {PeerID[]}\n */\n removeOutdated() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.awarenesswasm_removeOutdated(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Creates a new `Awareness` instance.\n *\n * The `timeout` parameter specifies the duration in milliseconds.\n * A state of a peer is considered outdated, if the last update of the state of the peer\n * is older than the `timeout`.\n * @param {number | bigint | `${number}`} peer\n * @param {number} timeout\n */\n constructor(peer, timeout) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.awarenesswasm_new(retptr, addHeapObject(peer), timeout);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n this.__wbg_ptr = r0 >>> 0;\n AwarenessWasmFinalization.register(this, this.__wbg_ptr, this);\n return this;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the PeerID of the local peer.\n * @returns {PeerID}\n */\n peer() {\n const ret = wasm.awarenesswasm_peer(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Applies the encoded state of peers.\n *\n * Each peer's deletion countdown will be reset upon update, requiring them to pass through the `timeout`\n * interval again before being eligible for deletion.\n * @param {Uint8Array} encoded_peers_info\n * @returns {{ updated: PeerID[], added: PeerID[] }}\n */\n apply(encoded_peers_info) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(encoded_peers_info, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.awarenesswasm_apply(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get all the peers\n * @returns {PeerID[]}\n */\n peers() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.awarenesswasm_peers(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Encodes the state of the given peers.\n * @param {Array} peers\n * @returns {Uint8Array}\n */\n encode(peers) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.awarenesswasm_encode(retptr, this.__wbg_ptr, addHeapObject(peers));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the number of peers.\n * @returns {number}\n */\n length() {\n const ret = wasm.awarenesswasm_length(this.__wbg_ptr);\n return ret;\n }\n /**\n * If the state is empty.\n * @returns {boolean}\n */\n isEmpty() {\n const ret = wasm.awarenesswasm_isEmpty(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the state of a given peer.\n * @param {number | bigint | `${number}`} peer\n * @returns {any}\n */\n getState(peer) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.awarenesswasm_getState(retptr, this.__wbg_ptr, addHeapObject(peer));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Encodes the state of all peers.\n * @returns {Uint8Array}\n */\n encodeAll() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.awarenesswasm_encodeAll(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst ChangeModifierFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_changemodifier_free(ptr >>> 0, 1));\n\nexport class ChangeModifier {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(ChangeModifier.prototype);\n obj.__wbg_ptr = ptr;\n ChangeModifierFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n ChangeModifierFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_changemodifier_free(ptr, 0);\n }\n /**\n * @param {string} message\n * @returns {ChangeModifier}\n */\n setMessage(message) {\n const ptr0 = passStringToWasm0(message, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.changemodifier_setMessage(this.__wbg_ptr, ptr0, len0);\n return ChangeModifier.__wrap(ret);\n }\n /**\n * @param {number} timestamp\n * @returns {ChangeModifier}\n */\n setTimestamp(timestamp) {\n const ret = wasm.changemodifier_setTimestamp(this.__wbg_ptr, timestamp);\n return ChangeModifier.__wrap(ret);\n }\n}\n\nconst CursorFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_cursor_free(ptr >>> 0, 1));\n/**\n * Cursor is a stable position representation in the doc.\n * When expressing the position of a cursor, using \"index\" can be unstable\n * because the cursor's position may change due to other deletions and insertions,\n * requiring updates with each edit. To stably represent a position or range within\n * a list structure, we can utilize the ID of each item/character on List CRDT or\n * Text CRDT for expression.\n *\n * Loro optimizes State metadata by not storing the IDs of deleted elements. This\n * approach complicates tracking cursors since they rely on these IDs. The solution\n * recalculates position by replaying relevant history to update cursors\n * accurately. To minimize the performance impact of history replay, the system\n * updates cursor info to reference only the IDs of currently present elements,\n * thereby reducing the need for replay.\n *\n * @example\n * ```ts\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"123\");\n * const pos0 = text.getCursor(0, 0);\n * {\n * const ans = doc.getCursorPos(pos0!);\n * expect(ans.offset).toBe(0);\n * }\n * text.insert(0, \"1\");\n * {\n * const ans = doc.getCursorPos(pos0!);\n * expect(ans.offset).toBe(1);\n * }\n * ```\n */\nexport class Cursor {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(Cursor.prototype);\n obj.__wbg_ptr = ptr;\n CursorFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n CursorFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_cursor_free(ptr, 0);\n }\n /**\n * Get the id of the given container.\n * @returns {ContainerID}\n */\n containerId() {\n const ret = wasm.cursor_containerId(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the ID that represents the position.\n *\n * It can be undefined if it's not bind into a specific ID.\n * @returns {{ peer: PeerID, counter: number } | undefined}\n */\n pos() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.cursor_pos(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * \"Cursor\"\n * @returns {any}\n */\n kind() {\n const ret = wasm.cursor_kind(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get which side of the character/list item the cursor is on.\n * @returns {Side}\n */\n side() {\n const ret = wasm.cursor_side(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Decode the cursor from a Uint8Array.\n * @param {Uint8Array} data\n * @returns {Cursor}\n */\n static decode(data) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.cursor_decode(retptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return Cursor.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Encode the cursor into a Uint8Array.\n * @returns {Uint8Array}\n */\n encode() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.cursor_encode(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst EphemeralStoreWasmFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_ephemeralstorewasm_free(ptr >>> 0, 1));\n\nexport class EphemeralStoreWasm {\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n EphemeralStoreWasmFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_ephemeralstorewasm_free(ptr, 0);\n }\n /**\n * @returns {any}\n */\n getAllStates() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.ephemeralstorewasm_getAllStates(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n removeOutdated() {\n wasm.ephemeralstorewasm_removeOutdated(this.__wbg_ptr);\n }\n /**\n * @param {Function} f\n * @returns {any}\n */\n subscribeLocalUpdates(f) {\n const ret = wasm.ephemeralstorewasm_subscribeLocalUpdates(this.__wbg_ptr, addHeapObject(f));\n return takeObject(ret);\n }\n /**\n * @param {string} key\n * @returns {any}\n */\n get(key) {\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.ephemeralstorewasm_get(this.__wbg_ptr, ptr0, len0);\n return takeObject(ret);\n }\n /**\n * Creates a new `EphemeralStore` instance.\n *\n * The `timeout` parameter specifies the duration in milliseconds.\n * A state of a peer is considered outdated, if the last update of the state of the peer\n * is older than the `timeout`.\n * @param {number} timeout\n */\n constructor(timeout) {\n const ret = wasm.ephemeralstorewasm_new(timeout);\n this.__wbg_ptr = ret >>> 0;\n EphemeralStoreWasmFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * @param {string} key\n * @param {any} value\n */\n set(key, value) {\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.ephemeralstorewasm_set(this.__wbg_ptr, ptr0, len0, addHeapObject(value));\n }\n /**\n * @returns {string[]}\n */\n keys() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.ephemeralstorewasm_keys(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @param {Uint8Array} data\n */\n apply(data) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.ephemeralstorewasm_apply(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @param {string} key\n */\n delete(key) {\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.ephemeralstorewasm_delete(this.__wbg_ptr, ptr0, len0);\n }\n /**\n * @param {string} key\n * @returns {Uint8Array}\n */\n encode(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.ephemeralstorewasm_encode(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v2 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v2;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * If the state is empty.\n * @returns {boolean}\n */\n isEmpty() {\n const ret = wasm.ephemeralstorewasm_isEmpty(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * @returns {Uint8Array}\n */\n encodeAll() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.ephemeralstorewasm_encodeAll(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n const ret = wasm.ephemeralstorewasm_subscribe(this.__wbg_ptr, addHeapObject(f));\n return takeObject(ret);\n }\n}\n\nconst LoroCounterFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_lorocounter_free(ptr >>> 0, 1));\n/**\n * The handler of a counter container.\n */\nexport class LoroCounter {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroCounter.prototype);\n obj.__wbg_ptr = ptr;\n LoroCounterFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroCounterFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_lorocounter_free(ptr, 0);\n }\n /**\n * Convert this attached container and all descendants to an independent tree.\n * Text format applies recursively. Does not commit; throws for detached\n * containers, unsupported types, invalid options, or nesting above 256.\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerNode}\n */\n toContainerTree(opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_toContainerTree(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Whether the container is attached to a docuemnt.\n *\n * If it's detached, the operations on the container will not be persisted.\n * @returns {boolean}\n */\n isAttached() {\n const ret = wasm.lorocounter_isAttached(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the attached container associated with this.\n *\n * Returns an attached `Container` that equals to this or created by this, otherwise `undefined`.\n * @returns {LoroTree | undefined}\n */\n getAttached() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_getAttached(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the value of the counter.\n * @returns {number}\n */\n getShallowValue() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_getShallowValue(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getFloat64(retptr + 8 * 0, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n return r0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * The container id of this handler.\n * @returns {ContainerID}\n */\n get id() {\n const ret = wasm.lorocounter_id(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Create a new LoroCounter.\n */\n constructor() {\n const ret = wasm.lorocounter_new();\n this.__wbg_ptr = ret >>> 0;\n LoroCounterFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * \"Counter\"\n * @returns {'Counter'}\n */\n kind() {\n const ret = wasm.lorocounter_kind(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the parent container of the counter container.\n *\n * - The parent container of the root counter is `undefined`.\n * - The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n * @returns {Container | undefined}\n */\n parent() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_parent(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @returns {number}\n */\n toJSON() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_getShallowValue(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getFloat64(retptr + 8 * 0, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n return r0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Decrement the counter by the given value.\n * @param {number} value\n */\n decrement(value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_decrement(retptr, this.__wbg_ptr, value);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the value of the counter.\n * @returns {number}\n */\n get value() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_getShallowValue(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getFloat64(retptr + 8 * 0, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n return r0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Increment the counter by the given value.\n * @param {number} value\n */\n increment(value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_increment(retptr, this.__wbg_ptr, value);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Subscribe to the changes of the counter.\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorocounter_subscribe(retptr, this.__wbg_ptr, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst LoroDocFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_lorodoc_free(ptr >>> 0, 1));\n/**\n * The CRDTs document. Loro supports different CRDTs include [**List**](LoroList),\n * [**RichText**](LoroText), [**Map**](LoroMap) and [**Movable Tree**](LoroTree),\n * you could build all kind of applications by these.\n *\n * **Important:** Loro is a pure library and does not handle network protocols.\n * It is the responsibility of the user to manage the storage, loading, and synchronization\n * of the bytes exported by Loro in a manner suitable for their specific environment.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\"\n *\n * const loro = new LoroDoc();\n * const text = loro.getText(\"text\");\n * const list = loro.getList(\"list\");\n * const map = loro.getMap(\"Map\");\n * const tree = loro.getTree(\"tree\");\n * ```\n */\nexport class LoroDoc {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroDoc.prototype);\n obj.__wbg_ptr = ptr;\n LoroDocFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroDocFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_lorodoc_free(ptr, 0);\n }\n /**\n * Apply a batch of diff to the document\n *\n * A diff batch represents a set of changes between two versions of the document.\n * You can calculate a diff batch using `doc.diff()`.\n *\n * Changes are associated with container IDs. During diff application, if new containers were created in the source\n * document, they will be assigned fresh IDs in the target document. Loro automatically handles remapping these\n * container IDs from their original IDs to the new IDs as the diff is applied.\n *\n * @example\n * ```ts\n * const doc1 = new LoroDoc();\n * const doc2 = new LoroDoc();\n *\n * // Make some changes to doc1\n * const text = doc1.getText(\"text\");\n * text.insert(0, \"Hello\");\n *\n * // Calculate diff between empty and current state\n * const diff = doc1.diff([], doc1.frontiers());\n *\n * // Apply changes to doc2\n * doc2.applyDiff(diff);\n * console.log(doc2.getText(\"text\").toString()); // \"Hello\"\n * ```\n *\n * Pass `{ fullState: true }` when applying the result of `doc.diff()` to a document that may\n * keep hidden state for a mergeable child the diff makes visible again (e.g. applying\n * `doc.diff(afterDelete, beforeDelete)` to `doc` itself or to a copy of it). The child's\n * entry is then read as its full content and aligned with that hidden state. Without it\n * (the default), entries are applied as increments, which is right for events forwarded to\n * a document that shares the source's hidden state. Never pass it for events from local\n * commits; see `ApplyDiffOptions.fullState`.\n *\n * ```ts\n * const text = doc.getMap(\"m\").ensureMergeableText(\"t\");\n * text.insert(0, \"hello\");\n * const before = doc.frontiers();\n * doc.getMap(\"m\").delete(\"t\");\n * doc.applyDiff(doc.diff(doc.frontiers(), before), { fullState: true });\n * console.log(doc.getMap(\"m\").get(\"t\").toString()); // \"hello\"\n * ```\n * @param {[ContainerID, Diff|JsonDiff][]} diff\n * @param {ApplyDiffOptions | null} [options]\n */\n applyDiff(diff, options) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_applyDiff(retptr, this.__wbg_ptr, addHeapObject(diff), isLikeNone(options) ? 0 : addHeapObject(options));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Check if the doc contains the full history.\n * @returns {boolean}\n */\n isShallow() {\n const ret = wasm.lorodoc_isShallow(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the number of changes in the oplog.\n * @returns {number}\n */\n changeCount() {\n const ret = wasm.lorodoc_changeCount(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * Get the value or container at the given path\n *\n * The path can be specified in different ways depending on the container type:\n *\n * For Tree:\n * 1. Using node IDs: `tree/{node_id}/property`\n * 2. Using indices: `tree/0/1/property`\n *\n * For List and MovableList:\n * - Using indices: `list/0` or `list/1/property`\n *\n * For Map:\n * - Using keys: `map/key` or `map/nested/property`\n *\n * For tree structures, index-based paths follow depth-first traversal order.\n * The indices start from 0 and represent the position of a node among its siblings.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"key\", 1);\n * console.log(doc.getByPath(\"map/key\")); // 1\n * console.log(doc.getByPath(\"map\")); // LoroMap\n * ```\n * @param {string} path\n * @returns {Value | Container | undefined}\n */\n getByPath(path) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(path, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_getByPath(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get a LoroCounter by container id\n *\n * If the container does not exist, an error will be thrown.\n * @param {ContainerID | string} cid\n * @returns {LoroCounter}\n */\n getCounter(cid) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getCounter(retptr, this.__wbg_ptr, addBorrowedObject(cid));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroCounter.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * `detached` indicates that the `DocState` is not synchronized with the latest version of `OpLog`.\n *\n * > The document becomes detached during a `checkout` operation.\n * > Being `detached` implies that the `DocState` is not synchronized with the latest version of the `OpLog`.\n * > In a detached state, the document is not editable by default, and any `import` operations will be\n * > recorded in the `OpLog` without being applied to the `DocState`.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * const frontiers = doc.frontiers();\n * text.insert(0, \"Hello World!\");\n * console.log(doc.isDetached()); // false\n * doc.checkout(frontiers);\n * console.log(doc.isDetached()); // true\n * doc.attach();\n * console.log(doc.isDetached()); // false\n * ```\n * @returns {boolean}\n */\n isDetached() {\n const ret = wasm.lorodoc_isDetached(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get peer id in decimal string.\n * @returns {PeerID}\n */\n get peerIdStr() {\n const ret = wasm.lorodoc_peerIdStr(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Set the peer ID of the current writer.\n *\n * It must be a number, a BigInt, or a decimal string that can be parsed to a unsigned 64-bit integer.\n *\n * Note: use it with caution. You need to make sure there is not chance that two peers\n * have the same peer ID. Otherwise, we cannot ensure the consistency of the document.\n * @param {number | bigint | `${number}`} peer_id\n */\n setPeerId(peer_id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_setPeerId(retptr, this.__wbg_ptr, addHeapObject(peer_id));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the absolute position of the given Cursor\n *\n * @example\n * ```ts\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"123\");\n * const pos0 = text.getCursor(0, 0);\n * {\n * const ans = doc.getCursorPos(pos0!);\n * expect(ans.offset).toBe(0);\n * }\n * text.insert(0, \"1\");\n * {\n * const ans = doc.getCursorPos(pos0!);\n * expect(ans.offset).toBe(1);\n * }\n * ```\n * @param {Cursor} cursor\n * @returns {{ update?: Cursor, offset: number, side: Side } | undefined}\n */\n getCursorPos(cursor) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n _assertClass(cursor, Cursor);\n wasm.lorodoc_getCursorPos(retptr, this.__wbg_ptr, cursor.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Check if the doc contains the target container.\n *\n * A root container always exists, while a normal container exists\n * if it has ever been created on the doc.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroMap, LoroText, LoroList } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * doc.setPeerId(\"1\");\n * const text = doc.getMap(\"map\").setContainer(\"text\", new LoroText());\n * const list = doc.getMap(\"map\").setContainer(\"list\", new LoroList());\n * expect(doc.isContainerExists(\"cid:root-map:Map\")).toBe(true);\n * expect(doc.isContainerExists(\"cid:0@1:Text\")).toBe(true);\n * expect(doc.isContainerExists(\"cid:1@1:List\")).toBe(true);\n *\n * const doc2 = new LoroDoc();\n * // Containers exist, as long as the history or the doc state include it\n * doc.detach();\n * doc2.import(doc.export({ mode: \"update\" }));\n * expect(doc2.isContainerExists(\"cid:root-map:Map\")).toBe(true);\n * expect(doc2.isContainerExists(\"cid:0@1:Text\")).toBe(true);\n * expect(doc2.isContainerExists(\"cid:1@1:List\")).toBe(true);\n * ```\n * @param {ContainerID} container_id\n * @returns {boolean}\n */\n hasContainer(container_id) {\n const ret = wasm.lorodoc_hasContainer(this.__wbg_ptr, addHeapObject(container_id));\n return ret !== 0;\n }\n /**\n * Import a batch of updates or snapshots.\n *\n * It's more efficient than importing updates one by one.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * const updates = doc.export({ mode: \"update\" });\n * const snapshot = doc.export({ mode: \"snapshot\" });\n * const doc2 = new LoroDoc();\n * doc2.importBatch([snapshot, updates]);\n * ```\n * @param {Uint8Array[]} data\n * @returns {ImportStatus}\n */\n importBatch(data) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_importBatch(retptr, this.__wbg_ptr, addHeapObject(data));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Compare the ordering of two Frontiers.\n *\n * It's assumed that both Frontiers are included by the doc. Otherwise, an error will be thrown.\n *\n * Return value:\n *\n * - -1: a < b\n * - 0: a == b\n * - 1: a > b\n * - undefined: a ∥ b: a and b are concurrent\n * @param {({ peer: PeerID, counter: number })[]} a\n * @param {({ peer: PeerID, counter: number })[]} b\n * @returns {-1 | 1 | 0 | undefined}\n */\n cmpFrontiers(a, b) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(a, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArrayJsValueToWasm0(b, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n wasm.lorodoc_cmpFrontiers(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Debug the size of the history\n */\n debugHistory() {\n wasm.lorodoc_debugHistory(this.__wbg_ptr);\n }\n /**\n * Create a loro document from the snapshot.\n *\n * @see You can learn more [here](https://loro.dev/docs/tutorial/encoding).\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\"\n *\n * const doc = new LoroDoc();\n * // ...\n * const bytes = doc.export({ mode: \"snapshot\" });\n * const loro = LoroDoc.fromSnapshot(bytes);\n * ```\n * @param {Uint8Array} snapshot\n * @returns {LoroDoc}\n */\n static fromSnapshot(snapshot) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(snapshot, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_fromSnapshot(retptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroDoc.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the change that contains the specific ID\n * @param {{ peer: PeerID, counter: number }} id\n * @returns {Change}\n */\n getChangeAt(id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getChangeAt(retptr, this.__wbg_ptr, addHeapObject(id));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the version vector of the latest known version in OpLog.\n *\n * If you checkout to a specific version, this version vector will not change.\n * @returns {VersionVector}\n */\n oplogVersion() {\n const ret = wasm.lorodoc_oplogVersion(this.__wbg_ptr);\n return VersionVector.__wrap(ret);\n }\n /**\n * Get a LoroMovableList by container id\n *\n * The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n *\n * If the container does not exist, an error will be thrown.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getMovableList(\"list\");\n * ```\n * @param {ContainerID | string} cid\n * @returns {LoroMovableList}\n */\n getMovableList(cid) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getMovableList(retptr, this.__wbg_ptr, addBorrowedObject(cid));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroMovableList.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Convert frontiers to a version vector\n *\n * Learn more about frontiers and version vector [here](https://loro.dev/docs/advanced/version_deep_dive)\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * const frontiers = doc.frontiers();\n * const version = doc.frontiersToVV(frontiers);\n * ```\n * @param {({ peer: PeerID, counter: number })[]} frontiers\n * @returns {VersionVector}\n */\n frontiersToVV(frontiers) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(frontiers, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_frontiersToVV(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return VersionVector.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get all of changes in the oplog.\n *\n * Note: this method is expensive when the oplog is large. O(n)\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * const changes = doc.getAllChanges();\n *\n * for (let [peer, c] of changes.entries()){\n * console.log(\"peer: \", peer);\n * for (let change of c){\n * console.log(\"change: \", change);\n * }\n * }\n * ```\n * @returns {Map}\n */\n getAllChanges() {\n const ret = wasm.lorodoc_getAllChanges(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the [frontiers](https://loro.dev/docs/advanced/version_deep_dive) of the latest version in OpLog.\n *\n * If you checkout to a specific version, this value will not change.\n * @returns {{ peer: PeerID, counter: number }[]}\n */\n oplogFrontiers() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_oplogFrontiers(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert a version vector to frontiers\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * const version = doc.version();\n * const frontiers = doc.vvToFrontiers(version);\n * ```\n * @param {VersionVector} vv\n * @returns {{ peer: PeerID, counter: number }[]}\n */\n vvToFrontiers(vv) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n _assertClass(vv, VersionVector);\n wasm.lorodoc_vvToFrontiers(retptr, this.__wbg_ptr, vv.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * The doc only contains the history since this version\n *\n * This is empty if the doc is not shallow.\n *\n * The ops included by the shallow history start version vector are not in the doc.\n * @returns {VersionVector}\n */\n shallowSinceVV() {\n const ret = wasm.lorodoc_shallowSinceVV(this.__wbg_ptr);\n return VersionVector.__wrap(ret);\n }\n /**\n * Set the rich text format configuration of the document.\n *\n * You need to config it if you use rich text `mark` method.\n * Specifically, you need to config the `expand` property of each style.\n *\n * Expand is used to specify the behavior of expanding when new text is inserted at the\n * beginning or end of the style.\n *\n * You can specify the `expand` option to set the behavior when inserting text at the boundary of the range.\n *\n * - `after`(default): when inserting text right after the given range, the mark will be expanded to include the inserted text\n * - `before`: when inserting text right before the given range, the mark will be expanded to include the inserted text\n * - `none`: the mark will not be expanded to include the inserted text at the boundaries\n * - `both`: when inserting text either right before or right after the given range, the mark will be expanded to include the inserted text\n *\n * @example\n * ```ts\n * const doc = new LoroDoc();\n * doc.configTextStyle({\n * bold: { expand: \"after\" },\n * link: { expand: \"before\" }\n * });\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello World!\");\n * text.mark({ start: 0, end: 5 }, \"bold\", true);\n * expect(text.toDelta()).toStrictEqual([\n * {\n * insert: \"Hello\",\n * attributes: {\n * bold: true,\n * },\n * },\n * {\n * insert: \" World!\",\n * },\n * ] as Delta[]);\n * ```\n * @param {{[key: string]: { expand: 'before'|'after'|'none'|'both' }}} styles\n */\n configTextStyle(styles) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_configTextStyle(retptr, this.__wbg_ptr, addHeapObject(styles));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get all ops of the change that contains the specific ID\n * @param {{ peer: PeerID, counter: number }} id\n * @returns {any[]}\n */\n getOpsInChange(id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getOpsInChange(retptr, this.__wbg_ptr, addHeapObject(id));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the shallow json format of the document state.\n *\n * Unlike `toJSON()` which recursively resolves all containers to their values,\n * `getShallowValue()` returns container IDs as strings for any nested containers.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * const tree = doc.getTree(\"tree\");\n * const map = doc.getMap(\"map\");\n * const shallowValue = doc.getShallowValue();\n * console.log(shallowValue);\n * // {\n * // list: 'cid:root-list:List',\n * // tree: 'cid:root-tree:Tree',\n * // map: 'cid:root-map:Map'\n * // }\n *\n * // It points to the same container as `list`\n * const listB = doc.getContainerById(shallowValue.list);\n * ```\n * @returns {Record}\n */\n getShallowValue() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getShallowValue(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Checkout the `DocState` to the latest version of `OpLog`.\n *\n * > The document becomes detached during a `checkout` operation.\n * > Being `detached` implies that the `DocState` is not synchronized with the latest version of the `OpLog`.\n * > In a detached state, the document is not editable by default, and any `import` operations will be\n * > recorded in the `OpLog` without being applied to the `DocState`.\n *\n * This has the same effect as `attach`.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * const frontiers = doc.frontiers();\n * text.insert(0, \"Hello World!\");\n * doc.checkout(frontiers);\n * // you need call `checkoutToLatest()` or `attach()` before changing the doc.\n * doc.checkoutToLatest();\n * text.insert(0, \"Hi\");\n * ```\n */\n checkoutToLatest() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_checkoutToLatest(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Compare the version of the OpLog with the specified frontiers.\n *\n * This method is useful to compare the version by only a small amount of data.\n *\n * This method returns an integer indicating the relationship between the version of the OpLog (referred to as 'self')\n * and the provided 'frontiers' parameter:\n *\n * - -1: The version of 'self' is either less than 'frontiers' or is non-comparable (parallel) to 'frontiers',\n * indicating that it is not definitively less than 'frontiers'.\n * - 0: The version of 'self' is equal to 'frontiers'.\n * - 1: The version of 'self' is greater than 'frontiers'.\n *\n * # Internal\n *\n * Frontiers cannot be compared without the history of the OpLog.\n * @param {({ peer: PeerID, counter: number })[]} frontiers\n * @returns {number}\n */\n cmpWithFrontiers(frontiers) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(frontiers, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_cmpWithFrontiers(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @param {{ peer: PeerID, counter: number, length: number }} idSpan\n * @returns {any}\n */\n exportJsonInIdSpan(idSpan) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_exportJsonInIdSpan(retptr, this.__wbg_ptr, addHeapObject(idSpan));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Subscribe to changes that may affect a JSONPath query.\n *\n * The callback receives no query result; it is a lightweight notifier and may\n * fire false positives so callers can debounce/throttle before running JSONPath\n * themselves.\n * @param {string} jsonpath\n * @param {Function} f\n * @returns {any}\n */\n subscribeJsonpath(jsonpath, f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(jsonpath, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_subscribeJsonpath(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Delete all content from a root container and hide it from the document.\n *\n * When a root container is empty and hidden:\n * - It won't show up in `get_deep_value()` results\n * - It won't be included in document snapshots\n *\n * Only works on root containers (containers without parents).\n * @param {ContainerID} cid\n */\n deleteRootContainer(cid) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_deleteRootContainer(retptr, this.__wbg_ptr, addHeapObject(cid));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Export updates in the given range in JSON format.\n * @param {any} start_vv\n * @param {any} end_vv\n * @param {boolean | null} [with_peer_compression]\n * @returns {JsonSchema}\n */\n exportJsonUpdates(start_vv, end_vv, with_peer_compression) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_exportJsonUpdates(retptr, this.__wbg_ptr, addHeapObject(start_vv), addHeapObject(end_vv), isLikeNone(with_peer_compression) ? 0xFFFFFF : with_peer_compression ? 1 : 0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the container corresponding to the container id.\n *\n * If the container does not exist, it returns `undefined`.\n *\n * A mergeable container (created via `ensureMergeableMap` and friends) is resolvable\n * right after it has been ensured — even before any op is written into it — for as\n * long as the parent map's child ref is alive. A mergeable container id that was\n * never ensured on this doc resolves to `undefined`.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * let text = doc.getText(\"text\");\n * const textId = text.id;\n * text = doc.getContainerById(textId);\n * ```\n * @param {ContainerID} container_id\n * @returns {any}\n */\n getContainerById(container_id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getContainerById(retptr, this.__wbg_ptr, addHeapObject(container_id));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the number of operations in the pending transaction.\n *\n * The pending transaction is the one that is not committed yet. It will be committed\n * automatically after calling `doc.commit()`, `doc.export(mode)` or `doc.checkout(version)`.\n * @returns {number}\n */\n getPendingTxnLength() {\n const ret = wasm.lorodoc_getPendingTxnLength(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * Import updates from the JSON format.\n *\n * only supports backward compatibility but not forward compatibility.\n * @param {string | JsonSchema} json\n * @returns {ImportStatus}\n */\n importJsonUpdates(json) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_importJsonUpdates(retptr, this.__wbg_ptr, addHeapObject(json));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Import a batch of updates and snapshots.\n *\n * It's more efficient than importing updates one by one.\n *\n * @deprecated Use `importBatch` instead.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * const updates = doc.export({ mode: \"update\" });\n * const snapshot = doc.export({ mode: \"snapshot\" });\n * const doc2 = new LoroDoc();\n * doc2.importBatch([snapshot, updates]);\n * ```\n * @param {Uint8Array[]} data\n * @returns {ImportStatus}\n */\n importUpdateBatch(data) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_importBatch(retptr, this.__wbg_ptr, addHeapObject(data));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Enables editing in detached mode, which is disabled by default.\n *\n * The doc enter detached mode after calling `detach` or checking out a non-latest version.\n *\n * # Important Notes:\n *\n * - This mode uses a different PeerID for each checkout.\n * - Ensure no concurrent operations share the same PeerID if set manually.\n * - Importing does not affect the document's state or version; changes are\n * recorded in the [OpLog] only. Call `checkout` to apply changes.\n * @param {boolean} enable\n */\n setDetachedEditing(enable) {\n wasm.lorodoc_setDetachedEditing(this.__wbg_ptr, enable);\n }\n /**\n * Set whether to record the timestamp of each change. Default is `false`.\n *\n * If enabled, the Unix timestamp (in seconds) will be recorded for each change automatically.\n *\n * You can also set each timestamp manually when you commit a change.\n * The timestamp manually set will override the automatic one.\n *\n * NOTE: Timestamps are forced to be in ascending order in the OpLog's history.\n * If you commit a new change with a timestamp that is less than the existing one,\n * the largest existing timestamp will be used instead.\n * @param {boolean} auto_record\n */\n setRecordTimestamp(auto_record) {\n wasm.lorodoc_setRecordTimestamp(this.__wbg_ptr, auto_record);\n }\n /**\n * Subscribe to the pre-commit event.\n *\n * The callback will be called when the changes are committed but not yet applied to the OpLog.\n * You can modify the commit message and timestamp in the callback by `ChangeModifier`.\n * @param {Function} f\n * @returns {any}\n */\n subscribePreCommit(f) {\n const ret = wasm.lorodoc_subscribePreCommit(this.__wbg_ptr, addHeapObject(f));\n return takeObject(ret);\n }\n /**\n * Find the op id spans that between the `from` version and the `to` version.\n *\n * You can combine it with `exportJsonInIdSpan` to get the changes between two versions.\n *\n * You can use it to travel all the changes from `from` to `to`. `from` and `to` are frontiers,\n * and they can be concurrent to each other. You can use it to find all the changes related to an event:\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const docA = new LoroDoc();\n * docA.setPeerId(\"1\");\n * const docB = new LoroDoc();\n *\n * docA.getText(\"text\").update(\"Hello\");\n * docA.commit();\n * const snapshot = docA.export({ mode: \"snapshot\" });\n * let done = false;\n * docB.subscribe(e => {\n * const spans = docB.findIdSpansBetween(e.from, e.to);\n * const changes = docB.exportJsonInIdSpan(spans.forward[0]);\n * console.log(changes);\n * // [{\n * // id: \"0@1\",\n * // timestamp: expect.any(Number),\n * // deps: [],\n * // lamport: 0,\n * // msg: undefined,\n * // ops: [{\n * // container: \"cid:root-text:Text\",\n * // counter: 0,\n * // content: {\n * // type: \"insert\",\n * // pos: 0,\n * // text: \"Hello\"\n * // }\n * // }]\n * // }]\n * });\n * docB.import(snapshot);\n * ```\n * @param {({ peer: PeerID, counter: number })[]} from\n * @param {({ peer: PeerID, counter: number })[]} to\n * @returns {VersionVectorDiff}\n */\n findIdSpansBetween(from, to) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(from, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArrayJsValueToWasm0(to, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n wasm.lorodoc_findIdSpansBetween(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the change of with specific peer_id and lamport <= given lamport\n * @param {string} peer_id\n * @param {number} lamport\n * @returns {Change | undefined}\n */\n getChangeAtLamport(peer_id, lamport) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(peer_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_getChangeAtLamport(retptr, this.__wbg_ptr, ptr0, len0, lamport);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the path from the root to the container\n * @param {ContainerID} id\n * @returns {(string|number)[] | undefined}\n */\n getPathToContainer(id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getPathToContainer(retptr, this.__wbg_ptr, addHeapObject(id));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Export remote updates received through import APIs that are still waiting\n * for missing causal dependencies. These differ from uncommitted local operations.\n *\n * Returns `undefined` when no remote updates are pending. Ordinary snapshot\n * and update exports exclude these pending updates, so persist this result\n * as a separate sidecar to a normal snapshot. Export errors are thrown;\n * they are not returned as `undefined`.\n *\n * Restore the snapshot first, then pass the sidecar bytes to ordinary\n * `import()`. The restored updates remain pending until later imports supply\n * their real missing dependencies. This method only exports operations already\n * received; it cannot supply missing predecessors.\n *\n * This method is read-only: it does not consume pending updates, advance the\n * applied version vector/frontiers, emit document events, or commit a local\n * transaction. Uncommitted local operations are excluded. Ordinary snapshot\n * export still commits local operations as usual.\n *\n * Coordinate document mutations while collecting the snapshot and sidecar,\n * and persist them as one consistent checkpoint. The two export calls do not\n * form an atomic capture. Replace the saved checkpoint only after both exports\n * succeed. As part of that successful replacement, `undefined` means remove\n * any old pending sidecar. If either export throws, keep the previous checkpoint.\n *\n * This method does not define or advance a sync cursor or establish that the\n * document is synced. `undefined` only means no received remote updates are\n * currently pending.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const source = new LoroDoc();\n * source.setPeerId(\"1\");\n * source.getText(\"text\").insert(0, \"base|\");\n * const baseSnapshot = source.export({ mode: \"snapshot\" });\n * const beforeA = source.oplogVersion();\n * source.getText(\"text\").insert(5, \"A\");\n * const a = source.export({ mode: \"update\", from: beforeA });\n * const beforeB = source.oplogVersion();\n * source.getText(\"text\").insert(6, \"B\");\n * const b = source.export({ mode: \"update\", from: beforeB });\n *\n * const doc = new LoroDoc();\n * doc.import(baseSnapshot);\n * doc.import(b); // A is missing, so B stays pending.\n * // Coordinate checkpoint collection and storage with document mutations.\n * let savedCheckpoint = {\n * snapshot: doc.export({ mode: \"snapshot\" }),\n * pending: doc.exportPendingUpdates(),\n * };\n *\n * const restored = new LoroDoc();\n * restored.import(savedCheckpoint.snapshot);\n * if (savedCheckpoint.pending !== undefined) restored.import(savedCheckpoint.pending);\n * console.assert(restored.getText(\"text\").toString() === \"base|\");\n * restored.import(a);\n * console.assert(restored.getText(\"text\").toString() === \"base|AB\");\n *\n * savedCheckpoint = {\n * snapshot: restored.export({ mode: \"snapshot\" }),\n * pending: restored.exportPendingUpdates(),\n * };\n * console.assert(savedCheckpoint.pending === undefined);\n * // After both exports succeed, replace the checkpoint and remove its old pending sidecar.\n * ```\n * @returns {Uint8Array | undefined}\n */\n exportPendingUpdates() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_exportPendingUpdates(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n let v1;\n if (r0 !== 0) {\n v1 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n }\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Gets container IDs modified in the given ID range.\n *\n * **NOTE:** This method will implicitly commit.\n *\n * This method identifies which containers were affected by changes in a given range of operations.\n * It can be used together with `doc.travelChangeAncestors()` to analyze the history of changes\n * and determine which containers were modified by each change.\n *\n * @param id - The starting ID of the change range\n * @param len - The length of the change range to check\n * @returns An array of container IDs that were modified in the given range\n * @param {{ peer: PeerID, counter: number }} id\n * @param {number} len\n * @returns {ContainerID[]}\n */\n getChangedContainersIn(id, len) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getChangedContainersIn(retptr, this.__wbg_ptr, addHeapObject(id), len);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get deep value of the document with container id\n * @returns {any}\n */\n getDeepValueWithID() {\n const ret = wasm.lorodoc_getDeepValueWithID(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Set the origin of the next commit\n * @param {string} origin\n */\n setNextCommitOrigin(origin) {\n const ptr0 = passStringToWasm0(origin, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_setNextCommitOrigin(this.__wbg_ptr, ptr0, len0);\n }\n /**\n * Get the pending operations from the current transaction in JSON format\n *\n * This method returns a JSON representation of operations that have been applied\n * but not yet committed in the current transaction.\n *\n * It will use the same data format as `doc.exportJsonUpdates()`\n *\n * @example\n * ```ts\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * // Get pending ops before commit\n * const pendingOps = doc.getPendingOpsFromCurrentTxnAsJson();\n * doc.commit();\n * const emptyOps = doc.getPendingOpsFromCurrentTxnAsJson(); // this is undefined\n * ```\n * @returns {JsonSchema | undefined}\n */\n getUncommittedOpsAsJson() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getUncommittedOpsAsJson(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Set the commit message of the next commit\n * @param {string} msg\n */\n setNextCommitMessage(msg) {\n const ptr0 = passStringToWasm0(msg, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_setNextCommitMessage(this.__wbg_ptr, ptr0, len0);\n }\n /**\n * Set the options of the next commit\n * @param {{ origin?: string, timestamp?: number, message?: string }} options\n */\n setNextCommitOptions(options) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_setNextCommitOptions(retptr, this.__wbg_ptr, addHeapObject(options));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * The doc only contains the history since this version\n *\n * This is empty if the doc is not shallow.\n *\n * The ops included by the shallow history start frontiers are not in the doc.\n * @returns {{ peer: PeerID, counter: number }[]}\n */\n shallowSinceFrontiers() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_shallowSinceFrontiers(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Subscribe the updates from local edits\n * @param {Function} f\n * @returns {any}\n */\n subscribeLocalUpdates(f) {\n const ret = wasm.lorodoc_subscribeLocalUpdates(this.__wbg_ptr, addHeapObject(f));\n return takeObject(ret);\n }\n /**\n * Visit all the ancestors of the changes in causal order.\n *\n * @param ids - the changes to visit\n * @param f - the callback function, return `true` to continue visiting, return `false` to stop\n * @param {({ peer: PeerID, counter: number })[]} ids\n * @param {(change: Change) => boolean} f\n */\n travelChangeAncestors(ids, f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(ids, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_travelChangeAncestors(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Clear the options of the next commit\n */\n clearNextCommitOptions() {\n wasm.lorodoc_clearNextCommitOptions(this.__wbg_ptr);\n }\n /**\n * Configures the default text style for the document.\n *\n * This method sets the default text style configuration for the document when using LoroText.\n * If `None` is provided, the default style is reset.\n * @param {{ expand: 'before'|'after'|'none'|'both' } | undefined} style\n */\n configDefaultTextStyle(style) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_configDefaultTextStyle(retptr, this.__wbg_ptr, addHeapObject(style));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Maximum number of lazily loaded container values retained by handler reads.\n * The default is 2048.\n * @returns {number}\n */\n getDecodedValueCacheLimit() {\n const ret = wasm.lorodoc_getDecodedValueCacheLimit(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * If two continuous local changes are within (<=) the interval(**in seconds**), they will be merged into one change.\n *\n * The default value is 1_000 seconds.\n *\n * By default, we record timestamps in seconds for each change. So if the merge interval is 1, and changes A and B\n * have timestamps of 3 and 4 respectively, then they will be merged into one change\n * @param {number} interval\n */\n setChangeMergeInterval(interval) {\n wasm.lorodoc_setChangeMergeInterval(this.__wbg_ptr, interval);\n }\n /**\n * Set the timestamp of the next commit\n * @param {number} timestamp\n */\n setNextCommitTimestamp(timestamp) {\n wasm.lorodoc_setNextCommitTimestamp(this.__wbg_ptr, timestamp);\n }\n /**\n * Set whether to hide empty root containers.\n *\n * @example\n * ```ts\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * console.log(doc.toJSON()); // { map: {} }\n * doc.setHideEmptyRootContainers(true);\n * console.log(doc.toJSON()); // {}\n * ```\n * @param {boolean} hide\n */\n setHideEmptyRootContainers(hide) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_setHideEmptyRootContainers(retptr, this.__wbg_ptr, hide);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Whether the editing is enabled in detached mode.\n *\n * The doc enter detached mode after calling `detach` or checking out a non-latest version.\n *\n * # Important Notes:\n *\n * - This mode uses a different PeerID for each checkout.\n * - Ensure no concurrent operations share the same PeerID if set manually.\n * - Importing does not affect the document's state or version; changes are\n * recorded in the [OpLog] only. Call `checkout` to apply changes.\n * @returns {boolean}\n */\n isDetachedEditingEnabled() {\n const ret = wasm.lorodoc_isDetachedEditingEnabled(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Set how many lazily loaded container values handler reads may cache.\n *\n * The default is 2048. A larger finite limit trades memory for faster repeated\n * reads of large imported snapshots. Zero disables this cache. Lowering the\n * limit immediately evicts excess cached values without losing local edits.\n *\n * This counts cached values, not bytes or all document state: modified\n * containers and materialized tree state are outside this bound. Bulk reads\n * such as `doc.toJSON()` do not populate this cache.\n *\n * The setting is local to this document, is copied independently by forks,\n * and is not encoded in snapshots or updates. `limit` must be a finite\n * integer between 0 and 4294967295 (inclusive); Infinity is not supported.\n * @param {number} limit\n */\n setDecodedValueCacheLimit(limit) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_setDecodedValueCacheLimit(retptr, this.__wbg_ptr, limit);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @param {Function} f\n * @returns {any}\n */\n subscribeFirstCommitFromPeer(f) {\n const ret = wasm.lorodoc_subscribeFirstCommitFromPeer(this.__wbg_ptr, addHeapObject(f));\n return takeObject(ret);\n }\n /**\n * Create a new loro document.\n *\n * New document will have a random peer id.\n */\n constructor() {\n const ret = wasm.lorodoc_new();\n this.__wbg_ptr = ret >>> 0;\n LoroDocFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * Calculate the differences between two frontiers\n *\n * The entries in the returned object are sorted by causal order: the creation of a child container will be\n * presented before its use.\n * @param {({ peer: PeerID, counter: number })[]} from\n * @param {({ peer: PeerID, counter: number })[]} to\n * @param {boolean | null} [for_json]\n * @returns {[ContainerID, Diff|JsonDiff][]}\n */\n diff(from, to, for_json) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(from, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArrayJsValueToWasm0(to, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n wasm.lorodoc_diff(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1, isLikeNone(for_json) ? 0xFFFFFF : for_json ? 1 : 0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Duplicate the document with a different PeerID\n *\n * The time complexity and space complexity of this operation are both O(n),\n *\n * When called in detached mode, it will fork at the current state frontiers.\n * It will have the same effect as `forkAt(&self.frontiers())`.\n * @returns {LoroDoc}\n */\n fork() {\n const ret = wasm.lorodoc_fork(this.__wbg_ptr);\n return LoroDoc.__wrap(ret);\n }\n /**\n * Attach the document state to the latest known version.\n *\n * > The document becomes detached during a `checkout` operation.\n * > Being `detached` implies that the `DocState` is not synchronized with the latest version of the `OpLog`.\n * > In a detached state, the document is not editable, and any `import` operations will be\n * > recorded in the `OpLog` without being applied to the `DocState`.\n *\n * This method has the same effect as invoking `checkoutToLatest`.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * const frontiers = doc.frontiers();\n * text.insert(0, \"Hello World!\");\n * doc.checkout(frontiers);\n * // you need call `attach()` or `checkoutToLatest()` before changing the doc.\n * doc.attach();\n * text.insert(0, \"Hi\");\n * ```\n */\n attach() {\n wasm.lorodoc_attach(this.__wbg_ptr);\n }\n /**\n * Commit the cumulative auto-committed transaction.\n *\n * You can specify the `origin`, `timestamp`, and `message` of the commit.\n *\n * - The `origin` is used to mark the event\n * - The `message` works like a git commit message, which will be recorded and synced to peers\n * - The `timestamp` is the number of seconds that have elapsed since 00:00:00 UTC on January 1, 1970.\n * It defaults to `Date.now() / 1000` when timestamp recording is enabled\n *\n * The events will be emitted after a transaction is committed. A transaction is committed when:\n *\n * - `doc.commit()` is called.\n * - `doc.export(mode)` is called.\n * - `doc.import(data)` is called.\n * - `doc.checkout(version)` is called.\n *\n * NOTE: Timestamps are forced to be in ascending order.\n * If you commit a new change with a timestamp that is less than the existing one,\n * the largest existing timestamp will be used instead.\n *\n * NOTE: The `origin` will not be persisted, but the `message` will.\n *\n * Behavior on empty commits:\n * - This method is an explicit commit. If the pending transaction is empty, any provided\n * options (message/timestamp/origin) are swallowed and will not carry over to the next commit.\n * - Implicit commits triggered by `export`/`checkout` act as processing barriers. If the\n * transaction is empty in those cases, `message`/`timestamp`/`origin` are preserved for the\n * next commit.\n * @param {{ origin?: string, timestamp?: number, message?: string } | null} [options]\n */\n commit(options) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_commit(retptr, this.__wbg_ptr, isLikeNone(options) ? 0 : addHeapObject(options));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Detach the document state from the latest known version.\n *\n * After detaching, all import operations will be recorded in the `OpLog` without being applied to the `DocState`.\n * When `detached`, the document is not editable.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * doc.detach();\n * console.log(doc.isDetached()); // true\n * ```\n */\n detach() {\n wasm.lorodoc_detach(this.__wbg_ptr);\n }\n /**\n * Export the document based on the specified ExportMode.\n *\n * @param mode - The export mode to use. Can be one of:\n * - `{ mode: \"snapshot\" }`: Export a full snapshot of the document.\n * - `{ mode: \"update\", from?: VersionVector }`: Export updates from the given version vector.\n * If `from` is not provided, it will export the whole history of the document.\n * - `{ mode: \"updates-in-range\", spans: { id: ID, len: number }[] }`: Export updates within the specified ID spans.\n * - `{ mode: \"shallow-snapshot\", frontiers: Frontiers }`: Export a garbage-collected snapshot up to the given frontiers.\n *\n * @returns A byte array containing the exported data.\n *\n * This export commits the current local transaction before producing bytes.\n *\n * Snapshot and update exports do not include remote updates that are still\n * waiting for missing causal dependencies. Use `exportPendingUpdates()` to\n * persist those updates separately.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * doc.setPeerId(\"1\");\n * doc.getText(\"text\").update(\"Hello World\");\n *\n * // Export a full snapshot\n * const snapshotBytes = doc.export({ mode: \"snapshot\" });\n *\n * // Export updates from a specific version\n * const vv = doc.oplogVersion();\n * doc.getText(\"text\").update(\"Hello Loro\");\n * const updateBytes = doc.export({ mode: \"update\", from: vv });\n *\n * // Export a shallow snapshot that only includes the history since the frontiers\n * const shallowBytes = doc.export({ mode: \"shallow-snapshot\", frontiers: doc.oplogFrontiers() });\n *\n * // Export updates within specific ID spans\n * const spanBytes = doc.export({\n * mode: \"updates-in-range\",\n * spans: [{ id: { peer: \"1\", counter: 0 }, len: 10 }]\n * });\n * ```\n * @param {ExportMode} mode\n * @returns {Uint8Array}\n */\n export(mode) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_export(retptr, this.__wbg_ptr, addHeapObject(mode));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Import snapshot or updates into current doc.\n *\n * Note:\n * - Updates within the current version will be ignored\n * - Updates with missing dependencies will be pending until the dependencies are received\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * // get all updates of the doc\n * const updates = doc.export({ mode: \"update\" });\n * const snapshot = doc.export({ mode: \"snapshot\" });\n * const doc2 = new LoroDoc();\n * // import snapshot\n * doc2.import(snapshot);\n * // or import updates\n * doc2.import(updates);\n * ```\n * @param {Uint8Array} update_or_snapshot\n * @returns {ImportStatus}\n */\n import(update_or_snapshot) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(update_or_snapshot, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_import(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Creates a new LoroDoc at a specified version (Frontiers)\n *\n * The created doc will only contain the history before the specified frontiers.\n * @param {({ peer: PeerID, counter: number })[]} frontiers\n * @returns {LoroDoc}\n */\n forkAt(frontiers) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(frontiers, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_forkAt(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroDoc.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get a LoroMap by container id\n *\n * The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n *\n * If the container does not exist, an error will be thrown.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * ```\n * @param {ContainerID | string} cid\n * @returns {LoroMap}\n */\n getMap(cid) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getMap(retptr, this.__wbg_ptr, addBorrowedObject(cid));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroMap.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get the number of ops in the oplog.\n * @returns {number}\n */\n opCount() {\n const ret = wasm.lorodoc_opCount(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * Peer ID of the current writer.\n * @returns {bigint}\n */\n get peerId() {\n const ret = wasm.lorodoc_peerId(this.__wbg_ptr);\n return BigInt.asUintN(64, ret);\n }\n /**\n * Get the json format of the entire document state.\n *\n * Unlike `getShallowValue()` which returns container IDs as strings,\n * `toJSON()` recursively resolves all containers to their actual values.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText, LoroMap } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, \"Hello\");\n * const text = list.insertContainer(0, new LoroText());\n * text.insert(0, \"Hello\");\n * const map = list.insertContainer(1, new LoroMap());\n * map.set(\"foo\", \"bar\");\n * console.log(doc.toJSON());\n * // {\"list\": [\"Hello\", {\"foo\": \"bar\"}]}\n * ```\n * @returns {any}\n */\n toJSON() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_toJSON(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the version vector of the current document state.\n *\n * If you checkout to a specific version, the version vector will change.\n * @returns {VersionVector}\n */\n version() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_version(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return VersionVector.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Checkout the `DocState` to a specific version.\n *\n * > The document becomes detached during a `checkout` operation.\n * > Being `detached` implies that the `DocState` is not synchronized with the latest version of the `OpLog`.\n * > In a detached state, the document is not editable, and any `import` operations will be\n * > recorded in the `OpLog` without being applied to the `DocState`.\n *\n * You should call `attach` to attach the `DocState` to the latest version of `OpLog`.\n *\n * @param frontiers - the specific frontiers\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * const frontiers = doc.frontiers();\n * text.insert(0, \"Hello World!\");\n * doc.checkout(frontiers);\n * console.log(doc.toJSON()); // {\"text\": \"\"}\n * ```\n * @param {({ peer: PeerID, counter: number })[]} frontiers\n */\n checkout(frontiers) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(frontiers, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_checkout(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get a LoroList by container id\n *\n * The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n *\n * If the container does not exist, an error will be thrown.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * ```\n * @param {ContainerID | string} cid\n * @returns {LoroList}\n */\n getList(cid) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getList(retptr, this.__wbg_ptr, addBorrowedObject(cid));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroList.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get a LoroText by container id.\n *\n * The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n *\n * If the container does not exist, an error will be thrown.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * ```\n * @param {ContainerID | string} cid\n * @returns {LoroText}\n */\n getText(cid) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getText(retptr, this.__wbg_ptr, addBorrowedObject(cid));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroText.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get a LoroTree by container id\n *\n * The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n *\n * If the container does not exist, an error will be thrown.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * ```\n * @param {ContainerID | string} cid\n * @returns {LoroTree}\n */\n getTree(cid) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_getTree(retptr, this.__wbg_ptr, addBorrowedObject(cid));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroTree.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get the [frontiers](https://loro.dev/docs/advanced/version_deep_dive) of the current document state.\n *\n * If you checkout to a specific version, this value will change.\n * @returns {{ peer: PeerID, counter: number }[]}\n */\n frontiers() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_frontiers(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Evaluate JSONPath against a LoroDoc\n * @param {string} jsonpath\n * @returns {Array}\n */\n JSONPath(jsonpath) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(jsonpath, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_JSONPath(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Revert the document to the given frontiers.\n *\n * The doc will not become detached when using this method. Instead, it will generate a series\n * of operations to revert the document to the given version.\n *\n * @example\n * ```ts\n * const doc = new LoroDoc();\n * doc.setPeerId(\"1\");\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * doc.commit();\n * doc.revertTo([{ peer: \"1\", counter: 1 }]);\n * expect(doc.getText(\"text\").toString()).toBe(\"He\");\n * ```\n * @param {({ peer: PeerID, counter: number })[]} frontiers\n */\n revertTo(frontiers) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm0(frontiers, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorodoc_revertTo(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Subscribe to the changes of the loro document. The function will be called when the\n * transaction is committed and after importing updates/snapshot from remote.\n *\n * Returns a subscription callback, which can be used to unsubscribe.\n *\n * The events will be emitted after a transaction is committed. A transaction is committed when:\n *\n * - `doc.commit()` is called.\n * - `doc.export(mode)` is called.\n * - `doc.import(data)` is called.\n * - `doc.checkout(version)` is called.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * const sub = doc.subscribe((event)=>{\n * console.log(event);\n * });\n * text.insert(0, \"Hello\");\n * // the events will be emitted when `commit()` is called.\n * doc.commit();\n * // unsubscribe\n * sub();\n * ```\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n const ret = wasm.lorodoc_subscribe(this.__wbg_ptr, addHeapObject(f));\n return takeObject(ret);\n }\n /**\n * Convert visible roots to independent container trees without committing.\n * The text format applies recursively, including Tree metadata. Unknown or\n * hidden roots are omitted; roots: [] returns an empty object. Reads never\n * create roots. Binary values are owned Uint8Arrays. Not a CRDT export.\n * @param {DocumentContainerTreeOptions | null} [opts]\n * @returns {Record}\n */\n toContainerTree(opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_toContainerTree(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Read visible roots as one JSON string, using the same node shapes and text\n * formats as toContainerTree. No per-value JS calls or implicit commit.\n * Throws for binary or non-finite numbers rather than losing their values.\n * @param {DocumentContainerTreeOptions | null} [opts]\n * @returns {string}\n */\n toContainerTreeJson(opts) {\n let deferred2_0;\n let deferred2_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorodoc_toContainerTreeJson(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n var ptr1 = r0;\n var len1 = r1;\n if (r3) {\n ptr1 = 0; len1 = 0;\n throw takeObject(r2);\n }\n deferred2_0 = ptr1;\n deferred2_1 = len1;\n return getStringFromWasm0(ptr1, len1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);\n }\n }\n}\n\nconst LoroListFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_lorolist_free(ptr >>> 0, 1));\n/**\n * The handler of a list container.\n *\n * Learn more at https://loro.dev/docs/tutorial/list\n */\nexport class LoroList {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroList.prototype);\n obj.__wbg_ptr = ptr;\n LoroListFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroListFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_lorolist_free(ptr, 0);\n }\n /**\n * Whether the container is attached to a document.\n *\n * If it's detached, the operations on the container will not be persisted.\n * @returns {boolean}\n */\n isAttached() {\n const ret = wasm.lorolist_isAttached(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the attached container associated with this.\n *\n * Returns an attached `Container` that equals to this or created by this, otherwise `undefined`.\n * @returns {LoroList | undefined}\n */\n getAttached() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_getAttached(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @param {Container} child\n * @returns {Container}\n */\n pushContainer(child) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_pushContainer(retptr, this.__wbg_ptr, addHeapObject(child));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the deep value of the elements in the range `[start, end)`.\n *\n * Each child container in the range is recursively resolved to its deep\n * value. Negative bounds are clamped to 0 and out-of-range bounds are\n * clamped to the list length; an empty or inverted range returns `[]`.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.getRangeValue(0, 2)); // [100, \"Hello\"]\n * ```\n * @param {number} start\n * @param {number} end\n * @returns {any}\n */\n getRangeValue(start, end) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_getRangeValue(retptr, this.__wbg_ptr, start, end);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Insert a container at the index.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.toJSON()); // [100, \"Hello\"];\n * ```\n * @param {number} index\n * @param {Container} child\n * @returns {Container}\n */\n insertContainer(index, child) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_insertContainer(retptr, this.__wbg_ptr, index, addHeapObject(child));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the shallow value of the list.\n *\n * Unlike `toJSON()` which recursively resolves all containers to their values,\n * `getShallowValue()` returns container IDs as strings for any nested containers.\n *\n * ```js\n * const doc = new LoroDoc();\n * doc.setPeerId(\"1\");\n * const list = doc.getList(\"list\");\n * list.insert(0, 1);\n * list.insert(1, \"two\");\n * const subList = list.insertContainer(2, new LoroList());\n * subList.insert(0, \"sub\");\n * list.getShallowValue(); // [1, \"two\", \"cid:2@1:List\"]\n * list.toJSON(); // [1, \"two\", [\"sub\"]]\n * ```\n * @returns {Value[]}\n */\n getShallowValue() {\n const ret = wasm.lorolist_getShallowValue(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the deep value of the list with its container id.\n *\n * The result is a `{ cid, value }` object, where `cid` is the container id\n * string (the same as `list.id`) and `value` is the deep value of the\n * list. Child containers inside `value` are recursively replaced by their\n * own `{ cid, value }` nodes. This is the same node shape that\n * `LoroDoc.getDeepValueWithID()` emits for every container.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.getDeepValueWithID());\n * // { cid: \"cid:root-list:List\",\n * // value: [100, { cid: \"cid:0@1:Text\", value: \"Hello\" }] }\n * ```\n * @returns {any}\n */\n getDeepValueWithID() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_getDeepValueWithID(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the deep value of the elements in the range `[start, end)`, with\n * container ids.\n *\n * Each child container in the range is recursively replaced by its own\n * `{ cid, value }` node. Negative bounds are clamped to 0 and\n * out-of-range bounds are clamped to the list length; an empty or\n * inverted range returns `[]`.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.getRangeDeepValueWithID(0, 2));\n * // [100, { cid: \"cid:0@1:Text\", value: \"Hello\" }]\n * ```\n * @param {number} start\n * @param {number} end\n * @returns {any}\n */\n getRangeDeepValueWithID(start, end) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_getRangeDeepValueWithID(retptr, this.__wbg_ptr, start, end);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the id of this container.\n * @returns {ContainerID}\n */\n get id() {\n const ret = wasm.lorolist_id(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the value at the index. If the value is a container, the corresponding handler will be returned.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * console.log(list.get(0)); // 100\n * console.log(list.get(1)); // undefined\n * ```\n * @param {number} index\n * @returns {Value | Container | undefined}\n */\n get(index) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_get(retptr, this.__wbg_ptr, index);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Create a new detached LoroList (not attached to any LoroDoc).\n *\n * The edits on a detached container will not be persisted.\n * To attach the container to the document, please insert it into an attached container.\n */\n constructor() {\n const ret = wasm.lorolist_new();\n this.__wbg_ptr = ret >>> 0;\n LoroListFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * Pop a value from the end of the list.\n * @returns {Value | undefined}\n */\n pop() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_pop(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * \"List\"\n * @returns {'List'}\n */\n kind() {\n const ret = wasm.lorolist_kind(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Push a value to the end of the list.\n * @param {Value} value\n */\n push(value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_push(retptr, this.__wbg_ptr, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Delete all elements in the list.\n */\n clear() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_clear(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Delete elements from index to index + len.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.delete(0, 1);\n * console.log(list.value); // []\n * ```\n * @param {number} index\n * @param {number} len\n */\n delete(index, len) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_delete(retptr, this.__wbg_ptr, index, len);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Insert a value at index.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.insert(1, \"foo\");\n * list.insert(2, true);\n * console.log(list.value); // [100, \"foo\", true];\n * ```\n * @param {number} index\n * @param {Value} value\n */\n insert(index, value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_insert(retptr, this.__wbg_ptr, index, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the length of list.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.insert(1, \"foo\");\n * list.insert(2, true);\n * console.log(list.length); // 3\n * ```\n * @returns {number}\n */\n get length() {\n const ret = wasm.lorolist_length(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * Get the parent container.\n *\n * - The parent container of the root tree is `undefined`.\n * - The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n * @returns {Container | undefined}\n */\n parent() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_parent(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @param {number} pos\n * @returns {{ peer: PeerID, counter: number } | undefined}\n */\n getIdAt(pos) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_getIdAt(retptr, this.__wbg_ptr, pos);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get elements of the list. If the type of a element is a container, it will be\n * resolved recursively.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.toJSON()); // [100, \"Hello\"];\n * ```\n * @returns {any}\n */\n toJSON() {\n const ret = wasm.lorolist_toJSON(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get elements of the list. If the value is a child container, the corresponding\n * `Container` will be returned.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.insert(1, \"foo\");\n * list.insert(2, true);\n * list.insertContainer(3, new LoroText());\n * console.log(list.value); // [100, \"foo\", true, LoroText];\n * ```\n * @returns {(Value | Container)[]}\n */\n toArray() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_toArray(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the cursor at the position.\n *\n * - The first argument is the position .\n * - The second argument is the side: `-1` for left, `0` for middle, `1` for right.\n * @param {number} pos\n * @param {Side} side\n * @returns {Cursor | undefined}\n */\n getCursor(pos, side) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_getCursor(retptr, this.__wbg_ptr, pos, addHeapObject(side));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 === 0 ? undefined : Cursor.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Check if the container is deleted\n * @returns {boolean}\n */\n isDeleted() {\n const ret = wasm.lorolist_isDeleted(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Subscribe to the changes of the list.\n *\n * Returns a subscription callback, which can be used to unsubscribe.\n *\n * The events will be emitted after a transaction is committed. A transaction is committed when:\n *\n * - `doc.commit()` is called.\n * - `doc.export(mode)` is called.\n * - `doc.import(data)` is called.\n * - `doc.checkout(version)` is called.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.subscribe((event)=>{\n * console.log(event);\n * });\n * list.insert(0, 100);\n * doc.commit();\n * ```\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_subscribe(retptr, this.__wbg_ptr, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert this attached container and all descendants to an independent tree.\n * Text format applies recursively. Does not commit; throws for detached\n * containers, unsupported types, invalid options, or nesting above 256.\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerNode}\n */\n toContainerTree(opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_toContainerTree(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Read [start,end), clamped to list length. Inverted bounds return no items.\n * Returns actual start, totalLength and items; this is not a complete container.\n * Only selected descendants are traversed; parent shallow list access is O(N).\n * @param {number} start\n * @param {number} end\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerTreeSlice}\n */\n toContainerTreeSlice(start, end, opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorolist_toContainerTreeSlice(retptr, this.__wbg_ptr, start, end, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst LoroMapFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_loromap_free(ptr >>> 0, 1));\n/**\n * The handler of a map container.\n *\n * Learn more at https://loro.dev/docs/tutorial/map\n *\n * ## Mergeable child containers\n *\n * `ensureMergeable*` methods create deterministic child containers under a map\n * key. If two peers independently call the same method with the same parent\n * map, key, and container type, they get the same child container id and their\n * subsequent edits merge in that child.\n *\n * Loro activates a mergeable child by writing a specially constructed binary\n * marker value into the parent map slot. String values do not activate\n * mergeable children. If the key already holds a non-mergeable value,\n * `ensureMergeable*` returns an error and leaves the value unchanged.\n * Calling `ensureMergeable*` with a different container type at an existing\n * mergeable key is a deliberate kind change: the map slot activates the new\n * type, while the state of the other mergeable child remains preserved under\n * its deterministic id.\n *\n * Deleting the map key clears the ref and hides the mergeable child, but the\n * child's state is preserved. Calling the same `ensureMergeable*` method again\n * writes the ref back and resurfaces the preserved state.\n */\nexport class LoroMap {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroMap.prototype);\n obj.__wbg_ptr = ptr;\n LoroMapFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroMapFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_loromap_free(ptr, 0);\n }\n /**\n * Whether the container is attached to a document.\n *\n * If it's detached, the operations on the container will not be persisted.\n * @returns {boolean}\n */\n isAttached() {\n const ret = wasm.loromap_isAttached(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the attached container associated with this.\n *\n * Returns an attached `Container` that equals to this or created by this, otherwise `undefined`.\n * @returns {LoroMap | undefined}\n */\n getAttached() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_getAttached(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the peer id of the last editor on the given entry\n * @param {string} key\n * @returns {PeerID | undefined}\n */\n getLastEditor(key) {\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.loromap_getLastEditor(this.__wbg_ptr, ptr0, len0);\n return takeObject(ret);\n }\n /**\n * Set the key with a regular child container.\n *\n * The inserted child receives a regular op-created container id. Use this\n * for replacement semantics or when each creation should produce a distinct\n * child. Use `ensureMergeable*` when peers may lazily initialize the same\n * logical child under a map key.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText, LoroList } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * const text = map.setContainer(\"text\", new LoroText());\n * const list = map.setContainer(\"list\", new LoroList());\n * ```\n * @param {string} key\n * @param {Container} child\n * @returns {Container}\n */\n setContainer(key, child) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_setContainer(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(child));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the shallow value of the map.\n *\n * Unlike `toJSON()` which recursively resolves all containers to their values,\n * `getShallowValue()` returns container IDs as strings for any nested containers.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * doc.setPeerId(\"1\");\n * const map = doc.getMap(\"map\");\n * map.set(\"key\", \"value\");\n * const subText = map.setContainer(\"text\", new LoroText());\n * subText.insert(0, \"Hello\");\n *\n * // Get shallow value - nested containers are represented by their IDs\n * console.log(map.getShallowValue());\n * // Output: { key: \"value\", text: \"cid:1@1:Text\" }\n *\n * // Get full value with nested containers resolved by `toJSON()`\n * console.log(map.toJSON());\n * // Output: { key: \"value\", text: \"Hello\" }\n * ```\n * @returns {Record}\n */\n getShallowValue() {\n const ret = wasm.loromap_getShallowValue(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Ensure a mergeable Map exists under the given key and return it.\n *\n * If the map is detached, or if the key already holds a non-mergeable\n * value, this throws and leaves the value unchanged.\n *\n * Prefer to avoid very deep mergeable-map chains: mergeable cids encode\n * their flattened logical path, so cid size still grows with depth and\n * rides through every op/snapshot reference to it.\n * @param {string} key\n * @returns {LoroMap}\n */\n ensureMergeableMap(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_ensureMergeableMap(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroMap.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Ensure a mergeable List exists under the given key and return it.\n *\n * If the map is detached, or if the key already holds a non-mergeable\n * value, this throws and leaves the value unchanged.\n * @param {string} key\n * @returns {LoroList}\n */\n ensureMergeableList(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_ensureMergeableList(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroList.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Ensure a mergeable Text exists under the given key and return it.\n *\n * If the map is detached, or if the key already holds a non-mergeable\n * value, this throws and leaves the value unchanged.\n * @param {string} key\n * @returns {LoroText}\n */\n ensureMergeableText(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_ensureMergeableText(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroText.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Ensure a mergeable Tree exists under the given key and return it.\n *\n * If the map is detached, or if the key already holds a non-mergeable\n * value, this throws and leaves the value unchanged.\n * @param {string} key\n * @returns {LoroTree}\n */\n ensureMergeableTree(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_ensureMergeableTree(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroTree.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the deep value of the map with its container id.\n *\n * The result is a `{ cid, value }` object, where `cid` is the container id\n * string (the same as `map.id`) and `value` is the deep value of the map.\n * Child containers inside `value` are recursively replaced by their own\n * `{ cid, value }` nodes. This is the same node shape that\n * `LoroDoc.getDeepValueWithID()` emits for every container.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * const text = map.setContainer(\"text\", new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(map.getDeepValueWithID());\n * // { cid: \"cid:root-map:Map\",\n * // value: { foo: \"bar\", text: { cid: \"cid:0@1:Text\", value: \"Hello\" } } }\n * ```\n * @returns {any}\n */\n getDeepValueWithID() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_getDeepValueWithID(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get or create a regular child container at the given key.\n *\n * @deprecated Use `ensureMergeable*` for lazy map-key child creation. This\n * method creates regular op-id children, so concurrent first creation at\n * the same key can fork child state and leave one branch hidden by map\n * conflict resolution. Use `setContainer` for regular replacement/attach\n * semantics.\n *\n * If the key is empty or `null`, this creates a regular child container.\n * If the key already holds a child of the same type, it returns that child.\n * If the key holds a scalar or a child of another type, it throws.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * const text = map.getOrCreateContainer(\"text\", new LoroText());\n * text.insert(0, \"legacy regular child\");\n * ```\n * @param {string} key\n * @param {Container} child\n * @returns {Container}\n */\n getOrCreateContainer(key, child) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_getOrCreateContainer(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(child));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Ensure a mergeable Counter exists under the given key and return it.\n *\n * If the map is detached, or if the key already holds a non-mergeable\n * value, this throws and leaves the value unchanged.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const counter = doc.getMap(\"state\").ensureMergeableCounter(\"revision\");\n * counter.increment(1);\n * ```\n * @param {string} key\n * @returns {LoroCounter}\n */\n ensureMergeableCounter(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_ensureMergeableCounter(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroCounter.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Ensure a mergeable MovableList exists under the given key and return it.\n *\n * If the map is detached, or if the key already holds a non-mergeable\n * value, this throws and leaves the value unchanged.\n * @param {string} key\n * @returns {LoroMovableList}\n */\n ensureMergeableMovableList(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_ensureMergeableMovableList(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroMovableList.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * The container id of this handler.\n * @returns {ContainerID}\n */\n get id() {\n const ret = wasm.loromap_id(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the value of the key. If the value is a child container, the corresponding\n * `Container` will be returned.\n *\n * The object/value returned is a new js object/value each time because it need to cross\n * the WASM boundary.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * const bar = map.get(\"foo\");\n * ```\n * @param {string} key\n * @returns {Value | Container | undefined}\n */\n get(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_get(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Create a new detached LoroMap (not attached to any LoroDoc).\n *\n * The edits on a detached container will not be persisted.\n * To attach the container to the document, please insert it into an attached container.\n */\n constructor() {\n const ret = wasm.loromap_new();\n this.__wbg_ptr = ret >>> 0;\n LoroMapFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * Get the keys of the map.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * map.set(\"baz\", \"bar\");\n * const keys = map.keys(); // [\"foo\", \"baz\"]\n * ```\n * @returns {any[]}\n */\n keys() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_keys(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * \"Map\"\n * @returns {'Map'}\n */\n kind() {\n const ret = wasm.loromap_kind(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the size of the map.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * console.log(map.size); // 1\n * ```\n * @returns {number}\n */\n get size() {\n const ret = wasm.loromap_size(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * Delete all key-value pairs in the map.\n */\n clear() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_clear(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Remove the key from the map.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * map.delete(\"foo\");\n * ```\n * @param {string} key\n */\n delete(key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_delete(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Set the key with the value.\n *\n * If the value of the key is exist, the old value will be updated.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * map.set(\"foo\", \"baz\");\n * ```\n * @param {string} key\n * @param {Value} value\n */\n set(key, value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.loromap_set(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the parent container.\n *\n * - The parent container of the root tree is `undefined`.\n * - The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n * @returns {Container | undefined}\n */\n parent() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_parent(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the values of the map. If the value is a child container, the corresponding\n * `Container` will be returned.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * map.set(\"baz\", \"bar\");\n * const values = map.values(); // [\"bar\", \"bar\"]\n * ```\n * @returns {any[]}\n */\n values() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_values(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the entries of the map. If the value is a child container, the corresponding\n * `Container` will be returned.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * map.set(\"baz\", \"bar\");\n * const entries = map.entries(); // [[\"foo\", \"bar\"], [\"baz\", \"bar\"]]\n * ```\n * @returns {([string, Value | Container])[]}\n */\n entries() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_entries(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the keys and the values. If the type of value is a child container,\n * it will be resolved recursively.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.set(\"foo\", \"bar\");\n * const text = map.setContainer(\"text\", new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(map.toJSON()); // {\"foo\": \"bar\", \"text\": \"Hello\"}\n * ```\n * @returns {any}\n */\n toJSON() {\n const ret = wasm.loromap_toJSON(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Check if the container is deleted\n * @returns {boolean}\n */\n isDeleted() {\n const ret = wasm.loromap_isDeleted(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Subscribe to the changes of the map.\n *\n * Returns a subscription callback, which can be used to unsubscribe.\n *\n * The events will be emitted after a transaction is committed. A transaction is committed when:\n *\n * - `doc.commit()` is called.\n * - `doc.export(mode)` is called.\n * - `doc.import(data)` is called.\n * - `doc.checkout(version)` is called.\n *\n * @param {Listener} f - Event listener\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * map.subscribe((event)=>{\n * console.log(event);\n * });\n * map.set(\"foo\", \"bar\");\n * doc.commit();\n * ```\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_subscribe(retptr, this.__wbg_ptr, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert this attached container and all descendants to an independent tree.\n * Text format applies recursively. Does not commit; throws for detached\n * containers, unsupported types, invalid options, or nesting above 256.\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerNode}\n */\n toContainerTree(opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromap_toContainerTree(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst LoroMovableListFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_loromovablelist_free(ptr >>> 0, 1));\n/**\n * The handler of a list container.\n *\n * Learn more at https://loro.dev/docs/tutorial/list\n */\nexport class LoroMovableList {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroMovableList.prototype);\n obj.__wbg_ptr = ptr;\n LoroMovableListFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroMovableListFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_loromovablelist_free(ptr, 0);\n }\n /**\n * Whether the container is attached to a document.\n *\n * If it's detached, the operations on the container will not be persisted.\n * @returns {boolean}\n */\n isAttached() {\n const ret = wasm.loromovablelist_isAttached(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the creator of the list item at the given position.\n * @param {number} pos\n * @returns {PeerID | undefined}\n */\n getCreatorAt(pos) {\n const ret = wasm.loromovablelist_getCreatorAt(this.__wbg_ptr, pos);\n return takeObject(ret);\n }\n /**\n * Get the attached container associated with this.\n *\n * Returns an attached `Container` that equals to this or created by this, otherwise `undefined`.\n * @returns {LoroList | undefined}\n */\n getAttached() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_getAttached(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Set the container at the given position.\n * @param {number} pos\n * @param {Container} child\n * @returns {Container}\n */\n setContainer(pos, child) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_setContainer(retptr, this.__wbg_ptr, pos, addHeapObject(child));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the last mover of the list item at the given position.\n * @param {number} pos\n * @returns {PeerID | undefined}\n */\n getLastMoverAt(pos) {\n const ret = wasm.loromovablelist_getLastMoverAt(this.__wbg_ptr, pos);\n return takeObject(ret);\n }\n /**\n * Push a container to the end of the list.\n * @param {Container} child\n * @returns {Container}\n */\n pushContainer(child) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_pushContainer(retptr, this.__wbg_ptr, addHeapObject(child));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the last editor of the list item at the given position.\n * @param {number} pos\n * @returns {PeerID | undefined}\n */\n getLastEditorAt(pos) {\n const ret = wasm.loromovablelist_getLastEditorAt(this.__wbg_ptr, pos);\n return takeObject(ret);\n }\n /**\n * Get the deep value of the elements in the range `[start, end)`.\n *\n * Each child container in the range is recursively resolved to its deep\n * value. Negative bounds are clamped to 0 and out-of-range bounds are\n * clamped to the list length; an empty or inverted range returns `[]`.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getMovableList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.getRangeValue(0, 2)); // [100, \"Hello\"]\n * ```\n * @param {number} start\n * @param {number} end\n * @returns {any}\n */\n getRangeValue(start, end) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_getRangeValue(retptr, this.__wbg_ptr, start, end);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Insert a container at the index.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.toJSON()); // [100, \"Hello\"];\n * ```\n * @param {number} index\n * @param {Container} child\n * @returns {Container}\n */\n insertContainer(index, child) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_insertContainer(retptr, this.__wbg_ptr, index, addHeapObject(child));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the shallow value of the movable list.\n *\n * Unlike `toJSON()` which recursively resolves all containers to their values,\n * `getShallowValue()` returns container IDs as strings for any nested containers.\n *\n * ```js\n * const doc = new LoroDoc();\n * doc.setPeerId(\"1\");\n * const list = doc.getMovableList(\"list\");\n * list.insert(0, 1);\n * list.insert(1, \"two\");\n * const subList = list.insertContainer(2, new LoroList());\n * subList.insert(0, \"sub\");\n * list.getShallowValue(); // [1, \"two\", \"cid:2@1:List\"]\n * list.toJSON(); // [1, \"two\", [\"sub\"]]\n * ```\n * @returns {Value[]}\n */\n getShallowValue() {\n const ret = wasm.loromovablelist_getShallowValue(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the deep value of the movable list with its container id.\n *\n * The result is a `{ cid, value }` object, where `cid` is the container id\n * string (the same as `list.id`) and `value` is the deep value of the\n * list. Child containers inside `value` are recursively replaced by their\n * own `{ cid, value }` nodes. This is the same node shape that\n * `LoroDoc.getDeepValueWithID()` emits for every container.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getMovableList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.getDeepValueWithID());\n * // { cid: \"cid:root-list:MovableList\",\n * // value: [100, { cid: \"cid:0@1:Text\", value: \"Hello\" }] }\n * ```\n * @returns {any}\n */\n getDeepValueWithID() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_getDeepValueWithID(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the deep value of the elements in the range `[start, end)`, with\n * container ids.\n *\n * Each child container in the range is recursively replaced by its own\n * `{ cid, value }` node. Negative bounds are clamped to 0 and\n * out-of-range bounds are clamped to the list length; an empty or\n * inverted range returns `[]`.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getMovableList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.getRangeDeepValueWithID(0, 2));\n * // [100, { cid: \"cid:0@1:Text\", value: \"Hello\" }]\n * ```\n * @param {number} start\n * @param {number} end\n * @returns {any}\n */\n getRangeDeepValueWithID(start, end) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_getRangeDeepValueWithID(retptr, this.__wbg_ptr, start, end);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the id of this container.\n * @returns {ContainerID}\n */\n get id() {\n const ret = wasm.loromovablelist_id(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the value at the index. If the value is a container, the corresponding handler will be returned.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * console.log(list.get(0)); // 100\n * console.log(list.get(1)); // undefined\n * ```\n * @param {number} index\n * @returns {Value | Container | undefined}\n */\n get(index) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_get(retptr, this.__wbg_ptr, index);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Move the element from `from` to `to`.\n *\n * The new position of the element will be `to`.\n * Move the element from `from` to `to`.\n *\n * The new position of the element will be `to`. This method is optimized to prevent redundant\n * operations that might occur with a naive remove and insert approach. Specifically, it avoids\n * creating surplus values in the list, unlike a delete followed by an insert, which can lead to\n * additional values in cases of concurrent edits. This ensures more efficient and accurate\n * operations in a MovableList.\n * @param {number} from\n * @param {number} to\n */\n move(from, to) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_move(retptr, this.__wbg_ptr, from, to);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Create a new detached LoroMovableList (not attached to any LoroDoc).\n *\n * The edits on a detached container will not be persisted.\n * To attach the container to the document, please insert it into an attached container.\n */\n constructor() {\n const ret = wasm.loromovablelist_new();\n this.__wbg_ptr = ret >>> 0;\n LoroMovableListFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * Pop a value from the end of the list.\n * @returns {Value | undefined}\n */\n pop() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_pop(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Set the value at the given position.\n *\n * It's different from `delete` + `insert` that it will replace the value at the position.\n *\n * For example, if you have a list `[1, 2, 3]`, and you call `set(1, 100)`, the list will be `[1, 100, 3]`.\n * If concurrently someone call `set(1, 200)`, the list will be `[1, 200, 3]` or `[1, 100, 3]`.\n *\n * But if you use `delete` + `insert` to simulate the set operation, they may create redundant operations\n * and the final result will be `[1, 100, 200, 3]` or `[1, 200, 100, 3]`.\n * @param {number} pos\n * @param {Value} value\n */\n set(pos, value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_set(retptr, this.__wbg_ptr, pos, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * \"MovableList\"\n * @returns {'MovableList'}\n */\n kind() {\n const ret = wasm.loromovablelist_kind(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Push a value to the end of the list.\n * @param {Value} value\n */\n push(value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_push(retptr, this.__wbg_ptr, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Delete all elements in the list.\n */\n clear() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_clear(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Delete elements from index to index + len.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.delete(0, 1);\n * console.log(list.value); // []\n * ```\n * @param {number} index\n * @param {number} len\n */\n delete(index, len) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_delete(retptr, this.__wbg_ptr, index, len);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Insert a value at index.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.insert(1, \"foo\");\n * list.insert(2, true);\n * console.log(list.value); // [100, \"foo\", true];\n * ```\n * @param {number} index\n * @param {Value} value\n */\n insert(index, value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_insert(retptr, this.__wbg_ptr, index, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the length of list.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.insert(1, \"foo\");\n * list.insert(2, true);\n * console.log(list.length); // 3\n * ```\n * @returns {number}\n */\n get length() {\n const ret = wasm.loromovablelist_length(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * Get the parent container.\n *\n * - The parent container of the root tree is `undefined`.\n * - The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n * @returns {Container | undefined}\n */\n parent() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_parent(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get elements of the list. If the type of a element is a container, it will be\n * resolved recursively.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * const text = list.insertContainer(1, new LoroText());\n * text.insert(0, \"Hello\");\n * console.log(list.toJSON()); // [100, \"Hello\"];\n * ```\n * @returns {any}\n */\n toJSON() {\n const ret = wasm.loromovablelist_toJSON(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get elements of the list. If the value is a child container, the corresponding\n * `Container` will be returned.\n *\n * @example\n * ```ts\n * import { LoroDoc, LoroText } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.insert(0, 100);\n * list.insert(1, \"foo\");\n * list.insert(2, true);\n * list.insertContainer(3, new LoroText());\n * console.log(list.value); // [100, \"foo\", true, LoroText];\n * ```\n * @returns {(Value | Container)[]}\n */\n toArray() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_toArray(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the cursor of the container.\n * @param {number} pos\n * @param {Side} side\n * @returns {Cursor | undefined}\n */\n getCursor(pos, side) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_getCursor(retptr, this.__wbg_ptr, pos, addHeapObject(side));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 === 0 ? undefined : Cursor.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Check if the container is deleted\n * @returns {boolean}\n */\n isDeleted() {\n const ret = wasm.loromovablelist_isDeleted(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Subscribe to the changes of the list.\n *\n * Returns a subscription callback, which can be used to unsubscribe.\n *\n * The events will be emitted after a transaction is committed. A transaction is committed when:\n *\n * - `doc.commit()` is called.\n * - `doc.export(mode)` is called.\n * - `doc.import(data)` is called.\n * - `doc.checkout(version)` is called.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const list = doc.getList(\"list\");\n * list.subscribe((event)=>{\n * console.log(event);\n * });\n * list.insert(0, 100);\n * doc.commit();\n * ```\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_subscribe(retptr, this.__wbg_ptr, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert this attached container and all descendants to an independent tree.\n * Text format applies recursively. Does not commit; throws for detached\n * containers, unsupported types, invalid options, or nesting above 256.\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerNode}\n */\n toContainerTree(opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_toContainerTree(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Read [start,end), clamped to list length. Inverted bounds return no items.\n * Returns actual start, totalLength and items; this is not a complete container.\n * Only selected descendants are traversed; parent shallow list access is O(N).\n * @param {number} start\n * @param {number} end\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerTreeSlice}\n */\n toContainerTreeSlice(start, end, opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.loromovablelist_toContainerTreeSlice(retptr, this.__wbg_ptr, start, end, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst LoroTextFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_lorotext_free(ptr >>> 0, 1));\n/**\n * The handler of a text container. It supports rich text CRDT.\n *\n * Learn more at https://loro.dev/docs/tutorial/text\n */\nexport class LoroText {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroText.prototype);\n obj.__wbg_ptr = ptr;\n LoroTextFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroTextFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_lorotext_free(ptr, 0);\n }\n /**\n * Change the state of this text by delta.\n *\n * If a delta item is `insert`, it should include all the attributes of the inserted text.\n * Loro's rich text CRDT may make the inserted text inherit some styles when you use\n * `insert` method directly. However, when you use `applyDelta` if some attributes are\n * inherited from CRDT but not included in the delta, they will be removed.\n *\n * Another special property of `applyDelta` is if you format an attribute for ranges out of\n * the text length, Loro will insert new lines to fill the gap first. It's useful when you\n * build the binding between Loro and rich text editors like Quill, which might assume there\n * is always a newline at the end of the text implicitly.\n *\n * @example\n * ```ts\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * doc.configTextStyle({bold: {expand: \"after\"}});\n * text.insert(0, \"Hello World!\");\n * text.mark({ start: 0, end: 5 }, \"bold\", true);\n * const delta = text.toDelta();\n * const text2 = doc.getText(\"text2\");\n * text2.applyDelta(delta);\n * expect(text2.toDelta()).toStrictEqual(delta);\n * ```\n * @param {Delta[]} delta\n */\n applyDelta(delta) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_applyDelta(retptr, this.__wbg_ptr, addHeapObject(delta));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert a position between coordinate systems.\n *\n * Supported values: `\"unicode\"`, `\"utf16\"`, `\"utf8\"`.\n *\n * Returns `undefined` when out of bounds or unsupported.\n * @param {number} index\n * @param {string} from\n * @param {string} to\n * @returns {any}\n */\n convertPos(index, from, to) {\n const ptr0 = passStringToWasm0(from, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passStringToWasm0(to, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len1 = WASM_VECTOR_LEN;\n const ret = wasm.lorotext_convertPos(this.__wbg_ptr, index, ptr0, len0, ptr1, len1);\n return takeObject(ret);\n }\n /**\n * Delete elements from index to utf-8 index + len\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insertUtf8(0, \"Hello\");\n * text.deleteUtf8(1, 3);\n * const s = text.toString();\n * console.log(s); // \"Ho\"\n * ```\n * @param {number} index\n * @param {number} len\n */\n deleteUtf8(index, len) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_deleteUtf8(retptr, this.__wbg_ptr, index, len);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the editor of the text at the given position.\n *\n * Returns `undefined` if the position is out of range.\n * @param {number} pos\n * @returns {PeerID | undefined}\n */\n getEditorOf(pos) {\n const ret = wasm.lorotext_getEditorOf(this.__wbg_ptr, pos);\n return takeObject(ret);\n }\n /**\n * Insert some string at utf-8 index.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insertUtf8(0, \"Hello\");\n * ```\n * @param {number} index\n * @param {string} content\n */\n insertUtf8(index, content) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_insertUtf8(retptr, this.__wbg_ptr, index, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Whether the container is attached to a LoroDoc.\n *\n * If it's detached, the operations on the container will not be persisted.\n * @returns {boolean}\n */\n isAttached() {\n const ret = wasm.lorotext_isAttached(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the rich text delta in the given range (utf-16 index).\n * @param {number} start\n * @param {number} end\n * @returns {Delta[]}\n */\n sliceDelta(start, end) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_sliceDelta(retptr, this.__wbg_ptr, start, end);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the attached container associated with this.\n *\n * Returns an attached `Container` that is equal to this or created by this; otherwise, it returns `undefined`.\n * @returns {LoroText | undefined}\n */\n getAttached() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_getAttached(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Update the current text to the target text, the difference is calculated line by line.\n *\n * It uses Myers' diff algorithm to compute the optimal difference.\n * @param {string} text\n * @param {any} options\n */\n updateByLine(text, options) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_updateByLine(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(options));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the rich text delta in the given range (utf-8 index).\n * @param {number} start\n * @param {number} end\n * @returns {Delta[]}\n */\n sliceDeltaUtf8(start, end) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_sliceDeltaUtf8(retptr, this.__wbg_ptr, start, end);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the shallow value of the text. This equals to `text.toString()`.\n * @returns {string}\n */\n getShallowValue() {\n let deferred1_0;\n let deferred1_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_getShallowValue(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n deferred1_0 = r0;\n deferred1_1 = r1;\n return getStringFromWasm0(r0, r1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n }\n /**\n * Get the deep value of the text with its container id.\n *\n * The result is a `{ cid, value }` object, where `cid` is the container id\n * string (the same as `text.id`) and `value` is the text content. This is\n * the same node shape that `LoroDoc.getDeepValueWithID()` emits for every\n * container.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * console.log(text.getDeepValueWithID()); // { cid: \"cid:root-text:Text\", value: \"Hello\" }\n * ```\n * @returns {any}\n */\n getDeepValueWithID() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_getDeepValueWithID(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the container id of the text.\n * @returns {ContainerID}\n */\n get id() {\n const ret = wasm.lorotext_id(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Create a new detached LoroText (not attached to any LoroDoc).\n *\n * The edits on a detached container will not be persisted.\n * To attach the container to the document, please insert it into an attached container.\n */\n constructor() {\n const ret = wasm.lorotext_new();\n this.__wbg_ptr = ret >>> 0;\n LoroTextFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * Iterate each text span(internal storage unit)\n *\n * The callback function will be called for each span in the text.\n * If the callback returns `false`, the iteration will stop.\n *\n * The current text chunks are snapshotted before callbacks run, so the callback\n * may read or mutate the document without re-entering internal state locks.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * text.iter((str) => (console.log(str), true));\n * ```\n * @param {(text: string) => boolean} callback\n */\n iter(callback) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_iter(retptr, this.__wbg_ptr, addHeapObject(callback));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * \"Text\"\n * @returns {'Text'}\n */\n kind() {\n const ret = wasm.lorotext_kind(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Mark a range of text with a key and a value (utf-16 index).\n *\n * > You should call `configTextStyle` before using `mark` and `unmark`.\n *\n * You can use it to create a highlight, make a range of text bold, or add a link to a range of text.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * doc.configTextStyle({bold: {expand: \"after\"}});\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello World!\");\n * text.mark({ start: 0, end: 5 }, \"bold\", true);\n * ```\n * @param {{ start: number, end: number }} range\n * @param {string} key\n * @param {any} value\n */\n mark(range, key, value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_mark(retptr, this.__wbg_ptr, addHeapObject(range), ptr0, len0, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Push a string to the end of the text.\n * @param {string} s\n */\n push(s) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(s, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_push(retptr, this.__wbg_ptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get a string slice (utf-16 index).\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * text.slice(0, 2); // \"He\"\n * ```\n * @param {number} start_index\n * @param {number} end_index\n * @returns {string}\n */\n slice(start_index, end_index) {\n let deferred2_0;\n let deferred2_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_slice(retptr, this.__wbg_ptr, start_index, end_index);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n var ptr1 = r0;\n var len1 = r1;\n if (r3) {\n ptr1 = 0; len1 = 0;\n throw takeObject(r2);\n }\n deferred2_0 = ptr1;\n deferred2_1 = len1;\n return getStringFromWasm0(ptr1, len1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);\n }\n }\n /**\n * Delete elements from index to index + len (utf-16 index).\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * text.delete(1, 3);\n * const s = text.toString();\n * console.log(s); // \"Ho\"\n * ```\n * @param {number} index\n * @param {number} len\n */\n delete(index, len) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_delete(retptr, this.__wbg_ptr, index, len);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Insert the string at the given index (utf-16 index).\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * ```\n * @param {number} index\n * @param {string} content\n */\n insert(index, content) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_insert(retptr, this.__wbg_ptr, index, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the length of text (utf-16 length).\n * @returns {number}\n */\n get length() {\n const ret = wasm.lorotext_length(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * Get the parent container.\n *\n * - The parent of the root is `undefined`.\n * - The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n * @returns {Container | undefined}\n */\n parent() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_parent(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Delete and return the string at the given range and insert a string at the same position (utf-16 index).\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * text.splice(2, 3, \"llo\"); // \"llo\"\n * ```\n * @param {number} pos\n * @param {number} len\n * @param {string} s\n * @returns {string}\n */\n splice(pos, len, s) {\n let deferred3_0;\n let deferred3_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(s, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_splice(retptr, this.__wbg_ptr, pos, len, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n var ptr2 = r0;\n var len2 = r1;\n if (r3) {\n ptr2 = 0; len2 = 0;\n throw takeObject(r2);\n }\n deferred3_0 = ptr2;\n deferred3_1 = len2;\n return getStringFromWasm0(ptr2, len2);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);\n }\n }\n /**\n * Unmark a range of text with a key and a value (utf-16 index).\n *\n * > You should call `configTextStyle` before using `mark` and `unmark`.\n *\n * You can use it to remove highlights, bolds or links\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * doc.configTextStyle({bold: {expand: \"after\"}});\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello World!\");\n * text.mark({ start: 0, end: 5 }, \"bold\", true);\n * text.unmark({ start: 0, end: 5 }, \"bold\");\n * ```\n * @param {{ start: number, end: number }} range\n * @param {string} key\n */\n unmark(range, key) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_unmark(retptr, this.__wbg_ptr, addHeapObject(range), ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Update the current text to the target text.\n *\n * It will calculate the minimal difference and apply it to the current text.\n * It uses Myers' diff algorithm to compute the optimal difference.\n *\n * This could take a long time for large texts (e.g. > 50_000 characters).\n * In that case, you should use `updateByLine` instead.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * text.update(\"Hello World\");\n * console.log(text.toString()); // \"Hello World\"\n * ```\n * @param {string} text\n * @param {any} options\n */\n update(text, options) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.lorotext_update(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(options));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the character at the given position (utf-16 index).\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * text.insert(0, \"Hello\");\n * text.charAt(0); // \"H\"\n * ```\n * @param {number} pos\n * @returns {string}\n */\n charAt(pos) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_charAt(retptr, this.__wbg_ptr, pos);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return String.fromCodePoint(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the JSON representation of the text.\n * @returns {any}\n */\n toJSON() {\n const ret = wasm.lorotext_toJSON(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the text in [Delta](https://quilljs.com/docs/delta/) format.\n *\n * The returned value will include the rich text information.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const text = doc.getText(\"text\");\n * doc.configTextStyle({bold: {expand: \"after\"}});\n * text.insert(0, \"Hello World!\");\n * text.mark({ start: 0, end: 5 }, \"bold\", true);\n * console.log(text.toDelta()); // [ { insert: 'Hello', attributes: { bold: true } } ]\n * ```\n * @returns {Delta[]}\n */\n toDelta() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_toDelta(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the cursor at the given position.\n *\n * - The first argument is the position (utf16-index).\n * - The second argument is the side: `-1` for left, `0` for middle, `1` for right.\n * @param {number} pos\n * @param {Side} side\n * @returns {Cursor | undefined}\n */\n getCursor(pos, side) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_getCursor(retptr, this.__wbg_ptr, pos, addHeapObject(side));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 === 0 ? undefined : Cursor.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Check if the container is deleted\n * @returns {boolean}\n */\n isDeleted() {\n const ret = wasm.lorotext_isDeleted(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Subscribe to the changes of the text.\n *\n * The events will be emitted after a transaction is committed. A transaction is committed when:\n *\n * - `doc.commit()` is called.\n * - `doc.export(mode)` is called.\n * - `doc.import(data)` is called.\n * - `doc.checkout(version)` is called.\n *\n * returns a subscription callback, which can be used to unsubscribe.\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_subscribe(retptr, this.__wbg_ptr, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert the text to a string\n * @returns {string}\n */\n toString() {\n let deferred1_0;\n let deferred1_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_toString(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n deferred1_0 = r0;\n deferred1_1 = r1;\n return getStringFromWasm0(r0, r1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n }\n /**\n * Convert this attached container and all descendants to an independent tree.\n * Text format applies recursively. Does not commit; throws for detached\n * containers, unsupported types, invalid options, or nesting above 256.\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerNode}\n */\n toContainerTree(opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotext_toContainerTree(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst LoroTreeFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_lorotree_free(ptr >>> 0, 1));\n/**\n * The handler of a tree(forest) container.\n *\n * Learn more at https://loro.dev/docs/tutorial/tree\n */\nexport class LoroTree {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroTree.prototype);\n obj.__wbg_ptr = ptr;\n LoroTreeFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroTreeFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_lorotree_free(ptr, 0);\n }\n /**\n * Create a new tree node as the child of parent and return a `LoroTreeNode` instance.\n * If the parent is undefined, the tree node will be a root node.\n *\n * If the index is not provided, the new node will be appended to the end.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * const node = tree.createNode(undefined, 0);\n *\n * // undefined\n * // / \\\n * // node root\n * ```\n * @param {TreeID | undefined} parent\n * @param {number | null} [index]\n * @returns {LoroTreeNode}\n */\n createNode(parent, index) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_createNode(retptr, this.__wbg_ptr, addBorrowedObject(parent), isLikeNone(index) ? 0x100000001 : (index) >>> 0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroTreeNode.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Whether the container is attached to a document.\n *\n * If it's detached, the operations on the container will not be persisted.\n * @returns {boolean}\n */\n isAttached() {\n const ret = wasm.lorotree_isAttached(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the attached container associated with this.\n *\n * Returns an attached `Container` that equals to this or created by this, otherwise `undefined`.\n * @returns {LoroTree | undefined}\n */\n getAttached() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_getAttached(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get LoroTreeNode by the TreeID.\n * @param {TreeID} target\n * @returns {LoroTreeNode | undefined}\n */\n getNodeByID(target) {\n try {\n const ret = wasm.lorotree_getNodeByID(this.__wbg_ptr, addBorrowedObject(target));\n return ret === 0 ? undefined : LoroTreeNode.__wrap(ret);\n } finally {\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Return `None` if the node is not exist, otherwise return `Some(true)` if the node is deleted.\n * @param {TreeID} target\n * @returns {boolean}\n */\n isNodeDeleted(target) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_isNodeDeleted(retptr, this.__wbg_ptr, addBorrowedObject(target));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 !== 0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get the shallow value of the tree.\n *\n * Unlike `toJSON()` which recursively resolves nested containers to their values,\n * `getShallowValue()` returns container IDs as strings for any nested containers.\n *\n * @example\n * ```ts\n * const doc = new LoroDoc();\n * doc.setPeerId(\"1\");\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * root.data.set(\"name\", \"root\");\n * const text = root.data.setContainer(\"content\", new LoroText());\n * text.insert(0, \"Hello\");\n *\n * console.log(tree.getShallowValue());\n * // [{\n * // id: \"0@1\",\n * // parent: null,\n * // index: 0,\n * // fractional_index: \"80\",\n * // meta: \"cid:0@1:Map\",\n * // children: []\n * // }]\n *\n * console.log(tree.toJSON());\n * // [{\n * // id: \"0@1\",\n * // parent: null,\n * // index: 0,\n * // fractional_index: \"80\",\n * // meta: {\n * // name: \"root\",\n * // content: \"Hello\"\n * // },\n * // children: []\n * // }]\n * ```\n * @returns {TreeNodeShallowValue[]}\n */\n getShallowValue() {\n const ret = wasm.lorotree_getShallowValue(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the deep value of the tree with its container id.\n *\n * The result is a `{ cid, value }` object, where `cid` is the container id\n * string (the same as `tree.id`) and `value` is the deep value of the\n * tree (each node's `meta` is the deep value of its associated metadata\n * map). This is the same node shape that `LoroDoc.getDeepValueWithID()`\n * emits for every container.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * root.data.set(\"color\", \"red\");\n * console.log(tree.getDeepValueWithID());\n * // { cid: \"cid:root-tree:Tree\",\n * // value: [ { id: '0@1', parent: null, ..., meta: { color: 'red' }, children: [] } ] }\n * ```\n * @returns {any}\n */\n getDeepValueWithID() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_getDeepValueWithID(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Set whether to generate a fractional index for moving and creating.\n *\n * A fractional index can be used to determine the position of tree nodes among their siblings.\n *\n * The jitter is used to avoid conflicts when multiple users are creating a node at the same position.\n * A value of 0 is the default, which means no jitter; any value larger than 0 will enable jitter.\n *\n * Generally speaking, higher jitter value will increase the size of the operation\n * [Read more about it](https://www.loro.dev/blog/movable-tree#implementation-and-encoding-size)\n * @param {number} jitter\n */\n enableFractionalIndex(jitter) {\n wasm.lorotree_enableFractionalIndex(this.__wbg_ptr, jitter);\n }\n /**\n * Disable the fractional index generation when you don't need the Tree's siblings to be sorted.\n * The fractional index will always be set to the same default value 0.\n *\n * After calling this, you cannot use `tree.moveTo()`, `tree.moveBefore()`, `tree.moveAfter()`,\n * and `tree.createAt()`.\n */\n disableFractionalIndex() {\n wasm.lorotree_disableFractionalIndex(this.__wbg_ptr);\n }\n /**\n * Whether the tree enables the fractional index generation.\n * @returns {boolean}\n */\n isFractionalIndexEnabled() {\n const ret = wasm.lorotree_isFractionalIndexEnabled(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Get the id of the container.\n * @returns {ContainerID}\n */\n get id() {\n const ret = wasm.lorotree_id(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Move the target tree node to be a child of the parent.\n * It's not allowed that the target is an ancestor of the parent\n * or the target and the parent are the same node.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * const node = root.createNode();\n * const node2 = node.createNode();\n * tree.move(node2.id, root.id);\n * // Error will be thrown if move operation creates a cycle\n * // tree.move(root.id, node.id);\n * ```\n * @param {TreeID} target\n * @param {TreeID | undefined} parent\n * @param {number | null} [index]\n */\n move(target, parent, index) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_move(retptr, this.__wbg_ptr, addBorrowedObject(target), addBorrowedObject(parent), isLikeNone(index) ? 0x100000001 : (index) >>> 0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Create a new detached LoroTree (not attached to any LoroDoc).\n *\n * The edits on a detached container will not be persisted.\n * To attach the container to the document, please insert it into an attached container.\n */\n constructor() {\n const ret = wasm.lorotree_new();\n this.__wbg_ptr = ret >>> 0;\n LoroTreeFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * \"Tree\"\n * @returns {'Tree'}\n */\n kind() {\n const ret = wasm.lorotree_kind(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get all tree nodes of the forest, including deleted nodes.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * const node = root.createNode();\n * const node2 = node.createNode();\n * console.log(tree.nodes());\n * ```\n * @returns {LoroTreeNode[]}\n */\n nodes() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_nodes(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the root nodes of the forest.\n * @returns {LoroTreeNode[]}\n */\n roots() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_roots(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayJsValueFromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 4, 4);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Delete a tree node from the forest.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * const node = root.createNode();\n * tree.delete(node.id);\n * ```\n * @param {TreeID} target\n */\n delete(target) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_delete(retptr, this.__wbg_ptr, addBorrowedObject(target));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get the parent container of the tree container.\n *\n * - The parent container of the root tree is `undefined`.\n * - The object returned is a new js object each time because it need to cross\n * the WASM boundary.\n * @returns {Container | undefined}\n */\n parent() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_parent(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the hierarchy array with metadata of the forest.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * root.data.set(\"color\", \"red\");\n * // [ { id: '0@F2462C4159C4C8D1', parent: null, meta: { color: 'red' }, children: [] } ]\n * console.log(tree.toJSON());\n * ```\n * @returns {any}\n */\n toJSON() {\n const ret = wasm.lorotree_toJSON(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Return `true` if the tree contains the TreeID, include deleted node.\n * @param {TreeID} target\n * @returns {boolean}\n */\n has(target) {\n try {\n const ret = wasm.lorotree_has(this.__wbg_ptr, addBorrowedObject(target));\n return ret !== 0;\n } finally {\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get the hierarchy array of the forest.\n *\n * Note: the metadata will be not resolved. So if you don't only care about hierarchy\n * but also the metadata, you should use `toJson()`.\n * @returns {Array}\n */\n toArray() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_toArray(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the flat array of the forest. If `with_deleted` is true, the deleted nodes will be included.\n * @param {{ withDeleted: boolean }} options\n * @returns {Array}\n */\n getNodes(options) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_getNodes(retptr, this.__wbg_ptr, addHeapObject(options));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Check if the container is deleted\n * @returns {boolean}\n */\n isDeleted() {\n const ret = wasm.lorotree_isDeleted(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Subscribe to the changes of the tree.\n *\n * Returns a subscription callback, which can be used to unsubscribe.\n *\n * Trees have three types of events: `create`, `delete`, and `move`.\n * - `create`: Creates a new node with its `target` TreeID. If `parent` is undefined,\n * a root node is created; otherwise, a child node of `parent` is created.\n * If the node being created was previously deleted and has archived child nodes,\n * create events for these child nodes will also be received.\n * - `delete`: Deletes the target node. The structure and state of the target node and\n * its child nodes are archived, and delete events for the child nodes will not be received.\n * - `move`: Moves the target node. If `parent` is undefined, the target node becomes a root node;\n * otherwise, it becomes a child node of `parent`.\n *\n * If a tree container is subscribed, the event of metadata changes will also be received as a MapDiff.\n * And event's `path` will end with `TreeID`.\n *\n * The events will be emitted after a transaction is committed. A transaction is committed when:\n *\n * - `doc.commit()` is called.\n * - `doc.export(mode)` is called.\n * - `doc.import(data)` is called.\n * - `doc.checkout(version)` is called.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * tree.subscribe((event)=>{\n * // event.type: \"create\" | \"delete\" | \"move\"\n * });\n * const root = tree.createNode();\n * const node = root.createNode();\n * doc.commit();\n * ```\n * @param {Function} f\n * @returns {any}\n */\n subscribe(f) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_subscribe(retptr, this.__wbg_ptr, addHeapObject(f));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert this attached container and all descendants to an independent tree.\n * Text format applies recursively. Does not commit; throws for detached\n * containers, unsupported types, invalid options, or nesting above 256.\n * @param {ContainerTreeOptions | null} [opts]\n * @returns {ContainerNode}\n */\n toContainerTree(opts) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotree_toContainerTree(retptr, this.__wbg_ptr, isLikeNone(opts) ? 0 : addHeapObject(opts));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst LoroTreeNodeFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_lorotreenode_free(ptr >>> 0, 1));\n/**\n * The handler of a tree node.\n */\nexport class LoroTreeNode {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(LoroTreeNode.prototype);\n obj.__wbg_ptr = ptr;\n LoroTreeNodeFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n LoroTreeNodeFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_lorotreenode_free(ptr, 0);\n }\n /**\n * @returns {string}\n */\n __getClassname() {\n let deferred1_0;\n let deferred1_1;\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode___getClassname(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n deferred1_0 = r0;\n deferred1_1 = r1;\n return getStringFromWasm0(r0, r1);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n }\n /**\n * Get the creation id of this node.\n * @returns {{ peer: PeerID, counter: number }}\n */\n creationId() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_creationId(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Check if the node is deleted.\n * @returns {boolean}\n */\n isDeleted() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_isDeleted(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 !== 0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Move the tree node to be before the target node.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * const node = root.createNode();\n * const node2 = root.createNode();\n * node2.moveBefore(node);\n * // root\n * // / \\\n * // node2 node\n * ```\n * @param {LoroTreeNode} target\n */\n moveBefore(target) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n _assertClass(target, LoroTreeNode);\n wasm.lorotreenode_moveBefore(retptr, this.__wbg_ptr, target.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Create a new node as the child of the current node and\n * return an instance of `LoroTreeNode`.\n *\n * If the index is not provided, the new node will be appended to the end.\n *\n * @example\n * ```typescript\n * import { LoroDoc } from \"loro-crdt\";\n *\n * let doc = new LoroDoc();\n * let tree = doc.getTree(\"tree\");\n * let root = tree.createNode();\n * let node = root.createNode();\n * let node2 = root.createNode(0);\n * // root\n * // / \\\n * // node2 node\n * ```\n * @param {number | null} [index]\n * @returns {LoroTreeNode}\n */\n createNode(index) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_createNode(retptr, this.__wbg_ptr, isLikeNone(index) ? 0x100000001 : (index) >>> 0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroTreeNode.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the last mover of this node.\n * @returns {{ peer: PeerID, counter: number } | undefined}\n */\n getLastMoveId() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_getLastMoveId(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @returns {any}\n */\n toJSON() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_toJSON(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the `Fractional Index` of the node.\n *\n * Note: the tree container must be attached to the document.\n * @returns {string | undefined}\n */\n fractionalIndex() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_fractionalIndex(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return takeObject(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * The TreeID of the node.\n * @returns {TreeID}\n */\n get id() {\n const ret = wasm.lorotreenode_id(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * @param {LoroTreeNode | undefined} parent\n * @param {number | null} [index]\n */\n move(parent, index) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_move(retptr, this.__wbg_ptr, addBorrowedObject(parent), isLikeNone(index) ? 0x100000001 : (index) >>> 0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n heap[stack_pointer++] = undefined;\n }\n }\n /**\n * Get the associated metadata map container of a tree node.\n * @returns {LoroMap}\n */\n get data() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_data(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return LoroMap.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the index of the node in the parent's children.\n * @returns {number | undefined}\n */\n index() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_index(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getFloat64(retptr + 8 * 0, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n return r0 === 0x100000001 ? undefined : r0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @returns {LoroTreeNode | undefined}\n */\n parent() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.lorotreenode_parent(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 === 0 ? undefined : LoroTreeNode.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the creator of this node.\n * @returns {PeerID}\n */\n creator() {\n const ret = wasm.lorotreenode_creator(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the children of this node.\n *\n * The objects returned are new js objects each time because they need to cross\n * the WASM boundary.\n * @returns {any}\n */\n children() {\n const ret = wasm.lorotreenode_children(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Move the tree node to be after the target node.\n *\n * @example\n * ```ts\n * import { LoroDoc } from \"loro-crdt\";\n *\n * const doc = new LoroDoc();\n * const tree = doc.getTree(\"tree\");\n * const root = tree.createNode();\n * const node = root.createNode();\n * const node2 = root.createNode();\n * node2.moveAfter(node);\n * // root\n * // / \\\n * // node node2\n * ```\n * @param {LoroTreeNode} target\n */\n moveAfter(target) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n _assertClass(target, LoroTreeNode);\n wasm.lorotreenode_moveAfter(retptr, this.__wbg_ptr, target.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nconst UndoManagerFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_undomanager_free(ptr >>> 0, 1));\n/**\n * `UndoManager` is responsible for handling undo and redo operations.\n *\n * By default, the maxUndoSteps is set to 100, mergeInterval is set to 1000 ms.\n *\n * Each commit made by the current peer is recorded as an undo step in the `UndoManager`.\n * Undo steps can be merged if they occur within a specified merge interval.\n *\n * Note that undo operations are local and cannot revert changes made by other peers.\n * To undo changes made by other peers, consider using the time travel feature.\n *\n * Once the `peerId` is bound to the `UndoManager` in the document, it cannot be changed.\n * Otherwise, the `UndoManager` may not function correctly.\n */\nexport class UndoManager {\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n UndoManagerFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_undomanager_free(ptr, 0);\n }\n groupStart() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.undomanager_groupStart(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Get the value associated with the top redo stack item, if any.\n * Returns `undefined` if there is no redo item.\n * @returns {Value | undefined}\n */\n topRedoValue() {\n const ret = wasm.undomanager_topRedoValue(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Get the value associated with the top undo stack item, if any.\n * Returns `undefined` if there is no undo item.\n * @returns {Value | undefined}\n */\n topUndoValue() {\n const ret = wasm.undomanager_topUndoValue(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * The number of max undo steps.\n * If the number of undo steps exceeds this number, the oldest undo step will be removed.\n * @param {number} steps\n */\n setMaxUndoSteps(steps) {\n wasm.undomanager_setMaxUndoSteps(this.__wbg_ptr, steps);\n }\n /**\n * Set the merge interval (in ms).\n *\n * If the interval is set to 0, the undo steps will not be merged.\n * Otherwise, the undo steps will be merged if the interval between the two steps is less than the given interval.\n * @param {number} interval\n */\n setMergeInterval(interval) {\n wasm.undomanager_setMergeInterval(this.__wbg_ptr, interval);\n }\n /**\n * If a local event's origin matches the given prefix, it will not be recorded in the\n * undo stack.\n * @param {string} prefix\n */\n addExcludeOriginPrefix(prefix) {\n const ptr0 = passStringToWasm0(prefix, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.undomanager_addExcludeOriginPrefix(this.__wbg_ptr, ptr0, len0);\n }\n /**\n * `UndoManager` is responsible for handling undo and redo operations.\n *\n * PeerID cannot be changed during the lifetime of the UndoManager.\n *\n * Note that undo operations are local and cannot revert changes made by other peers.\n * To undo changes made by other peers, consider using the time travel feature.\n *\n * Each commit made by the current peer is recorded as an undo step in the `UndoManager`.\n * Undo steps can be merged if they occur within a specified merge interval.\n *\n * ## Config\n *\n * - `mergeInterval`: Optional. The interval in milliseconds within which undo steps can be merged. Default is 1000 ms.\n * - `maxUndoSteps`: Optional. The maximum number of undo steps to retain. Default is 100.\n * - `excludeOriginPrefixes`: Optional. An array of string prefixes. Events with origins matching these prefixes will be excluded from undo steps.\n * - `onPush`: Optional. A callback function that is called when an undo/redo step is pushed.\n * The function can return a meta data value that will be attached to the given stack item.\n * - `onPop`: Optional. A callback function that is called when an undo/redo step is popped.\n * The function will have a meta data value that was attached to the given stack item when\n * `onPush` was called.\n * @param {LoroDoc} doc\n * @param {UndoConfig} config\n */\n constructor(doc, config) {\n _assertClass(doc, LoroDoc);\n const ret = wasm.undomanager_new(doc.__wbg_ptr, addHeapObject(config));\n this.__wbg_ptr = ret >>> 0;\n UndoManagerFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * Get the peer id of the undo manager.\n * @returns {PeerID}\n */\n peer() {\n const ret = wasm.undomanager_peer(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Redo the last undone operation.\n *\n * Consumes at most one history item, including a no-op. Returns whether\n * local operations were generated. A false result does not imply that the\n * redo stack is empty; use `canRedo()` to check for remaining history.\n *\n * Throws like `undo` on steps that would recreate a container of an\n * unknown type.\n * @returns {boolean}\n */\n redo() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.undomanager_redo(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 !== 0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Undo the last operation.\n *\n * Consumes at most one history item, as defined by grouping and the merge\n * interval. Returns whether local operations were generated. A no-op item\n * is consumed and returns false without undoing earlier items. Use\n * `canUndo()` to check whether history remains.\n *\n * Throws without changing the doc if the step would have to recreate a\n * container of a type unknown to this version (created by a newer\n * loro-crdt). That step, with every edit merged into it, is dropped and its\n * edits stay; the next call undoes the step before it, rebased over the\n * dropped step's edits like over a remote peer's.\n * @returns {boolean}\n */\n undo() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.undomanager_undo(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return r0 !== 0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n clear() {\n wasm.undomanager_clear(this.__wbg_ptr);\n }\n /**\n * Pause the UndoManager so that local edits and checkout events are ignored.\n *\n * While paused, local edits are not recorded as undo steps and checkout\n * events do not clear the stacks. Import events (remote changes) are still\n * processed so that the stacks remain correctly transformed against\n * concurrent edits.\n *\n * Use this before temporary checkouts (e.g. read-only history preview) that\n * should not disturb undo/redo history. Close any open group before pausing.\n *\n * Call `resume()` after returning the document to its original state.\n */\n pause() {\n wasm.undomanager_pause(this.__wbg_ptr);\n }\n /**\n * Resume the UndoManager after a `pause()`.\n */\n resume() {\n wasm.undomanager_resume(this.__wbg_ptr);\n }\n /**\n * Can redo the last operation.\n * @returns {boolean}\n */\n canRedo() {\n const ret = wasm.undomanager_canRedo(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Can undo the last operation.\n * @returns {boolean}\n */\n canUndo() {\n const ret = wasm.undomanager_canUndo(this.__wbg_ptr);\n return ret !== 0;\n }\n groupEnd() {\n wasm.undomanager_groupEnd(this.__wbg_ptr);\n }\n /**\n * Returns whether the UndoManager is currently paused.\n * @returns {boolean}\n */\n isPaused() {\n const ret = wasm.undomanager_isPaused(this.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * Set the on pop event listener.\n *\n * Every time an undo step or redo step is popped, the on pop event listener will be called.\n * @param {any} on_pop\n */\n setOnPop(on_pop) {\n wasm.undomanager_setOnPop(this.__wbg_ptr, addHeapObject(on_pop));\n }\n /**\n * Clear only the redo stack, preserving the undo stack.\n *\n * This is useful when coordinating undo/redo across multiple participants\n * (e.g., multiple editors) where a new edit in one participant should\n * invalidate redo in all other participants.\n */\n clearRedo() {\n wasm.undomanager_clearRedo(this.__wbg_ptr);\n }\n /**\n * Clear only the undo stack, preserving the redo stack.\n */\n clearUndo() {\n wasm.undomanager_clearUndo(this.__wbg_ptr);\n }\n /**\n * Set the on push event listener.\n *\n * Every time an undo step or redo step is pushed, the on push event listener will be called.\n * @param {any} on_push\n */\n setOnPush(on_push) {\n wasm.undomanager_setOnPush(this.__wbg_ptr, addHeapObject(on_push));\n }\n}\n\nconst VersionVectorFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_versionvector_free(ptr >>> 0, 1));\n/**\n * [VersionVector](https://en.wikipedia.org/wiki/Version_vector)\n * is a map from [PeerID] to [Counter]. Its a right-open interval.\n *\n * i.e. a [VersionVector] of `{A: 1, B: 2}` means that A has 1 atomic op and B has 2 atomic ops,\n * thus ID of `{client: A, counter: 1}` is out of the range.\n */\nexport class VersionVector {\n\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(VersionVector.prototype);\n obj.__wbg_ptr = ptr;\n VersionVectorFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n VersionVectorFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_versionvector_free(ptr, 0);\n }\n /**\n * Get the counter of a peer.\n * @param {number | bigint | `${number}`} peer_id\n * @returns {number | undefined}\n */\n get(peer_id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.versionvector_get(retptr, this.__wbg_ptr, addHeapObject(peer_id));\n var r0 = getDataViewMemory0().getFloat64(retptr + 8 * 0, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);\n if (r3) {\n throw takeObject(r2);\n }\n return r0 === 0x100000001 ? undefined : r0;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Create a new version vector.\n * @param {Map | Uint8Array | VersionVector | undefined | null} value\n */\n constructor(value) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.versionvector_new(retptr, addHeapObject(value));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n this.__wbg_ptr = r0 >>> 0;\n VersionVectorFinalization.register(this, this.__wbg_ptr, this);\n return this;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Decode the version vector from a Uint8Array.\n * @param {Uint8Array} bytes\n * @returns {VersionVector}\n */\n static decode(bytes) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.versionvector_decode(retptr, ptr0, len0);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return VersionVector.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Encode the version vector into a Uint8Array.\n * @returns {Uint8Array}\n */\n encode() {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.versionvector_encode(retptr, this.__wbg_ptr);\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var v1 = getArrayU8FromWasm0(r0, r1).slice();\n wasm.__wbindgen_free(r0, r1 * 1, 1);\n return v1;\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * @returns {number}\n */\n length() {\n const ret = wasm.versionvector_length(this.__wbg_ptr);\n return ret >>> 0;\n }\n /**\n * @param {PeerID} peer\n */\n remove(peer) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.versionvector_remove(retptr, this.__wbg_ptr, addHeapObject(peer));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * set the exclusive ending point. target id will NOT be included by self\n * @param {{ peer: PeerID, counter: number }} id\n */\n setEnd(id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.versionvector_setEnd(retptr, this.__wbg_ptr, addHeapObject(id));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Compare the version vector with another version vector.\n *\n * If they are concurrent, return undefined.\n * @param {VersionVector} other\n * @returns {number | undefined}\n */\n compare(other) {\n _assertClass(other, VersionVector);\n const ret = wasm.versionvector_compare(this.__wbg_ptr, other.__wbg_ptr);\n return ret === 0x100000001 ? undefined : ret;\n }\n /**\n * set the inclusive ending point. target id will be included\n * @param {{ peer: PeerID, counter: number }} id\n */\n setLast(id) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.versionvector_setLast(retptr, this.__wbg_ptr, addHeapObject(id));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n if (r1) {\n throw takeObject(r0);\n }\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n /**\n * Convert the version vector to a Map\n * @returns {Map}\n */\n toJSON() {\n const ret = wasm.versionvector_toJSON(this.__wbg_ptr);\n return takeObject(ret);\n }\n /**\n * Create a new version vector from a Map.\n * @param {Map} version\n * @returns {VersionVector}\n */\n static parseJSON(version) {\n try {\n const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);\n wasm.versionvector_parseJSON(retptr, addHeapObject(version));\n var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);\n var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);\n var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);\n if (r2) {\n throw takeObject(r1);\n }\n return VersionVector.__wrap(r0);\n } finally {\n wasm.__wbindgen_add_to_stack_pointer(16);\n }\n }\n}\n\nasync function __wbg_load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n\n } catch (e) {\n if (module.headers.get('Content-Type') != 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else {\n throw e;\n }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n\n } else {\n return instance;\n }\n }\n}\n\nfunction __wbg_get_imports() {\n const imports = {};\n imports.wbg = {};\n imports.wbg.__wbg_String_8f0eb39a4a4c2f66 = function(arg0, arg1) {\n const ret = String(getObject(arg1));\n const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len1 = WASM_VECTOR_LEN;\n getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);\n };\n imports.wbg.__wbg_apply_36be6a55257c99bf = function() { return handleError(function (arg0, arg1, arg2) {\n const ret = getObject(arg0).apply(getObject(arg1), getObject(arg2));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_apply_eb9e9b97497f91e4 = function() { return handleError(function (arg0, arg1, arg2) {\n const ret = Reflect.apply(getObject(arg0), getObject(arg1), getObject(arg2));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_buffer_609cc3eee51ed158 = function(arg0) {\n const ret = getObject(arg0).buffer;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_call_672a4d21634d4a24 = function() { return handleError(function (arg0, arg1) {\n const ret = getObject(arg0).call(getObject(arg1));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_call_7cccdd69e0791ae2 = function() { return handleError(function (arg0, arg1, arg2) {\n const ret = getObject(arg0).call(getObject(arg1), getObject(arg2));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_call_833bed5770ea2041 = function() { return handleError(function (arg0, arg1, arg2, arg3) {\n const ret = getObject(arg0).call(getObject(arg1), getObject(arg2), getObject(arg3));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_call_b8adc8b1d0a0d8eb = function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) {\n const ret = getObject(arg0).call(getObject(arg1), getObject(arg2), getObject(arg3), getObject(arg4));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_changemodifier_new = function(arg0) {\n const ret = ChangeModifier.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_crypto_574e78ad8b13b65f = function(arg0) {\n const ret = getObject(arg0).crypto;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_cursor_new = function(arg0) {\n const ret = Cursor.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_done_769e5ede4b31c67b = function(arg0) {\n const ret = getObject(arg0).done;\n return ret;\n };\n imports.wbg.__wbg_entries_3265d4158b33e5dc = function(arg0) {\n const ret = Object.entries(getObject(arg0));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_entries_c8a90a7ed73e84ce = function(arg0) {\n const ret = getObject(arg0).entries();\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_error_428bae4e36b351e3 = function(arg0, arg1) {\n console.error(getStringFromWasm0(arg0, arg1));\n };\n imports.wbg.__wbg_from_2a5d3e218e67aa85 = function(arg0) {\n const ret = Array.from(getObject(arg0));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_getOwnPropertySymbols_97eebed6fe6e08be = function(arg0) {\n const ret = Object.getOwnPropertySymbols(getObject(arg0));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_getRandomValues_b8f5dbd5f3995a9e = function() { return handleError(function (arg0, arg1) {\n getObject(arg0).getRandomValues(getObject(arg1));\n }, arguments) };\n imports.wbg.__wbg_get_67b2ba62fc30de12 = function() { return handleError(function (arg0, arg1) {\n const ret = Reflect.get(getObject(arg0), getObject(arg1));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_get_b9b93047fe3cf45b = function(arg0, arg1) {\n const ret = getObject(arg0)[arg1 >>> 0];\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_getindex_5b00c274b05714aa = function(arg0, arg1) {\n const ret = getObject(arg0)[arg1 >>> 0];\n return ret;\n };\n imports.wbg.__wbg_getwithrefkey_1dc361bd10053bfe = function(arg0, arg1) {\n const ret = getObject(arg0)[getObject(arg1)];\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_instanceof_ArrayBuffer_e14585432e3737fc = function(arg0) {\n let result;\n try {\n result = getObject(arg0) instanceof ArrayBuffer;\n } catch (_) {\n result = false;\n }\n const ret = result;\n return ret;\n };\n imports.wbg.__wbg_instanceof_Map_f3469ce2244d2430 = function(arg0) {\n let result;\n try {\n result = getObject(arg0) instanceof Map;\n } catch (_) {\n result = false;\n }\n const ret = result;\n return ret;\n };\n imports.wbg.__wbg_instanceof_Object_7f2dcef8f78644a4 = function(arg0) {\n let result;\n try {\n result = getObject(arg0) instanceof Object;\n } catch (_) {\n result = false;\n }\n const ret = result;\n return ret;\n };\n imports.wbg.__wbg_instanceof_Uint8Array_17156bcf118086a9 = function(arg0) {\n let result;\n try {\n result = getObject(arg0) instanceof Uint8Array;\n } catch (_) {\n result = false;\n }\n const ret = result;\n return ret;\n };\n imports.wbg.__wbg_isArray_a1eab7e0d067391b = function(arg0) {\n const ret = Array.isArray(getObject(arg0));\n return ret;\n };\n imports.wbg.__wbg_isSafeInteger_343e2beeeece1bb0 = function(arg0) {\n const ret = Number.isSafeInteger(getObject(arg0));\n return ret;\n };\n imports.wbg.__wbg_iterator_9a24c88df860dc65 = function() {\n const ret = Symbol.iterator;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_length_a446193dc22c12f8 = function(arg0) {\n const ret = getObject(arg0).length;\n return ret;\n };\n imports.wbg.__wbg_length_e2d2a49132c1b256 = function(arg0) {\n const ret = getObject(arg0).length;\n return ret;\n };\n imports.wbg.__wbg_log_0cc1b7768397bcfe = function(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {\n let deferred0_0;\n let deferred0_1;\n try {\n deferred0_0 = arg0;\n deferred0_1 = arg1;\n console.log(getStringFromWasm0(arg0, arg1), getStringFromWasm0(arg2, arg3), getStringFromWasm0(arg4, arg5), getStringFromWasm0(arg6, arg7));\n } finally {\n wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);\n }\n };\n imports.wbg.__wbg_log_882f657276590a29 = function(arg0, arg1) {\n console.log(getStringFromWasm0(arg0, arg1));\n };\n imports.wbg.__wbg_log_cb9e190acc5753fb = function(arg0, arg1) {\n let deferred0_0;\n let deferred0_1;\n try {\n deferred0_0 = arg0;\n deferred0_1 = arg1;\n console.log(getStringFromWasm0(arg0, arg1));\n } finally {\n wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);\n }\n };\n imports.wbg.__wbg_lorocounter_new = function(arg0) {\n const ret = LoroCounter.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_lorolist_new = function(arg0) {\n const ret = LoroList.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_loromap_new = function(arg0) {\n const ret = LoroMap.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_loromovablelist_new = function(arg0) {\n const ret = LoroMovableList.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_lorotext_new = function(arg0) {\n const ret = LoroText.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_lorotree_new = function(arg0) {\n const ret = LoroTree.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_lorotreenode_new = function(arg0) {\n const ret = LoroTreeNode.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_mark_7438147ce31e9d4b = function(arg0, arg1) {\n performance.mark(getStringFromWasm0(arg0, arg1));\n };\n imports.wbg.__wbg_measure_fb7825c11612c823 = function() { return handleError(function (arg0, arg1, arg2, arg3) {\n let deferred0_0;\n let deferred0_1;\n let deferred1_0;\n let deferred1_1;\n try {\n deferred0_0 = arg0;\n deferred0_1 = arg1;\n deferred1_0 = arg2;\n deferred1_1 = arg3;\n performance.measure(getStringFromWasm0(arg0, arg1), getStringFromWasm0(arg2, arg3));\n } finally {\n wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n }, arguments) };\n imports.wbg.__wbg_msCrypto_a61aeb35a24c1329 = function(arg0) {\n const ret = getObject(arg0).msCrypto;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_new_405e22f390576ce2 = function() {\n const ret = new Object();\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_new_5e0be73521bc8c17 = function() {\n const ret = new Map();\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_new_78feb108b6472713 = function() {\n const ret = new Array();\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_new_a12002a7f91c75be = function(arg0) {\n const ret = new Uint8Array(getObject(arg0));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_new_c68d7209be747379 = function(arg0, arg1) {\n const ret = new Error(getStringFromWasm0(arg0, arg1));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_newnoargs_105ed471475aaf50 = function(arg0, arg1) {\n const ret = new Function(getStringFromWasm0(arg0, arg1));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_newwithbyteoffsetandlength_d97e637ebe145a9a = function(arg0, arg1, arg2) {\n const ret = new Uint8Array(getObject(arg0), arg1 >>> 0, arg2 >>> 0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_newwithlength_a381634e90c276d4 = function(arg0) {\n const ret = new Uint8Array(arg0 >>> 0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_newwithlength_c4c419ef0bc8a1f8 = function(arg0) {\n const ret = new Array(arg0 >>> 0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_next_25feadfc0913fea9 = function(arg0) {\n const ret = getObject(arg0).next;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_next_6574e1a8a62d1055 = function() { return handleError(function (arg0) {\n const ret = getObject(arg0).next();\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_node_905d3e251edff8a2 = function(arg0) {\n const ret = getObject(arg0).node;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_now_2b509d5c9d429404 = function() {\n const ret = Date.now();\n return ret;\n };\n imports.wbg.__wbg_ownKeys_3930041068756f1f = function() { return handleError(function (arg0) {\n const ret = Reflect.ownKeys(getObject(arg0));\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_process_dc0fbacc7c1c06f7 = function(arg0) {\n const ret = getObject(arg0).process;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_push_737cfc8c1432c2c6 = function(arg0, arg1) {\n const ret = getObject(arg0).push(getObject(arg1));\n return ret;\n };\n imports.wbg.__wbg_randomFillSync_ac0988aba3254290 = function() { return handleError(function (arg0, arg1) {\n getObject(arg0).randomFillSync(takeObject(arg1));\n }, arguments) };\n imports.wbg.__wbg_require_60cc747a6bc5215a = function() { return handleError(function () {\n const ret = module.require;\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_resolve_4851785c9c5f573d = function(arg0) {\n const ret = Promise.resolve(getObject(arg0));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_set_37837023f3d740e8 = function(arg0, arg1, arg2) {\n getObject(arg0)[arg1 >>> 0] = takeObject(arg2);\n };\n imports.wbg.__wbg_set_3f1d0b984ed272ed = function(arg0, arg1, arg2) {\n getObject(arg0)[takeObject(arg1)] = takeObject(arg2);\n };\n imports.wbg.__wbg_set_65595bdd868b3009 = function(arg0, arg1, arg2) {\n getObject(arg0).set(getObject(arg1), arg2 >>> 0);\n };\n imports.wbg.__wbg_set_8fc6bf8a5b1071d1 = function(arg0, arg1, arg2) {\n const ret = getObject(arg0).set(getObject(arg1), getObject(arg2));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_set_bb8cecf6a62b9f46 = function() { return handleError(function (arg0, arg1, arg2) {\n const ret = Reflect.set(getObject(arg0), getObject(arg1), getObject(arg2));\n return ret;\n }, arguments) };\n imports.wbg.__wbg_stateBinary_bcc49261f5205b9f = function(arg0, arg1) {\n const ret = stateBinary(getArrayU8FromWasm0(arg0, arg1));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_stateCid_ddf7fe40691e2c8f = function(arg0, arg1, arg2) {\n const ret = stateCid(getObject(arg0), arg1, arg2);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_stateContainer_8b73508686ecac7f = function(arg0, arg1, arg2) {\n const ret = stateContainer(arg0, getObject(arg1), takeObject(arg2));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_stateIndex_985e23155ddc5679 = function() { return handleError(function (arg0, arg1, arg2) {\n stateIndex(getObject(arg0), arg1 >>> 0, getObject(arg2));\n }, arguments) };\n imports.wbg.__wbg_stateOptions_234376ac96321e68 = function() { return handleError(function (arg0, arg1) {\n const ret = stateOptions(takeObject(arg0), arg1 !== 0);\n return addHeapObject(ret);\n }, arguments) };\n imports.wbg.__wbg_stateRootCid_92a320b321ddff0a = function(arg0, arg1, arg2) {\n const ret = stateRootCid(getStringFromWasm0(arg0, arg1), arg2);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_stateSet_9c75457bd566f749 = function() { return handleError(function (arg0, arg1, arg2) {\n stateSet(getObject(arg0), getObject(arg1), getObject(arg2));\n }, arguments) };\n imports.wbg.__wbg_stateSlice_4573448d6dfd609f = function(arg0, arg1, arg2) {\n const ret = stateSlice(takeObject(arg0), arg1 >>> 0, arg2 >>> 0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_stateValue_32a9721f28b53795 = function(arg0) {\n const ret = stateValue(takeObject(arg0));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_static_accessor_GLOBAL_88a902d13a557d07 = function() {\n const ret = typeof global === 'undefined' ? null : global;\n return isLikeNone(ret) ? 0 : addHeapObject(ret);\n };\n imports.wbg.__wbg_static_accessor_GLOBAL_THIS_56578be7e9f832b0 = function() {\n const ret = typeof globalThis === 'undefined' ? null : globalThis;\n return isLikeNone(ret) ? 0 : addHeapObject(ret);\n };\n imports.wbg.__wbg_static_accessor_SELF_37c5d418e4bf5819 = function() {\n const ret = typeof self === 'undefined' ? null : self;\n return isLikeNone(ret) ? 0 : addHeapObject(ret);\n };\n imports.wbg.__wbg_static_accessor_WINDOW_5de37043a91a9c40 = function() {\n const ret = typeof window === 'undefined' ? null : window;\n return isLikeNone(ret) ? 0 : addHeapObject(ret);\n };\n imports.wbg.__wbg_subarray_aa9065fa9dc5df96 = function(arg0, arg1, arg2) {\n const ret = getObject(arg0).subarray(arg1 >>> 0, arg2 >>> 0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_then_44b73946d2fb3e7d = function(arg0, arg1) {\n const ret = getObject(arg0).then(getObject(arg1));\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_value_cd1ffa7b1ab794f1 = function(arg0) {\n const ret = getObject(arg0).value;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_versions_c01dfd4722a88165 = function(arg0) {\n const ret = getObject(arg0).versions;\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_versionvector_new = function(arg0) {\n const ret = VersionVector.__wrap(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbg_warn_5d1fd3858772ca54 = function(arg0, arg1) {\n console.warn(getStringFromWasm0(arg0, arg1));\n };\n imports.wbg.__wbindgen_as_number = function(arg0) {\n const ret = +getObject(arg0);\n return ret;\n };\n imports.wbg.__wbindgen_bigint_from_i64 = function(arg0) {\n const ret = arg0;\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_bigint_from_u64 = function(arg0) {\n const ret = BigInt.asUintN(64, arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_bigint_get_as_i64 = function(arg0, arg1) {\n const v = getObject(arg1);\n const ret = typeof(v) === 'bigint' ? v : undefined;\n getDataViewMemory0().setBigInt64(arg0 + 8 * 1, isLikeNone(ret) ? BigInt(0) : ret, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);\n };\n imports.wbg.__wbindgen_boolean_get = function(arg0) {\n const v = getObject(arg0);\n const ret = typeof(v) === 'boolean' ? (v ? 1 : 0) : 2;\n return ret;\n };\n imports.wbg.__wbindgen_cb_drop = function(arg0) {\n const obj = takeObject(arg0).original;\n if (obj.cnt-- == 1) {\n obj.a = 0;\n return true;\n }\n const ret = false;\n return ret;\n };\n imports.wbg.__wbindgen_closure_wrapper295 = function(arg0, arg1, arg2) {\n const ret = makeMutClosure(arg0, arg1, 16, __wbg_adapter_58);\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_closure_wrapper551 = function(arg0, arg1, arg2) {\n const ret = makeMutClosure(arg0, arg1, 16, __wbg_adapter_61);\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_debug_string = function(arg0, arg1) {\n const ret = debugString(getObject(arg1));\n const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len1 = WASM_VECTOR_LEN;\n getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);\n };\n imports.wbg.__wbindgen_error_new = function(arg0, arg1) {\n const ret = new Error(getStringFromWasm0(arg0, arg1));\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_in = function(arg0, arg1) {\n const ret = getObject(arg0) in getObject(arg1);\n return ret;\n };\n imports.wbg.__wbindgen_is_array = function(arg0) {\n const ret = Array.isArray(getObject(arg0));\n return ret;\n };\n imports.wbg.__wbindgen_is_bigint = function(arg0) {\n const ret = typeof(getObject(arg0)) === 'bigint';\n return ret;\n };\n imports.wbg.__wbindgen_is_function = function(arg0) {\n const ret = typeof(getObject(arg0)) === 'function';\n return ret;\n };\n imports.wbg.__wbindgen_is_null = function(arg0) {\n const ret = getObject(arg0) === null;\n return ret;\n };\n imports.wbg.__wbindgen_is_object = function(arg0) {\n const val = getObject(arg0);\n const ret = typeof(val) === 'object' && val !== null;\n return ret;\n };\n imports.wbg.__wbindgen_is_string = function(arg0) {\n const ret = typeof(getObject(arg0)) === 'string';\n return ret;\n };\n imports.wbg.__wbindgen_is_undefined = function(arg0) {\n const ret = getObject(arg0) === undefined;\n return ret;\n };\n imports.wbg.__wbindgen_jsval_eq = function(arg0, arg1) {\n const ret = getObject(arg0) === getObject(arg1);\n return ret;\n };\n imports.wbg.__wbindgen_jsval_loose_eq = function(arg0, arg1) {\n const ret = getObject(arg0) == getObject(arg1);\n return ret;\n };\n imports.wbg.__wbindgen_memory = function() {\n const ret = wasm.memory;\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_number_get = function(arg0, arg1) {\n const obj = getObject(arg1);\n const ret = typeof(obj) === 'number' ? obj : undefined;\n getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);\n };\n imports.wbg.__wbindgen_number_new = function(arg0) {\n const ret = arg0;\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_object_clone_ref = function(arg0) {\n const ret = getObject(arg0);\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_object_drop_ref = function(arg0) {\n takeObject(arg0);\n };\n imports.wbg.__wbindgen_rethrow = function(arg0) {\n throw takeObject(arg0);\n };\n imports.wbg.__wbindgen_string_get = function(arg0, arg1) {\n const obj = getObject(arg1);\n const ret = typeof(obj) === 'string' ? obj : undefined;\n var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n var len1 = WASM_VECTOR_LEN;\n getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);\n };\n imports.wbg.__wbindgen_string_new = function(arg0, arg1) {\n const ret = getStringFromWasm0(arg0, arg1);\n return addHeapObject(ret);\n };\n imports.wbg.__wbindgen_throw = function(arg0, arg1) {\n throw new Error(getStringFromWasm0(arg0, arg1));\n };\n imports.wbg.__wbindgen_typeof = function(arg0) {\n const ret = typeof getObject(arg0);\n return addHeapObject(ret);\n };\n\n return imports;\n}\n\nfunction __wbg_init_memory(imports, memory) {\n\n}\n\nfunction __wbg_finalize_init(instance, module) {\n wasm = instance.exports;\n __wbg_init.__wbindgen_wasm_module = module;\n cachedDataViewMemory0 = null;\n cachedUint8ArrayMemory0 = null;\n\n\n wasm.__wbindgen_start();\n return wasm;\n}\n\nfunction initSync(module) {\n if (wasm !== undefined) return wasm;\n\n\n if (typeof module !== 'undefined') {\n if (Object.getPrototypeOf(module) === Object.prototype) {\n ({module} = module)\n } else {\n console.warn('using deprecated parameters for `initSync()`; pass a single object instead')\n }\n }\n\n const imports = __wbg_get_imports();\n\n __wbg_init_memory(imports);\n\n if (!(module instanceof WebAssembly.Module)) {\n module = new WebAssembly.Module(module);\n }\n\n const instance = new WebAssembly.Instance(module, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nasync function __wbg_init(module_or_path) {\n if (wasm !== undefined) return wasm;\n\n\n if (typeof module_or_path !== 'undefined') {\n if (Object.getPrototypeOf(module_or_path) === Object.prototype) {\n ({module_or_path} = module_or_path)\n } else {\n console.warn('using deprecated parameters for the initialization function; pass a single object instead')\n }\n }\n\n if (typeof module_or_path === 'undefined') {\n module_or_path = new URL('loro_wasm_bg.wasm', import.meta.url);\n }\n const imports = __wbg_get_imports();\n\n if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {\n module_or_path = fetch(module_or_path);\n }\n\n __wbg_init_memory(imports);\n\n const { instance, module } = await __wbg_load(await module_or_path, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nexport { initSync };\nexport default __wbg_init;\n\n// A container handler never changes identity during one JS wrapper's lifetime.\n// Attaching a detached handler returns a different wrapper, and getAttached()\n// also returns a new wrapper. Cache on the wrapper, not by container id.\nconst __loroContainerIdCache = Symbol(\"loroContainerId\");\n\nfunction __loroCacheContainerIdGetter(ContainerClass) {\n const prototype = ContainerClass.prototype;\n const idDescriptor = Object.getOwnPropertyDescriptor(prototype, \"id\");\n const getId = idDescriptor && idDescriptor.get;\n const destroyDescriptor = Object.getOwnPropertyDescriptor(\n prototype,\n \"__destroy_into_raw\",\n );\n const destroy = destroyDescriptor && destroyDescriptor.value;\n\n if (!getId || !destroyDescriptor || !destroy) {\n throw new Error(\"Unexpected wasm-bindgen container wrapper shape\");\n }\n\n Object.defineProperty(prototype, \"id\", {\n ...idDescriptor,\n get() {\n // Preserve wasm-bindgen's post-free error instead of returning stale data.\n if (this.__wbg_ptr === 0) {\n return getId.call(this);\n }\n\n const cached = this[__loroContainerIdCache];\n if (cached !== undefined) {\n return cached;\n }\n\n const id = getId.call(this);\n try {\n Object.defineProperty(this, __loroContainerIdCache, {\n configurable: true,\n value: id,\n });\n } catch {\n // Caching must not make a non-extensible wrapper's id unreadable.\n }\n return id;\n },\n });\n\n Object.defineProperty(prototype, \"__destroy_into_raw\", {\n ...destroyDescriptor,\n value() {\n try {\n delete this[__loroContainerIdCache];\n } catch {\n // Cache cleanup must not replace wasm-bindgen's free behavior.\n }\n return destroy.call(this);\n },\n });\n}\n\n// `kind()` returns a constant string per container class and never depends on\n// instance state, so one module-level memo per class is enough. Repeated reads\n// (e.g. loro-mirror's traversal) must not cross into WASM again.\nfunction __loroCacheKindMethod(ContainerClass) {\n const prototype = ContainerClass.prototype;\n const kindDescriptor = Object.getOwnPropertyDescriptor(prototype, \"kind\");\n const kind = kindDescriptor && kindDescriptor.value;\n\n if (typeof kind !== \"function\") {\n throw new Error(\"Unexpected wasm-bindgen container wrapper shape\");\n }\n\n let cached;\n Object.defineProperty(prototype, \"kind\", {\n ...kindDescriptor,\n value() {\n // Preserve wasm-bindgen's post-free error instead of returning stale data.\n if (this.__wbg_ptr === 0) {\n return kind.call(this);\n }\n\n if (cached === undefined) {\n cached = kind.call(this);\n }\n return cached;\n },\n });\n}\n\nfor (const ContainerClass of [\n LoroMap,\n LoroText,\n LoroList,\n LoroTree,\n LoroMovableList,\n LoroCounter,\n]) {\n __loroCacheContainerIdGetter(ContainerClass);\n __loroCacheKindMethod(ContainerClass);\n}\n", - "export { default } from \"./loro_wasm.js\";\nimport { LoroDoc, EphemeralStoreWasm, UndoManager, isValidContainerId, AwarenessWasm, callPendingEvents } from \"./loro_wasm.js\";\nexport * from \"./loro_wasm.js\";\n\n/**\n * @deprecated Please use LoroDoc\n */\nclass Loro extends LoroDoc {\n}\nconst CONTAINER_TYPES = [\n \"Map\",\n \"Text\",\n \"List\",\n \"Tree\",\n \"MovableList\",\n \"Counter\",\n];\nfunction isContainerId(s) {\n return isValidContainerId(s);\n}\n/** Whether the value is a container.\n *\n * # Example\n *\n * ```ts\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * const list = doc.getList(\"list\");\n * const text = doc.getText(\"text\");\n * isContainer(map); // true\n * isContainer(list); // true\n * isContainer(text); // true\n * isContainer(123); // false\n * isContainer(\"123\"); // false\n * isContainer({}); // false\n * ```\n */\nfunction isContainer(value) {\n if (typeof value !== \"object\" || value == null) {\n return false;\n }\n const p = Object.getPrototypeOf(value);\n if (p == null || typeof p !== \"object\" || typeof p[\"kind\"] !== \"function\") {\n return false;\n }\n return CONTAINER_TYPES.includes(value.kind());\n}\n/** Get the type of a value that may be a container.\n *\n * # Example\n *\n * ```ts\n * const doc = new LoroDoc();\n * const map = doc.getMap(\"map\");\n * const list = doc.getList(\"list\");\n * const text = doc.getText(\"text\");\n * getType(map); // \"Map\"\n * getType(list); // \"List\"\n * getType(text); // \"Text\"\n * getType(123); // \"Json\"\n * getType(\"123\"); // \"Json\"\n * getType({}); // \"Json\"\n * ```\n */\nfunction getType(value) {\n if (isContainer(value)) {\n return value.kind();\n }\n return \"Json\";\n}\nfunction newContainerID(id, type) {\n return `cid:${id.counter}@${id.peer}:${type}`;\n}\nfunction newRootContainerID(name, type) {\n return `cid:root-${name}:${type}`;\n}\n/**\n * @deprecated Please use `EphemeralStore` instead.\n *\n * Awareness is a structure that allows to track the ephemeral state of the peers.\n *\n * If we don't receive a state update from a peer within the timeout, we will remove their state.\n * The timeout is in milliseconds. This can be used to handle the offline state of a peer.\n */\nclass Awareness {\n constructor(peer, timeout = 30000) {\n this.listeners = new Set();\n this.inner = new AwarenessWasm(peer, timeout);\n this.peer = peer;\n this.timeout = timeout;\n }\n apply(bytes, origin = \"remote\") {\n const { updated, added } = this.inner.apply(bytes);\n this.listeners.forEach((listener) => {\n listener({ updated, added, removed: [] }, origin);\n });\n this.startTimerIfNotEmpty();\n }\n setLocalState(state) {\n const wasEmpty = this.inner.getState(this.peer) == null;\n this.inner.setLocalState(state);\n if (wasEmpty) {\n this.listeners.forEach((listener) => {\n listener({ updated: [], added: [this.inner.peer()], removed: [] }, \"local\");\n });\n }\n else {\n this.listeners.forEach((listener) => {\n listener({ updated: [this.inner.peer()], added: [], removed: [] }, \"local\");\n });\n }\n this.startTimerIfNotEmpty();\n }\n getLocalState() {\n return this.inner.getState(this.peer);\n }\n getAllStates() {\n return this.inner.getAllStates();\n }\n encode(peers) {\n return this.inner.encode(peers);\n }\n encodeAll() {\n return this.inner.encodeAll();\n }\n addListener(listener) {\n this.listeners.add(listener);\n }\n removeListener(listener) {\n this.listeners.delete(listener);\n }\n peers() {\n return this.inner.peers();\n }\n destroy() {\n clearInterval(this.timer);\n this.listeners.clear();\n }\n startTimerIfNotEmpty() {\n if (this.inner.isEmpty() || this.timer != null) {\n return;\n }\n this.timer = setInterval(() => {\n const removed = this.inner.removeOutdated();\n if (removed.length > 0) {\n this.listeners.forEach((listener) => {\n listener({ updated: [], added: [], removed }, \"timeout\");\n });\n }\n if (this.inner.isEmpty()) {\n clearInterval(this.timer);\n this.timer = undefined;\n }\n }, this.timeout / 2);\n }\n}\n/**\n * EphemeralStore tracks ephemeral key-value state across peers.\n *\n * - Use it for lightweight presence/state like cursors, selections, and UI hints.\n * - Conflict resolution is timestamp-based LWW (Last-Write-Wins) per key.\n * - Timeout unit: milliseconds.\n * - After timeout: keys are considered expired. They are omitted from\n * `encode(key)`, `encodeAll()` and `getAllStates()`. A periodic cleanup runs\n * while the store is non-empty and removes expired keys; when removals happen\n * subscribers receive an event with `by: \"timeout\"` and the `removed` keys.\n *\n * See: https://loro.dev/docs/tutorial/ephemeral\n *\n * @param timeout Inactivity timeout in milliseconds (default: 30000). If a key\n * doesn't receive updates within this duration, it will expire and be removed\n * on the next cleanup tick.\n *\n * @example\n * ```ts\n * const store = new EphemeralStore();\n * const store2 = new EphemeralStore();\n * // Subscribe to local updates and forward over the wire\n * store.subscribeLocalUpdates((data) => {\n * store2.apply(data);\n * });\n * // Subscribe to all updates (including removals by timeout)\n * store2.subscribe((event) => {\n * console.log(\"event:\", event);\n * });\n * // Set a value\n * store.set(\"key\", \"value\");\n * // Encode the value\n * const encoded = store.encode(\"key\");\n * // Apply the encoded value\n * store2.apply(encoded);\n * ```\n */\nclass EphemeralStore {\n constructor(timeout = 30000) {\n this.inner = new EphemeralStoreWasm(timeout);\n this.timeout = timeout;\n }\n apply(bytes) {\n this.inner.apply(bytes);\n this.startTimerIfNotEmpty();\n }\n set(key, value) {\n this.inner.set(key, value);\n this.startTimerIfNotEmpty();\n }\n delete(key) {\n this.inner.delete(key);\n }\n get(key) {\n return this.inner.get(key);\n }\n getAllStates() {\n return this.inner.getAllStates();\n }\n encode(key) {\n return this.inner.encode(key);\n }\n encodeAll() {\n return this.inner.encodeAll();\n }\n keys() {\n return this.inner.keys();\n }\n destroy() {\n clearInterval(this.timer);\n }\n subscribe(listener) {\n return this.inner.subscribe(listener);\n }\n subscribeLocalUpdates(listener) {\n return this.inner.subscribeLocalUpdates(listener);\n }\n startTimerIfNotEmpty() {\n if (this.inner.isEmpty() || this.timer != null) {\n return;\n }\n this.timer = setInterval(() => {\n this.inner.removeOutdated();\n if (this.inner.isEmpty()) {\n clearInterval(this.timer);\n this.timer = undefined;\n }\n }, this.timeout / 2);\n }\n}\nLoroDoc.prototype.toJsonWithReplacer = function (replacer) {\n const processed = new Set();\n const doc = this;\n const m = (key, value) => {\n if (typeof value === \"string\") {\n if (isContainerId(value) && !processed.has(value)) {\n processed.add(value);\n const container = doc.getContainerById(value);\n if (container == null) {\n throw new Error(`ContainerID not found: ${value}`);\n }\n const ans = replacer(key, container);\n if (ans === container) {\n const ans = container.getShallowValue();\n if (typeof ans === \"object\") {\n return run(ans);\n }\n return ans;\n }\n if (isContainer(ans)) {\n throw new Error(\"Using new container is not allowed in toJsonWithReplacer\");\n }\n if (typeof ans === \"object\" && ans != null) {\n return run(ans);\n }\n return ans;\n }\n }\n if (typeof value === \"object\" && value != null) {\n return run(value);\n }\n const ans = replacer(key, value);\n if (isContainer(ans)) {\n throw new Error(\"Using new container is not allowed in toJsonWithReplacer\");\n }\n return ans;\n };\n const run = (layer) => {\n if (Array.isArray(layer)) {\n return layer\n .map((item, index) => {\n return m(index, item);\n })\n .filter((item) => item !== undefined);\n }\n const result = {};\n for (const [key, value] of Object.entries(layer)) {\n const ans = m(key, value);\n if (ans !== undefined) {\n result[key] = ans;\n }\n }\n return result;\n };\n const layer = doc.getShallowValue();\n return run(layer);\n};\nfunction idStrToId(idStr) {\n const [counter, peer] = idStr.split(\"@\");\n return {\n counter: parseInt(counter),\n peer: peer,\n };\n}\nconst CALL_PENDING_EVENTS_WRAPPED = Symbol(\"loro.callPendingEventsWrapped\");\nfunction decorateMethod(prototype, method) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, method);\n if (!descriptor || typeof descriptor.value !== \"function\") {\n return;\n }\n const original = descriptor.value;\n if (original[CALL_PENDING_EVENTS_WRAPPED]) {\n return;\n }\n const wrapped = function (...args) {\n let result;\n try {\n result = original.apply(this, args);\n return result;\n }\n finally {\n if (result && typeof result.then === \"function\") {\n result.finally(() => {\n callPendingEvents();\n });\n }\n else {\n callPendingEvents();\n }\n }\n };\n wrapped[CALL_PENDING_EVENTS_WRAPPED] = true;\n Object.defineProperty(prototype, method, {\n ...descriptor,\n value: wrapped,\n });\n}\nfunction decorateMethods(prototype, methods) {\n for (const method of methods) {\n decorateMethod(prototype, method);\n }\n}\ndecorateMethods(LoroDoc.prototype, [\n \"setDetachedEditing\",\n \"attach\",\n \"detach\",\n \"fork\",\n \"forkAt\",\n \"checkoutToLatest\",\n \"checkout\",\n \"commit\",\n \"getCursorPos\",\n \"revertTo\",\n \"export\",\n \"exportJsonUpdates\",\n \"exportJsonInIdSpan\",\n \"importJsonUpdates\",\n \"import\",\n \"importUpdateBatch\",\n \"importBatch\",\n \"travelChangeAncestors\",\n \"getChangedContainersIn\",\n \"diff\",\n \"applyDiff\",\n \"setPeerId\",\n]);\ndecorateMethods(EphemeralStoreWasm.prototype, [\n \"set\",\n \"delete\",\n \"apply\",\n \"removeOutdated\",\n]);\ndecorateMethods(UndoManager.prototype, [\"undo\", \"redo\"]);\n\nexport { Awareness, EphemeralStore, Loro, getType, idStrToId, isContainer, isContainerId, newContainerID, newRootContainerID };\n// loro-explicit-wasm-reexports\nexport {\n AwarenessWasm,\n ChangeModifier,\n Cursor,\n EphemeralStoreWasm,\n LORO_VERSION,\n LoroCounter,\n LoroDoc,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n LoroTreeNode,\n UndoManager,\n VersionVector,\n callPendingEvents,\n decodeFrontiers,\n decodeImportBlobMeta,\n encodeFrontiers,\n initSync,\n isValidContainerId,\n redactJsonUpdates,\n run,\n setDebug,\n} from \"./loro_wasm.js\";\n//# sourceMappingURL=index.js.map\n", - "// ::- Persistent data structure representing an ordered mapping from\n// strings to values, with some convenient update methods.\nfunction OrderedMap(content) {\n this.content = content;\n}\n\nOrderedMap.prototype = {\n constructor: OrderedMap,\n\n find: function(key) {\n for (var i = 0; i < this.content.length; i += 2)\n if (this.content[i] === key) return i\n return -1\n },\n\n // :: (string) → ?any\n // Retrieve the value stored under `key`, or return undefined when\n // no such key exists.\n get: function(key) {\n var found = this.find(key);\n return found == -1 ? undefined : this.content[found + 1]\n },\n\n // :: (string, any, ?string) → OrderedMap\n // Create a new map by replacing the value of `key` with a new\n // value, or adding a binding to the end of the map. If `newKey` is\n // given, the key of the binding will be replaced with that key.\n update: function(key, value, newKey) {\n var self = newKey && newKey != key ? this.remove(newKey) : this;\n var found = self.find(key), content = self.content.slice();\n if (found == -1) {\n content.push(newKey || key, value);\n } else {\n content[found + 1] = value;\n if (newKey) content[found] = newKey;\n }\n return new OrderedMap(content)\n },\n\n // :: (string) → OrderedMap\n // Return a map with the given key removed, if it existed.\n remove: function(key) {\n var found = this.find(key);\n if (found == -1) return this\n var content = this.content.slice();\n content.splice(found, 2);\n return new OrderedMap(content)\n },\n\n // :: (string, any) → OrderedMap\n // Add a new key to the start of the map.\n addToStart: function(key, value) {\n return new OrderedMap([key, value].concat(this.remove(key).content))\n },\n\n // :: (string, any) → OrderedMap\n // Add a new key to the end of the map.\n addToEnd: function(key, value) {\n var content = this.remove(key).content.slice();\n content.push(key, value);\n return new OrderedMap(content)\n },\n\n // :: (string, string, any) → OrderedMap\n // Add a key after the given key. If `place` is not found, the new\n // key is added to the end.\n addBefore: function(place, key, value) {\n var without = this.remove(key), content = without.content.slice();\n var found = without.find(place);\n content.splice(found == -1 ? content.length : found, 0, key, value);\n return new OrderedMap(content)\n },\n\n // :: ((key: string, value: any))\n // Call the given function for each key/value pair in the map, in\n // order.\n forEach: function(f) {\n for (var i = 0; i < this.content.length; i += 2)\n f(this.content[i], this.content[i + 1]);\n },\n\n // :: (union) → OrderedMap\n // Create a new map by prepending the keys in this map that don't\n // appear in `map` before the keys in `map`.\n prepend: function(map) {\n map = OrderedMap.from(map);\n if (!map.size) return this\n return new OrderedMap(map.content.concat(this.subtract(map).content))\n },\n\n // :: (union) → OrderedMap\n // Create a new map by appending the keys in this map that don't\n // appear in `map` after the keys in `map`.\n append: function(map) {\n map = OrderedMap.from(map);\n if (!map.size) return this\n return new OrderedMap(this.subtract(map).content.concat(map.content))\n },\n\n // :: (union) → OrderedMap\n // Create a map containing all the keys in this map that don't\n // appear in `map`.\n subtract: function(map) {\n var result = this;\n map = OrderedMap.from(map);\n for (var i = 0; i < map.content.length; i += 2)\n result = result.remove(map.content[i]);\n return result\n },\n\n // :: () → Object\n // Turn ordered map into a plain object.\n toObject: function() {\n var result = {};\n this.forEach(function(key, value) { result[key] = value; });\n return result\n },\n\n // :: number\n // The amount of keys in this map.\n get size() {\n return this.content.length >> 1\n }\n};\n\n// :: (?union) → OrderedMap\n// Return a map with the given content. If null, create an empty\n// map. If given an ordered map, return that map itself. If given an\n// object, create a map from the object's properties.\nOrderedMap.from = function(value) {\n if (value instanceof OrderedMap) return value\n var content = [];\n if (value) for (var prop in value) content.push(prop, value[prop]);\n return new OrderedMap(content)\n};\n\nexport default OrderedMap;\n", - "import OrderedMap from 'orderedmap';\n\nfunction findDiffStart(a, b, pos) {\n for (let i = 0;; i++) {\n if (i == a.childCount || i == b.childCount)\n return a.childCount == b.childCount ? null : pos;\n let childA = a.child(i), childB = b.child(i);\n if (childA == childB) {\n pos += childA.nodeSize;\n continue;\n }\n if (!childA.sameMarkup(childB))\n return pos;\n if (childA.isText && childA.text != childB.text) {\n let tA = childA.text, tB = childB.text, j = 0;\n for (; tA[j] == tB[j]; j++)\n pos++;\n if (j && j < tA.length && j < tB.length && surrogateHigh(tA.charCodeAt(j - 1)) && surrogateLow(tA.charCodeAt(j)))\n pos--;\n return pos;\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffStart(childA.content, childB.content, pos + 1);\n if (inner != null)\n return inner;\n }\n pos += childA.nodeSize;\n }\n}\nfunction findDiffEnd(a, b, posA, posB) {\n for (let iA = a.childCount, iB = b.childCount;;) {\n if (iA == 0 || iB == 0)\n return iA == iB ? null : { a: posA, b: posB };\n let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;\n if (childA == childB) {\n posA -= size;\n posB -= size;\n continue;\n }\n if (!childA.sameMarkup(childB))\n return { a: posA, b: posB };\n if (childA.isText && childA.text != childB.text) {\n let tA = childA.text, tB = childB.text, iA = tA.length, iB = tB.length;\n while (iA > 0 && iB > 0 && tA[iA - 1] == tB[iB - 1]) {\n iA--;\n iB--;\n posA--;\n posB--;\n }\n if (iA && iB && iA < tA.length && surrogateHigh(tA.charCodeAt(iA - 1)) && surrogateLow(tA.charCodeAt(iA))) {\n posA++;\n posB++;\n }\n return { a: posA, b: posB };\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);\n if (inner)\n return inner;\n }\n posA -= size;\n posB -= size;\n }\n}\nfunction surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }\nfunction surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }\n\n/**\nA fragment represents a node's collection of child nodes.\n\nLike nodes, fragments are persistent data structures, and you\nshould not mutate them or their content. Rather, you create new\ninstances whenever needed. The API tries to make this easy.\n*/\nclass Fragment {\n /**\n @internal\n */\n constructor(\n /**\n The child nodes in this fragment.\n */\n content, size) {\n this.content = content;\n this.size = size || 0;\n if (size == null)\n for (let i = 0; i < content.length; i++)\n this.size += content[i].nodeSize;\n }\n /**\n Invoke a callback for all descendant nodes between the given two\n positions (relative to start of this fragment). Doesn't descend\n into a node when the callback returns `false`.\n */\n nodesBetween(from, to, f, nodeStart = 0, parent) {\n for (let i = 0, pos = 0; pos < to; i++) {\n let child = this.content[i], end = pos + child.nodeSize;\n if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {\n let start = pos + 1;\n child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);\n }\n pos = end;\n }\n }\n /**\n Call the given callback for every descendant node. `pos` will be\n relative to the start of the fragment. The callback may return\n `false` to prevent traversal of a given node's children.\n */\n descendants(f) {\n this.nodesBetween(0, this.size, f);\n }\n /**\n Extract the text between `from` and `to`. See the same method on\n [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).\n */\n textBetween(from, to, blockSeparator, leafText) {\n let text = \"\", first = true;\n this.nodesBetween(from, to, (node, pos) => {\n let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos)\n : !node.isLeaf ? \"\"\n : leafText ? (typeof leafText === \"function\" ? leafText(node) : leafText)\n : node.type.spec.leafText ? node.type.spec.leafText(node)\n : \"\";\n if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {\n if (first)\n first = false;\n else\n text += blockSeparator;\n }\n text += nodeText;\n }, 0);\n return text;\n }\n /**\n Create a new fragment containing the combined content of this\n fragment and the other.\n */\n append(other) {\n if (!other.size)\n return this;\n if (!this.size)\n return other;\n let last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;\n if (last.isText && last.sameMarkup(first)) {\n content[content.length - 1] = last.withText(last.text + first.text);\n i = 1;\n }\n for (; i < other.content.length; i++)\n content.push(other.content[i]);\n return new Fragment(content, this.size + other.size);\n }\n /**\n Cut out the sub-fragment between the two given positions.\n */\n cut(from, to = this.size) {\n if (from == 0 && to == this.size)\n return this;\n let result = [], size = 0;\n if (to > from)\n for (let i = 0, pos = 0; pos < to; i++) {\n let child = this.content[i], end = pos + child.nodeSize;\n if (end > from) {\n if (pos < from || end > to) {\n if (child.isText)\n child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));\n else\n child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));\n }\n result.push(child);\n size += child.nodeSize;\n }\n pos = end;\n }\n return new Fragment(result, size);\n }\n /**\n @internal\n */\n cutByIndex(from, to) {\n if (from == to)\n return Fragment.empty;\n if (from == 0 && to == this.content.length)\n return this;\n return new Fragment(this.content.slice(from, to));\n }\n /**\n Create a new fragment in which the node at the given index is\n replaced by the given node.\n */\n replaceChild(index, node) {\n let current = this.content[index];\n if (current == node)\n return this;\n let copy = this.content.slice();\n let size = this.size + node.nodeSize - current.nodeSize;\n copy[index] = node;\n return new Fragment(copy, size);\n }\n /**\n Create a new fragment by prepending the given node to this\n fragment.\n */\n addToStart(node) {\n return new Fragment([node].concat(this.content), this.size + node.nodeSize);\n }\n /**\n Create a new fragment by appending the given node to this\n fragment.\n */\n addToEnd(node) {\n return new Fragment(this.content.concat(node), this.size + node.nodeSize);\n }\n /**\n Compare this fragment to another one.\n */\n eq(other) {\n if (this.content.length != other.content.length)\n return false;\n for (let i = 0; i < this.content.length; i++)\n if (!this.content[i].eq(other.content[i]))\n return false;\n return true;\n }\n /**\n The first child of the fragment, or `null` if it is empty.\n */\n get firstChild() { return this.content.length ? this.content[0] : null; }\n /**\n The last child of the fragment, or `null` if it is empty.\n */\n get lastChild() { return this.content.length ? this.content[this.content.length - 1] : null; }\n /**\n The number of child nodes in this fragment.\n */\n get childCount() { return this.content.length; }\n /**\n Get the child node at the given index. Raise an error when the\n index is out of range.\n */\n child(index) {\n let found = this.content[index];\n if (!found)\n throw new RangeError(\"Index \" + index + \" out of range for \" + this);\n return found;\n }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) {\n return this.content[index] || null;\n }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) {\n for (let i = 0, p = 0; i < this.content.length; i++) {\n let child = this.content[i];\n f(child, p, i);\n p += child.nodeSize;\n }\n }\n /**\n Find the first position at which this fragment and another\n fragment differ, or `null` if they are the same.\n */\n findDiffStart(other, pos = 0) {\n return findDiffStart(this, other, pos);\n }\n /**\n Find the first position, searching from the end, at which this\n fragment and the given fragment differ, or `null` if they are\n the same. Since this position will not be the same in both\n nodes, an object with two separate positions is returned.\n */\n findDiffEnd(other, pos = this.size, otherPos = other.size) {\n return findDiffEnd(this, other, pos, otherPos);\n }\n /**\n Find the index and inner offset corresponding to a given relative\n position in this fragment. The result object will be reused\n (overwritten) the next time the function is called. @internal\n */\n findIndex(pos) {\n if (pos == 0)\n return retIndex(0, pos);\n if (pos == this.size)\n return retIndex(this.content.length, pos);\n if (pos > this.size || pos < 0)\n throw new RangeError(`Position ${pos} outside of fragment (${this})`);\n for (let i = 0, curPos = 0;; i++) {\n let cur = this.child(i), end = curPos + cur.nodeSize;\n if (end >= pos) {\n if (end == pos)\n return retIndex(i + 1, end);\n return retIndex(i, curPos);\n }\n curPos = end;\n }\n }\n /**\n Return a debugging string that describes this fragment.\n */\n toString() { return \"<\" + this.toStringInner() + \">\"; }\n /**\n @internal\n */\n toStringInner() { return this.content.join(\", \"); }\n /**\n Create a JSON-serializeable representation of this fragment.\n */\n toJSON() {\n return this.content.length ? this.content.map(n => n.toJSON()) : null;\n }\n /**\n Deserialize a fragment from its JSON representation.\n */\n static fromJSON(schema, value) {\n if (!value)\n return Fragment.empty;\n if (!Array.isArray(value))\n throw new RangeError(\"Invalid input for Fragment.fromJSON\");\n return Fragment.fromArray(value.map(schema.nodeFromJSON));\n }\n /**\n Build a fragment from an array of nodes. Ensures that adjacent\n text nodes with the same marks are joined together.\n */\n static fromArray(array) {\n if (!array.length)\n return Fragment.empty;\n let joined, size = 0;\n for (let i = 0; i < array.length; i++) {\n let node = array[i];\n size += node.nodeSize;\n if (i && node.isText && array[i - 1].sameMarkup(node)) {\n if (!joined)\n joined = array.slice(0, i);\n joined[joined.length - 1] = node\n .withText(joined[joined.length - 1].text + node.text);\n }\n else if (joined) {\n joined.push(node);\n }\n }\n return new Fragment(joined || array, size);\n }\n /**\n Create a fragment from something that can be interpreted as a\n set of nodes. For `null`, it returns the empty fragment. For a\n fragment, the fragment itself. For a node or array of nodes, a\n fragment containing those nodes.\n */\n static from(nodes) {\n if (!nodes)\n return Fragment.empty;\n if (nodes instanceof Fragment)\n return nodes;\n if (Array.isArray(nodes))\n return this.fromArray(nodes);\n if (nodes.attrs)\n return new Fragment([nodes], nodes.nodeSize);\n throw new RangeError(\"Can not convert \" + nodes + \" to a Fragment\" +\n (nodes.nodesBetween ? \" (looks like multiple versions of prosemirror-model were loaded)\" : \"\"));\n }\n}\n/**\nAn empty fragment. Intended to be reused whenever a node doesn't\ncontain anything (rather than allocating a new empty fragment for\neach leaf node).\n*/\nFragment.empty = new Fragment([], 0);\nconst found = { index: 0, offset: 0 };\nfunction retIndex(index, offset) {\n found.index = index;\n found.offset = offset;\n return found;\n}\n\nfunction compareDeep(a, b) {\n if (a === b)\n return true;\n if (!(a && typeof a == \"object\") ||\n !(b && typeof b == \"object\"))\n return false;\n let array = Array.isArray(a);\n if (Array.isArray(b) != array)\n return false;\n if (array) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!compareDeep(a[i], b[i]))\n return false;\n }\n else {\n for (let p in a)\n if (!(p in b) || !compareDeep(a[p], b[p]))\n return false;\n for (let p in b)\n if (!(p in a))\n return false;\n }\n return true;\n}\n\n/**\nA mark is a piece of information that can be attached to a node,\nsuch as it being emphasized, in code font, or a link. It has a\ntype and optionally a set of attributes that provide further\ninformation (such as the target of the link). Marks are created\nthrough a `Schema`, which controls which types exist and which\nattributes they have.\n*/\nclass Mark {\n /**\n @internal\n */\n constructor(\n /**\n The type of this mark.\n */\n type, \n /**\n The attributes associated with this mark.\n */\n attrs) {\n this.type = type;\n this.attrs = attrs;\n }\n /**\n Given a set of marks, create a new set which contains this one as\n well, in the right position. If this mark is already in the set,\n the set itself is returned. If any marks that are set to be\n [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,\n those are replaced by this one.\n */\n addToSet(set) {\n let copy, placed = false;\n for (let i = 0; i < set.length; i++) {\n let other = set[i];\n if (this.eq(other))\n return set;\n if (this.type.excludes(other.type)) {\n if (!copy)\n copy = set.slice(0, i);\n }\n else if (other.type.excludes(this.type)) {\n return set;\n }\n else {\n if (!placed && other.type.rank > this.type.rank) {\n if (!copy)\n copy = set.slice(0, i);\n copy.push(this);\n placed = true;\n }\n if (copy)\n copy.push(other);\n }\n }\n if (!copy)\n copy = set.slice();\n if (!placed)\n copy.push(this);\n return copy;\n }\n /**\n Remove this mark from the given set, returning a new set. If this\n mark is not in the set, the set itself is returned.\n */\n removeFromSet(set) {\n for (let i = 0; i < set.length; i++)\n if (this.eq(set[i]))\n return set.slice(0, i).concat(set.slice(i + 1));\n return set;\n }\n /**\n Test whether this mark is in the given set of marks.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++)\n if (this.eq(set[i]))\n return true;\n return false;\n }\n /**\n Test whether this mark has the same type and attributes as\n another mark.\n */\n eq(other) {\n return this == other ||\n (this.type == other.type && compareDeep(this.attrs, other.attrs));\n }\n /**\n Convert this mark to a JSON-serializeable representation.\n */\n toJSON() {\n let obj = { type: this.type.name };\n for (let _ in this.attrs) {\n obj.attrs = this.attrs;\n break;\n }\n return obj;\n }\n /**\n Deserialize a mark from JSON.\n */\n static fromJSON(schema, json) {\n if (!json)\n throw new RangeError(\"Invalid input for Mark.fromJSON\");\n let type = schema.marks[json.type];\n if (!type)\n throw new RangeError(`There is no mark type ${json.type} in this schema`);\n let mark = type.create(json.attrs);\n return mark;\n }\n /**\n Test whether two sets of marks are identical.\n */\n static sameSet(a, b) {\n if (a == b)\n return true;\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].eq(b[i]))\n return false;\n return true;\n }\n /**\n Create a properly sorted mark set from null, a single mark, or an\n unsorted array of marks.\n */\n static setFrom(marks) {\n if (!marks || Array.isArray(marks) && marks.length == 0)\n return Mark.none;\n if (marks instanceof Mark)\n return [marks];\n let copy = marks.slice();\n copy.sort((a, b) => a.type.rank - b.type.rank);\n return copy;\n }\n}\n/**\nThe empty set of marks.\n*/\nMark.none = [];\n\n/**\nError type raised by [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) when\ngiven an invalid replacement.\n*/\nclass ReplaceError extends Error {\n}\n/**\nA slice represents a piece cut out of a larger document. It\nstores not only a fragment, but also the depth up to which nodes on\nboth side are ‘open’ (cut through).\n*/\nclass Slice {\n /**\n Create a slice. When specifying a non-zero open depth, you must\n make sure that there are nodes of at least that depth at the\n appropriate side of the fragment—i.e. if the fragment is an\n empty paragraph node, `openStart` and `openEnd` can't be greater\n than 1.\n \n It is not necessary for the content of open nodes to conform to\n the schema's content constraints, though it should be a valid\n start/end/middle for such a node, depending on which sides are\n open.\n */\n constructor(\n /**\n The slice's content.\n */\n content, \n /**\n The open depth at the start of the fragment.\n */\n openStart, \n /**\n The open depth at the end.\n */\n openEnd) {\n this.content = content;\n this.openStart = openStart;\n this.openEnd = openEnd;\n }\n /**\n The size this slice would add when inserted into a document.\n */\n get size() {\n return this.content.size - this.openStart - this.openEnd;\n }\n /**\n @internal\n */\n insertAt(pos, fragment) {\n let content = insertInto(this.content, pos + this.openStart, fragment, this.openStart + 1, this.openEnd + 1);\n return content && new Slice(content, this.openStart, this.openEnd);\n }\n /**\n @internal\n */\n removeBetween(from, to) {\n return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);\n }\n /**\n Tests whether this slice is equal to another slice.\n */\n eq(other) {\n return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;\n }\n /**\n @internal\n */\n toString() {\n return this.content + \"(\" + this.openStart + \",\" + this.openEnd + \")\";\n }\n /**\n Convert a slice to a JSON-serializable representation.\n */\n toJSON() {\n if (!this.content.size)\n return null;\n let json = { content: this.content.toJSON() };\n if (this.openStart > 0)\n json.openStart = this.openStart;\n if (this.openEnd > 0)\n json.openEnd = this.openEnd;\n return json;\n }\n /**\n Deserialize a slice from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json)\n return Slice.empty;\n let openStart = json.openStart || 0, openEnd = json.openEnd || 0;\n if (typeof openStart != \"number\" || typeof openEnd != \"number\")\n throw new RangeError(\"Invalid input for Slice.fromJSON\");\n return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);\n }\n /**\n Create a slice from a fragment by taking the maximum possible\n open value on both side of the fragment.\n */\n static maxOpen(fragment, openIsolating = true) {\n let openStart = 0, openEnd = 0;\n for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)\n openStart++;\n for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)\n openEnd++;\n return new Slice(fragment, openStart, openEnd);\n }\n}\n/**\nThe empty slice.\n*/\nSlice.empty = new Slice(Fragment.empty, 0, 0);\nfunction removeRange(content, from, to) {\n let { index, offset } = content.findIndex(from), child = content.maybeChild(index);\n let { index: indexTo, offset: offsetTo } = content.findIndex(to);\n if (offset == from || child.isText) {\n if (offsetTo != to && !content.child(indexTo).isText)\n throw new RangeError(\"Removing non-flat range\");\n return content.cut(0, from).append(content.cut(to));\n }\n if (index != indexTo)\n throw new RangeError(\"Removing non-flat range\");\n return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));\n}\nfunction insertInto(content, dist, insert, openStart, openEnd, parent) {\n let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);\n if (offset == dist || child.isText) {\n if (parent && openStart <= 0 && openEnd <= 0 && !parent.canReplace(index, index, insert))\n return null;\n return content.cut(0, dist).append(insert).append(content.cut(dist));\n }\n let inner = insertInto(child.content, dist - offset - 1, insert, index == 0 ? openStart - 1 : 0, index == content.childCount - 1 ? openEnd - 1 : 0, child);\n return inner && content.replaceChild(index, child.copy(inner));\n}\nfunction replace($from, $to, slice) {\n if (slice.openStart > $from.depth)\n throw new ReplaceError(\"Inserted content deeper than insertion position\");\n if ($from.depth - slice.openStart != $to.depth - slice.openEnd)\n throw new ReplaceError(\"Inconsistent open depths\");\n return replaceOuter($from, $to, slice, 0);\n}\nfunction replaceOuter($from, $to, slice, depth) {\n let index = $from.index(depth), node = $from.node(depth);\n if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {\n let inner = replaceOuter($from, $to, slice, depth + 1);\n return node.copy(node.content.replaceChild(index, inner));\n }\n else if (!slice.content.size) {\n return close(node, replaceTwoWay($from, $to, depth));\n }\n else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case\n let parent = $from.parent, content = parent.content;\n return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));\n }\n else {\n let { start, end } = prepareSliceForReplace(slice, $from);\n return close(node, replaceThreeWay($from, start, end, $to, depth));\n }\n}\nfunction checkJoin(main, sub) {\n if (!sub.type.compatibleContent(main.type))\n throw new ReplaceError(\"Cannot join \" + sub.type.name + \" onto \" + main.type.name);\n}\nfunction joinable($before, $after, depth) {\n let node = $before.node(depth);\n checkJoin(node, $after.node(depth));\n return node;\n}\nfunction addNode(child, target) {\n let last = target.length - 1;\n if (last >= 0 && child.isText && child.sameMarkup(target[last]))\n target[last] = child.withText(target[last].text + child.text);\n else\n target.push(child);\n}\nfunction addRange($start, $end, depth, target) {\n let node = ($end || $start).node(depth);\n let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;\n if ($start) {\n startIndex = $start.index(depth);\n if ($start.depth > depth) {\n startIndex++;\n }\n else if ($start.textOffset) {\n addNode($start.nodeAfter, target);\n startIndex++;\n }\n }\n for (let i = startIndex; i < endIndex; i++)\n addNode(node.child(i), target);\n if ($end && $end.depth == depth && $end.textOffset)\n addNode($end.nodeBefore, target);\n}\nfunction close(node, content) {\n if (!node.type.validContent(content))\n throw new ReplaceError(\"Invalid content for node \" + node.type.name);\n return node.copy(content);\n}\nfunction replaceThreeWay($from, $start, $end, $to, depth) {\n let openStart = $from.depth > depth && joinable($from, $start, depth + 1);\n let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);\n let content = [];\n addRange(null, $from, depth, content);\n if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {\n checkJoin(openStart, openEnd);\n addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);\n }\n else {\n if (openStart)\n addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);\n addRange($start, $end, depth, content);\n if (openEnd)\n addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content);\n}\nfunction replaceTwoWay($from, $to, depth) {\n let content = [];\n addRange(null, $from, depth, content);\n if ($from.depth > depth) {\n let type = joinable($from, $to, depth + 1);\n addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content);\n}\nfunction prepareSliceForReplace(slice, $along) {\n let extra = $along.depth - slice.openStart, parent = $along.node(extra);\n let node = parent.copy(slice.content);\n for (let i = extra - 1; i >= 0; i--)\n node = $along.node(i).copy(Fragment.from(node));\n return { start: node.resolveNoCache(slice.openStart + extra),\n end: node.resolveNoCache(node.content.size - slice.openEnd - extra) };\n}\n\n/**\nYou can [_resolve_](https://prosemirror.net/docs/ref/#model.Node.resolve) a position to get more\ninformation about it. Objects of this class represent such a\nresolved position, providing various pieces of context\ninformation, and some helper methods.\n\nThroughout this interface, methods that take an optional `depth`\nparameter will interpret undefined as `this.depth` and negative\nnumbers as `this.depth + value`.\n*/\nclass ResolvedPos {\n /**\n @internal\n */\n constructor(\n /**\n The position that was resolved.\n */\n pos, \n /**\n @internal\n */\n path, \n /**\n The offset this position has into its parent node.\n */\n parentOffset) {\n this.pos = pos;\n this.path = path;\n this.parentOffset = parentOffset;\n this.depth = path.length / 3 - 1;\n }\n /**\n @internal\n */\n resolveDepth(val) {\n if (val == null)\n return this.depth;\n if (val < 0)\n return this.depth + val;\n return val;\n }\n /**\n The parent node that the position points into. Note that even if\n a position points into a text node, that node is not considered\n the parent—text nodes are ‘flat’ in this model, and have no content.\n */\n get parent() { return this.node(this.depth); }\n /**\n The root node in which the position was resolved.\n */\n get doc() { return this.node(0); }\n /**\n The ancestor node at the given level. `p.node(p.depth)` is the\n same as `p.parent`.\n */\n node(depth) { return this.path[this.resolveDepth(depth) * 3]; }\n /**\n The index into the ancestor at the given level. If this points\n at the 3rd node in the 2nd paragraph on the top level, for\n example, `p.index(0)` is 1 and `p.index(1)` is 2.\n */\n index(depth) { return this.path[this.resolveDepth(depth) * 3 + 1]; }\n /**\n The index pointing after this position into the ancestor at the\n given level.\n */\n indexAfter(depth) {\n depth = this.resolveDepth(depth);\n return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);\n }\n /**\n The (absolute) position at the start of the node at the given\n level.\n */\n start(depth) {\n depth = this.resolveDepth(depth);\n return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n }\n /**\n The (absolute) position at the end of the node at the given\n level.\n */\n end(depth) {\n depth = this.resolveDepth(depth);\n return this.start(depth) + this.node(depth).content.size;\n }\n /**\n The (absolute) position directly before the wrapping node at the\n given level, or, when `depth` is `this.depth + 1`, the original\n position.\n */\n before(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n throw new RangeError(\"There is no position before the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];\n }\n /**\n The (absolute) position directly after the wrapping node at the\n given level, or the original position when `depth` is `this.depth + 1`.\n */\n after(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n throw new RangeError(\"There is no position after the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;\n }\n /**\n When this position points into a text node, this returns the\n distance between the position and the start of the text node.\n Will be zero for positions that point between nodes.\n */\n get textOffset() { return this.pos - this.path[this.path.length - 1]; }\n /**\n Get the node directly after the position, if any. If the position\n points into a text node, only the part of that node after the\n position is returned.\n */\n get nodeAfter() {\n let parent = this.parent, index = this.index(this.depth);\n if (index == parent.childCount)\n return null;\n let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);\n return dOff ? parent.child(index).cut(dOff) : child;\n }\n /**\n Get the node directly before the position, if any. If the\n position points into a text node, only the part of that node\n before the position is returned.\n */\n get nodeBefore() {\n let index = this.index(this.depth);\n let dOff = this.pos - this.path[this.path.length - 1];\n if (dOff)\n return this.parent.child(index).cut(0, dOff);\n return index == 0 ? null : this.parent.child(index - 1);\n }\n /**\n Get the position at the given index in the parent node at the\n given depth (which defaults to `this.depth`).\n */\n posAtIndex(index, depth) {\n depth = this.resolveDepth(depth);\n let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n for (let i = 0; i < index; i++)\n pos += node.child(i).nodeSize;\n return pos;\n }\n /**\n Get the marks at this position, factoring in the surrounding\n marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the\n position is at the start of a non-empty node, the marks of the\n node after it (if any) are returned.\n */\n marks() {\n let parent = this.parent, index = this.index();\n // In an empty parent, return the empty array\n if (parent.content.size == 0)\n return Mark.none;\n // When inside a text node, just return the text node's marks\n if (this.textOffset)\n return parent.child(index).marks;\n let main = parent.maybeChild(index - 1), other = parent.maybeChild(index);\n // If the `after` flag is true of there is no node before, make\n // the node after this position the main reference.\n if (!main) {\n let tmp = main;\n main = other;\n other = tmp;\n }\n // Use all marks in the main node, except those that have\n // `inclusive` set to false and are not present in the other node.\n let marks = main.marks;\n for (var i = 0; i < marks.length; i++)\n if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks)))\n marks = marks[i--].removeFromSet(marks);\n return marks;\n }\n /**\n Get the marks after the current position, if any, except those\n that are non-inclusive and not present at position `$end`. This\n is mostly useful for getting the set of marks to preserve after a\n deletion. Will return `null` if this position is at the end of\n its parent node or its parent node isn't a textblock (in which\n case no marks should be preserved).\n */\n marksAcross($end) {\n let after = this.parent.maybeChild(this.index());\n if (!after || !after.isInline)\n return null;\n let marks = after.marks, next = $end.parent.maybeChild($end.index());\n for (var i = 0; i < marks.length; i++)\n if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))\n marks = marks[i--].removeFromSet(marks);\n return marks;\n }\n /**\n The depth up to which this position and the given (non-resolved)\n position share the same parent nodes.\n */\n sharedDepth(pos) {\n for (let depth = this.depth; depth > 0; depth--)\n if (this.start(depth) <= pos && this.end(depth) >= pos)\n return depth;\n return 0;\n }\n /**\n Returns a range based on the place where this position and the\n given position diverge around block content. If both point into\n the same textblock, for example, a range around that textblock\n will be returned. If they point into different blocks, the range\n around those blocks in their shared ancestor is returned. You can\n pass in an optional predicate that will be called with a parent\n node to see if a range into that parent is acceptable.\n */\n blockRange(other = this, pred) {\n if (other.pos < this.pos)\n return other.blockRange(this);\n for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)\n if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))\n return new NodeRange(this, other, d);\n return null;\n }\n /**\n Query whether the given position shares the same parent node.\n */\n sameParent(other) {\n return this.pos - this.parentOffset == other.pos - other.parentOffset;\n }\n /**\n Return the greater of this and the given position.\n */\n max(other) {\n return other.pos > this.pos ? other : this;\n }\n /**\n Return the smaller of this and the given position.\n */\n min(other) {\n return other.pos < this.pos ? other : this;\n }\n /**\n @internal\n */\n toString() {\n let str = \"\";\n for (let i = 1; i <= this.depth; i++)\n str += (str ? \"/\" : \"\") + this.node(i).type.name + \"_\" + this.index(i - 1);\n return str + \":\" + this.parentOffset;\n }\n /**\n @internal\n */\n static resolve(doc, pos) {\n if (!(pos >= 0 && pos <= doc.content.size))\n throw new RangeError(\"Position \" + pos + \" out of range\");\n let path = [];\n let start = 0, parentOffset = pos;\n for (let node = doc;;) {\n let { index, offset } = node.content.findIndex(parentOffset);\n let rem = parentOffset - offset;\n path.push(node, index, start + offset);\n if (!rem)\n break;\n node = node.child(index);\n if (node.isText)\n break;\n parentOffset = rem - 1;\n start += offset + 1;\n }\n return new ResolvedPos(pos, path, parentOffset);\n }\n /**\n @internal\n */\n static resolveCached(doc, pos) {\n let cache = resolveCache.get(doc);\n if (cache) {\n for (let i = 0; i < cache.elts.length; i++) {\n let elt = cache.elts[i];\n if (elt.pos == pos)\n return elt;\n }\n }\n else {\n resolveCache.set(doc, cache = new ResolveCache);\n }\n let result = cache.elts[cache.i] = ResolvedPos.resolve(doc, pos);\n cache.i = (cache.i + 1) % resolveCacheSize;\n return result;\n }\n}\nclass ResolveCache {\n constructor() {\n this.elts = [];\n this.i = 0;\n }\n}\nconst resolveCacheSize = 12, resolveCache = new WeakMap();\n/**\nRepresents a flat range of content, i.e. one that starts and\nends in the same node.\n*/\nclass NodeRange {\n /**\n Construct a node range. `$from` and `$to` should point into the\n same node until at least the given `depth`, since a node range\n denotes an adjacent set of nodes in a single parent node.\n */\n constructor(\n /**\n A resolved position along the start of the content. May have a\n `depth` greater than this object's `depth` property, since\n these are the positions that were used to compute the range,\n not re-resolved positions directly at its boundaries.\n */\n $from, \n /**\n A position along the end of the content. See\n caveat for [`$from`](https://prosemirror.net/docs/ref/#model.NodeRange.$from).\n */\n $to, \n /**\n The depth of the node that this range points into.\n */\n depth) {\n this.$from = $from;\n this.$to = $to;\n this.depth = depth;\n }\n /**\n The position at the start of the range.\n */\n get start() { return this.$from.before(this.depth + 1); }\n /**\n The position at the end of the range.\n */\n get end() { return this.$to.after(this.depth + 1); }\n /**\n The parent node that the range points into.\n */\n get parent() { return this.$from.node(this.depth); }\n /**\n The start index of the range in the parent node.\n */\n get startIndex() { return this.$from.index(this.depth); }\n /**\n The end index of the range in the parent node.\n */\n get endIndex() { return this.$to.indexAfter(this.depth); }\n}\n\nconst emptyAttrs = Object.create(null);\n/**\nThis class represents a node in the tree that makes up a\nProseMirror document. So a document is an instance of `Node`, with\nchildren that are also instances of `Node`.\n\nNodes are persistent data structures. Instead of changing them, you\ncreate new ones with the content you want. Old ones keep pointing\nat the old document shape. This is made cheaper by sharing\nstructure between the old and new data as much as possible, which a\ntree shape like this (without back pointers) makes easy.\n\n**Do not** directly mutate the properties of a `Node` object. See\n[the guide](https://prosemirror.net/docs/guide/#doc) for more information.\n*/\nclass Node {\n /**\n @internal\n */\n constructor(\n /**\n The type of node that this is.\n */\n type, \n /**\n An object mapping attribute names to values. The kind of\n attributes allowed and required are\n [determined](https://prosemirror.net/docs/ref/#model.NodeSpec.attrs) by the node type.\n */\n attrs, \n // A fragment holding the node's children.\n content, \n /**\n The marks (things like whether it is emphasized or part of a\n link) applied to this node.\n */\n marks = Mark.none) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.content = content || Fragment.empty;\n }\n /**\n The array of this node's child nodes.\n */\n get children() { return this.content.content; }\n /**\n The size of this node, as defined by the integer-based [indexing\n scheme](https://prosemirror.net/docs/guide/#doc.indexing). For text nodes, this is the\n amount of characters. For other leaf nodes, it is one. For\n non-leaf nodes, it is the size of the content plus two (the\n start and end token).\n */\n get nodeSize() { return this.isLeaf ? 1 : 2 + this.content.size; }\n /**\n The number of children that the node has.\n */\n get childCount() { return this.content.childCount; }\n /**\n Get the child node at the given index. Raises an error when the\n index is out of range.\n */\n child(index) { return this.content.child(index); }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) { return this.content.maybeChild(index); }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) { this.content.forEach(f); }\n /**\n Invoke a callback for all descendant nodes recursively overlapping\n the given two positions that are relative to start of this\n node's content. This includes all ancestors of the nodes\n containing the two positions. The callback is invoked with the\n node, its position relative to the original node (method receiver),\n its parent node, and its child index. When the callback returns\n false for a given node, that node's children will not be\n recursed over. The last parameter can be used to specify a\n starting position to count from.\n */\n nodesBetween(from, to, f, startPos = 0) {\n this.content.nodesBetween(from, to, f, startPos, this);\n }\n /**\n Call the given callback for every descendant node. Doesn't\n descend into a node when the callback returns `false`.\n */\n descendants(f) {\n this.nodesBetween(0, this.content.size, f);\n }\n /**\n Concatenates all the text nodes found in this fragment and its\n children.\n */\n get textContent() {\n return (this.isLeaf && this.type.spec.leafText)\n ? this.type.spec.leafText(this)\n : this.textBetween(0, this.content.size, \"\");\n }\n /**\n Get all text between positions `from` and `to`. When\n `blockSeparator` is given, it will be inserted to separate text\n from different block nodes. If `leafText` is given, it'll be\n inserted for every non-text leaf node encountered, otherwise\n [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used.\n */\n textBetween(from, to, blockSeparator, leafText) {\n return this.content.textBetween(from, to, blockSeparator, leafText);\n }\n /**\n Returns this node's first child, or `null` if there are no\n children.\n */\n get firstChild() { return this.content.firstChild; }\n /**\n Returns this node's last child, or `null` if there are no\n children.\n */\n get lastChild() { return this.content.lastChild; }\n /**\n Test whether two nodes represent the same piece of document.\n */\n eq(other) {\n return this == other || (this.sameMarkup(other) && this.content.eq(other.content));\n }\n /**\n Compare the markup (type, attributes, and marks) of this node to\n those of another. Returns `true` if both have the same markup.\n */\n sameMarkup(other) {\n return this.hasMarkup(other.type, other.attrs, other.marks);\n }\n /**\n Check whether this node's markup correspond to the given type,\n attributes, and marks.\n */\n hasMarkup(type, attrs, marks) {\n return this.type == type &&\n compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) &&\n Mark.sameSet(this.marks, marks || Mark.none);\n }\n /**\n Create a new node with the same markup as this node, containing\n the given content (or empty, if no content is given).\n */\n copy(content = null) {\n if (content == this.content)\n return this;\n return new Node(this.type, this.attrs, content, this.marks);\n }\n /**\n Create a copy of this node, with the given set of marks instead\n of the node's own marks.\n */\n mark(marks) {\n return marks == this.marks ? this : new Node(this.type, this.attrs, this.content, marks);\n }\n /**\n Create a copy of this node with only the content between the\n given positions. If `to` is not given, it defaults to the end of\n the node.\n */\n cut(from, to = this.content.size) {\n if (from == 0 && to == this.content.size)\n return this;\n return this.copy(this.content.cut(from, to));\n }\n /**\n Cut out the part of the document between the given positions, and\n return it as a `Slice` object.\n */\n slice(from, to = this.content.size, includeParents = false) {\n if (from == to)\n return Slice.empty;\n let $from = this.resolve(from), $to = this.resolve(to);\n let depth = includeParents ? 0 : $from.sharedDepth(to);\n let start = $from.start(depth), node = $from.node(depth);\n let content = node.content.cut($from.pos - start, $to.pos - start);\n return new Slice(content, $from.depth - depth, $to.depth - depth);\n }\n /**\n Replace the part of the document between the given positions with\n the given slice. The slice must 'fit', meaning its open sides\n must be able to connect to the surrounding content, and its\n content nodes must be valid children for the node they are placed\n into. If any of this is violated, an error of type\n [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.\n */\n replace(from, to, slice) {\n return replace(this.resolve(from), this.resolve(to), slice);\n }\n /**\n Find the node directly after the given position.\n */\n nodeAt(pos) {\n for (let node = this;;) {\n let { index, offset } = node.content.findIndex(pos);\n node = node.maybeChild(index);\n if (!node)\n return null;\n if (offset == pos || node.isText)\n return node;\n pos -= offset + 1;\n }\n }\n /**\n Find the (direct) child node after the given offset, if any,\n and return it along with its index and offset relative to this\n node.\n */\n childAfter(pos) {\n let { index, offset } = this.content.findIndex(pos);\n return { node: this.content.maybeChild(index), index, offset };\n }\n /**\n Find the (direct) child node before the given offset, if any,\n and return it along with its index and offset relative to this\n node.\n */\n childBefore(pos) {\n if (pos == 0)\n return { node: null, index: 0, offset: 0 };\n let { index, offset } = this.content.findIndex(pos);\n if (offset < pos)\n return { node: this.content.child(index), index, offset };\n let node = this.content.child(index - 1);\n return { node, index: index - 1, offset: offset - node.nodeSize };\n }\n /**\n Resolve the given position in the document, returning an\n [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.\n */\n resolve(pos) { return ResolvedPos.resolveCached(this, pos); }\n /**\n @internal\n */\n resolveNoCache(pos) { return ResolvedPos.resolve(this, pos); }\n /**\n Test whether a given mark or mark type occurs in this document\n between the two given positions.\n */\n rangeHasMark(from, to, type) {\n let found = false;\n if (to > from)\n this.nodesBetween(from, to, node => {\n if (type.isInSet(node.marks))\n found = true;\n return !found;\n });\n return found;\n }\n /**\n True when this is a block (non-inline node)\n */\n get isBlock() { return this.type.isBlock; }\n /**\n True when this is a textblock node, a block node with inline\n content.\n */\n get isTextblock() { return this.type.isTextblock; }\n /**\n True when this node allows inline content.\n */\n get inlineContent() { return this.type.inlineContent; }\n /**\n True when this is an inline node (a text node or a node that can\n appear among text).\n */\n get isInline() { return this.type.isInline; }\n /**\n True when this is a text node.\n */\n get isText() { return this.type.isText; }\n /**\n True when this is a leaf node.\n */\n get isLeaf() { return this.type.isLeaf; }\n /**\n True when this is an atom, i.e. when it does not have directly\n editable content. This is usually the same as `isLeaf`, but can\n be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)\n on a node's spec (typically used when the node is displayed as\n an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).\n */\n get isAtom() { return this.type.isAtom; }\n /**\n Return a string representation of this node for debugging\n purposes.\n */\n toString() {\n if (this.type.spec.toDebugString)\n return this.type.spec.toDebugString(this);\n let name = this.type.name;\n if (this.content.size)\n name += \"(\" + this.content.toStringInner() + \")\";\n return wrapMarks(this.marks, name);\n }\n /**\n Get the content match in this node at the given index.\n */\n contentMatchAt(index) {\n let match = this.type.contentMatch.matchFragment(this.content, 0, index);\n if (!match)\n throw new Error(\"Called contentMatchAt on a node with invalid content\");\n return match;\n }\n /**\n Test whether replacing the range between `from` and `to` (by\n child index) with the given replacement fragment (which defaults\n to the empty fragment) would leave the node's content valid. You\n can optionally pass `start` and `end` indices into the\n replacement fragment.\n */\n canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {\n let one = this.contentMatchAt(from).matchFragment(replacement, start, end);\n let two = one && one.matchFragment(this.content, to);\n if (!two || !two.validEnd)\n return false;\n for (let i = start; i < end; i++)\n if (!this.type.allowsMarks(replacement.child(i).marks))\n return false;\n return true;\n }\n /**\n Test whether replacing the range `from` to `to` (by index) with\n a node of the given type would leave the node's content valid.\n */\n canReplaceWith(from, to, type, marks) {\n if (marks && !this.type.allowsMarks(marks))\n return false;\n let start = this.contentMatchAt(from).matchType(type);\n let end = start && start.matchFragment(this.content, to);\n return end ? end.validEnd : false;\n }\n /**\n Test whether the given node's content could be appended to this\n node. If that node is empty, this will only return true if there\n is at least one node type that can appear in both nodes (to avoid\n merging completely incompatible nodes).\n */\n canAppend(other) {\n if (other.content.size)\n return this.canReplace(this.childCount, this.childCount, other.content);\n else\n return this.type.compatibleContent(other.type);\n }\n /**\n Check whether this node and its descendants conform to the\n schema, and raise an exception when they do not.\n */\n check() {\n this.type.checkContent(this.content);\n checkAttrs(this.type.attrs, this.attrs, \"node\", this.type.name);\n let copy = Mark.none;\n for (let i = 0; i < this.marks.length; i++) {\n let mark = this.marks[i];\n checkAttrs(mark.type.attrs, mark.attrs, \"mark\", mark.type.name);\n copy = mark.addToSet(copy);\n }\n if (!Mark.sameSet(copy, this.marks))\n throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(m => m.type.name)}`);\n this.content.forEach(node => node.check());\n }\n /**\n Return a JSON-serializeable representation of this node.\n */\n toJSON() {\n let obj = { type: this.type.name };\n for (let _ in this.attrs) {\n obj.attrs = this.attrs;\n break;\n }\n if (this.content.size)\n obj.content = this.content.toJSON();\n if (this.marks.length)\n obj.marks = this.marks.map(n => n.toJSON());\n return obj;\n }\n /**\n Deserialize a node from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json)\n throw new RangeError(\"Invalid input for Node.fromJSON\");\n let marks = undefined;\n if (json.marks) {\n if (!Array.isArray(json.marks))\n throw new RangeError(\"Invalid mark data for Node.fromJSON\");\n marks = json.marks.map(schema.markFromJSON);\n }\n if (json.type == \"text\") {\n if (typeof json.text != \"string\")\n throw new RangeError(\"Invalid text node in JSON\");\n return schema.text(json.text, marks);\n }\n let content = Fragment.fromJSON(schema, json.content);\n let node = schema.nodeType(json.type).create(json.attrs, content, marks);\n return node;\n }\n}\nNode.prototype.text = undefined;\nclass TextNode extends Node {\n /**\n @internal\n */\n constructor(type, attrs, content, marks) {\n super(type, attrs, null, marks);\n if (!content)\n throw new RangeError(\"Empty text nodes are not allowed\");\n this.text = content;\n }\n toString() {\n if (this.type.spec.toDebugString)\n return this.type.spec.toDebugString(this);\n return wrapMarks(this.marks, JSON.stringify(this.text));\n }\n get textContent() { return this.text; }\n textBetween(from, to) { return this.text.slice(from, to); }\n get nodeSize() { return this.text.length; }\n mark(marks) {\n return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks);\n }\n withText(text) {\n if (text == this.text)\n return this;\n return new TextNode(this.type, this.attrs, text, this.marks);\n }\n cut(from = 0, to = this.text.length) {\n if (from == 0 && to == this.text.length)\n return this;\n return this.withText(this.text.slice(from, to));\n }\n eq(other) {\n return this.sameMarkup(other) && this.text == other.text;\n }\n toJSON() {\n let base = super.toJSON();\n base.text = this.text;\n return base;\n }\n}\nfunction wrapMarks(marks, str) {\n for (let i = marks.length - 1; i >= 0; i--)\n str = marks[i].type.name + \"(\" + str + \")\";\n return str;\n}\nfunction checkAttrs(attrs, values, type, name) {\n for (let attr in values)\n if (!(attr in attrs))\n throw new RangeError(`Unsupported attribute ${attr} for ${type} of type ${name}`);\n for (let attr in attrs) {\n if (attrs[attr].validate)\n attrs[attr].validate(values[attr]);\n }\n}\n\n/**\nInstances of this class represent a match state of a node type's\n[content expression](https://prosemirror.net/docs/ref/#model.NodeSpec.content), and can be used to\nfind out whether further content matches here, and whether a given\nposition is a valid end of the node.\n*/\nclass ContentMatch {\n /**\n @internal\n */\n constructor(\n /**\n True when this match state represents a valid end of the node.\n */\n validEnd) {\n this.validEnd = validEnd;\n /**\n @internal\n */\n this.next = [];\n /**\n @internal\n */\n this.wrapCache = [];\n }\n /**\n @internal\n */\n static parse(string, nodeTypes) {\n let stream = new TokenStream(string, nodeTypes);\n if (stream.next == null)\n return ContentMatch.empty;\n let expr = parseExpr(stream);\n if (stream.next)\n stream.err(\"Unexpected trailing text\");\n let match = dfa(nfa(expr));\n checkForDeadEnds(match, stream);\n return match;\n }\n /**\n Match a node type, returning a match after that node if\n successful.\n */\n matchType(type) {\n for (let i = 0; i < this.next.length; i++)\n if (this.next[i].type == type)\n return this.next[i].next;\n return null;\n }\n /**\n Try to match a fragment. Returns the resulting match when\n successful.\n */\n matchFragment(frag, start = 0, end = frag.childCount) {\n let cur = this;\n for (let i = start; cur && i < end; i++)\n cur = cur.matchType(frag.child(i).type);\n return cur;\n }\n /**\n @internal\n */\n get inlineContent() {\n return this.next.length != 0 && this.next[0].type.isInline;\n }\n /**\n Get the first matching node type at this match position that can\n be generated.\n */\n get defaultType() {\n for (let i = 0; i < this.next.length; i++) {\n let { type } = this.next[i];\n if (!(type.isText || type.hasRequiredAttrs()))\n return type;\n }\n return null;\n }\n /**\n @internal\n */\n compatible(other) {\n for (let i = 0; i < this.next.length; i++)\n for (let j = 0; j < other.next.length; j++)\n if (this.next[i].type == other.next[j].type)\n return true;\n return false;\n }\n /**\n Try to match the given fragment, and if that fails, see if it can\n be made to match by inserting nodes in front of it. When\n successful, return a fragment of inserted nodes (which may be\n empty if nothing had to be inserted). When `toEnd` is true, only\n return a fragment if the resulting match goes to the end of the\n content expression.\n */\n fillBefore(after, toEnd = false, startIndex = 0) {\n let seen = [this];\n function search(match, types) {\n let finished = match.matchFragment(after, startIndex);\n if (finished && (!toEnd || finished.validEnd))\n return Fragment.from(types.map(tp => tp.createAndFill()));\n for (let i = 0; i < match.next.length; i++) {\n let { type, next } = match.next[i];\n if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {\n seen.push(next);\n let found = search(next, types.concat(type));\n if (found)\n return found;\n }\n }\n return null;\n }\n return search(this, []);\n }\n /**\n Find a set of wrapping node types that would allow a node of the\n given type to appear at this position. The result may be empty\n (when it fits directly) and will be null when no such wrapping\n exists.\n */\n findWrapping(target) {\n for (let i = 0; i < this.wrapCache.length; i += 2)\n if (this.wrapCache[i] == target)\n return this.wrapCache[i + 1];\n let computed = this.computeWrapping(target);\n this.wrapCache.push(target, computed);\n return computed;\n }\n /**\n @internal\n */\n computeWrapping(target) {\n let seen = Object.create(null), active = [{ match: this, type: null, via: null }];\n while (active.length) {\n let current = active.shift(), match = current.match;\n if (match.matchType(target)) {\n let result = [];\n for (let obj = current; obj.type; obj = obj.via)\n result.push(obj.type);\n return result.reverse();\n }\n for (let i = 0; i < match.next.length; i++) {\n let { type, next } = match.next[i];\n if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {\n active.push({ match: type.contentMatch, type, via: current });\n seen[type.name] = true;\n }\n }\n }\n return null;\n }\n /**\n The number of outgoing edges this node has in the finite\n automaton that describes the content expression.\n */\n get edgeCount() {\n return this.next.length;\n }\n /**\n Get the _n_​th outgoing edge from this node in the finite\n automaton that describes the content expression.\n */\n edge(n) {\n if (n >= this.next.length)\n throw new RangeError(`There's no ${n}th edge in this content match`);\n return this.next[n];\n }\n /**\n @internal\n */\n toString() {\n let seen = [];\n function scan(m) {\n seen.push(m);\n for (let i = 0; i < m.next.length; i++)\n if (seen.indexOf(m.next[i].next) == -1)\n scan(m.next[i].next);\n }\n scan(this);\n return seen.map((m, i) => {\n let out = i + (m.validEnd ? \"*\" : \" \") + \" \";\n for (let i = 0; i < m.next.length; i++)\n out += (i ? \", \" : \"\") + m.next[i].type.name + \"->\" + seen.indexOf(m.next[i].next);\n return out;\n }).join(\"\\n\");\n }\n}\n/**\n@internal\n*/\nContentMatch.empty = new ContentMatch(true);\nclass TokenStream {\n constructor(string, nodeTypes) {\n this.string = string;\n this.nodeTypes = nodeTypes;\n this.inline = null;\n this.pos = 0;\n this.tokens = string.split(/\\s*(?=\\b|\\W|$)/);\n if (this.tokens[this.tokens.length - 1] == \"\")\n this.tokens.pop();\n if (this.tokens[0] == \"\")\n this.tokens.shift();\n }\n get next() { return this.tokens[this.pos]; }\n eat(tok) { return this.next == tok && (this.pos++ || true); }\n err(str) { throw new SyntaxError(str + \" (in content expression '\" + this.string + \"')\"); }\n}\nfunction parseExpr(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSeq(stream));\n } while (stream.eat(\"|\"));\n return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n}\nfunction parseExprSeq(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSubscript(stream));\n } while (stream.next && stream.next != \")\" && stream.next != \"|\");\n return exprs.length == 1 ? exprs[0] : { type: \"seq\", exprs };\n}\nfunction parseExprSubscript(stream) {\n let expr = parseExprAtom(stream);\n for (;;) {\n if (stream.eat(\"+\"))\n expr = { type: \"plus\", expr };\n else if (stream.eat(\"*\"))\n expr = { type: \"star\", expr };\n else if (stream.eat(\"?\"))\n expr = { type: \"opt\", expr };\n else if (stream.eat(\"{\"))\n expr = parseExprRange(stream, expr);\n else\n break;\n }\n return expr;\n}\nfunction parseNum(stream) {\n if (/\\D/.test(stream.next))\n stream.err(\"Expected number, got '\" + stream.next + \"'\");\n let result = Number(stream.next);\n stream.pos++;\n return result;\n}\nfunction parseExprRange(stream, expr) {\n let min = parseNum(stream), max = min;\n if (stream.eat(\",\")) {\n if (stream.next != \"}\")\n max = parseNum(stream);\n else\n max = -1;\n }\n if (!stream.eat(\"}\"))\n stream.err(\"Unclosed braced range\");\n return { type: \"range\", min, max, expr };\n}\nfunction resolveName(stream, name) {\n let types = stream.nodeTypes, type = types[name];\n if (type)\n return [type];\n let result = [];\n for (let typeName in types) {\n let type = types[typeName];\n if (type.isInGroup(name))\n result.push(type);\n }\n if (result.length == 0)\n stream.err(\"No node type or group '\" + name + \"' found\");\n return result;\n}\nfunction parseExprAtom(stream) {\n if (stream.eat(\"(\")) {\n let expr = parseExpr(stream);\n if (!stream.eat(\")\"))\n stream.err(\"Missing closing paren\");\n return expr;\n }\n else if (!/\\W/.test(stream.next)) {\n let exprs = resolveName(stream, stream.next).map(type => {\n if (stream.inline == null)\n stream.inline = type.isInline;\n else if (stream.inline != type.isInline)\n stream.err(\"Mixing inline and block content\");\n return { type: \"name\", value: type };\n });\n stream.pos++;\n return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n }\n else {\n stream.err(\"Unexpected token '\" + stream.next + \"'\");\n }\n}\n// Construct an NFA from an expression as returned by the parser. The\n// NFA is represented as an array of states, which are themselves\n// arrays of edges, which are `{term, to}` objects. The first state is\n// the entry state and the last node is the success state.\n//\n// Note that unlike typical NFAs, the edge ordering in this one is\n// significant, in that it is used to contruct filler content when\n// necessary.\nfunction nfa(expr) {\n let nfa = [[]];\n connect(compile(expr, 0), node());\n return nfa;\n function node() { return nfa.push([]) - 1; }\n function edge(from, to, term) {\n let edge = { term, to };\n nfa[from].push(edge);\n return edge;\n }\n function connect(edges, to) {\n edges.forEach(edge => edge.to = to);\n }\n function compile(expr, from) {\n if (expr.type == \"choice\") {\n return expr.exprs.reduce((out, expr) => out.concat(compile(expr, from)), []);\n }\n else if (expr.type == \"seq\") {\n for (let i = 0;; i++) {\n let next = compile(expr.exprs[i], from);\n if (i == expr.exprs.length - 1)\n return next;\n connect(next, from = node());\n }\n }\n else if (expr.type == \"star\") {\n let loop = node();\n edge(from, loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n }\n else if (expr.type == \"plus\") {\n let loop = node();\n connect(compile(expr.expr, from), loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n }\n else if (expr.type == \"opt\") {\n return [edge(from)].concat(compile(expr.expr, from));\n }\n else if (expr.type == \"range\") {\n let cur = from;\n for (let i = 0; i < expr.min; i++) {\n let next = node();\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n if (expr.max == -1) {\n connect(compile(expr.expr, cur), cur);\n }\n else {\n for (let i = expr.min; i < expr.max; i++) {\n let next = node();\n edge(cur, next);\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n }\n return [edge(cur)];\n }\n else if (expr.type == \"name\") {\n return [edge(from, undefined, expr.value)];\n }\n else {\n throw new Error(\"Unknown expr type\");\n }\n }\n}\nfunction cmp(a, b) { return b - a; }\n// Get the set of nodes reachable by null edges from `node`. Omit\n// nodes with only a single null-out-edge, since they may lead to\n// needless duplicated nodes.\nfunction nullFrom(nfa, node) {\n let result = [];\n scan(node);\n return result.sort(cmp);\n function scan(node) {\n let edges = nfa[node];\n if (edges.length == 1 && !edges[0].term)\n return scan(edges[0].to);\n result.push(node);\n for (let i = 0; i < edges.length; i++) {\n let { term, to } = edges[i];\n if (!term && result.indexOf(to) == -1)\n scan(to);\n }\n }\n}\n// Compiles an NFA as produced by `nfa` into a DFA, modeled as a set\n// of state objects (`ContentMatch` instances) with transitions\n// between them.\nfunction dfa(nfa) {\n let labeled = Object.create(null);\n return explore(nullFrom(nfa, 0));\n function explore(states) {\n let out = [];\n states.forEach(node => {\n nfa[node].forEach(({ term, to }) => {\n if (!term)\n return;\n let set;\n for (let i = 0; i < out.length; i++)\n if (out[i][0] == term)\n set = out[i][1];\n nullFrom(nfa, to).forEach(node => {\n if (!set)\n out.push([term, set = []]);\n if (set.indexOf(node) == -1)\n set.push(node);\n });\n });\n });\n let state = labeled[states.join(\",\")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1);\n for (let i = 0; i < out.length; i++) {\n let states = out[i][1].sort(cmp);\n state.next.push({ type: out[i][0], next: labeled[states.join(\",\")] || explore(states) });\n }\n return state;\n }\n}\nfunction checkForDeadEnds(match, stream) {\n for (let i = 0, work = [match]; i < work.length; i++) {\n let state = work[i], dead = !state.validEnd, nodes = [];\n for (let j = 0; j < state.next.length; j++) {\n let { type, next } = state.next[j];\n nodes.push(type.name);\n if (dead && !(type.isText || type.hasRequiredAttrs()))\n dead = false;\n if (work.indexOf(next) == -1)\n work.push(next);\n }\n if (dead)\n stream.err(\"Only non-generatable nodes (\" + nodes.join(\", \") + \") in a required position (see https://prosemirror.net/docs/guide/#generatable)\");\n }\n}\n\n// For node types where all attrs have a default value (or which don't\n// have any attributes), build up a single reusable default attribute\n// object, and use it for all nodes that don't specify specific\n// attributes.\nfunction defaultAttrs(attrs) {\n let defaults = Object.create(null);\n for (let attrName in attrs) {\n let attr = attrs[attrName];\n if (!attr.hasDefault)\n return null;\n defaults[attrName] = attr.default;\n }\n return defaults;\n}\nfunction computeAttrs(attrs, value) {\n let built = Object.create(null);\n for (let name in attrs) {\n let attr = attrs[name];\n let given = value && value[name];\n if (given === undefined) {\n if (attr.hasDefault)\n given = attr.default;\n else\n throw new RangeError(\"No value supplied for attribute \" + name);\n }\n else if (attr.validate) {\n attr.validate(given);\n }\n built[name] = given;\n }\n return built;\n}\nfunction initAttrs(typeName, attrs) {\n let result = Object.create(null);\n if (attrs)\n for (let name in attrs)\n result[name] = new Attribute(typeName, name, attrs[name]);\n return result;\n}\n/**\nNode types are objects allocated once per `Schema` and used to\n[tag](https://prosemirror.net/docs/ref/#model.Node.type) `Node` instances. They contain information\nabout the node type, such as its name and what kind of node it\nrepresents.\n*/\nclass NodeType {\n /**\n @internal\n */\n constructor(\n /**\n The name the node type has in this schema.\n */\n name, \n /**\n A link back to the `Schema` the node type belongs to.\n */\n schema, \n /**\n The spec that this type is based on\n */\n spec) {\n this.name = name;\n this.schema = schema;\n this.spec = spec;\n /**\n The set of marks allowed in this node. `null` means all marks\n are allowed.\n */\n this.markSet = null;\n this.groups = spec.group ? spec.group.split(\" \") : [];\n this.attrs = initAttrs(name, spec.attrs);\n this.defaultAttrs = defaultAttrs(this.attrs);\n this.contentMatch = null;\n this.inlineContent = null;\n this.isBlock = !(spec.inline || name == \"text\");\n this.isText = name == \"text\";\n }\n /**\n True if this is an inline type.\n */\n get isInline() { return !this.isBlock; }\n /**\n True if this is a textblock type, a block that contains inline\n content.\n */\n get isTextblock() { return this.isBlock && this.inlineContent; }\n /**\n True for node types that allow no content.\n */\n get isLeaf() { return this.contentMatch == ContentMatch.empty; }\n /**\n True when this node is an atom, i.e. when it does not have\n directly editable content.\n */\n get isAtom() { return this.isLeaf || !!this.spec.atom; }\n /**\n Return true when this node type is part of the given\n [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).\n */\n isInGroup(group) {\n return this.groups.indexOf(group) > -1;\n }\n /**\n The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.\n */\n get whitespace() {\n return this.spec.whitespace || (this.spec.code ? \"pre\" : \"normal\");\n }\n /**\n Tells you whether this node type has any required attributes.\n */\n hasRequiredAttrs() {\n for (let n in this.attrs)\n if (this.attrs[n].isRequired)\n return true;\n return false;\n }\n /**\n Indicates whether this node allows some of the same content as\n the given node type.\n */\n compatibleContent(other) {\n return this == other || this.contentMatch.compatible(other.contentMatch);\n }\n /**\n @internal\n */\n computeAttrs(attrs) {\n if (!attrs && this.defaultAttrs)\n return this.defaultAttrs;\n else\n return computeAttrs(this.attrs, attrs);\n }\n /**\n Create a `Node` of this type. The given attributes are\n checked and defaulted (you can pass `null` to use the type's\n defaults entirely, if no required attributes exist). `content`\n may be a `Fragment`, a node, an array of nodes, or\n `null`. Similarly `marks` may be `null` to default to the empty\n set of marks.\n */\n create(attrs = null, content, marks) {\n if (this.isText)\n throw new Error(\"NodeType.create can't construct text nodes\");\n return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks));\n }\n /**\n Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content\n against the node type's content restrictions, and throw an error\n if it doesn't match.\n */\n createChecked(attrs = null, content, marks) {\n content = Fragment.from(content);\n this.checkContent(content);\n return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));\n }\n /**\n Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is\n necessary to add nodes to the start or end of the given fragment\n to make it fit the node. If no fitting wrapping can be found,\n return null. Note that, due to the fact that required nodes can\n always be created, this will always succeed if you pass null or\n `Fragment.empty` as content.\n */\n createAndFill(attrs = null, content, marks) {\n attrs = this.computeAttrs(attrs);\n content = Fragment.from(content);\n if (content.size) {\n let before = this.contentMatch.fillBefore(content);\n if (!before)\n return null;\n content = before.append(content);\n }\n let matched = this.contentMatch.matchFragment(content);\n let after = matched && matched.fillBefore(Fragment.empty, true);\n if (!after)\n return null;\n return new Node(this, attrs, content.append(after), Mark.setFrom(marks));\n }\n /**\n Returns true if the given fragment is valid content for this node\n type.\n */\n validContent(content) {\n let result = this.contentMatch.matchFragment(content);\n if (!result || !result.validEnd)\n return false;\n for (let i = 0; i < content.childCount; i++)\n if (!this.allowsMarks(content.child(i).marks))\n return false;\n return true;\n }\n /**\n Throws a RangeError if the given fragment is not valid content for this\n node type.\n @internal\n */\n checkContent(content) {\n if (!this.validContent(content))\n throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);\n }\n /**\n @internal no longer useful, but called by old prosemirror-view versions\n */\n checkAttrs(attrs) { }\n /**\n Check whether the given mark type is allowed in this node.\n */\n allowsMarkType(markType) {\n return this.markSet == null || this.markSet.indexOf(markType) > -1;\n }\n /**\n Test whether the given set of marks are allowed in this node.\n */\n allowsMarks(marks) {\n if (this.markSet == null)\n return true;\n for (let i = 0; i < marks.length; i++)\n if (!this.allowsMarkType(marks[i].type))\n return false;\n return true;\n }\n /**\n Removes the marks that are not allowed in this node from the given set.\n */\n allowedMarks(marks) {\n if (this.markSet == null)\n return marks;\n let copy;\n for (let i = 0; i < marks.length; i++) {\n if (!this.allowsMarkType(marks[i].type)) {\n if (!copy)\n copy = marks.slice(0, i);\n }\n else if (copy) {\n copy.push(marks[i]);\n }\n }\n return !copy ? marks : copy.length ? copy : Mark.none;\n }\n /**\n @internal\n */\n static compile(nodes, schema) {\n let result = Object.create(null);\n nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec));\n let topType = schema.spec.topNode || \"doc\";\n if (!result[topType])\n throw new RangeError(\"Schema is missing its top node type ('\" + topType + \"')\");\n if (!result.text)\n throw new RangeError(\"Every schema needs a 'text' type\");\n for (let _ in result.text.attrs)\n throw new RangeError(\"The text node type should not have attributes\");\n return result;\n }\n}\nfunction validateType(typeName, attrName, type) {\n let types = type.split(\"|\");\n return (value) => {\n let name = value === null ? \"null\" : typeof value;\n if (types.indexOf(name) < 0)\n throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);\n };\n}\n// Attribute descriptors\nclass Attribute {\n constructor(typeName, attrName, options) {\n this.hasDefault = Object.prototype.hasOwnProperty.call(options, \"default\");\n this.default = options.default;\n this.validate = typeof options.validate == \"string\" ? validateType(typeName, attrName, options.validate) : options.validate;\n }\n get isRequired() {\n return !this.hasDefault;\n }\n}\n// Marks\n/**\nLike nodes, marks (which are associated with nodes to signify\nthings like emphasis or being part of a link) are\n[tagged](https://prosemirror.net/docs/ref/#model.Mark.type) with type objects, which are\ninstantiated once per `Schema`.\n*/\nclass MarkType {\n /**\n @internal\n */\n constructor(\n /**\n The name of the mark type.\n */\n name, \n /**\n @internal\n */\n rank, \n /**\n The schema that this mark type instance is part of.\n */\n schema, \n /**\n The spec on which the type is based.\n */\n spec) {\n this.name = name;\n this.rank = rank;\n this.schema = schema;\n this.spec = spec;\n this.attrs = initAttrs(name, spec.attrs);\n this.excluded = null;\n let defaults = defaultAttrs(this.attrs);\n this.instance = defaults ? new Mark(this, defaults) : null;\n }\n /**\n Create a mark of this type. `attrs` may be `null` or an object\n containing only some of the mark's attributes. The others, if\n they have defaults, will be added.\n */\n create(attrs = null) {\n if (!attrs && this.instance)\n return this.instance;\n return new Mark(this, computeAttrs(this.attrs, attrs));\n }\n /**\n @internal\n */\n static compile(marks, schema) {\n let result = Object.create(null), rank = 0;\n marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec));\n return result;\n }\n /**\n When there is a mark of this type in the given set, a new set\n without it is returned. Otherwise, the input set is returned.\n */\n removeFromSet(set) {\n for (var i = 0; i < set.length; i++)\n if (set[i].type == this) {\n set = set.slice(0, i).concat(set.slice(i + 1));\n i--;\n }\n return set;\n }\n /**\n Tests whether there is a mark of this type in the given set.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++)\n if (set[i].type == this)\n return set[i];\n }\n /**\n Queries whether a given mark type is\n [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.\n */\n excludes(other) {\n return this.excluded.indexOf(other) > -1;\n }\n}\n/**\nA document schema. Holds [node](https://prosemirror.net/docs/ref/#model.NodeType) and [mark\ntype](https://prosemirror.net/docs/ref/#model.MarkType) objects for the nodes and marks that may\noccur in conforming documents, and provides functionality for\ncreating and deserializing such documents.\n\nWhen given, the type parameters provide the names of the nodes and\nmarks in this schema.\n*/\nclass Schema {\n /**\n Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).\n */\n constructor(spec) {\n /**\n The [linebreak\n replacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement) node defined\n in this schema, if any.\n */\n this.linebreakReplacement = null;\n /**\n An object for storing whatever values modules may want to\n compute and cache per schema. (If you want to store something\n in it, try to use property names unlikely to clash.)\n */\n this.cached = Object.create(null);\n let instanceSpec = this.spec = {};\n for (let prop in spec)\n instanceSpec[prop] = spec[prop];\n instanceSpec.nodes = OrderedMap.from(spec.nodes),\n instanceSpec.marks = OrderedMap.from(spec.marks || {}),\n this.nodes = NodeType.compile(this.spec.nodes, this);\n this.marks = MarkType.compile(this.spec.marks, this);\n let contentExprCache = Object.create(null);\n for (let prop in this.nodes) {\n if (prop in this.marks)\n throw new RangeError(prop + \" can not be both a node and a mark\");\n let type = this.nodes[prop], contentExpr = type.spec.content || \"\", markExpr = type.spec.marks;\n type.contentMatch = contentExprCache[contentExpr] ||\n (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));\n type.inlineContent = type.contentMatch.inlineContent;\n if (type.spec.linebreakReplacement) {\n if (this.linebreakReplacement)\n throw new RangeError(\"Multiple linebreak nodes defined\");\n if (!type.isInline || !type.isLeaf)\n throw new RangeError(\"Linebreak replacement nodes must be inline leaf nodes\");\n this.linebreakReplacement = type;\n }\n type.markSet = markExpr == \"_\" ? null :\n markExpr ? gatherMarks(this, markExpr.split(\" \")) :\n markExpr == \"\" || !type.inlineContent ? [] : null;\n }\n for (let prop in this.marks) {\n let type = this.marks[prop], excl = type.spec.excludes;\n type.excluded = excl == null ? [type] : excl == \"\" ? [] : gatherMarks(this, excl.split(\" \"));\n }\n this.nodeFromJSON = json => Node.fromJSON(this, json);\n this.markFromJSON = json => Mark.fromJSON(this, json);\n this.topNodeType = this.nodes[this.spec.topNode || \"doc\"];\n this.cached.wrappings = Object.create(null);\n }\n /**\n Create a node in this schema. The `type` may be a string or a\n `NodeType` instance. Attributes will be extended with defaults,\n `content` may be a `Fragment`, `null`, a `Node`, or an array of\n nodes.\n */\n node(type, attrs = null, content, marks) {\n if (typeof type == \"string\")\n type = this.nodeType(type);\n else if (!(type instanceof NodeType))\n throw new RangeError(\"Invalid node type: \" + type);\n else if (type.schema != this)\n throw new RangeError(\"Node type from different schema used (\" + type.name + \")\");\n return type.createChecked(attrs, content, marks);\n }\n /**\n Create a text node in the schema. Empty text nodes are not\n allowed.\n */\n text(text, marks) {\n let type = this.nodes.text;\n return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks));\n }\n /**\n Create a mark with the given type and attributes.\n */\n mark(type, attrs) {\n if (typeof type == \"string\")\n type = this.marks[type];\n return type.create(attrs);\n }\n /**\n @internal\n */\n nodeType(name) {\n let found = this.nodes[name];\n if (!found)\n throw new RangeError(\"Unknown node type: \" + name);\n return found;\n }\n}\nfunction gatherMarks(schema, marks) {\n let found = [];\n for (let i = 0; i < marks.length; i++) {\n let name = marks[i], mark = schema.marks[name], ok = mark;\n if (mark) {\n found.push(mark);\n }\n else {\n for (let prop in schema.marks) {\n let mark = schema.marks[prop];\n if (name == \"_\" || (mark.spec.group && mark.spec.group.split(\" \").indexOf(name) > -1))\n found.push(ok = mark);\n }\n }\n if (!ok)\n throw new SyntaxError(\"Unknown mark type: '\" + marks[i] + \"'\");\n }\n return found;\n}\n\nfunction isTagRule(rule) { return rule.tag != null; }\nfunction isStyleRule(rule) { return rule.style != null; }\n/**\nA DOM parser represents a strategy for parsing DOM content into a\nProseMirror document conforming to a given schema. Its behavior is\ndefined by an array of [rules](https://prosemirror.net/docs/ref/#model.ParseRule).\n*/\nclass DOMParser {\n /**\n Create a parser that targets the given schema, using the given\n parsing rules.\n */\n constructor(\n /**\n The schema into which the parser parses.\n */\n schema, \n /**\n The set of [parse rules](https://prosemirror.net/docs/ref/#model.ParseRule) that the parser\n uses, in order of precedence.\n */\n rules) {\n this.schema = schema;\n this.rules = rules;\n /**\n @internal\n */\n this.tags = [];\n /**\n @internal\n */\n this.styles = [];\n let matchedStyles = this.matchedStyles = [];\n rules.forEach(rule => {\n if (isTagRule(rule)) {\n this.tags.push(rule);\n }\n else if (isStyleRule(rule)) {\n let prop = /[^=]*/.exec(rule.style)[0];\n if (matchedStyles.indexOf(prop) < 0)\n matchedStyles.push(prop);\n this.styles.push(rule);\n }\n });\n // Only normalize list elements when lists in the schema can't directly contain themselves\n this.normalizeLists = !this.tags.some(r => {\n if (!/^(ul|ol)\\b/.test(r.tag) || !r.node)\n return false;\n let node = schema.nodes[r.node];\n return node.contentMatch.matchType(node);\n });\n }\n /**\n Parse a document from the content of a DOM node.\n */\n parse(dom, options = {}) {\n let context = new ParseContext(this, options, false);\n context.addAll(dom, Mark.none, options.from, options.to);\n return context.finish();\n }\n /**\n Parses the content of the given DOM node, like\n [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of\n options. But unlike that method, which produces a whole node,\n this one returns a slice that is open at the sides, meaning that\n the schema constraints aren't applied to the start of nodes to\n the left of the input and the end of nodes at the end.\n */\n parseSlice(dom, options = {}) {\n let context = new ParseContext(this, options, true);\n context.addAll(dom, Mark.none, options.from, options.to);\n return Slice.maxOpen(context.finish());\n }\n /**\n @internal\n */\n matchTag(dom, context, after) {\n for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) {\n let rule = this.tags[i];\n if (matches(dom, rule.tag) &&\n (rule.namespace === undefined || dom.namespaceURI == rule.namespace) &&\n (!rule.context || context.matchesContext(rule.context))) {\n if (rule.getAttrs) {\n let result = rule.getAttrs(dom);\n if (result === false)\n continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n }\n /**\n @internal\n */\n matchStyle(prop, value, context, after) {\n for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) {\n let rule = this.styles[i], style = rule.style;\n if (style.indexOf(prop) != 0 ||\n rule.context && !context.matchesContext(rule.context) ||\n // Test that the style string either precisely matches the prop,\n // or has an '=' sign after the prop, followed by the given\n // value.\n style.length > prop.length &&\n (style.charCodeAt(prop.length) != 61 || style.slice(prop.length + 1) != value))\n continue;\n if (rule.getAttrs) {\n let result = rule.getAttrs(value);\n if (result === false)\n continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n /**\n @internal\n */\n static schemaRules(schema) {\n let result = [];\n function insert(rule) {\n let priority = rule.priority == null ? 50 : rule.priority, i = 0;\n for (; i < result.length; i++) {\n let next = result[i], nextPriority = next.priority == null ? 50 : next.priority;\n if (nextPriority < priority)\n break;\n }\n result.splice(i, 0, rule);\n }\n for (let name in schema.marks) {\n let rules = schema.marks[name].spec.parseDOM;\n if (rules)\n rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.mark || rule.ignore || rule.clearMark))\n rule.mark = name;\n });\n }\n for (let name in schema.nodes) {\n let rules = schema.nodes[name].spec.parseDOM;\n if (rules)\n rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.node || rule.ignore || rule.mark))\n rule.node = name;\n });\n }\n return result;\n }\n /**\n Construct a DOM parser using the parsing rules listed in a\n schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by\n [priority](https://prosemirror.net/docs/ref/#model.GenericParseRule.priority).\n */\n static fromSchema(schema) {\n return schema.cached.domParser ||\n (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema)));\n }\n}\nconst blockTags = {\n address: true, article: true, aside: true, blockquote: true, body: true, canvas: true,\n dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true,\n footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true,\n h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true,\n output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true\n};\nconst ignoreTags = {\n head: true, noscript: true, object: true, script: true, style: true, title: true\n};\nconst listTags = { ol: true, ul: true };\n// Using a bitfield for node context options\nconst OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4;\nfunction wsOptionsFor(type, preserveWhitespace, base) {\n if (preserveWhitespace != null)\n return (preserveWhitespace ? OPT_PRESERVE_WS : 0) |\n (preserveWhitespace === \"full\" ? OPT_PRESERVE_WS_FULL : 0);\n return type && type.whitespace == \"pre\" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base & ~OPT_OPEN_LEFT;\n}\nclass NodeContext {\n constructor(type, attrs, marks, solid, match, options) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.solid = solid;\n this.options = options;\n this.content = [];\n // Marks applied to the node's children\n this.activeMarks = Mark.none;\n this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);\n }\n findWrapping(node) {\n if (!this.match) {\n if (!this.type)\n return [];\n let fill = this.type.contentMatch.fillBefore(Fragment.from(node));\n if (fill) {\n this.match = this.type.contentMatch.matchFragment(fill);\n }\n else {\n let start = this.type.contentMatch, wrap;\n if (wrap = start.findWrapping(node.type)) {\n this.match = start;\n return wrap;\n }\n else {\n return null;\n }\n }\n }\n return this.match.findWrapping(node.type);\n }\n finish(openEnd) {\n if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace\n let last = this.content[this.content.length - 1], m;\n if (last && last.isText && (m = /[ \\t\\r\\n\\u000c]+$/.exec(last.text))) {\n let text = last;\n if (last.text.length == m[0].length)\n this.content.pop();\n else\n this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length));\n }\n }\n let content = Fragment.from(this.content);\n if (!openEnd && this.match)\n content = content.append(this.match.fillBefore(Fragment.empty, true));\n return this.type ? this.type.create(this.attrs, content, this.marks) : content;\n }\n inlineContext(node) {\n if (this.type)\n return this.type.inlineContent;\n if (this.content.length)\n return this.content[0].isInline;\n return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());\n }\n}\nclass ParseContext {\n constructor(\n // The parser we are using.\n parser, \n // The options passed to this parse.\n options, isOpen) {\n this.parser = parser;\n this.options = options;\n this.isOpen = isOpen;\n this.open = 0;\n this.localPreserveWS = false;\n let topNode = options.topNode, topContext;\n let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);\n if (topNode)\n topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);\n else if (isOpen)\n topContext = new NodeContext(null, null, Mark.none, true, null, topOptions);\n else\n topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions);\n this.nodes = [topContext];\n this.find = options.findPositions;\n this.needsBlock = false;\n }\n get top() {\n return this.nodes[this.open];\n }\n // Add a DOM node to the content. Text is inserted as text node,\n // otherwise, the node is passed to `addElement` or, if it has a\n // `style` attribute, `addElementWithStyles`.\n addDOM(dom, marks) {\n if (dom.nodeType == 3)\n this.addTextNode(dom, marks);\n else if (dom.nodeType == 1)\n this.addElement(dom, marks);\n }\n addTextNode(dom, marks) {\n let value = dom.nodeValue;\n let top = this.top, preserveWS = (top.options & OPT_PRESERVE_WS_FULL) ? \"full\"\n : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0;\n let { schema } = this.parser;\n if (preserveWS === \"full\" ||\n top.inlineContext(dom) ||\n /[^ \\t\\r\\n\\u000c]/.test(value)) {\n if (!preserveWS) {\n value = value.replace(/[ \\t\\r\\n\\u000c]+/g, \" \");\n // If this starts with whitespace, and there is no node before it, or\n // a hard break, or a text node that ends with whitespace, strip the\n // leading space.\n if (/^[ \\t\\r\\n\\u000c]/.test(value) && this.open == this.nodes.length - 1) {\n let nodeBefore = top.content[top.content.length - 1];\n let domNodeBefore = dom.previousSibling;\n if (!nodeBefore ||\n (domNodeBefore && domNodeBefore.nodeName == 'BR') ||\n (nodeBefore.isText && /[ \\t\\r\\n\\u000c]$/.test(nodeBefore.text)))\n value = value.slice(1);\n }\n }\n else if (preserveWS === \"full\") {\n value = value.replace(/\\r\\n?/g, \"\\n\");\n }\n else if (schema.linebreakReplacement && /[\\r\\n]/.test(value) && this.top.findWrapping(schema.linebreakReplacement.create())) {\n let lines = value.split(/\\r?\\n|\\r/);\n for (let i = 0; i < lines.length; i++) {\n if (i)\n this.insertNode(schema.linebreakReplacement.create(), marks, true);\n if (lines[i])\n this.insertNode(schema.text(lines[i]), marks, !/\\S/.test(lines[i]));\n }\n value = \"\";\n }\n else {\n value = value.replace(/\\r?\\n|\\r/g, \" \");\n }\n if (value)\n this.insertNode(schema.text(value), marks, !/\\S/.test(value));\n this.findInText(dom);\n }\n else {\n this.findInside(dom);\n }\n }\n // Try to find a handler for the given tag and use that to parse. If\n // none is found, the element's content nodes are added directly.\n addElement(dom, marks, matchAfter) {\n let outerWS = this.localPreserveWS, top = this.top;\n if (dom.tagName == \"PRE\" || /pre/.test(dom.style && dom.style.whiteSpace))\n this.localPreserveWS = true;\n let name = dom.nodeName.toLowerCase(), ruleID;\n if (listTags.hasOwnProperty(name) && this.parser.normalizeLists)\n normalizeList(dom);\n let rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) ||\n (ruleID = this.parser.matchTag(dom, this, matchAfter));\n out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {\n this.findInside(dom);\n this.ignoreFallback(dom, marks);\n }\n else if (!rule || rule.skip || rule.closeParent) {\n if (rule && rule.closeParent)\n this.open = Math.max(0, this.open - 1);\n else if (rule && rule.skip.nodeType)\n dom = rule.skip;\n let sync, oldNeedsBlock = this.needsBlock;\n if (blockTags.hasOwnProperty(name)) {\n if (top.content.length && top.content[0].isInline && this.open) {\n this.open--;\n top = this.top;\n }\n sync = true;\n if (!top.type)\n this.needsBlock = true;\n }\n else if (!dom.firstChild) {\n this.leafFallback(dom, marks);\n break out;\n }\n let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);\n if (innerMarks)\n this.addAll(dom, innerMarks);\n if (sync)\n this.sync(top);\n this.needsBlock = oldNeedsBlock;\n }\n else {\n let innerMarks = this.readStyles(dom, marks);\n if (innerMarks)\n this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : undefined);\n }\n this.localPreserveWS = outerWS;\n }\n // Called for leaf DOM nodes that would otherwise be ignored\n leafFallback(dom, marks) {\n if (dom.nodeName == \"BR\" && this.top.type && this.top.type.inlineContent)\n this.addTextNode(dom.ownerDocument.createTextNode(\"\\n\"), marks);\n }\n // Called for ignored nodes\n ignoreFallback(dom, marks) {\n // Ignored BR nodes should at least create an inline context\n if (dom.nodeName == \"BR\" && (!this.top.type || !this.top.type.inlineContent))\n this.findPlace(this.parser.schema.text(\"-\"), marks, true);\n }\n // Run any style parser associated with the node's styles. Either\n // return an updated array of marks, or null to indicate some of the\n // styles had a rule with `ignore` set.\n readStyles(dom, marks) {\n let styles = dom.style;\n // Because many properties will only show up in 'normalized' form\n // in `style.item` (i.e. text-decoration becomes\n // text-decoration-line, text-decoration-color, etc), we directly\n // query the styles mentioned in our rules instead of iterating\n // over the items.\n if (styles && styles.length)\n for (let i = 0; i < this.parser.matchedStyles.length; i++) {\n let name = this.parser.matchedStyles[i], value = styles.getPropertyValue(name);\n if (value)\n for (let after = undefined;;) {\n let rule = this.parser.matchStyle(name, value, this, after);\n if (!rule)\n break;\n if (rule.ignore)\n return null;\n if (rule.clearMark)\n marks = marks.filter(m => !rule.clearMark(m));\n else\n marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));\n if (rule.consuming === false)\n after = rule;\n else\n break;\n }\n }\n return marks;\n }\n // Look up a handler for the given node. If none are found, return\n // false. Otherwise, apply it, use its return value to drive the way\n // the node's content is wrapped, and return true.\n addElementByRule(dom, rule, marks, continueAfter) {\n let sync, nodeType;\n if (rule.node) {\n nodeType = this.parser.schema.nodes[rule.node];\n if (!nodeType.isLeaf) {\n let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);\n if (inner) {\n sync = true;\n marks = inner;\n }\n }\n else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == \"BR\")) {\n this.leafFallback(dom, marks);\n }\n }\n else {\n let markType = this.parser.schema.marks[rule.mark];\n marks = marks.concat(markType.create(rule.attrs));\n }\n let startIn = this.top;\n if (nodeType && nodeType.isLeaf) {\n this.findInside(dom);\n }\n else if (continueAfter) {\n this.addElement(dom, marks, continueAfter);\n }\n else if (rule.getContent) {\n this.findInside(dom);\n rule.getContent(dom, this.parser.schema).forEach(node => this.insertNode(node, marks, false));\n }\n else {\n let contentDOM = dom;\n if (typeof rule.contentElement == \"string\")\n contentDOM = dom.querySelector(rule.contentElement);\n else if (typeof rule.contentElement == \"function\")\n contentDOM = rule.contentElement(dom);\n else if (rule.contentElement)\n contentDOM = rule.contentElement;\n this.findAround(dom, contentDOM, true);\n this.addAll(contentDOM, marks);\n this.findAround(dom, contentDOM, false);\n }\n if (sync && this.sync(startIn))\n this.open--;\n }\n // Add all child nodes between `startIndex` and `endIndex` (or the\n // whole node, if not given). If `sync` is passed, use it to\n // synchronize after every block element.\n addAll(parent, marks, startIndex, endIndex) {\n let index = startIndex || 0;\n for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {\n this.findAtPoint(parent, index);\n this.addDOM(dom, marks);\n }\n this.findAtPoint(parent, index);\n }\n // Try to find a way to fit the given node type into the current\n // context. May add intermediate wrappers and/or leave non-solid\n // nodes that we're in.\n findPlace(node, marks, cautious) {\n let route, sync;\n for (let depth = this.open, penalty = 0; depth >= 0; depth--) {\n let cx = this.nodes[depth];\n let found = cx.findWrapping(node);\n if (found && (!route || route.length > found.length + penalty)) {\n route = found;\n sync = cx;\n if (!found.length)\n break;\n }\n if (cx.solid) {\n if (cautious)\n break;\n penalty += 2;\n }\n }\n if (!route)\n return null;\n this.sync(sync);\n for (let i = 0; i < route.length; i++)\n marks = this.enterInner(route[i], null, marks, false);\n return marks;\n }\n // Try to insert the given node, adjusting the context when needed.\n insertNode(node, marks, cautious) {\n if (node.isInline && this.needsBlock && !this.top.type) {\n let block = this.textblockFromContext();\n if (block)\n marks = this.enterInner(block, null, marks);\n }\n let innerMarks = this.findPlace(node, marks, cautious);\n if (innerMarks) {\n this.closeExtra();\n let top = this.top;\n if (top.match)\n top.match = top.match.matchType(node.type);\n let nodeMarks = Mark.none;\n for (let m of innerMarks.concat(node.marks))\n if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type))\n nodeMarks = m.addToSet(nodeMarks);\n top.content.push(node.mark(nodeMarks));\n return true;\n }\n return false;\n }\n // Try to start a node of the given type, adjusting the context when\n // necessary.\n enter(type, attrs, marks, preserveWS) {\n let innerMarks = this.findPlace(type.create(attrs), marks, false);\n if (innerMarks)\n innerMarks = this.enterInner(type, attrs, marks, true, preserveWS);\n return innerMarks;\n }\n // Open a node of the given type\n enterInner(type, attrs, marks, solid = false, preserveWS) {\n this.closeExtra();\n let top = this.top;\n top.match = top.match && top.match.matchType(type);\n let options = wsOptionsFor(type, preserveWS, top.options);\n if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0)\n options |= OPT_OPEN_LEFT;\n let applyMarks = Mark.none;\n marks = marks.filter(m => {\n if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) {\n applyMarks = m.addToSet(applyMarks);\n return false;\n }\n return true;\n });\n this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options));\n this.open++;\n return marks;\n }\n // Make sure all nodes above this.open are finished and added to\n // their parents\n closeExtra(openEnd = false) {\n let i = this.nodes.length - 1;\n if (i > this.open) {\n for (; i > this.open; i--)\n this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));\n this.nodes.length = this.open + 1;\n }\n }\n finish() {\n this.open = 0;\n this.closeExtra(this.isOpen);\n return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));\n }\n sync(to) {\n for (let i = this.open; i >= 0; i--) {\n if (this.nodes[i] == to) {\n this.open = i;\n return true;\n }\n else if (this.localPreserveWS) {\n this.nodes[i].options |= OPT_PRESERVE_WS;\n }\n }\n return false;\n }\n get currentPos() {\n this.closeExtra();\n let pos = 0;\n for (let i = this.open; i >= 0; i--) {\n let content = this.nodes[i].content;\n for (let j = content.length - 1; j >= 0; j--)\n pos += content[j].nodeSize;\n if (i)\n pos++;\n }\n return pos;\n }\n findAtPoint(parent, offset) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].node == parent && this.find[i].offset == offset)\n this.find[i].pos = this.currentPos;\n }\n }\n findInside(parent) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node))\n this.find[i].pos = this.currentPos;\n }\n }\n findAround(parent, content, before) {\n if (parent != content && this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {\n let pos = content.compareDocumentPosition(this.find[i].node);\n if (pos & (before ? 2 : 4))\n this.find[i].pos = this.currentPos;\n }\n }\n }\n findInText(textNode) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].node == textNode)\n this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset);\n }\n }\n // Determines whether the given context string matches this context.\n matchesContext(context) {\n if (context.indexOf(\"|\") > -1)\n return context.split(/\\s*\\|\\s*/).some(this.matchesContext, this);\n let parts = context.split(\"/\");\n let option = this.options.context;\n let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);\n let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);\n let match = (i, depth) => {\n for (; i >= 0; i--) {\n let part = parts[i];\n if (part == \"\") {\n if (i == parts.length - 1 || i == 0)\n continue;\n for (; depth >= minDepth; depth--)\n if (match(i - 1, depth))\n return true;\n return false;\n }\n else {\n let next = depth > 0 || (depth == 0 && useRoot) ? this.nodes[depth].type\n : option && depth >= minDepth ? option.node(depth - minDepth).type\n : null;\n if (!next || (next.name != part && !next.isInGroup(part)))\n return false;\n depth--;\n }\n }\n return true;\n };\n return match(parts.length - 1, this.open);\n }\n textblockFromContext() {\n let $context = this.options.context;\n if ($context)\n for (let d = $context.depth; d >= 0; d--) {\n let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;\n if (deflt && deflt.isTextblock && deflt.defaultAttrs)\n return deflt;\n }\n for (let name in this.parser.schema.nodes) {\n let type = this.parser.schema.nodes[name];\n if (type.isTextblock && type.defaultAttrs)\n return type;\n }\n }\n}\n// Kludge to work around directly nested list nodes produced by some\n// tools and allowed by browsers to mean that the nested list is\n// actually part of the list item above it.\nfunction normalizeList(dom) {\n for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {\n let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;\n if (name && listTags.hasOwnProperty(name) && prevItem) {\n prevItem.appendChild(child);\n child = prevItem;\n }\n else if (name == \"li\") {\n prevItem = child;\n }\n else if (name) {\n prevItem = null;\n }\n }\n}\n// Apply a CSS selector.\nfunction matches(dom, selector) {\n return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);\n}\nfunction copy(obj) {\n let copy = {};\n for (let prop in obj)\n copy[prop] = obj[prop];\n return copy;\n}\n// Used when finding a mark at the top level of a fragment parse.\n// Checks whether it would be reasonable to apply a given mark type to\n// a given node, by looking at the way the mark occurs in the schema.\nfunction markMayApply(markType, nodeType) {\n let nodes = nodeType.schema.nodes;\n for (let name in nodes) {\n let parent = nodes[name];\n if (!parent.allowsMarkType(markType))\n continue;\n let seen = [], scan = (match) => {\n seen.push(match);\n for (let i = 0; i < match.edgeCount; i++) {\n let { type, next } = match.edge(i);\n if (type == nodeType)\n return true;\n if (seen.indexOf(next) < 0 && scan(next))\n return true;\n }\n };\n if (scan(parent.contentMatch))\n return true;\n }\n}\n\n/**\nA DOM serializer knows how to convert ProseMirror nodes and\nmarks of various types to DOM nodes.\n*/\nclass DOMSerializer {\n /**\n Create a serializer. `nodes` should map node names to functions\n that take a node and return a description of the corresponding\n DOM. `marks` does the same for mark names, but also gets an\n argument that tells it whether the mark's content is block or\n inline content (for typical use, it'll always be inline). A mark\n serializer may be `null` to indicate that marks of that type\n should not be serialized.\n */\n constructor(\n /**\n The node serialization functions.\n */\n nodes, \n /**\n The mark serialization functions.\n */\n marks) {\n this.nodes = nodes;\n this.marks = marks;\n }\n /**\n Serialize the content of this fragment to a DOM fragment. When\n not in the browser, the `document` option, containing a DOM\n document, should be passed so that the serializer can create\n nodes.\n */\n serializeFragment(fragment, options = {}, target) {\n if (!target)\n target = doc(options).createDocumentFragment();\n let top = target, active = [];\n fragment.forEach(node => {\n if (active.length || node.marks.length) {\n let keep = 0, rendered = 0;\n while (keep < active.length && rendered < node.marks.length) {\n let next = node.marks[rendered];\n if (!this.marks[next.type.name]) {\n rendered++;\n continue;\n }\n if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)\n break;\n keep++;\n rendered++;\n }\n while (keep < active.length)\n top = active.pop()[1];\n while (rendered < node.marks.length) {\n let add = node.marks[rendered++];\n let markDOM = this.serializeMark(add, node.isInline, options);\n if (markDOM) {\n active.push([add, top]);\n top.appendChild(markDOM.dom);\n top = markDOM.contentDOM || markDOM.dom;\n }\n }\n }\n top.appendChild(this.serializeNodeInner(node, options));\n });\n return target;\n }\n /**\n @internal\n */\n serializeNodeInner(node, options) {\n if (node.isText)\n return doc(options).createTextNode(node.text);\n let { dom, contentDOM } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs);\n if (contentDOM) {\n if (node.isLeaf)\n throw new RangeError(\"Content hole not allowed in a leaf node spec\");\n this.serializeFragment(node.content, options, contentDOM);\n }\n return dom;\n }\n /**\n Serialize this node to a DOM node. This can be useful when you\n need to serialize a part of a document, as opposed to the whole\n document. To serialize a whole document, use\n [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on\n its [content](https://prosemirror.net/docs/ref/#model.Node.content).\n */\n serializeNode(node, options = {}) {\n let dom = this.serializeNodeInner(node, options);\n for (let i = node.marks.length - 1; i >= 0; i--) {\n let wrap = this.serializeMark(node.marks[i], node.isInline, options);\n if (wrap) {\n (wrap.contentDOM || wrap.dom).appendChild(dom);\n dom = wrap.dom;\n }\n }\n return dom;\n }\n /**\n @internal\n */\n serializeMark(mark, inline, options = {}) {\n let toDOM = this.marks[mark.type.name];\n return toDOM && renderSpec(doc(options), toDOM(mark, inline), null, mark.attrs);\n }\n static renderSpec(doc, structure, xmlNS = null, blockArraysIn) {\n // Kludge for backwards-compatibility with accidental original behavious\n if (typeof structure == \"string\")\n return { dom: doc.createTextNode(structure) };\n return renderSpec(doc, structure, xmlNS, blockArraysIn);\n }\n /**\n Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)\n properties in a schema's node and mark specs.\n */\n static fromSchema(schema) {\n return schema.cached.domSerializer ||\n (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));\n }\n /**\n Gather the serializers in a schema's node specs into an object.\n This can be useful as a base to build a custom serializer from.\n */\n static nodesFromSchema(schema) {\n let result = gatherToDOM(schema.nodes);\n if (!result.text)\n result.text = node => node.text;\n return result;\n }\n /**\n Gather the serializers in a schema's mark specs into an object.\n */\n static marksFromSchema(schema) {\n return gatherToDOM(schema.marks);\n }\n}\nfunction gatherToDOM(obj) {\n let result = {};\n for (let name in obj) {\n let toDOM = obj[name].spec.toDOM;\n if (toDOM)\n result[name] = toDOM;\n }\n return result;\n}\nfunction doc(options) {\n return options.document || window.document;\n}\nconst suspiciousAttributeCache = new WeakMap();\nfunction suspiciousAttributes(attrs) {\n let value = suspiciousAttributeCache.get(attrs);\n if (value === undefined)\n suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs));\n return value;\n}\nfunction suspiciousAttributesInner(attrs) {\n let result = null;\n function scan(value) {\n if (value && typeof value == \"object\") {\n if (Array.isArray(value)) {\n if (typeof value[0] == \"string\") {\n if (!result)\n result = [];\n result.push(value);\n }\n else {\n for (let i = 0; i < value.length; i++)\n scan(value[i]);\n }\n }\n else {\n for (let prop in value)\n scan(value[prop]);\n }\n }\n }\n scan(attrs);\n return result;\n}\nfunction renderSpec(doc, structure, xmlNS, blockArraysIn) {\n if (structure.nodeType == 1)\n return { dom: structure };\n if (structure.dom && structure.dom.nodeType == 1)\n return structure;\n let tagName = structure[0], suspicious;\n if (typeof tagName != \"string\")\n throw new RangeError(\"Invalid array passed to renderSpec\");\n if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) &&\n suspicious.indexOf(structure) > -1)\n throw new RangeError(\"Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.\");\n let space = tagName.indexOf(\" \");\n if (space > 0) {\n xmlNS = tagName.slice(0, space);\n tagName = tagName.slice(space + 1);\n }\n let contentDOM;\n let dom = (xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName));\n let attrs = structure[1], start = 1;\n if (attrs && typeof attrs == \"object\" && attrs.nodeType == null && !Array.isArray(attrs)) {\n start = 2;\n for (let name in attrs)\n if (attrs[name] != null) {\n let space = name.indexOf(\" \");\n if (space > 0)\n dom.setAttributeNS(name.slice(0, space), name.slice(space + 1), attrs[name]);\n else if (name == \"style\" && dom.style)\n dom.style.cssText = attrs[name];\n else\n dom.setAttribute(name, attrs[name]);\n }\n }\n for (let i = start; i < structure.length; i++) {\n let child = structure[i];\n if (child === 0) {\n if (i < structure.length - 1 || i > start)\n throw new RangeError(\"Content hole must be the only child of its parent node\");\n return { dom, contentDOM: dom };\n }\n else if (typeof child == \"string\") {\n dom.appendChild(doc.createTextNode(child));\n }\n else {\n let { dom: inner, contentDOM: innerContent } = renderSpec(doc, child, xmlNS, blockArraysIn);\n dom.appendChild(inner);\n if (innerContent) {\n if (contentDOM)\n throw new RangeError(\"Multiple content holes\");\n contentDOM = innerContent;\n }\n }\n }\n return { dom, contentDOM };\n}\n\nexport { ContentMatch, DOMParser, DOMSerializer, Fragment, Mark, MarkType, Node, NodeRange, NodeType, ReplaceError, ResolvedPos, Schema, Slice };\n", - "import { ReplaceError, Slice, Mark, Fragment, MarkType } from 'prosemirror-model';\n\n// Recovery values encode a range index and an offset. They are\n// represented as numbers, because tons of them will be created when\n// mapping, for example, a large number of decorations. The number's\n// lower 16 bits provide the index, the remaining bits the offset.\n//\n// Note: We intentionally don't use bit shift operators to en- and\n// decode these, since those clip to 32 bits, which we might in rare\n// cases want to overflow. A 64-bit float can represent 48-bit\n// integers precisely.\nconst lower16 = 0xffff;\nconst factor16 = Math.pow(2, 16);\nfunction makeRecover(index, offset) { return index + offset * factor16; }\nfunction recoverIndex(value) { return value & lower16; }\nfunction recoverOffset(value) { return (value - (value & lower16)) / factor16; }\nconst DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8;\n/**\nAn object representing a mapped position with extra\ninformation.\n*/\nclass MapResult {\n /**\n @internal\n */\n constructor(\n /**\n The mapped version of the position.\n */\n pos, \n /**\n @internal\n */\n delInfo, \n /**\n @internal\n */\n recover) {\n this.pos = pos;\n this.delInfo = delInfo;\n this.recover = recover;\n }\n /**\n Tells you whether the position was deleted, that is, whether the\n step removed the token on the side queried (via the `assoc`)\n argument from the document.\n */\n get deleted() { return (this.delInfo & DEL_SIDE) > 0; }\n /**\n Tells you whether the token before the mapped position was deleted.\n */\n get deletedBefore() { return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; }\n /**\n True when the token after the mapped position was deleted.\n */\n get deletedAfter() { return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; }\n /**\n Tells whether any of the steps mapped through deletes across the\n position (including both the token before and after the\n position).\n */\n get deletedAcross() { return (this.delInfo & DEL_ACROSS) > 0; }\n}\n/**\nA map describing the deletions and insertions made by a step, which\ncan be used to find the correspondence between positions in the\npre-step version of a document and the same position in the\npost-step version.\n*/\nclass StepMap {\n /**\n Create a position map. The modifications to the document are\n represented as an array of numbers, in which each group of three\n represents a modified chunk as `[start, oldSize, newSize]`.\n */\n constructor(\n /**\n @internal\n */\n ranges, \n /**\n @internal\n */\n inverted = false) {\n this.ranges = ranges;\n this.inverted = inverted;\n if (!ranges.length && StepMap.empty)\n return StepMap.empty;\n }\n /**\n @internal\n */\n recover(value) {\n let diff = 0, index = recoverIndex(value);\n if (!this.inverted)\n for (let i = 0; i < index; i++)\n diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];\n return this.ranges[index * 3] + diff + recoverOffset(value);\n }\n mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n map(pos, assoc = 1) { return this._map(pos, assoc, true); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;\n if (pos <= end) {\n let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;\n let result = start + diff + (side < 0 ? 0 : newSize);\n if (simple)\n return result;\n let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);\n let del = 0;\n if (oldSize) {\n del |= pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;\n if (assoc < 0 ? pos != start : pos != end)\n del |= DEL_SIDE;\n }\n return new MapResult(result, del, recover);\n }\n diff += newSize - oldSize;\n }\n return simple ? pos + diff : new MapResult(pos + diff, 0, null);\n }\n /**\n @internal\n */\n touches(pos, recover) {\n let diff = 0, index = recoverIndex(recover);\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], end = start + oldSize;\n if (pos <= end && i == index * 3)\n return true;\n diff += this.ranges[i + newIndex] - oldSize;\n }\n return false;\n }\n /**\n Calls the given function on each of the changed ranges included in\n this map.\n */\n forEach(f) {\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0, diff = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);\n let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];\n f(oldStart, oldStart + oldSize, newStart, newStart + newSize);\n diff += newSize - oldSize;\n }\n }\n /**\n Create an inverted version of this map. The result can be used to\n map positions in the post-step document to the pre-step document.\n */\n invert() {\n return new StepMap(this.ranges, !this.inverted);\n }\n /**\n @internal\n */\n toString() {\n return (this.inverted ? \"-\" : \"\") + JSON.stringify(this.ranges);\n }\n /**\n Create a map that moves all positions by offset `n` (which may be\n negative). This can be useful when applying steps meant for a\n sub-document to a larger document, or vice-versa.\n */\n static offset(n) {\n return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);\n }\n}\n/**\nA StepMap that contains no changed ranges.\n*/\nStepMap.empty = new StepMap([]);\n/**\nA mapping represents a pipeline of zero or more [step\nmaps](https://prosemirror.net/docs/ref/#transform.StepMap). It has special provisions for losslessly\nhandling mapping positions through a series of steps in which some\nsteps are inverted versions of earlier steps. (This comes up when\n‘[rebasing](https://prosemirror.net/docs/guide/#transform.rebasing)’ steps for\ncollaboration or history management.)\n*/\nclass Mapping {\n /**\n Create a new mapping with the given position maps.\n */\n constructor(maps, \n /**\n @internal\n */\n mirror, \n /**\n The starting position in the `maps` array, used when `map` or\n `mapResult` is called.\n */\n from = 0, \n /**\n The end position in the `maps` array.\n */\n to = maps ? maps.length : 0) {\n this.mirror = mirror;\n this.from = from;\n this.to = to;\n this._maps = maps || [];\n this.ownData = !(maps || mirror);\n }\n /**\n The step maps in this mapping.\n */\n get maps() { return this._maps; }\n /**\n Create a mapping that maps only through a part of this one.\n */\n slice(from = 0, to = this.maps.length) {\n return new Mapping(this._maps, this.mirror, from, to);\n }\n /**\n Add a step map to the end of this mapping. If `mirrors` is\n given, it should be the index of the step map that is the mirror\n image of this one.\n */\n appendMap(map, mirrors) {\n if (!this.ownData) {\n this._maps = this._maps.slice();\n this.mirror = this.mirror && this.mirror.slice();\n this.ownData = true;\n }\n this.to = this._maps.push(map);\n if (mirrors != null)\n this.setMirror(this._maps.length - 1, mirrors);\n }\n /**\n Add all the step maps in a given mapping to this one (preserving\n mirroring information).\n */\n appendMapping(mapping) {\n for (let i = 0, startSize = this._maps.length; i < mapping._maps.length; i++) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping._maps[i], mirr != null && mirr < i ? startSize + mirr : undefined);\n }\n }\n /**\n Finds the offset of the step map that mirrors the map at the\n given offset, in this mapping (as per the second argument to\n `appendMap`).\n */\n getMirror(n) {\n if (this.mirror)\n for (let i = 0; i < this.mirror.length; i++)\n if (this.mirror[i] == n)\n return this.mirror[i + (i % 2 ? -1 : 1)];\n }\n /**\n @internal\n */\n setMirror(n, m) {\n if (!this.mirror)\n this.mirror = [];\n this.mirror.push(n, m);\n }\n /**\n Append the inverse of the given mapping to this one.\n */\n appendMappingInverted(mapping) {\n for (let i = mapping.maps.length - 1, totalSize = this._maps.length + mapping._maps.length; i >= 0; i--) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping._maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : undefined);\n }\n }\n /**\n Create an inverted version of this mapping.\n */\n invert() {\n let inverse = new Mapping;\n inverse.appendMappingInverted(this);\n return inverse;\n }\n /**\n Map a position through this mapping.\n */\n map(pos, assoc = 1) {\n if (this.mirror)\n return this._map(pos, assoc, true);\n for (let i = this.from; i < this.to; i++)\n pos = this._maps[i].map(pos, assoc);\n return pos;\n }\n /**\n Map a position through this mapping, returning a mapping\n result.\n */\n mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let delInfo = 0;\n for (let i = this.from; i < this.to; i++) {\n let map = this._maps[i], result = map.mapResult(pos, assoc);\n if (result.recover != null) {\n let corr = this.getMirror(i);\n if (corr != null && corr > i && corr < this.to) {\n i = corr;\n pos = this._maps[corr].recover(result.recover);\n continue;\n }\n }\n delInfo |= result.delInfo;\n pos = result.pos;\n }\n return simple ? pos : new MapResult(pos, delInfo, null);\n }\n}\n\nconst stepsByID = Object.create(null);\n/**\nA step object represents an atomic change. It generally applies\nonly to the document it was created for, since the positions\nstored in it will only make sense for that document.\n\nNew steps are defined by creating classes that extend `Step`,\noverriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`\nmethods, and registering your class with a unique\nJSON-serialization identifier using\n[`Step.jsonID`](https://prosemirror.net/docs/ref/#transform.Step^jsonID).\n*/\nclass Step {\n /**\n Get the step map that represents the changes made by this step,\n and which can be used to transform between positions in the old\n and the new document.\n */\n getMap() { return StepMap.empty; }\n /**\n Try to merge this step with another one, to be applied directly\n after it. Returns the merged step when possible, null if the\n steps can't be merged.\n */\n merge(other) { return null; }\n /**\n Deserialize a step from its JSON representation. Will call\n through to the step class' own implementation of this method.\n */\n static fromJSON(schema, json) {\n if (!json || !json.stepType)\n throw new RangeError(\"Invalid input for Step.fromJSON\");\n let type = stepsByID[json.stepType];\n if (!type)\n throw new RangeError(`No step type ${json.stepType} defined`);\n return type.fromJSON(schema, json);\n }\n /**\n To be able to serialize steps to JSON, each step needs a string\n ID to attach to its JSON representation. Use this method to\n register an ID for your step classes. Try to pick something\n that's unlikely to clash with steps from other modules.\n */\n static jsonID(id, stepClass) {\n if (id in stepsByID)\n throw new RangeError(\"Duplicate use of step JSON ID \" + id);\n stepsByID[id] = stepClass;\n stepClass.prototype.jsonID = id;\n return stepClass;\n }\n}\n/**\nThe result of [applying](https://prosemirror.net/docs/ref/#transform.Step.apply) a step. Contains either a\nnew document or a failure value.\n*/\nclass StepResult {\n /**\n @internal\n */\n constructor(\n /**\n The transformed document, if successful.\n */\n doc, \n /**\n The failure message, if unsuccessful.\n */\n failed) {\n this.doc = doc;\n this.failed = failed;\n }\n /**\n Create a successful step result.\n */\n static ok(doc) { return new StepResult(doc, null); }\n /**\n Create a failed step result.\n */\n static fail(message) { return new StepResult(null, message); }\n /**\n Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given\n arguments. Create a successful result if it succeeds, and a\n failed one if it throws a `ReplaceError`.\n */\n static fromReplace(doc, from, to, slice) {\n try {\n return StepResult.ok(doc.replace(from, to, slice));\n }\n catch (e) {\n if (e instanceof ReplaceError)\n return StepResult.fail(e.message);\n throw e;\n }\n }\n}\n\nfunction mapFragment(fragment, f, parent) {\n let mapped = [];\n for (let i = 0; i < fragment.childCount; i++) {\n let child = fragment.child(i);\n if (child.content.size)\n child = child.copy(mapFragment(child.content, f, child));\n if (child.isInline)\n child = f(child, parent, i);\n mapped.push(child);\n }\n return Fragment.fromArray(mapped);\n}\n/**\nAdd a mark to all inline content between two positions.\n*/\nclass AddMarkStep extends Step {\n /**\n Create a mark step.\n */\n constructor(\n /**\n The start of the marked range.\n */\n from, \n /**\n The end of the marked range.\n */\n to, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from);\n let parent = $from.node($from.sharedDepth(this.to));\n let slice = new Slice(mapFragment(oldSlice.content, (node, parent) => {\n if (!node.isAtom || !parent.type.allowsMarkType(this.mark.type))\n return node;\n return node.mark(this.mark.addToSet(node.marks));\n }, parent), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert(doc) {\n let steps = [];\n doc.nodesBetween(this.from, this.to, (node, pos) => {\n if (node.isInline && node.isAtom) {\n let added = this.mark.addToSet(node.marks);\n if (!Mark.sameSet(added, node.marks)) {\n let from = Math.max(this.from, pos), to = Math.min(this.to, pos + node.nodeSize);\n pushMarkStep(RemoveMarkStep, from, to, this.mark, steps);\n for (let mark of node.marks)\n if (!mark.isInSet(added))\n pushMarkStep(AddMarkStep, from, to, mark, steps);\n }\n }\n });\n return steps.length == 1 ? steps[0] : new MarkSetStep(steps);\n }\n map(mapping) {\n let from = mapping.map(this.from, 1), to = mapping.map(this.to, -1);\n if (from >= to)\n return null;\n return new AddMarkStep(from, to, this.mark);\n }\n merge(other) {\n if (other instanceof AddMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"addMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for AddMarkStep.fromJSON\");\n return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addMark\", AddMarkStep);\n/**\nRemove a mark from all inline content between two positions.\n*/\nclass RemoveMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The start of the unmarked range.\n */\n from, \n /**\n The end of the unmarked range.\n */\n to, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to);\n let slice = new Slice(mapFragment(oldSlice.content, node => {\n return node.mark(this.mark.removeFromSet(node.marks));\n }, doc), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert(doc) {\n let steps = [];\n doc.nodesBetween(this.from, this.to, (node, pos) => {\n if (node.isInline && node.isAtom && this.mark.isInSet(node.marks))\n pushMarkStep(AddMarkStep, Math.max(this.from, pos), Math.min(this.to, pos + node.nodeSize), this.mark, steps);\n });\n return steps.length == 1 ? steps[0] : new MarkSetStep(steps);\n }\n map(mapping) {\n let from = mapping.map(this.from, 1), to = mapping.map(this.to, -1);\n if (from >= to)\n return null;\n return new RemoveMarkStep(from, to, this.mark);\n }\n merge(other) {\n if (other instanceof RemoveMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"removeMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for RemoveMarkStep.fromJSON\");\n return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeMark\", RemoveMarkStep);\nfunction pushMarkStep(cls, from, to, mark, target) {\n let last = target.length ? target[target.length - 1] : null;\n if (last && last instanceof cls && last.to == from && last.mark.eq(mark)) {\n target[target.length - 1] = new cls(last.from, to, mark);\n }\n else {\n target.push(new cls(from, to, mark));\n }\n}\nclass MarkSetStep extends Step {\n constructor(steps) {\n super();\n this.steps = steps;\n }\n apply(doc) {\n for (let step of this.steps) {\n let result = step.apply(doc);\n if (!result.doc)\n return result;\n doc = result.doc;\n }\n return new StepResult(doc, null);\n }\n invert(doc) {\n return new MarkSetStep(this.steps.map(s => s.invert(doc)));\n }\n map(mapping) {\n let result = [];\n for (let step of this.steps) {\n let mapped = step.map(mapping);\n if (mapped)\n result.push(mapped);\n }\n return result.length ? new MarkSetStep(result) : null;\n }\n toJSON() {\n return { stepType: \"markSet\", steps: this.steps.map(s => s.toJSON()) };\n }\n static fromJSON(schema, json) {\n if (!Array.isArray(json.steps) || !json.steps.every((s) => s.stepType == \"addMark\" || s.stepType == \"removeMark\"))\n throw new RangeError(\"Invalid JSON for MarkSetStep\");\n return new MarkSetStep(json.steps.map((s) => Step.fromJSON(schema, s)));\n }\n}\nStep.jsonID(\"markSet\", MarkSetStep);\n/**\nAdd a mark to a specific node.\n*/\nclass AddNodeMarkStep extends Step {\n /**\n Create a node mark step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (node) {\n let newSet = this.mark.addToSet(node.marks);\n if (newSet.length == node.marks.length) {\n for (let i = 0; i < node.marks.length; i++)\n if (!node.marks[i].isInSet(newSet))\n return new AddNodeMarkStep(this.pos, node.marks[i]);\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n }\n return new RemoveNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"addNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for AddNodeMarkStep.fromJSON\");\n return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addNodeMark\", AddNodeMarkStep);\n/**\nRemove a mark from a specific node.\n*/\nclass RemoveNodeMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node || !this.mark.isInSet(node.marks))\n return this;\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"removeNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for RemoveNodeMarkStep.fromJSON\");\n return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeNodeMark\", RemoveNodeMarkStep);\n\n/**\nReplace a part of the document with a slice of new content.\n*/\nclass ReplaceStep extends Step {\n /**\n The given `slice` should fit the 'gap' between `from` and\n `to`—the depths must line up, and the surrounding nodes must be\n able to be joined with the open sides of the slice. When\n `structure` is true, the step will fail if the content between\n from and to is not just a sequence of closing and then opening\n tokens (this is to guard against rebased replace steps\n overwriting something they weren't supposed to).\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The slice to insert.\n */\n slice, \n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.slice = slice;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && contentBetween(doc, this.from, this.to))\n return StepResult.fail(\"Structure replace would overwrite content\");\n return StepResult.fromReplace(doc, this.from, this.to, this.slice);\n }\n getMap() {\n return new StepMap([this.from, this.to - this.from, this.slice.size]);\n }\n invert(doc) {\n return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to));\n }\n map(mapping) {\n let to = mapping.mapResult(this.to, -1);\n let from = this.from == this.to && ReplaceStep.MAP_BIAS < 0 ? to : mapping.mapResult(this.from, 1);\n if (from.deletedAcross && to.deletedAcross)\n return null;\n return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice, this.structure);\n }\n merge(other) {\n if (!(other instanceof ReplaceStep) || other.structure || this.structure)\n return null;\n if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);\n return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure);\n }\n else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);\n return new ReplaceStep(other.from, this.to, slice, this.structure);\n }\n else {\n return null;\n }\n }\n toJSON() {\n let json = { stepType: \"replace\", from: this.from, to: this.to };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for ReplaceStep.fromJSON\");\n return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure);\n }\n}\n/**\nBy default, for backwards compatibility, an inserting step\nmapped over an insertion at that same position fill move after\nthe inserted content. In a collaborative editing situation, that\ncan make redone insertions appear in unexpected places. You can\nset this to -1 to make such mapping keep the step before the\ninsertion instead.\n*/\nReplaceStep.MAP_BIAS = 1;\nStep.jsonID(\"replace\", ReplaceStep);\n/**\nReplace a part of the document with a slice of content, but\npreserve a range of the replaced content by moving it into the\nslice.\n*/\nclass ReplaceAroundStep extends Step {\n /**\n Create a replace-around step with the given range and gap.\n `insert` should be the point in the slice into which the content\n of the gap should be moved. `structure` has the same meaning as\n it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The start of preserved range.\n */\n gapFrom, \n /**\n The end of preserved range.\n */\n gapTo, \n /**\n The slice to insert.\n */\n slice, \n /**\n The position in the slice where the preserved range should be\n inserted.\n */\n insert, \n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.gapFrom = gapFrom;\n this.gapTo = gapTo;\n this.slice = slice;\n this.insert = insert;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && (contentBetween(doc, this.from, this.gapFrom) ||\n contentBetween(doc, this.gapTo, this.to)))\n return StepResult.fail(\"Structure gap-replace would overwrite content\");\n let gap = doc.slice(this.gapFrom, this.gapTo);\n if (gap.openStart || gap.openEnd)\n return StepResult.fail(\"Gap is not a flat range\");\n let inserted = this.slice.insertAt(this.insert, gap.content);\n if (!inserted)\n return StepResult.fail(\"Content does not fit in gap\");\n return StepResult.fromReplace(doc, this.from, this.to, inserted);\n }\n getMap() {\n return new StepMap([this.from, this.gapFrom - this.from, this.insert,\n this.gapTo, this.to - this.gapTo, this.slice.size - this.insert]);\n }\n invert(doc) {\n let gap = this.gapTo - this.gapFrom;\n return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n let gapFrom = this.from == this.gapFrom ? from.pos : mapping.map(this.gapFrom, -1);\n let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);\n if ((from.deletedAcross && to.deletedAcross) || gapFrom < from.pos || gapTo > to.pos)\n return null;\n return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);\n }\n toJSON() {\n let json = { stepType: \"replaceAround\", from: this.from, to: this.to,\n gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\" ||\n typeof json.gapFrom != \"number\" || typeof json.gapTo != \"number\" || typeof json.insert != \"number\")\n throw new RangeError(\"Invalid input for ReplaceAroundStep.fromJSON\");\n return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);\n }\n}\nStep.jsonID(\"replaceAround\", ReplaceAroundStep);\nfunction contentBetween(doc, from, to) {\n let $from = doc.resolve(from), dist = to - from, depth = $from.depth;\n while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {\n depth--;\n dist--;\n }\n if (dist > 0) {\n let next = $from.node(depth).maybeChild($from.indexAfter(depth));\n while (dist > 0) {\n if (!next || next.isLeaf)\n return true;\n next = next.firstChild;\n dist--;\n }\n }\n return false;\n}\n\nfunction addMark(tr, from, to, mark) {\n let added = [];\n tr.doc.nodesBetween(from, to, (node, pos, parent) => {\n if (!node.isInline)\n return;\n let marks = node.marks;\n if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {\n let start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to);\n pushMarkStep(AddMarkStep, start, end, mark, added);\n }\n });\n added.forEach(s => tr.step(s));\n}\nfunction removeMark(tr, from, to, mark) {\n let matched = [], step = 0;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isInline || !node.isAtom)\n return;\n step++;\n let toRemove = null;\n if (mark instanceof MarkType) {\n let set = node.marks, found;\n while (found = mark.isInSet(set)) {\n (toRemove || (toRemove = [])).push(found);\n set = found.removeFromSet(set);\n }\n }\n else if (mark) {\n if (mark.isInSet(node.marks))\n toRemove = [mark];\n }\n else {\n toRemove = node.marks;\n }\n if (toRemove && toRemove.length) {\n let end = Math.min(pos + node.nodeSize, to);\n for (let i = 0; i < toRemove.length; i++) {\n let style = toRemove[i], found;\n for (let j = 0; j < matched.length; j++) {\n let m = matched[j];\n if (m.step == step - 1 && style.eq(matched[j].style))\n found = m;\n }\n if (found) {\n found.to = end;\n found.step = step;\n }\n else {\n matched.push({ style, from: Math.max(pos, from), to: end, step });\n }\n }\n }\n });\n matched.forEach(m => tr.step(new RemoveMarkStep(m.from, m.to, m.style)));\n}\nfunction clearIncompatible(tr, pos, parentType, match = parentType.contentMatch, clearNewlines = true) {\n let node = tr.doc.nodeAt(pos);\n let replSteps = [], cur = pos + 1;\n for (let i = 0; i < node.childCount; i++) {\n let child = node.child(i), end = cur + child.nodeSize;\n let allowed = match.matchType(child.type);\n if (!allowed) {\n replSteps.push(new ReplaceStep(cur, end, Slice.empty));\n }\n else {\n match = allowed;\n for (let j = 0; j < child.marks.length; j++)\n if (!parentType.allowsMarkType(child.marks[j].type))\n tr.step(new RemoveMarkStep(cur, end, child.marks[j]));\n if (clearNewlines && child.isText && parentType.whitespace != \"pre\") {\n let m, newline = /\\r?\\n|\\r/g, slice;\n while (m = newline.exec(child.text)) {\n if (!slice)\n slice = new Slice(Fragment.from(parentType.schema.text(\" \", parentType.allowedMarks(child.marks))), 0, 0);\n replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice));\n }\n }\n }\n cur = end;\n }\n if (!match.validEnd) {\n let fill = match.fillBefore(Fragment.empty, true);\n tr.replace(cur, cur, new Slice(fill, 0, 0));\n }\n for (let i = replSteps.length - 1; i >= 0; i--)\n tr.step(replSteps[i]);\n}\n\nfunction canCut(node, start, end) {\n return (start == 0 || node.canReplace(start, node.childCount)) &&\n (end == node.childCount || node.canReplace(0, end));\n}\n/**\nTry to find a target depth to which the content in the given range\ncan be lifted. Will not go across\n[isolating](https://prosemirror.net/docs/ref/#model.NodeSpec.isolating) parent nodes.\n*/\nfunction liftTarget(range) {\n let parent = range.parent;\n let content = parent.content.cutByIndex(range.startIndex, range.endIndex);\n for (let depth = range.depth, contentBefore = 0, contentAfter = 0;; --depth) {\n let node = range.$from.node(depth);\n let index = range.$from.index(depth) + contentBefore, endIndex = range.$to.indexAfter(depth) - contentAfter;\n if (depth < range.depth && node.canReplace(index, endIndex, content))\n return depth;\n if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex))\n break;\n if (index)\n contentBefore = 1;\n if (endIndex < node.childCount)\n contentAfter = 1;\n }\n return null;\n}\nfunction lift(tr, range, target) {\n let { $from, $to, depth } = range;\n let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);\n let start = gapStart, end = gapEnd;\n let before = Fragment.empty, openStart = 0;\n for (let d = depth, splitting = false; d > target; d--)\n if (splitting || $from.index(d) > 0) {\n splitting = true;\n before = Fragment.from($from.node(d).copy(before));\n openStart++;\n }\n else {\n start--;\n }\n let after = Fragment.empty, openEnd = 0;\n for (let d = depth, splitting = false; d > target; d--)\n if (splitting || $to.after(d + 1) < $to.end(d)) {\n splitting = true;\n after = Fragment.from($to.node(d).copy(after));\n openEnd++;\n }\n else {\n end++;\n }\n tr.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));\n}\n/**\nTry to find a valid way to wrap the content in the given range in a\nnode of the given type. May introduce extra nodes around and inside\nthe wrapper node, if necessary. Returns null if no valid wrapping\ncould be found. When `innerRange` is given, that range's content is\nused as the content to fit into the wrapping, instead of the\ncontent of `range`.\n*/\nfunction findWrapping(range, nodeType, attrs = null, innerRange = range) {\n let around = findWrappingOutside(range, nodeType);\n let inner = around && findWrappingInside(innerRange, nodeType);\n if (!inner)\n return null;\n return around.map(withAttrs)\n .concat({ type: nodeType, attrs }).concat(inner.map(withAttrs));\n}\nfunction withAttrs(type) { return { type, attrs: null }; }\nfunction findWrappingOutside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let around = parent.contentMatchAt(startIndex).findWrapping(type);\n if (!around)\n return null;\n let outer = around.length ? around[0] : type;\n return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;\n}\nfunction findWrappingInside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let inner = parent.child(startIndex);\n let inside = type.contentMatch.findWrapping(inner.type);\n if (!inside)\n return null;\n let lastType = inside.length ? inside[inside.length - 1] : type;\n let innerMatch = lastType.contentMatch;\n for (let i = startIndex; innerMatch && i < endIndex; i++)\n innerMatch = innerMatch.matchType(parent.child(i).type);\n if (!innerMatch || !innerMatch.validEnd)\n return null;\n return inside;\n}\nfunction wrap(tr, range, wrappers) {\n let content = Fragment.empty;\n for (let i = wrappers.length - 1; i >= 0; i--) {\n if (content.size) {\n let match = wrappers[i].type.contentMatch.matchFragment(content);\n if (!match || !match.validEnd)\n throw new RangeError(\"Wrapper type given to Transform.wrap does not form valid content of its parent wrapper\");\n }\n content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n }\n let start = range.start, end = range.end;\n tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));\n}\nfunction setBlockType(tr, from, to, type, attrs) {\n if (!type.isTextblock)\n throw new RangeError(\"Type given to setBlockType should be a textblock\");\n let mapFrom = tr.steps.length;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n let attrsHere = typeof attrs == \"function\" ? attrs(node) : attrs;\n if (node.isTextblock && !node.hasMarkup(type, attrsHere) &&\n canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) {\n let convertNewlines = null;\n if (type.schema.linebreakReplacement) {\n let pre = type.whitespace == \"pre\", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n // Ensure all markup that isn't allowed in the new node type is cleared\n if (convertNewlines === false)\n replaceLinebreaks(tr, node, pos, mapFrom);\n clearIncompatible(tr, tr.mapping.slice(mapFrom).map(pos, 1), type, undefined, convertNewlines === null);\n let mapping = tr.mapping.slice(mapFrom);\n let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);\n tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true));\n if (convertNewlines === true)\n replaceNewlines(tr, node, pos, mapFrom);\n return false;\n }\n });\n}\nfunction replaceNewlines(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.isText) {\n let m, newline = /\\r?\\n|\\r/g;\n while (m = newline.exec(child.text)) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset + m.index);\n tr.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create());\n }\n }\n });\n}\nfunction replaceLinebreaks(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.type == child.type.schema.linebreakReplacement) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset);\n tr.replaceWith(start, start + 1, node.type.schema.text(\"\\n\"));\n }\n });\n}\nfunction canChangeType(doc, pos, type) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return $pos.parent.canReplaceWith(index, index + 1, type);\n}\n/**\nChange the type, attributes, and/or marks of the node at `pos`.\nWhen `type` isn't given, the existing node type is preserved,\n*/\nfunction setNodeMarkup(tr, pos, type, attrs, marks) {\n let node = tr.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at given position\");\n if (!type)\n type = node.type;\n let newNode = type.create(attrs, null, marks || node.marks);\n if (node.isLeaf)\n return tr.replaceWith(pos, pos + node.nodeSize, newNode);\n if (!type.validContent(node.content))\n throw new RangeError(\"Invalid content for node type \" + type.name);\n tr.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));\n}\n/**\nCheck whether splitting at the given position is allowed.\n*/\nfunction canSplit(doc, pos, depth = 1, typesAfter) {\n let $pos = doc.resolve(pos), base = $pos.depth - depth;\n let innerType = (typesAfter && typesAfter[typesAfter.length - 1]) || $pos.parent;\n if (base < 0 || $pos.parent.type.spec.isolating ||\n !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) ||\n !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))\n return false;\n for (let d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {\n let node = $pos.node(d), index = $pos.index(d);\n if (node.type.spec.isolating)\n return false;\n let rest = node.content.cutByIndex(index, node.childCount);\n let overrideChild = typesAfter && typesAfter[i + 1];\n if (overrideChild)\n rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));\n let after = (typesAfter && typesAfter[i]) || node;\n if (!node.canReplace(index + 1, node.childCount) || !after.type.validContent(rest))\n return false;\n }\n let index = $pos.indexAfter(base);\n let baseType = typesAfter && typesAfter[0];\n return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type);\n}\nfunction split(tr, pos, depth = 1, typesAfter) {\n let $pos = tr.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;\n for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {\n before = Fragment.from($pos.node(d).copy(before));\n let typeAfter = typesAfter && typesAfter[i];\n after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));\n }\n tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));\n}\n/**\nTest whether the blocks before and after a given position can be\njoined.\n*/\nfunction canJoin(doc, pos) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return joinable($pos.nodeBefore, $pos.nodeAfter) &&\n $pos.parent.canReplace(index, index + 1);\n}\nfunction canAppendWithSubstitutedLinebreaks(a, b) {\n if (!b.content.size)\n a.type.compatibleContent(b.type);\n let match = a.contentMatchAt(a.childCount);\n let { linebreakReplacement } = a.type.schema;\n for (let i = 0; i < b.childCount; i++) {\n let child = b.child(i);\n let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type;\n match = match.matchType(type);\n if (!match)\n return false;\n if (!a.type.allowsMarks(child.marks))\n return false;\n }\n return match.validEnd;\n}\nfunction joinable(a, b) {\n return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b));\n}\n/**\nFind an ancestor of the given position that can be joined to the\nblock before (or after if `dir` is positive). Returns the joinable\npoint, if any.\n*/\nfunction joinPoint(doc, pos, dir = -1) {\n let $pos = doc.resolve(pos);\n for (let d = $pos.depth;; d--) {\n let before, after, index = $pos.index(d);\n if (d == $pos.depth) {\n before = $pos.nodeBefore;\n after = $pos.nodeAfter;\n }\n else if (dir > 0) {\n before = $pos.node(d + 1);\n index++;\n after = $pos.node(d).maybeChild(index);\n }\n else {\n before = $pos.node(d).maybeChild(index - 1);\n after = $pos.node(d + 1);\n }\n if (before && !before.isTextblock && joinable(before, after) &&\n $pos.node(d).canReplace(index, index + 1))\n return pos;\n if (d == 0)\n break;\n pos = dir < 0 ? $pos.before(d) : $pos.after(d);\n }\n}\nfunction join(tr, pos, depth) {\n let convertNewlines = null;\n let { linebreakReplacement } = tr.doc.type.schema;\n let $before = tr.doc.resolve(pos - depth), beforeType = $before.node().type;\n if (linebreakReplacement && beforeType.inlineContent) {\n let pre = beforeType.whitespace == \"pre\";\n let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n let mapFrom = tr.steps.length;\n if (convertNewlines === false) {\n let $after = tr.doc.resolve(pos + depth);\n replaceLinebreaks(tr, $after.node(), $after.before(), mapFrom);\n }\n if (beforeType.inlineContent)\n clearIncompatible(tr, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null);\n let mapping = tr.mapping.slice(mapFrom), start = mapping.map(pos - depth);\n tr.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true));\n if (convertNewlines === true) {\n let $full = tr.doc.resolve(start);\n replaceNewlines(tr, $full.node(), $full.before(), tr.steps.length);\n }\n return tr;\n}\n/**\nTry to find a point where a node of the given type can be inserted\nnear `pos`, by searching up the node hierarchy when `pos` itself\nisn't a valid place but is at the start or end of a node. Return\nnull if no position was found.\n*/\nfunction insertPoint(doc, pos, nodeType) {\n let $pos = doc.resolve(pos);\n if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))\n return pos;\n if ($pos.parentOffset == 0)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.index(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.before(d + 1);\n if (index > 0)\n return null;\n }\n if ($pos.parentOffset == $pos.parent.content.size)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.indexAfter(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.after(d + 1);\n if (index < $pos.node(d).childCount)\n return null;\n }\n return null;\n}\n/**\nFinds a position at or around the given position where the given\nslice can be inserted. Will look at parent nodes' nearest boundary\nand try there, even if the original position wasn't directly at the\nstart or end of that node. Returns null when no position was found.\n*/\nfunction dropPoint(doc, pos, slice) {\n let $pos = doc.resolve(pos);\n if (!slice.content.size)\n return pos;\n let content = slice.content;\n for (let i = 0; i < slice.openStart; i++)\n content = content.firstChild.content;\n for (let pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {\n for (let d = $pos.depth; d >= 0; d--) {\n let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;\n let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);\n let parent = $pos.node(d), fits = false;\n if (pass == 1) {\n fits = parent.canReplace(insertPos, insertPos, content);\n }\n else {\n let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type);\n fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);\n }\n if (fits)\n return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);\n }\n }\n return null;\n}\n\n/**\n‘Fit’ a slice into a given position in the document, producing a\n[step](https://prosemirror.net/docs/ref/#transform.Step) that inserts it. Will return null if\nthere's no meaningful way to insert the slice here, or inserting it\nwould be a no-op (an empty slice over an empty range).\n*/\nfunction replaceStep(doc, from, to = from, slice = Slice.empty) {\n if (from == to && !slice.size)\n return null;\n let $from = doc.resolve(from), $to = doc.resolve(to);\n // Optimization -- avoid work if it's obvious that it's not needed.\n if (fitsTrivially($from, $to, slice))\n return new ReplaceStep(from, to, slice);\n return new Fitter($from, $to, slice).fit();\n}\nfunction fitsTrivially($from, $to, slice) {\n return !slice.openStart && !slice.openEnd && $from.start() == $to.start() &&\n $from.parent.canReplace($from.index(), $to.index(), slice.content);\n}\n// Algorithm for 'placing' the elements of a slice into a gap:\n//\n// We consider the content of each node that is open to the left to be\n// independently placeable. I.e. in , when the\n// paragraph on the left is open, \"foo\" can be placed (somewhere on\n// the left side of the replacement gap) independently from p(\"bar\").\n//\n// This class tracks the state of the placement progress in the\n// following properties:\n//\n// - `frontier` holds a stack of `{type, match}` objects that\n// represent the open side of the replacement. It starts at\n// `$from`, then moves forward as content is placed, and is finally\n// reconciled with `$to`.\n//\n// - `unplaced` is a slice that represents the content that hasn't\n// been placed yet.\n//\n// - `placed` is a fragment of placed content. Its open-start value\n// is implicit in `$from`, and its open-end value in `frontier`.\nclass Fitter {\n constructor($from, $to, unplaced) {\n this.$from = $from;\n this.$to = $to;\n this.unplaced = unplaced;\n this.frontier = [];\n this.placed = Fragment.empty;\n for (let i = 0; i <= $from.depth; i++) {\n let node = $from.node(i);\n this.frontier.push({\n type: node.type,\n match: node.contentMatchAt($from.indexAfter(i))\n });\n }\n for (let i = $from.depth; i > 0; i--)\n this.placed = Fragment.from($from.node(i).copy(this.placed));\n }\n get depth() { return this.frontier.length - 1; }\n fit() {\n // As long as there's unplaced content, try to place some of it.\n // If that fails, either increase the open score of the unplaced\n // slice, or drop nodes from it, and then try again.\n while (this.unplaced.size) {\n let fit = this.findFittable();\n if (fit)\n this.placeNodes(fit);\n else\n this.openMore() || this.dropNode();\n }\n // When there's inline content directly after the frontier _and_\n // directly after `this.$to`, we must generate a `ReplaceAround`\n // step that pulls that content into the node after the frontier.\n // That means the fitting must be done to the end of the textblock\n // node after `this.$to`, not `this.$to` itself.\n let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;\n let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));\n if (!$to)\n return null;\n // If closing to `$to` succeeded, create a step\n let content = this.placed, openStart = $from.depth, openEnd = $to.depth;\n while (openStart && openEnd && content.childCount == 1) { // Normalize by dropping open parent nodes\n content = content.firstChild.content;\n openStart--;\n openEnd--;\n }\n let slice = new Slice(content, openStart, openEnd);\n if (moveInline > -1)\n return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize);\n if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps\n return new ReplaceStep($from.pos, $to.pos, slice);\n return null;\n }\n // Find a position on the start spine of `this.unplaced` that has\n // content that can be moved somewhere on the frontier. Returns two\n // depths, one for the slice and one for the frontier.\n findFittable() {\n let startDepth = this.unplaced.openStart;\n for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) {\n let node = cur.firstChild;\n if (cur.childCount > 1)\n openEnd = 0;\n if (node.type.spec.isolating && openEnd <= d) {\n startDepth = d;\n break;\n }\n cur = node.content;\n }\n // Only try wrapping nodes (pass 2) after finding a place without\n // wrapping failed.\n for (let pass = 1; pass <= 2; pass++) {\n for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {\n let fragment, parent = null;\n if (sliceDepth) {\n parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;\n fragment = parent.content;\n }\n else {\n fragment = this.unplaced.content;\n }\n let first = fragment.firstChild;\n for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {\n let { type, match } = this.frontier[frontierDepth], wrap, inject = null;\n // In pass 1, if the next node matches, or there is no next\n // node but the parents look compatible, we've found a\n // place.\n if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false))\n : parent && type.compatibleContent(parent.type)))\n return { sliceDepth, frontierDepth, parent, inject };\n // In pass 2, look for a set of wrapping nodes that make\n // `first` fit here.\n else if (pass == 2 && first && (wrap = match.findWrapping(first.type)))\n return { sliceDepth, frontierDepth, parent, wrap };\n // Don't continue looking further up if the parent node\n // would fit here.\n if (parent && match.matchType(parent.type))\n break;\n }\n }\n }\n }\n openMore() {\n let { content, openStart, openEnd } = this.unplaced;\n if (maxOpen(content, -1) <= openStart)\n return false;\n if (this.unplaced.size > 1 && maxOpen(content, 1) > openEnd)\n openEnd++;\n this.unplaced = new Slice(content, openStart + 1, openEnd);\n return true;\n }\n dropNode() {\n let { content, openStart, openEnd } = this.unplaced;\n let inner = contentAt(content, openStart);\n if (inner.childCount <= 1 && openStart > 0) {\n let openAtEnd = content.size - openStart <= openStart + inner.size;\n this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);\n }\n else {\n this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);\n }\n }\n // Move content from the unplaced slice at `sliceDepth` to the\n // frontier node at `frontierDepth`. Close that frontier node when\n // applicable.\n placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap }) {\n while (this.depth > frontierDepth)\n this.closeFrontierNode();\n if (wrap)\n for (let i = 0; i < wrap.length; i++)\n this.openFrontierNode(wrap[i]);\n let slice = this.unplaced, fragment = parent ? parent.content : slice.content;\n let openStart = slice.openStart - sliceDepth;\n let taken = 0, add = [];\n let { match, type } = this.frontier[frontierDepth];\n if (inject) {\n for (let i = 0; i < inject.childCount; i++)\n add.push(inject.child(i));\n match = match.matchFragment(inject);\n }\n // Computes the amount of (end) open nodes at the end of the\n // fragment. When 0, the parent is open, but no more. When\n // negative, nothing is open.\n let openEndCount = (fragment.size + sliceDepth) - (slice.content.size - slice.openEnd);\n // Scan over the fragment, fitting as many child nodes as\n // possible.\n while (taken < fragment.childCount) {\n let next = fragment.child(taken), matches = match.matchType(next.type);\n if (!matches)\n break;\n taken++;\n if (taken > 1 || openStart == 0 || next.content.size) { // Drop empty open nodes\n match = matches;\n add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));\n }\n }\n let toEnd = taken == fragment.childCount;\n if (!toEnd)\n openEndCount = -1;\n this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));\n this.frontier[frontierDepth].match = match;\n // If the parent types match, and the entire node was moved, and\n // it's not open, close this frontier node right away.\n if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1)\n this.closeFrontierNode();\n // Add new frontier nodes for any open nodes at the end.\n for (let i = 0, cur = fragment; i < openEndCount; i++) {\n let node = cur.lastChild;\n this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) });\n cur = node.content;\n }\n // Update `this.unplaced`. Drop the entire node from which we\n // placed it we got to its end, otherwise just drop the placed\n // nodes.\n this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd)\n : sliceDepth == 0 ? Slice.empty\n : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);\n }\n mustMoveInline() {\n if (!this.$to.parent.isTextblock)\n return -1;\n let top = this.frontier[this.depth], level;\n if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) ||\n (this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth))\n return -1;\n let { depth } = this.$to, after = this.$to.after(depth);\n while (depth > 1 && after == this.$to.end(--depth))\n ++after;\n return after;\n }\n findCloseLevel($to) {\n scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {\n let { match, type } = this.frontier[i];\n let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));\n let fit = contentAfterFits($to, i, type, match, dropInner);\n if (!fit)\n continue;\n for (let d = i - 1; d >= 0; d--) {\n let { match, type } = this.frontier[d];\n let matches = contentAfterFits($to, d, type, match, true);\n if (!matches || matches.childCount)\n continue scan;\n }\n return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to };\n }\n }\n close($to) {\n let close = this.findCloseLevel($to);\n if (!close)\n return null;\n while (this.depth > close.depth)\n this.closeFrontierNode();\n if (close.fit.childCount)\n this.placed = addToFragment(this.placed, close.depth, close.fit);\n $to = close.move;\n for (let d = close.depth + 1; d <= $to.depth; d++) {\n let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));\n this.openFrontierNode(node.type, node.attrs, add);\n }\n return $to;\n }\n openFrontierNode(type, attrs = null, content) {\n let top = this.frontier[this.depth];\n top.match = top.match.matchType(type);\n this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));\n this.frontier.push({ type, match: type.contentMatch });\n }\n closeFrontierNode() {\n let open = this.frontier.pop();\n let add = open.match.fillBefore(Fragment.empty, true);\n if (add.childCount)\n this.placed = addToFragment(this.placed, this.frontier.length, add);\n }\n}\nfunction dropFromFragment(fragment, depth, count) {\n if (depth == 0)\n return fragment.cutByIndex(count, fragment.childCount);\n return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));\n}\nfunction addToFragment(fragment, depth, content) {\n if (depth == 0)\n return fragment.append(content);\n return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));\n}\nfunction contentAt(fragment, depth) {\n for (let i = 0; i < depth; i++)\n fragment = fragment.firstChild.content;\n return fragment;\n}\nfunction closeNodeStart(node, openStart, openEnd) {\n if (openStart <= 0)\n return node;\n let frag = node.content;\n if (openStart > 1)\n frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));\n if (openStart > 0) {\n frag = node.type.contentMatch.fillBefore(frag).append(frag);\n if (openEnd <= 0)\n frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));\n }\n return node.copy(frag);\n}\nfunction contentAfterFits($to, depth, type, match, open) {\n let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);\n if (index == node.childCount && !type.compatibleContent(node.type))\n return null;\n let fit = match.fillBefore(node.content, true, index);\n return fit && !invalidMarks(type, node.content, index) ? fit : null;\n}\nfunction invalidMarks(type, fragment, start) {\n for (let i = start; i < fragment.childCount; i++)\n if (!type.allowsMarks(fragment.child(i).marks))\n return true;\n return false;\n}\nfunction definesContent(type) {\n return type.spec.defining || type.spec.definingForContent;\n}\nfunction maxOpen(frag, side) {\n for (let count = 0;; count++) {\n let ch = side < 0 ? frag.firstChild : frag.lastChild;\n if (!ch || ch.isAtom)\n return count;\n frag = ch.content;\n }\n}\nfunction replaceRange(tr, from, to, slice) {\n if (!slice.size)\n return tr.deleteRange(from, to);\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n if (fitsTrivially($from, $to, slice))\n return tr.step(new ReplaceStep(from, to, slice));\n let targetDepths = coveredDepths($from, $to);\n // Can't replace the whole document, so remove 0 if it's present\n if (targetDepths[targetDepths.length - 1] == 0)\n targetDepths.pop();\n // Negative numbers represent not expansion over the whole node at\n // that depth, but replacing from $from.before(-D) to $to.pos.\n let preferredTarget = -($from.depth + 1);\n targetDepths.unshift(preferredTarget);\n // This loop picks a preferred target depth, if one of the covering\n // depths is not outside of a defining node, and adds negative\n // depths for any depth that has $from at its start and does not\n // cross a defining node.\n for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {\n let spec = $from.node(d).type.spec;\n if (spec.defining || spec.definingAsContext || spec.isolating)\n break;\n if (targetDepths.indexOf(d) > -1)\n preferredTarget = d;\n else if ($from.before(d) == pos)\n targetDepths.splice(1, 0, -d);\n }\n // Try to fit each possible depth of the slice into each possible\n // target depth, starting with the preferred depths.\n let preferredTargetIndex = targetDepths.indexOf(preferredTarget);\n let leftNodes = [], preferredDepth = slice.openStart;\n for (let content = slice.content, i = 0;; i++) {\n let node = content.firstChild;\n leftNodes.push(node);\n if (i == slice.openStart)\n break;\n content = node.content;\n }\n // Back up preferredDepth to cover defining textblocks directly\n // above it, possibly skipping a non-defining textblock.\n for (let d = preferredDepth - 1; d >= 0; d--) {\n let leftNode = leftNodes[d], def = definesContent(leftNode.type);\n if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))\n preferredDepth = d;\n else if (def || !leftNode.type.isTextblock)\n break;\n }\n for (let j = slice.openStart; j >= 0; j--) {\n let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);\n let insert = leftNodes[openDepth];\n if (!insert)\n continue;\n for (let i = 0; i < targetDepths.length; i++) {\n // Loop over possible expansion levels, starting with the\n // preferred one\n let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true;\n if (targetDepth < 0) {\n expand = false;\n targetDepth = -targetDepth;\n }\n let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);\n if (parent.canReplaceWith(index, index, insert.type, insert.marks))\n return tr.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd));\n }\n }\n let startSteps = tr.steps.length;\n for (let i = targetDepths.length - 1; i >= 0; i--) {\n tr.replace(from, to, slice);\n if (tr.steps.length > startSteps)\n break;\n let depth = targetDepths[i];\n if (depth < 0)\n continue;\n from = $from.before(depth);\n to = $to.after(depth);\n }\n}\nfunction closeFragment(fragment, depth, oldOpen, newOpen, parent) {\n if (depth < oldOpen) {\n let first = fragment.firstChild;\n fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));\n }\n if (depth > newOpen) {\n let match = parent.contentMatchAt(0);\n let start = match.fillBefore(fragment).append(fragment);\n fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));\n }\n return fragment;\n}\nfunction replaceRangeWith(tr, from, to, node) {\n if (!node.isInline && from == to && tr.doc.resolve(from).parent.content.size) {\n let point = insertPoint(tr.doc, from, node.type);\n if (point != null)\n from = to = point;\n }\n tr.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0));\n}\nfunction deleteRange(tr, from, to) {\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n // When the deleted range spans from the start of one textblock to\n // the start of another one, move out of the start of both blocks.\n if ($from.parent.isTextblock && $to.parent.isTextblock && $from.start() != $to.start() &&\n $from.parentOffset == 0 && $to.parentOffset == 0) {\n let shared = $from.sharedDepth(to), isolated = false;\n for (let d = $from.depth; d > shared; d--)\n if ($from.node(d).type.spec.isolating)\n isolated = true;\n for (let d = $to.depth; d > shared; d--)\n if ($to.node(d).type.spec.isolating)\n isolated = true;\n if (!isolated) {\n for (let d = $from.depth; d > 0 && from == $from.start(d); d--)\n from = $from.before(d);\n for (let d = $to.depth; d > 0 && to == $to.start(d); d--)\n to = $to.before(d);\n $from = tr.doc.resolve(from);\n $to = tr.doc.resolve(to);\n }\n }\n let covered = coveredDepths($from, $to);\n for (let i = 0; i < covered.length; i++) {\n let depth = covered[i], last = i == covered.length - 1;\n if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd)\n return tr.delete($from.start(depth), $to.end(depth));\n if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))\n return tr.delete($from.before(depth), $to.after(depth));\n }\n for (let d = 1; d <= $from.depth && d <= $to.depth; d++) {\n if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d &&\n $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1)))\n return tr.delete($from.before(d), to);\n }\n tr.delete(from, to);\n}\n// Returns an array of all depths for which $from - $to spans the\n// whole content of the nodes at that depth.\nfunction coveredDepths($from, $to) {\n let result = [], minDepth = Math.min($from.depth, $to.depth);\n for (let d = minDepth; d >= 0; d--) {\n let start = $from.start(d);\n if (start < $from.pos - ($from.depth - d) ||\n $to.end(d) > $to.pos + ($to.depth - d) ||\n $from.node(d).type.spec.isolating ||\n $to.node(d).type.spec.isolating)\n break;\n if (start == $to.start(d) ||\n (d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent &&\n d && $to.start(d - 1) == start - 1))\n result.push(d);\n }\n return result;\n}\n\n/**\nUpdate an attribute in a specific node.\n*/\nclass AttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.pos = pos;\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at attribute step's position\");\n let attrs = Object.create(null);\n for (let name in node.attrs)\n attrs[name] = node.attrs[name];\n attrs[this.attr] = this.value;\n let updated = node.type.create(attrs, null, node.marks);\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new AttrStep(this.pos, this.attr, doc.nodeAt(this.pos).attrs[this.attr]);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value);\n }\n toJSON() {\n return { stepType: \"attr\", pos: this.pos, attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\" || typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for AttrStep.fromJSON\");\n return new AttrStep(json.pos, json.attr, json.value);\n }\n}\nStep.jsonID(\"attr\", AttrStep);\n/**\nUpdate an attribute in the doc node.\n*/\nclass DocAttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let attrs = Object.create(null);\n for (let name in doc.attrs)\n attrs[name] = doc.attrs[name];\n attrs[this.attr] = this.value;\n let updated = doc.type.create(attrs, doc.content, doc.marks);\n return StepResult.ok(updated);\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new DocAttrStep(this.attr, doc.attrs[this.attr]);\n }\n map(mapping) {\n return this;\n }\n toJSON() {\n return { stepType: \"docAttr\", attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for DocAttrStep.fromJSON\");\n return new DocAttrStep(json.attr, json.value);\n }\n}\nStep.jsonID(\"docAttr\", DocAttrStep);\n\n/**\n@internal\n*/\nlet TransformError = class extends Error {\n};\nTransformError = function TransformError(message) {\n let err = Error.call(this, message);\n err.__proto__ = TransformError.prototype;\n return err;\n};\nTransformError.prototype = Object.create(Error.prototype);\nTransformError.prototype.constructor = TransformError;\nTransformError.prototype.name = \"TransformError\";\n/**\nAbstraction to build up and track an array of\n[steps](https://prosemirror.net/docs/ref/#transform.Step) representing a document transformation.\n\nMost transforming methods return the `Transform` object itself, so\nthat they can be chained.\n*/\nclass Transform {\n /**\n Create a transform that starts with the given document.\n */\n constructor(\n /**\n The current document (the result of applying the steps in the\n transform).\n */\n doc) {\n this.doc = doc;\n /**\n The steps in this transform.\n */\n this.steps = [];\n /**\n The documents before each of the steps.\n */\n this.docs = [];\n /**\n A mapping with the maps for each of the steps in this transform.\n */\n this.mapping = new Mapping;\n }\n /**\n The starting document.\n */\n get before() { return this.docs.length ? this.docs[0] : this.doc; }\n /**\n Apply a new step in this transform, saving the result. Throws an\n error when the step fails.\n */\n step(step) {\n let result = this.maybeStep(step);\n if (result.failed)\n throw new TransformError(result.failed);\n return this;\n }\n /**\n Try to apply a step in this transformation, ignoring it if it\n fails. Returns the step result.\n */\n maybeStep(step) {\n let result = step.apply(this.doc);\n if (!result.failed)\n this.addStep(step, result.doc);\n return result;\n }\n /**\n True when the document has been changed (when there are any\n steps).\n */\n get docChanged() {\n return this.steps.length > 0;\n }\n /**\n Return a single range, in post-transform document positions,\n that covers all content changed by this transform. Returns null\n if no replacements are made. Note that this will ignore changes\n that add/remove marks without replacing the underlying content.\n */\n changedRange() {\n let from = 1e9, to = -1e9;\n for (let i = 0; i < this.mapping.maps.length; i++) {\n let map = this.mapping.maps[i];\n if (i) {\n from = map.map(from, 1);\n to = map.map(to, -1);\n }\n map.forEach((_f, _t, fromB, toB) => {\n from = Math.min(from, fromB);\n to = Math.max(to, toB);\n });\n }\n return from == 1e9 ? null : { from, to };\n }\n /**\n @internal\n */\n addStep(step, doc) {\n this.docs.push(this.doc);\n this.steps.push(step);\n this.mapping.appendMap(step.getMap());\n this.doc = doc;\n }\n /**\n Replace the part of the document between `from` and `to` with the\n given `slice`.\n */\n replace(from, to = from, slice = Slice.empty) {\n let step = replaceStep(this.doc, from, to, slice);\n if (step)\n this.step(step);\n return this;\n }\n /**\n Replace the given range with the given content, which may be a\n fragment, node, or array of nodes.\n */\n replaceWith(from, to, content) {\n return this.replace(from, to, new Slice(Fragment.from(content), 0, 0));\n }\n /**\n Delete the content between the given positions.\n */\n delete(from, to) {\n return this.replace(from, to, Slice.empty);\n }\n /**\n Insert the given content at the given position.\n */\n insert(pos, content) {\n return this.replaceWith(pos, pos, content);\n }\n /**\n Replace a range of the document with a given slice, using\n `from`, `to`, and the slice's\n [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather\n than fixed start and end points. This method may grow the\n replaced area or close open nodes in the slice in order to get a\n fit that is more in line with WYSIWYG expectations, by dropping\n fully covered parent nodes of the replaced region when they are\n marked [non-defining as\n context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an\n open parent node from the slice that _is_ marked as [defining\n its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n \n This is the method, for example, to handle paste. The similar\n [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more\n primitive tool which will _not_ move the start and end of its given\n range, and is useful in situations where you need more precise\n control over what happens.\n */\n replaceRange(from, to, slice) {\n replaceRange(this, from, to, slice);\n return this;\n }\n /**\n Replace the given range with a node, but use `from` and `to` as\n hints, rather than precise positions. When from and to are the same\n and are at the start or end of a parent node in which the given\n node doesn't fit, this method may _move_ them out towards a parent\n that does allow the given node to be placed. When the given range\n completely covers a parent node, this method may completely replace\n that parent node.\n */\n replaceRangeWith(from, to, node) {\n replaceRangeWith(this, from, to, node);\n return this;\n }\n /**\n Delete the given range, expanding it to cover fully covered\n parent nodes until a valid replace is found.\n */\n deleteRange(from, to) {\n deleteRange(this, from, to);\n return this;\n }\n /**\n Split the content in the given range off from its parent, if there\n is sibling content before or after it, and move it up the tree to\n the depth specified by `target`. You'll probably want to use\n [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make\n sure the lift is valid.\n */\n lift(range, target) {\n lift(this, range, target);\n return this;\n }\n /**\n Join the blocks around the given position. If depth is 2, their\n last and first siblings are also joined, and so on.\n */\n join(pos, depth = 1) {\n join(this, pos, depth);\n return this;\n }\n /**\n Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.\n The wrappers are assumed to be valid in this position, and should\n probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).\n */\n wrap(range, wrappers) {\n wrap(this, range, wrappers);\n return this;\n }\n /**\n Set the type of all textblocks (partly) between `from` and `to` to\n the given node type with the given attributes.\n */\n setBlockType(from, to = from, type, attrs = null) {\n setBlockType(this, from, to, type, attrs);\n return this;\n }\n /**\n Change the type, attributes, and/or marks of the node at `pos`.\n When `type` isn't given, the existing node type is preserved,\n */\n setNodeMarkup(pos, type, attrs = null, marks) {\n setNodeMarkup(this, pos, type, attrs, marks);\n return this;\n }\n /**\n Set a single attribute on a given node to a new value.\n The `pos` addresses the document content. Use `setDocAttribute`\n to set attributes on the document itself.\n */\n setNodeAttribute(pos, attr, value) {\n this.step(new AttrStep(pos, attr, value));\n return this;\n }\n /**\n Set a single attribute on the document to a new value.\n */\n setDocAttribute(attr, value) {\n this.step(new DocAttrStep(attr, value));\n return this;\n }\n /**\n Add a mark to the node at position `pos`.\n */\n addNodeMark(pos, mark) {\n this.step(new AddNodeMarkStep(pos, mark));\n return this;\n }\n /**\n Remove a mark (or all marks of the given type) from the node at\n position `pos`.\n */\n removeNodeMark(pos, mark) {\n let node = this.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at position \" + pos);\n if (mark instanceof Mark) {\n if (mark.isInSet(node.marks))\n this.step(new RemoveNodeMarkStep(pos, mark));\n }\n else {\n let set = node.marks, found, steps = [];\n while (found = mark.isInSet(set)) {\n steps.push(new RemoveNodeMarkStep(pos, found));\n set = found.removeFromSet(set);\n }\n for (let i = steps.length - 1; i >= 0; i--)\n this.step(steps[i]);\n }\n return this;\n }\n /**\n Split the node at the given position, and optionally, if `depth` is\n greater than one, any number of nodes above that. By default, the\n parts split off will inherit the node type of the original node.\n This can be changed by passing an array of types and attributes to\n use after the split (with the outermost nodes coming first).\n */\n split(pos, depth = 1, typesAfter) {\n split(this, pos, depth, typesAfter);\n return this;\n }\n /**\n Add the given mark to the inline content between `from` and `to`.\n */\n addMark(from, to, mark) {\n addMark(this, from, to, mark);\n return this;\n }\n /**\n Remove marks from inline nodes between `from` and `to`. When\n `mark` is a single mark, remove precisely that mark. When it is\n a mark type, remove all marks of that type. When it is null,\n remove all marks of any type.\n */\n removeMark(from, to, mark) {\n removeMark(this, from, to, mark);\n return this;\n }\n /**\n Removes all marks and nodes from the content of the node at\n `pos` that don't match the given new parent node type. Accepts\n an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as\n third argument.\n */\n clearIncompatible(pos, parentType, match) {\n clearIncompatible(this, pos, parentType, match);\n return this;\n }\n}\n\nexport { AddMarkStep, AddNodeMarkStep, AttrStep, DocAttrStep, MapResult, Mapping, RemoveMarkStep, RemoveNodeMarkStep, ReplaceAroundStep, ReplaceStep, Step, StepMap, StepResult, Transform, TransformError, canJoin, canSplit, dropPoint, findWrapping, insertPoint, joinPoint, liftTarget, replaceStep };\n", - "import { Slice, Fragment, Mark, Node } from 'prosemirror-model';\nimport { ReplaceStep, ReplaceAroundStep, Transform } from 'prosemirror-transform';\n\nconst classesById = Object.create(null);\n/**\nSuperclass for editor selections. Every selection type should\nextend this. Should not be instantiated directly.\n*/\nclass Selection {\n /**\n Initialize a selection with the head and anchor and ranges. If no\n ranges are given, constructs a single range across `$anchor` and\n `$head`.\n */\n constructor(\n /**\n The resolved anchor of the selection (the side that stays in\n place when the selection is modified).\n */\n $anchor, \n /**\n The resolved head of the selection (the side that moves when\n the selection is modified).\n */\n $head, ranges) {\n this.$anchor = $anchor;\n this.$head = $head;\n this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];\n }\n /**\n The selection's anchor, as an unresolved position.\n */\n get anchor() { return this.$anchor.pos; }\n /**\n The selection's head.\n */\n get head() { return this.$head.pos; }\n /**\n The lower bound of the selection's main range.\n */\n get from() { return this.$from.pos; }\n /**\n The upper bound of the selection's main range.\n */\n get to() { return this.$to.pos; }\n /**\n The resolved lower bound of the selection's main range.\n */\n get $from() {\n return this.ranges[0].$from;\n }\n /**\n The resolved upper bound of the selection's main range.\n */\n get $to() {\n return this.ranges[0].$to;\n }\n /**\n Indicates whether the selection contains any content.\n */\n get empty() {\n let ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++)\n if (ranges[i].$from.pos != ranges[i].$to.pos)\n return false;\n return true;\n }\n /**\n Get the content of this selection as a slice.\n */\n content() {\n return this.$from.doc.slice(this.from, this.to, true);\n }\n /**\n Replace the selection with a slice or, if no slice is given,\n delete the selection. Will append to the given transaction.\n */\n replace(tr, content = Slice.empty) {\n // Put the new selection at the position after the inserted\n // content. When that ended in an inline node, search backwards,\n // to get the position after that node. If not, search forward.\n let lastNode = content.content.lastChild, lastParent = null;\n for (let i = 0; i < content.openEnd; i++) {\n lastParent = lastNode;\n lastNode = lastNode.lastChild;\n }\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);\n if (i == 0)\n selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);\n }\n }\n /**\n Replace the selection with the given node, appending the changes\n to the given transaction.\n */\n replaceWith(tr, node) {\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n let from = mapping.map($from.pos), to = mapping.map($to.pos);\n if (i) {\n tr.deleteRange(from, to);\n }\n else {\n tr.replaceRangeWith(from, to, node);\n selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);\n }\n }\n }\n /**\n Find a valid cursor or leaf node selection starting at the given\n position and searching back if `dir` is negative, and forward if\n positive. When `textOnly` is true, only consider cursor\n selections. Will return null when no valid selection position is\n found.\n */\n static findFrom($pos, dir, textOnly = false) {\n let inner = $pos.parent.inlineContent ? new TextSelection($pos)\n : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);\n if (inner)\n return inner;\n for (let depth = $pos.depth - 1; depth >= 0; depth--) {\n let found = dir < 0\n ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly)\n : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);\n if (found)\n return found;\n }\n return null;\n }\n /**\n Find a valid cursor or leaf node selection near the given\n position. Searches forward first by default, but if `bias` is\n negative, it will search backwards first.\n */\n static near($pos, bias = 1) {\n return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));\n }\n /**\n Find the cursor or leaf node selection closest to the start of\n the given document. Will return an\n [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position\n exists.\n */\n static atStart(doc) {\n return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc);\n }\n /**\n Find the cursor or leaf node selection closest to the end of the\n given document.\n */\n static atEnd(doc) {\n return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc);\n }\n /**\n Deserialize the JSON representation of a selection. Must be\n implemented for custom classes (as a static class method).\n */\n static fromJSON(doc, json) {\n if (!json || !json.type)\n throw new RangeError(\"Invalid input for Selection.fromJSON\");\n let cls = classesById[json.type];\n if (!cls)\n throw new RangeError(`No selection type ${json.type} defined`);\n return cls.fromJSON(doc, json);\n }\n /**\n To be able to deserialize selections from JSON, custom selection\n classes must register themselves with an ID string, so that they\n can be disambiguated. Try to pick something that's unlikely to\n clash with classes from other modules.\n */\n static jsonID(id, selectionClass) {\n if (id in classesById)\n throw new RangeError(\"Duplicate use of selection JSON ID \" + id);\n classesById[id] = selectionClass;\n selectionClass.prototype.jsonID = id;\n return selectionClass;\n }\n /**\n Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,\n which is a value that can be mapped without having access to a\n current document, and later resolved to a real selection for a\n given document again. (This is used mostly by the history to\n track and restore old selections.) The default implementation of\n this method just converts the selection to a text selection and\n returns the bookmark for that.\n */\n getBookmark() {\n return TextSelection.between(this.$anchor, this.$head).getBookmark();\n }\n}\nSelection.prototype.visible = true;\n/**\nRepresents a selected range in a document.\n*/\nclass SelectionRange {\n /**\n Create a range.\n */\n constructor(\n /**\n The lower bound of the range.\n */\n $from, \n /**\n The upper bound of the range.\n */\n $to) {\n this.$from = $from;\n this.$to = $to;\n }\n}\nlet warnedAboutTextSelection = false;\nfunction checkTextSelection($pos) {\n if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {\n warnedAboutTextSelection = true;\n console[\"warn\"](\"TextSelection endpoint not pointing into a node with inline content (\" + $pos.parent.type.name + \")\");\n }\n}\n/**\nA text selection represents a classical editor selection, with a\nhead (the moving side) and anchor (immobile side), both of which\npoint into textblock nodes. It can be empty (a regular cursor\nposition).\n*/\nclass TextSelection extends Selection {\n /**\n Construct a text selection between the given points.\n */\n constructor($anchor, $head = $anchor) {\n checkTextSelection($anchor);\n checkTextSelection($head);\n super($anchor, $head);\n }\n /**\n Returns a resolved position if this is a cursor selection (an\n empty text selection), and null otherwise.\n */\n get $cursor() { return this.$anchor.pos == this.$head.pos ? this.$head : null; }\n map(doc, mapping) {\n let $head = doc.resolve(mapping.map(this.head));\n if (!$head.parent.inlineContent)\n return Selection.near($head);\n let $anchor = doc.resolve(mapping.map(this.anchor));\n return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);\n }\n replace(tr, content = Slice.empty) {\n super.replace(tr, content);\n if (content == Slice.empty) {\n let marks = this.$from.marksAcross(this.$to);\n if (marks)\n tr.ensureMarks(marks);\n }\n }\n eq(other) {\n return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head;\n }\n getBookmark() {\n return new TextBookmark(this.anchor, this.head);\n }\n toJSON() {\n return { type: \"text\", anchor: this.anchor, head: this.head };\n }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\" || typeof json.head != \"number\")\n throw new RangeError(\"Invalid input for TextSelection.fromJSON\");\n return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head));\n }\n /**\n Create a text selection from non-resolved positions.\n */\n static create(doc, anchor, head = anchor) {\n let $anchor = doc.resolve(anchor);\n return new this($anchor, head == anchor ? $anchor : doc.resolve(head));\n }\n /**\n Return a text selection that spans the given positions or, if\n they aren't text positions, find a text selection near them.\n `bias` determines whether the method searches forward (default)\n or backwards (negative number) first. Will fall back to calling\n [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document\n doesn't contain a valid text position.\n */\n static between($anchor, $head, bias) {\n let dPos = $anchor.pos - $head.pos;\n if (!bias || dPos)\n bias = dPos >= 0 ? 1 : -1;\n if (!$head.parent.inlineContent) {\n let found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);\n if (found)\n $head = found.$head;\n else\n return Selection.near($head, bias);\n }\n if (!$anchor.parent.inlineContent) {\n if (dPos == 0) {\n $anchor = $head;\n }\n else {\n $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;\n if (($anchor.pos < $head.pos) != (dPos < 0))\n $anchor = $head;\n }\n }\n return new TextSelection($anchor, $head);\n }\n}\nSelection.jsonID(\"text\", TextSelection);\nclass TextBookmark {\n constructor(anchor, head) {\n this.anchor = anchor;\n this.head = head;\n }\n map(mapping) {\n return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));\n }\n resolve(doc) {\n return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head));\n }\n}\n/**\nA node selection is a selection that points at a single node. All\nnodes marked [selectable](https://prosemirror.net/docs/ref/#model.NodeSpec.selectable) can be the\ntarget of a node selection. In such a selection, `from` and `to`\npoint directly before and after the selected node, `anchor` equals\n`from`, and `head` equals `to`..\n*/\nclass NodeSelection extends Selection {\n /**\n Create a node selection. Does not verify the validity of its\n argument.\n */\n constructor($pos) {\n let node = $pos.nodeAfter;\n let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);\n super($pos, $end);\n this.node = node;\n }\n map(doc, mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n let $pos = doc.resolve(pos);\n if (deleted)\n return Selection.near($pos);\n return new NodeSelection($pos);\n }\n content() {\n return new Slice(Fragment.from(this.node), 0, 0);\n }\n eq(other) {\n return other instanceof NodeSelection && other.anchor == this.anchor;\n }\n toJSON() {\n return { type: \"node\", anchor: this.anchor };\n }\n getBookmark() { return new NodeBookmark(this.anchor); }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\")\n throw new RangeError(\"Invalid input for NodeSelection.fromJSON\");\n return new NodeSelection(doc.resolve(json.anchor));\n }\n /**\n Create a node selection from non-resolved positions.\n */\n static create(doc, from) {\n return new NodeSelection(doc.resolve(from));\n }\n /**\n Determines whether the given node may be selected as a node\n selection.\n */\n static isSelectable(node) {\n return !node.isText && node.type.spec.selectable !== false;\n }\n}\nNodeSelection.prototype.visible = false;\nSelection.jsonID(\"node\", NodeSelection);\nclass NodeBookmark {\n constructor(anchor) {\n this.anchor = anchor;\n }\n map(mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);\n }\n resolve(doc) {\n let $pos = doc.resolve(this.anchor), node = $pos.nodeAfter;\n if (node && NodeSelection.isSelectable(node))\n return new NodeSelection($pos);\n return Selection.near($pos);\n }\n}\n/**\nA selection type that represents selecting the whole document\n(which can not necessarily be expressed with a text selection, when\nthere are for example leaf block nodes at the start or end of the\ndocument).\n*/\nclass AllSelection extends Selection {\n /**\n Create an all-selection over the given document.\n */\n constructor(doc) {\n super(doc.resolve(0), doc.resolve(doc.content.size));\n }\n replace(tr, content = Slice.empty) {\n if (content == Slice.empty) {\n tr.delete(0, tr.doc.content.size);\n let sel = Selection.atStart(tr.doc);\n if (!sel.eq(tr.selection))\n tr.setSelection(sel);\n }\n else {\n super.replace(tr, content);\n }\n }\n toJSON() { return { type: \"all\" }; }\n /**\n @internal\n */\n static fromJSON(doc) { return new AllSelection(doc); }\n map(doc) { return new AllSelection(doc); }\n eq(other) { return other instanceof AllSelection; }\n getBookmark() { return AllBookmark; }\n}\nSelection.jsonID(\"all\", AllSelection);\nconst AllBookmark = {\n map() { return this; },\n resolve(doc) { return new AllSelection(doc); }\n};\n// FIXME we'll need some awareness of text direction when scanning for selections\n// Try to find a selection inside the given node. `pos` points at the\n// position where the search starts. When `text` is true, only return\n// text selections.\nfunction findSelectionIn(doc, node, pos, index, dir, text = false) {\n if (node.inlineContent)\n return TextSelection.create(doc, pos);\n for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {\n let child = node.child(i);\n if (!child.isAtom) {\n let inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);\n if (inner)\n return inner;\n }\n else if (!text && NodeSelection.isSelectable(child)) {\n return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0));\n }\n pos += child.nodeSize * dir;\n }\n return null;\n}\nfunction selectionToInsertionEnd(tr, startLen, bias) {\n let last = tr.steps.length - 1;\n if (last < startLen)\n return;\n let step = tr.steps[last];\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))\n return;\n let map = tr.mapping.maps[last], end;\n map.forEach((_from, _to, _newFrom, newTo) => { if (end == null)\n end = newTo; });\n tr.setSelection(Selection.near(tr.doc.resolve(end), bias));\n}\n\nconst UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;\n/**\nAn editor state transaction, which can be applied to a state to\ncreate an updated state. Use\n[`EditorState.tr`](https://prosemirror.net/docs/ref/#state.EditorState.tr) to create an instance.\n\nTransactions track changes to the document (they are a subclass of\n[`Transform`](https://prosemirror.net/docs/ref/#transform.Transform)), but also other state changes,\nlike selection updates and adjustments of the set of [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks). In addition, you can store\nmetadata properties in a transaction, which are extra pieces of\ninformation that client code or plugins can use to describe what a\ntransaction represents, so that they can update their [own\nstate](https://prosemirror.net/docs/ref/#state.StateField) accordingly.\n\nThe [editor view](https://prosemirror.net/docs/ref/#view.EditorView) uses a few metadata\nproperties: it will attach a property `\"pointer\"` with the value\n`true` to selection transactions directly caused by mouse or touch\ninput, a `\"composition\"` property holding an ID identifying the\ncomposition that caused it to transactions caused by composed DOM\ninput, and a `\"uiEvent\"` property of that may be `\"paste\"`,\n`\"cut\"`, or `\"drop\"`.\n*/\nclass Transaction extends Transform {\n /**\n @internal\n */\n constructor(state) {\n super(state.doc);\n // The step count for which the current selection is valid.\n this.curSelectionFor = 0;\n // Bitfield to track which aspects of the state were updated by\n // this transaction.\n this.updated = 0;\n // Object used to store metadata properties for the transaction.\n this.meta = Object.create(null);\n this.time = Date.now();\n this.curSelection = state.selection;\n this.storedMarks = state.storedMarks;\n }\n /**\n The transaction's current selection. This defaults to the editor\n selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the\n transaction, but can be overwritten with\n [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).\n */\n get selection() {\n if (this.curSelectionFor < this.steps.length) {\n this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));\n this.curSelectionFor = this.steps.length;\n }\n return this.curSelection;\n }\n /**\n Update the transaction's current selection. Will determine the\n selection that the editor gets when the transaction is applied.\n */\n setSelection(selection) {\n if (selection.$from.doc != this.doc)\n throw new RangeError(\"Selection passed to setSelection must point at the current document\");\n this.curSelection = selection;\n this.curSelectionFor = this.steps.length;\n this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;\n this.storedMarks = null;\n return this;\n }\n /**\n Whether the selection was explicitly updated by this transaction.\n */\n get selectionSet() {\n return (this.updated & UPDATED_SEL) > 0;\n }\n /**\n Set the current stored marks.\n */\n setStoredMarks(marks) {\n this.storedMarks = marks;\n this.updated |= UPDATED_MARKS;\n return this;\n }\n /**\n Make sure the current stored marks or, if that is null, the marks\n at the selection, match the given set of marks. Does nothing if\n this is already the case.\n */\n ensureMarks(marks) {\n if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))\n this.setStoredMarks(marks);\n return this;\n }\n /**\n Add a mark to the set of stored marks.\n */\n addStoredMark(mark) {\n return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Remove a mark or mark type from the set of stored marks.\n */\n removeStoredMark(mark) {\n return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Whether the stored marks were explicitly set for this transaction.\n */\n get storedMarksSet() {\n return (this.updated & UPDATED_MARKS) > 0;\n }\n /**\n @internal\n */\n addStep(step, doc) {\n super.addStep(step, doc);\n this.updated = this.updated & ~UPDATED_MARKS;\n this.storedMarks = null;\n }\n /**\n Update the timestamp for the transaction.\n */\n setTime(time) {\n this.time = time;\n return this;\n }\n /**\n Replace the current selection with the given slice.\n */\n replaceSelection(slice) {\n this.selection.replace(this, slice);\n return this;\n }\n /**\n Replace the selection with the given node. When `inheritMarks` is\n true and the content is inline, it inherits the marks from the\n place where it is inserted.\n */\n replaceSelectionWith(node, inheritMarks = true) {\n let selection = this.selection;\n if (inheritMarks)\n node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : (selection.$from.marksAcross(selection.$to) || Mark.none)));\n selection.replaceWith(this, node);\n return this;\n }\n /**\n Delete the selection.\n */\n deleteSelection() {\n this.selection.replace(this);\n return this;\n }\n /**\n Replace the given range, or the selection if no range is given,\n with a text node containing the given string.\n */\n insertText(text, from, to) {\n let schema = this.doc.type.schema;\n if (from == null) {\n if (!text)\n return this.deleteSelection();\n return this.replaceSelectionWith(schema.text(text), true);\n }\n else {\n if (to == null)\n to = from;\n if (!text)\n return this.deleteRange(from, to);\n let marks = this.storedMarks;\n if (!marks) {\n let $from = this.doc.resolve(from);\n marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));\n }\n this.replaceRangeWith(from, to, schema.text(text, marks));\n if (!this.selection.empty && this.selection.to == from + text.length)\n this.setSelection(Selection.near(this.selection.$to));\n return this;\n }\n }\n /**\n Store a metadata property in this transaction, keyed either by\n name or by plugin.\n */\n setMeta(key, value) {\n this.meta[typeof key == \"string\" ? key : key.key] = value;\n return this;\n }\n /**\n Retrieve a metadata property for a given name or plugin.\n */\n getMeta(key) {\n return this.meta[typeof key == \"string\" ? key : key.key];\n }\n /**\n Returns true if this transaction doesn't contain any metadata,\n and can thus safely be extended.\n */\n get isGeneric() {\n for (let _ in this.meta)\n return false;\n return true;\n }\n /**\n Indicate that the editor should scroll the selection into view\n when updated to the state produced by this transaction.\n */\n scrollIntoView() {\n this.updated |= UPDATED_SCROLL;\n return this;\n }\n /**\n True when this transaction has had `scrollIntoView` called on it.\n */\n get scrolledIntoView() {\n return (this.updated & UPDATED_SCROLL) > 0;\n }\n}\n\nfunction bind(f, self) {\n return !self || !f ? f : f.bind(self);\n}\nclass FieldDesc {\n constructor(name, desc, self) {\n this.name = name;\n this.init = bind(desc.init, self);\n this.apply = bind(desc.apply, self);\n }\n}\nconst baseFields = [\n new FieldDesc(\"doc\", {\n init(config) { return config.doc || config.schema.topNodeType.createAndFill(); },\n apply(tr) { return tr.doc; }\n }),\n new FieldDesc(\"selection\", {\n init(config, instance) { return config.selection || Selection.atStart(instance.doc); },\n apply(tr) { return tr.selection; }\n }),\n new FieldDesc(\"storedMarks\", {\n init(config) { return config.storedMarks || null; },\n apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null; }\n }),\n new FieldDesc(\"scrollToSelection\", {\n init() { return 0; },\n apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev; }\n })\n];\n// Object wrapping the part of a state object that stays the same\n// across transactions. Stored in the state's `config` property.\nclass Configuration {\n constructor(schema, plugins) {\n this.schema = schema;\n this.plugins = [];\n this.pluginsByKey = Object.create(null);\n this.fields = baseFields.slice();\n if (plugins)\n plugins.forEach(plugin => {\n if (this.pluginsByKey[plugin.key])\n throw new RangeError(\"Adding different instances of a keyed plugin (\" + plugin.key + \")\");\n this.plugins.push(plugin);\n this.pluginsByKey[plugin.key] = plugin;\n if (plugin.spec.state)\n this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));\n });\n }\n}\n/**\nThe state of a ProseMirror editor is represented by an object of\nthis type. A state is a persistent data structure—it isn't\nupdated, but rather a new state value is computed from an old one\nusing the [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) method.\n\nA state holds a number of built-in fields, and plugins can\n[define](https://prosemirror.net/docs/ref/#state.PluginSpec.state) additional fields.\n*/\nclass EditorState {\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n config) {\n this.config = config;\n }\n /**\n The schema of the state's document.\n */\n get schema() {\n return this.config.schema;\n }\n /**\n The plugins that are active in this state.\n */\n get plugins() {\n return this.config.plugins;\n }\n /**\n Apply the given transaction to produce a new state.\n */\n apply(tr) {\n return this.applyTransaction(tr).state;\n }\n /**\n @internal\n */\n filterTransaction(tr, ignore = -1) {\n for (let i = 0; i < this.config.plugins.length; i++)\n if (i != ignore) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this))\n return false;\n }\n return true;\n }\n /**\n Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that\n returns the precise transactions that were applied (which might\n be influenced by the [transaction\n hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of\n plugins) along with the new state.\n */\n applyTransaction(rootTr) {\n if (!this.filterTransaction(rootTr))\n return { state: this, transactions: [] };\n let trs = [rootTr], newState = this.applyInner(rootTr), seen = null;\n // This loop repeatedly gives plugins a chance to respond to\n // transactions as new transactions are added, making sure to only\n // pass the transactions the plugin did not see before.\n for (;;) {\n let haveNew = false;\n for (let i = 0; i < this.config.plugins.length; i++) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.appendTransaction) {\n let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;\n let tr = n < trs.length &&\n plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);\n if (tr && newState.filterTransaction(tr, i)) {\n tr.setMeta(\"appendedTransaction\", rootTr);\n if (!seen) {\n seen = [];\n for (let j = 0; j < this.config.plugins.length; j++)\n seen.push(j < i ? { state: newState, n: trs.length } : { state: this, n: 0 });\n }\n trs.push(tr);\n newState = newState.applyInner(tr);\n haveNew = true;\n }\n if (seen)\n seen[i] = { state: newState, n: trs.length };\n }\n }\n if (!haveNew)\n return { state: newState, transactions: trs };\n }\n }\n /**\n @internal\n */\n applyInner(tr) {\n if (!tr.before.eq(this.doc))\n throw new RangeError(\"Applying a mismatched transaction\");\n let newInstance = new EditorState(this.config), fields = this.config.fields;\n for (let i = 0; i < fields.length; i++) {\n let field = fields[i];\n newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);\n }\n return newInstance;\n }\n /**\n Accessor that constructs and returns a new [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.\n */\n get tr() { return new Transaction(this); }\n /**\n Create a new state.\n */\n static create(config) {\n let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins);\n let instance = new EditorState($config);\n for (let i = 0; i < $config.fields.length; i++)\n instance[$config.fields[i].name] = $config.fields[i].init(config, instance);\n return instance;\n }\n /**\n Create a new state based on this one, but with an adjusted set\n of active plugins. State fields that exist in both sets of\n plugins are kept unchanged. Those that no longer exist are\n dropped, and those that are new are initialized using their\n [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new\n configuration object..\n */\n reconfigure(config) {\n let $config = new Configuration(this.schema, config.plugins);\n let fields = $config.fields, instance = new EditorState($config);\n for (let i = 0; i < fields.length; i++) {\n let name = fields[i].name;\n instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);\n }\n return instance;\n }\n /**\n Serialize this state to JSON. If you want to serialize the state\n of plugins, pass an object mapping property names to use in the\n resulting JSON object to plugin objects. The argument may also be\n a string or number, in which case it is ignored, to support the\n way `JSON.stringify` calls `toString` methods.\n */\n toJSON(pluginFields) {\n let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };\n if (this.storedMarks)\n result.storedMarks = this.storedMarks.map(m => m.toJSON());\n if (pluginFields && typeof pluginFields == 'object')\n for (let prop in pluginFields) {\n if (prop == \"doc\" || prop == \"selection\")\n throw new RangeError(\"The JSON fields `doc` and `selection` are reserved\");\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (state && state.toJSON)\n result[prop] = state.toJSON.call(plugin, this[plugin.key]);\n }\n return result;\n }\n /**\n Deserialize a JSON representation of a state. `config` should\n have at least a `schema` field, and should contain array of\n plugins to initialize the state with. `pluginFields` can be used\n to deserialize the state of plugins, by associating plugin\n instances with the property names they use in the JSON object.\n */\n static fromJSON(config, json, pluginFields) {\n if (!json)\n throw new RangeError(\"Invalid input for EditorState.fromJSON\");\n if (!config.schema)\n throw new RangeError(\"Required config field 'schema' missing\");\n let $config = new Configuration(config.schema, config.plugins);\n let instance = new EditorState($config);\n $config.fields.forEach(field => {\n if (field.name == \"doc\") {\n instance.doc = Node.fromJSON(config.schema, json.doc);\n }\n else if (field.name == \"selection\") {\n instance.selection = Selection.fromJSON(instance.doc, json.selection);\n }\n else if (field.name == \"storedMarks\") {\n if (json.storedMarks)\n instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);\n }\n else {\n if (pluginFields)\n for (let prop in pluginFields) {\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (plugin.key == field.name && state && state.fromJSON &&\n Object.prototype.hasOwnProperty.call(json, prop)) {\n instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);\n return;\n }\n }\n instance[field.name] = field.init(config, instance);\n }\n });\n return instance;\n }\n}\n\nfunction bindProps(obj, self, target) {\n for (let prop in obj) {\n let val = obj[prop];\n if (val instanceof Function)\n val = val.bind(self);\n else if (prop == \"handleDOMEvents\")\n val = bindProps(val, self, {});\n target[prop] = val;\n }\n return target;\n}\n/**\nPlugins bundle functionality that can be added to an editor.\nThey are part of the [editor state](https://prosemirror.net/docs/ref/#state.EditorState) and\nmay influence that state and the view that contains it.\n*/\nclass Plugin {\n /**\n Create a plugin.\n */\n constructor(\n /**\n The plugin's [spec object](https://prosemirror.net/docs/ref/#state.PluginSpec).\n */\n spec) {\n this.spec = spec;\n /**\n The [props](https://prosemirror.net/docs/ref/#view.EditorProps) exported by this plugin.\n */\n this.props = {};\n if (spec.props)\n bindProps(spec.props, this, this.props);\n this.key = spec.key ? spec.key.key : createKey(\"plugin\");\n }\n /**\n Extract the plugin's state field from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\nconst keys = Object.create(null);\nfunction createKey(name) {\n if (name in keys)\n return name + \"$\" + ++keys[name];\n keys[name] = 0;\n return name + \"$\";\n}\n/**\nA key is used to [tag](https://prosemirror.net/docs/ref/#state.PluginSpec.key) plugins in a way\nthat makes it possible to find them, given an editor state.\nAssigning a key does mean only one plugin of that type can be\nactive in a state.\n*/\nclass PluginKey {\n /**\n Create a plugin key.\n */\n constructor(name = \"key\") { this.key = createKey(name); }\n /**\n Get the active plugin with this key, if any, from an editor\n state.\n */\n get(state) { return state.config.pluginsByKey[this.key]; }\n /**\n Get the plugin's state from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\n\nexport { AllSelection, EditorState, NodeSelection, Plugin, PluginKey, Selection, SelectionRange, TextSelection, Transaction };\n", - "import { TextSelection, NodeSelection, Selection, AllSelection } from 'prosemirror-state';\nimport { DOMSerializer, Fragment, Mark, Slice, DOMParser } from 'prosemirror-model';\nimport { dropPoint } from 'prosemirror-transform';\n\nconst domIndex = function (node) {\n for (var index = 0;; index++) {\n node = node.previousSibling;\n if (!node)\n return index;\n }\n};\nconst parentNode = function (node) {\n let parent = node.assignedSlot || node.parentNode;\n return parent && parent.nodeType == 11 ? parent.host : parent;\n};\nlet reusedRange = null;\n// Note that this will always return the same range, because DOM range\n// objects are every expensive, and keep slowing down subsequent DOM\n// updates, for some reason.\nconst textRange = function (node, from, to) {\n let range = reusedRange || (reusedRange = document.createRange());\n range.setEnd(node, to == null ? node.nodeValue.length : to);\n range.setStart(node, from || 0);\n return range;\n};\nconst clearReusedRange = function () {\n reusedRange = null;\n};\n// Scans forward and backward through DOM positions equivalent to the\n// given one to see if the two are in the same place (i.e. after a\n// text node vs at the end of that text node)\nconst isEquivalentPosition = function (node, off, targetNode, targetOff) {\n return targetNode && (scanFor(node, off, targetNode, targetOff, -1) ||\n scanFor(node, off, targetNode, targetOff, 1));\n};\nconst atomElements = /^(img|br|input|textarea|hr)$/i;\nfunction scanFor(node, off, targetNode, targetOff, dir) {\n var _a;\n for (;;) {\n if (node == targetNode && off == targetOff)\n return true;\n if (off == (dir < 0 ? 0 : nodeSize(node))) {\n let parent = node.parentNode;\n if (!parent || !isElt(parent) || hasBlockDesc(node) || atomElements.test(node.nodeName) ||\n node.contentEditable == \"false\")\n return false;\n off = domIndex(node) + (dir < 0 ? 0 : 1);\n node = parent;\n }\n else if (isElt(node)) {\n let child = node.childNodes[off + (dir < 0 ? -1 : 0)];\n if (isElt(child) && child.contentEditable == \"false\") {\n if ((_a = child.pmViewDesc) === null || _a === void 0 ? void 0 : _a.ignoreForSelection)\n off += dir;\n else\n return false;\n }\n else {\n node = child;\n off = dir < 0 ? nodeSize(node) : 0;\n }\n }\n else {\n return false;\n }\n }\n}\nfunction nodeSize(node) {\n return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;\n}\nfunction isElt(node) { return node.nodeType == 1; }\nfunction isText(node) { return node.nodeType == 3; }\nfunction contains(parent, child) {\n return child ? parent.contains(isElt(child) ? child : child.parentNode) : false;\n}\nfunction textNodeBefore$1(node, offset) {\n for (;;) {\n if (isText(node) && offset)\n return node;\n if (isElt(node) && offset > 0) {\n if (node.contentEditable == \"false\")\n return null;\n node = node.childNodes[offset - 1];\n offset = nodeSize(node);\n }\n else if (node.parentNode && !hasBlockDesc(node)) {\n offset = domIndex(node);\n node = node.parentNode;\n }\n else {\n return null;\n }\n }\n}\nfunction textNodeAfter$1(node, offset) {\n for (;;) {\n if (isText(node) && offset < node.nodeValue.length)\n return node;\n if (isElt(node) && offset < node.childNodes.length) {\n if (node.contentEditable == \"false\")\n return null;\n node = node.childNodes[offset];\n offset = 0;\n }\n else if (node.parentNode && !hasBlockDesc(node)) {\n offset = domIndex(node) + 1;\n node = node.parentNode;\n }\n else {\n return null;\n }\n }\n}\nfunction isOnEdge(node, offset, parent) {\n for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd;) {\n if (node == parent)\n return true;\n let index = domIndex(node);\n node = node.parentNode;\n if (!node)\n return false;\n atStart = atStart && index == 0;\n atEnd = atEnd && index == nodeSize(node);\n }\n}\nfunction hasBlockDesc(dom) {\n let desc;\n for (let cur = dom; cur; cur = cur.parentNode)\n if (desc = cur.pmViewDesc)\n break;\n return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom);\n}\n// Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523\n// (isCollapsed inappropriately returns true in shadow dom)\nconst selectionCollapsed = function (domSel) {\n return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset);\n};\nfunction keyEvent(keyCode, key) {\n let event = document.createEvent(\"Event\");\n event.initEvent(\"keydown\", true, true);\n event.keyCode = keyCode;\n event.key = event.code = key;\n return event;\n}\nfunction deepActiveElement(doc) {\n let elt = doc.activeElement;\n while (elt && elt.shadowRoot)\n elt = elt.shadowRoot.activeElement;\n return elt;\n}\nfunction caretFromPoint(doc, x, y) {\n if (doc.caretPositionFromPoint) {\n try { // Firefox throws for this call in hard-to-predict circumstances (#994)\n let pos = doc.caretPositionFromPoint(x, y);\n // Clip the offset, because Chrome will return a text offset\n // into nodes, which can't be treated as a regular DOM\n // offset\n if (pos)\n return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) };\n }\n catch (_) { }\n }\n if (doc.caretRangeFromPoint) {\n let range = doc.caretRangeFromPoint(x, y);\n if (range)\n return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) };\n }\n}\n\nconst nav = typeof navigator != \"undefined\" ? navigator : null;\nconst doc = typeof document != \"undefined\" ? document : null;\nconst agent = (nav && nav.userAgent) || \"\";\nconst ie_edge = /Edge\\/(\\d+)/.exec(agent);\nconst ie_upto10 = /MSIE \\d/.exec(agent);\nconst ie_11up = /Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(agent);\nconst ie = !!(ie_upto10 || ie_11up || ie_edge);\nconst ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0;\nconst gecko = !ie && /gecko\\/(\\d+)/i.test(agent);\ngecko && +(/Firefox\\/(\\d+)/.exec(agent) || [0, 0])[1];\nconst _chrome = !ie && /Chrome\\/(\\d+)/.exec(agent);\nconst chrome = !!_chrome;\nconst chrome_version = _chrome ? +_chrome[1] : 0;\nconst safari = !ie && !!nav && /Apple Computer/.test(nav.vendor);\n// Is true for both iOS and iPadOS for convenience\nconst ios = safari && (/Mobile\\/\\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2);\nconst mac = ios || (nav ? /Mac/.test(nav.platform) : false);\nconst windows = nav ? /Win/.test(nav.platform) : false;\nconst android = /Android \\d/.test(agent);\nconst webkit = !!doc && \"webkitFontSmoothing\" in doc.documentElement.style;\nconst webkit_version = webkit ? +(/\\bAppleWebKit\\/(\\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0;\n\nfunction windowRect(doc) {\n let vp = doc.defaultView && doc.defaultView.visualViewport;\n if (vp)\n return {\n left: 0, right: vp.width,\n top: 0, bottom: vp.height\n };\n return { left: 0, right: doc.documentElement.clientWidth,\n top: 0, bottom: doc.documentElement.clientHeight };\n}\nfunction getSide(value, side) {\n return typeof value == \"number\" ? value : value[side];\n}\nfunction clientRect(node) {\n let rect = node.getBoundingClientRect();\n // Adjust for elements with style \"transform: scale()\"\n let scaleX = (rect.width / node.offsetWidth) || 1;\n let scaleY = (rect.height / node.offsetHeight) || 1;\n // Make sure scrollbar width isn't included in the rectangle\n return { left: rect.left, right: rect.left + node.clientWidth * scaleX,\n top: rect.top, bottom: rect.top + node.clientHeight * scaleY };\n}\nfunction scrollRectIntoView(view, rect, startDOM) {\n // Skip empty rects with all sides at 0, for example, when the element has no CSS box (display: none)\n if (!nonZero(rect) && rect.left == 0)\n return;\n let scrollThreshold = view.someProp(\"scrollThreshold\") || 0, scrollMargin = view.someProp(\"scrollMargin\") || 5;\n let doc = view.dom.ownerDocument;\n for (let parent = startDOM || view.dom;;) {\n if (!parent)\n break;\n if (!isElt(parent)) {\n parent = parentNode(parent);\n continue;\n }\n let atTop = parent == doc.body;\n let bounding = atTop ? windowRect(doc) : clientRect(parent);\n let moveX = 0, moveY = 0;\n if (rect.top < bounding.top + getSide(scrollThreshold, \"top\"))\n moveY = -(bounding.top - rect.top + getSide(scrollMargin, \"top\"));\n else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, \"bottom\"))\n moveY = rect.bottom - rect.top > bounding.bottom - bounding.top\n ? rect.top + getSide(scrollMargin, \"top\") - bounding.top\n : rect.bottom - bounding.bottom + getSide(scrollMargin, \"bottom\");\n if (rect.left < bounding.left + getSide(scrollThreshold, \"left\"))\n moveX = -(bounding.left - rect.left + getSide(scrollMargin, \"left\"));\n else if (rect.right > bounding.right - getSide(scrollThreshold, \"right\"))\n moveX = rect.right - bounding.right + getSide(scrollMargin, \"right\");\n if (moveX || moveY) {\n if (atTop) {\n doc.defaultView.scrollBy(moveX, moveY);\n }\n else {\n let startX = parent.scrollLeft, startY = parent.scrollTop;\n if (moveY)\n parent.scrollTop += moveY;\n if (moveX)\n parent.scrollLeft += moveX;\n let dX = parent.scrollLeft - startX, dY = parent.scrollTop - startY;\n rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY };\n }\n }\n let pos = atTop ? \"fixed\" : getComputedStyle(parent).position;\n if (/^(fixed|sticky)$/.test(pos))\n break;\n parent = pos == \"absolute\" ? parent.offsetParent : parentNode(parent);\n }\n}\n// Store the scroll position of the editor's parent nodes, along with\n// the top position of an element near the top of the editor, which\n// will be used to make sure the visible viewport remains stable even\n// when the size of the content above changes.\nfunction storeScrollPos(view) {\n let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top);\n let refDOM, refTop;\n for (let x = (rect.left + rect.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect.bottom); y += 5) {\n let dom = view.root.elementFromPoint(x, y);\n if (!dom || dom == view.dom || !view.dom.contains(dom))\n continue;\n let localRect = dom.getBoundingClientRect();\n if (localRect.top >= startY - 20) {\n refDOM = dom;\n refTop = localRect.top;\n break;\n }\n }\n return { refDOM: refDOM, refTop: refTop, stack: scrollStack(view.dom) };\n}\nfunction scrollStack(dom) {\n let stack = [], doc = dom.ownerDocument;\n for (let cur = dom; cur; cur = parentNode(cur)) {\n stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft });\n if (dom == doc)\n break;\n }\n return stack;\n}\n// Reset the scroll position of the editor's parent nodes to that what\n// it was before, when storeScrollPos was called.\nfunction resetScrollPos({ refDOM, refTop, stack }) {\n let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;\n restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);\n}\nfunction restoreScrollStack(stack, dTop) {\n for (let i = 0; i < stack.length; i++) {\n let { dom, top, left } = stack[i];\n if (dom.scrollTop != top + dTop)\n dom.scrollTop = top + dTop;\n if (dom.scrollLeft != left)\n dom.scrollLeft = left;\n }\n}\nlet preventScrollSupported = null;\n// Feature-detects support for .focus({preventScroll: true}), and uses\n// a fallback kludge when not supported.\nfunction focusPreventScroll(dom) {\n if (dom.setActive)\n return dom.setActive(); // in IE\n if (preventScrollSupported)\n return dom.focus(preventScrollSupported);\n let stored = scrollStack(dom);\n dom.focus(preventScrollSupported == null ? {\n get preventScroll() {\n preventScrollSupported = { preventScroll: true };\n return true;\n }\n } : undefined);\n if (!preventScrollSupported) {\n preventScrollSupported = false;\n restoreScrollStack(stored, 0);\n }\n}\nfunction findOffsetInNode(node, coords) {\n let closest;\n let dxClosest = 2e8, coordsClosest, offset = 0;\n let rowBot = coords.top, rowTop = coords.top;\n let firstBelow, coordsBelow;\n for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {\n let rects;\n if (isElt(child))\n rects = child.getClientRects();\n else if (isText(child))\n rects = textRange(child).getClientRects();\n else\n continue;\n for (let i = 0; i < rects.length; i++) {\n let rect = rects[i];\n if (rect.top <= rowBot && rect.bottom >= rowTop) {\n rowBot = Math.max(rect.bottom, rowBot);\n rowTop = Math.min(rect.top, rowTop);\n let dx = rect.left > coords.left ? rect.left - coords.left\n : rect.right < coords.left ? coords.left - rect.right : 0;\n if (dx < dxClosest) {\n closest = child;\n dxClosest = dx;\n coordsClosest = dx && isText(closest) ? {\n left: rect.right < coords.left ? rect.right : rect.left,\n top: coords.top\n } : coords;\n if (isElt(child) && dx)\n offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0);\n continue;\n }\n }\n else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) {\n firstBelow = child;\n coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top };\n }\n if (!closest && (coords.left >= rect.right && coords.top >= rect.top ||\n coords.left >= rect.left && coords.top >= rect.bottom))\n offset = childIndex + 1;\n }\n }\n if (!closest && firstBelow) {\n closest = firstBelow;\n coordsClosest = coordsBelow;\n dxClosest = 0;\n }\n if (closest && isText(closest))\n return findOffsetInText(closest, coordsClosest);\n if (!closest || dxClosest)\n return { node, offset };\n return findOffsetInNode(closest, coordsClosest);\n}\nfunction findOffsetInText(node, coords) {\n let len = node.nodeValue.length;\n let range = document.createRange(), result;\n for (let i = 0; i < len; i++) {\n range.setEnd(node, i + 1);\n range.setStart(node, i);\n let rect = singleRect(range, 1);\n if (rect.top == rect.bottom)\n continue;\n if (inRect(coords, rect)) {\n result = { node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) };\n break;\n }\n }\n range.detach();\n return result || { node, offset: 0 };\n}\nfunction inRect(coords, rect) {\n return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 &&\n coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1;\n}\nfunction targetKludge(dom, coords) {\n let parent = dom.parentNode;\n if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left)\n return parent;\n return dom;\n}\nfunction posFromElement(view, elt, coords) {\n let { node, offset } = findOffsetInNode(elt, coords), bias = -1;\n if (isElt(node) && !node.firstChild) {\n let rect = node.getBoundingClientRect();\n bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1;\n }\n return view.docView.posFromDOM(node, offset, bias);\n}\nfunction posFromCaret(view, node, offset, coords) {\n // Browser (in caretPosition/RangeFromPoint) will agressively\n // normalize towards nearby inline nodes. Since we are interested in\n // positions between block nodes too, we first walk up the hierarchy\n // of nodes to see if there are block nodes that the coordinates\n // fall outside of. If so, we take the position before/after that\n // block. If not, we call `posFromDOM` on the raw node/offset.\n let outsideBlock = -1;\n for (let cur = node, sawBlock = false;;) {\n if (cur == view.dom)\n break;\n let desc = view.docView.nearestDesc(cur, true), rect;\n if (!desc)\n return null;\n if (isElt(desc.dom) && (desc.node.isBlock && desc.parent || !desc.contentDOM) &&\n // Ignore elements with zero-size bounding rectangles\n ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) {\n if (desc.node.isBlock && desc.parent && !/^T(R|BODY|HEAD|FOOT)$/.test(desc.dom.nodeName)) {\n // Only apply the horizontal test to the innermost block. Vertical for any parent.\n if (!sawBlock && rect.left > coords.left || rect.top > coords.top)\n outsideBlock = desc.posBefore;\n else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top)\n outsideBlock = desc.posAfter;\n sawBlock = true;\n }\n if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) {\n // If we are inside a leaf, return the side of the leaf closer to the coords\n let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2\n : coords.left < (rect.left + rect.right) / 2;\n return before ? desc.posBefore : desc.posAfter;\n }\n }\n cur = desc.dom.parentNode;\n }\n return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node, offset, -1);\n}\nfunction elementFromPoint(element, coords, box) {\n let len = element.childNodes.length;\n if (len && box.top < box.bottom) {\n for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI;;) {\n let child = element.childNodes[i];\n if (isElt(child)) {\n let rects = child.getClientRects();\n for (let j = 0; j < rects.length; j++) {\n let rect = rects[j];\n if (inRect(coords, rect))\n return elementFromPoint(child, coords, rect);\n }\n }\n if ((i = (i + 1) % len) == startI)\n break;\n }\n }\n return element;\n}\n// Given an x,y position on the editor, get the position in the document.\nfunction posAtCoords(view, coords) {\n let doc = view.dom.ownerDocument, node, offset = 0;\n let caret = caretFromPoint(doc, coords.left, coords.top);\n if (caret)\n ({ node, offset } = caret);\n let elt = (view.root.elementFromPoint ? view.root : doc)\n .elementFromPoint(coords.left, coords.top);\n let pos;\n if (!elt || !view.dom.contains(elt)) {\n let box = view.dom.getBoundingClientRect();\n if (!inRect(coords, box))\n return null;\n elt = elementFromPoint(view.dom, coords, box);\n if (!elt)\n return null;\n }\n // Safari's caretRangeFromPoint returns nonsense when on a draggable element\n if (safari) {\n for (let p = elt; node && p; p = parentNode(p))\n if (p.draggable)\n node = undefined;\n }\n elt = targetKludge(elt, coords);\n if (node) {\n if (gecko && isElt(node)) {\n // Firefox will sometimes return offsets into nodes, which\n // have no actual children, from caretPositionFromPoint (#953)\n offset = Math.min(offset, node.childNodes.length);\n // It'll also move the returned position before image nodes,\n // even if those are behind it.\n if (offset < node.childNodes.length) {\n let next = node.childNodes[offset], box;\n if (next.nodeName == \"IMG\" && (box = next.getBoundingClientRect()).right <= coords.left &&\n box.bottom > coords.top)\n offset++;\n }\n }\n let prev;\n // When clicking above the right side of an uneditable node, Chrome will report a cursor position after that node.\n if (webkit && offset && isElt(node) && isElt(prev = node.childNodes[offset - 1]) &&\n prev.contentEditable == \"false\" && prev.getBoundingClientRect().top >= coords.top)\n offset--;\n // Suspiciously specific kludge to work around caret*FromPoint\n // never returning a position at the end of the document\n if (node == view.dom && offset == node.childNodes.length - 1 && isElt(node.lastChild) &&\n coords.top > node.lastChild.getBoundingClientRect().bottom)\n pos = view.state.doc.content.size;\n // Ignore positions directly after a BR, since caret*FromPoint\n // 'round up' positions that would be more accurately placed\n // before the BR node.\n else if (offset == 0 || !isElt(node) || node.childNodes[offset - 1].nodeName != \"BR\")\n pos = posFromCaret(view, node, offset, coords);\n }\n if (pos == null)\n pos = posFromElement(view, elt, coords);\n let desc = view.docView.nearestDesc(elt, true);\n return { pos, inside: desc ? desc.posAtStart - desc.border : -1 };\n}\nfunction nonZero(rect) {\n return rect.top < rect.bottom || rect.left < rect.right;\n}\nfunction singleRect(target, bias) {\n let rects = target.getClientRects();\n if (rects.length) {\n let first = rects[bias < 0 ? 0 : rects.length - 1];\n if (nonZero(first))\n return first;\n }\n return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect();\n}\nconst BIDI = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/;\n// Given a position in the document model, get a bounding box of the\n// character at that position, relative to the window.\nfunction coordsAtPos(view, pos, side) {\n let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1);\n let supportEmptyRange = webkit || gecko;\n if (isText(node)) {\n // These browsers support querying empty text ranges. Prefer that in\n // bidi context or when at the end of a node.\n if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) {\n let rect = singleRect(textRange(node, offset, offset), side);\n // Firefox returns bad results (the position before the space)\n // when querying a position directly after line-broken\n // whitespace. Detect this situation and and kludge around it\n if (gecko && offset && /\\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) {\n let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1);\n if (rectBefore.top == rect.top) {\n let rectAfter = singleRect(textRange(node, offset, offset + 1), -1);\n if (rectAfter.top != rect.top)\n return flattenV(rectAfter, rectAfter.left < rectBefore.left);\n }\n }\n return rect;\n }\n else {\n let from = offset, to = offset, takeSide = side < 0 ? 1 : -1;\n if (side < 0 && !offset) {\n to++;\n takeSide = -1;\n }\n else if (side >= 0 && offset == node.nodeValue.length) {\n from--;\n takeSide = 1;\n }\n else if (side < 0) {\n from--;\n }\n else {\n to++;\n }\n return flattenV(singleRect(textRange(node, from, to), takeSide), takeSide < 0);\n }\n }\n let $dom = view.state.doc.resolve(pos - (atom || 0));\n // Return a horizontal line in block context\n if (!$dom.parent.inlineContent) {\n if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n let before = node.childNodes[offset - 1];\n if (isElt(before))\n return flattenH(before.getBoundingClientRect(), false);\n }\n if (atom == null && offset < nodeSize(node)) {\n let after = node.childNodes[offset];\n if (isElt(after))\n return flattenH(after.getBoundingClientRect(), true);\n }\n return flattenH(node.getBoundingClientRect(), side >= 0);\n }\n // Inline, not in text node (this is not Bidi-safe)\n if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n let before = node.childNodes[offset - 1];\n let target = isText(before) ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1))\n // BR nodes tend to only return the rectangle before them.\n // Only use them if they are the last element in their parent\n : isElt(before) && (before.nodeName != \"BR\" || !before.nextSibling) ? before : null;\n if (target)\n return flattenV(singleRect(target, 1), false);\n }\n if (atom == null && offset < nodeSize(node)) {\n let after = node.childNodes[offset];\n while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords)\n after = after.nextSibling;\n let target = !after ? null : isText(after) ? textRange(after, 0, (supportEmptyRange ? 0 : 1))\n : isElt(after) ? after : null;\n if (target)\n return flattenV(singleRect(target, -1), true);\n }\n // All else failed, just try to get a rectangle for the target node\n return flattenV(singleRect(isText(node) ? textRange(node) : node, -side), side >= 0);\n}\nfunction flattenV(rect, left) {\n if (rect.width == 0)\n return rect;\n let x = left ? rect.left : rect.right;\n return { top: rect.top, bottom: rect.bottom, left: x, right: x };\n}\nfunction flattenH(rect, top) {\n if (rect.height == 0)\n return rect;\n let y = top ? rect.top : rect.bottom;\n return { top: y, bottom: y, left: rect.left, right: rect.right };\n}\nfunction withFlushedState(view, state, f) {\n let viewState = view.state, active = view.root.activeElement;\n if (viewState != state)\n view.updateState(state);\n if (active != view.dom)\n view.focus();\n try {\n return f();\n }\n finally {\n if (viewState != state)\n view.updateState(viewState);\n if (active != view.dom && active)\n active.focus();\n }\n}\n// Whether vertical position motion in a given direction\n// from a position would leave a text block.\nfunction endOfTextblockVertical(view, state, dir) {\n let sel = state.selection;\n let $pos = dir == \"up\" ? sel.$from : sel.$to;\n return withFlushedState(view, state, () => {\n let { node: dom } = view.docView.domFromPos($pos.pos, dir == \"up\" ? -1 : 1);\n for (;;) {\n let nearest = view.docView.nearestDesc(dom, true);\n if (!nearest)\n break;\n if (nearest.node.isBlock) {\n dom = nearest.contentDOM || nearest.dom;\n break;\n }\n dom = nearest.dom.parentNode;\n }\n let coords = coordsAtPos(view, $pos.pos, 1);\n for (let child = dom.firstChild; child; child = child.nextSibling) {\n let boxes;\n if (isElt(child))\n boxes = child.getClientRects();\n else if (isText(child))\n boxes = textRange(child, 0, child.nodeValue.length).getClientRects();\n else\n continue;\n for (let i = 0; i < boxes.length; i++) {\n let box = boxes[i];\n if (box.bottom > box.top + 1 &&\n (dir == \"up\" ? coords.top - box.top > (box.bottom - coords.top) * 2\n : box.bottom - coords.bottom > (coords.bottom - box.top) * 2))\n return false;\n }\n }\n return true;\n });\n}\nconst maybeRTL = /[\\u0590-\\u08ac]/;\nfunction endOfTextblockHorizontal(view, state, dir) {\n let { $head } = state.selection;\n if (!$head.parent.isTextblock)\n return false;\n let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size;\n let sel = view.domSelection();\n if (!sel)\n return $head.pos == $head.start() || $head.pos == $head.end();\n // If the textblock is all LTR, or the browser doesn't support\n // Selection.modify (Edge), fall back to a primitive approach\n if (!maybeRTL.test($head.parent.textContent) || !sel.modify)\n return dir == \"left\" || dir == \"backward\" ? atStart : atEnd;\n return withFlushedState(view, state, () => {\n // This is a huge hack, but appears to be the best we can\n // currently do: use `Selection.modify` to move the selection by\n // one character, and see if that moves the cursor out of the\n // textblock (or doesn't move it at all, when at the start/end of\n // the document).\n let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange();\n let oldBidiLevel = sel.caretBidiLevel // Only for Firefox\n ;\n sel.modify(\"move\", dir, \"character\");\n let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;\n let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange();\n let result = newNode && !contains(parentDOM, newNode) || (oldNode == newNode && oldOff == newOff);\n // Restore the previous selection\n try {\n sel.collapse(anchorNode, anchorOffset);\n if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend)\n sel.extend(oldNode, oldOff);\n }\n catch (_) { }\n if (oldBidiLevel != null)\n sel.caretBidiLevel = oldBidiLevel;\n return result;\n });\n}\nlet cachedState = null;\nlet cachedDir = null;\nlet cachedResult = false;\nfunction endOfTextblock(view, state, dir) {\n if (cachedState == state && cachedDir == dir)\n return cachedResult;\n cachedState = state;\n cachedDir = dir;\n return cachedResult = dir == \"up\" || dir == \"down\"\n ? endOfTextblockVertical(view, state, dir)\n : endOfTextblockHorizontal(view, state, dir);\n}\n\n// View descriptions are data structures that describe the DOM that is\n// used to represent the editor's content. They are used for:\n//\n// - Incremental redrawing when the document changes\n//\n// - Figuring out what part of the document a given DOM position\n// corresponds to\n//\n// - Wiring in custom implementations of the editing interface for a\n// given node\n//\n// They form a doubly-linked mutable tree, starting at `view.docView`.\nconst NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3;\n// Superclass for the various kinds of descriptions. Defines their\n// basic structure and shared methods.\nclass ViewDesc {\n constructor(parent, children, dom, \n // This is the node that holds the child views. It may be null for\n // descs that don't have children.\n contentDOM) {\n this.parent = parent;\n this.children = children;\n this.dom = dom;\n this.contentDOM = contentDOM;\n this.dirty = NOT_DIRTY;\n // An expando property on the DOM node provides a link back to its\n // description.\n dom.pmViewDesc = this;\n }\n // Used to check whether a given description corresponds to a\n // widget/mark/node.\n matchesWidget(widget) { return false; }\n matchesMark(mark) { return false; }\n matchesNode(node, outerDeco, innerDeco) { return false; }\n matchesHack(nodeName) { return false; }\n // When parsing in-editor content (in domchange.js), we allow\n // descriptions to determine the parse rules that should be used to\n // parse them.\n parseRule(addedNodes) { return null; }\n // Used by the editor's event handler to ignore events that come\n // from certain descs.\n stopEvent(event) { return false; }\n // The size of the content represented by this desc.\n get size() {\n let size = 0;\n for (let i = 0; i < this.children.length; i++)\n size += this.children[i].size;\n return size;\n }\n // For block nodes, this represents the space taken up by their\n // start/end tokens.\n get border() { return 0; }\n destroy() {\n this.parent = undefined;\n if (this.dom.pmViewDesc == this)\n this.dom.pmViewDesc = undefined;\n for (let i = 0; i < this.children.length; i++)\n this.children[i].destroy();\n }\n posBeforeChild(child) {\n for (let i = 0, pos = this.posAtStart;; i++) {\n let cur = this.children[i];\n if (cur == child)\n return pos;\n pos += cur.size;\n }\n }\n get posBefore() {\n return this.parent.posBeforeChild(this);\n }\n get posAtStart() {\n return this.parent ? this.parent.posBeforeChild(this) + this.border : 0;\n }\n get posAfter() {\n return this.posBefore + this.size;\n }\n get posAtEnd() {\n return this.posAtStart + this.size - 2 * this.border;\n }\n localPosFromDOM(dom, offset, bias) {\n // If the DOM position is in the content, use the child desc after\n // it to figure out a position.\n if (this.contentDOM && contains(this.contentDOM, dom)) {\n if (bias < 0) {\n let domBefore, desc;\n if (dom == this.contentDOM) {\n domBefore = dom.childNodes[offset - 1];\n }\n else {\n while (dom.parentNode != this.contentDOM)\n dom = dom.parentNode;\n domBefore = dom.previousSibling;\n }\n while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this))\n domBefore = domBefore.previousSibling;\n return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart;\n }\n else {\n let domAfter, desc;\n if (dom == this.contentDOM) {\n domAfter = dom.childNodes[offset];\n }\n else {\n while (dom.parentNode != this.contentDOM)\n dom = dom.parentNode;\n domAfter = dom.nextSibling;\n }\n while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this))\n domAfter = domAfter.nextSibling;\n return domAfter ? this.posBeforeChild(desc) : this.posAtEnd;\n }\n }\n // Otherwise, use various heuristics, falling back on the bias\n // parameter, to determine whether to return the position at the\n // start or at the end of this view desc.\n let atEnd;\n if (dom == this.dom && this.contentDOM) {\n atEnd = offset > domIndex(this.contentDOM);\n }\n else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {\n let rel = dom.compareDocumentPosition(this.contentDOM);\n if (rel & 16) { // this.contentDOM is inside dom\n atEnd = offset > Array.from(dom.childNodes).findIndex(n => n.contains(this.contentDOM));\n }\n else { // Check if after or before\n atEnd = !(rel & 4);\n }\n }\n else if (this.dom.firstChild) {\n if (offset == 0)\n for (let search = dom;; search = search.parentNode) {\n if (search == this.dom) {\n atEnd = false;\n break;\n }\n if (search.previousSibling)\n break;\n }\n if (atEnd == null && offset == dom.childNodes.length)\n for (let search = dom;; search = search.parentNode) {\n if (search == this.dom) {\n atEnd = true;\n break;\n }\n if (search.nextSibling)\n break;\n }\n }\n return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart;\n }\n nearestDesc(dom, onlyNodes = false) {\n for (let first = true, cur = dom; cur; cur = cur.parentNode) {\n let desc = this.getDesc(cur), nodeDOM;\n if (desc && (!onlyNodes || desc.node)) {\n // If dom is outside of this desc's nodeDOM, don't count it.\n if (first && (nodeDOM = desc.nodeDOM) &&\n !(isElt(nodeDOM) ? contains(nodeDOM, dom) : nodeDOM == dom))\n first = false;\n else\n return desc;\n }\n }\n }\n getDesc(dom) {\n let desc = dom.pmViewDesc;\n for (let cur = desc; cur; cur = cur.parent)\n if (cur == this)\n return desc;\n }\n posFromDOM(dom, offset, bias) {\n for (let scan = dom; scan; scan = scan.parentNode) {\n let desc = this.getDesc(scan);\n if (desc)\n return desc.localPosFromDOM(dom, offset, bias);\n }\n return -1;\n }\n // Find the desc for the node after the given pos, if any. (When a\n // parent node overrode rendering, there might not be one.)\n descAt(pos) {\n for (let i = 0, offset = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (offset == pos && end != offset) {\n while (!child.border && child.children.length) {\n for (let i = 0; i < child.children.length; i++) {\n let inner = child.children[i];\n if (inner.size) {\n child = inner;\n break;\n }\n }\n }\n return child;\n }\n if (pos < end)\n return child.descAt(pos - offset - child.border);\n offset = end;\n }\n }\n domFromPos(pos, side) {\n if (!this.contentDOM)\n return { node: this.dom, offset: 0, atom: pos + 1 };\n // First find the position in the child array\n let i = 0, offset = 0;\n for (let curPos = 0; i < this.children.length; i++) {\n let child = this.children[i], end = curPos + child.size;\n if (end > pos) {\n offset = pos - curPos;\n break;\n }\n curPos = end;\n }\n // If this points into the middle of a child, call through\n if (offset)\n return this.children[i].domFromPos(offset - this.children[i].border, side);\n // Go back if there were any zero-length widgets with side >= 0 before this point\n for (; i > 0; i--) {\n let prev = this.children[i - 1];\n if (prev.size || !(prev instanceof BufferHackViewDesc || prev instanceof WidgetViewDesc && prev.side >= 0))\n break;\n }\n // Scan towards the first useable node\n if (side <= 0) {\n let prev, enter = true;\n for (;; i--, enter = false) {\n prev = i ? this.children[i - 1] : null;\n if (!prev || prev.dom.parentNode == this.contentDOM)\n break;\n }\n if (prev && side && enter && !prev.border && !prev.domAtom)\n return prev.domFromPos(prev.size, side);\n return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 };\n }\n else {\n let next, enter = true;\n for (;; i++, enter = false) {\n next = i < this.children.length ? this.children[i] : null;\n if (!next || next.dom.parentNode == this.contentDOM)\n break;\n }\n if (next && enter && !next.border && !next.domAtom)\n return next.domFromPos(0, side);\n return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length };\n }\n }\n // Used to find a DOM range in a single parent for a given changed\n // range.\n parseRange(from, to, base = 0) {\n if (this.children.length == 0)\n return { node: this.contentDOM, from, to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length };\n let fromOffset = -1, toOffset = -1;\n for (let offset = base, i = 0;; i++) {\n let child = this.children[i], end = offset + child.size;\n if (fromOffset == -1 && from <= end) {\n let childBase = offset + child.border;\n // FIXME maybe descend mark views to parse a narrower range?\n if (from >= childBase && to <= end - child.border && child.node &&\n child.contentDOM && this.contentDOM.contains(child.contentDOM))\n return child.parseRange(from, to, childBase);\n from = offset;\n for (let j = i; j > 0; j--) {\n let prev = this.children[j - 1];\n if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {\n fromOffset = domIndex(prev.dom) + 1;\n break;\n }\n from -= prev.size;\n }\n if (fromOffset == -1)\n fromOffset = 0;\n }\n if (fromOffset > -1 && (end > to || i == this.children.length - 1)) {\n to = end;\n for (let j = i + 1; j < this.children.length; j++) {\n let next = this.children[j];\n if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {\n toOffset = domIndex(next.dom);\n break;\n }\n to += next.size;\n }\n if (toOffset == -1)\n toOffset = this.contentDOM.childNodes.length;\n break;\n }\n offset = end;\n }\n return { node: this.contentDOM, from, to, fromOffset, toOffset };\n }\n emptyChildAt(side) {\n if (this.border || !this.contentDOM || !this.children.length)\n return false;\n let child = this.children[side < 0 ? 0 : this.children.length - 1];\n return child.size == 0 || child.emptyChildAt(side);\n }\n domAfterPos(pos) {\n let { node, offset } = this.domFromPos(pos, 0);\n if (!isElt(node) || offset == node.childNodes.length)\n throw new RangeError(\"No node after pos \" + pos);\n return node.childNodes[offset];\n }\n // View descs are responsible for setting any selection that falls\n // entirely inside of them, so that custom implementations can do\n // custom things with the selection. Note that this falls apart when\n // a selection starts in such a node and ends in another, in which\n // case we just use whatever domFromPos produces as a best effort.\n setSelection(anchor, head, view, force = false) {\n // If the selection falls entirely in a child, give it to that child\n let from = Math.min(anchor, head), to = Math.max(anchor, head);\n for (let i = 0, offset = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (from > offset && to < end)\n return child.setSelection(anchor - offset - child.border, head - offset - child.border, view, force);\n offset = end;\n }\n let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1);\n let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1);\n let domSel = view.root.getSelection();\n let selRange = view.domSelectionRange();\n let brKludge = false;\n // On Firefox, using Selection.collapse to put the cursor after a\n // BR node for some reason doesn't always work (#1073). On Safari,\n // the cursor sometimes inexplicable visually lags behind its\n // reported position in such situations (#1092).\n if ((gecko || safari) && anchor == head) {\n let { node, offset } = anchorDOM;\n if (isText(node)) {\n brKludge = !!(offset && node.nodeValue[offset - 1] == \"\\n\");\n // Issue #1128\n if (brKludge && offset == node.nodeValue.length) {\n for (let scan = node, after; scan; scan = scan.parentNode) {\n if (after = scan.nextSibling) {\n if (after.nodeName == \"BR\")\n anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 };\n break;\n }\n let desc = scan.pmViewDesc;\n if (desc && desc.node && desc.node.isBlock)\n break;\n }\n }\n }\n else {\n let prev = node.childNodes[offset - 1];\n brKludge = prev && (prev.nodeName == \"BR\" || prev.contentEditable == \"false\");\n }\n }\n // Firefox can act strangely when the selection is in front of an\n // uneditable node. See #1163 and https://bugzilla.mozilla.org/show_bug.cgi?id=1709536\n if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && isElt(selRange.focusNode)) {\n let after = selRange.focusNode.childNodes[selRange.focusOffset];\n if (after && after.contentEditable == \"false\")\n force = true;\n }\n if (!(force || brKludge && safari) &&\n isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) &&\n isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset))\n return;\n // Selection.extend can be used to create an 'inverted' selection\n // (one where the focus is before the anchor), but not all\n // browsers support it yet.\n let domSelExtended = false;\n if ((domSel.extend || anchor == head) && !(brKludge && gecko)) {\n domSel.collapse(anchorDOM.node, anchorDOM.offset);\n try {\n if (anchor != head)\n domSel.extend(headDOM.node, headDOM.offset);\n domSelExtended = true;\n }\n catch (_) {\n // In some cases with Chrome the selection is empty after calling\n // collapse, even when it should be valid. This appears to be a bug, but\n // it is difficult to isolate. If this happens fallback to the old path\n // without using extend.\n // Similarly, this could crash on Safari if the editor is hidden, and\n // there was no selection.\n }\n }\n if (!domSelExtended) {\n if (anchor > head) {\n let tmp = anchorDOM;\n anchorDOM = headDOM;\n headDOM = tmp;\n }\n let range = document.createRange();\n range.setEnd(headDOM.node, headDOM.offset);\n range.setStart(anchorDOM.node, anchorDOM.offset);\n domSel.removeAllRanges();\n domSel.addRange(range);\n }\n }\n ignoreMutation(mutation) {\n return !this.contentDOM && mutation.type != \"selection\";\n }\n get contentLost() {\n return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM);\n }\n // Remove a subtree of the element tree that has been touched\n // by a DOM change, so that the next update will redraw it.\n markDirty(from, to) {\n for (let offset = 0, i = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (offset == end ? from <= end && to >= offset : from < end && to > offset) {\n let startInside = offset + child.border, endInside = end - child.border;\n if (from >= startInside && to <= endInside) {\n this.dirty = from == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY;\n if (from == startInside && to == endInside &&\n (child.contentLost || child.dom.parentNode != this.contentDOM))\n child.dirty = NODE_DIRTY;\n else\n child.markDirty(from - startInside, to - startInside);\n return;\n }\n else {\n child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length\n ? CONTENT_DIRTY : NODE_DIRTY;\n }\n }\n offset = end;\n }\n this.dirty = CONTENT_DIRTY;\n }\n markParentsDirty() {\n let level = 1;\n for (let node = this.parent; node; node = node.parent, level++) {\n let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;\n if (node.dirty < dirty)\n node.dirty = dirty;\n }\n }\n get domAtom() { return false; }\n get ignoreForCoords() { return false; }\n get ignoreForSelection() { return false; }\n isText(text) { return false; }\n}\n// A widget desc represents a widget decoration, which is a DOM node\n// drawn between the document nodes.\nclass WidgetViewDesc extends ViewDesc {\n constructor(parent, widget, view, pos) {\n let self, dom = widget.type.toDOM;\n if (typeof dom == \"function\")\n dom = dom(view, () => {\n if (!self)\n return pos;\n if (self.parent)\n return self.parent.posBeforeChild(self);\n });\n if (!widget.type.spec.raw) {\n let elt = isElt(dom) ? dom : document.createElement(\"span\");\n if (elt != dom) {\n elt.appendChild(dom);\n dom = elt;\n }\n if (!elt.hasAttribute(\"contenteditable\"))\n elt.contentEditable = \"false\";\n elt.classList.add(\"ProseMirror-widget\");\n }\n super(parent, [], dom, null);\n this.widget = widget;\n this.widget = widget;\n self = this;\n }\n matchesWidget(widget) {\n return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type);\n }\n parseRule() { return { ignore: true }; }\n stopEvent(event) {\n let stop = this.widget.spec.stopEvent;\n return stop ? stop(event) : false;\n }\n ignoreMutation(mutation) {\n return mutation.type != \"selection\" || this.widget.spec.ignoreSelection;\n }\n destroy() {\n this.widget.type.destroy(this.dom);\n super.destroy();\n }\n get domAtom() { return true; }\n get ignoreForSelection() { return !!this.widget.type.spec.relaxedSide; }\n get side() { return this.widget.type.side; }\n}\nclass CompositionViewDesc extends ViewDesc {\n constructor(parent, dom, textDOM, text) {\n super(parent, [], dom, null);\n this.textDOM = textDOM;\n this.text = text;\n }\n get size() { return this.text.length; }\n localPosFromDOM(dom, offset) {\n if (dom != this.textDOM)\n return this.posAtStart + (offset ? this.size : 0);\n return this.posAtStart + offset;\n }\n domFromPos(pos) {\n return { node: this.textDOM, offset: pos };\n }\n ignoreMutation(mut) {\n return mut.type === 'characterData' && mut.target.nodeValue == mut.oldValue;\n }\n}\n// A mark desc represents a mark. May have multiple children,\n// depending on how the mark is split. Note that marks are drawn using\n// a fixed nesting order, for simplicity and predictability, so in\n// some cases they will be split more often than would appear\n// necessary.\nclass MarkViewDesc extends ViewDesc {\n constructor(parent, mark, dom, contentDOM, spec) {\n super(parent, [], dom, contentDOM);\n this.mark = mark;\n this.spec = spec;\n }\n static create(parent, mark, inline, view) {\n let custom = view.nodeViews[mark.type.name];\n let spec = custom && custom(mark, view, inline);\n if (!spec || !spec.dom)\n spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline), null, mark.attrs);\n return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom, spec);\n }\n parseRule() {\n if ((this.dirty & NODE_DIRTY) || this.mark.type.spec.reparseInView)\n return null;\n return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM };\n }\n matchesMark(mark) { return this.dirty != NODE_DIRTY && this.mark.eq(mark); }\n markDirty(from, to) {\n super.markDirty(from, to);\n // Move dirty info to nearest node view\n if (this.dirty != NOT_DIRTY) {\n let parent = this.parent;\n while (!parent.node)\n parent = parent.parent;\n if (parent.dirty < this.dirty)\n parent.dirty = this.dirty;\n this.dirty = NOT_DIRTY;\n }\n }\n slice(from, to, view) {\n let copy = MarkViewDesc.create(this.parent, this.mark, true, view);\n let nodes = this.children, size = this.size;\n if (to < size)\n nodes = replaceNodes(nodes, to, size, view);\n if (from > 0)\n nodes = replaceNodes(nodes, 0, from, view);\n for (let i = 0; i < nodes.length; i++)\n nodes[i].parent = copy;\n copy.children = nodes;\n return copy;\n }\n ignoreMutation(mutation) {\n return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n }\n destroy() {\n if (this.spec.destroy)\n this.spec.destroy();\n super.destroy();\n }\n}\n// Node view descs are the main, most common type of view desc, and\n// correspond to an actual node in the document. Unlike mark descs,\n// they populate their child array themselves.\nclass NodeViewDesc extends ViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM) {\n super(parent, [], dom, contentDOM);\n this.node = node;\n this.outerDeco = outerDeco;\n this.innerDeco = innerDeco;\n this.nodeDOM = nodeDOM;\n }\n // By default, a node is rendered using the `toDOM` method from the\n // node type spec. But client code can use the `nodeViews` spec to\n // supply a custom node view, which can influence various aspects of\n // the way the node works.\n //\n // (Using subclassing for this was intentionally decided against,\n // since it'd require exposing a whole slew of finicky\n // implementation details to the user code that they probably will\n // never need.)\n static create(parent, node, outerDeco, innerDeco, view, pos) {\n let custom = view.nodeViews[node.type.name], descObj;\n let spec = custom && custom(node, view, () => {\n // (This is a function that allows the custom view to find its\n // own position)\n if (!descObj)\n return pos;\n if (descObj.parent)\n return descObj.parent.posBeforeChild(descObj);\n }, outerDeco, innerDeco);\n let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;\n if (node.isText) {\n if (!dom)\n dom = document.createTextNode(node.text);\n else if (!isText(dom))\n throw new RangeError(\"Text must be rendered as a DOM text node\");\n }\n else if (!dom) {\n let spec = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs);\n ({ dom, contentDOM } = spec);\n }\n if (!contentDOM && !node.isText && dom.nodeName != \"BR\") { // Chrome gets confused by
\n if (!dom.hasAttribute(\"contenteditable\"))\n dom.contentEditable = \"false\";\n if (node.type.spec.draggable)\n dom.draggable = true;\n }\n let nodeDOM = dom;\n dom = applyOuterDeco(dom, outerDeco, node);\n if (spec)\n return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec);\n else if (node.isText)\n return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM);\n else\n return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM);\n }\n parseRule(addedNodes) {\n // Experimental kludge to allow opt-in re-parsing of nodes\n if (this.node.type.spec.reparseInView)\n return null;\n // FIXME the assumption that this can always return the current\n // attrs means that if the user somehow manages to change the\n // attrs in the dom, that won't be picked up. Not entirely sure\n // whether this is a problem\n let rule = { node: this.node.type.name, attrs: this.node.attrs };\n if (this.node.type.whitespace == \"pre\")\n rule.preserveWhitespace = \"full\";\n if (!this.contentDOM) {\n rule.getContent = () => this.node.content;\n }\n else if (!this.contentLost) {\n rule.contentElement = this.contentDOM;\n }\n else {\n // Chrome likes to randomly recreate parent nodes when\n // backspacing things. When that happens, this tries to find the\n // new parent.\n for (let i = this.children.length - 1; i >= 0; i--) {\n let child = this.children[i];\n if (this.dom.contains(child.dom.parentNode)) {\n rule.contentElement = child.dom.parentNode;\n break;\n }\n }\n if (!rule.contentElement) {\n let found = addedNodes &&\n addedNodes.find(n => isElt(n) && addedNodes.indexOf(n.parentNode) < 0 && this.dom.contains(n));\n if (found)\n rule.contentElement = found;\n else\n rule.getContent = () => Fragment.empty;\n }\n }\n return rule;\n }\n matchesNode(node, outerDeco, innerDeco) {\n return this.dirty == NOT_DIRTY && node.eq(this.node) &&\n sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco);\n }\n get size() { return this.node.nodeSize; }\n get border() { return this.node.isLeaf ? 0 : 1; }\n // Syncs `this.children` to match `this.node.content` and the local\n // decorations, possibly introducing nesting for marks. Then, in a\n // separate step, syncs the DOM inside `this.contentDOM` to\n // `this.children`.\n updateChildren(view, pos) {\n let inline = this.node.inlineContent, off = pos;\n let composition = view.composing ? this.localCompositionInfo(view, pos) : null;\n let localComposition = composition && composition.pos > -1 ? composition : null;\n let compositionInChild = composition && composition.pos < 0;\n let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view);\n let addBuffers = this.node.inlineContent, atBufferPos = addBuffers && this.node.isBlock;\n iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => {\n if (widget.spec.marks)\n updater.syncToMarks(widget.spec.marks, inline, view, i);\n else if (widget.type.side >= 0 && !insideNode)\n updater.syncToMarks(i == this.node.childCount ? Mark.none : this.node.child(i).marks, inline, view, i);\n // If the next node is a desc matching this widget, reuse it,\n // otherwise insert the widget as a new view desc.\n updater.placeWidget(widget, view, off);\n }, (child, outerDeco, innerDeco, i) => {\n // Make sure the wrapping mark descs match the node's marks.\n updater.syncToMarks(child.marks, inline, view, i);\n if (atBufferPos && child.isAtom && !child.isText)\n updater.addHackNode(\"IMG\", updater.top);\n // Try several strategies for drawing this node\n let compIndex;\n if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) ;\n else if (compositionInChild && view.state.selection.from > off &&\n view.state.selection.to < off + child.nodeSize &&\n (compIndex = updater.findIndexWithChild(composition.node)) > -1 &&\n updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) ;\n else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i, off)) ;\n else {\n // Add it as a new view\n updater.addNode(child, outerDeco, innerDeco, view, off);\n }\n off += child.nodeSize;\n if (addBuffers)\n atBufferPos = child.isAtom && !child.isText;\n });\n // Drop all remaining descs after the current position.\n updater.syncToMarks([], inline, view, 0);\n if (this.node.isTextblock)\n updater.addTextblockHacks();\n updater.destroyRest();\n // Sync the DOM if anything changed\n if (updater.changed || this.dirty == CONTENT_DIRTY) {\n // May have to protect focused DOM from being changed if a composition is active\n if (localComposition)\n this.protectLocalComposition(view, localComposition);\n renderDescs(this.contentDOM, this.children, view);\n if (ios)\n iosHacks(this.dom);\n }\n }\n localCompositionInfo(view, pos) {\n // Only do something if both the selection and a focused text node\n // are inside of this node\n let { from, to } = view.state.selection;\n if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size)\n return null;\n let textNode = view.input.compositionNode;\n if (!textNode || !this.dom.contains(textNode.parentNode))\n return null;\n if (this.node.inlineContent) {\n // Find the text in the focused node in the node, stop if it's not\n // there (may have been modified through other means, in which\n // case it should overwritten)\n let text = textNode.nodeValue;\n let textPos = findTextInFragment(this.node.content, text, from - pos, to - pos);\n return textPos < 0 ? null : { node: textNode, pos: textPos, text };\n }\n else {\n return { node: textNode, pos: -1, text: \"\" };\n }\n }\n protectLocalComposition(view, { node, pos, text }) {\n // The node is already part of a local view desc, leave it there\n if (this.getDesc(node))\n return;\n // Create a composition view for the orphaned nodes\n let topNode = node;\n for (;; topNode = topNode.parentNode) {\n if (topNode.parentNode == this.contentDOM)\n break;\n while (topNode.previousSibling)\n topNode.parentNode.removeChild(topNode.previousSibling);\n while (topNode.nextSibling)\n topNode.parentNode.removeChild(topNode.nextSibling);\n if (topNode.pmViewDesc)\n topNode.pmViewDesc = undefined;\n }\n let desc = new CompositionViewDesc(this, topNode, node, text);\n view.input.compositionNodes.push(desc);\n // Patch up this.children to contain the composition view\n this.children = replaceNodes(this.children, pos, pos + text.length, view, desc);\n }\n // If this desc must be updated to match the given node decoration,\n // do so and return true.\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY ||\n !node.sameMarkup(this.node))\n return false;\n this.updateInner(node, outerDeco, innerDeco, view);\n return true;\n }\n updateInner(node, outerDeco, innerDeco, view) {\n this.updateOuterDeco(outerDeco);\n this.node = node;\n this.innerDeco = innerDeco;\n if (this.contentDOM)\n this.updateChildren(view, this.posAtStart);\n this.dirty = NOT_DIRTY;\n }\n updateOuterDeco(outerDeco) {\n if (sameOuterDeco(outerDeco, this.outerDeco))\n return;\n let needsWrap = !isElt(this.nodeDOM);\n let oldDOM = this.dom;\n this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap));\n if (this.dom != oldDOM) {\n oldDOM.pmViewDesc = undefined;\n this.dom.pmViewDesc = this;\n }\n this.outerDeco = outerDeco;\n }\n // Mark this node as being the selected node.\n selectNode() {\n if (isElt(this.nodeDOM)) {\n this.nodeDOM.classList.add(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable)\n this.nodeDOM.draggable = true;\n }\n }\n // Remove selected node marking from this node.\n deselectNode() {\n if (isElt(this.nodeDOM)) {\n this.nodeDOM.classList.remove(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable)\n this.nodeDOM.removeAttribute(\"draggable\");\n }\n }\n get domAtom() { return this.node.isAtom; }\n}\n// Create a view desc for the top-level document node, to be exported\n// and used by the view class.\nfunction docViewDesc(doc, outerDeco, innerDeco, dom, view) {\n applyOuterDeco(dom, outerDeco, doc);\n let docView = new NodeViewDesc(undefined, doc, outerDeco, innerDeco, dom, dom, dom);\n if (docView.contentDOM)\n docView.updateChildren(view, 0);\n return docView;\n}\nclass TextViewDesc extends NodeViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, nodeDOM) {\n super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM);\n }\n parseRule() {\n let skip = this.nodeDOM.parentNode;\n while (skip && skip != this.dom && !skip.pmIsDeco)\n skip = skip.parentNode;\n return { skip: (skip || true) };\n }\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY || (this.dirty != NOT_DIRTY && !this.inParent()) ||\n !node.sameMarkup(this.node))\n return false;\n this.updateOuterDeco(outerDeco);\n if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {\n this.nodeDOM.nodeValue = node.text;\n if (view.trackWrites == this.nodeDOM)\n view.trackWrites = null;\n }\n this.node = node;\n this.dirty = NOT_DIRTY;\n return true;\n }\n inParent() {\n let parentDOM = this.parent.contentDOM;\n for (let n = this.nodeDOM; n; n = n.parentNode)\n if (n == parentDOM)\n return true;\n return false;\n }\n domFromPos(pos) {\n return { node: this.nodeDOM, offset: pos };\n }\n localPosFromDOM(dom, offset, bias) {\n if (dom == this.nodeDOM)\n return this.posAtStart + Math.min(offset, this.node.text.length);\n return super.localPosFromDOM(dom, offset, bias);\n }\n ignoreMutation(mutation) {\n return mutation.type != \"characterData\" && mutation.type != \"selection\";\n }\n slice(from, to, _view) {\n let node = this.node.cut(from, to), dom = document.createTextNode(node.text);\n return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom);\n }\n markDirty(from, to) {\n super.markDirty(from, to);\n if (this.dom != this.nodeDOM && (from == 0 || to == this.nodeDOM.nodeValue.length))\n this.dirty = NODE_DIRTY;\n }\n get domAtom() { return false; }\n isText(text) { return this.node.text == text; }\n}\n// A dummy desc used to tag extra BR or IMG nodes created to work\n// around contentEditable terribleness.\nclass BufferHackViewDesc extends ViewDesc {\n parseRule() { return { ignore: true }; }\n matchesHack(nodeName) { return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName; }\n get domAtom() { return true; }\n get ignoreForCoords() { return this.dom.nodeName == \"IMG\"; }\n}\n// A separate subclass is used for customized node views, so that the\n// extra checks only have to be made for nodes that are actually\n// customized.\nclass CustomNodeViewDesc extends NodeViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec) {\n super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM);\n this.spec = spec;\n }\n // A custom `update` method gets to decide whether the update goes\n // through. If it does, and there's a `contentDOM` node, our logic\n // updates the children.\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY)\n return false;\n if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) {\n let result = this.spec.update(node, outerDeco, innerDeco);\n if (result)\n this.updateInner(node, outerDeco, innerDeco, view);\n return result;\n }\n else if (!this.contentDOM && !node.isLeaf) {\n return false;\n }\n else {\n return super.update(node, outerDeco, innerDeco, view);\n }\n }\n selectNode() {\n this.spec.selectNode ? this.spec.selectNode() : super.selectNode();\n }\n deselectNode() {\n this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode();\n }\n setSelection(anchor, head, view, force) {\n this.spec.setSelection ? this.spec.setSelection(anchor, head, view.root)\n : super.setSelection(anchor, head, view, force);\n }\n destroy() {\n if (this.spec.destroy)\n this.spec.destroy();\n super.destroy();\n }\n stopEvent(event) {\n return this.spec.stopEvent ? this.spec.stopEvent(event) : false;\n }\n ignoreMutation(mutation) {\n return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n }\n}\n// Sync the content of the given DOM node with the nodes associated\n// with the given array of view descs, recursing into mark descs\n// because this should sync the subtree for a whole node at a time.\nfunction renderDescs(parentDOM, descs, view) {\n let dom = parentDOM.firstChild, written = false;\n for (let i = 0; i < descs.length; i++) {\n let desc = descs[i], childDOM = desc.dom;\n if (childDOM.parentNode == parentDOM) {\n while (childDOM != dom) {\n dom = rm(dom);\n written = true;\n }\n dom = dom.nextSibling;\n }\n else {\n written = true;\n parentDOM.insertBefore(childDOM, dom);\n }\n if (desc instanceof MarkViewDesc) {\n let pos = dom ? dom.previousSibling : parentDOM.lastChild;\n renderDescs(desc.contentDOM, desc.children, view);\n dom = pos ? pos.nextSibling : parentDOM.firstChild;\n }\n }\n while (dom) {\n dom = rm(dom);\n written = true;\n }\n if (written && view.trackWrites == parentDOM)\n view.trackWrites = null;\n}\nconst OuterDecoLevel = function (nodeName) {\n if (nodeName)\n this.nodeName = nodeName;\n};\nOuterDecoLevel.prototype = Object.create(null);\nconst noDeco = [new OuterDecoLevel];\nfunction computeOuterDeco(outerDeco, node, needsWrap) {\n if (outerDeco.length == 0)\n return noDeco;\n let top = needsWrap ? noDeco[0] : new OuterDecoLevel, result = [top];\n for (let i = 0; i < outerDeco.length; i++) {\n let attrs = outerDeco[i].type.attrs;\n if (!attrs)\n continue;\n if (attrs.nodeName)\n result.push(top = new OuterDecoLevel(attrs.nodeName));\n for (let name in attrs) {\n let val = attrs[name];\n if (val == null)\n continue;\n if (needsWrap && result.length == 1)\n result.push(top = new OuterDecoLevel(node.isInline ? \"span\" : \"div\"));\n if (name == \"class\")\n top.class = (top.class ? top.class + \" \" : \"\") + val;\n else if (name == \"style\")\n top.style = (top.style ? top.style + \";\" : \"\") + val;\n else if (name != \"nodeName\")\n top[name] = val;\n }\n }\n return result;\n}\nfunction patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {\n // Shortcut for trivial case\n if (prevComputed == noDeco && curComputed == noDeco)\n return nodeDOM;\n let curDOM = nodeDOM;\n for (let i = 0; i < curComputed.length; i++) {\n let deco = curComputed[i], prev = prevComputed[i];\n if (i) {\n let parent;\n if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM &&\n (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) {\n curDOM = parent;\n }\n else {\n parent = document.createElement(deco.nodeName);\n parent.pmIsDeco = true;\n parent.appendChild(curDOM);\n prev = noDeco[0];\n curDOM = parent;\n }\n }\n patchAttributes(curDOM, prev || noDeco[0], deco);\n }\n return curDOM;\n}\nfunction patchAttributes(dom, prev, cur) {\n for (let name in prev)\n if (name != \"class\" && name != \"style\" && name != \"nodeName\" && !(name in cur))\n dom.removeAttribute(name);\n for (let name in cur)\n if (name != \"class\" && name != \"style\" && name != \"nodeName\" && cur[name] != prev[name])\n dom.setAttribute(name, cur[name]);\n if (prev.class != cur.class) {\n let prevList = prev.class ? prev.class.split(\" \").filter(Boolean) : [];\n let curList = cur.class ? cur.class.split(\" \").filter(Boolean) : [];\n for (let i = 0; i < prevList.length; i++)\n if (curList.indexOf(prevList[i]) == -1)\n dom.classList.remove(prevList[i]);\n for (let i = 0; i < curList.length; i++)\n if (prevList.indexOf(curList[i]) == -1)\n dom.classList.add(curList[i]);\n if (dom.classList.length == 0)\n dom.removeAttribute(\"class\");\n }\n if (prev.style != cur.style) {\n if (prev.style) {\n let prop = /\\s*([\\w\\-\\xa1-\\uffff]+)\\s*:(?:\"(?:\\\\.|[^\"])*\"|'(?:\\\\.|[^'])*'|\\(.*?\\)|[^;])*/g, m;\n while (m = prop.exec(prev.style))\n dom.style.removeProperty(m[1]);\n }\n if (cur.style)\n dom.style.cssText += cur.style;\n }\n}\nfunction applyOuterDeco(dom, deco, node) {\n return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, !isElt(dom)));\n}\nfunction sameOuterDeco(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].type.eq(b[i].type))\n return false;\n return true;\n}\n// Remove a DOM node and return its next sibling.\nfunction rm(dom) {\n let next = dom.nextSibling;\n dom.parentNode.removeChild(dom);\n return next;\n}\n// Helper class for incrementally updating a tree of mark descs and\n// the widget and node descs inside of them.\nclass ViewTreeUpdater {\n constructor(top, lock, view) {\n this.lock = lock;\n this.view = view;\n // Index into `this.top`'s child array, represents the current\n // update position.\n this.index = 0;\n // When entering a mark, the current top and index are pushed\n // onto this.\n this.stack = [];\n // Tracks whether anything was changed\n this.changed = false;\n this.top = top;\n this.preMatch = preMatch(top.node.content, top);\n }\n // Destroy and remove the children between the given indices in\n // `this.top`.\n destroyBetween(start, end) {\n if (start == end)\n return;\n for (let i = start; i < end; i++)\n this.top.children[i].destroy();\n this.top.children.splice(start, end - start);\n this.changed = true;\n }\n // Destroy all remaining children in `this.top`.\n destroyRest() {\n this.destroyBetween(this.index, this.top.children.length);\n }\n // Sync the current stack of mark descs with the given array of\n // marks, reusing existing mark descs when possible.\n syncToMarks(marks, inline, view, parentIndex) {\n let keep = 0, depth = this.stack.length >> 1;\n let maxKeep = Math.min(depth, marks.length);\n while (keep < maxKeep &&\n (keep == depth - 1 ? this.top : this.stack[(keep + 1) << 1])\n .matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)\n keep++;\n while (keep < depth) {\n this.destroyRest();\n this.top.dirty = NOT_DIRTY;\n this.index = this.stack.pop();\n this.top = this.stack.pop();\n depth--;\n }\n while (depth < marks.length) {\n this.stack.push(this.top, this.index + 1);\n let found = -1, scanTo = this.top.children.length;\n if (parentIndex < this.preMatch.index)\n scanTo = Math.min(this.index + 3, scanTo);\n for (let i = this.index; i < scanTo; i++) {\n let next = this.top.children[i];\n if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) {\n found = i;\n break;\n }\n }\n // When nothing matches, try to update the mark view at this position\n // in place, so a custom mark view can adapt to a changed mark without\n // re-creating its DOM.\n if (found < 0 && this.index < this.top.children.length) {\n let cur = this.top.children[this.index];\n if (cur instanceof MarkViewDesc && cur.dirty != NODE_DIRTY &&\n cur.mark.type == marks[depth].type && cur.spec.update &&\n !this.isLocked(cur.dom) && cur.spec.update(marks[depth])) {\n cur.mark = marks[depth];\n found = this.index;\n this.changed = true;\n }\n }\n if (found > -1) {\n if (found > this.index) {\n this.changed = true;\n this.destroyBetween(this.index, found);\n }\n this.top = this.top.children[this.index];\n }\n else {\n let markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view);\n this.top.children.splice(this.index, 0, markDesc);\n this.top = markDesc;\n this.changed = true;\n }\n this.index = 0;\n depth++;\n }\n }\n // Try to find a node desc matching the given data. Skip over it and\n // return true when successful.\n findNodeMatch(node, outerDeco, innerDeco, index) {\n let found = -1, targetDesc;\n if (index >= this.preMatch.index &&\n (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top &&\n targetDesc.matchesNode(node, outerDeco, innerDeco)) {\n found = this.top.children.indexOf(targetDesc, this.index);\n }\n else {\n for (let i = this.index, e = Math.min(this.top.children.length, i + 5); i < e; i++) {\n let child = this.top.children[i];\n if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) {\n found = i;\n break;\n }\n }\n }\n if (found < 0)\n return false;\n this.destroyBetween(this.index, found);\n this.index++;\n return true;\n }\n updateNodeAt(node, outerDeco, innerDeco, index, view) {\n let child = this.top.children[index];\n if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM)\n child.dirty = CONTENT_DIRTY;\n if (!child.update(node, outerDeco, innerDeco, view))\n return false;\n this.destroyBetween(this.index, index);\n this.index++;\n return true;\n }\n findIndexWithChild(domNode) {\n for (;;) {\n let parent = domNode.parentNode;\n if (!parent)\n return -1;\n if (parent == this.top.contentDOM) {\n let desc = domNode.pmViewDesc;\n if (desc)\n for (let i = this.index; i < this.top.children.length; i++) {\n if (this.top.children[i] == desc)\n return i;\n }\n return -1;\n }\n domNode = parent;\n }\n }\n // Try to update the next node, if any, to the given data. Checks\n // pre-matches to avoid overwriting nodes that could still be used.\n updateNextNode(node, outerDeco, innerDeco, view, index, pos) {\n for (let i = this.index; i < this.top.children.length; i++) {\n let next = this.top.children[i];\n if (next instanceof NodeViewDesc) {\n let preMatch = this.preMatch.matched.get(next);\n if (preMatch != null && preMatch != index)\n return false;\n let nextDOM = next.dom, updated;\n // Can't update if nextDOM is or contains this.lock, except if\n // it's a text node whose content already matches the new text\n // and whose decorations match the new ones.\n let locked = this.isLocked(nextDOM) &&\n !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text &&\n next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco));\n if (!locked && next.update(node, outerDeco, innerDeco, view)) {\n this.destroyBetween(this.index, i);\n if (next.dom != nextDOM)\n this.changed = true;\n this.index++;\n return true;\n }\n else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) {\n this.destroyBetween(this.index, i);\n this.top.children[this.index] = updated;\n if (updated.contentDOM) {\n updated.dirty = CONTENT_DIRTY;\n updated.updateChildren(view, pos + 1);\n updated.dirty = NOT_DIRTY;\n }\n this.changed = true;\n this.index++;\n return true;\n }\n break;\n }\n }\n return false;\n }\n // When a node with content is replaced by a different node with\n // identical content, move over its children.\n recreateWrapper(next, node, outerDeco, innerDeco, view, pos) {\n if (next.dirty || node.isAtom || !next.children.length ||\n !next.node.content.eq(node.content) ||\n !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco))\n return null;\n let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n if (wrapper.contentDOM) {\n wrapper.children = next.children;\n next.children = [];\n for (let ch of wrapper.children)\n ch.parent = wrapper;\n }\n next.destroy();\n return wrapper;\n }\n // Insert the node as a newly created node desc.\n addNode(node, outerDeco, innerDeco, view, pos) {\n let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n if (desc.contentDOM)\n desc.updateChildren(view, pos + 1);\n this.top.children.splice(this.index++, 0, desc);\n this.changed = true;\n }\n placeWidget(widget, view, pos) {\n let next = this.index < this.top.children.length ? this.top.children[this.index] : null;\n if (next && next.matchesWidget(widget) &&\n (widget == next.widget || !next.widget.type.toDOM.parentNode)) {\n this.index++;\n }\n else {\n let desc = new WidgetViewDesc(this.top, widget, view, pos);\n this.top.children.splice(this.index++, 0, desc);\n this.changed = true;\n }\n }\n // Make sure a textblock looks and behaves correctly in\n // contentEditable.\n addTextblockHacks() {\n let lastChild = this.top.children[this.index - 1], parent = this.top;\n while (lastChild instanceof MarkViewDesc) {\n parent = lastChild;\n lastChild = parent.children[parent.children.length - 1];\n }\n if (!lastChild || // Empty textblock\n !(lastChild instanceof TextViewDesc) ||\n /\\n$/.test(lastChild.node.text) ||\n (this.view.requiresGeckoHackNode && /\\s$/.test(lastChild.node.text))) {\n // Avoid bugs in Safari's cursor drawing (#1165) and Chrome's mouse selection (#1152)\n if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == \"false\")\n this.addHackNode(\"IMG\", parent);\n this.addHackNode(\"BR\", this.top);\n }\n }\n addHackNode(nodeName, parent) {\n if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) {\n this.index++;\n }\n else {\n let dom = document.createElement(nodeName);\n if (nodeName == \"IMG\") {\n dom.className = \"ProseMirror-separator\";\n dom.alt = \"\";\n }\n if (nodeName == \"BR\")\n dom.className = \"ProseMirror-trailingBreak\";\n let hack = new BufferHackViewDesc(this.top, [], dom, null);\n if (parent != this.top)\n parent.children.push(hack);\n else\n parent.children.splice(this.index++, 0, hack);\n this.changed = true;\n }\n }\n isLocked(node) {\n return this.lock && (node == this.lock || isElt(node) && node.contains(this.lock.parentNode));\n }\n}\n// Iterate from the end of the fragment and array of descs to find\n// directly matching ones, in order to avoid overeagerly reusing those\n// for other nodes.\nfunction preMatch(frag, parentDesc) {\n let curDesc = parentDesc, descI = curDesc.children.length;\n let fI = frag.childCount, matched = new Map, matches = [];\n outer: while (fI > 0) {\n let desc;\n for (;;) {\n if (descI) {\n let next = curDesc.children[descI - 1];\n if (next instanceof MarkViewDesc) {\n curDesc = next;\n descI = next.children.length;\n }\n else {\n desc = next;\n descI--;\n break;\n }\n }\n else if (curDesc == parentDesc) {\n break outer;\n }\n else {\n descI = curDesc.parent.children.indexOf(curDesc);\n curDesc = curDesc.parent;\n }\n }\n let node = desc.node;\n if (!node)\n continue;\n if (node != frag.child(fI - 1))\n break;\n --fI;\n matched.set(desc, fI);\n matches.push(desc);\n }\n return { index: fI, matched, matches: matches.reverse() };\n}\nfunction compareSide(a, b) {\n return a.type.side - b.type.side;\n}\n// This function abstracts iterating over the nodes and decorations in\n// a fragment. Calls `onNode` for each node, with its local and child\n// decorations. Splits text nodes when there is a decoration starting\n// or ending inside of them. Calls `onWidget` for each widget.\nfunction iterDeco(parent, deco, onWidget, onNode) {\n let locals = deco.locals(parent), offset = 0;\n // Simple, cheap variant for when there are no local decorations\n if (locals.length == 0) {\n for (let i = 0; i < parent.childCount; i++) {\n let child = parent.child(i);\n onNode(child, locals, deco.forChild(offset, child), i);\n offset += child.nodeSize;\n }\n return;\n }\n let decoIndex = 0, active = [], restNode = null;\n for (let parentIndex = 0;;) {\n let widget, widgets;\n while (decoIndex < locals.length && locals[decoIndex].to == offset) {\n let next = locals[decoIndex++];\n if (next.widget) {\n if (!widget)\n widget = next;\n else\n (widgets || (widgets = [widget])).push(next);\n }\n }\n if (widget) {\n if (widgets) {\n widgets.sort(compareSide);\n for (let i = 0; i < widgets.length; i++)\n onWidget(widgets[i], parentIndex, !!restNode);\n }\n else {\n onWidget(widget, parentIndex, !!restNode);\n }\n }\n let child, index;\n if (restNode) {\n index = -1;\n child = restNode;\n restNode = null;\n }\n else if (parentIndex < parent.childCount) {\n index = parentIndex;\n child = parent.child(parentIndex++);\n }\n else {\n break;\n }\n for (let i = 0; i < active.length; i++)\n if (active[i].to <= offset)\n active.splice(i--, 1);\n while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)\n active.push(locals[decoIndex++]);\n let end = offset + child.nodeSize;\n if (child.isText) {\n let cutAt = end;\n if (decoIndex < locals.length && locals[decoIndex].from < cutAt)\n cutAt = locals[decoIndex].from;\n for (let i = 0; i < active.length; i++)\n if (active[i].to < cutAt)\n cutAt = active[i].to;\n if (cutAt < end) {\n restNode = child.cut(cutAt - offset);\n child = child.cut(0, cutAt - offset);\n end = cutAt;\n index = -1;\n }\n }\n else {\n while (decoIndex < locals.length && locals[decoIndex].to < end)\n decoIndex++;\n }\n let outerDeco = child.isInline && !child.isLeaf ? active.filter(d => !d.inline) : active.slice();\n onNode(child, outerDeco, deco.forChild(offset, child), index);\n offset = end;\n }\n}\n// List markers in Mobile Safari will mysteriously disappear\n// sometimes. This works around that.\nfunction iosHacks(dom) {\n if (dom.nodeName == \"UL\" || dom.nodeName == \"OL\") {\n let oldCSS = dom.style.cssText;\n dom.style.cssText = oldCSS + \"; list-style: square !important\";\n window.getComputedStyle(dom).listStyle;\n dom.style.cssText = oldCSS;\n }\n}\n// Find a piece of text in an inline fragment, overlapping from-to\nfunction findTextInFragment(frag, text, from, to) {\n for (let i = 0, pos = 0; i < frag.childCount && pos <= to;) {\n let child = frag.child(i++), childStart = pos;\n pos += child.nodeSize;\n if (!child.isText)\n continue;\n let str = child.text;\n while (i < frag.childCount) {\n let next = frag.child(i++);\n pos += next.nodeSize;\n if (!next.isText)\n break;\n str += next.text;\n }\n if (pos >= from) {\n if (pos >= to && str.slice(to - text.length - childStart, to - childStart) == text)\n return to - text.length;\n let found = childStart < to ? str.lastIndexOf(text, to - childStart - 1) : -1;\n if (found >= 0 && found + text.length + childStart >= from)\n return childStart + found;\n if (from == to && str.length >= (to + text.length) - childStart &&\n str.slice(to - childStart, to - childStart + text.length) == text)\n return to;\n }\n }\n return -1;\n}\n// Replace range from-to in an array of view descs with replacement\n// (may be null to just delete). This goes very much against the grain\n// of the rest of this code, which tends to create nodes with the\n// right shape in one go, rather than messing with them after\n// creation, but is necessary in the composition hack.\nfunction replaceNodes(nodes, from, to, view, replacement) {\n let result = [];\n for (let i = 0, off = 0; i < nodes.length; i++) {\n let child = nodes[i], start = off, end = off += child.size;\n if (start >= to || end <= from) {\n result.push(child);\n }\n else {\n if (start < from)\n result.push(child.slice(0, from - start, view));\n if (replacement) {\n result.push(replacement);\n replacement = undefined;\n }\n if (end > to)\n result.push(child.slice(to - start, child.size, view));\n }\n }\n return result;\n}\n\nfunction selectionFromDOM(view, origin = null) {\n let domSel = view.domSelectionRange(), doc = view.state.doc;\n if (!domSel.focusNode)\n return null;\n let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;\n let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1);\n if (head < 0)\n return null;\n let $head = doc.resolve(head), anchor, selection;\n if (selectionCollapsed(domSel)) {\n anchor = head;\n while (nearestDesc && !nearestDesc.node)\n nearestDesc = nearestDesc.parent;\n if (nearestDesc && nearestDesc.node.isAtom && NodeSelection.isSelectable(nearestDesc.node) &&\n nearestDesc.parent &&\n !(nearestDesc.node.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {\n let pos = nearestDesc.posBefore;\n selection = new NodeSelection(head == pos ? $head : doc.resolve(pos));\n }\n else if (gecko && origin == \"key\" && head > view.state.selection.to &&\n isElt(domSel.focusNode) && domSel.focusOffset == domSel.focusNode.childNodes.length &&\n nearestDesc && nearestDesc.posAtStart > view.state.selection.to) {\n // Firefox will jump across scrollable wrapper nodes on keyboard\n // cursor motion (#1594). This tries to detect this situation\n // and work around it.\n for (let scan = domSel.focusNode;; scan = scan.parentNode) {\n if (getComputedStyle(scan).overflow != \"visible\") {\n selection = Selection.findFrom(doc.resolve(nearestDesc.posAtStart), 1);\n break;\n }\n if (scan == nearestDesc.dom || scan.nextSibling || !scan.parentNode || !isElt(scan.parentNode))\n break;\n }\n }\n }\n else {\n if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) {\n let min = head, max = head;\n for (let i = 0; i < domSel.rangeCount; i++) {\n let range = domSel.getRangeAt(i);\n min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1));\n max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1));\n }\n if (min < 0)\n return null;\n [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max];\n $head = doc.resolve(head);\n }\n else {\n anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1);\n }\n if (anchor < 0)\n return null;\n }\n let $anchor = doc.resolve(anchor);\n if (!selection) {\n let bias = origin == \"pointer\" || (view.state.selection.head < $head.pos && !inWidget) ? 1 : -1;\n selection = selectionBetween(view, $anchor, $head, bias);\n }\n return selection;\n}\nfunction editorOwnsSelection(view) {\n return view.editable ? view.hasFocus() :\n hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom);\n}\nfunction selectionToDOM(view, force = false) {\n let sel = view.state.selection;\n syncNodeSelection(view, sel);\n if (!editorOwnsSelection(view))\n return;\n // Need to delay selection normalization during a native selection\n // drag on Chrome, or it will cause further dragging to glitch.\n let mouseDown = view.input.mouseDown;\n if (!force && chrome && mouseDown) {\n let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection;\n if (domSel.anchorNode && curSel.anchorNode &&\n isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset) &&\n mouseDown.delaySelUpdate()) {\n view.domObserver.setCurSelection();\n return;\n }\n }\n view.domObserver.disconnectSelection();\n if (view.cursorWrapper) {\n selectCursorWrapper(view);\n }\n else {\n let { anchor, head } = sel, resetEditableFrom, resetEditableTo;\n if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) {\n if (!sel.$from.parent.inlineContent)\n resetEditableFrom = temporarilyEditableNear(view, sel.from);\n if (!sel.empty && !sel.$from.parent.inlineContent)\n resetEditableTo = temporarilyEditableNear(view, sel.to);\n }\n view.docView.setSelection(anchor, head, view, force);\n if (brokenSelectBetweenUneditable) {\n if (resetEditableFrom)\n resetEditable(resetEditableFrom);\n if (resetEditableTo)\n resetEditable(resetEditableTo);\n }\n if (sel.visible) {\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n }\n else {\n view.dom.classList.add(\"ProseMirror-hideselection\");\n if (\"onselectionchange\" in document)\n removeClassOnSelectionChange(view);\n }\n }\n view.domObserver.setCurSelection();\n view.domObserver.connectSelection();\n}\n// Kludge to work around Webkit not allowing a selection to start/end\n// between non-editable block nodes. We briefly make something\n// editable, set the selection, then set it uneditable again.\nconst brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63;\nfunction temporarilyEditableNear(view, pos) {\n let { node, offset } = view.docView.domFromPos(pos, 0);\n let after = offset < node.childNodes.length ? node.childNodes[offset] : null;\n let before = offset ? node.childNodes[offset - 1] : null;\n if (safari && after && after.contentEditable == \"false\")\n return setEditable(after);\n if ((!after || after.contentEditable == \"false\") &&\n (!before || before.contentEditable == \"false\")) {\n if (after)\n return setEditable(after);\n else if (before)\n return setEditable(before);\n }\n}\nfunction setEditable(element) {\n element.contentEditable = \"true\";\n if (safari && element.draggable) {\n element.draggable = false;\n element.wasDraggable = true;\n }\n return element;\n}\nfunction resetEditable(element) {\n element.contentEditable = \"false\";\n if (element.wasDraggable) {\n element.draggable = true;\n element.wasDraggable = null;\n }\n}\nfunction removeClassOnSelectionChange(view) {\n let doc = view.dom.ownerDocument;\n doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n let domSel = view.domSelectionRange();\n let node = domSel.anchorNode, offset = domSel.anchorOffset;\n doc.addEventListener(\"selectionchange\", view.input.hideSelectionGuard = () => {\n if (domSel.anchorNode != node || domSel.anchorOffset != offset) {\n doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n setTimeout(() => {\n if (!editorOwnsSelection(view) || view.state.selection.visible)\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n }, 20);\n }\n });\n}\nfunction selectCursorWrapper(view) {\n let domSel = view.domSelection();\n if (!domSel)\n return;\n let node = view.cursorWrapper.dom, img = node.nodeName == \"IMG\";\n if (img)\n domSel.collapse(node.parentNode, domIndex(node) + 1);\n else\n domSel.collapse(node, 0);\n // Kludge to kill 'control selection' in IE11 when selecting an\n // invisible cursor wrapper, since that would result in those weird\n // resize handles and a selection that considers the absolutely\n // positioned wrapper, rather than the root editable node, the\n // focused element.\n if (!img && !view.state.selection.visible && ie && ie_version <= 11) {\n node.disabled = true;\n node.disabled = false;\n }\n}\nfunction syncNodeSelection(view, sel) {\n if (sel instanceof NodeSelection) {\n let desc = view.docView.descAt(sel.from);\n if (desc != view.lastSelectedViewDesc) {\n clearNodeSelection(view);\n if (desc)\n desc.selectNode();\n view.lastSelectedViewDesc = desc;\n }\n }\n else {\n clearNodeSelection(view);\n }\n}\n// Clear all DOM statefulness of the last node selection.\nfunction clearNodeSelection(view) {\n if (view.lastSelectedViewDesc) {\n if (view.lastSelectedViewDesc.parent)\n view.lastSelectedViewDesc.deselectNode();\n view.lastSelectedViewDesc = undefined;\n }\n}\nfunction selectionBetween(view, $anchor, $head, bias) {\n return view.someProp(\"createSelectionBetween\", f => f(view, $anchor, $head))\n || TextSelection.between($anchor, $head, bias);\n}\nfunction hasFocusAndSelection(view) {\n if (view.editable && !view.hasFocus())\n return false;\n return hasSelection(view);\n}\nfunction hasSelection(view) {\n let sel = view.domSelectionRange();\n if (!sel.anchorNode)\n return false;\n try {\n // Firefox will raise 'permission denied' errors when accessing\n // properties of `sel.anchorNode` when it's in a generated CSS\n // element.\n return contains(view.dom, sel.anchorNode) && (view.editable || contains(view.dom, sel.focusNode));\n }\n catch (_) {\n return false;\n }\n}\nfunction anchorInRightPlace(view) {\n let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0);\n let domSel = view.domSelectionRange();\n return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset);\n}\n\nfunction moveSelectionBlock(state, dir) {\n let { $anchor, $head } = state.selection;\n let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);\n let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;\n return $start && Selection.findFrom($start, dir);\n}\nfunction apply(view, sel) {\n view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());\n return true;\n}\nfunction selectHorizontally(view, dir, mods) {\n let sel = view.state.selection;\n if (sel instanceof TextSelection) {\n if (mods.indexOf(\"s\") > -1) {\n let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter;\n if (!node || node.isText || !node.isLeaf)\n return false;\n let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1));\n return apply(view, new TextSelection(sel.$anchor, $newHead));\n }\n else if (!sel.empty) {\n return false;\n }\n else if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\")) {\n let next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection))\n return apply(view, next);\n return false;\n }\n else if (!mac || mods.indexOf(\"m\") < 0) {\n let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;\n if (!node || node.isText)\n return false;\n let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos;\n if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM))\n return false;\n if (NodeSelection.isSelectable(node)) {\n return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head));\n }\n else {\n // Chrome and Safari will introduce extra pointless cursor\n // positions around inline uneditable nodes (#937), and\n // Firefox will sometimes just plain refuse to move across\n // them (#1592), so in this situation we move the cursor\n // ourselves.\n return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize)));\n }\n }\n }\n else if (sel instanceof NodeSelection && sel.node.isInline) {\n return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from));\n }\n else {\n let next = moveSelectionBlock(view.state, dir);\n if (next)\n return apply(view, next);\n return false;\n }\n}\nfunction isIgnorable(dom, dir) {\n let desc = dom.pmViewDesc;\n return desc ? desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != \"BR\")\n : isElt(dom) && dom.contentEditable == \"false\";\n}\nfunction skipIgnoredNodes(view, dir) {\n return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view);\n}\n// Make sure the cursor isn't directly after one or more ignored\n// nodes, which will confuse the browser's cursor motion logic.\nfunction skipIgnoredNodesBefore(view) {\n let sel = view.domSelectionRange();\n let node = sel.focusNode, offset = sel.focusOffset;\n if (!node)\n return;\n let moveNode, moveOffset, force = false;\n // Gecko will do odd things when the selection is directly in front\n // of a non-editable node, so in that case, move it into the next\n // node if possible. Issue prosemirror/prosemirror#832.\n if (gecko && isElt(node) && offset < nodeSize(node) && isIgnorable(node.childNodes[offset], -1))\n force = true;\n for (;;) {\n if (offset > 0) {\n if (!isElt(node))\n break;\n let before = node.childNodes[offset - 1];\n if (isIgnorable(before, -1)) {\n moveNode = node;\n moveOffset = --offset;\n }\n else if (isText(before)) {\n node = before;\n offset = node.nodeValue.length;\n }\n else {\n break;\n }\n }\n else if (isBlockNode(node)) {\n break;\n }\n else {\n let prev = node.previousSibling;\n while (prev && isIgnorable(prev, -1)) {\n moveNode = node.parentNode;\n moveOffset = domIndex(prev);\n prev = prev.previousSibling;\n }\n if (!prev) {\n node = node.parentNode;\n if (node == view.dom)\n break;\n offset = 0;\n }\n else {\n node = prev;\n offset = nodeSize(node);\n }\n }\n }\n if (force)\n setSelFocus(view, node, offset);\n else if (moveNode)\n setSelFocus(view, moveNode, moveOffset);\n}\n// Make sure the cursor isn't directly before one or more ignored\n// nodes.\nfunction skipIgnoredNodesAfter(view) {\n let sel = view.domSelectionRange();\n let node = sel.focusNode, offset = sel.focusOffset;\n if (!node)\n return;\n let len = nodeSize(node);\n let moveNode, moveOffset;\n for (;;) {\n if (offset < len) {\n if (!isElt(node))\n break;\n let after = node.childNodes[offset];\n if (isIgnorable(after, 1)) {\n moveNode = node;\n moveOffset = ++offset;\n }\n else {\n break;\n }\n }\n else if (isBlockNode(node)) {\n break;\n }\n else {\n let next = node.nextSibling;\n while (next && isIgnorable(next, 1)) {\n moveNode = next.parentNode;\n moveOffset = domIndex(next) + 1;\n next = next.nextSibling;\n }\n if (!next) {\n node = node.parentNode;\n if (node == view.dom)\n break;\n offset = len = 0;\n }\n else {\n node = next;\n offset = 0;\n len = nodeSize(node);\n }\n }\n }\n if (moveNode)\n setSelFocus(view, moveNode, moveOffset);\n}\nfunction isBlockNode(dom) {\n let desc = dom.pmViewDesc;\n return desc && desc.node && desc.node.isBlock;\n}\nfunction textNodeAfter(node, offset) {\n while (node && offset == node.childNodes.length && !hasBlockDesc(node)) {\n offset = domIndex(node) + 1;\n node = node.parentNode;\n }\n while (node && offset < node.childNodes.length) {\n let next = node.childNodes[offset];\n if (isText(next))\n return next;\n if (isElt(next) && next.contentEditable == \"false\")\n break;\n node = next;\n offset = 0;\n }\n}\nfunction textNodeBefore(node, offset) {\n while (node && !offset && !hasBlockDesc(node)) {\n offset = domIndex(node);\n node = node.parentNode;\n }\n while (node && offset) {\n let next = node.childNodes[offset - 1];\n if (isText(next))\n return next;\n if (isElt(next) && next.contentEditable == \"false\")\n break;\n node = next;\n offset = node.childNodes.length;\n }\n}\nfunction setSelFocus(view, node, offset) {\n if (!isText(node)) {\n let before, after;\n if (after = textNodeAfter(node, offset)) {\n node = after;\n offset = 0;\n }\n else if (before = textNodeBefore(node, offset)) {\n node = before;\n offset = before.nodeValue.length;\n }\n }\n let sel = view.domSelection(), range = view.domSelectionRange();\n if (!sel)\n return;\n if (selectionCollapsed(range)) {\n sel.collapse(node, offset);\n }\n else if (sel.extend) {\n sel.collapse(range.anchorNode, range.anchorOffset);\n sel.extend(node, offset);\n }\n view.domObserver.setCurSelection();\n let { state } = view;\n // If no state update ends up happening, reset the selection.\n setTimeout(() => {\n if (view.state == state)\n selectionToDOM(view);\n }, 50);\n}\nfunction findDirection(view, pos) {\n let $pos = view.state.doc.resolve(pos);\n if (!(chrome || windows) && $pos.parent.inlineContent) {\n let coords = view.coordsAtPos(pos);\n if (pos > $pos.start()) {\n let before = view.coordsAtPos(pos - 1);\n let mid = (before.top + before.bottom) / 2;\n if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1)\n return before.left < coords.left ? \"ltr\" : \"rtl\";\n }\n if (pos < $pos.end()) {\n let after = view.coordsAtPos(pos + 1);\n let mid = (after.top + after.bottom) / 2;\n if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1)\n return after.left > coords.left ? \"ltr\" : \"rtl\";\n }\n }\n let block = view.dom;\n for (let d = $pos.depth; d > 0; d--)\n if ($pos.node(d).isBlock) {\n block = view.nodeDOM($pos.before(d)) || block;\n break;\n }\n let computed = getComputedStyle(block).direction;\n return computed == \"rtl\" ? \"rtl\" : \"ltr\";\n}\n// Check whether vertical selection motion would involve node\n// selections. If so, apply it (if not, the result is left to the\n// browser)\nfunction selectVertically(view, dir, mods) {\n let sel = view.state.selection;\n if (sel instanceof TextSelection && !sel.empty || mods.indexOf(\"s\") > -1)\n return false;\n if (mac && mods.indexOf(\"m\") > -1)\n return false;\n let { $from, $to } = sel;\n if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? \"up\" : \"down\")) {\n let next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection))\n return apply(view, next);\n }\n if (!$from.parent.inlineContent) {\n let side = dir < 0 ? $from : $to;\n let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir);\n return beyond ? apply(view, beyond) : false;\n }\n return false;\n}\nfunction stopNativeHorizontalDelete(view, dir) {\n if (!(view.state.selection instanceof TextSelection))\n return true;\n let { $head, $anchor, empty } = view.state.selection;\n if (!$head.sameParent($anchor))\n return true;\n if (!empty)\n return false;\n if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\"))\n return true;\n let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);\n if (nextNode && !nextNode.isText) {\n let tr = view.state.tr;\n if (dir < 0)\n tr.delete($head.pos - nextNode.nodeSize, $head.pos);\n else\n tr.delete($head.pos, $head.pos + nextNode.nodeSize);\n view.dispatch(tr);\n return true;\n }\n return false;\n}\nfunction switchEditable(view, node, state) {\n view.domObserver.stop();\n node.contentEditable = state;\n view.domObserver.start();\n}\n// Issue #867 / #1090 / https://bugs.chromium.org/p/chromium/issues/detail?id=903821\n// In which Safari (and at some point in the past, Chrome) does really\n// wrong things when the down arrow is pressed when the cursor is\n// directly at the start of a textblock and has an uneditable node\n// after it\nfunction safariDownArrowBug(view) {\n if (!safari || view.state.selection.$head.parentOffset > 0)\n return false;\n let { focusNode, focusOffset } = view.domSelectionRange();\n if (focusNode && isElt(focusNode) && focusOffset == 0 &&\n focusNode.firstChild && isElt(focusNode.firstChild) && focusNode.firstChild.contentEditable == \"false\") {\n let child = focusNode.firstChild;\n switchEditable(view, child, \"true\");\n setTimeout(() => switchEditable(view, child, \"false\"), 20);\n }\n return false;\n}\n// A backdrop key mapping used to make sure we always suppress keys\n// that have a dangerous default effect, even if the commands they are\n// bound to return false, and to make sure that cursor-motion keys\n// find a cursor (as opposed to a node selection) when pressed. For\n// cursor-motion keys, the code in the handlers also takes care of\n// block selections.\nfunction getMods(event) {\n let result = \"\";\n if (event.ctrlKey)\n result += \"c\";\n if (event.metaKey)\n result += \"m\";\n if (event.altKey)\n result += \"a\";\n if (event.shiftKey)\n result += \"s\";\n return result;\n}\nfunction captureKeyDown(view, event) {\n let code = event.keyCode, mods = getMods(event);\n if (code == 8 || (mac && code == 72 && mods == \"c\")) { // Backspace, Ctrl-h on Mac\n return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1);\n }\n else if ((code == 46 && !event.shiftKey) || (mac && code == 68 && mods == \"c\")) { // Delete, Ctrl-d on Mac\n return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1);\n }\n else if (code == 13 || code == 27) { // Enter, Esc\n return true;\n }\n else if (code == 37 || (mac && code == 66 && mods == \"c\")) { // Left arrow, Ctrl-b on Mac\n let dir = code == 37 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? -1 : 1) : -1;\n return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n }\n else if (code == 39 || (mac && code == 70 && mods == \"c\")) { // Right arrow, Ctrl-f on Mac\n let dir = code == 39 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? 1 : -1) : 1;\n return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n }\n else if (code == 38 || (mac && code == 80 && mods == \"c\")) { // Up arrow, Ctrl-p on Mac\n return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1);\n }\n else if (code == 40 || (mac && code == 78 && mods == \"c\")) { // Down arrow, Ctrl-n on Mac\n return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1);\n }\n else if (mods == (mac ? \"m\" : \"c\") &&\n (code == 66 || code == 73 || code == 89 || code == 90)) { // Mod-[biyz]\n return true;\n }\n return false;\n}\n\nfunction serializeForClipboard(view, slice) {\n view.someProp(\"transformCopied\", f => { slice = f(slice, view); });\n let context = [], { content, openStart, openEnd } = slice;\n while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {\n openStart--;\n openEnd--;\n let node = content.firstChild;\n context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null);\n content = node.content;\n }\n let serializer = view.someProp(\"clipboardSerializer\") || DOMSerializer.fromSchema(view.state.schema);\n let doc = detachedDoc(), wrap = doc.createElement(\"div\");\n wrap.appendChild(serializer.serializeFragment(content, { document: doc }));\n let firstChild = wrap.firstChild, needsWrap, wrappers = 0;\n while (firstChild && isElt(firstChild) && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {\n for (let i = needsWrap.length - 1; i >= 0; i--) {\n let wrapper = doc.createElement(needsWrap[i]);\n while (wrap.firstChild)\n wrapper.appendChild(wrap.firstChild);\n wrap.appendChild(wrapper);\n wrappers++;\n }\n firstChild = wrap.firstChild;\n }\n if (firstChild && isElt(firstChild))\n firstChild.setAttribute(\"data-pm-slice\", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : \"\"} ${JSON.stringify(context)}`);\n let text = view.someProp(\"clipboardTextSerializer\", f => f(slice, view)) ||\n slice.content.textBetween(0, slice.content.size, \"\\n\\n\");\n return { dom: wrap, text, slice };\n}\n// Read a slice of content from the clipboard (or drop data).\nfunction parseFromClipboard(view, text, html, plainText, $context) {\n let inCode = $context.parent.type.spec.code;\n let dom, slice;\n if (!html && !text)\n return null;\n let asText = !!text && (plainText || inCode || !html);\n if (asText) {\n view.someProp(\"transformPastedText\", f => { text = f(text, inCode || plainText, view); });\n if (inCode) {\n slice = new Slice(Fragment.from(view.state.schema.text(text.replace(/\\r\\n?/g, \"\\n\"))), 0, 0);\n view.someProp(\"transformPasted\", f => { slice = f(slice, view, true); });\n return slice;\n }\n let parsed = view.someProp(\"clipboardTextParser\", f => f(text, $context, plainText, view));\n if (parsed) {\n slice = parsed;\n }\n else {\n let marks = $context.marks();\n let { schema } = view.state, serializer = DOMSerializer.fromSchema(schema);\n dom = document.createElement(\"div\");\n text.split(/(?:\\r\\n?|\\n)+/).forEach(block => {\n let p = dom.appendChild(document.createElement(\"p\"));\n if (block)\n p.appendChild(serializer.serializeNode(schema.text(block, marks)));\n });\n }\n }\n else {\n view.someProp(\"transformPastedHTML\", f => { html = f(html, view); });\n dom = readHTML(html);\n if (webkit)\n restoreReplacedSpaces(dom);\n }\n let contextNode = dom && dom.querySelector(\"[data-pm-slice]\");\n let sliceData = contextNode && /^(\\d+) (\\d+)(?: -(\\d+))? (.*)/.exec(contextNode.getAttribute(\"data-pm-slice\") || \"\");\n if (sliceData && sliceData[3])\n for (let i = +sliceData[3]; i > 0; i--) {\n let child = dom.firstChild;\n while (child && !isElt(child))\n child = child.nextSibling;\n if (!child)\n break;\n dom = child;\n }\n if (!slice) {\n let parser = view.someProp(\"clipboardParser\") || view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n slice = parser.parseSlice(dom, {\n preserveWhitespace: !!(asText || sliceData),\n context: $context,\n ruleFromNode(dom) {\n if (dom.nodeName == \"BR\" && !dom.nextSibling &&\n dom.parentNode && !inlineParents.test(dom.parentNode.nodeName))\n return { ignore: true };\n return null;\n }\n });\n }\n if (sliceData) {\n slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[4]);\n }\n else { // HTML wasn't created by ProseMirror. Make sure top-level siblings are coherent\n slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), true);\n if (slice.openStart || slice.openEnd) {\n let openStart = 0, openEnd = 0;\n for (let node = slice.content.firstChild; openStart < slice.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) { }\n for (let node = slice.content.lastChild; openEnd < slice.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) { }\n slice = closeSlice(slice, openStart, openEnd);\n }\n }\n view.someProp(\"transformPasted\", f => { slice = f(slice, view, asText); });\n return slice;\n}\nconst inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;\n// Takes a slice parsed with parseSlice, which means there hasn't been\n// any content-expression checking done on the top nodes, tries to\n// find a parent node in the current context that might fit the nodes,\n// and if successful, rebuilds the slice so that it fits into that parent.\n//\n// This addresses the problem that Transform.replace expects a\n// coherent slice, and will fail to place a set of siblings that don't\n// fit anywhere in the schema.\nfunction normalizeSiblings(fragment, $context) {\n if (fragment.childCount < 2)\n return fragment;\n for (let d = $context.depth; d >= 0; d--) {\n let parent = $context.node(d);\n let match = parent.contentMatchAt($context.index(d));\n let lastWrap, result = [];\n fragment.forEach(node => {\n if (!result)\n return;\n let wrap = match.findWrapping(node.type), inLast;\n if (!wrap)\n return result = null;\n if (inLast = result.length && lastWrap.length && addToSibling(wrap, lastWrap, node, result[result.length - 1], 0)) {\n result[result.length - 1] = inLast;\n }\n else {\n if (result.length)\n result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length);\n let wrapped = withWrappers(node, wrap);\n result.push(wrapped);\n match = match.matchType(wrapped.type);\n lastWrap = wrap;\n }\n });\n if (result)\n return Fragment.from(result);\n }\n return fragment;\n}\nfunction withWrappers(node, wrap, from = 0) {\n for (let i = wrap.length - 1; i >= from; i--)\n node = wrap[i].create(null, Fragment.from(node));\n return node;\n}\n// Used to group adjacent nodes wrapped in similar parents by\n// normalizeSiblings into the same parent node\nfunction addToSibling(wrap, lastWrap, node, sibling, depth) {\n if (depth < wrap.length && depth < lastWrap.length && wrap[depth] == lastWrap[depth]) {\n let inner = addToSibling(wrap, lastWrap, node, sibling.lastChild, depth + 1);\n if (inner)\n return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner));\n let match = sibling.contentMatchAt(sibling.childCount);\n if (match.matchType(depth == wrap.length - 1 ? node.type : wrap[depth + 1]))\n return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap, depth + 1))));\n }\n}\nfunction closeRight(node, depth) {\n if (depth == 0)\n return node;\n let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1));\n let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true);\n return node.copy(fragment.append(fill));\n}\nfunction closeRange(fragment, side, from, to, depth, openEnd) {\n let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content;\n if (fragment.childCount > 1)\n openEnd = 0;\n if (depth < to - 1)\n inner = closeRange(inner, side, from, to, depth + 1, openEnd);\n if (depth >= from)\n inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner)\n : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true));\n return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner));\n}\nfunction closeSlice(slice, openStart, openEnd) {\n if (openStart < slice.openStart)\n slice = new Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd);\n if (openEnd < slice.openEnd)\n slice = new Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd);\n return slice;\n}\n// Trick from jQuery -- some elements must be wrapped in other\n// elements for innerHTML to work. I.e. if you do `div.innerHTML =\n// \"..\"` the table cells are ignored.\nconst wrapMap = {\n thead: [\"table\"],\n tbody: [\"table\"],\n tfoot: [\"table\"],\n caption: [\"table\"],\n colgroup: [\"table\"],\n col: [\"table\", \"colgroup\"],\n tr: [\"table\", \"tbody\"],\n td: [\"table\", \"tbody\", \"tr\"],\n th: [\"table\", \"tbody\", \"tr\"]\n};\nfunction detachedDoc() {\n return document.implementation.createHTMLDocument(\"title\");\n}\nlet _policy = null;\nfunction maybeWrapTrusted(html) {\n let trustedTypes = window.trustedTypes;\n if (!trustedTypes)\n return html;\n // With the require-trusted-types-for CSP, Chrome will block\n // innerHTML, even on a detached document. This wraps the string in\n // a way that makes the browser allow us to use its parser again.\n if (!_policy) {\n if (_policy = trustedTypes.defaultPolicy)\n try {\n return _policy.createHTML(html);\n }\n catch (_a) { }\n _policy = trustedTypes.createPolicy(\"ProseMirrorClipboard\", { createHTML: (s) => s });\n }\n return _policy.createHTML(html);\n}\nfunction readHTML(html) {\n let metas = /^(\\s*]*>)*/.exec(html);\n if (metas)\n html = html.slice(metas[0].length);\n let doc = detachedDoc(), elt = doc.body;\n let firstTag = /<([a-z][^>\\s]+)/i.exec(html), wrap;\n if (wrap = firstTag && wrapMap[firstTag[1].toLowerCase()])\n html = wrap.map(n => \"<\" + n + \">\").join(\"\") + html + wrap.map(n => \"\").reverse().join(\"\");\n elt.innerHTML = maybeWrapTrusted(html);\n if (wrap)\n for (let i = 0; i < wrap.length; i++)\n elt = elt.querySelector(wrap[i]) || elt;\n // Inline styles defined in the pasted content, so that parse rules pick them up\n for (let i = 0; i < doc.styleSheets.length; i++) {\n let style = doc.styleSheets[i];\n for (let j = 0; j < style.rules.length; j++) {\n let rule = style.rules[j];\n if (rule instanceof CSSStyleRule) {\n let matches = elt.querySelectorAll(rule.selectorText);\n for (let k = 0; k < matches.length; k++)\n matches[k].style.cssText += rule.style.cssText;\n }\n }\n }\n return elt;\n}\n// Webkit browsers do some hard-to-predict replacement of regular\n// spaces with non-breaking spaces when putting content on the\n// clipboard. This tries to convert such non-breaking spaces (which\n// will be wrapped in a plain span on Chrome, a span with class\n// Apple-converted-space on Safari) back to regular spaces.\nfunction restoreReplacedSpaces(dom) {\n let nodes = dom.querySelectorAll(chrome ? \"span:not([class]):not([style])\" : \"span.Apple-converted-space\");\n for (let i = 0; i < nodes.length; i++) {\n let node = nodes[i];\n if (node.childNodes.length == 1 && node.textContent == \"\\u00a0\" && node.parentNode)\n node.parentNode.replaceChild(dom.ownerDocument.createTextNode(\" \"), node);\n }\n}\nfunction addContext(slice, context) {\n if (!slice.size)\n return slice;\n let schema = slice.content.firstChild.type.schema, array;\n try {\n array = JSON.parse(context);\n }\n catch (e) {\n return slice;\n }\n let { content, openStart, openEnd } = slice;\n for (let i = array.length - 2; i >= 0; i -= 2) {\n let type = schema.nodes[array[i]];\n if (!type || type.hasRequiredAttrs())\n break;\n try {\n content = Fragment.from(type.create(array[i + 1], content));\n }\n catch (e) {\n break;\n }\n openStart++;\n openEnd++;\n }\n return new Slice(content, openStart, openEnd);\n}\n\n// A collection of DOM events that occur within the editor, and callback functions\n// to invoke when the event fires.\nconst handlers = {};\nconst editHandlers = {};\nconst passiveHandlers = { touchstart: true, touchmove: true };\nclass InputState {\n constructor() {\n this.shiftKey = false;\n this.mouseDown = null;\n this.lastKeyCode = null;\n this.lastKeyCodeTime = 0;\n this.lastClick = { time: 0, x: 0, y: 0, type: \"\", button: 0 };\n this.lastSelectionOrigin = null;\n this.lastSelectionTime = 0;\n this.lastIOSEnter = 0;\n this.lastIOSEnterFallbackTimeout = -1;\n this.lastFocus = 0;\n this.lastTouch = 0;\n this.lastChromeDelete = 0;\n this.composing = false;\n this.compositionNode = null;\n this.composingTimeout = -1;\n this.compositionNodes = [];\n this.compositionEndedAt = -2e8;\n this.compositionID = 1;\n this.badSafariComposition = false;\n // Set to a composition ID when there are pending changes at compositionend\n this.compositionPendingChanges = 0;\n this.domChangeCount = 0;\n this.eventHandlers = Object.create(null);\n this.hideSelectionGuard = null;\n }\n}\nfunction initInput(view) {\n for (let event in handlers) {\n let handler = handlers[event];\n view.dom.addEventListener(event, view.input.eventHandlers[event] = (event) => {\n if (eventBelongsToView(view, event) && !runCustomHandler(view, event) &&\n (view.editable || !(event.type in editHandlers)))\n handler(view, event);\n }, passiveHandlers[event] ? { passive: true } : undefined);\n }\n // On Safari, for reasons beyond my understanding, adding an input\n // event handler makes an issue where the composition vanishes when\n // you press enter go away.\n if (safari)\n view.dom.addEventListener(\"input\", () => null);\n ensureListeners(view);\n}\nfunction setSelectionOrigin(view, origin) {\n view.input.lastSelectionOrigin = origin;\n view.input.lastSelectionTime = Date.now();\n}\nfunction destroyInput(view) {\n if (view.input.mouseDown)\n view.input.mouseDown.done();\n view.domObserver.stop();\n for (let type in view.input.eventHandlers)\n view.dom.removeEventListener(type, view.input.eventHandlers[type]);\n clearTimeout(view.input.composingTimeout);\n clearTimeout(view.input.lastIOSEnterFallbackTimeout);\n}\nfunction ensureListeners(view) {\n view.someProp(\"handleDOMEvents\", currentHandlers => {\n for (let type in currentHandlers)\n if (!view.input.eventHandlers[type])\n view.dom.addEventListener(type, view.input.eventHandlers[type] = event => runCustomHandler(view, event));\n });\n}\nfunction runCustomHandler(view, event) {\n return view.someProp(\"handleDOMEvents\", handlers => {\n let handler = handlers[event.type];\n return handler ? handler(view, event) || event.defaultPrevented : false;\n });\n}\nfunction eventBelongsToView(view, event) {\n if (!event.bubbles)\n return true;\n if (event.defaultPrevented)\n return false;\n for (let node = event.target; node != view.dom; node = node.parentNode)\n if (!node || node.nodeType == 11 ||\n (node.pmViewDesc && node.pmViewDesc.stopEvent(event)))\n return false;\n return true;\n}\nfunction dispatchEvent(view, event) {\n if (!runCustomHandler(view, event) && handlers[event.type] &&\n (view.editable || !(event.type in editHandlers)))\n handlers[event.type](view, event);\n}\neditHandlers.keydown = (view, _event) => {\n let event = _event;\n view.input.shiftKey = event.keyCode == 16 || event.shiftKey;\n if (inOrNearComposition(view))\n return;\n view.input.lastKeyCode = event.keyCode;\n view.input.lastKeyCodeTime = Date.now();\n // Suppress enter key events on Chrome Android, because those tend\n // to be part of a confused sequence of composition events fired,\n // and handling them eagerly tends to corrupt the input.\n if (android && chrome && event.keyCode == 13)\n return;\n if (event.keyCode != 229)\n view.domObserver.forceFlush();\n // On iOS, if we preventDefault enter key presses, the virtual\n // keyboard gets confused. So the hack here is to set a flag that\n // makes the DOM change code recognize that what just happens should\n // be replaced by whatever the Enter key handlers do.\n if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {\n let now = Date.now();\n view.input.lastIOSEnter = now;\n view.input.lastIOSEnterFallbackTimeout = setTimeout(() => {\n if (view.input.lastIOSEnter == now) {\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")));\n view.input.lastIOSEnter = 0;\n }\n }, 200);\n }\n else if (view.someProp(\"handleKeyDown\", f => f(view, event)) || captureKeyDown(view, event)) {\n event.preventDefault();\n }\n else {\n setSelectionOrigin(view, \"key\");\n }\n};\neditHandlers.keyup = (view, event) => {\n if (event.keyCode == 16)\n view.input.shiftKey = false;\n};\neditHandlers.keypress = (view, _event) => {\n let event = _event;\n if (inOrNearComposition(view) || !event.charCode ||\n event.ctrlKey && !event.altKey || mac && event.metaKey)\n return;\n if (view.someProp(\"handleKeyPress\", f => f(view, event))) {\n event.preventDefault();\n return;\n }\n let sel = view.state.selection;\n if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {\n let text = String.fromCharCode(event.charCode);\n let deflt = () => view.state.tr.insertText(text).scrollIntoView();\n if (!/[\\r\\n]/.test(text) && !view.someProp(\"handleTextInput\", f => f(view, sel.$from.pos, sel.$to.pos, text, deflt)))\n view.dispatch(deflt());\n event.preventDefault();\n }\n};\nfunction eventCoords(event) { return { left: event.clientX, top: event.clientY }; }\nfunction isNear(event, click) {\n let dx = click.x - event.clientX, dy = click.y - event.clientY;\n return dx * dx + dy * dy < 100;\n}\nfunction runHandlerOnContext(view, propName, pos, inside, event) {\n if (inside == -1)\n return false;\n let $pos = view.state.doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n if (view.someProp(propName, f => i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true)\n : f(view, pos, $pos.node(i), $pos.before(i), event, false)))\n return true;\n }\n return false;\n}\nfunction updateSelection(view, selection, origin) {\n if (!view.focused)\n view.focus();\n if (view.state.selection.eq(selection))\n return;\n let tr = view.state.tr.setSelection(selection);\n tr.setMeta(\"pointer\", true);\n view.dispatch(tr);\n}\nfunction selectClickedLeaf(view, inside) {\n if (inside == -1)\n return false;\n let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter;\n if (node && node.isAtom && NodeSelection.isSelectable(node)) {\n updateSelection(view, new NodeSelection($pos));\n return true;\n }\n return false;\n}\nfunction selectClickedNode(view, inside) {\n if (inside == -1)\n return false;\n let sel = view.state.selection, selectedNode, selectAt;\n if (sel instanceof NodeSelection)\n selectedNode = sel.node;\n let $pos = view.state.doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n if (NodeSelection.isSelectable(node)) {\n if (selectedNode && sel.$from.depth > 0 &&\n i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos)\n selectAt = $pos.before(sel.$from.depth);\n else\n selectAt = $pos.before(i);\n break;\n }\n }\n if (selectAt != null) {\n updateSelection(view, NodeSelection.create(view.state.doc, selectAt));\n return true;\n }\n else {\n return false;\n }\n}\nfunction handleSingleClick(view, pos, inside, event, selectNode) {\n return runHandlerOnContext(view, \"handleClickOn\", pos, inside, event) ||\n view.someProp(\"handleClick\", f => f(view, pos, event)) ||\n (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside));\n}\nfunction handleDoubleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleDoubleClickOn\", pos, inside, event) ||\n view.someProp(\"handleDoubleClick\", f => f(view, pos, event));\n}\nfunction handleTripleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleTripleClickOn\", pos, inside, event) ||\n view.someProp(\"handleTripleClick\", f => f(view, pos, event)) ||\n defaultTripleClick(view, inside, event);\n}\nfunction defaultTripleClick(view, inside, event) {\n if (event.button != 0)\n return false;\n let selection = selectionForTripleClick(view, inside, true), doc = view.state.doc;\n if (!selection)\n return false;\n updateSelection(view, selection);\n if (selection instanceof TextSelection && doc.eq(view.state.doc))\n view.input.mouseDown = new TripleClickDrag(view, selection);\n return true;\n}\nfunction selectionForTripleClick(view, inside, selectNodes) {\n let doc = view.state.doc;\n if (inside == -1)\n return doc.inlineContent ? TextSelection.create(doc, 0, doc.content.size) : null;\n let $pos = doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n let nodePos = $pos.before(i);\n if (node.inlineContent)\n return TextSelection.create(doc, nodePos + 1, nodePos + 1 + node.content.size);\n else if (selectNodes && NodeSelection.isSelectable(node))\n return NodeSelection.create(doc, nodePos);\n }\n return null;\n}\nfunction forceDOMFlush(view) {\n return endComposition(view);\n}\nconst selectNodeModifier = mac ? \"metaKey\" : \"ctrlKey\";\nhandlers.mousedown = (view, _event) => {\n let event = _event;\n view.input.shiftKey = event.shiftKey;\n let flushed = forceDOMFlush(view);\n let now = Date.now(), type = \"singleClick\";\n if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier] &&\n view.input.lastClick.button == event.button) {\n if (view.input.lastClick.type == \"singleClick\")\n type = \"doubleClick\";\n else if (view.input.lastClick.type == \"doubleClick\")\n type = \"tripleClick\";\n }\n view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type, button: event.button };\n if (view.input.mouseDown)\n view.input.mouseDown.done();\n let pos = view.posAtCoords(eventCoords(event));\n if (!pos)\n return;\n if (type == \"singleClick\") {\n view.input.mouseDown = new LeftMouseDown(view, pos, event, !!flushed);\n }\n else if ((type == \"doubleClick\" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) {\n event.preventDefault();\n }\n else {\n setSelectionOrigin(view, \"pointer\");\n }\n};\nclass MouseDown {\n constructor(view) {\n this.view = view;\n this.mightDrag = null;\n view.root.addEventListener(\"mouseup\", this.up = this.up.bind(this));\n view.root.addEventListener(\"mousemove\", this.move = this.move.bind(this));\n }\n up(event) {\n this.done();\n }\n move(event) {\n if (event.buttons == 0)\n this.done();\n }\n done() {\n this.view.root.removeEventListener(\"mouseup\", this.up);\n this.view.root.removeEventListener(\"mousemove\", this.move);\n if (this.view.input.mouseDown == this)\n this.view.input.mouseDown = null;\n }\n delaySelUpdate() { return false; }\n}\nclass LeftMouseDown extends MouseDown {\n constructor(view, pos, event, flushed) {\n super(view);\n this.pos = pos;\n this.event = event;\n this.flushed = flushed;\n this.delayedSelectionSync = false;\n this.startDoc = view.state.doc;\n this.selectNode = !!event[selectNodeModifier];\n this.allowDefault = event.shiftKey;\n let targetNode, targetPos;\n if (pos.inside > -1) {\n targetNode = view.state.doc.nodeAt(pos.inside);\n targetPos = pos.inside;\n }\n else {\n let $pos = view.state.doc.resolve(pos.pos);\n targetNode = $pos.parent;\n targetPos = $pos.depth ? $pos.before() : 0;\n }\n const target = flushed ? null : event.target;\n const targetDesc = target ? view.docView.nearestDesc(target, true) : null;\n this.target = targetDesc && isElt(targetDesc.nodeDOM) ? targetDesc.nodeDOM : null;\n let { selection } = view.state;\n if (event.button == 0 &&\n (targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false ||\n selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos))\n this.mightDrag = {\n node: targetNode,\n pos: targetPos,\n addAttr: !!(this.target && !this.target.draggable),\n setUneditable: !!(this.target && gecko && !this.target.hasAttribute(\"contentEditable\"))\n };\n if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) {\n this.view.domObserver.stop();\n if (this.mightDrag.addAttr)\n this.target.draggable = true;\n if (this.mightDrag.setUneditable)\n setTimeout(() => {\n if (this.view.input.mouseDown == this)\n this.target.setAttribute(\"contentEditable\", \"false\");\n }, 20);\n this.view.domObserver.start();\n }\n setSelectionOrigin(view, \"pointer\");\n }\n done() {\n super.done();\n if (this.mightDrag && this.target) {\n this.view.domObserver.stop();\n if (this.mightDrag.addAttr)\n this.target.removeAttribute(\"draggable\");\n if (this.mightDrag.setUneditable)\n this.target.removeAttribute(\"contentEditable\");\n this.view.domObserver.start();\n }\n if (this.delayedSelectionSync)\n setTimeout(() => {\n if (!this.view.isDestroyed)\n selectionToDOM(this.view);\n });\n }\n up(event) {\n this.done();\n if (!this.view.dom.contains(event.target))\n return;\n let pos = this.pos;\n if (this.view.state.doc != this.startDoc)\n pos = this.view.posAtCoords(eventCoords(event));\n this.updateAllowDefault(event);\n if (this.allowDefault || !pos) {\n setSelectionOrigin(this.view, \"pointer\");\n }\n else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {\n event.preventDefault();\n }\n else if (event.button == 0 &&\n (this.flushed ||\n // Safari ignores clicks on draggable elements\n (safari && this.mightDrag && !this.mightDrag.node.isAtom) ||\n // Chrome will sometimes treat a node selection as a\n // cursor, but still report that the node is selected\n // when asked through getSelection. You'll then get a\n // situation where clicking at the point where that\n // (hidden) cursor is doesn't change the selection, and\n // thus doesn't get a reaction from ProseMirror. This\n // works around that.\n (chrome && !this.view.state.selection.visible &&\n Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2))) {\n updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)));\n event.preventDefault();\n }\n else {\n setSelectionOrigin(this.view, \"pointer\");\n }\n }\n move(event) {\n this.updateAllowDefault(event);\n setSelectionOrigin(this.view, \"pointer\");\n super.move(event);\n }\n updateAllowDefault(event) {\n if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 ||\n Math.abs(this.event.y - event.clientY) > 4))\n this.allowDefault = true;\n }\n delaySelUpdate() {\n if (!this.allowDefault)\n return false;\n this.delayedSelectionSync = true;\n return true;\n }\n}\nclass TripleClickDrag extends MouseDown {\n constructor(view, startSelection) {\n super(view);\n this.startSelection = startSelection;\n this.startDoc = view.state.doc;\n }\n move(event) {\n if (event.buttons == 0 || this.view.isDestroyed || !this.view.state.doc.eq(this.startDoc)) {\n this.done();\n return;\n }\n event.preventDefault();\n setSelectionOrigin(this.view, \"pointer\");\n let pos = this.view.posAtCoords(eventCoords(event));\n let target = pos && selectionForTripleClick(this.view, pos.inside, false);\n if (!target)\n return;\n let { doc } = this.view.state, start = this.startSelection;\n let [anchor, head] = target.from < start.from ? [start.to, target.from] : [start.from, target.to];\n updateSelection(this.view, TextSelection.create(doc, anchor, head));\n }\n}\nhandlers.touchstart = view => {\n view.input.lastTouch = Date.now();\n forceDOMFlush(view);\n setSelectionOrigin(view, \"pointer\");\n};\nhandlers.touchmove = view => {\n view.input.lastTouch = Date.now();\n setSelectionOrigin(view, \"pointer\");\n};\nhandlers.contextmenu = view => forceDOMFlush(view);\nfunction inOrNearComposition(view, event) {\n if (view.composing)\n return true;\n // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.\n // On Japanese input method editors (IMEs), the Enter key is used to confirm character\n // selection. On Safari, when Enter is pressed, compositionend and keydown events are\n // emitted. The keydown event triggers newline insertion, which we don't want.\n // This method returns true if the keydown event should be ignored.\n // We only ignore it once, as pressing Enter a second time *should* insert a newline.\n // Furthermore, the keydown event timestamp must be close to the compositionEndedAt timestamp.\n // This guards against the case where compositionend is triggered without the keyboard\n // (e.g. character confirmation may be done with the mouse), and keydown is triggered\n // afterwards- we wouldn't want to ignore the keydown event in this case.\n if (safari && Math.abs(Date.now() - view.input.compositionEndedAt) < 500) {\n view.input.compositionEndedAt = -2e8;\n return true;\n }\n return false;\n}\n// Drop active composition after 5 seconds of inactivity on Android\nconst timeoutComposition = android ? 5000 : -1;\neditHandlers.compositionstart = editHandlers.compositionupdate = view => {\n if (!view.composing) {\n view.domObserver.flush();\n let { state } = view, $pos = state.selection.$to;\n if (state.selection instanceof TextSelection && state.selection.empty &&\n (state.storedMarks ||\n (!$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some(m => m.type.spec.inclusive === false)) ||\n chrome && windows && selectionBeforeUneditable(view))) { // Issue #1500\n // Need to wrap the cursor in mark nodes different from the ones in the DOM context\n view.markCursor = view.state.storedMarks || $pos.marks();\n endComposition(view, true);\n view.markCursor = null;\n }\n else {\n endComposition(view, !state.selection.empty);\n // In firefox, if the cursor is after but outside a marked node,\n // the inserted text won't inherit the marks. So this moves it\n // inside if necessary.\n if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {\n let sel = view.domSelectionRange();\n for (let node = sel.focusNode, offset = sel.focusOffset; node && isElt(node) && offset != 0;) {\n let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1];\n if (!before)\n break;\n if (isText(before)) {\n let sel = view.domSelection();\n if (sel)\n sel.collapse(before, before.nodeValue.length);\n break;\n }\n else {\n node = before;\n offset = -1;\n }\n }\n }\n }\n view.input.composing = true;\n }\n scheduleComposeEnd(view, timeoutComposition);\n};\nfunction selectionBeforeUneditable(view) {\n let { focusNode, focusOffset } = view.domSelectionRange();\n if (!focusNode || !isElt(focusNode) || focusOffset >= focusNode.childNodes.length)\n return false;\n let next = focusNode.childNodes[focusOffset];\n return isElt(next) && next.contentEditable == \"false\";\n}\neditHandlers.compositionend = (view, event) => {\n if (view.composing) {\n view.input.composing = false;\n view.input.compositionEndedAt = Date.now();\n view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0;\n view.input.compositionNode = null;\n if (view.input.badSafariComposition)\n view.domObserver.forceFlush();\n else if (view.input.compositionPendingChanges)\n Promise.resolve().then(() => view.domObserver.flush());\n view.input.compositionID++;\n scheduleComposeEnd(view, 20);\n }\n};\nfunction scheduleComposeEnd(view, delay) {\n clearTimeout(view.input.composingTimeout);\n if (delay > -1)\n view.input.composingTimeout = setTimeout(() => endComposition(view), delay);\n}\nfunction clearComposition(view) {\n if (view.composing) {\n view.input.composing = false;\n view.input.compositionEndedAt = Date.now();\n }\n while (view.input.compositionNodes.length > 0)\n view.input.compositionNodes.pop().markParentsDirty();\n}\nfunction findCompositionNode(view) {\n let sel = view.domSelectionRange();\n if (!sel.focusNode)\n return null;\n let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset);\n let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset);\n if (textBefore && textAfter && textBefore != textAfter) {\n let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode;\n if (textBefore == lastChanged || textAfter == lastChanged)\n return lastChanged;\n if (!descAfter || !descAfter.isText(textAfter.nodeValue)) {\n return textAfter;\n }\n else if (view.input.compositionNode == textAfter) {\n let descBefore = textBefore.pmViewDesc;\n if (!(!descBefore || !descBefore.isText(textBefore.nodeValue)))\n return textAfter;\n }\n }\n return textBefore || textAfter;\n}\n/**\n@internal\n*/\nfunction endComposition(view, restarting = false) {\n if (android && view.domObserver.flushingSoon >= 0)\n return;\n view.domObserver.forceFlush();\n clearComposition(view);\n if (restarting || view.docView && view.docView.dirty) {\n let sel = selectionFromDOM(view), cur = view.state.selection;\n if (sel && !sel.eq(cur))\n view.dispatch(view.state.tr.setSelection(sel));\n else if ((view.markCursor || restarting) && !cur.$from.node(cur.$from.sharedDepth(cur.to)).inlineContent)\n view.dispatch(view.state.tr.deleteSelection());\n else\n view.updateState(view.state);\n return true;\n }\n return false;\n}\nfunction captureCopy(view, dom) {\n // The extra wrapper is somehow necessary on IE/Edge to prevent the\n // content from being mangled when it is put onto the clipboard\n if (!view.dom.parentNode)\n return;\n let wrap = view.dom.parentNode.appendChild(document.createElement(\"div\"));\n wrap.appendChild(dom);\n wrap.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n let sel = getSelection(), range = document.createRange();\n range.selectNodeContents(dom);\n // Done because IE will fire a selectionchange moving the selection\n // to its start when removeAllRanges is called and the editor still\n // has focus (which will mess up the editor's selection state).\n view.dom.blur();\n sel.removeAllRanges();\n sel.addRange(range);\n setTimeout(() => {\n if (wrap.parentNode)\n wrap.parentNode.removeChild(wrap);\n view.focus();\n }, 50);\n}\n// This is very crude, but unfortunately both these browsers _pretend_\n// that they have a clipboard API—all the objects and methods are\n// there, they just don't work, and they are hard to test.\nconst brokenClipboardAPI = (ie && ie_version < 15) ||\n (ios && webkit_version < 604);\nhandlers.copy = editHandlers.cut = (view, _event) => {\n let event = _event;\n let sel = view.state.selection, cut = event.type == \"cut\";\n if (sel.empty)\n return;\n // IE and Edge's clipboard interface is completely broken\n let data = brokenClipboardAPI ? null : event.clipboardData;\n let slice = sel.content(), { dom, text } = serializeForClipboard(view, slice);\n if (data) {\n event.preventDefault();\n data.clearData();\n data.setData(\"text/html\", dom.innerHTML);\n data.setData(\"text/plain\", text);\n }\n else {\n captureCopy(view, dom);\n }\n if (cut)\n view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta(\"uiEvent\", \"cut\"));\n};\nfunction sliceSingleNode(slice) {\n return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null;\n}\nfunction capturePaste(view, event) {\n if (!view.dom.parentNode)\n return;\n let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code;\n let target = view.dom.parentNode.appendChild(document.createElement(plainText ? \"textarea\" : \"div\"));\n if (!plainText)\n target.contentEditable = \"true\";\n target.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n target.focus();\n let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n setTimeout(() => {\n view.focus();\n if (target.parentNode)\n target.parentNode.removeChild(target);\n if (plainText)\n doPaste(view, target.value, null, plain, event);\n else\n doPaste(view, target.textContent, target.innerHTML, plain, event);\n }, 50);\n}\nfunction doPaste(view, text, html, preferPlain, event) {\n let slice = parseFromClipboard(view, text, html, preferPlain, view.state.selection.$from);\n if (view.someProp(\"handlePaste\", f => f(view, event, slice || Slice.empty)))\n return true;\n if (!slice)\n return false;\n let singleNode = sliceSingleNode(slice);\n let tr = singleNode\n ? view.state.tr.replaceSelectionWith(singleNode, preferPlain)\n : view.state.tr.replaceSelection(slice);\n view.dispatch(tr.scrollIntoView().setMeta(\"paste\", true).setMeta(\"uiEvent\", \"paste\"));\n return true;\n}\nfunction getText(clipboardData) {\n let text = clipboardData.getData(\"text/plain\") || clipboardData.getData(\"Text\");\n if (text)\n return text;\n let uris = clipboardData.getData(\"text/uri-list\");\n return uris ? uris.replace(/\\r?\\n/g, \" \") : \"\";\n}\neditHandlers.paste = (view, _event) => {\n let event = _event;\n // Handling paste from JavaScript during composition is very poorly\n // handled by browsers, so as a dodgy but preferable kludge, we just\n // let the browser do its native thing there, except on Android,\n // where the editor is almost always composing.\n if (view.composing && !android)\n return;\n let data = brokenClipboardAPI ? null : event.clipboardData;\n let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n if (data && doPaste(view, getText(data), data.getData(\"text/html\"), plain, event))\n event.preventDefault();\n else\n capturePaste(view, event);\n};\nclass Dragging {\n constructor(slice, move, node) {\n this.slice = slice;\n this.move = move;\n this.node = node;\n }\n}\nconst dragCopyModifier = mac ? \"altKey\" : \"ctrlKey\";\nfunction dragMoves(view, event) {\n let copy;\n view.someProp(\"dragCopies\", test => { copy = copy || test(event); });\n return copy != null ? !copy : !event[dragCopyModifier];\n}\nhandlers.dragstart = (view, _event) => {\n let event = _event;\n let mouseDown = view.input.mouseDown;\n if (mouseDown)\n mouseDown.done();\n if (!event.dataTransfer)\n return;\n let sel = view.state.selection;\n let pos = sel.empty ? null : view.posAtCoords(eventCoords(event));\n let node;\n if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ;\n else if (mouseDown && mouseDown.mightDrag) {\n node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos);\n }\n else if (event.target && isElt(event.target)) {\n let desc = view.docView.nearestDesc(event.target, true);\n if (desc && desc.node.type.spec.draggable && desc != view.docView)\n node = NodeSelection.create(view.state.doc, desc.posBefore);\n }\n let draggedSlice = (node || view.state.selection).content();\n let { dom, text, slice } = serializeForClipboard(view, draggedSlice);\n // Pre-120 Chrome versions clear files when calling `clearData` (#1472)\n if (!event.dataTransfer.files.length || !chrome || chrome_version > 120)\n event.dataTransfer.clearData();\n event.dataTransfer.setData(brokenClipboardAPI ? \"Text\" : \"text/html\", dom.innerHTML);\n // See https://code.haverbeke.berlin/prosemirror/prosemirror/issues/1156\n event.dataTransfer.effectAllowed = \"copyMove\";\n if (!brokenClipboardAPI)\n event.dataTransfer.setData(\"text/plain\", text);\n view.dragging = new Dragging(slice, dragMoves(view, event), node);\n};\nhandlers.dragend = view => {\n let dragging = view.dragging;\n window.setTimeout(() => {\n if (view.dragging == dragging)\n view.dragging = null;\n }, 50);\n};\neditHandlers.dragover = editHandlers.dragenter = (_, e) => e.preventDefault();\neditHandlers.drop = (view, event) => {\n try {\n handleDrop(view, event, view.dragging);\n }\n finally {\n view.dragging = null;\n }\n};\nfunction handleDrop(view, event, dragging) {\n if (!event.dataTransfer)\n return;\n let eventPos = view.posAtCoords(eventCoords(event));\n if (!eventPos)\n return;\n let $mouse = view.state.doc.resolve(eventPos.pos);\n let slice = dragging && dragging.slice;\n if (slice) {\n view.someProp(\"transformPasted\", f => { slice = f(slice, view, false); });\n }\n else {\n slice = parseFromClipboard(view, getText(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData(\"text/html\"), false, $mouse);\n }\n let move = !!(dragging && dragMoves(view, event));\n if (view.someProp(\"handleDrop\", f => f(view, event, slice || Slice.empty, move))) {\n event.preventDefault();\n return;\n }\n if (!slice)\n return;\n event.preventDefault();\n let insertPos = slice ? dropPoint(view.state.doc, $mouse.pos, slice) : $mouse.pos;\n if (insertPos == null)\n insertPos = $mouse.pos;\n let tr = view.state.tr;\n if (move) {\n let { node } = dragging;\n if (node)\n node.replace(tr);\n else\n tr.deleteSelection();\n }\n let pos = tr.mapping.map(insertPos);\n let isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1;\n let beforeInsert = tr.doc;\n if (isNode)\n tr.replaceRangeWith(pos, pos, slice.content.firstChild);\n else\n tr.replaceRange(pos, pos, slice);\n if (tr.doc.eq(beforeInsert))\n return;\n let $pos = tr.doc.resolve(pos);\n if (isNode && NodeSelection.isSelectable(slice.content.firstChild) &&\n $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice.content.firstChild)) {\n tr.setSelection(new NodeSelection($pos));\n }\n else {\n let end = tr.mapping.map(insertPos);\n tr.mapping.maps[tr.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo);\n tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(end)));\n }\n view.focus();\n view.dispatch(tr.setMeta(\"uiEvent\", \"drop\"));\n}\nhandlers.focus = view => {\n view.input.lastFocus = Date.now();\n if (!view.focused) {\n view.domObserver.stop();\n view.dom.classList.add(\"ProseMirror-focused\");\n view.domObserver.start();\n view.focused = true;\n setTimeout(() => {\n if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange()))\n selectionToDOM(view);\n }, 20);\n }\n};\nhandlers.blur = (view, _event) => {\n let event = _event;\n if (view.focused) {\n view.domObserver.stop();\n view.dom.classList.remove(\"ProseMirror-focused\");\n view.domObserver.start();\n if (event.relatedTarget && view.dom.contains(event.relatedTarget))\n view.domObserver.currentSelection.clear();\n view.focused = false;\n }\n};\nhandlers.beforeinput = (view, _event) => {\n let event = _event;\n // We should probably do more with beforeinput events, but support\n // is so spotty that I'm still waiting to see where they are going.\n // Very specific hack to deal with backspace sometimes failing on\n // Chrome and Firefox Android when after an uneditable node.\n if (android && event.inputType == \"deleteContentBackward\") {\n view.domObserver.flushSoon();\n let { domChangeCount } = view.input;\n setTimeout(() => {\n if (view.input.domChangeCount != domChangeCount)\n return; // Event already had some effect\n // This bug tends to close the virtual keyboard, so we refocus\n view.dom.blur();\n view.focus();\n if (view.someProp(\"handleKeyDown\", f => f(view, keyEvent(8, \"Backspace\"))))\n return;\n let { $cursor } = view.state.selection;\n // Crude approximation of backspace behavior when no command handled it\n if ($cursor && $cursor.pos > 0)\n view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView());\n }, 50);\n }\n};\n// Make sure all handlers get registered\nfor (let prop in editHandlers)\n handlers[prop] = editHandlers[prop];\n\nfunction compareObjs(a, b) {\n if (a == b)\n return true;\n for (let p in a)\n if (a[p] !== b[p])\n return false;\n for (let p in b)\n if (!(p in a))\n return false;\n return true;\n}\nclass FragmentCursor {\n constructor(frag) {\n this.frag = frag;\n this.index = 0;\n this.off = 0;\n }\n nodeAt(off) {\n while (this.off <= off && this.index < this.frag.childCount) {\n let next = this.frag.child(this.index);\n if (this.off == off)\n return next;\n this.off += next.nodeSize;\n this.index++;\n }\n return null;\n }\n}\nclass WidgetType {\n constructor(toDOM, spec) {\n this.toDOM = toDOM;\n this.spec = spec || noSpec;\n this.side = this.spec.side || 0;\n }\n map(mapping, span, offset, oldOffset) {\n let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);\n return deleted ? null : new Decoration(pos - offset, pos - offset, this);\n }\n valid() { return true; }\n eq(other) {\n return this == other ||\n (other instanceof WidgetType &&\n (this.spec.key && this.spec.key == other.spec.key ||\n this.toDOM == other.toDOM && compareObjs(this.spec, other.spec)));\n }\n destroy(node) {\n if (this.spec.destroy)\n this.spec.destroy(node);\n }\n}\nclass InlineType {\n constructor(attrs, spec) {\n this.attrs = attrs;\n this.spec = spec || noSpec;\n }\n map(mapping, span, offset, oldOffset) {\n let from = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;\n let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;\n return from >= to ? null : new Decoration(from, to, this);\n }\n valid(_, span) { return span.from < span.to; }\n eq(other) {\n return this == other ||\n (other instanceof InlineType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec));\n }\n static is(span) { return span.type instanceof InlineType; }\n destroy() { }\n}\nclass NodeType {\n constructor(attrs, spec) {\n this.attrs = attrs;\n this.spec = spec || noSpec;\n }\n map(mapping, span, offset, oldOffset) {\n let from = mapping.mapResult(span.from + oldOffset, 1);\n if (from.deleted)\n return null;\n let to = mapping.mapResult(span.to + oldOffset, -1);\n if (to.deleted || to.pos <= from.pos)\n return null;\n return new Decoration(from.pos - offset, to.pos - offset, this);\n }\n valid(node, span, cursor) {\n let found = cursor.nodeAt(span.from);\n return !!found && !found.isText && span.from + found.nodeSize == span.to;\n }\n eq(other) {\n return this == other ||\n (other instanceof NodeType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec));\n }\n destroy() { }\n}\n/**\nDecoration objects can be provided to the view through the\n[`decorations` prop](https://prosemirror.net/docs/ref/#view.EditorProps.decorations). They come in\nseveral variants—see the static members of this class for details.\n*/\nclass Decoration {\n /**\n @internal\n */\n constructor(\n /**\n The start position of the decoration.\n */\n from, \n /**\n The end position. Will be the same as `from` for [widget\n decorations](https://prosemirror.net/docs/ref/#view.Decoration^widget).\n */\n to, \n /**\n @internal\n */\n type) {\n this.from = from;\n this.to = to;\n this.type = type;\n }\n /**\n @internal\n */\n copy(from, to) {\n return new Decoration(from, to, this.type);\n }\n /**\n @internal\n */\n eq(other, offset = 0) {\n return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to;\n }\n /**\n @internal\n */\n map(mapping, offset, oldOffset) {\n return this.type.map(mapping, this, offset, oldOffset);\n }\n /**\n Creates a widget decoration, which is a DOM node that's shown in\n the document at the given position. It is recommended that you\n delay rendering the widget by passing a function that will be\n called when the widget is actually drawn in a view, but you can\n also directly pass a DOM node. `getPos` can be used to find the\n widget's current document position.\n */\n static widget(pos, toDOM, spec) {\n return new Decoration(pos, pos, new WidgetType(toDOM, spec));\n }\n /**\n Creates an inline decoration, which adds the given attributes to\n each inline node between `from` and `to`.\n */\n static inline(from, to, attrs, spec) {\n return new Decoration(from, to, new InlineType(attrs, spec));\n }\n /**\n Creates a node decoration. `from` and `to` should point precisely\n before and after a node in the document. That node, and only that\n node, will receive the given attributes.\n */\n static node(from, to, attrs, spec) {\n return new Decoration(from, to, new NodeType(attrs, spec));\n }\n /**\n The spec provided when creating this decoration. Can be useful\n if you've stored extra information in that object.\n */\n get spec() { return this.type.spec; }\n /**\n @internal\n */\n get inline() { return this.type instanceof InlineType; }\n /**\n @internal\n */\n get widget() { return this.type instanceof WidgetType; }\n}\nconst none = [], noSpec = {};\n/**\nA collection of [decorations](https://prosemirror.net/docs/ref/#view.Decoration), organized in such\na way that the drawing algorithm can efficiently use and compare\nthem. This is a persistent data structure—it is not modified,\nupdates create a new value.\n*/\nclass DecorationSet {\n /**\n @internal\n */\n constructor(local, children) {\n this.local = local.length ? local : none;\n this.children = children.length ? children : none;\n }\n /**\n Create a set of decorations, using the structure of the given\n document. This will consume (modify) the `decorations` array, so\n you must make a copy if you want need to preserve that.\n */\n static create(doc, decorations) {\n return decorations.length ? buildTree(decorations, doc, 0, noSpec) : empty;\n }\n /**\n Find all decorations in this set which touch the given range\n (including decorations that start or end directly at the\n boundaries) and match the given predicate on their spec. When\n `start` and `end` are omitted, all decorations in the set are\n considered. When `predicate` isn't given, all decorations are\n assumed to match.\n */\n find(start, end, predicate) {\n let result = [];\n this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate);\n return result;\n }\n findInner(start, end, result, offset, predicate) {\n for (let i = 0; i < this.local.length; i++) {\n let span = this.local[i];\n if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec)))\n result.push(span.copy(span.from + offset, span.to + offset));\n }\n for (let i = 0; i < this.children.length; i += 3) {\n if (this.children[i] < end && this.children[i + 1] > start) {\n let childOff = this.children[i] + 1;\n this.children[i + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate);\n }\n }\n }\n /**\n Map the set of decorations in response to a change in the\n document.\n */\n map(mapping, doc, options) {\n if (this == empty || mapping.maps.length == 0)\n return this;\n return this.mapInner(mapping, doc, 0, 0, options || noSpec);\n }\n /**\n @internal\n */\n mapInner(mapping, node, offset, oldOffset, options) {\n let newLocal;\n if (this.local.length) {\n let cur = new FragmentCursor(node.content);\n for (let i = 0; i < this.local.length; i++) {\n let mapped = this.local[i].map(mapping, offset, oldOffset);\n if (mapped && mapped.type.valid(node, mapped, cur))\n (newLocal || (newLocal = [])).push(mapped);\n else if (options.onRemove)\n options.onRemove(this.local[i].spec);\n }\n }\n if (this.children.length)\n return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options);\n else\n return newLocal ? new DecorationSet(newLocal.sort(byPos), none) : empty;\n }\n /**\n Add the given array of decorations to the ones in the set,\n producing a new set. Consumes the `decorations` array. Needs\n access to the current document to create the appropriate tree\n structure.\n */\n add(doc, decorations) {\n if (!decorations.length)\n return this;\n if (this == empty)\n return DecorationSet.create(doc, decorations);\n return this.addInner(doc, decorations, 0);\n }\n addInner(doc, decorations, offset) {\n let children, childIndex = 0;\n doc.forEach((childNode, childOffset) => {\n let baseOffset = childOffset + offset, found;\n if (!(found = takeSpansForNode(decorations, childNode, baseOffset)))\n return;\n if (!children)\n children = this.children.slice();\n while (childIndex < children.length && children[childIndex] < childOffset)\n childIndex += 3;\n if (children[childIndex] == childOffset)\n children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found, baseOffset + 1);\n else\n children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found, childNode, baseOffset + 1, noSpec));\n childIndex += 3;\n });\n let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset);\n if (local.length) {\n let cur = new FragmentCursor(doc.content);\n for (let i = 0; i < local.length; i++)\n if (!local[i].type.valid(doc, local[i], cur))\n local.splice(i--, 1);\n }\n return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children);\n }\n /**\n Create a new set that contains the decorations in this set, minus\n the ones in the given array.\n */\n remove(decorations) {\n if (decorations.length == 0 || this == empty)\n return this;\n return this.removeInner(decorations, 0);\n }\n removeInner(decorations, offset) {\n let children = this.children, local = this.local;\n for (let i = 0; i < children.length; i += 3) {\n let found;\n let from = children[i] + offset, to = children[i + 1] + offset;\n for (let j = 0, span; j < decorations.length; j++)\n if (span = decorations[j]) {\n if (span.from > from && span.to < to) {\n decorations[j] = null;\n (found || (found = [])).push(span);\n }\n }\n if (!found)\n continue;\n if (children == this.children)\n children = this.children.slice();\n let removed = children[i + 2].removeInner(found, from + 1);\n if (removed != empty) {\n children[i + 2] = removed;\n }\n else {\n children.splice(i, 3);\n i -= 3;\n }\n }\n if (local.length)\n for (let i = 0, span; i < decorations.length; i++)\n if (span = decorations[i]) {\n for (let j = 0; j < local.length; j++)\n if (local[j].eq(span, offset)) {\n if (local == this.local)\n local = this.local.slice();\n local.splice(j--, 1);\n }\n }\n if (children == this.children && local == this.local)\n return this;\n return local.length || children.length ? new DecorationSet(local, children) : empty;\n }\n forChild(offset, node) {\n if (this == empty)\n return this;\n if (node.isLeaf)\n return DecorationSet.empty;\n let child, local;\n for (let i = 0; i < this.children.length; i += 3)\n if (this.children[i] >= offset) {\n if (this.children[i] == offset)\n child = this.children[i + 2];\n break;\n }\n let start = offset + 1, end = start + node.content.size;\n for (let i = 0; i < this.local.length; i++) {\n let dec = this.local[i];\n if (dec.from < end && dec.to > start && (dec.type instanceof InlineType)) {\n let from = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start;\n if (from < to)\n (local || (local = [])).push(dec.copy(from, to));\n }\n }\n if (local) {\n let localSet = new DecorationSet(local.sort(byPos), none);\n return child ? new DecorationGroup([localSet, child]) : localSet;\n }\n return child || empty;\n }\n /**\n @internal\n */\n eq(other) {\n if (this == other)\n return true;\n if (!(other instanceof DecorationSet) ||\n this.local.length != other.local.length ||\n this.children.length != other.children.length)\n return false;\n for (let i = 0; i < this.local.length; i++)\n if (!this.local[i].eq(other.local[i]))\n return false;\n for (let i = 0; i < this.children.length; i += 3)\n if (this.children[i] != other.children[i] ||\n this.children[i + 1] != other.children[i + 1] ||\n !this.children[i + 2].eq(other.children[i + 2]))\n return false;\n return true;\n }\n /**\n @internal\n */\n locals(node) {\n return removeOverlap(this.localsInner(node));\n }\n /**\n @internal\n */\n localsInner(node) {\n if (this == empty)\n return none;\n if (node.inlineContent || !this.local.some(InlineType.is))\n return this.local;\n let result = [];\n for (let i = 0; i < this.local.length; i++) {\n if (!(this.local[i].type instanceof InlineType))\n result.push(this.local[i]);\n }\n return result;\n }\n forEachSet(f) { f(this); }\n}\n/**\nThe empty set of decorations.\n*/\nDecorationSet.empty = new DecorationSet([], []);\n/**\n@internal\n*/\nDecorationSet.removeOverlap = removeOverlap;\nconst empty = DecorationSet.empty;\n// An abstraction that allows the code dealing with decorations to\n// treat multiple DecorationSet objects as if it were a single object\n// with (a subset of) the same interface.\nclass DecorationGroup {\n constructor(members) {\n this.members = members;\n }\n map(mapping, doc) {\n const mappedDecos = this.members.map(member => member.map(mapping, doc, noSpec));\n return DecorationGroup.from(mappedDecos);\n }\n forChild(offset, child) {\n if (child.isLeaf)\n return DecorationSet.empty;\n let found = [];\n for (let i = 0; i < this.members.length; i++) {\n let result = this.members[i].forChild(offset, child);\n if (result == empty)\n continue;\n if (result instanceof DecorationGroup)\n found = found.concat(result.members);\n else\n found.push(result);\n }\n return DecorationGroup.from(found);\n }\n eq(other) {\n if (!(other instanceof DecorationGroup) ||\n other.members.length != this.members.length)\n return false;\n for (let i = 0; i < this.members.length; i++)\n if (!this.members[i].eq(other.members[i]))\n return false;\n return true;\n }\n locals(node) {\n let result, sorted = true;\n for (let i = 0; i < this.members.length; i++) {\n let locals = this.members[i].localsInner(node);\n if (!locals.length)\n continue;\n if (!result) {\n result = locals;\n }\n else {\n if (sorted) {\n result = result.slice();\n sorted = false;\n }\n for (let j = 0; j < locals.length; j++)\n result.push(locals[j]);\n }\n }\n return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none;\n }\n // Create a group for the given array of decoration sets, or return\n // a single set when possible.\n static from(members) {\n switch (members.length) {\n case 0: return empty;\n case 1: return members[0];\n default: return new DecorationGroup(members.every(m => m instanceof DecorationSet) ? members :\n members.reduce((r, m) => r.concat(m instanceof DecorationSet ? m : m.members), []));\n }\n }\n forEachSet(f) {\n for (let i = 0; i < this.members.length; i++)\n this.members[i].forEachSet(f);\n }\n}\nfunction mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) {\n let children = oldChildren.slice();\n // Mark the children that are directly touched by changes, and\n // move those that are after the changes.\n for (let i = 0, baseOffset = oldOffset; i < mapping.maps.length; i++) {\n let moved = 0;\n mapping.maps[i].forEach((oldStart, oldEnd, newStart, newEnd) => {\n let dSize = (newEnd - newStart) - (oldEnd - oldStart);\n for (let i = 0; i < children.length; i += 3) {\n let end = children[i + 1];\n if (end < 0 || oldStart > end + baseOffset - moved)\n continue;\n let start = children[i] + baseOffset - moved;\n if (oldEnd >= start) {\n children[i + 1] = oldStart <= start ? -2 : -1;\n }\n else if (oldStart >= baseOffset && dSize) {\n children[i] += dSize;\n children[i + 1] += dSize;\n }\n }\n moved += dSize;\n });\n baseOffset = mapping.maps[i].map(baseOffset, -1);\n }\n // Find the child nodes that still correspond to a single node,\n // recursively call mapInner on them and update their positions.\n let mustRebuild = false;\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] < 0) { // Touched nodes\n if (children[i + 1] == -2) {\n mustRebuild = true;\n children[i + 1] = -1;\n continue;\n }\n let from = mapping.map(oldChildren[i] + oldOffset), fromLocal = from - offset;\n if (fromLocal < 0 || fromLocal >= node.content.size) {\n mustRebuild = true;\n continue;\n }\n // Must read oldChildren because children was tagged with -1\n let to = mapping.map(oldChildren[i + 1] + oldOffset, -1), toLocal = to - offset;\n let { index, offset: childOffset } = node.content.findIndex(fromLocal);\n let childNode = node.maybeChild(index);\n if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {\n let mapped = children[i + 2]\n .mapInner(mapping, childNode, from + 1, oldChildren[i] + oldOffset + 1, options);\n if (mapped != empty) {\n children[i] = fromLocal;\n children[i + 1] = toLocal;\n children[i + 2] = mapped;\n }\n else {\n children[i + 1] = -2;\n mustRebuild = true;\n }\n }\n else {\n mustRebuild = true;\n }\n }\n // Remaining children must be collected and rebuilt into the appropriate structure\n if (mustRebuild) {\n let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options);\n let built = buildTree(decorations, node, 0, options);\n newLocal = built.local;\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] < 0) {\n children.splice(i, 3);\n i -= 3;\n }\n for (let i = 0, j = 0; i < built.children.length; i += 3) {\n let from = built.children[i];\n while (j < children.length && children[j] < from)\n j += 3;\n children.splice(j, 0, built.children[i], built.children[i + 1], built.children[i + 2]);\n }\n }\n return new DecorationSet(newLocal.sort(byPos), children);\n}\nfunction moveSpans(spans, offset) {\n if (!offset || !spans.length)\n return spans;\n let result = [];\n for (let i = 0; i < spans.length; i++) {\n let span = spans[i];\n result.push(new Decoration(span.from + offset, span.to + offset, span.type));\n }\n return result;\n}\nfunction mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) {\n // Gather all decorations from the remaining marked children\n function gather(set, oldOffset) {\n for (let i = 0; i < set.local.length; i++) {\n let mapped = set.local[i].map(mapping, offset, oldOffset);\n if (mapped)\n decorations.push(mapped);\n else if (options.onRemove)\n options.onRemove(set.local[i].spec);\n }\n for (let i = 0; i < set.children.length; i += 3)\n gather(set.children[i + 2], set.children[i] + oldOffset + 1);\n }\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] == -1)\n gather(children[i + 2], oldChildren[i] + oldOffset + 1);\n return decorations;\n}\nfunction takeSpansForNode(spans, node, offset) {\n if (node.isLeaf)\n return null;\n let end = offset + node.nodeSize, found = null;\n for (let i = 0, span; i < spans.length; i++) {\n if ((span = spans[i]) && span.from > offset && span.to < end) {\n (found || (found = [])).push(span);\n spans[i] = null;\n }\n }\n return found;\n}\nfunction withoutNulls(array) {\n let result = [];\n for (let i = 0; i < array.length; i++)\n if (array[i] != null)\n result.push(array[i]);\n return result;\n}\n// Build up a tree that corresponds to a set of decorations. `offset`\n// is a base offset that should be subtracted from the `from` and `to`\n// positions in the spans (so that we don't have to allocate new spans\n// for recursive calls).\nfunction buildTree(spans, node, offset, options) {\n let children = [], hasNulls = false;\n node.forEach((childNode, localStart) => {\n let found = takeSpansForNode(spans, childNode, localStart + offset);\n if (found) {\n hasNulls = true;\n let subtree = buildTree(found, childNode, offset + localStart + 1, options);\n if (subtree != empty)\n children.push(localStart, localStart + childNode.nodeSize, subtree);\n }\n });\n let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);\n if (locals.length) {\n let cur = new FragmentCursor(node.content);\n for (let i = 0; i < locals.length; i++)\n if (!locals[i].type.valid(node, locals[i], cur)) {\n if (options.onRemove)\n options.onRemove(locals[i].spec);\n locals.splice(i--, 1);\n }\n }\n return locals.length || children.length ? new DecorationSet(locals, children) : empty;\n}\n// Used to sort decorations so that ones with a low start position\n// come first, and within a set with the same start position, those\n// with an smaller end position come first.\nfunction byPos(a, b) {\n return a.from - b.from || a.to - b.to;\n}\n// Scan a sorted array of decorations for partially overlapping spans,\n// and split those so that only fully overlapping spans are left (to\n// make subsequent rendering easier). Will return the input array if\n// no partially overlapping spans are found (the common case).\nfunction removeOverlap(spans) {\n let working = spans;\n for (let i = 0; i < working.length - 1; i++) {\n let span = working[i];\n if (span.from != span.to)\n for (let j = i + 1; j < working.length; j++) {\n let next = working[j];\n if (next.from == span.from) {\n if (next.to != span.to) {\n if (working == spans)\n working = spans.slice();\n // Followed by a partially overlapping larger span. Split that\n // span.\n working[j] = next.copy(next.from, span.to);\n insertAhead(working, j + 1, next.copy(span.to, next.to));\n }\n continue;\n }\n else {\n if (next.from < span.to) {\n if (working == spans)\n working = spans.slice();\n // The end of this one overlaps with a subsequent span. Split\n // this one.\n working[i] = span.copy(span.from, next.from);\n insertAhead(working, j, span.copy(next.from, span.to));\n }\n break;\n }\n }\n }\n return working;\n}\nfunction insertAhead(array, i, deco) {\n while (i < array.length && byPos(deco, array[i]) > 0)\n i++;\n array.splice(i, 0, deco);\n}\n// Get the decorations associated with the current props of a view.\nfunction viewDecorations(view) {\n let found = [];\n view.someProp(\"decorations\", f => {\n let result = f(view.state);\n if (result && result != empty)\n found.push(result);\n });\n if (view.cursorWrapper)\n found.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco]));\n return DecorationGroup.from(found);\n}\n\nconst observeOptions = {\n childList: true,\n characterData: true,\n characterDataOldValue: true,\n attributes: true,\n attributeOldValue: true,\n subtree: true\n};\n// IE11 has very broken mutation observers, so we also listen to DOMCharacterDataModified\nconst useCharData = ie && ie_version <= 11;\nclass SelectionState {\n constructor() {\n this.anchorNode = null;\n this.anchorOffset = 0;\n this.focusNode = null;\n this.focusOffset = 0;\n }\n set(sel) {\n this.anchorNode = sel.anchorNode;\n this.anchorOffset = sel.anchorOffset;\n this.focusNode = sel.focusNode;\n this.focusOffset = sel.focusOffset;\n }\n clear() {\n this.anchorNode = this.focusNode = null;\n }\n eq(sel) {\n return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset &&\n sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset;\n }\n}\nclass DOMObserver {\n constructor(view, handleDOMChange) {\n this.view = view;\n this.handleDOMChange = handleDOMChange;\n this.queue = [];\n this.flushingSoon = -1;\n this.observer = null;\n this.currentSelection = new SelectionState;\n this.onCharData = null;\n this.suppressingSelectionUpdates = false;\n this.lastChangedTextNode = null;\n this.observer = window.MutationObserver &&\n new window.MutationObserver(mutations => {\n for (let i = 0; i < mutations.length; i++)\n this.queue.push(mutations[i]);\n if (ie && ie_version <= 11 && mutations.some(m => m.type == \"childList\" && m.removedNodes.length ||\n m.type == \"characterData\" && m.oldValue.length > m.target.nodeValue.length)) {\n // IE11 will sometimes (on backspacing out a single character\n // text node after a BR node) call the observer callback\n // before actually updating the DOM, which will cause\n // ProseMirror to miss the change (see #930)\n this.flushSoon();\n }\n else if (safari && view.composing && mutations.some(m => m.type == \"childList\" && m.target.nodeName == \"TR\")) {\n // Safari does weird stuff when finishing a composition in a\n // table cell, which tends to involve inserting inappropriate\n // nodes in the table row.\n view.input.badSafariComposition = true;\n this.flushSoon();\n }\n else {\n this.flush();\n }\n });\n if (useCharData) {\n this.onCharData = e => {\n this.queue.push({ target: e.target, type: \"characterData\", oldValue: e.prevValue });\n this.flushSoon();\n };\n }\n this.onSelectionChange = this.onSelectionChange.bind(this);\n }\n flushSoon() {\n if (this.flushingSoon < 0)\n this.flushingSoon = window.setTimeout(() => { this.flushingSoon = -1; this.flush(); }, 20);\n }\n forceFlush() {\n if (this.flushingSoon > -1) {\n window.clearTimeout(this.flushingSoon);\n this.flushingSoon = -1;\n this.flush();\n }\n }\n start() {\n if (this.observer) {\n this.observer.takeRecords();\n this.observer.observe(this.view.dom, observeOptions);\n }\n if (this.onCharData)\n this.view.dom.addEventListener(\"DOMCharacterDataModified\", this.onCharData);\n this.connectSelection();\n }\n stop() {\n if (this.observer) {\n let take = this.observer.takeRecords();\n if (take.length) {\n for (let i = 0; i < take.length; i++)\n this.queue.push(take[i]);\n window.setTimeout(() => this.flush(), 20);\n }\n this.observer.disconnect();\n }\n if (this.onCharData)\n this.view.dom.removeEventListener(\"DOMCharacterDataModified\", this.onCharData);\n this.disconnectSelection();\n }\n connectSelection() {\n this.view.dom.ownerDocument.addEventListener(\"selectionchange\", this.onSelectionChange);\n }\n disconnectSelection() {\n this.view.dom.ownerDocument.removeEventListener(\"selectionchange\", this.onSelectionChange);\n }\n suppressSelectionUpdates() {\n this.suppressingSelectionUpdates = true;\n setTimeout(() => this.suppressingSelectionUpdates = false, 50);\n }\n onSelectionChange() {\n if (!hasFocusAndSelection(this.view))\n return;\n if (this.suppressingSelectionUpdates)\n return selectionToDOM(this.view);\n // Deletions on IE11 fire their events in the wrong order, giving\n // us a selection change event before the DOM changes are\n // reported.\n if (ie && ie_version <= 11 && !this.view.state.selection.empty) {\n let sel = this.view.domSelectionRange();\n // Selection.isCollapsed isn't reliable on IE\n if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))\n return this.flushSoon();\n }\n this.flush();\n }\n setCurSelection() {\n this.currentSelection.set(this.view.domSelectionRange());\n }\n ignoreSelectionChange(sel) {\n if (!sel.focusNode)\n return true;\n let ancestors = new Set, container;\n for (let scan = sel.focusNode; scan; scan = parentNode(scan))\n ancestors.add(scan);\n for (let scan = sel.anchorNode; scan; scan = parentNode(scan))\n if (ancestors.has(scan)) {\n container = scan;\n break;\n }\n let desc = container && this.view.docView.nearestDesc(container);\n if (desc && desc.ignoreMutation({\n type: \"selection\",\n target: isText(container) ? container.parentNode : container\n })) {\n this.setCurSelection();\n return true;\n }\n }\n pendingRecords() {\n if (this.observer)\n for (let mut of this.observer.takeRecords())\n this.queue.push(mut);\n return this.queue;\n }\n flush() {\n let { view } = this;\n if (!view.docView || this.flushingSoon > -1)\n return;\n let mutations = this.pendingRecords();\n if (mutations.length)\n this.queue = [];\n let selRange, newSel = false;\n if (!this.suppressingSelectionUpdates && hasFocusAndSelection(view)) {\n selRange = view.domSelectionRange();\n newSel = !this.currentSelection.eq(selRange) && !this.ignoreSelectionChange(selRange);\n }\n let from = -1, to = -1, typeOver = false, added = [];\n if (view.editable) {\n for (let i = 0; i < mutations.length; i++) {\n let result = this.registerMutation(mutations[i], added);\n if (result) {\n from = from < 0 ? result.from : Math.min(result.from, from);\n to = to < 0 ? result.to : Math.max(result.to, to);\n if (result.typeOver)\n typeOver = true;\n }\n }\n }\n if (added.some(n => n.nodeName == \"BR\") &&\n (view.input.lastKeyCode == 8 || view.input.lastKeyCode == 46 ||\n chrome && (view.composing || view.input.compositionEndedAt > Date.now() - 50) &&\n mutations.some(m => m.type == \"childList\" && m.removedNodes.length))) {\n // Browsers sometimes insert a bogus break node if you\n // backspace out the last bit of text before an inline-flex node (#1552)\n for (let node of added)\n if (node.nodeName == \"BR\" && node.parentNode) {\n let after = node.nextSibling;\n while (after && isElt(after)) {\n if (after.contentEditable == \"false\") {\n node.parentNode.removeChild(node);\n break;\n }\n after = after.firstChild;\n }\n }\n }\n else if (gecko && added.length) {\n let brs = added.filter(n => n.nodeName == \"BR\");\n if (brs.length == 2) {\n let [a, b] = brs;\n if (a.parentNode && a.parentNode.parentNode == b.parentNode)\n b.remove();\n else\n a.remove();\n }\n else {\n let { focusNode } = this.currentSelection;\n for (let br of brs) {\n let parent = br.parentNode;\n if (parent && parent.nodeName == \"LI\" && (!focusNode || blockParent(view, focusNode) != parent))\n br.remove();\n }\n }\n }\n let readSel = null;\n // If it looks like the browser has reset the selection to the\n // start of the document after focus, restore the selection from\n // the state\n if (from < 0 && newSel && view.input.lastFocus > Date.now() - 200 &&\n Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 &&\n selectionCollapsed(selRange) && (readSel = selectionFromDOM(view)) &&\n readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) {\n view.input.lastFocus = 0;\n selectionToDOM(view);\n this.currentSelection.set(selRange);\n view.scrollToSelection();\n }\n else if (from > -1 || newSel) {\n if (from > -1) {\n view.docView.markDirty(from, to);\n checkCSS(view);\n }\n if (view.input.badSafariComposition) {\n view.input.badSafariComposition = false;\n fixUpBadSafariComposition(view, added);\n }\n this.handleDOMChange(from, to, typeOver, added);\n if (view.docView && view.docView.dirty)\n view.updateState(view.state);\n else if (selRange && !this.currentSelection.eq(selRange))\n selectionToDOM(view);\n if (selRange)\n this.currentSelection.set(selRange);\n }\n }\n registerMutation(mut, added) {\n // Ignore mutations inside nodes that were already noted as inserted\n if (added.indexOf(mut.target) > -1)\n return null;\n let desc = this.view.docView.nearestDesc(mut.target);\n if (mut.type == \"attributes\" &&\n (desc == this.view.docView || mut.attributeName == \"contenteditable\" ||\n // Firefox sometimes fires spurious events for null/empty styles\n (mut.attributeName == \"style\" && !mut.oldValue && !mut.target.getAttribute(\"style\"))))\n return null;\n if (!desc || desc.ignoreMutation(mut))\n return null;\n if (mut.type == \"childList\") {\n for (let i = 0; i < mut.addedNodes.length; i++) {\n let node = mut.addedNodes[i];\n added.push(node);\n if (isText(node))\n this.lastChangedTextNode = node;\n }\n if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target))\n return { from: desc.posBefore, to: desc.posAfter };\n let prev = mut.previousSibling, next = mut.nextSibling;\n if (ie && ie_version <= 11 && mut.addedNodes.length) {\n // IE11 gives us incorrect next/prev siblings for some\n // insertions, so if there are added nodes, recompute those\n for (let i = 0; i < mut.addedNodes.length; i++) {\n let { previousSibling, nextSibling } = mut.addedNodes[i];\n if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0)\n prev = previousSibling;\n if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0)\n next = nextSibling;\n }\n }\n let fromOffset = prev && prev.parentNode == mut.target\n ? domIndex(prev) + 1 : 0;\n let from = desc.localPosFromDOM(mut.target, fromOffset, -1);\n let toOffset = next && next.parentNode == mut.target\n ? domIndex(next) : mut.target.childNodes.length;\n let to = desc.localPosFromDOM(mut.target, toOffset, 1);\n return { from, to };\n }\n else if (mut.type == \"attributes\") {\n return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border };\n }\n else { // \"characterData\"\n this.lastChangedTextNode = mut.target;\n return {\n from: desc.posAtStart,\n to: desc.posAtEnd,\n // An event was generated for a text change that didn't change\n // any text. Mark the dom change to fall back to assuming the\n // selection was typed over with an identical value if it can't\n // find another change.\n typeOver: mut.target.nodeValue == mut.oldValue\n };\n }\n }\n}\nlet cssChecked = new WeakMap();\nlet cssCheckWarned = false;\nfunction checkCSS(view) {\n if (cssChecked.has(view))\n return;\n cssChecked.set(view, null);\n if (['normal', 'nowrap', 'pre-line'].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) {\n view.requiresGeckoHackNode = gecko;\n if (cssCheckWarned)\n return;\n console[\"warn\"](\"ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.\");\n cssCheckWarned = true;\n }\n}\nfunction rangeToSelectionRange(view, range) {\n let anchorNode = range.startContainer, anchorOffset = range.startOffset;\n let focusNode = range.endContainer, focusOffset = range.endOffset;\n let currentAnchor = view.domAtPos(view.state.selection.anchor);\n // Since such a range doesn't distinguish between anchor and head,\n // use a heuristic that flips it around if its end matches the\n // current anchor.\n if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset))\n [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];\n return { anchorNode, anchorOffset, focusNode, focusOffset };\n}\n// Used to work around a Safari Selection/shadow DOM bug\n// Based on https://github.com/codemirror/dev/issues/414 fix\nfunction safariShadowSelectionRange(view, selection) {\n if (selection.getComposedRanges) {\n let range = selection.getComposedRanges(view.root)[0];\n if (range)\n return rangeToSelectionRange(view, range);\n }\n let found;\n function read(event) {\n event.preventDefault();\n event.stopImmediatePropagation();\n found = event.getTargetRanges()[0];\n }\n // Because Safari (at least in 2018-2022) doesn't provide regular\n // access to the selection inside a shadowRoot, we have to perform a\n // ridiculous hack to get at it—using `execCommand` to trigger a\n // `beforeInput` event so that we can read the target range from the\n // event.\n view.dom.addEventListener(\"beforeinput\", read, true);\n document.execCommand(\"indent\");\n view.dom.removeEventListener(\"beforeinput\", read, true);\n return found ? rangeToSelectionRange(view, found) : null;\n}\nfunction blockParent(view, node) {\n for (let p = node.parentNode; p && p != view.dom; p = p.parentNode) {\n let desc = view.docView.nearestDesc(p, true);\n if (desc && desc.node.isBlock)\n return p;\n }\n return null;\n}\n// Kludge for a Safari bug where, on ending a composition in an\n// otherwise empty table cell, it randomly moves the composed text\n// into the table row around that cell, greatly confusing everything\n// (#188).\nfunction fixUpBadSafariComposition(view, addedNodes) {\n var _a;\n let { focusNode, focusOffset } = view.domSelectionRange();\n for (let node of addedNodes) {\n if (((_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.nodeName) == \"TR\") {\n let nextCell = node.nextSibling;\n while (nextCell && (nextCell.nodeName != \"TD\" && nextCell.nodeName != \"TH\"))\n nextCell = nextCell.nextSibling;\n if (nextCell) {\n let parent = nextCell;\n for (;;) {\n let first = parent.firstChild;\n if (!first || !isElt(first) || first.contentEditable == \"false\" || /^(BR|IMG)$/.test(first.nodeName))\n break;\n parent = first;\n }\n parent.insertBefore(node, parent.firstChild);\n if (focusNode == node)\n view.domSelection().collapse(node, focusOffset);\n }\n else {\n node.parentNode.removeChild(node);\n }\n }\n }\n}\n\n// Note that all referencing and parsing is done with the\n// start-of-operation selection and document, since that's the one\n// that the DOM represents. If any changes came in in the meantime,\n// the modification is mapped over those before it is applied, in\n// readDOMChange.\nfunction parseBetween(view, from_, to_, addedNodes) {\n let { node: parent, fromOffset, toOffset, from, to } = view.docView.parseRange(from_, to_);\n let domSel = view.domSelectionRange();\n let find;\n let anchor = domSel.anchorNode;\n if (anchor && contains(view.dom, anchor)) {\n find = [{ node: anchor, offset: domSel.anchorOffset }];\n if (!selectionCollapsed(domSel))\n find.push({ node: domSel.focusNode, offset: domSel.focusOffset });\n }\n // Work around issue in Chrome where backspacing sometimes replaces\n // the deleted content with a random BR node (issues #799, #831)\n if (chrome && view.input.lastKeyCode === 8) {\n for (let off = toOffset; off > fromOffset; off--) {\n let node = parent.childNodes[off - 1], desc = node.pmViewDesc;\n if (node.nodeName == \"BR\" && !desc) {\n toOffset = off;\n break;\n }\n if (!desc || desc.size)\n break;\n }\n }\n let startDoc = view.state.doc;\n let parser = view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n let $from = startDoc.resolve(from);\n let sel = null, doc = parser.parse(parent, {\n topNode: $from.parent,\n topMatch: $from.parent.contentMatchAt($from.index()),\n topOpen: true,\n from: fromOffset,\n to: toOffset,\n preserveWhitespace: $from.parent.type.whitespace == \"pre\" ? \"full\" : true,\n findPositions: find,\n ruleFromNode: ruleFromNode(addedNodes),\n context: $from\n });\n if (find && find[0].pos != null) {\n let anchor = find[0].pos, head = find[1] && find[1].pos;\n if (head == null)\n head = anchor;\n sel = { anchor: anchor + from, head: head + from };\n }\n return { doc, sel, from, to };\n}\nconst ruleFromNode = (added) => (dom) => {\n let desc = dom.pmViewDesc;\n if (desc) {\n return desc.parseRule(added);\n }\n else if (dom.nodeName == \"BR\" && dom.parentNode) {\n // Safari replaces the list item or table cell with a BR\n // directly in the list node (?!) if you delete the last\n // character in a list item or table cell (#708, #862)\n if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {\n let skip = document.createElement(\"div\");\n skip.appendChild(document.createElement(\"li\"));\n return { skip };\n }\n else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {\n return { ignore: true };\n }\n }\n else if (dom.nodeName == \"IMG\" && dom.getAttribute(\"mark-placeholder\")) {\n return { ignore: true };\n }\n return null;\n};\nconst isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;\nfunction readDOMChange(view, from, to, typeOver, addedNodes) {\n let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0);\n view.input.compositionPendingChanges = 0;\n if (from < 0) {\n let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null;\n let newSel = selectionFromDOM(view, origin);\n if (newSel && !view.state.selection.eq(newSel)) {\n if (chrome && android &&\n view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\"))))\n return;\n let tr = view.state.tr.setSelection(newSel);\n if (origin == \"pointer\")\n tr.setMeta(\"pointer\", true);\n else if (origin == \"key\")\n tr.scrollIntoView();\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n view.dispatch(tr);\n }\n return;\n }\n let $before = view.state.doc.resolve(from);\n let shared = $before.sharedDepth(to);\n from = $before.before(shared + 1);\n to = view.state.doc.resolve(to).after(shared + 1);\n let sel = view.state.selection;\n let parse = parseBetween(view, from, to, addedNodes);\n let doc = view.state.doc, compare = doc.slice(parse.from, parse.to);\n let preferredPos, preferredSide;\n // Prefer anchoring to end when Backspace is pressed\n if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) {\n preferredPos = view.state.selection.to;\n preferredSide = \"end\";\n }\n else {\n preferredPos = view.state.selection.from;\n preferredSide = \"start\";\n }\n view.input.lastKeyCode = null;\n let change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide);\n if (change)\n view.input.domChangeCount++;\n if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) &&\n addedNodes.some(n => isElt(n) && !isInline.test(n.nodeName)) &&\n (!change || change.endA >= change.endB) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")))) {\n view.input.lastIOSEnter = 0;\n return;\n }\n if (!change) {\n if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) &&\n !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) {\n change = { start: sel.from, endA: sel.to, endB: sel.to };\n }\n else {\n if (parse.sel) {\n let sel = resolveSelection(view, view.state.doc, parse.sel);\n if (sel && !sel.eq(view.state.selection)) {\n let tr = view.state.tr.setSelection(sel);\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n view.dispatch(tr);\n }\n }\n return;\n }\n }\n // Handle the case where overwriting a selection by typing matches\n // the start or end of the selected content, creating a change\n // that's smaller than what was actually overwritten.\n if (view.state.selection.from < view.state.selection.to &&\n change.start == change.endB &&\n view.state.selection instanceof TextSelection) {\n if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 &&\n view.state.selection.from >= parse.from) {\n change.start = view.state.selection.from;\n }\n else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 &&\n view.state.selection.to <= parse.to) {\n change.endB += (view.state.selection.to - change.endA);\n change.endA = view.state.selection.to;\n }\n }\n // IE11 will insert a non-breaking space _ahead_ of the space after\n // the cursor space when adding a space before another space. When\n // that happened, adjust the change to cover the space instead.\n if (ie && ie_version <= 11 && change.endB == change.start + 1 &&\n change.endA == change.start && change.start > parse.from &&\n parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == \" \\u00a0\") {\n change.start--;\n change.endA--;\n change.endB--;\n }\n let $from = parse.doc.resolveNoCache(change.start - parse.from);\n let $to = parse.doc.resolveNoCache(change.endB - parse.from);\n let $fromA = doc.resolve(change.start);\n let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA;\n // If this looks like the effect of pressing Enter (or was recorded\n // as being an iOS enter press), just dispatch an Enter key instead.\n if (((ios && view.input.lastIOSEnter > Date.now() - 225 &&\n (!inlineChange || addedNodes.some(n => n.nodeName == \"DIV\" || n.nodeName == \"P\"))) ||\n (!inlineChange && looksLikeEnter(parse.doc, $from.pos, $to.pos))) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")))) {\n view.input.lastIOSEnter = 0;\n return;\n }\n // Same for backspace\n if (view.state.selection.anchor > change.start &&\n (inlineChange ? change.endA > change.start && change.endB == change.start\n : looksLikeBlockJoin(doc, change.start, change.endA, $from, $to)) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(8, \"Backspace\")))) {\n if (android && chrome)\n view.domObserver.suppressSelectionUpdates(); // #820\n return;\n }\n // Chrome will occasionally, during composition, delete the\n // entire composition and then immediately insert it again. This is\n // used to detect that situation.\n if (chrome && change.endB == change.start)\n view.input.lastChromeDelete = Date.now();\n // This tries to detect Android virtual keyboard\n // enter-and-pick-suggestion action. That sometimes (see issue\n // #1059) first fires a DOM mutation, before moving the selection to\n // the newly created block. And then, because ProseMirror cleans up\n // the DOM selection, it gives up moving the selection entirely,\n // leaving the cursor in the wrong place. When that happens, we drop\n // the new paragraph from the initial change, and fire a simulated\n // enter key afterwards.\n if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth &&\n parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) {\n change.endB -= 2;\n $to = parse.doc.resolveNoCache(change.endB - parse.from);\n setTimeout(() => {\n view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(13, \"Enter\")); });\n }, 20);\n }\n let chFrom = change.start, chTo = change.endA;\n let mkTr = (base) => {\n let tr = base || view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from));\n if (parse.sel) {\n let sel = resolveSelection(view, tr.doc, parse.sel);\n // Chrome will sometimes, during composition, report the\n // selection in the wrong place. If it looks like that is\n // happening, don't update the selection.\n // Edge just doesn't move the cursor forward when you start typing\n // in an empty block or between br nodes.\n if (sel && !(chrome && view.composing && sel.empty &&\n (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) &&\n (sel.head == chFrom || sel.head == tr.mapping.map(chTo) - 1) ||\n ie && sel.empty && sel.head == chFrom))\n tr.setSelection(sel);\n }\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n return tr.scrollIntoView();\n };\n let markChange;\n if (inlineChange) {\n if ($from.pos == $to.pos) { // Deletion\n // IE11 sometimes weirdly moves the DOM selection around after\n // backspacing out the first element in a textblock\n if (ie && ie_version <= 11 && $from.parentOffset == 0) {\n view.domObserver.suppressSelectionUpdates();\n setTimeout(() => selectionToDOM(view), 20);\n }\n let tr = mkTr(view.state.tr.delete(chFrom, chTo));\n let marks = doc.resolve(change.start).marksAcross(doc.resolve(change.endA));\n if (marks)\n tr.ensureMarks(marks);\n view.dispatch(tr);\n }\n else if ( // Adding or removing a mark\n change.endA == change.endB &&\n (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start())))) {\n let tr = mkTr(view.state.tr);\n if (markChange.type == \"add\")\n tr.addMark(chFrom, chTo, markChange.mark);\n else\n tr.removeMark(chFrom, chTo, markChange.mark);\n view.dispatch(tr);\n }\n else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {\n // Both positions in the same text node -- simply insert text\n let text = $from.parent.textBetween($from.parentOffset, $to.parentOffset);\n let deflt = () => mkTr(view.state.tr.insertText(text, chFrom, chTo));\n if (!view.someProp(\"handleTextInput\", f => f(view, chFrom, chTo, text, deflt)))\n view.dispatch(deflt());\n }\n else {\n view.dispatch(mkTr());\n }\n }\n else {\n view.dispatch(mkTr());\n }\n}\nfunction resolveSelection(view, doc, parsedSel) {\n if (Math.max(parsedSel.anchor, parsedSel.head) > doc.content.size)\n return null;\n return selectionBetween(view, doc.resolve(parsedSel.anchor), doc.resolve(parsedSel.head));\n}\n// Given two same-length, non-empty fragments of inline content,\n// determine whether the first could be created from the second by\n// removing or adding a single mark type.\nfunction isMarkChange(cur, prev) {\n let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;\n let added = curMarks, removed = prevMarks, type, mark, update;\n for (let i = 0; i < prevMarks.length; i++)\n added = prevMarks[i].removeFromSet(added);\n for (let i = 0; i < curMarks.length; i++)\n removed = curMarks[i].removeFromSet(removed);\n if (added.length == 1 && removed.length == 0) {\n mark = added[0];\n type = \"add\";\n update = (node) => node.mark(mark.addToSet(node.marks));\n }\n else if (added.length == 0 && removed.length == 1) {\n mark = removed[0];\n type = \"remove\";\n update = (node) => node.mark(mark.removeFromSet(node.marks));\n }\n else {\n return null;\n }\n let updated = [];\n for (let i = 0; i < prev.childCount; i++)\n updated.push(update(prev.child(i)));\n if (Fragment.from(updated).eq(cur))\n return { mark, type };\n}\nfunction looksLikeBlockJoin(old, start, end, $newStart, $newEnd) {\n if ( // The content must have shrunk\n end - start <= $newEnd.pos - $newStart.pos ||\n // newEnd must point directly at or after the end of the block that newStart points into\n skipClosingAndOpening($newStart, true, false) < $newEnd.pos)\n return false;\n let $start = old.resolve(start);\n // Handle the case where, rather than joining blocks, the change just removed an entire block\n if (!$newStart.parent.inlineContent) {\n let after = $start.nodeAfter;\n return after != null && end == start + after.nodeSize;\n }\n // Start must be at the end of a block\n if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock)\n return false;\n let $next = old.resolve(skipClosingAndOpening($start, true, true));\n // The next textblock must start before end and end near it\n if (!$next.parent.isTextblock || $next.pos > end ||\n skipClosingAndOpening($next, true, false) < end)\n return false;\n // The fragments after the join point must match\n return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content);\n}\nfunction looksLikeEnter(content, from, to) {\n let newTextlines = 0, newLeaves = 0;\n content.nodesBetween(from, to, (node, pos) => {\n if (node.isTextblock && pos >= from && pos < to)\n newTextlines++;\n else if (node.isText ? /\\S/.test(node.text.slice(Math.max(0, from - pos), Math.min(node.nodeSize, to - pos))) : node.isLeaf)\n newLeaves++;\n });\n return newLeaves == 0 && newTextlines == 1;\n}\nfunction skipClosingAndOpening($pos, fromEnd, mayOpen) {\n let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos;\n while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {\n depth--;\n end++;\n fromEnd = false;\n }\n if (mayOpen) {\n let next = $pos.node(depth).maybeChild($pos.indexAfter(depth));\n while (next && !next.isLeaf) {\n next = next.firstChild;\n end++;\n }\n }\n return end;\n}\nfunction findDiff(a, b, pos, preferredPos, preferredSide) {\n let start = a.findDiffStart(b, pos), lenA = pos + a.size, lenB = pos + b.size;\n if (start == null)\n return null;\n let { a: endA, b: endB } = a.findDiffEnd(b, lenA, lenB);\n if (preferredSide == \"end\") {\n let adjust = Math.max(0, start - Math.min(endA, endB));\n preferredPos -= endA + adjust - start;\n }\n if (endA < start && lenA < lenB) {\n let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0;\n start -= move;\n endB = start + (endB - endA);\n endA = start;\n }\n else if (endB < start) {\n let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0;\n start -= move;\n endA = start + (endA - endB);\n endB = start;\n }\n return { start, endA, endB };\n}\n\n/**\n@internal\n*/\nconst __parseFromClipboard = parseFromClipboard;\n/**\n@internal\n*/\nconst __endComposition = endComposition;\n/**\nAn editor view manages the DOM structure that represents an\neditable document. Its state and behavior are determined by its\n[props](https://prosemirror.net/docs/ref/#view.DirectEditorProps).\n*/\nclass EditorView {\n /**\n Create a view. `place` may be a DOM node that the editor should\n be appended to, a function that will place it into the document,\n or an object whose `mount` property holds the node to use as the\n document container. If it is `null`, the editor will not be\n added to the document.\n */\n constructor(place, props) {\n this._root = null;\n /**\n @internal\n */\n this.focused = false;\n /**\n Kludge used to work around a Chrome bug @internal\n */\n this.trackWrites = null;\n this.mounted = false;\n /**\n @internal\n */\n this.markCursor = null;\n /**\n @internal\n */\n this.cursorWrapper = null;\n /**\n @internal\n */\n this.lastSelectedViewDesc = undefined;\n /**\n @internal\n */\n this.input = new InputState;\n this.prevDirectPlugins = [];\n this.pluginViews = [];\n /**\n Holds `true` when a hack node is needed in Firefox to prevent the\n [space is eaten issue](https://code.haverbeke.berlin/prosemirror/prosemirror/issues/651)\n @internal\n */\n this.requiresGeckoHackNode = false;\n /**\n When editor content is being dragged, this object contains\n information about the dragged slice and whether it is being\n copied or moved. At any other time, it is null.\n */\n this.dragging = null;\n this._props = props;\n this.state = props.state;\n this.directPlugins = props.plugins || [];\n this.directPlugins.forEach(checkStateComponent);\n this.dispatch = this.dispatch.bind(this);\n this.dom = (place && place.mount) || document.createElement(\"div\");\n if (place) {\n if (place.appendChild)\n place.appendChild(this.dom);\n else if (typeof place == \"function\")\n place(this.dom);\n else if (place.mount)\n this.mounted = true;\n }\n this.editable = getEditable(this);\n updateCursorWrapper(this);\n this.nodeViews = buildNodeViews(this);\n this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);\n this.domObserver = new DOMObserver(this, (from, to, typeOver, added) => readDOMChange(this, from, to, typeOver, added));\n this.domObserver.start();\n initInput(this);\n this.updatePluginViews();\n }\n /**\n Holds `true` when a\n [composition](https://w3c.github.io/uievents/#events-compositionevents)\n is active.\n */\n get composing() { return this.input.composing; }\n /**\n The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps).\n */\n get props() {\n if (this._props.state != this.state) {\n let prev = this._props;\n this._props = {};\n for (let name in prev)\n this._props[name] = prev[name];\n this._props.state = this.state;\n }\n return this._props;\n }\n /**\n Update the view's props. Will immediately cause an update to\n the DOM.\n */\n update(props) {\n if (props.handleDOMEvents != this._props.handleDOMEvents)\n ensureListeners(this);\n let prevProps = this._props;\n this._props = props;\n if (props.plugins) {\n props.plugins.forEach(checkStateComponent);\n this.directPlugins = props.plugins;\n }\n this.updateStateInner(props.state, prevProps);\n }\n /**\n Update the view by updating existing props object with the object\n given as argument. Equivalent to `view.update(Object.assign({},\n view.props, props))`.\n */\n setProps(props) {\n let updated = {};\n for (let name in this._props)\n updated[name] = this._props[name];\n updated.state = this.state;\n for (let name in props)\n updated[name] = props[name];\n this.update(updated);\n }\n /**\n Update the editor's `state` prop, without touching any of the\n other props.\n */\n updateState(state) {\n this.updateStateInner(state, this._props);\n }\n updateStateInner(state, prevProps) {\n var _a;\n let prev = this.state, redraw = false, updateSel = false;\n // When stored marks are added, stop composition, so that they can\n // be displayed.\n if (state.storedMarks && this.composing) {\n clearComposition(this);\n updateSel = true;\n }\n this.state = state;\n let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins;\n if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) {\n let nodeViews = buildNodeViews(this);\n if (changedNodeViews(nodeViews, this.nodeViews)) {\n this.nodeViews = nodeViews;\n redraw = true;\n }\n }\n if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) {\n ensureListeners(this);\n }\n this.editable = getEditable(this);\n updateCursorWrapper(this);\n let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);\n let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? \"reset\"\n : state.scrollToSelection > prev.scrollToSelection ? \"to selection\" : \"preserve\";\n let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);\n if (updateDoc || !state.selection.eq(prev.selection))\n updateSel = true;\n let oldScrollPos = scroll == \"preserve\" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);\n if (updateSel) {\n this.domObserver.stop();\n // Work around an issue in Chrome, IE, and Edge where changing\n // the DOM around an active selection puts it into a broken\n // state where the thing the user sees differs from the\n // selection reported by the Selection object (#710, #973,\n // #1011, #1013, #1035).\n let forceSelUpdate = updateDoc && (ie || chrome) && !this.composing &&\n !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);\n if (updateDoc) {\n // If the node that the selection points into is written to,\n // Chrome sometimes starts misreporting the selection, so this\n // tracks that and forces a selection reset when our update\n // did write to the node.\n let chromeKludge = chrome ? (this.trackWrites = this.domSelectionRange().focusNode) : null;\n if (this.composing)\n this.input.compositionNode = findCompositionNode(this);\n if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {\n this.docView.updateOuterDeco(outerDeco);\n this.docView.destroy();\n this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);\n }\n if (chromeKludge && (!this.trackWrites || !this.dom.contains(this.trackWrites)))\n forceSelUpdate = true;\n }\n // Work around for an issue where an update arriving right between\n // a DOM selection change and the \"selectionchange\" event for it\n // can cause a spurious DOM selection update, disrupting mouse\n // drag selection.\n let mouseDown = this.input.mouseDown;\n if (forceSelUpdate ||\n !(mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) &&\n anchorInRightPlace(this) && mouseDown.delaySelUpdate())) {\n selectionToDOM(this, forceSelUpdate);\n }\n else {\n syncNodeSelection(this, state.selection);\n this.domObserver.setCurSelection();\n }\n this.domObserver.start();\n }\n this.updatePluginViews(prev);\n if (((_a = this.dragging) === null || _a === void 0 ? void 0 : _a.node) && !prev.doc.eq(state.doc))\n this.updateDraggedNode(this.dragging, prev);\n if (scroll == \"reset\") {\n this.dom.scrollTop = 0;\n }\n else if (scroll == \"to selection\") {\n this.scrollToSelection();\n }\n else if (oldScrollPos) {\n resetScrollPos(oldScrollPos);\n }\n }\n /**\n @internal\n */\n scrollToSelection() {\n let startDOM = this.domSelectionRange().focusNode;\n if (!startDOM || !contains(this.dom, startDOM)) ;\n else if (this.someProp(\"handleScrollToSelection\", f => f(this))) ;\n else if (this.state.selection instanceof NodeSelection) {\n let target = this.docView.domAfterPos(this.state.selection.from);\n if (isElt(target))\n scrollRectIntoView(this, target.getBoundingClientRect(), startDOM);\n }\n else {\n scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM);\n }\n }\n destroyPluginViews() {\n let view;\n while (view = this.pluginViews.pop())\n if (view.destroy)\n view.destroy();\n }\n updatePluginViews(prevState) {\n if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {\n this.prevDirectPlugins = this.directPlugins;\n this.destroyPluginViews();\n for (let i = 0; i < this.directPlugins.length; i++) {\n let plugin = this.directPlugins[i];\n if (plugin.spec.view)\n this.pluginViews.push(plugin.spec.view(this));\n }\n for (let i = 0; i < this.state.plugins.length; i++) {\n let plugin = this.state.plugins[i];\n if (plugin.spec.view)\n this.pluginViews.push(plugin.spec.view(this));\n }\n }\n else {\n for (let i = 0; i < this.pluginViews.length; i++) {\n let pluginView = this.pluginViews[i];\n if (pluginView.update)\n pluginView.update(this, prevState);\n }\n }\n }\n updateDraggedNode(dragging, prev) {\n let sel = dragging.node, found = -1;\n if (sel.from < this.state.doc.content.size && this.state.doc.nodeAt(sel.from) == sel.node) {\n found = sel.from;\n }\n else {\n let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size);\n let moved = movedPos > 0 && movedPos < this.state.doc.content.size && this.state.doc.nodeAt(movedPos);\n if (moved == sel.node)\n found = movedPos;\n }\n this.dragging = new Dragging(dragging.slice, dragging.move, found < 0 ? undefined : NodeSelection.create(this.state.doc, found));\n }\n someProp(propName, f) {\n let prop = this._props && this._props[propName], value;\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n for (let i = 0; i < this.directPlugins.length; i++) {\n let prop = this.directPlugins[i].props[propName];\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n }\n let plugins = this.state.plugins;\n if (plugins)\n for (let i = 0; i < plugins.length; i++) {\n let prop = plugins[i].props[propName];\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n }\n }\n /**\n Query whether the view has focus.\n */\n hasFocus() {\n // Work around IE not handling focus correctly if resize handles are shown.\n // If the cursor is inside an element with resize handles, activeElement\n // will be that element instead of this.dom.\n if (ie) {\n // If activeElement is within this.dom, and there are no other elements\n // setting `contenteditable` to false in between, treat it as focused.\n let node = this.root.activeElement;\n if (node == this.dom)\n return true;\n if (!node || !this.dom.contains(node))\n return false;\n while (node && this.dom != node && this.dom.contains(node)) {\n if (node.contentEditable == 'false')\n return false;\n node = node.parentElement;\n }\n return true;\n }\n return this.root.activeElement == this.dom;\n }\n /**\n Focus the editor.\n */\n focus() {\n this.domObserver.stop();\n if (this.editable)\n focusPreventScroll(this.dom);\n selectionToDOM(this);\n this.domObserver.start();\n }\n /**\n Get the document root in which the editor exists. This will\n usually be the top-level `document`, but might be a [shadow\n DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)\n root if the editor is inside one.\n */\n get root() {\n let cached = this._root;\n if (cached == null)\n for (let search = this.dom.parentNode; search; search = search.parentNode) {\n if (search.nodeType == 9 || (search.nodeType == 11 && search.host)) {\n if (!search.getSelection)\n Object.getPrototypeOf(search).getSelection = () => search.ownerDocument.getSelection();\n return this._root = search;\n }\n }\n return cached || document;\n }\n /**\n When an existing editor view is moved to a new document or\n shadow tree, call this to make it recompute its root.\n */\n updateRoot() {\n this._root = null;\n }\n /**\n Given a pair of viewport coordinates, return the document\n position that corresponds to them. May return null if the given\n coordinates aren't inside of the editor. When an object is\n returned, its `pos` property is the position nearest to the\n coordinates, and its `inside` property holds the position of the\n inner node that the position falls inside of, or -1 if it is at\n the top level, not in any node.\n */\n posAtCoords(coords) {\n return posAtCoords(this, coords);\n }\n /**\n Returns the viewport rectangle at a given document position.\n `left` and `right` will be the same number, as this returns a\n flat cursor-ish rectangle. If the position is between two things\n that aren't directly adjacent, `side` determines which element\n is used. When < 0, the element before the position is used,\n otherwise the element after.\n */\n coordsAtPos(pos, side = 1) {\n return coordsAtPos(this, pos, side);\n }\n /**\n Find the DOM position that corresponds to the given document\n position. When `side` is negative, find the position as close as\n possible to the content before the position. When positive,\n prefer positions close to the content after the position. When\n zero, prefer as shallow a position as possible.\n \n Note that you should **not** mutate the editor's internal DOM,\n only inspect it (and even that is usually not necessary).\n */\n domAtPos(pos, side = 0) {\n return this.docView.domFromPos(pos, side);\n }\n /**\n Find the DOM node that represents the document node after the\n given position. May return `null` when the position doesn't point\n in front of a node or if the node is inside an opaque node view.\n \n This is intended to be able to call things like\n `getBoundingClientRect` on that DOM node. Do **not** mutate the\n editor DOM directly, or add styling this way, since that will be\n immediately overriden by the editor as it redraws the node.\n */\n nodeDOM(pos) {\n let desc = this.docView.descAt(pos);\n return desc ? desc.nodeDOM : null;\n }\n /**\n Find the document position that corresponds to a given DOM\n position. (Whenever possible, it is preferable to inspect the\n document structure directly, rather than poking around in the\n DOM, but sometimes—for example when interpreting an event\n target—you don't have a choice.)\n \n The `bias` parameter can be used to influence which side of a DOM\n node to use when the position is inside a leaf node.\n */\n posAtDOM(node, offset, bias = -1) {\n let pos = this.docView.posFromDOM(node, offset, bias);\n if (pos == null)\n throw new RangeError(\"DOM position not inside the editor\");\n return pos;\n }\n /**\n Find out whether the selection is at the end of a textblock when\n moving in a given direction. When, for example, given `\"left\"`,\n it will return true if moving left from the current cursor\n position would leave that position's parent textblock. Will apply\n to the view's current state by default, but it is possible to\n pass a different state.\n */\n endOfTextblock(dir, state) {\n return endOfTextblock(this, state || this.state, dir);\n }\n /**\n Run the editor's paste logic with the given HTML string. The\n `event`, if given, will be passed to the\n [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook.\n */\n pasteHTML(html, event) {\n return doPaste(this, \"\", html, false, event || new ClipboardEvent(\"paste\"));\n }\n /**\n Run the editor's paste logic with the given plain-text input.\n */\n pasteText(text, event) {\n return doPaste(this, text, null, true, event || new ClipboardEvent(\"paste\"));\n }\n /**\n Serialize the given slice as it would be if it was copied from\n this editor. Returns a DOM element that contains a\n representation of the slice as its children, a textual\n representation, and the transformed slice (which can be\n different from the given input due to hooks like\n [`transformCopied`](https://prosemirror.net/docs/ref/#view.EditorProps.transformCopied)).\n */\n serializeForClipboard(slice) {\n return serializeForClipboard(this, slice);\n }\n /**\n Removes the editor from the DOM and destroys all [node\n views](https://prosemirror.net/docs/ref/#view.NodeView).\n */\n destroy() {\n if (!this.docView)\n return;\n destroyInput(this);\n this.destroyPluginViews();\n if (this.mounted) {\n this.docView.update(this.state.doc, [], viewDecorations(this), this);\n this.dom.textContent = \"\";\n }\n else if (this.dom.parentNode) {\n this.dom.parentNode.removeChild(this.dom);\n }\n this.docView.destroy();\n this.docView = null;\n clearReusedRange();\n }\n /**\n This is true when the view has been\n [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be\n used anymore).\n */\n get isDestroyed() {\n return this.docView == null;\n }\n /**\n Used for testing.\n */\n dispatchEvent(event) {\n return dispatchEvent(this, event);\n }\n /**\n @internal\n */\n domSelectionRange() {\n let sel = this.dom.isConnected !== false && this.domSelection();\n if (!sel)\n return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 };\n return safari && this.root.nodeType === 11 &&\n deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel;\n }\n /**\n @internal\n */\n domSelection() {\n return this.root.getSelection();\n }\n}\nEditorView.prototype.dispatch = function (tr) {\n let dispatchTransaction = this._props.dispatchTransaction;\n if (dispatchTransaction)\n dispatchTransaction.call(this, tr);\n else\n this.updateState(this.state.apply(tr));\n};\nfunction computeDocDeco(view) {\n let attrs = Object.create(null);\n attrs.class = \"ProseMirror\";\n attrs.contenteditable = String(view.editable);\n view.someProp(\"attributes\", value => {\n if (typeof value == \"function\")\n value = value(view.state);\n if (value)\n for (let attr in value) {\n if (attr == \"class\")\n attrs.class += \" \" + value[attr];\n else if (attr == \"style\")\n attrs.style = (attrs.style ? attrs.style + \";\" : \"\") + value[attr];\n else if (!attrs[attr] && attr != \"contenteditable\" && attr != \"nodeName\")\n attrs[attr] = String(value[attr]);\n }\n });\n if (!attrs.translate)\n attrs.translate = \"no\";\n return [Decoration.node(0, view.state.doc.content.size, attrs)];\n}\nfunction updateCursorWrapper(view) {\n if (view.markCursor) {\n let dom = document.createElement(\"img\");\n dom.className = \"ProseMirror-separator\";\n dom.setAttribute(\"mark-placeholder\", \"true\");\n dom.setAttribute(\"alt\", \"\");\n view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) };\n }\n else {\n view.cursorWrapper = null;\n }\n}\nfunction getEditable(view) {\n return !view.someProp(\"editable\", value => value(view.state) === false);\n}\nfunction selectionContextChanged(sel1, sel2) {\n let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));\n return sel1.$anchor.start(depth) != sel2.$anchor.start(depth);\n}\nfunction buildNodeViews(view) {\n let result = Object.create(null);\n function add(obj) {\n for (let prop in obj)\n if (!Object.prototype.hasOwnProperty.call(result, prop))\n result[prop] = obj[prop];\n }\n view.someProp(\"nodeViews\", add);\n view.someProp(\"markViews\", add);\n return result;\n}\nfunction changedNodeViews(a, b) {\n let nA = 0, nB = 0;\n for (let prop in a) {\n if (a[prop] != b[prop])\n return true;\n nA++;\n }\n for (let _ in b)\n nB++;\n return nA != nB;\n}\nfunction checkStateComponent(plugin) {\n if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction)\n throw new RangeError(\"Plugins passed directly to the view must not have a state component\");\n}\n\nexport { Decoration, DecorationSet, EditorView, __endComposition, __parseFromClipboard };\n", - "export const EqualityTraitSymbol = Symbol('Equality')\n\n/**\n * @typedef {{ [EqualityTraitSymbol]:(other:EqualityTrait)=>boolean }} EqualityTrait\n */\n\n/**\n *\n * Utility function to compare any two objects.\n *\n * Note that it is expected that the first parameter is more specific than the latter one.\n *\n * @example js\n * class X { [traits.EqualityTraitSymbol] (other) { return other === this } }\n * class X2 { [traits.EqualityTraitSymbol] (other) { return other === this }, x2 () { return 2 } }\n * // this is fine\n * traits.equals(new X2(), new X())\n * // this is not, because the left type is less specific than the right one\n * traits.equals(new X(), new X2())\n *\n * @template {EqualityTrait} T\n * @param {NoInfer} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equals = (a, b) => a === b || !!a?.[EqualityTraitSymbol]?.(b) || false\n", - "import * as equalityTrait from './trait/equality.js'\n\n/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * @param {any} o\n * @return {o is { [k:string]:any }}\n */\nexport const isObject = o => typeof o === 'object'\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[key:string]: V}} obj\n * @return {Array}\n */\nexport const values = Object.values\n\n/**\n * @template V\n * @param {{[k:string]:V}} obj\n * @param {function(V,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @todo implement mapToArray & map\n *\n * @template R\n * @param {Object} obj\n * @param {function(any,string):R} f\n * @return {Array}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @deprecated use object.size instead\n * @param {Object} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @return {number}\n */\nexport const size = obj => keys(obj).length\n\n/**\n * @template {{ [key:string|number|symbol]: any }} T\n * @param {T} obj\n * @param {(v:T[keyof T],k:keyof T)=>boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object|null|undefined} obj\n */\nexport const isEmpty = obj => {\n // eslint-disable-next-line no-unreachable-loop\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @template {{ [key:string|number|symbol]: any }} T\n * @param {T} obj\n * @param {(v:T[keyof T],k:keyof T)=>boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|number|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (size(a) === size(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && equalityTrait.equals(b[key], val)))\n\n/**\n * Make an object immutable. This hurts performance and is usually not needed if you perform good\n * coding practices.\n */\nexport const freeze = Object.freeze\n\n/**\n * Make an object and all its children immutable.\n * This *really* hurts performance and is usually not needed if you perform good coding practices.\n *\n * @template {any} T\n * @param {T} o\n * @return {Readonly}\n */\nexport const deepFreeze = (o) => {\n for (const key in o) {\n const c = o[key]\n if (typeof c === 'object' || typeof c === 'function') {\n deepFreeze(o[key])\n }\n }\n return freeze(o)\n}\n\n/**\n * Get object property. Create T if property is undefined and set T on object.\n *\n * @function\n * @template {object} KV\n * @template {keyof KV} [K=keyof KV]\n * @param {KV} o\n * @param {K} key\n * @param {() => KV[K]} createT\n * @return {KV[K]}\n */\nexport const setIfUndefined = (o, key, createT) => hasProperty(o, key) ? o[key] : (o[key] = createT())\n", - "/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\nimport * as equalityTrait from './trait/equality.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array} fs\n * @param {Array} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array|object} a\n * @param {Array|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((array.isArray(a) && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/* c8 ignore start */\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a === b) {\n return true\n }\n if (a == null || b == null || (a.constructor !== b.constructor && (a.constructor || Object) !== (b.constructor || Object))) {\n return false\n }\n if (a[equalityTrait.EqualityTraitSymbol] != null) {\n return a[equalityTrait.EqualityTraitSymbol](b)\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case undefined:\n case Object:\n if (object.size(a) !== object.size(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n\n/**\n * @template V\n * @template {V} OPTS\n *\n * @param {V} value\n * @param {Array} options\n */\n// @ts-ignore\nexport const isOneOf = (value, options) => options.includes(value)\n/* c8 ignore stop */\n\nexport const isArray = array.isArray\n\n/**\n * @param {any} s\n * @return {s is String}\n */\nexport const isString = (s) => s && s.constructor === String\n\n/**\n * @param {any} n\n * @return {n is Number}\n */\nexport const isNumber = n => n != null && n.constructor === Number\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {any} n\n * @param {TYPE} T\n * @return {n is InstanceType}\n */\nexport const is = (n, T) => n && n.constructor === T\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {TYPE} T\n */\nexport const isTemplate = (T) =>\n /**\n * @param {any} n\n * @return {n is InstanceType}\n **/\n n => n && n.constructor === T\n", - "/**\n * Efficient diffs.\n *\n * @module diff\n */\n\nimport { equalityStrict } from './function.js'\n\n/**\n * A SimpleDiff describes a change on a String.\n *\n * ```js\n * console.log(a) // the old value\n * console.log(b) // the updated value\n * // Apply changes of diff (pseudocode)\n * a.remove(diff.index, diff.remove) // Remove `diff.remove` characters\n * a.insert(diff.index, diff.insert) // Insert `diff.insert`\n * a === b // values match\n * ```\n *\n * @template {string|Array} T\n * @typedef {Object} SimpleDiff\n * @property {Number} index The index where changes were applied\n * @property {Number} remove The number of characters to delete starting\n * at `index`.\n * @property {T} insert The new text to insert at `index` after applying\n */\n\nconst highSurrogateRegex = /[\\uD800-\\uDBFF]/\nconst lowSurrogateRegex = /[\\uDC00-\\uDFFF]/\n\n/**\n * Create a diff between two strings. This diff implementation is highly\n * efficient, but not very sophisticated.\n *\n * @function\n *\n * @param {string} a The old version of the string\n * @param {string} b The updated version of the string\n * @return {SimpleDiff} The diff description.\n */\nexport const simpleDiffString = (a, b) => {\n let left = 0 // number of same characters counting from left\n let right = 0 // number of same characters counting from right\n while (left < a.length && left < b.length && a[left] === b[left]) {\n left++\n }\n // If the last same character is a high surrogate, we need to rollback to the previous character\n if (left > 0 && highSurrogateRegex.test(a[left - 1])) left--\n while (right + left < a.length && right + left < b.length && a[a.length - right - 1] === b[b.length - right - 1]) {\n right++\n }\n // If the last same character is a low surrogate, we need to rollback to the previous character\n if (right > 0 && lowSurrogateRegex.test(a[a.length - right])) right--\n return {\n index: left,\n remove: a.length - left - right,\n insert: b.slice(left, b.length - right)\n }\n}\n\n/**\n * @todo Remove in favor of simpleDiffString\n * @deprecated\n */\nexport const simpleDiff = simpleDiffString\n\n/**\n * Create a diff between two arrays. This diff implementation is highly\n * efficient, but not very sophisticated.\n *\n * Note: This is basically the same function as above. Another function was created so that the runtime\n * can better optimize these function calls.\n *\n * @function\n * @template T\n *\n * @param {Array} a The old version of the array\n * @param {Array} b The updated version of the array\n * @param {function(T, T):boolean} [compare]\n * @return {SimpleDiff>} The diff description.\n */\nexport const simpleDiffArray = (a, b, compare = equalityStrict) => {\n let left = 0 // number of same characters counting from left\n let right = 0 // number of same characters counting from right\n while (left < a.length && left < b.length && compare(a[left], b[left])) {\n left++\n }\n while (right + left < a.length && right + left < b.length && compare(a[a.length - right - 1], b[b.length - right - 1])) {\n right++\n }\n return {\n index: left,\n remove: a.length - left - right,\n insert: b.slice(left, b.length - right)\n }\n}\n\n/**\n * Diff text and try to diff at the current cursor position.\n *\n * @param {string} a\n * @param {string} b\n * @param {number} cursor This should refer to the current left cursor-range position\n */\nexport const simpleDiffStringWithCursor = (a, b, cursor) => {\n let left = 0 // number of same characters counting from left\n let right = 0 // number of same characters counting from right\n // Iterate left to the right until we find a changed character\n // First iteration considers the current cursor position\n while (\n left < a.length &&\n left < b.length &&\n a[left] === b[left] &&\n left < cursor\n ) {\n left++\n }\n // If the last same character is a high surrogate, we need to rollback to the previous character\n if (left > 0 && highSurrogateRegex.test(a[left - 1])) left--\n // Iterate right to the left until we find a changed character\n while (\n right + left < a.length &&\n right + left < b.length &&\n a[a.length - right - 1] === b[b.length - right - 1]\n ) {\n right++\n }\n // If the last same character is a low surrogate, we need to rollback to the previous character\n if (right > 0 && lowSurrogateRegex.test(a[a.length - right])) right--\n // Try to iterate left further to the right without caring about the current cursor position\n while (\n right + left < a.length &&\n right + left < b.length &&\n a[left] === b[left]\n ) {\n left++\n }\n if (left > 0 && highSurrogateRegex.test(a[left - 1])) left--\n return {\n index: left,\n remove: a.length - left - right,\n insert: b.slice(left, b.length - right)\n }\n}\n", - "import { Fragment, Node, Schema, Slice } from \"prosemirror-model\";\nimport { EditorState, Plugin, PluginKey, Selection, TextSelection } from \"prosemirror-state\";\nimport { Awareness, Cursor, EphemeralStore, LoroDoc, LoroList, LoroMap, LoroText, LoroTree, UndoManager, isContainer } from \"loro-crdt\";\nimport { Decoration, DecorationSet, EditorView } from \"prosemirror-view\";\nimport { simpleDiff } from \"lib0/diff\";\nimport { equalityDeep } from \"lib0/function\";\n\n//#region src/lib.ts\nconst ROOT_DOC_KEY = \"doc\";\nconst ATTRIBUTES_KEY = \"attributes\";\nconst CHILDREN_KEY = \"children\";\nconst NODE_NAME_KEY = \"nodeName\";\n/**\n* Maps PM non-text nodes to their corresponding Loro Container IDs.\n*/\nconst WEAK_NODE_TO_LORO_CONTAINER_MAPPING = /* @__PURE__ */ new WeakMap();\nfunction updateLoroToPmState(doc, mapping, editorState, containerId) {\n\tconst node = editorState.doc;\n\tconst map = containerId ? doc.getContainerById(containerId) : doc.getMap(ROOT_DOC_KEY);\n\tlet isInit = false;\n\tif (map.get(\"nodeName\") == null) {\n\t\tdoc.commit();\n\t\tisInit = true;\n\t\tmap.set(\"nodeName\", node.type.name);\n\t}\n\tupdateLoroMap(map, node, mapping);\n\tif (isInit) doc.commit({ origin: \"sys:init\" });\n\telse doc.commit({ origin: \"loroSyncPlugin\" });\n}\nfunction createNodeFromLoroObj(schema, obj, mapping) {\n\tlet retval = mapping.get(obj.id) ?? null;\n\tif (retval != null) return retval;\n\tif (obj instanceof LoroMap) {\n\t\tconst attributes = getLoroMapAttributes(obj);\n\t\tconst children = getLoroMapChildren(obj);\n\t\tconst nodeName = obj.get(\"nodeName\");\n\t\tif (nodeName == null || typeof nodeName !== \"string\") throw new Error(\"Invalid nodeName\");\n\t\tconst mappedChildren = children.toArray().flatMap((child) => createNodeFromLoroObj(schema, child, mapping)).filter((n) => n !== null);\n\t\ttry {\n\t\t\tretval = schema.node(nodeName, attributes.toJSON(), mappedChildren);\n\t\t\tWEAK_NODE_TO_LORO_CONTAINER_MAPPING.set(retval, obj.id);\n\t\t} catch (e) {\n\t\t\tconsole.error(e);\n\t\t}\n\t} else if (obj instanceof LoroText) {\n\t\tretval = [];\n\t\tfor (const delta of obj.toDelta()) {\n\t\t\tif (delta.insert == null) continue;\n\t\t\ttry {\n\t\t\t\tconst marks = [];\n\t\t\t\tfor (const [markName, mark] of Object.entries(delta.attributes ?? {})) {\n\t\t\t\t\tconst markAttrs = valueToAttrs(mark);\n\t\t\t\t\tmarks.push(schema.mark(markName, markAttrs ?? void 0));\n\t\t\t\t}\n\t\t\t\tretval.push(schema.text(delta.insert, marks));\n\t\t\t} catch (e) {\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t} else\n /* v8 ignore next */\n\tthrow new Error(\"Invalid LoroType\");\n\tif (retval != null) {\n\t\tif (!Array.isArray(retval)) WEAK_NODE_TO_LORO_CONTAINER_MAPPING.set(retval, obj.id);\n\t\tmapping.set(obj.id, retval);\n\t} else mapping.delete(obj.id);\n\treturn retval;\n}\nfunction createLoroChild(parentList, pos, nodeOrNodeList, mapping) {\n\treturn Array.isArray(nodeOrNodeList) ? createLoroText(parentList, pos, nodeOrNodeList, mapping) : createLoroMap(parentList, pos, nodeOrNodeList, mapping);\n}\nfunction createLoroText(parentList, pos, nodes, mapping) {\n\tconst obj = parentList.insertContainer(pos ?? parentList.length, new LoroText()).getAttached();\n\tconst delta = nodes.map((node) => ({\n\t\tinsert: node.text,\n\t\tattributes: nodeMarksToAttributes(node.marks)\n\t}));\n\tobj.applyDelta(delta);\n\tmapping.set(obj.id, nodes);\n\treturn obj;\n}\nfunction updateLoroText(obj, nodes, mapping) {\n\tmapping.set(obj.id, nodes);\n\tconst content = nodes.map((p) => ({\n\t\tinsert: p.text,\n\t\tattributes: nodeMarksToAttributes(p.marks)\n\t}));\n\tconst { insert, remove, index } = simpleDiff(obj.toString(), content.map((c) => c.insert).join(\"\"));\n\tif (remove > 0) obj.delete(index, remove);\n\tif (insert.length) obj.insert(index, insert);\n\tconst styles = diffTextStyles(obj.toDelta(), content);\n\tif (styles != null) obj.applyDelta(styles);\n}\n/**\n* Computes the minimal delta that restyles `current` (what the LoroText\n* holds) as `content` (what ProseMirror wants). The text of both sides must\n* already be equal. Returns null when the styles already agree everywhere.\n*/\nfunction diffTextStyles(current, content) {\n\tconst styles = [];\n\tlet i = 0;\n\tlet iUsed = 0;\n\tlet j = 0;\n\tlet jUsed = 0;\n\twhile (i < current.length && j < content.length) {\n\t\tconst currentRun = current[i];\n\t\tconst contentRun = content[j];\n\t\tif (currentRun.insert == null) {\n\t\t\ti += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tconst length = Math.min(currentRun.insert.length - iUsed, contentRun.insert.length - jUsed);\n\t\tif (length > 0) {\n\t\t\tconst patch = attributesPatch(currentRun.attributes ?? {}, contentRun.attributes);\n\t\t\tstyles.push(patch != null ? {\n\t\t\t\tretain: length,\n\t\t\t\tattributes: patch\n\t\t\t} : { retain: length });\n\t\t}\n\t\tiUsed += length;\n\t\tif (iUsed === currentRun.insert.length) {\n\t\t\ti += 1;\n\t\t\tiUsed = 0;\n\t\t}\n\t\tjUsed += length;\n\t\tif (jUsed === contentRun.insert.length) {\n\t\t\tj += 1;\n\t\t\tjUsed = 0;\n\t\t}\n\t}\n\twhile (styles.length > 0 && styles[styles.length - 1].attributes == null) styles.pop();\n\treturn styles.length > 0 ? styles : null;\n}\n/**\n* Computes the attribute changes that turn `current` into `wanted`, or null\n* if they are already equal.\n*/\nfunction attributesPatch(current, wanted) {\n\tlet patch = null;\n\tfor (const [key, attrs] of Object.entries(wanted)) if (!equalityDeep(current[key], attrs)) {\n\t\tpatch = patch ?? {};\n\t\tpatch[key] = attrs;\n\t}\n\tfor (const key of Object.keys(current)) if (!(key in wanted) && current[key] != null) {\n\t\tpatch = patch ?? {};\n\t\tpatch[key] = null;\n\t}\n\treturn patch;\n}\nfunction nodeMarksToAttributes(marks) {\n\tconst pattrs = {};\n\tfor (const mark of marks) pattrs[mark.type.name] = mark.attrs;\n\treturn pattrs;\n}\nfunction valueToAttrs(value) {\n\tif (value != null && typeof value === \"object\" && !Array.isArray(value) && !(value instanceof Uint8Array)) return value;\n\treturn null;\n}\nfunction eqLoroTextNodes(obj, nodes) {\n\tconst delta = obj.toDelta();\n\treturn delta.length === nodes.length && delta.every((delta, i) => delta.insert === nodes[i].text && Object.keys(delta.attributes || {}).length === nodes[i].marks.length && nodes[i].marks.every((mark) => {\n\t\tconst attrs = valueToAttrs((delta.attributes || {})[mark.type.name]);\n\t\treturn attrs != null && eqAttrs(attrs, mark.attrs);\n\t}));\n}\n/**\n* Whether the loro object is equal to the node.\n*/\nfunction eqLoroObjNode(obj, node) {\n\tif (obj instanceof LoroMap) {\n\t\tif (Array.isArray(node) || !eqNodeName(obj, node)) return false;\n\t\tconst loroChildren = getLoroMapChildren(obj);\n\t\tconst normalizedContent = normalizeNodeContent(node);\n\t\treturn loroChildren.length === normalizedContent.length && eqAttrs(getLoroMapAttributes(obj).toJSON(), node.attrs) && normalizedContent.every((childNode, i) => eqLoroObjNode(loroChildren.get(i), childNode));\n\t}\n\treturn obj instanceof LoroText && Array.isArray(node) && eqLoroTextNodes(obj, node);\n}\nfunction eqAttrs(attrs1, attrs2) {\n\tconst keys = Object.keys(attrs1).filter((key) => attrs1[key] !== null);\n\tlet eq = keys.length === Object.keys(attrs2).filter((key) => attrs2[key] !== null).length;\n\tfor (let i = 0; eq && i < keys.length; i++) {\n\t\tconst key = keys[i];\n\t\tconst l = attrs1[key];\n\t\tconst r = attrs2[key];\n\t\teq = l === r || typeof l === \"object\" && l !== null && typeof r === \"object\" && r !== null && eqAttrs(l, r);\n\t}\n\treturn eq;\n}\nfunction eqNodeName(obj, node) {\n\treturn !Array.isArray(node) && obj.get(\"nodeName\") === node.type.name;\n}\n/**\n* Checks if two nodes (or arrays of nodes) are equal.\n* - If both are the same object, returns true.\n* - If both are single nodes, uses their .eq() method.\n* - If both are arrays, checks that they have the same length and each corresponding node is equal.\n*/\nfunction eqMappedNode(mapped, node) {\n\tif (mapped === node) return true;\n\tif (!Array.isArray(mapped) && !Array.isArray(node) && node) return mapped?.eq(node) ?? false;\n\tif (Array.isArray(mapped) && Array.isArray(node)) {\n\t\tif (mapped.length !== node.length) return false;\n\t\tfor (let i = 0; i < mapped.length; i++) if (!node[i].eq(mapped[i])) return false;\n\t\treturn true;\n\t}\n\treturn false;\n}\nfunction normalizeNodeContent(node) {\n\tconst res = [];\n\tlet textNodes = null;\n\tnode.content.forEach((node, _offset, _i) => {\n\t\tif (node.isText) {\n\t\t\tif (textNodes == null) {\n\t\t\t\ttextNodes = [];\n\t\t\t\tres.push(textNodes);\n\t\t\t}\n\t\t\ttextNodes.push(node);\n\t\t} else {\n\t\t\tres.push(node);\n\t\t\ttextNodes = null;\n\t\t}\n\t});\n\treturn res;\n}\nfunction computeChildEqualityFactor(obj, node, mapping) {\n\tconst loroChildren = getLoroMapChildren(obj);\n\tconst loroChildLength = loroChildren.length;\n\tconst nodeChildren = normalizeNodeContent(node);\n\tconst nodeChildLength = nodeChildren.length;\n\tconst minLength = Math.min(loroChildLength, nodeChildLength);\n\tlet left = 0;\n\tlet right = 0;\n\tlet foundMappedChild = false;\n\tfor (; left < minLength; left++) {\n\t\tconst leftLoro = loroChildren.get(left);\n\t\tconst leftNode = nodeChildren[left];\n\t\tif (eqMappedNode(leftLoro != null && isContainer(leftLoro) ? mapping.get(leftLoro.id) : void 0, leftNode)) foundMappedChild = true;\n\t\telse if (leftLoro == null || leftNode == null || !eqLoroObjNode(leftLoro, leftNode)) break;\n\t}\n\tfor (; left + right < minLength; right++) {\n\t\tconst rightLoro = loroChildren.get(loroChildLength - right - 1);\n\t\tconst rightNode = nodeChildren[nodeChildLength - right - 1];\n\t\tif (eqMappedNode(rightLoro != null && isContainer(rightLoro) ? mapping.get(rightLoro.id) : void 0, rightNode)) foundMappedChild = true;\n\t\telse if (rightLoro == null || rightNode == null || !eqLoroObjNode(rightLoro, rightNode)) break;\n\t}\n\treturn {\n\t\tfactor: left + right,\n\t\tfoundMappedChild\n\t};\n}\nfunction createLoroMap(parentList, pos, node, mapping) {\n\tconst obj = parentList.insertContainer(pos ?? parentList.length, new LoroMap()).getAttached();\n\tobj.set(\"nodeName\", node.type.name);\n\tconst attrs = getLoroMapAttributes(obj);\n\tfor (const [key, value] of Object.entries(node.attrs)) if (value !== null) attrs.set(key, value);\n\tconst children = getLoroMapChildren(obj);\n\tnormalizeNodeContent(node).forEach((child, _i) => createLoroChild(children, null, child, mapping));\n\tWEAK_NODE_TO_LORO_CONTAINER_MAPPING.set(node, obj.id);\n\tmapping.set(obj.id, node);\n\treturn obj;\n}\nfunction updateLoroMap(obj, node, mapping) {\n\tmapping.set(obj.id, node);\n\tWEAK_NODE_TO_LORO_CONTAINER_MAPPING.set(node, obj.id);\n\tif (!eqNodeName(obj, node)) throw new Error(\"node name mismatch!\");\n\tupdateLoroMapAttributes(obj, node, mapping);\n\tupdateLoroMapChildren(obj, node, mapping);\n}\nfunction getLoroMapAttributes(obj) {\n\treturn obj.getOrCreateContainer(ATTRIBUTES_KEY, new LoroMap());\n}\nfunction updateLoroMapAttributes(obj, node, _mapping) {\n\tconst attrs = getLoroMapAttributes(obj);\n\tconst keys = new Set(attrs.keys());\n\tconst pAttrs = node.attrs;\n\tfor (const [key, value] of Object.entries(pAttrs)) {\n\t\tif (value !== null) {\n\t\t\tif (!equalityDeep(attrs.get(key), value)) attrs.set(key, value);\n\t\t} else attrs.delete(key);\n\t\tkeys.delete(key);\n\t}\n\tfor (const key of keys) attrs.delete(key);\n}\nfunction getLoroMapChildren(obj) {\n\treturn obj.getOrCreateContainer(CHILDREN_KEY, new LoroList());\n}\nfunction updateLoroMapChildren(obj, node, mapping) {\n\tconst loroChildren = getLoroMapChildren(obj);\n\tconst loroChildLength = loroChildren.length;\n\tconst nodeChildren = normalizeNodeContent(node);\n\tconst nodeChildLength = nodeChildren.length;\n\tconst minLength = Math.min(nodeChildLength, loroChildLength);\n\tlet left = 0;\n\tlet right = 0;\n\tfor (; left < minLength; left++) {\n\t\tconst leftLoro = loroChildren.get(left);\n\t\tconst leftNode = nodeChildren[left];\n\t\tif (leftLoro == null || leftNode == null) break;\n\t\tif (isContainer(leftLoro) && mapping.get(leftLoro.id) !== leftNode) if (eqMappedNode(mapping.get(leftLoro.id), leftNode) || eqLoroObjNode(leftLoro, leftNode)) {\n\t\t\tif (!Array.isArray(leftNode)) updateLoroMap(leftLoro, leftNode, mapping);\n\t\t} else break;\n\t}\n\tfor (; right + left < minLength; right++) {\n\t\tconst rightLoro = loroChildren.get(loroChildLength - right - 1);\n\t\tconst rightNode = nodeChildren[nodeChildLength - right - 1];\n\t\tif (rightLoro == null || rightNode == null) break;\n\t\tif (isContainer(rightLoro) && mapping.get(rightLoro.id) !== rightNode) if (eqMappedNode(mapping.get(rightLoro.id), rightNode) || eqLoroObjNode(rightLoro, rightNode)) {\n\t\t\tif (!Array.isArray(rightNode)) updateLoroMap(rightLoro, rightNode, mapping);\n\t\t} else break;\n\t}\n\twhile (loroChildLength - left - right > 0 && nodeChildLength - left - right > 0) {\n\t\tconst leftLoro = loroChildren.get(left);\n\t\tconst leftNode = nodeChildren[left];\n\t\tconst rightLoro = loroChildren.get(loroChildLength - right - 1);\n\t\tconst rightNode = nodeChildren[nodeChildLength - right - 1];\n\t\tif (leftLoro instanceof LoroText && Array.isArray(leftNode)) {\n\t\t\tif (!eqLoroTextNodes(leftLoro, leftNode)) updateLoroText(leftLoro, leftNode, mapping);\n\t\t\tleft += 1;\n\t\t} else {\n\t\t\tlet updateLeft = leftLoro instanceof LoroMap && eqNodeName(leftLoro, leftNode);\n\t\t\tlet updateRight = rightLoro instanceof LoroMap && eqNodeName(rightLoro, rightNode);\n\t\t\tif (updateLeft && updateRight) {\n\t\t\t\tconst leftEquality = computeChildEqualityFactor(leftLoro, leftNode, mapping);\n\t\t\t\tconst rightEquality = computeChildEqualityFactor(rightLoro, rightNode, mapping);\n\t\t\t\tif (leftEquality.foundMappedChild && !rightEquality.foundMappedChild) updateRight = false;\n\t\t\t\telse if (rightEquality.foundMappedChild && !leftEquality.foundMappedChild) updateLeft = false;\n\t\t\t\telse if (leftEquality.factor < rightEquality.factor) updateLeft = false;\n\t\t\t\telse updateRight = false;\n\t\t\t}\n\t\t\tif (updateLeft) {\n\t\t\t\tupdateLoroMap(leftLoro, leftNode, mapping);\n\t\t\t\tleft += 1;\n\t\t\t} else if (updateRight) {\n\t\t\t\tupdateLoroMap(rightLoro, rightNode, mapping);\n\t\t\t\tright += 1;\n\t\t\t} else {\n\t\t\t\tconst child = loroChildren.get(left);\n\t\t\t\tif (isContainer(child)) mapping.delete(child.id);\n\t\t\t\tloroChildren.delete(left, 1);\n\t\t\t\tcreateLoroChild(loroChildren, left, leftNode, mapping);\n\t\t\t\tleft += 1;\n\t\t\t}\n\t\t}\n\t}\n\tconst loroDelLength = loroChildLength - left - right;\n\tif (loroChildLength === 1 && nodeChildLength === 0 && loroChildren.get(0) instanceof LoroText) {\n\t\tconst loroText = loroChildren.get(0);\n\t\tmapping.delete(loroText.id);\n\t\tloroText.delete(0, loroText.length);\n\t} else if (loroDelLength > 0) {\n\t\tloroChildren.toArray().slice(left, left + loroDelLength).filter(isContainer).forEach((type) => mapping.delete(type.id));\n\t\tloroChildren.delete(left, loroDelLength);\n\t}\n\tif (left + right < nodeChildLength) nodeChildren.slice(left, nodeChildLength - right).forEach((nodeChild, i) => createLoroChild(loroChildren, left + i, nodeChild, mapping));\n}\nfunction clearChangedNodes(doc, event, mapping) {\n\tfor (const e of event.events) {\n\t\tconst obj = doc.getContainerById(e.target);\n\t\tmapping.delete(obj.id);\n\t\tlet parentObj = obj.parent();\n\t\twhile (parentObj) {\n\t\t\tmapping.delete(parentObj.id);\n\t\t\tparentObj = parentObj.parent();\n\t\t}\n\t}\n}\n/**\n* Set a text selection between the given anchor and head positions. This\n* function will ignore out-of-bounds positions, and find a valid selection near\n* the given positions.\n*/\nfunction safeSetSelection(view, anchor, head) {\n\tconst doc = view.state.doc;\n\tconst docSize = doc.content.size;\n\tif (anchor < 0 || anchor > docSize || head != null && (head < 0 || head > docSize)) return;\n\tconst $anchor = doc.resolve(anchor);\n\tconst $head = head != null ? doc.resolve(head) : void 0;\n\tconst selection = TextSelection.between($anchor, $head || $anchor);\n\tview.dispatch(view.state.tr.setSelection(selection));\n}\n\n//#endregion\n//#region src/sync-plugin-key.ts\nconst loroSyncPluginKey = new PluginKey(\"loro-sync\");\n\n//#endregion\n//#region src/cursor/common.ts\nconst createCursorPlugin = (pluginKey, store, options) => {\n\tconst getSelection = options.getSelection || ((state) => state.selection);\n\tconst createSelection = options.createSelection || ((user) => ({\n\t\tclass: \"loro-selection\",\n\t\t\"data-peer\": user,\n\t\tstyle: `background-color: rgba(228, 208, 102, 0.5)`\n\t}));\n\tconst createCursor = options.createCursor || ((user) => {\n\t\tconst cursorUserData = store.getAll()[user];\n\t\tconst cursor = document.createElement(\"span\");\n\t\tcursor.classList.add(\"ProseMirror-loro-cursor\");\n\t\tcursor.setAttribute(\"style\", `border-color: ${cursorUserData?.user?.color ?? user.slice(0, 6)}`);\n\t\tconst userDiv = document.createElement(\"div\");\n\t\tuserDiv.setAttribute(\"style\", `background-color: ${cursorUserData?.user?.color ?? user.slice(0, 6)}`);\n\t\tuserDiv.insertBefore(document.createTextNode(cursorUserData?.user?.name ?? user.slice(0, 6)), null);\n\t\tconst nonbreakingSpace1 = document.createTextNode(\"⁠\");\n\t\tconst nonbreakingSpace2 = document.createTextNode(\"⁠\");\n\t\tcursor.insertBefore(nonbreakingSpace1, null);\n\t\tcursor.insertBefore(userDiv, null);\n\t\tcursor.insertBefore(nonbreakingSpace2, null);\n\t\treturn cursor;\n\t});\n\tconst plugin = new Plugin({\n\t\tkey: pluginKey,\n\t\tstate: {\n\t\t\tinit(_, state) {\n\t\t\t\treturn createDecorations(state, store, plugin, createSelection, createCursor);\n\t\t\t},\n\t\t\tapply(tr, prevState, _oldState, newState) {\n\t\t\t\tconst loroState = loroSyncPluginKey.getState(newState);\n\t\t\t\tconst loroCursorState = tr.getMeta(pluginKey);\n\t\t\t\tif (loroState && loroState.changedBy !== \"local\" || loroCursorState && loroCursorState.presenceUpdated) return createDecorations(newState, store, plugin, createSelection, createCursor);\n\t\t\t\treturn prevState.map(tr.mapping, tr.doc);\n\t\t\t}\n\t\t},\n\t\tprops: { decorations: (state) => {\n\t\t\treturn plugin.getState(state);\n\t\t} },\n\t\tview: (view) => {\n\t\t\tconst storeListener = (origin) => {\n\t\t\t\tif (origin !== \"local\") setTimeout(() => {\n\t\t\t\t\tif (view.isDestroyed) return;\n\t\t\t\t\tlet tr = view.state.tr;\n\t\t\t\t\ttr.setMeta(pluginKey, { presenceUpdated: true });\n\t\t\t\t\tview.dispatch(tr);\n\t\t\t\t}, 0);\n\t\t\t};\n\t\t\tconst updateCursorInfo = () => {\n\t\t\t\tconst loroState = loroSyncPluginKey.getState(view.state);\n\t\t\t\tconst current = store.getLocal();\n\t\t\t\tif (loroState?.doc == null) return;\n\t\t\t\tconst pmRootNode = view.state.doc;\n\t\t\t\tif (view.hasFocus()) {\n\t\t\t\t\tconst { anchor, focus } = convertPmSelectionToCursors(pmRootNode, getSelection(view.state), loroState);\n\t\t\t\t\tif (current == null || !cursorEq(current.anchor, anchor) || !cursorEq(current.focus, focus)) store.setLocal({\n\t\t\t\t\t\tuser: options.user,\n\t\t\t\t\t\tanchor,\n\t\t\t\t\t\tfocus\n\t\t\t\t\t});\n\t\t\t\t} else if (current?.focus != null) store.setLocal({});\n\t\t\t};\n\t\t\tconst unsubscribe = store.subscribe(storeListener);\n\t\t\tview.dom.addEventListener(\"focusin\", updateCursorInfo);\n\t\t\tview.dom.addEventListener(\"focusout\", updateCursorInfo);\n\t\t\treturn {\n\t\t\t\tupdate: updateCursorInfo,\n\t\t\t\tdestroy: () => {\n\t\t\t\t\tview.dom.removeEventListener(\"focusin\", updateCursorInfo);\n\t\t\t\t\tview.dom.removeEventListener(\"focusout\", updateCursorInfo);\n\t\t\t\t\tunsubscribe();\n\t\t\t\t\tstore.setLocal({});\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t});\n\treturn plugin;\n};\nfunction createDecorations(state, store, _plugin, createSelection, createCursor) {\n\tconst all = store.getAll();\n\tconst d = [];\n\tconst loroState = loroSyncPluginKey.getState(state);\n\tif (!loroState) return DecorationSet.create(state.doc, []);\n\tconst doc = loroState.doc;\n\tconst thisPeer = doc.peerIdStr;\n\tfor (const [peer, cursor] of Object.entries(all)) {\n\t\tif (peer === thisPeer) continue;\n\t\tif (!cursor.anchor || !cursor.focus) continue;\n\t\tconst [focus, focusCursorUpdate] = cursorToAbsolutePosition(cursor.focus, doc, loroState.mapping);\n\t\td.push(Decoration.widget(focus, createCursor(peer)));\n\t\tif (!cursorEq(cursor.anchor, cursor.focus)) {\n\t\t\tconst [anchor, anchorCursorUpdate] = cursorToAbsolutePosition(cursor.anchor, doc, loroState.mapping);\n\t\t\td.push(Decoration.inline(Math.min(anchor, focus), Math.max(anchor, focus), createSelection(peer)));\n\t\t\tif (focusCursorUpdate || anchorCursorUpdate) {\n\t\t\t\tconst existingLocalState = store.getLocal();\n\t\t\t\tstore.setLocal({\n\t\t\t\t\t...existingLocalState?.user && { user: existingLocalState.user },\n\t\t\t\t\tanchor: anchorCursorUpdate || cursor.anchor,\n\t\t\t\t\tfocus: focusCursorUpdate || cursor.focus\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (focusCursorUpdate) {\n\t\t\tconst existingLocalState = store.getLocal();\n\t\t\tstore.setLocal({\n\t\t\t\t...existingLocalState?.user && { user: existingLocalState.user },\n\t\t\t\tfocus: focusCursorUpdate,\n\t\t\t\tanchor: focusCursorUpdate\n\t\t\t});\n\t\t}\n\t}\n\treturn DecorationSet.create(state.doc, d);\n}\nfunction convertPmSelectionToCursors(pmRootNode, selection, loroState) {\n\tconst anchor = absolutePositionToCursor(pmRootNode, selection.anchor, loroState.doc, loroState.mapping);\n\treturn {\n\t\tanchor,\n\t\tfocus: selection.head == selection.anchor ? anchor : absolutePositionToCursor(pmRootNode, selection.head, loroState.doc, loroState.mapping)\n\t};\n}\nfunction getByValue(map, searchValue) {\n\tfor (let [key, value] of map.entries()) if (value === searchValue) return key;\n}\nfunction absolutePositionToCursor(pmRootNode, anchor, doc, mapping) {\n\tconst pos = pmRootNode.resolve(anchor);\n\tconst nodeParent = pos.node(pos.depth);\n\tconst offset = pos.parentOffset;\n\tconst loroId = WEAK_NODE_TO_LORO_CONTAINER_MAPPING.get(nodeParent) ?? getByValue(mapping, nodeParent);\n\tif (!loroId) {\n\t\tif (anchor > 1) console.error(\"Cannot find the loroNode\");\n\t\treturn;\n\t}\n\tconst children = doc.getMap(loroId).get(CHILDREN_KEY);\n\tif (children.length == 0) return children.getCursor(0);\n\tlet index = offset;\n\tlet childIndex = 0;\n\twhile (index >= 0 && childIndex < children.length) {\n\t\tconst child = children.get(childIndex);\n\t\tchildIndex += 1;\n\t\tif (child instanceof LoroText) return child.getCursor(index);\n\t\telse {\n\t\t\tif (index == 0) {\n\t\t\t\tif (childIndex < children.length) index += 1;\n\t\t\t}\n\t\t\tindex -= 1;\n\t\t}\n\t}\n}\nfunction cursorToAbsolutePosition(cursor, doc, mapping) {\n\tconst containerId = cursor.containerId();\n\tlet index = -1;\n\tlet targetChildId;\n\tlet loroNode;\n\tlet update;\n\tif (containerId.endsWith(\"List\")) {\n\t\tconst loroList = doc.getContainerById(containerId);\n\t\tif (!loroList) return [1, void 0];\n\t\tconst parentNode = loroList.parent();\n\t\tif (!parentNode) return [1, void 0];\n\t\ttargetChildId = parentNode.id;\n\t\tloroNode = parentNode.parent()?.parent();\n\t\tindex = 0;\n\t} else {\n\t\tconst loroText = doc.getText(containerId);\n\t\tconst pos = doc.getCursorPos(cursor);\n\t\tif (!pos) return [1, void 0];\n\t\tupdate = pos.update;\n\t\tindex += pos.offset;\n\t\ttargetChildId = loroText.id;\n\t\tloroNode = loroText.parent()?.parent();\n\t}\n\twhile (loroNode != null) {\n\t\tconst children = loroNode.get(CHILDREN_KEY);\n\t\tif (children instanceof LoroList) {\n\t\t\tconst childIds = children.toArray();\n\t\t\tfor (const iter of childIds) {\n\t\t\t\tif (iter.id === targetChildId) break;\n\t\t\t\tconst mapped = mapping.get(iter.id);\n\t\t\t\tif (Array.isArray(mapped)) mapped.forEach((child) => {\n\t\t\t\t\tindex += child.nodeSize;\n\t\t\t\t});\n\t\t\t\telse if (mapped != null) index += mapped.nodeSize;\n\t\t\t\telse console.error(childIds, children.toJSON());\n\t\t\t}\n\t\t\ttargetChildId = loroNode.id;\n\t\t\tloroNode = loroNode.parent()?.parent();\n\t\t\tindex += 1;\n\t\t} else throw new Error(\"Unreachable code\");\n\t}\n\treturn [index, update];\n}\nfunction cursorEq(a, b) {\n\tif (!a && !b) return true;\n\tif (!a || !b) return false;\n\tconst aPos = a.pos();\n\tconst bPos = b.pos();\n\treturn aPos?.peer === bPos?.peer && aPos?.counter === bPos?.counter && a.containerId() === b.containerId();\n}\n\n//#endregion\n//#region src/text-style.ts\nconst LORO_TEXT_STYLE_CACHE = /* @__PURE__ */ new WeakSet();\nfunction getLoroTextStyle(schema) {\n\treturn Object.fromEntries(Object.entries(schema.marks).map(([markName, markType]) => [markName, { expand: markType.spec.inclusive !== false ? \"after\" : \"none\" }]));\n}\nfunction configLoroTextStyle(doc, schema) {\n\tif (LORO_TEXT_STYLE_CACHE.has(doc)) return;\n\tLORO_TEXT_STYLE_CACHE.add(doc);\n\tdoc.configTextStyle(getLoroTextStyle(schema));\n}\n\n//#endregion\n//#region src/undo-plugin-key.ts\nconst loroUndoPluginKey = new PluginKey(\"loro-undo\");\n\n//#endregion\n//#region src/sync-plugin.ts\nconst LoroSyncPlugin = (props) => {\n\treturn new Plugin({\n\t\tkey: loroSyncPluginKey,\n\t\tprops: { editable: (state) => {\n\t\t\treturn loroSyncPluginKey.getState(state)?.snapshot == null;\n\t\t} },\n\t\tstate: {\n\t\t\tinit: (_config, editorState) => {\n\t\t\t\tconfigLoroTextStyle(props.doc, editorState.schema);\n\t\t\t\treturn {\n\t\t\t\t\tdoc: props.doc,\n\t\t\t\t\tmapping: props.mapping ?? /* @__PURE__ */ new Map(),\n\t\t\t\t\tchangedBy: \"local\",\n\t\t\t\t\tcontainerId: props.containerId\n\t\t\t\t};\n\t\t\t},\n\t\t\tapply: (tr, state, oldEditorState, newEditorState) => {\n\t\t\t\tconst meta = tr.getMeta(loroSyncPluginKey);\n\t\t\t\tconst undoState = loroUndoPluginKey.getState(oldEditorState);\n\t\t\t\tif (meta?.type === \"non-local-updates\") state.changedBy = \"import\";\n\t\t\t\telse state.changedBy = \"local\";\n\t\t\t\tswitch (meta?.type) {\n\t\t\t\t\tcase \"doc-changed\":\n\t\t\t\t\t\tif (!undoState?.isUndoing.current) updateLoroToPmState(state.doc, state.mapping, newEditorState, props.containerId);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"update-state\":\n\t\t\t\t\t\tstate = {\n\t\t\t\t\t\t\t...state,\n\t\t\t\t\t\t\t...meta.state\n\t\t\t\t\t\t};\n\t\t\t\t\t\tstate.doc.commit({\n\t\t\t\t\t\t\torigin: \"sys:init\",\n\t\t\t\t\t\t\ttimestamp: Date.now()\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault: break;\n\t\t\t\t}\n\t\t\t\treturn state;\n\t\t\t}\n\t\t},\n\t\tappendTransaction: (transactions, _oldEditorState, newEditorState) => {\n\t\t\tif (transactions.some((tr) => tr.docChanged)) return newEditorState.tr.setMeta(loroSyncPluginKey, { type: \"doc-changed\" });\n\t\t\treturn null;\n\t\t},\n\t\tview: (view) => {\n\t\t\tconst timeoutId = setTimeout(() => init(view), 0);\n\t\t\treturn {\n\t\t\t\tupdate: (_view, _prevState) => {},\n\t\t\t\tdestroy: () => {\n\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t});\n};\nfunction init(view) {\n\tif (view.isDestroyed) return;\n\tconst state = loroSyncPluginKey.getState(view.state);\n\tlet docSubscription = state.docSubscription;\n\tdocSubscription?.();\n\tif (state.containerId) docSubscription = state.doc.getContainerById(state.containerId).subscribe((event) => {\n\t\tupdateNodeOnLoroEvent(view, event);\n\t});\n\telse docSubscription = state.doc.subscribe((event) => updateNodeOnLoroEvent(view, event));\n\tconst innerDoc = state.containerId ? state.doc.getContainerById(state.containerId) : state.doc.getMap(ROOT_DOC_KEY);\n\tconst mapping = /* @__PURE__ */ new Map();\n\tif (innerDoc.size === 0) {\n\t\tconst tr = view.state.tr.delete(0, view.state.doc.content.size);\n\t\ttr.setMeta(loroSyncPluginKey, {\n\t\t\ttype: \"update-state\",\n\t\t\tstate: {\n\t\t\t\tmapping,\n\t\t\t\tdocSubscription,\n\t\t\t\tsnapshot: null\n\t\t\t}\n\t\t});\n\t\tview.dispatch(tr);\n\t} else {\n\t\tconst schema = view.state.schema;\n\t\tconst node = createNodeFromLoroObj(schema, innerDoc, mapping);\n\t\tconst tr = view.state.tr.replace(0, view.state.doc.content.size, new Slice(Fragment.from(node), 0, 0));\n\t\ttr.setMeta(loroSyncPluginKey, {\n\t\t\ttype: \"update-state\",\n\t\t\tstate: {\n\t\t\t\tmapping,\n\t\t\t\tdocSubscription,\n\t\t\t\tsnapshot: null\n\t\t\t}\n\t\t});\n\t\tview.dispatch(tr);\n\t}\n}\nfunction updateNodeOnLoroEvent(view, event) {\n\tif (view.isDestroyed) return;\n\tconst state = loroSyncPluginKey.getState(view.state);\n\tstate.changedBy = event.by;\n\tif (event.by === \"local\" && event.origin !== \"undo\") return;\n\tconst mapping = state.mapping;\n\tclearChangedNodes(state.doc, event, mapping);\n\tconst node = createNodeFromLoroObj(view.state.schema, state.containerId ? state.doc.getContainerById(state.containerId) : state.doc.getMap(ROOT_DOC_KEY), mapping);\n\tconst { anchor, focus } = convertPmSelectionToCursors(view.state.doc, view.state.selection, state);\n\tlet tr = view.state.tr.replace(0, view.state.doc.content.size, new Slice(Fragment.from(node), 0, 0));\n\ttr.setMeta(loroSyncPluginKey, { type: \"non-local-updates\" });\n\tview.dispatch(tr);\n\tif (anchor == null) return;\n\tsetTimeout(() => {\n\t\tsyncCursorsToPmSelection(view, anchor, focus);\n\t});\n}\n/**\n* Update ProseMirror selection based on the given Loro cursors.\n*/\nfunction syncCursorsToPmSelection(view, anchor, focus) {\n\tif (view.isDestroyed) return;\n\tconst state = loroSyncPluginKey.getState(view.state);\n\tif (!state) return;\n\tconst { doc, mapping } = state;\n\tconst anchorPos = cursorToAbsolutePosition(anchor, doc, mapping)[0];\n\tconst focusPos = focus && cursorToAbsolutePosition(focus, doc, mapping)[0];\n\tif (anchorPos == null) return;\n\tsafeSetSelection(view, anchorPos, focusPos);\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.112.0/helpers/typeof.js\nfunction _typeof(o) {\n\t\"@babel/helpers - typeof\";\n\treturn _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function(o) {\n\t\treturn typeof o;\n\t} : function(o) {\n\t\treturn o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n\t}, _typeof(o);\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.112.0/helpers/toPrimitive.js\nfunction toPrimitive(t, r) {\n\tif (\"object\" != _typeof(t) || !t) return t;\n\tvar e = t[Symbol.toPrimitive];\n\tif (void 0 !== e) {\n\t\tvar i = e.call(t, r || \"default\");\n\t\tif (\"object\" != _typeof(i)) return i;\n\t\tthrow new TypeError(\"@@toPrimitive must return a primitive value.\");\n\t}\n\treturn (\"string\" === r ? String : Number)(t);\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.112.0/helpers/toPropertyKey.js\nfunction toPropertyKey(t) {\n\tvar i = toPrimitive(t, \"string\");\n\treturn \"symbol\" == _typeof(i) ? i : i + \"\";\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.112.0/helpers/defineProperty.js\nfunction _defineProperty(e, r, t) {\n\treturn (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n\t\tvalue: t,\n\t\tenumerable: !0,\n\t\tconfigurable: !0,\n\t\twritable: !0\n\t}) : e[r] = t, e;\n}\n\n//#endregion\n//#region src/cursor/ephemeral.ts\nvar CursorEphemeralStore = class extends EphemeralStore {\n\tconstructor(peer, timeout) {\n\t\tsuper(timeout);\n\t\t_defineProperty(this, \"peer\", void 0);\n\t\tthis.peer = peer;\n\t}\n\tsetLocal(state) {\n\t\tif (!state.anchor && !state.focus && !state.user) {\n\t\t\tthis.delete(this.peer);\n\t\t\treturn;\n\t\t}\n\t\tthis.set(this.peer, {\n\t\t\tanchor: state.anchor?.encode() ?? null,\n\t\t\tfocus: state.focus?.encode() ?? null,\n\t\t\tuser: state.user ?? null\n\t\t});\n\t}\n\tgetLocal() {\n\t\tconst state = this.get(this.peer);\n\t\tif (!state) return;\n\t\treturn {\n\t\t\tanchor: state.anchor ? Cursor.decode(state.anchor) : void 0,\n\t\t\tfocus: state.focus ? Cursor.decode(state.focus) : void 0,\n\t\t\tuser: state.user ?? void 0\n\t\t};\n\t}\n\tgetAll() {\n\t\tconst ans = {};\n\t\tfor (const [peer, state] of Object.entries(this.getAllStates())) {\n\t\t\tif (!state) continue;\n\t\t\tans[peer] = {\n\t\t\t\tanchor: state.anchor ? Cursor.decode(state.anchor) : void 0,\n\t\t\t\tfocus: state.focus ? Cursor.decode(state.focus) : void 0,\n\t\t\t\tuser: state.user ?? void 0\n\t\t\t};\n\t\t}\n\t\treturn ans;\n\t}\n\tsubscribeBy(listener) {\n\t\treturn super.subscribe((event) => listener(event.by));\n\t}\n};\nconst loroEphemeralCursorPluginKey = new PluginKey(\"loro-ephemeral-cursor\");\nconst LoroEphemeralCursorPlugin = (store, options) => createCursorPlugin(loroEphemeralCursorPluginKey, ephemeralStoreAdapter(store), options);\nconst ephemeralStoreAdapter = (store) => ({\n\tgetAll: () => store.getAll(),\n\tgetLocal: () => store.getLocal(),\n\tsetLocal: (state) => store.setLocal(state),\n\tsubscribe: (listener) => store.subscribeBy(listener)\n});\n\n//#endregion\n//#region src/cursor/awareness.ts\nvar CursorAwareness = class extends Awareness {\n\tconstructor(peer, timeout = 3e4) {\n\t\tsuper(peer, timeout);\n\t}\n\tgetAll() {\n\t\tconst ans = {};\n\t\tfor (const [peer, state] of Object.entries(this.getAllStates())) ans[peer] = {\n\t\t\tanchor: state.anchor ? Cursor.decode(state.anchor) : void 0,\n\t\t\tfocus: state.focus ? Cursor.decode(state.focus) : void 0,\n\t\t\tuser: state.user ? state.user : void 0\n\t\t};\n\t\treturn ans;\n\t}\n\tsetLocal(state) {\n\t\tthis.setLocalState({\n\t\t\tanchor: state.anchor?.encode() || null,\n\t\t\tfocus: state.focus?.encode() || null,\n\t\t\tuser: state.user || null\n\t\t});\n\t}\n\tgetLocal() {\n\t\tconst state = this.getLocalState();\n\t\tif (!state) return;\n\t\treturn {\n\t\t\tanchor: state.anchor && Cursor.decode(state.anchor),\n\t\t\tfocus: state.focus && Cursor.decode(state.focus),\n\t\t\tuser: state.user\n\t\t};\n\t}\n};\nconst loroCursorPluginKey = new PluginKey(\"loro-cursor\");\nconst awarenessAdapter = (awareness) => ({\n\tgetAll: () => awareness.getAll(),\n\tgetLocal: () => {\n\t\tconst state = awareness.getLocal();\n\t\tif (!state) return;\n\t\treturn {\n\t\t\tanchor: state.anchor ?? void 0,\n\t\t\tfocus: state.focus ?? void 0,\n\t\t\tuser: state.user ?? void 0\n\t\t};\n\t},\n\tsetLocal: (state) => awareness.setLocal(state),\n\tsubscribe: (listener) => {\n\t\tconst awarenessListener = (_, origin) => listener(origin === \"local\" ? \"local\" : \"import\");\n\t\tawareness.addListener(awarenessListener);\n\t\treturn () => awareness.removeListener(awarenessListener);\n\t}\n});\nconst LoroCursorPlugin = (awareness, options) => createCursorPlugin(loroCursorPluginKey, awarenessAdapter(awareness), options);\n\n//#endregion\n//#region src/undo-plugin.ts\nconst LoroUndoPlugin = (props) => {\n\tconst undoManager = props.undoManager || new UndoManager(props.doc, {});\n\tlet lastSelection = {\n\t\tanchor: null,\n\t\tfocus: null\n\t};\n\treturn new Plugin({\n\t\tkey: loroUndoPluginKey,\n\t\tstate: {\n\t\t\tinit: (_config, editorState) => {\n\t\t\t\tconfigLoroTextStyle(props.doc, editorState.schema);\n\t\t\t\tundoManager.addExcludeOriginPrefix(\"sys:init\");\n\t\t\t\treturn {\n\t\t\t\t\tundoManager,\n\t\t\t\t\tcanUndo: undoManager.canUndo(),\n\t\t\t\t\tcanRedo: undoManager.canRedo(),\n\t\t\t\t\tisUndoing: { current: false }\n\t\t\t\t};\n\t\t\t},\n\t\t\tapply: (_tr, state, oldEditorState, _newEditorState) => {\n\t\t\t\tconst undoState = loroUndoPluginKey.getState(oldEditorState);\n\t\t\t\tconst loroState = loroSyncPluginKey.getState(oldEditorState);\n\t\t\t\tif (!undoState || !loroState) return state;\n\t\t\t\tconst canUndo = undoState.undoManager.canUndo();\n\t\t\t\tconst canRedo = undoState.undoManager.canRedo();\n\t\t\t\t{\n\t\t\t\t\tconst { anchor, focus } = convertPmSelectionToCursors(oldEditorState.doc, oldEditorState.selection, loroState);\n\t\t\t\t\tlastSelection = {\n\t\t\t\t\t\tanchor: anchor ?? null,\n\t\t\t\t\t\tfocus: focus ?? null\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\t...state,\n\t\t\t\t\tcanUndo,\n\t\t\t\t\tcanRedo\n\t\t\t\t};\n\t\t\t}\n\t\t},\n\t\tview: (view) => {\n\t\t\tundoManager.setOnPush((isUndo, _counterRange) => {\n\t\t\t\tif (loroSyncPluginKey.getState(view.state)?.doc == null) return {\n\t\t\t\t\tvalue: null,\n\t\t\t\t\tcursors: []\n\t\t\t\t};\n\t\t\t\tconst cursors = [];\n\t\t\t\tlet selection = lastSelection;\n\t\t\t\tif (!isUndo) {\n\t\t\t\t\tconst loroState = loroSyncPluginKey.getState(view.state);\n\t\t\t\t\tif (loroState) {\n\t\t\t\t\t\tconst { anchor, focus } = convertPmSelectionToCursors(view.state.doc, view.state.selection, loroState);\n\t\t\t\t\t\tselection.anchor = anchor || null;\n\t\t\t\t\t\tselection.focus = focus || null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (selection.anchor) cursors.push(selection.anchor);\n\t\t\t\tif (selection.focus) cursors.push(selection.focus);\n\t\t\t\treturn {\n\t\t\t\t\tvalue: null,\n\t\t\t\t\tcursors\n\t\t\t\t};\n\t\t\t});\n\t\t\tundoManager.setOnPop((_isUndo, meta, _counterRange) => {\n\t\t\t\tif (loroSyncPluginKey.getState(view.state)?.doc == null) return;\n\t\t\t\tconst anchor = meta.cursors[0];\n\t\t\t\tconst focus = meta.cursors[1];\n\t\t\t\tif (anchor == null) return;\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tsyncCursorsToPmSelection(view, anchor, focus);\n\t\t\t\t}, 0);\n\t\t\t});\n\t\t\treturn { destroy: () => {\n\t\t\t\tundoManager.setOnPop();\n\t\t\t\tundoManager.setOnPush();\n\t\t\t} };\n\t\t}\n\t});\n};\nfunction canUndo(state) {\n\treturn loroUndoPluginKey.getState(state)?.undoManager.canUndo() || false;\n}\nfunction canRedo(state) {\n\treturn loroUndoPluginKey.getState(state)?.undoManager.canRedo() || false;\n}\nconst undo = (state, dispatch) => {\n\tconst undoState = loroUndoPluginKey.getState(state);\n\tif (!undoState) return false;\n\tif (!dispatch) return undoState.undoManager.canUndo();\n\tundoState.isUndoing.current = true;\n\tsetTimeout(() => {\n\t\tundoState.isUndoing.current = false;\n\t}, 0);\n\treturn undoState.undoManager.undo();\n};\nconst redo = (state, dispatch) => {\n\tconst undoState = loroUndoPluginKey.getState(state);\n\tif (!undoState) return false;\n\tif (!dispatch) return undoState.undoManager.canRedo();\n\tundoState.isUndoing.current = true;\n\tsetTimeout(() => {\n\t\tundoState.isUndoing.current = false;\n\t}, 0);\n\treturn undoState.undoManager.redo();\n};\n\n//#endregion\nexport { ATTRIBUTES_KEY, CHILDREN_KEY, CursorAwareness, CursorEphemeralStore, LoroCursorPlugin, LoroEphemeralCursorPlugin, LoroSyncPlugin, LoroUndoPlugin, NODE_NAME_KEY, ROOT_DOC_KEY, canRedo, canUndo, createNodeFromLoroObj, loroSyncPluginKey, loroUndoPluginKey, redo, undo, updateLoroToPmState };\n//# sourceMappingURL=index.js.map", - "import { Schema } from 'prosemirror-model';\n\nconst pDOM = [\"p\", 0], blockquoteDOM = [\"blockquote\", 0], hrDOM = [\"hr\"], preDOM = [\"pre\", [\"code\", 0]], brDOM = [\"br\"];\n/**\n[Specs](https://prosemirror.net/docs/ref/#model.NodeSpec) for the nodes defined in this schema.\n*/\nconst nodes = {\n /**\n NodeSpec The top level document node.\n */\n doc: {\n content: \"block+\"\n },\n /**\n A plain paragraph textblock. Represented in the DOM\n as a `

` element.\n */\n paragraph: {\n content: \"inline*\",\n group: \"block\",\n parseDOM: [{ tag: \"p\" }],\n toDOM() { return pDOM; }\n },\n /**\n A blockquote (`

`) wrapping one or more blocks.\n */\n blockquote: {\n content: \"block+\",\n group: \"block\",\n defining: true,\n parseDOM: [{ tag: \"blockquote\" }],\n toDOM() { return blockquoteDOM; }\n },\n /**\n A horizontal rule (`
`).\n */\n horizontal_rule: {\n group: \"block\",\n parseDOM: [{ tag: \"hr\" }],\n toDOM() { return hrDOM; }\n },\n /**\n A heading textblock, with a `level` attribute that\n should hold the number 1 to 6. Parsed and serialized as `

` to\n `

` elements.\n */\n heading: {\n attrs: { level: { default: 1, validate: \"number\" } },\n content: \"inline*\",\n group: \"block\",\n defining: true,\n parseDOM: [{ tag: \"h1\", attrs: { level: 1 } },\n { tag: \"h2\", attrs: { level: 2 } },\n { tag: \"h3\", attrs: { level: 3 } },\n { tag: \"h4\", attrs: { level: 4 } },\n { tag: \"h5\", attrs: { level: 5 } },\n { tag: \"h6\", attrs: { level: 6 } }],\n toDOM(node) { return [\"h\" + +node.attrs.level, 0]; }\n },\n /**\n A code listing. Disallows marks or non-text inline\n nodes by default. Represented as a `
` element with a\n    `` element inside of it.\n    */\n    code_block: {\n        content: \"text*\",\n        marks: \"\",\n        group: \"block\",\n        code: true,\n        defining: true,\n        parseDOM: [{ tag: \"pre\", preserveWhitespace: \"full\" }],\n        toDOM() { return preDOM; }\n    },\n    /**\n    The text node.\n    */\n    text: {\n        group: \"inline\"\n    },\n    /**\n    An inline image (``) node. Supports `src`,\n    `alt`, and `href` attributes. The latter two default to the empty\n    string.\n    */\n    image: {\n        inline: true,\n        attrs: {\n            src: { validate: \"string\" },\n            alt: { default: null, validate: \"string|null\" },\n            title: { default: null, validate: \"string|null\" }\n        },\n        group: \"inline\",\n        draggable: true,\n        parseDOM: [{ tag: \"img[src]\", getAttrs(dom) {\n                    return {\n                        src: dom.getAttribute(\"src\"),\n                        title: dom.getAttribute(\"title\"),\n                        alt: dom.getAttribute(\"alt\")\n                    };\n                } }],\n        toDOM(node) { let { src, alt, title } = node.attrs; return [\"img\", { src, alt, title }]; }\n    },\n    /**\n    A hard line break, represented in the DOM as `
`.\n */\n hard_break: {\n inline: true,\n group: \"inline\",\n selectable: false,\n parseDOM: [{ tag: \"br\" }],\n toDOM() { return brDOM; }\n }\n};\nconst emDOM = [\"em\", 0], strongDOM = [\"strong\", 0], codeDOM = [\"code\", 0];\n/**\n[Specs](https://prosemirror.net/docs/ref/#model.MarkSpec) for the marks in the schema.\n*/\nconst marks = {\n /**\n A link. Has `href` and `title` attributes. `title`\n defaults to the empty string. Rendered and parsed as an ``\n element.\n */\n link: {\n attrs: {\n href: { validate: \"string\" },\n title: { default: null, validate: \"string|null\" }\n },\n inclusive: false,\n parseDOM: [{ tag: \"a[href]\", getAttrs(dom) {\n return { href: dom.getAttribute(\"href\"), title: dom.getAttribute(\"title\") };\n } }],\n toDOM(node) { let { href, title } = node.attrs; return [\"a\", { href, title }, 0]; }\n },\n /**\n An emphasis mark. Rendered as an `` element. Has parse rules\n that also match `` and `font-style: italic`.\n */\n em: {\n parseDOM: [\n { tag: \"i\" }, { tag: \"em\" },\n { style: \"font-style=italic\" },\n { style: \"font-style=normal\", clearMark: m => m.type.name == \"em\" }\n ],\n toDOM() { return emDOM; }\n },\n /**\n A strong mark. Rendered as ``, parse rules also match\n `` and `font-weight: bold`.\n */\n strong: {\n parseDOM: [\n { tag: \"strong\" },\n // This works around a Google Docs misbehavior where\n // pasted content will be inexplicably wrapped in ``\n // tags with a font-weight normal.\n { tag: \"b\", getAttrs: (node) => node.style.fontWeight != \"normal\" && null },\n { style: \"font-weight=400\", clearMark: m => m.type.name == \"strong\" },\n { style: \"font-weight\", getAttrs: (value) => /^(bold(er)?|[5-9]\\d{2,})$/.test(value) && null },\n ],\n toDOM() { return strongDOM; }\n },\n /**\n Code font mark. Represented as a `` element.\n */\n code: {\n code: true,\n parseDOM: [{ tag: \"code\" }],\n toDOM() { return codeDOM; }\n }\n};\n/**\nThis schema roughly corresponds to the document schema used by\n[CommonMark](http://commonmark.org/), minus the list elements,\nwhich are defined in the [`prosemirror-schema-list`](https://prosemirror.net/docs/ref/#schema-list)\nmodule.\n\nTo reuse elements from this schema, extend or read from its\n`spec.nodes` and `spec.marks` [properties](https://prosemirror.net/docs/ref/#model.Schema.spec).\n*/\nconst schema = new Schema({ nodes, marks });\n\nexport { marks, nodes, schema };\n", - "import { findWrapping, ReplaceAroundStep, canSplit, liftTarget, canJoin } from 'prosemirror-transform';\nimport { NodeRange, Fragment, Slice } from 'prosemirror-model';\nimport { Selection } from 'prosemirror-state';\n\nconst olDOM = [\"ol\", 0], ulDOM = [\"ul\", 0], liDOM = [\"li\", 0];\n/**\nAn ordered list [node spec](https://prosemirror.net/docs/ref/#model.NodeSpec). Has a single\nattribute, `order`, which determines the number at which the list\nstarts counting, and defaults to 1. Represented as an `
    `\nelement.\n*/\nconst orderedList = {\n attrs: { order: { default: 1, validate: \"number\" } },\n parseDOM: [{ tag: \"ol\", getAttrs(dom) {\n return { order: dom.hasAttribute(\"start\") ? +dom.getAttribute(\"start\") : 1 };\n } }],\n toDOM(node) {\n return node.attrs.order == 1 ? olDOM : [\"ol\", { start: node.attrs.order }, 0];\n }\n};\n/**\nA bullet list node spec, represented in the DOM as ` } + if let Some(href) = more { + (show_more) + } } diff --git a/src/app/search.rs b/src/app/search.rs index 41652ee..b4b09f5 100644 --- a/src/app/search.rs +++ b/src/app/search.rs @@ -14,9 +14,13 @@ use crate::app::shell::{now_millis, notebook_name, title_of}; use crate::i18n::{self, Msg, relative_time, results_for, t}; use crate::matcher::{Matcher, Options}; use crate::store::Store; +use note_model::links::percent_encode; /// Most results shown on one page. const RESULT_LIMIT: usize = 50; +/// How long a search reads long notes before it shows what it found, with a link to +/// search them all. +const SEARCH_BUDGET: std::time::Duration = std::time::Duration::from_millis(500); /// The `q` parameter of the search page and of the sidebar search box, and the search /// filters, each on when its parameter is "1". @@ -27,6 +31,8 @@ pub struct SearchQuery { pub word: Option, pub exact: Option, pub re: Option, + /// "1": read every note, however long it takes. + pub all: Option, } /// GET /search: notes whose title or text contain every word of `q`. @@ -50,13 +56,24 @@ async fn search(cx: &Cx) -> Result { return Ok(Child::new(crate::app::all_notes(cx).await?)); } - let hits = match &matcher { - Some(m) => store - .search(m, RESULT_LIMIT) - .await - .map_err(topcoat::Error::from_anyhow)?, - None => Vec::new(), + let budget = (!flag(&query.all)).then_some(SEARCH_BUDGET); + let (hits, partial) = match &matcher { + Some(m) => { + let found = store.search(m, RESULT_LIMIT, budget).await.map_err(topcoat::Error::from_anyhow)?; + (found.hits, found.partial) + } + None => (Vec::new(), false), }; + // The same search without the budget. + let search_all = partial.then(|| { + let mut href = format!("/search?q={}&all=1", percent_encode(&q)); + for (on, key) in [(opts.case, "case"), (opts.word, "word"), (opts.exact, "exact"), (opts.regex, "re")] { + if on { + href.push_str(&format!("&{key}=1")); + } + } + href + }); let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?; let lang = i18n::lang(cx); let now = now_millis(); @@ -108,6 +125,12 @@ async fn search(cx: &Cx) -> Result {

    (title)

    (summary)

    + if let Some(href) = search_all { +

    + (t(lang, Msg::SearchPartial))" " + (t(lang, Msg::SearchAll)) +

    + }
    diff --git a/src/app/shell.rs b/src/app/shell.rs index fc1bd8c..4cc863e 100644 --- a/src/app/shell.rs +++ b/src/app/shell.rs @@ -580,6 +580,9 @@ async fn scheme_items(current: Scheme, back: String) -> Result { const AVATAR: &str = "inline-flex size-8 shrink-0 items-center justify-center rounded-full bg-[var(--active-row)] text-xs font-semibold text-[var(--active-row-foreground)]"; /// A link row in a menu, with an icon, matching `dropdown_menu_item`. const MENU_ROW: &str = "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm whitespace-nowrap hover:bg-foreground/5 focus-visible:bg-foreground/5 active:bg-foreground/10"; +/// Most notebooks the sidebar lists: a long list makes every page heavy, and the rest are +/// found through the command palette. +const SIDEBAR_NOTEBOOKS: usize = 100; /// The sidebar: app name, search, New note, the notes and trash list, notebooks with /// a new-notebook form, and the theme and language controls. It is a `
    } else {
      - for note in trashed { + for note in page.notes {
    • (crate::app::shell::title_of(lang, ¬e.title))

      @@ -127,6 +134,9 @@ async fn trash(cx: &Cx) -> Result {
    • }
    + if let Some(href) = more { + (show_more) + } } if count > 0 { dialog( diff --git a/src/app/unfiled.rs b/src/app/unfiled.rs index 1b741a3..29eba9d 100644 --- a/src/app/unfiled.rs +++ b/src/app/unfiled.rs @@ -9,24 +9,25 @@ use topcoat::{ use crate::app::pane::{self, ListSpec, Mobile}; use crate::i18n::{self, Msg, t}; -use crate::store::Store; +use crate::store::{ListFilter, Store}; /// GET /unfiled: notes that are not in any notebook, beside the list. #[page] async fn unfiled(cx: &Cx) -> Result { let store = app_context::>(cx); - let notes = store.list_notes().await.map_err(topcoat::Error::from_anyhow)?; let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?; - let previews = store.previews().await.map_err(topcoat::Error::from_anyhow)?; + let page = pane::load_page(cx, store, ListFilter::Unfiled) + .await + .map_err(topcoat::Error::from_anyhow)?; let lang = i18n::lang(cx); - let loose: Vec<_> = notes.into_iter().filter(|n| n.notebook_id.is_none()).collect(); let spec = ListSpec { title: t(lang, Msg::Unfiled).to_owned(), heading: true, - count: loose.len(), + count: page.total, notebook_id: String::new(), - groups: pane::groups(lang, &loose, ¬ebooks, &previews, None, false), + groups: pane::groups(lang, &page.notes, ¬ebooks, &page.previews, None, false), empty: t(lang, Msg::EmptyUnfiled), + more: page.more, }; let list = pane::list_pane(cx, lang, spec, Child::new(())); Ok(pane::split( diff --git a/src/editor_assets.rs b/src/editor_assets.rs new file mode 100644 index 0000000..95e8d09 --- /dev/null +++ b/src/editor_assets.rs @@ -0,0 +1,60 @@ +//! The editor bundle's content-hashed file names, read from `assets/editor.manifest`. +//! +//! The build tool writes `editor-<16 hex>.js` and `editor-<16 hex>.wasm` into `assets/` +//! and a manifest with two lines, `js=` and `wasm=`. + +/// The names of the current editor files, as served at the site root. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EditorAssets { + pub js: String, + pub wasm: String, +} + +/// The manifest, relative to the working directory like `public_dir`. +const MANIFEST: &str = "assets/editor.manifest"; + +impl EditorAssets { + /// Reads the manifest. Returns `None` when it is missing or malformed, logging why. + pub fn load() -> Option { + let text = match std::fs::read_to_string(MANIFEST) { + Ok(text) => text, + Err(err) => { + eprintln!("editor assets: cannot read {MANIFEST}: {err}; editor not preloaded"); + return None; + } + }; + let mut js = None; + let mut wasm = None; + for line in text.lines() { + match line.split_once('=') { + Some(("js", name)) => js = Some(name.trim().to_owned()), + Some(("wasm", name)) => wasm = Some(name.trim().to_owned()), + _ => {} + } + } + match (js, wasm) { + (Some(js), Some(wasm)) if content_type(&js) == Some("text/javascript") && content_type(&wasm) == Some("application/wasm") => { + Some(EditorAssets { js, wasm }) + } + _ => { + eprintln!("editor assets: {MANIFEST} must name a hashed js and wasm file; editor not preloaded"); + None + } + } + } +} + +/// The content type for a content-hashed editor file name (`editor-<16 hex>.js` or +/// `editor-<16 hex>.wasm`), or `None` for any other name. +pub fn content_type(name: &str) -> Option<&'static str> { + let (stem, ext) = name.rsplit_once('.')?; + let hash = stem.strip_prefix("editor-")?; + if hash.len() != 16 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + match ext { + "js" => Some("text/javascript"), + "wasm" => Some("application/wasm"), + _ => None, + } +} diff --git a/src/export.rs b/src/export.rs index 98e5422..1ff3ef1 100644 --- a/src/export.rs +++ b/src/export.rs @@ -1,11 +1,12 @@ -//! Markdown export from a loro-prosemirror shaped LoroDoc. -//! -//! Layout (see loro-prosemirror `createLoroMap` / `createLoroText`): the root -//! is `doc.get_map("doc")`. Every non-text node is a LoroMap with `nodeName`, -//! `attributes` (LoroMap) and `children` (LoroList). Children are either node -//! maps or a LoroText whose rich-text deltas carry the marks as attributes. +//! Markdown export of a note, from its block tree (`note_model::flat`). -use loro::{Container, LoroDoc, LoroMap, LoroText, LoroValue, TextDelta, ValueOrContainer}; +use loro::LoroDoc; +use note_model::links::{link_target, percent_encode}; +use note_model::marks::Marks; +use note_model::write::{Block, Inline}; + +pub use note_model::links::{LinkTarget, note_links}; +pub use note_model::tree::title; mod html; pub use html::{html_page, to_html}; @@ -18,85 +19,144 @@ pub type Resolve<'a> = &'a dyn Fn(&str) -> Option; #[derive(Clone, Copy)] struct Ctx<'a> { wiki: Option>, + /// Set by `to_markdown_deferred`: links by id become placeholders, counted here. + deferred: Option<&'a std::cell::Cell>, } +/// Placeholder marks for links by id in `to_markdown_deferred`: Unicode noncharacters, +/// which text does not hold. +const DEFER_START: char = '\u{FDD0}'; +const DEFER_SEP: char = '\u{FDD1}'; +const DEFER_END: char = '\u{FDD2}'; + /// Full note as CommonMark/GFM. Note links stay ordinary markdown links, which is /// what the search text wants. pub fn to_markdown(doc: &LoroDoc) -> String { - render_doc(doc, Ctx { wiki: None }) + Body::read(doc).markdown() } /// Full note as markdown with note links written as `[[Title]]` (or `[[Title|text]]` /// when the link text differs). Links by title use the stored title; links by id use /// `resolve`, and an id it cannot name stays an ordinary link. pub fn to_markdown_with(doc: &LoroDoc, resolve: Resolve<'_>) -> String { - render_doc(doc, Ctx { wiki: Some(resolve) }) + Body::read(doc).markdown_with(resolve) +} + +/// `to_markdown_with` with the titles of links by id left as placeholders, for +/// [`resolve_deferred`] to fill in: the result stays right when a linked note is +/// renamed. None when the note's text holds the placeholder marks itself. +pub fn to_markdown_deferred(doc: &LoroDoc) -> Option { + Body::read(doc).markdown_deferred() +} + +/// A note's body read once. Every whole-note text comes from it without the doc, so +/// the hub reads it under the room lock (one pass over the text) and renders off it. +pub struct Body { + blocks: Vec, + links: Vec, +} + +/// As [`Body::title`], reading only the doc's start when the title is there: the first +/// text block with content, when it ends within that start. +pub fn title_of(doc: &LoroDoc) -> String { + const START: usize = 64 << 10; + let text = note_model::flat::body(doc); + let len = text.len_unicode(); + if len > START { + if let Ok(delta) = text.slice_delta(0, START, loro::cursor::PosType::Unicode) { + let mut blocks = note_model::flat::read_delta(delta); + blocks.pop(); // may be cut short, and its kind unknown + if let Some(b) = blocks.iter().find(|b| b.attrs.kind.is_text() && !b.plain().trim().is_empty()) { + return note_model::tree::title_from(&b.plain()); + } + } + } + Body::read(doc).title() } -fn render_doc(doc: &LoroDoc, cx: Ctx<'_>) -> String { - let root = doc.get_map("doc"); - let body = render_children(&root, false, cx); - if body.is_empty() { - String::new() - } else { - format!("{body}\n") +impl Body { + pub fn read(doc: &LoroDoc) -> Body { + let delta = note_model::flat::body(doc).to_delta(); + let links = note_model::links::links_in(&delta); + Body { blocks: note_model::flat::read_delta(delta), links } } -} -/// A link to another note: by id (`/notes/`) or by title (`/notes/by-title/`). -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum LinkTarget { - Id(String), - Title(String), + /// As [`title`]. + pub fn title(&self) -> String { + let first = self.blocks.iter().find(|b| b.attrs.kind.is_text() && !b.plain().trim().is_empty()); + note_model::tree::title_from(&first.map(|b| b.plain()).unwrap_or_default()) + } + + /// As [`note_links`]. + pub fn note_links(&self) -> Vec<LinkTarget> { + self.links.clone() + } + + /// As [`to_markdown`]. + pub fn markdown(&self) -> String { + self.render(Ctx { wiki: None, deferred: None }) + } + + /// As [`to_markdown_with`]. + pub fn markdown_with(&self, resolve: Resolve<'_>) -> String { + self.render(Ctx { wiki: Some(resolve), deferred: None }) + } + + /// As [`to_markdown_deferred`]. + pub fn markdown_deferred(&self) -> Option<String> { + let count = std::cell::Cell::new(0); + let none = |_: &str| None; + let md = self.render(Ctx { wiki: Some(&none), deferred: Some(&count) }); + let marks = |c: char| md.chars().filter(|&x| x == c).count(); + let n = count.get(); + (marks(DEFER_START) == n && marks(DEFER_END) == n && marks(DEFER_SEP) == 4 * n).then_some(md) + } + + /// As [`to_html`]. + pub fn html(&self) -> String { + html::render_blocks(¬e_model::flat::nest(&self.blocks)) + } + + fn render(&self, cx: Ctx<'_>) -> String { + let body = render_blocks(¬e_model::flat::nest(&self.blocks), false, cx); + if body.is_empty() { String::new() } else { format!("{body}\n") } + } } -/// Every note the doc links to, each target once, in document order. Hrefs that are -/// not note links are ignored. -pub fn note_links(doc: &LoroDoc) -> Vec<LinkTarget> { - let mut out = Vec::new(); - collect_links(&doc.get_map("doc"), &mut out); +/// Fills in the links of a `to_markdown_deferred` result with the current titles, +/// as `to_markdown_with` would have written them. +pub fn resolve_deferred(md: &str, resolve: Resolve<'_>) -> String { + let mut out = String::with_capacity(md.len()); + let mut rest = md; + while let Some(at) = rest.find(DEFER_START) { + out.push_str(&rest[..at]); + let after = &rest[at + DEFER_START.len_utf8()..]; + let end = after.find(DEFER_END).unwrap_or(after.len()); + let mut fields = after[..end].split(DEFER_SEP); + let mut next = || fields.next().unwrap_or(""); + let (id, core, flags, inner, dest) = (next(), next(), next(), next(), next()); + out.push_str(&deferred_link(resolve(id), core, flags, inner, dest)); + rest = after.get(end + DEFER_END.len_utf8()..).unwrap_or(""); + } + out.push_str(rest); out } -fn collect_links(node: &LoroMap, out: &mut Vec<LinkTarget>) { - for child in children(node) { - match child { - Child::Text(text) => { - for delta in text.to_delta() { - let TextDelta::Insert { - attributes: Some(attrs), - .. - } = delta - else { - continue; - }; - let Some(href) = attrs - .get("link") - .and_then(|link| link.get_by_key("href")) - .and_then(value_str) - else { - continue; - }; - if let Some(target) = link_target(&href) { - if !out.contains(&target) { - out.push(target); - } - } - } +/// One link by id of `render_group`, given the note's title if it has one. +fn deferred_link(target: Option<String>, core: &str, flags: &str, inner: &str, dest: &str) -> String { + let Some(target) = target else { return format!("[{inner}]({dest})") }; + if flags.contains('u') { + if let Some(mut link) = wiki_link(&target, core) { + if flags.contains('e') { + link = format!("*{link}*"); + } + if flags.contains('s') { + link = format!("**{link}**"); } - Child::Node(m) => collect_links(&m, out), + return link; } } -} - -fn link_target(href: &str) -> Option<LinkTarget> { - let rest = href.strip_prefix("/notes/")?; - if let Some(encoded) = rest.strip_prefix("by-title/") { - let title = percent_decode(encoded); - return (!title.trim().is_empty()).then_some(LinkTarget::Title(title)); - } - let is_id = !rest.is_empty() && !rest.contains(['/', '?', '#']); - is_id.then(|| LinkTarget::Id(rest.to_owned())) + format!("[{inner}]({})", percent_encode(&format!("{target}.md"))) } /// The note a link mark points at, as a title, when the link is a note link the @@ -123,190 +183,33 @@ fn wiki_link(target: &str, text: &str) -> Option<String> { } } -/// Percent-encodes everything except RFC 3986 unreserved characters. -pub fn percent_encode(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - for b in s.bytes() { - match b { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { - out.push(b as char) - } - _ => out.push_str(&format!("%{b:02X}")), - } - } - out -} - -/// Decodes `%XX` escapes. Malformed escapes are kept as they are. -pub fn percent_decode(s: &str) -> String { - let bytes = s.as_bytes(); - let mut out = Vec::with_capacity(bytes.len()); - let mut i = 0; - while i < bytes.len() { - if bytes[i] == b'%' && i + 2 < bytes.len() { - let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok(); - if let Some(v) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) { - out.push(v); - i += 3; - continue; - } - } - out.push(bytes[i]); - i += 1; - } - String::from_utf8_lossy(&out).into_owned() -} - -/// Plain text of the first non-empty block, trimmed, max 80 chars. "Untitled" if empty. -pub fn title(doc: &LoroDoc) -> String { - let root = doc.get_map("doc"); - let raw = first_text(&root).unwrap_or_default(); - let collapsed = raw.split_whitespace().collect::<Vec<_>>().join(" "); - let truncated: String = collapsed.chars().take(80).collect(); - let trimmed = truncated.trim_end(); - if trimmed.is_empty() { - "Untitled".to_string() - } else { - trimmed.to_string() - } -} - -// --------------------------------------------------------------------------- -// Tree access helpers -// --------------------------------------------------------------------------- - -pub(super) enum Child { - Text(LoroText), - Node(LoroMap), -} - -pub(super) fn children(node: &LoroMap) -> Vec<Child> { - let mut out = Vec::new(); - let Some(ValueOrContainer::Container(Container::List(list))) = node.get("children") else { - return out; - }; - for i in 0..list.len() { - match list.get(i) { - Some(ValueOrContainer::Container(Container::Text(t))) => out.push(Child::Text(t)), - Some(ValueOrContainer::Container(Container::Map(m))) => out.push(Child::Node(m)), - _ => {} - } - } - out -} - -pub(super) fn node_name(node: &LoroMap) -> String { - match node.get("nodeName") { - Some(ValueOrContainer::Value(v)) => value_str(&v).unwrap_or_default(), - _ => String::new(), - } -} - -pub(super) fn attr(node: &LoroMap, key: &str) -> Option<LoroValue> { - match node.get("attributes") { - Some(ValueOrContainer::Container(Container::Map(attrs))) => match attrs.get(key) { - Some(ValueOrContainer::Value(v)) => Some(v), - _ => None, - }, - _ => None, - } -} - -pub(super) fn attr_str(node: &LoroMap, key: &str) -> Option<String> { - attr(node, key).and_then(|v| value_str(&v)) -} - -pub(super) fn attr_num(node: &LoroMap, key: &str) -> Option<i64> { - match attr(node, key)? { - LoroValue::I64(i) => Some(i), - LoroValue::Double(d) => Some(d as i64), - _ => None, - } -} - -pub(super) fn value_str(v: &LoroValue) -> Option<String> { - v.as_string().map(|s| s.as_str().to_owned()) -} - -pub(super) fn plain_text(text: &LoroText) -> String { - text.to_delta() - .into_iter() - .filter_map(|d| match d { - TextDelta::Insert { insert, .. } => Some(insert), - _ => None, - }) - .collect() -} - -pub(super) fn plain_node_text(node: &LoroMap) -> String { - children(node) - .into_iter() - .map(|c| match c { - Child::Text(t) => plain_text(&t), - Child::Node(m) => plain_node_text(&m), - }) - .collect() -} - -/// First non-blank text of the tree, in document order. -fn first_text(node: &LoroMap) -> Option<String> { - for child in children(node) { - let found = match child { - Child::Text(t) => Some(plain_text(&t)), - Child::Node(m) => first_text(&m), - }; - if let Some(s) = found { - if !s.trim().is_empty() { - return Some(s); - } - } - } - None -} - // --------------------------------------------------------------------------- // Block rendering // --------------------------------------------------------------------------- -/// Renders the children of `node` as blocks separated by blank lines. -/// With `tight`, a nested list directly follows its sibling with a single -/// newline instead of a blank line (used inside list items). -fn render_children(node: &LoroMap, tight: bool, cx: Ctx<'_>) -> String { - let mut blocks: Vec<(String, bool)> = Vec::new(); - for child in children(node) { - match child { - Child::Text(t) => { - let s = paragraph_text(inline_text(&t, cx)); - if !s.is_empty() { - blocks.push((s, false)); - } - } - Child::Node(m) => { - let is_list = matches!(node_name(&m).as_str(), "bullet_list" | "ordered_list"); - if let Some(s) = render_block(&m, cx) { - blocks.push((s, is_list)); - } - } - } - } - +/// Renders blocks separated by blank lines. With `tight`, a nested list directly +/// follows its sibling with a single newline instead of a blank line (used inside +/// list items). +fn render_blocks(blocks: &[Block], tight: bool, cx: Ctx<'_>) -> String { let mut out = String::new(); - for (i, (block, is_list)) in blocks.iter().enumerate() { - if i > 0 { - out.push_str(if tight && *is_list { "\n" } else { "\n\n" }); + let mut first = true; + for b in blocks { + let Some(s) = render_block(b, cx) else { continue }; + if !first { + out.push_str(if tight && matches!(b, Block::List { .. }) { "\n" } else { "\n\n" }); } - out.push_str(block); + first = false; + out.push_str(&s); } out } -fn render_block(node: &LoroMap, cx: Ctx<'_>) -> Option<String> { - let name = node_name(node); - let out = match name.as_str() { - "paragraph" => paragraph_text(inline_children(node, cx)), - "heading" => { - let level = attr_num(node, "level").unwrap_or(1).clamp(1, 6) as usize; - let text = inline_children(node, cx).replace('\n', " "); +fn render_block(block: &Block, cx: Ctx<'_>) -> Option<String> { + let out = match block { + Block::Paragraph(inl) => paragraph_text(inline(inl, cx)), + Block::Heading(level, inl) => { + let level = (*level).clamp(1, 6) as usize; + let text = inline(inl, cx).replace('\n', " "); let text = text.trim(); if text.is_empty() { String::new() @@ -314,7 +217,7 @@ fn render_block(node: &LoroMap, cx: Ctx<'_>) -> Option<String> { format!("{} {}", "#".repeat(level), text) } } - "blockquote" => render_children(node, false, cx) + Block::Quote(inner) => render_blocks(inner, false, cx) .lines() .map(|l| { if l.is_empty() { @@ -325,15 +228,9 @@ fn render_block(node: &LoroMap, cx: Ctx<'_>) -> Option<String> { }) .collect::<Vec<_>>() .join("\n"), - "code_block" => code_block(node), - "horizontal_rule" => "---".to_string(), - "bullet_list" => render_list(node, false, cx), - "ordered_list" => render_list(node, true, cx), - "list_item" => render_children(node, true, cx), - "image" => paragraph_text(image_md(node)), - "hard_break" => String::new(), - // doc and unknown containers: render their children. - _ => render_children(node, false, cx), + Block::Code { lang, text } => code_block(lang.as_deref(), text), + Block::Rule => "---".to_string(), + Block::List { ordered, start, items } => render_list(items, *ordered, *start, cx), }; if out.trim().is_empty() { @@ -343,26 +240,17 @@ fn render_block(node: &LoroMap, cx: Ctx<'_>) -> Option<String> { } } -fn render_list(node: &LoroMap, ordered: bool, cx: Ctx<'_>) -> String { - let start = if ordered { - attr_num(node, "order").unwrap_or(1) - } else { - 1 - }; +fn render_list(list: &[Vec<Block>], ordered: bool, start: i64, cx: Ctx<'_>) -> String { + let start = if ordered { start } else { 1 }; let mut items = Vec::new(); - let mut index: i64 = 0; - for child in children(node) { - let Child::Node(item) = child else { - continue; - }; + for (index, item) in list.iter().enumerate() { let marker = if ordered { - format!("{}. ", start + index) + format!("{}. ", start + index as i64) } else { "- ".to_string() }; - index += 1; - let body = render_children(&item, true, cx); + let body = render_blocks(item, true, cx); if body.is_empty() { items.push(marker.trim_end().to_string()); continue; @@ -382,18 +270,14 @@ fn render_list(node: &LoroMap, ordered: bool, cx: Ctx<'_>) -> String { items.join("\n") } -fn code_block(node: &LoroMap) -> String { - let mut content = String::new(); - for child in children(node) { - match child { - Child::Text(t) => content.push_str(&plain_text(&t)), - Child::Node(m) if node_name(&m) == "hard_break" => content.push('\n'), - Child::Node(m) => content.push_str(&plain_node_text(&m)), - } - } +fn code_block(lang: Option<&str>, content: &str) -> String { let content = content.trim_end_matches('\n'); let fence = "`".repeat((longest_backtick_run(content) + 1).max(3)); - let lang = attr_str(node, "language").unwrap_or_default(); + // An explicit language wins; without one, the language is detected. + let lang = lang + .filter(|l| !l.trim().is_empty()) + .or_else(|| note_model::lang::detect(content)) + .unwrap_or_default(); if content.is_empty() { format!("{fence}{lang}\n{fence}") } else { @@ -464,65 +348,34 @@ fn escape_line_start(line: &str) -> String { // Inline rendering // --------------------------------------------------------------------------- -/// Concatenated inline content of a node: text runs and inline child nodes. -fn inline_children(node: &LoroMap, cx: Ctx<'_>) -> String { +/// Inline content as markdown. Each stretch of text between breaks and images merges +/// adjacent runs with identical marks, so e.g. two bold runs become one `**...**` span. +fn inline(inl: &[Inline], cx: Ctx<'_>) -> String { let mut out = String::new(); - for child in children(node) { - match child { - Child::Text(t) => out.push_str(&inline_text(&t, cx)), - Child::Node(m) => out.push_str(&inline_node(&m, cx)), + let mut runs: Vec<(String, Marks)> = Vec::new(); + for i in inl { + match i { + Inline::Text(s, m) => match runs.last_mut() { + Some((t, last)) if last == m => t.push_str(s), + _ => runs.push((s.clone(), m.clone())), + }, + Inline::HardBreak => { + out.push_str(&text_runs(&std::mem::take(&mut runs), cx)); + out.push_str("\\\n"); + } + Inline::Image { src, alt, title } => { + out.push_str(&text_runs(&std::mem::take(&mut runs), cx)); + out.push_str(&image_md(src, alt, title.as_deref())); + } } } + out.push_str(&text_runs(&runs, cx)); out } -fn inline_node(node: &LoroMap, cx: Ctx<'_>) -> String { - match node_name(node).as_str() { - "hard_break" => "\\\n".to_string(), - "image" => image_md(node), - _ => inline_children(node, cx), - } -} - -#[derive(PartialEq, Clone, Default)] -struct Marks { - strong: bool, - em: bool, - code: bool, - link: Option<(String, Option<String>)>, -} - -/// Renders a LoroText as markdown, merging adjacent runs with identical marks -/// so that e.g. two bold runs become one `**...**` span. -fn inline_text(text: &LoroText, cx: Ctx<'_>) -> String { - let mut runs: Vec<(String, Marks)> = Vec::new(); - for delta in text.to_delta() { - let TextDelta::Insert { insert, attributes } = delta else { - continue; - }; - let attrs = attributes.unwrap_or_default(); - let on = |k: &str| attrs.get(k).is_some_and(|v| !matches!(v, LoroValue::Null)); - let link = attrs.get("link").map(|v| { - let href = v.get_by_key("href").and_then(value_str).unwrap_or_default(); - let title = v - .get_by_key("title") - .and_then(value_str) - .filter(|t| !t.is_empty()); - (href, title) - }); - let marks = Marks { - strong: on("strong"), - em: on("em"), - code: on("code"), - link, - }; - match runs.last_mut() { - Some((s, m)) if *m == marks => s.push_str(&insert), - _ => runs.push((insert, marks)), - } - } - // Consecutive runs under the same link render as one link, so a partly bold link - // stays a single link. +/// Consecutive runs under the same link render as one link, so a partly bold link +/// stays a single link. +fn text_runs(runs: &[(String, Marks)], cx: Ctx<'_>) -> String { let mut out = String::new(); let mut i = 0; while i < runs.len() { @@ -538,7 +391,6 @@ fn inline_text(text: &LoroText, cx: Ctx<'_>) -> String { out } -/// One run without a link, or every run of one link. fn render_group(group: &[(String, Marks)], cx: Ctx<'_>) -> String { let Some((href, title)) = group[0].1.link.clone() else { return render_marks(&group[0].0, &group[0].1); @@ -551,11 +403,20 @@ fn render_group(group: &[(String, Marks)], cx: Ctx<'_>) -> String { let lead = &text[..text.len() - text.trim_start().len()]; let trail = &text[lead.len() + core.len()..]; + let first = &group[0].1; + // Marks that cover the whole link go around `[[...]]`, which can't hold any. + let uniform = !first.code && group.iter().all(|(_, m)| m.strong == first.strong && m.em == first.em); + if let (Some(count), Some(LinkTarget::Id(id))) = (cx.deferred, link_target(&href)) { + count.set(count.get() + 1); + let inner: String = group.iter().map(|(s, m)| render_marks(s, m)).collect(); + let flags = [(uniform, 'u'), (first.em, 'e'), (first.strong, 's')].iter().filter(|f| f.0).map(|f| f.1).collect::<String>(); + let dest = link_dest(&href, title.as_deref()); + return format!( + "{lead}{DEFER_START}{id}{DEFER_SEP}{core}{DEFER_SEP}{flags}{DEFER_SEP}{}{DEFER_SEP}{dest}{DEFER_END}{trail}", + inner.trim() + ); + } if let Some(target) = wiki_target(&href, cx) { - // Marks that cover the whole link go around `[[...]]`, which can't hold any. - let first = &group[0].1; - let uniform = !first.code - && group.iter().all(|(_, m)| m.strong == first.strong && m.em == first.em); if uniform { if let Some(mut link) = wiki_link(&target, core) { if first.em { @@ -654,16 +515,14 @@ fn link_dest(href: &str, title: Option<&str>) -> String { } } -fn image_md(node: &LoroMap) -> String { - let alt = attr_str(node, "alt").unwrap_or_default(); - let src = attr_str(node, "src").unwrap_or_default(); +fn image_md(src: &str, alt: &str, title: Option<&str>) -> String { if src.is_empty() { - return escape_text(&alt); + return escape_text(alt); } let alt = alt .replace('\\', "\\\\") .replace('[', "\\[") .replace(']', "\\]"); - let title = attr_str(node, "title").filter(|t| !t.is_empty()); - format!("![{alt}]({})", link_dest(&src, title.as_deref())) + let title = title.filter(|t| !t.is_empty()); + format!("![{alt}]({})", link_dest(src, title)) } diff --git a/src/export/html.rs b/src/export/html.rs index a2538ef..3a6ac16 100644 --- a/src/export/html.rs +++ b/src/export/html.rs @@ -1,15 +1,15 @@ -//! HTML export. Walks the same loro-prosemirror tree as the markdown export in -//! the parent module and emits an HTML body fragment, plus a standalone page -//! wrapper for download and print. +//! HTML export. Renders the plain block tree from `note_model::flat` as an HTML +//! body fragment, plus a standalone page wrapper for download and print. -use loro::{LoroDoc, LoroMap, LoroText, LoroValue, TextDelta}; - -use super::{Child, attr_num, attr_str, children, node_name, plain_node_text, plain_text, value_str}; +use loro::LoroDoc; +use note_model::marks::Marks; +use note_model::render::{Embed, embed_of}; +use note_model::write::{Block, Inline}; /// Note body as an HTML fragment (no surrounding document). pub fn to_html(doc: &LoroDoc) -> String { - let root = doc.get_map("doc"); - render_children(&root) + let blocks = note_model::flat::doc_blocks(doc); + render_blocks(&blocks) } /// Standalone HTML document around `body`. With `print`, the page opens the @@ -42,14 +42,14 @@ code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size: background:#f2f2f4;padding:.1em .3em;border-radius:4px}\ pre{background:#f2f2f4;padding:.75em 1em;border-radius:6px;overflow-x:auto;white-space:pre}\ pre code{background:none;padding:0;font-size:.875em}\ -img{max-width:100%;height:auto}\ +img,video,audio{max-width:100%;height:auto}audio{display:block}\ hr{border:0;border-top:1px solid #d0d0d5;margin:2em 0}\ a{color:#0a58ca}\ table{border-collapse:collapse;max-width:100%}\ th,td{border:1px solid #d0d0d5;padding:.4em .6em;text-align:left}\ @page{margin:2cm}\ @media print{body{color:#000}.note{max-width:none;margin:0;padding:0}\ -a{color:inherit}pre,blockquote,img{break-inside:avoid}pre{background:#f2f2f2}code{background:#f2f2f2}}"; +a{color:inherit}pre,blockquote,img,video,audio{break-inside:avoid}pre{background:#f2f2f2}code{background:#f2f2f2}}"; // --------------------------------------------------------------------------- // Escaping and link safety @@ -105,64 +105,50 @@ fn safe_src(src: &str) -> Option<&str> { // Block rendering // --------------------------------------------------------------------------- -/// Renders the children of `node` as blocks, in order. -fn render_children(node: &LoroMap) -> String { +/// Renders `blocks` in order. +pub(super) fn render_blocks(blocks: &[Block]) -> String { let mut out = String::new(); - for child in children(node) { - match child { - Child::Text(t) => { - let inner = inline_text(&t); - if !inner.trim().is_empty() { - out.push_str(&format!("<p>{}</p>\n", inner.trim())); - } - } - Child::Node(m) => { - if let Some(html) = render_block(&m) { - out.push_str(&html); - out.push('\n'); - } - } + for block in blocks { + if let Some(html) = render_block(block) { + out.push_str(&html); + out.push('\n'); } } out } -fn render_block(node: &LoroMap) -> Option<String> { - let html = match node_name(node).as_str() { - "paragraph" => { - let inner = inline_children(node); +fn render_block(block: &Block) -> Option<String> { + let html = match block { + Block::Paragraph(inlines) => { + let inner = render_inlines(inlines); if inner.trim().is_empty() { return None; } format!("<p>{}</p>", inner.trim()) } - "heading" => { - let level = attr_num(node, "level").unwrap_or(1).clamp(1, 6); - let inner = inline_children(node).replace('\n', " "); + Block::Heading(level, inlines) => { + let level = (*level).clamp(1, 6); + let inner = render_inlines(inlines).replace('\n', " "); let inner = inner.trim(); if inner.is_empty() { return None; } format!("<h{level}>{inner}</h{level}>") } - "blockquote" => { - let inner = render_children(node); + Block::Quote(blocks) => { + let inner = render_blocks(blocks); if inner.trim().is_empty() { return None; } format!("<blockquote>\n{inner}</blockquote>") } - "code_block" => code_block(node), - "horizontal_rule" => "<hr>".to_string(), - "bullet_list" => render_list(node, false)?, - "ordered_list" => render_list(node, true)?, - "image" => { - let inner = image_html(node); - format!("<p>{inner}</p>") - } - "hard_break" => return None, - // doc and unknown containers: render their children. - _ => render_children(node), + Block::Code { lang, text } => code_block(lang.as_deref(), text), + Block::Rule => "<hr>".to_string(), + Block::List { + ordered, + start, + items, + } => render_list(*ordered, *start, items)?, }; if html.trim().is_empty() { None @@ -171,41 +157,34 @@ fn render_block(node: &LoroMap) -> Option<String> { } } -fn render_list(node: &LoroMap, ordered: bool) -> Option<String> { - let mut items = String::new(); - for child in children(node) { - let Child::Node(item) = child else { - continue; - }; - items.push_str(&format!("<li>{}</li>\n", render_children(&item).trim_end())); +fn render_list(ordered: bool, start: i64, items: &[Vec<Block>]) -> Option<String> { + let mut rendered = String::new(); + for item in items { + rendered.push_str(&format!("<li>{}</li>\n", render_blocks(item).trim_end())); } - if items.is_empty() { + if rendered.is_empty() { return None; } if ordered { - let start = attr_num(node, "order").unwrap_or(1); let start_attr = if start == 1 { String::new() } else { format!(" start=\"{start}\"") }; - Some(format!("<ol{start_attr}>\n{items}</ol>")) + Some(format!("<ol{start_attr}>\n{rendered}</ol>")) } else { - Some(format!("<ul>\n{items}</ul>")) + Some(format!("<ul>\n{rendered}</ul>")) } } -fn code_block(node: &LoroMap) -> String { - let mut content = String::new(); - for child in children(node) { - match child { - Child::Text(t) => content.push_str(&plain_text(&t)), - Child::Node(m) if node_name(&m) == "hard_break" => content.push('\n'), - Child::Node(m) => content.push_str(&plain_node_text(&m)), - } - } - let content = content.trim_end_matches('\n'); - let lang = attr_str(node, "language").unwrap_or_default(); +fn code_block(lang: Option<&str>, text: &str) -> String { + let content = text.trim_end_matches('\n'); + // An explicit language wins; without one, the language is detected. + let lang = lang + .filter(|l| !l.trim().is_empty()) + .map(str::to_owned) + .or_else(|| note_model::lang::detect(content).map(str::to_owned)) + .unwrap_or_default(); let class = if lang.trim().is_empty() { String::new() } else { @@ -218,76 +197,35 @@ fn code_block(node: &LoroMap) -> String { // Inline rendering // --------------------------------------------------------------------------- -/// Concatenated inline content of a node: text runs and inline child nodes. -fn inline_children(node: &LoroMap) -> String { +/// Concatenated inline content: text runs, hard breaks and images. +fn render_inlines(inlines: &[Inline]) -> String { let mut out = String::new(); - for child in children(node) { - match child { - Child::Text(t) => out.push_str(&inline_text(&t)), - Child::Node(m) => out.push_str(&inline_node(&m)), + for inline in inlines { + match inline { + Inline::Text(s, m) => out.push_str(&render_run(s, m)), + Inline::HardBreak => out.push_str("<br>"), + Inline::Image { src, alt, title } => { + out.push_str(&image_html(src, alt, title.as_deref())); + } } } out } -fn inline_node(node: &LoroMap) -> String { - match node_name(node).as_str() { - "hard_break" => "<br>".to_string(), - "image" => image_html(node), - _ => inline_children(node), - } -} - -fn image_html(node: &LoroMap) -> String { - let alt = attr_str(node, "alt").unwrap_or_default(); - let src = attr_str(node, "src").unwrap_or_default(); - let Some(src) = safe_src(&src) else { - return esc(&alt); +fn image_html(src: &str, alt: &str, title: Option<&str>) -> String { + let Some(safe) = safe_src(src) else { + return esc(alt); }; - let title = attr_str(node, "title") + let title = title .filter(|t| !t.is_empty()) - .map(|t| format!(" title=\"{}\"", esc(&t))) + .map(|t| format!(" title=\"{}\"", esc(t))) .unwrap_or_default(); - format!("<img src=\"{}\" alt=\"{}\"{title}>", esc(src), esc(&alt)) -} - -#[derive(PartialEq, Clone, Default)] -struct Marks { - strong: bool, - em: bool, - code: bool, - link: Option<(String, Option<String>)>, -} - -/// Renders a LoroText as HTML, merging adjacent runs with identical marks. -fn inline_text(text: &LoroText) -> String { - let mut runs: Vec<(String, Marks)> = Vec::new(); - for delta in text.to_delta() { - let TextDelta::Insert { insert, attributes } = delta else { - continue; - }; - let attrs = attributes.unwrap_or_default(); - let on = |k: &str| attrs.get(k).is_some_and(|v| !matches!(v, LoroValue::Null)); - let link = attrs.get("link").map(|v| { - let href = v.get_by_key("href").and_then(value_str).unwrap_or_default(); - let title = v - .get_by_key("title") - .and_then(value_str) - .filter(|t| !t.is_empty()); - (href, title) - }); - let marks = Marks { - strong: on("strong"), - em: on("em"), - code: on("code"), - link, - }; - match runs.last_mut() { - Some((s, m)) if *m == marks => s.push_str(&insert), - _ => runs.push((insert, marks)), - } + let (src, alt) = (esc(safe), esc(alt)); + match embed_of(safe) { + Some(Embed::Audio) => format!("<audio controls src=\"{src}\" aria-label=\"{alt}\"{title}></audio>"), + Some(Embed::Video) => format!("<video controls src=\"{src}\" aria-label=\"{alt}\"{title}></video>"), + _ => format!("<img src=\"{src}\" alt=\"{alt}\"{title}>"), } - runs.iter().map(|(s, m)| render_run(s, m)).collect() } fn render_run(s: &str, m: &Marks) -> String { diff --git a/src/format.rs b/src/format.rs new file mode 100644 index 0000000..172e722 --- /dev/null +++ b/src/format.rs @@ -0,0 +1,140 @@ +//! Code formatting for the editor's `POST /format` endpoint. Maps a canonical language id +//! to its formatter. Errors are short messages that go back to the user as they are. + +use std::path::Path; + +/// Formats `code` as `language` (a canonical lowercase id). The output keeps the input's +/// trailing-newline state: a formatter's added newline is removed when the input had none. +pub fn format(language: &str, code: &str) -> Result<String, String> { + let out = match language { + "rust" => format_rust(code)?, + "javascript" => format_typescript(code, "js")?, + "typescript" => format_typescript(code, "tsx")?, + "json" => format_json(code)?, + "css" => malva::format_text(code, malva::Syntax::Css, &Default::default()) + .map_err(|err| err.to_string())?, + "html" => markup_fmt::format_text( + code, + markup_fmt::Language::Html, + &Default::default(), + |code, _| Ok(code.into()), + ) + .map_err(|err| err.to_string())?, + "yaml" => pretty_yaml::format_text(code, &Default::default()) + .map_err(|err| err.to_string())?, + "toml" => format_toml(code)?, + "sql" => format_sql(code), + "markdown" => format_markdown(code)?, + _ => return Err(format!("unsupported language: {language}")), + }; + Ok(keep_trailing_newline(code, out)) +} + +/// A whole file if it parses, else a snippet of statements: the snippet is wrapped in a +/// function, formatted, and its body is taken back out with one indent level removed. +fn format_rust(code: &str) -> Result<String, String> { + if let Ok(file) = syn::parse_file(code) { + return Ok(prettyplease::unparse(&file)); + } + let wrapped = format!("fn __snippet__() {{\n{code}\n}}"); + let file = syn::parse_file(&wrapped).map_err(|err| err.to_string())?; + let out = prettyplease::unparse(&file); + let body = out + .strip_prefix("fn __snippet__() {\n") + .and_then(|rest| rest.strip_suffix("}\n")) + .unwrap_or(""); + let lines: Vec<&str> = body + .lines() + .map(|line| line.strip_prefix(" ").unwrap_or(line)) + .collect(); + Ok(lines.join("\n") + "\n") +} + +fn format_typescript(code: &str, extension: &str) -> Result<String, String> { + let config = dprint_plugin_typescript::configuration::ConfigurationBuilder::new() + .indent_width(2) + .build(); + let file_name = format!("snippet.{extension}"); + let options = dprint_plugin_typescript::FormatTextOptions { + path: Path::new(&file_name), + extension: Some(extension), + text: code.to_owned(), + config: &config, + external_formatter: None, + }; + let out = dprint_plugin_typescript::format_text(options).map_err(|err| err.to_string())?; + Ok(out.unwrap_or_else(|| code.to_owned())) +} + +fn format_json(code: &str) -> Result<String, String> { + let config = dprint_plugin_json::configuration::ConfigurationBuilder::new() + .indent_width(2) + .build(); + let out = dprint_plugin_json::format_text(Path::new("snippet.json"), code, &config) + .map_err(|err| err.to_string())?; + Ok(out.unwrap_or_else(|| code.to_owned())) +} + +fn format_markdown(code: &str) -> Result<String, String> { + let config = dprint_plugin_markdown::configuration::ConfigurationBuilder::new().build(); + let out = dprint_plugin_markdown::format_text(code, &config, |_, _, _| Ok(None)) + .map_err(|err| err.to_string())?; + Ok(out.unwrap_or_else(|| code.to_owned())) +} + +/// Taplo formats what it can and skips broken ranges, so the parse errors are checked first. +fn format_toml(code: &str) -> Result<String, String> { + match taplo::parser::parse(code).errors.first() { + Some(err) => Err(err.message.clone()), + None => Ok(taplo::formatter::format(code, Default::default())), + } +} + +fn format_sql(code: &str) -> String { + let options = sqlformat::FormatOptions { + indent: sqlformat::Indent::Spaces(2), + uppercase: Some(true), + ..Default::default() + }; + sqlformat::format(code, &sqlformat::QueryParams::None, &options) +} + +/// Adds or removes the final newline so it matches the input. +fn keep_trailing_newline(code: &str, mut out: String) -> String { + match (code.ends_with('\n'), out.ends_with('\n')) { + (true, false) => out.push('\n'), + (false, true) => { + out.pop(); + } + _ => {} + } + out +} + +#[cfg(test)] +mod tests { + use super::format; + + #[test] + fn rust_statement_snippet() { + assert_eq!( + format("rust", "let x=1;\nfoo(x);").unwrap(), + "let x = 1;\nfoo(x);" + ); + assert!(format("rust", "let = ;").is_err()); + } + + #[test] + fn json_keeps_key_order_and_missing_newline() { + let out = format("json", r#"{"b":1,"a":2}"#).unwrap(); + assert!(!out.ends_with('\n')); + assert!(out.find("\"b\"") < out.find("\"a\"")); + } + + #[test] + fn typescript_formats_and_rejects_garbage() { + let out = format("typescript", "const a:number=1").unwrap(); + assert!(out.contains("const a: number = 1"), "{out}"); + assert!(format("typescript", "const = ;").is_err()); + } +} diff --git a/src/hub.rs b/src/hub.rs index f92b121..dd7a963 100644 --- a/src/hub.rs +++ b/src/hub.rs @@ -7,24 +7,38 @@ //! - `0x02` UPDATE: payload is Loro update bytes. Imported, persisted and //! broadcast to the other connections when it changed the doc. //! - `0x03` EPHEMERAL: opaque bytes, broadcast only, never persisted. +//! - `0x04` RECORDING: UTF-8 `<session>\t<live|lost|ended>`. The state of a recording take, +//! sent when a connection joins and whenever it changes. Not an edit. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; +use std::io; +use std::path::Path; use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; -use loro::{ExportMode, Frontiers, LoroDoc, LoroList, LoroMap, VersionVector}; -use tokio::sync::{Mutex as AsyncMutex, broadcast}; +use bytes::Bytes; +use loro::{ExportMode, Frontiers, LoroDoc, VersionVector}; +use tokio::sync::{Mutex as AsyncMutex, broadcast, oneshot}; use topcoat::router::content::websocket::{Message, WebSocket}; use crate::export; +use crate::media::{parts_in, part_file}; use crate::store::{Store, now_millis}; pub const SYNC_REQ: u8 = 0x01; pub const UPDATE: u8 = 0x02; pub const EPHEMERAL: u8 = 0x03; +pub const RECORDING: u8 = 0x04; + +/// How long a lost take stays lost before it is reported ended. +const LOST_FOR: Duration = Duration::from_secs(30); const SNAPSHOT_EVERY: u64 = 50; +/// Bodies longer than this derive their text one at a time ([`HEAVY`]): each derivation +/// holds a few copies of the text, and a 100 MB note's snapshot and text flush overlap. +const HEAVY_BYTES: usize = 16 << 20; +static HEAVY: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(1); /// Least time between two versions recorded while the note is being edited. const VERSION_EVERY_MS: i64 = 10 * 60 * 1000; /// Quiet time after the last applied update before the searchable text is written. @@ -32,11 +46,71 @@ const TEXT_FLUSH_DELAY: Duration = Duration::from_secs(2); const CHANNEL_CAPACITY: usize = 256; /// A broadcast item: the connection id that sent it, and the full frame. -type Frame = (u64, Vec<u8>); +type Frame = (u64, Bytes); + +/// The state of a recording take, as the editor shows it. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum TakeState { + /// A socket is attached to a part of the take. + Live, + /// A socket died without `end` and nothing has come back yet. + Lost, + /// The take is over. Only sent, never kept. + Ended, +} + +impl TakeState { + fn as_str(self) -> &'static str { + match self { + TakeState::Live => "live", + TakeState::Lost => "lost", + TakeState::Ended => "ended", + } + } +} + +/// How a part's socket stopped: with `end`, or any other way. +#[derive(Clone, Copy)] +pub enum Detach { + Ended, + Lost, +} + +/// A socket's attachment to a part: what [`Hub::attach`] answers. +pub struct Attachment { + pub part: u32, + /// Tells this attachment from a later one on the same part. + pub token: u64, + /// Fires when another socket takes the part over. + pub stop: oneshot::Receiver<()>, +} + +/// A recording take in memory, keyed by its session id. +struct Take { + state: TakeState, + /// The part numbers a socket is attached to. + attached: HashMap<u32, Slot>, + /// Counts the changes, so a lost take's timer can tell it changed since. + version: u64, +} + +/// A socket attached to a part. +struct Slot { + token: u64, + stop: oneshot::Sender<()>, +} pub struct Hub { rooms: Mutex<HashMap<String, std::sync::Arc<Room>>>, next_conn: AtomicU64, + /// One lock per note whose doc is being built from imported markdown. + building: Mutex<HashMap<String, std::sync::Arc<AsyncMutex<()>>>>, + /// Woken when an import leaves a doc to build. + pending: tokio::sync::Notify, + /// One import at a time builds its doc before answering (see [`Hub::build_now`]). + inline: tokio::sync::Semaphore, + /// Recording takes by note, then by session id. Also locks the choice of a new part. + takes: Mutex<HashMap<String, HashMap<String, Take>>>, } impl Hub { @@ -44,9 +118,139 @@ impl Hub { Self { rooms: Mutex::new(HashMap::new()), next_conn: AtomicU64::new(1), + building: Mutex::new(HashMap::new()), + pending: tokio::sync::Notify::new(), + inline: tokio::sync::Semaphore::new(1), + takes: Mutex::new(HashMap::new()), } } + /// Wakes [`build_pending`](Self::build_pending) after an import stored markdown + /// without a doc. + pub fn doc_pending(&self) { + self.pending.notify_one(); + } + + /// Builds the doc of a just imported note before the import answers, so the note + /// opens without waiting for it. Only one import at a time does: the others, and + /// any build that fails, are left to [`build_pending`](Self::build_pending), which + /// keeps the memory of many big imports at once bounded. + pub async fn build_now(&self, store: &Store, note_id: &str) { + let Ok(_permit) = self.inline.try_acquire() else { return self.doc_pending() }; + if let Err(err) = self.ensure_doc(store, note_id, false).await { + eprintln!("building the doc of note {note_id} failed: {err:#}"); + self.doc_pending(); + } + } + + /// Builds the docs of imported notes in the background, one at a time. + pub async fn build_pending(&self, store: &Store) { + loop { + match store.pending_docs().await { + Ok(ids) => { + for id in ids { + if let Err(err) = self.ensure_doc(store, &id, true).await { + eprintln!("building the doc of note {id} failed: {err:#}"); + } + } + } + Err(err) => eprintln!("reading pending docs failed: {err:#}"), + } + self.pending.notified().await; + } + } + + /// Snapshots the notes whose updates outgrew their snapshot, which happens when the + /// server stops before a due snapshot is written. Until then every load of such a + /// note replays its updates, and an export renders it from scratch. + pub async fn compact_stale(&self, store: &Store) { + let ids = match store.stale_snapshots().await { + Ok(ids) => ids, + Err(err) => return eprintln!("finding stale snapshots failed: {err:#}"), + }; + for id in ids { + // An open room snapshots on its own. + if self.rooms.lock().unwrap().contains_key(&id) { + continue; + } + let result = async { + let upto_seq = store.max_seq(&id).await?; + let (doc, _, _, _) = load_doc(store, &id).await?; + let (data, (title, markdown, links), export) = tokio::task::spawn_blocking(move || -> anyhow::Result<_> { + Ok((doc.export(ExportMode::Snapshot)?, derived_text(&doc), export::to_markdown_deferred(&doc))) + }) + .await??; + if store.put_snapshot(&id, data, upto_seq, &markdown, &title).await? { + store.set_links(&id, &links).await?; + if let Some(export) = export { + store.put_export_texts(&[(id.clone(), upto_seq, export)]).await?; + } + } + anyhow::Ok(()) + } + .await; + if let Err(err) = result { + eprintln!("snapshot failed for note {id}: {err:#}"); + } + } + } + + /// Builds the note's doc from its imported markdown if that has not happened yet. + /// A big import stores only the markdown, since a doc of a million blocks takes + /// Loro some 15 s to build and snapshot. + /// + /// The background builder (`skip_busy`) leaves a note alone that is being built: + /// waiting on it would count as someone opening the note, and keep its doc in memory. + async fn ensure_doc(&self, store: &Store, note_id: &str, skip_busy: bool) -> anyhow::Result<()> { + let lock = { + let mut building = self.building.lock().unwrap(); + if skip_busy && building.contains_key(note_id) { + return Ok(()); + } + building.entry(note_id.to_owned()).or_default().clone() + }; + let mut guard = Some(lock.lock().await); + let result = async { + // A builder before us may have handed its doc to a room, still storing it. + if self.rooms.lock().unwrap().contains_key(note_id) { + return Ok(()); + } + let Some(markdown) = store.pending_markdown(note_id).await? else { return Ok(()) }; + let (doc, snapshot, title, body, links) = tokio::task::spawn_blocking(move || -> anyhow::Result<_> { + let doc = crate::import::markdown_to_doc(&markdown)?; + // The text read overlaps the export: together about 1 s sooner. + let (snapshot, (title, body, links)) = std::thread::scope(|s| { + let text = s.spawn(|| derived_text(&doc)); + (doc.export(ExportMode::Snapshot), text.join().unwrap()) + }); + Ok((doc, snapshot?, title, body, links)) + }) + .await??; + let body = std::sync::Arc::new(body); + // Someone waits to open the note: give them the doc now, not after the store + // takes its 100+ MB of text (a second for a huge note). Edits stored meanwhile + // land after the snapshot, which covers no updates (`upto_seq` 0). Nobody + // waiting, the doc is dropped, so a bulk import keeps no docs in memory. + if std::sync::Arc::strong_count(&lock) > 2 { + let markdown = links.is_empty().then(|| (doc.oplog_vv(), body.clone())); + let last_version = load_last_version(store, note_id).await?; + let room = std::sync::Arc::new(Room::new(note_id, doc, last_version, snapshot.len(), markdown, 0)); + self.rooms.lock().unwrap().entry(note_id.to_owned()).or_insert(room); + guard.take(); + } else { + drop(doc); + } + store.finish_pending(note_id, &snapshot, &title, &body, &links).await + } + .await; + drop(guard); + let mut building = self.building.lock().unwrap(); + if std::sync::Arc::strong_count(&lock) == 2 { + building.remove(note_id); + } + result + } + /// Returns the live room for `note_id`, loading it from the store on first use. /// Rooms are kept in memory after their last connection leaves, so a room is /// never orphaned while a connection still holds it. @@ -58,13 +262,22 @@ impl Hub { .get(note_id) .cloned(); if let Some(room) = existing { + *room.used.lock().unwrap() = std::time::Instant::now(); return Ok(room); } // Load without holding the map lock: this awaits the store. - let doc = load_doc(store, note_id).await?; + self.ensure_doc(store, note_id, false).await?; + if let Some(room) = self.rooms.lock().unwrap().get(note_id).cloned() { + return Ok(room); + } + let (doc, stored, markdown, updates) = load_doc(store, note_id).await?; + let markdown = match markdown { + Some(md) if !store.has_links(note_id).await? => Some((doc.oplog_vv(), std::sync::Arc::new(md))), + _ => None, + }; let last_version = load_last_version(store, note_id).await?; - let room = std::sync::Arc::new(Room::new(note_id, doc, last_version)); + let room = std::sync::Arc::new(Room::new(note_id, doc, last_version, stored, markdown, updates)); // Another task may have loaded the same note meanwhile; keep the first one. let mut rooms = self.rooms.lock().unwrap(); @@ -74,6 +287,24 @@ impl Hub { .clone()) } + /// Unloads rooms nobody has used for a while, so the docs of notes opened once do + /// not stay in memory for good. Only a room nothing else holds and with every update + /// stored goes: the next use loads the same doc from the store. + pub async fn evict_idle(&self) { + const IDLE: Duration = Duration::from_secs(5 * 60); + loop { + tokio::time::sleep(Duration::from_secs(30)).await; + self.rooms.lock().unwrap().retain(|_, room| { + let idle = room.used.lock().unwrap().elapsed() >= IDLE; + let held = std::sync::Arc::strong_count(room) > 1; + let writing = room.queued.load(Ordering::Acquire) > 0; + // A locked state is in use. + let quiet = room.state.try_lock().is_ok_and(|s| s.conns == 0 && !s.text_pending && s.last_update.elapsed() >= IDLE); + !(idle && !held && !writing && quiet) + }); + } + } + /// Drops the in-memory room for a deleted note. Connections still holding the /// room keep working until they leave; nothing new is loaded for this id. pub fn forget(&self, note_id: &str) { @@ -83,6 +314,133 @@ impl Hub { fn next_conn_id(&self) -> u64 { self.next_conn.fetch_add(1, Ordering::Relaxed) } + + /// Attaches a socket to a part of take `session` of `note`, and makes the take live. With + /// `part` None the socket gets a new part, created now, numbered after the take's last part. + /// With `part` given it gets that part, which must exist, and a socket already on it stops. + /// Answers `None` when that part does not exist. `dir` is the take's folder. + pub fn attach(&self, note: &str, session: &str, part: Option<u32>, dir: &Path) -> io::Result<Option<Attachment>> { + let mut takes = self.takes.lock().unwrap(); + let part = match part { + Some(part) if !part_file(dir, part).is_file() => return Ok(None), + Some(part) => part, + None => { + let part = parts_in(dir)?.last().map_or(0, |(n, _)| n + 1); + std::fs::OpenOptions::new().write(true).create_new(true).open(part_file(dir, part))?; + part + } + }; + let token = self.next_conn_id(); + let (stop, stopped) = oneshot::channel(); + let take = takes + .entry(note.to_owned()) + .or_default() + .entry(session.to_owned()) + .or_insert_with(|| Take { state: TakeState::Ended, attached: HashMap::new(), version: 0 }); + take.version += 1; + if let Some(old) = take.attached.insert(part, Slot { token, stop }) { + let _ = old.stop.send(()); + } + let changed = take.state != TakeState::Live; + take.state = TakeState::Live; + drop(takes); + if changed { + self.publish(note, session, TakeState::Live); + } + Ok(Some(Attachment { part, token, stop: stopped })) + } + + /// Detaches the socket `token` from `part` of a take. Once no part is attached the take is + /// ended by `end`, and lost otherwise: a lost take becomes ended after [`LOST_FOR`] unless it + /// changes first. A socket that was taken over no longer matches its token, so this does + /// nothing for it. + pub fn detach(self: &std::sync::Arc<Self>, note: &str, session: &str, part: u32, token: u64, how: Detach) { + let mut takes = self.takes.lock().unwrap(); + let Some(sessions) = takes.get_mut(note) else { return }; + let Some(take) = sessions.get_mut(session) else { return }; + if take.attached.get(&part).is_none_or(|slot| slot.token != token) { + return; + } + take.attached.remove(&part); + take.version += 1; + if !take.attached.is_empty() { + return; + } + let version = take.version; + match how { + Detach::Ended => { + sessions.remove(session); + if sessions.is_empty() { + takes.remove(note); + } + drop(takes); + self.publish(note, session, TakeState::Ended); + } + Detach::Lost => { + take.state = TakeState::Lost; + drop(takes); + self.publish(note, session, TakeState::Lost); + let hub = self.clone(); + let (note, session) = (note.to_owned(), session.to_owned()); + tokio::spawn(async move { + tokio::time::sleep(LOST_FOR).await; + hub.expire(¬e, &session, version); + }); + } + } + } + + /// Ends a lost take that has not changed since `version`. + fn expire(&self, note: &str, session: &str, version: u64) { + let mut takes = self.takes.lock().unwrap(); + let Some(sessions) = takes.get_mut(note) else { return }; + let due = sessions + .get(session) + .is_some_and(|take| take.state == TakeState::Lost && take.version == version); + if !due { + return; + } + sessions.remove(session); + if sessions.is_empty() { + takes.remove(note); + } + drop(takes); + self.publish(note, session, TakeState::Ended); + } + + /// The part numbers of `session` that a socket is attached to. + pub fn attached(&self, session: &str) -> HashSet<u32> { + let takes = self.takes.lock().unwrap(); + let note = session.split('.').next().unwrap_or_default(); + takes + .get(note) + .and_then(|sessions| sessions.get(session)) + .map(|take| take.attached.keys().copied().collect()) + .unwrap_or_default() + } + + /// A RECORDING frame for each take of `note` that is live or lost, sent to a connection that + /// just joined. + pub fn take_frames(&self, note: &str) -> Vec<Bytes> { + let takes = self.takes.lock().unwrap(); + takes + .get(note) + .map(|sessions| sessions.iter().map(|(session, take)| recording_frame(session, take.state)).collect()) + .unwrap_or_default() + } + + /// Sends a take's state to the note's room, if the room is loaded. Its connections forward it. + fn publish(&self, note: &str, session: &str, state: TakeState) { + let room = self.rooms.lock().unwrap().get(note).cloned(); + if let Some(room) = room { + room.broadcast(0, recording_frame(session, state)); + } + } +} + +/// A RECORDING frame: the take's session id and state. +fn recording_frame(session: &str, state: TakeState) -> Bytes { + Bytes::from(frame(RECORDING, format!("{session}\t{}", state.as_str()).as_bytes())) } impl Default for Hub { @@ -91,19 +449,11 @@ impl Default for Hub { } } -/// Update holding the root structure loro-prosemirror expects: a `doc` node with -/// one empty paragraph. Written once at note creation so clients never race to -/// initialise the root. +/// Update holding the body of a new note: one empty paragraph. Written once at note +/// creation so clients never race to initialise it. pub fn initial_note_update() -> anyhow::Result<Vec<u8>> { let doc = LoroDoc::new(); - let root = doc.get_map("doc"); - root.insert("nodeName", "doc")?; - root.insert_container("attributes", LoroMap::new())?; - let children = root.insert_container("children", LoroList::new())?; - let paragraph = children.push_container(LoroMap::new())?; - paragraph.insert("nodeName", "paragraph")?; - paragraph.insert_container("attributes", LoroMap::new())?; - paragraph.insert_container("children", LoroList::new())?; + note_model::flat::init(&doc)?; doc.commit(); Ok(doc.export(ExportMode::all_updates())?) } @@ -116,16 +466,28 @@ async fn load_last_version(store: &Store, note_id: &str) -> anyhow::Result<Optio } } -pub async fn load_doc(store: &Store, note_id: &str) -> anyhow::Result<LoroDoc> { +/// The note's doc, how many bytes it is stored in, its stored markdown when that is up +/// to date, and how many updates it has after its snapshot. +/// Runs whole-doc work (imports, exports, reads of a huge note take seconds) without +/// stalling the other tasks on this runtime thread, such as page requests. +fn blocking<T>(f: impl FnOnce() -> T) -> T { + tokio::task::block_in_place(f) +} + +pub async fn load_doc(store: &Store, note_id: &str) -> anyhow::Result<(LoroDoc, usize, Option<String>, u64)> { let bytes = store.load_doc(note_id).await?; let doc = LoroDoc::new(); + let mut stored = 0; if let Some(snapshot) = bytes.snapshot { - doc.import(&snapshot)?; + stored += snapshot.len(); + blocking(|| doc.import(&snapshot))?; } + let updates = bytes.updates.len() as u64; for update in bytes.updates { - doc.import(&update)?; + stored += update.len(); + blocking(|| doc.import(&update))?; } - Ok(doc) + Ok((doc, stored, bytes.markdown, updates)) } struct RoomState { @@ -133,20 +495,69 @@ struct RoomState { /// Live WebSocket connections on this room. conns: usize, updates_since_snapshot: u64, + /// Bytes of the updates since the last snapshot, and the size of that snapshot: a + /// snapshot costs time in proportion to the doc, so a huge doc takes one rarely. + update_bytes: usize, + snapshot_len: usize, + /// How long the last searchable-text read took, and when the last update came: the + /// read waits for a pause in typing that long, so a huge doc is not re-read over + /// and over while someone types. + text_cost: Duration, + last_update: std::time::Instant, /// A searchable-text flush is scheduled and has not read the doc yet. text_pending: bool, + /// A huge doc's snapshot waits for [`HEAVY`] and has not been taken yet. + snapshot_pending: bool, /// Time in millis and frontiers of the newest recorded version. last_version: Option<(i64, Frontiers)>, + /// The doc's markdown at a version, kept only while the doc has no note links: + /// then it is also the export, which a huge doc takes seconds to write. + markdown: Option<(VersionVector, std::sync::Arc<String>)>, +} + +impl RoomState { + /// Keeps `markdown`, read at `vv`, if the doc is still at that version. + fn cache_markdown(&mut self, vv: VersionVector, markdown: std::sync::Arc<String>, links: &[export::LinkTarget]) { + self.markdown = (links.is_empty() && vv == self.doc.oplog_vv()).then(|| (vv, markdown)); + } + + fn cached_markdown(&self) -> Option<std::sync::Arc<String>> { + let (vv, md) = self.markdown.as_ref()?; + (*vv == self.doc.oplog_vv()).then(|| md.clone()) + } +} + +/// A snapshot taken under the room lock, still to be stored with its derived text. +struct Snapshot { + data: Vec<u8>, + /// The doc's body at the snapshot, for its derived text. + body: export::Body, + vv: VersionVector, + upto_seq: i64, + heavy: bool, } pub struct Room { note_id: String, tx: broadcast::Sender<Frame>, state: AsyncMutex<RoomState>, + /// Client updates on their way to the store, in order (see `apply_update`). + writes: std::sync::OnceLock<tokio::sync::mpsc::UnboundedSender<Bytes>>, + /// How many of those are not stored yet. + queued: std::sync::Arc<std::sync::atomic::AtomicUsize>, + /// When the room was last handed out (see [`Hub::evict_idle`]). + used: Mutex<std::time::Instant>, } impl Room { - fn new(note_id: &str, doc: LoroDoc, last_version: Option<(i64, Frontiers)>) -> Self { + fn new( + note_id: &str, + doc: LoroDoc, + last_version: Option<(i64, Frontiers)>, + stored: usize, + markdown: Option<(VersionVector, std::sync::Arc<String>)>, + updates: u64, + ) -> Self { let (tx, _) = broadcast::channel(CHANNEL_CAPACITY); Self { note_id: note_id.to_owned(), @@ -154,10 +565,19 @@ impl Room { state: AsyncMutex::new(RoomState { doc, conns: 0, - updates_since_snapshot: 0, + updates_since_snapshot: updates, + update_bytes: 0, + snapshot_len: stored, + text_cost: Duration::ZERO, + last_update: std::time::Instant::now(), text_pending: false, + snapshot_pending: false, last_version, + markdown, }), + writes: std::sync::OnceLock::new(), + queued: Default::default(), + used: Mutex::new(std::time::Instant::now()), } } @@ -170,15 +590,16 @@ impl Room { } /// Records a version and persists a snapshot when the last connection leaves. - async fn leave(&self, store: &Store) { + async fn leave(self: &std::sync::Arc<Self>, store: &std::sync::Arc<Store>) { let mut state = self.state.lock().await; state.conns = state.conns.saturating_sub(1); if state.conns == 0 { if let Err(err) = record_version(&mut state, store, &self.note_id).await { eprintln!("version record failed for note {}: {err:#}", self.note_id); } - if let Err(err) = write_snapshot(&mut state, store, &self.note_id).await { - eprintln!("snapshot failed for note {}: {err:#}", self.note_id); + // A reload leaves and joins again: only new updates are worth a snapshot. + if state.updates_since_snapshot > 0 { + schedule_snapshot(self, &mut state, store).await; } } } @@ -193,25 +614,47 @@ impl Room { async fn sync_reply(&self, payload: &[u8]) -> anyhow::Result<Vec<u8>> { let state = self.state.lock().await; let vv = VersionVector::decode(payload)?; - let updates = state.doc.export(ExportMode::updates(&vv))?; + // A fresh peer gets a snapshot: it loads lazily instead of replaying every op. + let mode = if vv.is_empty() { ExportMode::Snapshot } else { ExportMode::updates(&vv) }; + let updates = blocking(|| state.doc.export(mode))?; Ok(frame(UPDATE, &updates)) } async fn all_updates_frame(&self) -> anyhow::Result<Vec<u8>> { let state = self.state.lock().await; - Ok(frame(UPDATE, &state.doc.export(ExportMode::all_updates())?)) + Ok(frame(UPDATE, &blocking(|| state.doc.export(ExportMode::all_updates()))?)) } /// Imports an UPDATE payload. Returns `true` when it changed the doc, in which - /// case the update has been persisted and should be broadcast. - async fn apply_update(self: &std::sync::Arc<Self>, store: &std::sync::Arc<Store>, payload: &[u8]) -> anyhow::Result<bool> { + /// case it should be broadcast. The store write is queued, not awaited: one write + /// of a huge note's text holds the store for seconds, and collaborators would see + /// every keystroke that much later. A snapshot only covers updates the doc has + /// already imported, and a client resends on reconnect what the server lacks, so + /// order and a write lost in a crash are both harmless. + async fn apply_update(self: &std::sync::Arc<Self>, store: &std::sync::Arc<Store>, payload: Bytes) -> anyhow::Result<bool> { let mut state = self.state.lock().await; let before = state.doc.oplog_vv(); - state.doc.import(payload)?; + blocking(|| state.doc.import(&payload))?; if state.doc.oplog_vv() == before { return Ok(false); } - persist_update(self, &mut state, store, payload).await?; + let writes = self.writes.get_or_init(|| { + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Bytes>(); + let (store, note_id, queued) = (store.clone(), self.note_id.clone(), self.queued.clone()); + tokio::spawn(async move { + while let Some(update) = rx.recv().await { + if let Err(err) = store.append_update(¬e_id, &update).await { + eprintln!("update write failed for note {note_id}: {err:#}"); + } + queued.fetch_sub(1, Ordering::Release); + } + }); + tx + }); + self.queued.fetch_add(1, Ordering::Acquire); + let len = payload.len(); + let _ = writes.send(payload); + count_update(self, &mut state, store, len).await?; Ok(true) } @@ -234,29 +677,56 @@ impl Room { if state.doc.oplog_vv() == vv_before { return Ok(()); } - let update = state.doc.export(ExportMode::updates(&vv_before))?; + let update = blocking(|| state.doc.export(ExportMode::updates(&vv_before)))?; persist_update(self, &mut state, store, &update).await?; // Connection 0 never exists, so every connection receives the restore. - self.broadcast(0, frame(UPDATE, &update)); + self.broadcast(0, frame(UPDATE, &update).into()); record_version(&mut state, store, &self.note_id).await } - fn broadcast(&self, conn_id: u64, frame: Vec<u8>) { + fn broadcast(&self, conn_id: u64, frame: Bytes) { // Err only means there are no receivers, which is fine. let _ = self.tx.send((conn_id, frame)); } /// Live markdown of the in-memory doc, with note links written as `[[Title]]`. - /// `titles` maps note ids to their titles. - pub async fn markdown_with(&self, titles: HashMap<String, String>) -> String { + pub async fn markdown_with(&self, store: &Store) -> anyhow::Result<String> { + let body = { + let state = self.state.lock().await; + if let Some(md) = state.cached_markdown() { + return Ok(md.to_string()); + } + blocking(|| export::Body::read(&state.doc)) + }; + let ids: Vec<String> = body + .note_links() + .into_iter() + .filter_map(|t| match t { + export::LinkTarget::Id(id) => Some(id), + export::LinkTarget::Title(_) => None, + }) + .collect(); + let titles = store.titles_of(ids).await?; + Ok(tokio::task::spawn_blocking(move || body.markdown_with(&|id| titles.get(id).cloned())).await?) + } + + pub async fn html(&self) -> anyhow::Result<String> { + self.read(|body| body.html()).await + } + + /// Runs a whole-document read on a blocking thread. Only reading the body holds the + /// room (one pass over the text, ~50 ms for 100 MB): rendering it does not. + async fn read<T: Send + 'static>(&self, f: impl FnOnce(&export::Body) -> T + Send + 'static) -> anyhow::Result<T> { let state = self.state.lock().await; - let resolve = |id: &str| titles.get(id).cloned(); - export::to_markdown_with(&state.doc, &resolve) + let body = blocking(|| export::Body::read(&state.doc)); + drop(state); + Ok(tokio::task::spawn_blocking(move || f(&body)).await?) } - pub async fn html(&self) -> String { + /// The editor's markup for the doc, shown until the editor takes over. + pub async fn editor_html(&self) -> String { let state = self.state.lock().await; - export::to_html(&state.doc) + note_model::render::preview_html(&state.doc, 128, 100_000) } } @@ -269,9 +739,17 @@ async fn persist_update( payload: &[u8], ) -> anyhow::Result<()> { store.append_update(&room.note_id, payload).await?; + count_update(room, state, store, payload.len()).await +} + +/// Counts a stored or queued update towards the next snapshot, and schedules the +/// searchable-text flush. +async fn count_update(room: &std::sync::Arc<Room>, state: &mut RoomState, store: &std::sync::Arc<Store>, len: usize) -> anyhow::Result<()> { state.updates_since_snapshot += 1; - if state.updates_since_snapshot >= SNAPSHOT_EVERY { - write_snapshot(state, store, &room.note_id).await?; + state.update_bytes += len; + state.last_update = std::time::Instant::now(); + if state.updates_since_snapshot >= SNAPSHOT_EVERY && state.update_bytes * 16 >= state.snapshot_len { + schedule_snapshot(room, state, store).await; } if !state.text_pending { state.text_pending = true; @@ -297,9 +775,25 @@ async fn record_version(state: &mut RoomState, store: &Store, note_id: &str) -> /// cleared before the doc is read, so an update that arrives during the write /// schedules a new flush. A version is recorded when the last one is 10 minutes old. async fn flush_text(room: std::sync::Arc<Room>, store: std::sync::Arc<Store>) { - tokio::time::sleep(TEXT_FLUSH_DELAY).await; + let mut permit = None; let (title, body, links) = { - let mut state = room.state.lock().await; + let mut state = loop { + let state = room.state.lock().await; + let quiet = TEXT_FLUSH_DELAY.max(state.text_cost * 2); + let idle = state.last_update.elapsed(); + if idle >= quiet { + break state; + } + drop(state); + tokio::time::sleep(quiet - idle).await; + }; + // A huge body waits its turn, then reads the doc as it is by then. + if note_model::flat::body(&state.doc).len_utf8() > HEAVY_BYTES { + drop(state); + permit = Some(HEAVY.acquire().await.expect("never closed")); + state = room.state.lock().await; + } + let started = std::time::Instant::now(); state.text_pending = false; let due = state .last_version @@ -310,11 +804,35 @@ async fn flush_text(room: std::sync::Arc<Room>, store: std::sync::Arc<Store>) { eprintln!("version record failed for note {}: {err:#}", room.note_id); } } - ( - export::title(&state.doc), - export::to_markdown(&state.doc), - export::note_links(&state.doc), - ) + // A snapshot just rendered this version: only the title is left to read. + if let Some(markdown) = state.cached_markdown() { + let title = export::title_of(&state.doc); + state.text_cost = started.elapsed(); + drop(state); + (title, markdown, Vec::new()) + } else { + let body = blocking(|| export::Body::read(&state.doc)); + let vv = state.doc.oplog_vv(); + drop(state); + let read = tokio::task::spawn_blocking(move || { + let (title, markdown, links) = derived_body(&body); + (title, std::sync::Arc::new(markdown), links) + }) + .await; + let mut state = room.state.lock().await; + state.text_cost = started.elapsed(); + if let Ok((_, body, links)) = &read { + state.cache_markdown(vv, body.clone(), links); + } + drop(state); + match read { + Ok(out) => out, + Err(err) => { + eprintln!("text read failed for note {}: {err:#}", room.note_id); + return; + } + } + } }; if let Err(err) = store.set_title(&room.note_id, &title).await { eprintln!("title write failed for note {}: {err:#}", room.note_id); @@ -325,24 +843,101 @@ async fn flush_text(room: std::sync::Arc<Room>, store: std::sync::Arc<Store>) { if let Err(err) = store.set_links(&room.note_id, &links).await { eprintln!("link index write failed for note {}: {err:#}", room.note_id); } + drop(permit); } -async fn write_snapshot( - state: &mut RoomState, - store: &Store, - note_id: &str, -) -> anyhow::Result<()> { - let snapshot = state.doc.export(ExportMode::Snapshot)?; - let markdown = export::to_markdown(&state.doc); - let title = export::title(&state.doc); - store - .put_snapshot(note_id, &snapshot, &markdown, &title) - .await?; - store - .set_links(note_id, &export::note_links(&state.doc)) - .await?; +/// The title, searchable markdown and note links of a doc: three whole-doc reads. +fn derived_text(doc: &LoroDoc) -> (String, String, Vec<export::LinkTarget>) { + derived_body(&export::Body::read(doc)) +} + +fn derived_body(body: &export::Body) -> (String, String, Vec<export::LinkTarget>) { + (body.title(), body.markdown(), body.note_links()) +} + +/// Takes a snapshot now, or for a huge doc once [`HEAVY`] is free: its snapshot and +/// body would otherwise wait in memory beside the text flush that holds it. +async fn schedule_snapshot(room: &std::sync::Arc<Room>, state: &mut RoomState, store: &std::sync::Arc<Store>) { + if note_model::flat::body(&state.doc).len_utf8() > HEAVY_BYTES { + if !state.snapshot_pending { + state.snapshot_pending = true; + tokio::spawn(heavy_snapshot(room.clone(), store.clone())); + } + return; + } + match take_snapshot(state, store, &room.note_id).await { + Ok(snapshot) => { + tokio::spawn(write_snapshot(room.clone(), store.clone(), snapshot, None)); + } + Err(err) => eprintln!("snapshot failed for note {}: {err:#}", room.note_id), + } +} + +async fn heavy_snapshot(room: std::sync::Arc<Room>, store: std::sync::Arc<Store>) { + let permit = HEAVY.acquire().await.expect("never closed"); + let snapshot = { + let mut state = room.state.lock().await; + state.snapshot_pending = false; + if state.updates_since_snapshot == 0 { + return; + } + match take_snapshot(&mut state, &store, &room.note_id).await { + Ok(snapshot) => snapshot, + Err(err) => return eprintln!("snapshot failed for note {}: {err:#}", room.note_id), + } + }; + write_snapshot(room, store, snapshot, Some(permit)).await; +} + +/// Takes a snapshot of the doc and reads its body; [`write_snapshot`] renders the +/// derived text off the room lock. The update count is read under the lock too, so the snapshot +/// claims only updates it holds. +async fn take_snapshot(state: &mut RoomState, store: &Store, note_id: &str) -> anyhow::Result<Snapshot> { + let upto_seq = store.max_seq(note_id).await?; + let data = blocking(|| state.doc.export(ExportMode::Snapshot))?; state.updates_since_snapshot = 0; - Ok(()) + state.update_bytes = 0; + state.snapshot_len = data.len(); + let heavy = note_model::flat::body(&state.doc).len_utf8() > HEAVY_BYTES; + let body = blocking(|| export::Body::read(&state.doc)); + Ok(Snapshot { data, body, vv: state.doc.oplog_vv(), upto_seq, heavy }) +} + +/// Stores a snapshot from [`take_snapshot`] with its markdown, title and links. +async fn write_snapshot( + room: std::sync::Arc<Room>, + store: std::sync::Arc<Store>, + snapshot: Snapshot, + permit: Option<tokio::sync::SemaphorePermit<'static>>, +) { + let result = async { + let Snapshot { data, body, vv, upto_seq, heavy } = snapshot; + let permit = match permit { + None if heavy => Some(HEAVY.acquire().await?), + permit => permit, + }; + let ((title, markdown, links), export) = + tokio::task::spawn_blocking(move || { + let derived = derived_body(&body); + // Without note links the export is the markdown itself. + let export = if derived.2.is_empty() { None } else { body.markdown_deferred() }; + (derived, export) + }) + .await?; + if store.put_snapshot(&room.note_id, data, upto_seq, &markdown, &title).await? { + store.set_links(&room.note_id, &links).await?; + if let Some(export) = export { + store.put_export_texts(&[(room.note_id.clone(), upto_seq, export)]).await?; + } + } + room.state.lock().await.cache_markdown(vv, std::sync::Arc::new(markdown), &links); + drop(permit); + anyhow::Ok(()) + } + .await; + if let Err(err) = result { + eprintln!("snapshot failed for note {}: {err:#}", room.note_id); + } } fn frame(tag: u8, payload: &[u8]) -> Vec<u8> { @@ -365,6 +960,13 @@ pub async fn serve_socket(hub: std::sync::Arc<Hub>, store: std::sync::Arc<Store> room.leave(&store).await; return; } + // The takes of the note, so the editor shows them from the start. + for frame in hub.take_frames(&room.note_id) { + if socket.send(Message::binary(frame)).await.is_err() { + room.leave(&store).await; + return; + } + } loop { tokio::select! { @@ -375,7 +977,7 @@ pub async fn serve_socket(hub: std::sync::Arc<Hub>, store: std::sync::Arc<Store> }; match message { Message::Binary(bytes) => { - if !handle_frame(&room, &store, conn_id, &bytes, &mut socket).await { + if !handle_frame(&room, &store, conn_id, bytes, &mut socket).await { break; } } @@ -410,14 +1012,17 @@ async fn handle_frame( room: &std::sync::Arc<Room>, store: &std::sync::Arc<Store>, conn_id: u64, - bytes: &[u8], + bytes: Bytes, socket: &mut WebSocket, ) -> bool { - let Some((&tag, payload)) = bytes.split_first() else { + let Some(&tag) = bytes.first() else { return true; }; + // The frame's payload, sharing its buffer: a huge update is neither copied for the + // store write nor for the other connections, which get the frame as it came. + let payload = bytes.slice(1..); match tag { - SYNC_REQ => match room.sync_reply(payload).await { + SYNC_REQ => match room.sync_reply(&payload).await { Ok(reply) => socket.send(Message::binary(reply)).await.is_ok(), Err(err) => { eprintln!("bad sync request on note {}: {err:#}", room.note_id); @@ -426,16 +1031,17 @@ async fn handle_frame( }, UPDATE => { match room.apply_update(store, payload).await { - Ok(true) => room.broadcast(conn_id, frame(UPDATE, payload)), + Ok(true) => room.broadcast(conn_id, bytes), Ok(false) => {} Err(err) => eprintln!("bad update on note {}: {err:#}", room.note_id), } true } EPHEMERAL => { - room.broadcast(conn_id, frame(EPHEMERAL, payload)); + room.broadcast(conn_id, bytes); true } _ => true, } } + diff --git a/src/i18n.rs b/src/i18n.rs index dc94564..0655679 100644 --- a/src/i18n.rs +++ b/src/i18n.rs @@ -91,8 +91,13 @@ pub enum Msg { GroupPrevious7, GroupEarlier, BackToList, + /// Link under a list that has more rows than are shown. + ShowMore, MoveToNotebook, AlreadyHere, + FindNotebook, + NotebookByName, + NoSuchNotebook, ExportAs, ExportMarkdown, ExportHtml, @@ -129,6 +134,8 @@ pub enum Msg { RegexSearch, InvalidRegex, InvalidRegexHint, + SearchPartial, + SearchAll, CheckSpelling, NoteActions, VersionHistory, @@ -151,6 +158,71 @@ pub enum Msg { LinkedFrom, NoNoteNamed, CreateNote, + + // Editor + EditorPlaceholder, + EditorToolbarLabel, + EditorBubbleLabel, + EditorBlockMenu, + EditorNoMatches, + EditorNavigate, + EditorInsert, + EditorClose, + EditorUnavailable, + EditorUndo, + EditorRedo, + EditorParagraph, + EditorHeading1, + EditorHeading2, + EditorHeading3, + EditorBold, + EditorItalic, + EditorInlineCode, + EditorLink, + EditorBulletList, + EditorNumberedList, + EditorQuote, + EditorCodeBlock, + EditorDivider, + EditorText, + EditorLinkDialog, + EditorLinkMenu, + EditorLinkUrl, + EditorLinkInvalid, + EditorLinkNeedsLink, + EditorApply, + EditorRemove, + EditorOpen, + EditorEdit, + EditorStatusSaved, + EditorStatusSaving, + EditorStatusLocal, + EditorStatusReconnecting, + EditorStatusConnecting, + EditorAnnounceOffline, + EditorAnnounceOnline, + EditorPasteAsText, + EditorNoteMenu, + EditorCreateNote, + EditorNoNotesFound, + EditorUntitled, + EditorCodeLanguage, + EditorCodeAuto, + EditorCodeFormat, + EditorCodeFormatting, + EditorCodeFormatFailed, + EditorCodeFormatUnsupported, + EditorCodeCopy, + EditorCodeCopied, + EditorCodeAutoFormat, + EditorAttach, + EditorRecordAudio, + EditorStopRecording, + EditorMediaFailed, + EditorMicDenied, + EditorRecordingNow, + EditorRecordingLost, + EditorContinueRecording, } /// The text of `msg` in `lang`. @@ -203,8 +275,12 @@ pub fn t(lang: Lang, msg: Msg) -> &'static str { Msg::GroupPrevious7 => ("Previous 7 days", "Önceki 7 gün"), Msg::GroupEarlier => ("Earlier", "Daha önce"), Msg::BackToList => ("Back to list", "Listeye dön"), + Msg::ShowMore => ("Show more", "Daha fazla göster"), Msg::MoveToNotebook => ("Move to notebook", "Defterine taşı"), Msg::AlreadyHere => ("Already in this notebook.", "Zaten bu defterde."), + Msg::FindNotebook => ("Find a notebook…", "Defter bul…"), + Msg::NotebookByName => ("Notebook name", "Defter adı"), + Msg::NoSuchNotebook => ("No notebook has that name.", "Bu adda defter yok."), Msg::ExportAs => ("Export as", "Şu biçimde dışa aktar"), Msg::ExportMarkdown => ("Markdown (.md)", "Markdown (.md)"), Msg::ExportHtml => ("HTML (.html)", "HTML (.html)"), @@ -244,6 +320,8 @@ pub fn t(lang: Lang, msg: Msg) -> &'static str { Msg::RegexSearch => ("Regular expression", "Düzenli ifade"), Msg::InvalidRegex => ("Not a valid regular expression.", "Geçerli bir düzenli ifade değil."), Msg::InvalidRegexHint => ("Check the brackets and escapes.", "Parantezleri ve kaçış karakterlerini kontrol edin."), + Msg::SearchPartial => ("Some long notes were not searched yet.", "Bazı uzun notlarda henüz aranmadı."), + Msg::SearchAll => ("Search all", "Tümünde ara"), Msg::CheckSpelling => ( "Check the spelling or try fewer words.", "Yazımı kontrol edin ya da daha az kelime deneyin.", @@ -278,6 +356,76 @@ pub fn t(lang: Lang, msg: Msg) -> &'static str { Msg::RestoreVersion => ("Restore this version", "Bu sürümü geri yükle"), Msg::BackToNote => ("Back to note", "Nota dön"), Msg::ToastVersionRestored => ("Version restored.", "Sürüm geri yüklendi."), + // Editor + Msg::EditorPlaceholder => ("Start writing…", "Yazmaya başla…"), + Msg::EditorToolbarLabel => ("Formatting", "Biçimlendirme"), + Msg::EditorBubbleLabel => ("Text formatting", "Metin biçimlendirme"), + Msg::EditorBlockMenu => ("Insert block", "Blok ekle"), + Msg::EditorNoMatches => ("No matches", "Eşleşme yok"), + Msg::EditorNavigate => ("navigate", "gezin"), + Msg::EditorInsert => ("insert", "ekle"), + Msg::EditorClose => ("close", "kapat"), + Msg::EditorUnavailable => ("Not available here", "Bu alanda kullanılamaz"), + Msg::EditorUndo => ("Undo", "Geri al"), + Msg::EditorRedo => ("Redo", "Yinele"), + Msg::EditorParagraph => ("Paragraph", "Metin"), + Msg::EditorHeading1 => ("Heading 1", "Başlık 1"), + Msg::EditorHeading2 => ("Heading 2", "Başlık 2"), + Msg::EditorHeading3 => ("Heading 3", "Başlık 3"), + Msg::EditorBold => ("Bold", "Kalın"), + Msg::EditorItalic => ("Italic", "İtalik"), + Msg::EditorInlineCode => ("Inline code", "Kod"), + Msg::EditorLink => ("Link", "Bağlantı"), + Msg::EditorBulletList => ("Bullet list", "Madde listesi"), + Msg::EditorNumberedList => ("Numbered list", "Numaralı liste"), + Msg::EditorQuote => ("Quote", "Alıntı"), + Msg::EditorCodeBlock => ("Code block", "Kod bloğu"), + Msg::EditorDivider => ("Divider", "Ayırıcı"), + Msg::EditorText => ("Text", "Metin"), + Msg::EditorLinkDialog => ("Link", "Bağlantı"), + Msg::EditorLinkMenu => ("Link options", "Bağlantı seçenekleri"), + Msg::EditorLinkUrl => ("Link URL", "Bağlantı adresi"), + Msg::EditorLinkInvalid => ( + "Enter a valid link, such as example.com", + "Geçerli bir bağlantı girin, ör. example.com", + ), + Msg::EditorLinkNeedsLink => ("Add a link first", "Önce bir bağlantı ekleyin"), + Msg::EditorApply => ("Apply", "Uygula"), + Msg::EditorRemove => ("Remove", "Kaldır"), + Msg::EditorOpen => ("Open", "Aç"), + Msg::EditorEdit => ("Edit", "Düzenle"), + Msg::EditorStatusSaved => ("Saved", "Kaydedildi"), + Msg::EditorStatusSaving => ("Saving…", "Kaydediliyor…"), + Msg::EditorStatusLocal => ("Saved on this device", "Bu cihazda kaydedildi"), + Msg::EditorStatusReconnecting => ("Reconnecting…", "Yeniden bağlanıyor…"), + Msg::EditorStatusConnecting => ("Connecting…", "Bağlanıyor…"), + Msg::EditorAnnounceOffline => ( + "You are offline. Changes stay on this device.", + "Çevrimdışısınız. Değişiklikler bu cihazda kalır.", + ), + Msg::EditorAnnounceOnline => ("Back online.", "Yeniden çevrimiçisiniz."), + Msg::EditorPasteAsText => ("Paste as plain text", "Düz metin olarak yapıştır"), + Msg::EditorNoteMenu => ("Link to a note", "Nota bağlantısı"), + Msg::EditorCreateNote => ("Create note “{q}”", "“{q}” notunu oluştur"), + Msg::EditorNoNotesFound => ("No notes found", "Not bulunamadı"), + Msg::EditorUntitled => ("Untitled", "Adsız"), + Msg::EditorCodeLanguage => ("Language", "Dil"), + Msg::EditorCodeAuto => ("Auto", "Otomatik"), + Msg::EditorCodeFormat => ("Format", "Biçimlendir"), + Msg::EditorCodeFormatting => ("Formatting…", "Biçimlendiriliyor…"), + Msg::EditorCodeFormatFailed => ("Couldn't format", "Biçimlendirilemedi"), + Msg::EditorCodeFormatUnsupported => ("Formatting isn't available for this language", "Bu dil için biçimlendirme yok"), + Msg::EditorCodeCopy => ("Copy code", "Kodu kopyala"), + Msg::EditorCodeCopied => ("Copied", "Kopyalandı"), + Msg::EditorCodeAutoFormat => ("Format when leaving the block", "Bloktan çıkınca biçimlendir"), + Msg::EditorAttach => ("Attach file", "Dosya ekle"), + Msg::EditorRecordAudio => ("Record audio", "Ses kaydet"), + Msg::EditorStopRecording => ("Stop recording", "Kaydı durdur"), + Msg::EditorMediaFailed => ("Upload failed", "Yükleme başarısız"), + Msg::EditorMicDenied => ("Microphone unavailable", "Mikrofon kullanılamıyor"), + Msg::EditorRecordingNow => ("Recording…", "Kaydediliyor…"), + Msg::EditorRecordingLost => ("Connection lost, reconnecting…", "Bağlantı koptu, yeniden bağlanılıyor…"), + Msg::EditorContinueRecording => ("Continue recording", "Kayda devam et"), }; match lang { Lang::En => en, @@ -285,6 +433,73 @@ pub fn t(lang: Lang, msg: Msg) -> &'static str { } } +/// The editor's UI strings, keyed by their original `web/src/i18n.ts` key, in that file's order. +pub const EDITOR_MSGS: &[(&str, Msg)] = &[ + ("placeholder", Msg::EditorPlaceholder), + ("toolbarLabel", Msg::EditorToolbarLabel), + ("bubbleLabel", Msg::EditorBubbleLabel), + ("blockMenu", Msg::EditorBlockMenu), + ("noMatches", Msg::EditorNoMatches), + ("navigate", Msg::EditorNavigate), + ("insert", Msg::EditorInsert), + ("close", Msg::EditorClose), + ("unavailable", Msg::EditorUnavailable), + ("undo", Msg::EditorUndo), + ("redo", Msg::EditorRedo), + ("paragraph", Msg::EditorParagraph), + ("heading1", Msg::EditorHeading1), + ("heading2", Msg::EditorHeading2), + ("heading3", Msg::EditorHeading3), + ("bold", Msg::EditorBold), + ("italic", Msg::EditorItalic), + ("inlineCode", Msg::EditorInlineCode), + ("link", Msg::EditorLink), + ("bulletList", Msg::EditorBulletList), + ("numberedList", Msg::EditorNumberedList), + ("quote", Msg::EditorQuote), + ("codeBlock", Msg::EditorCodeBlock), + ("divider", Msg::EditorDivider), + ("text", Msg::EditorText), + ("linkDialog", Msg::EditorLinkDialog), + ("linkMenu", Msg::EditorLinkMenu), + ("linkUrl", Msg::EditorLinkUrl), + ("linkInvalid", Msg::EditorLinkInvalid), + ("linkNeedsLink", Msg::EditorLinkNeedsLink), + ("apply", Msg::EditorApply), + ("remove", Msg::EditorRemove), + ("open", Msg::EditorOpen), + ("edit", Msg::EditorEdit), + ("statusSaved", Msg::EditorStatusSaved), + ("statusSaving", Msg::EditorStatusSaving), + ("statusLocal", Msg::EditorStatusLocal), + ("statusReconnecting", Msg::EditorStatusReconnecting), + ("statusConnecting", Msg::EditorStatusConnecting), + ("announceOffline", Msg::EditorAnnounceOffline), + ("announceOnline", Msg::EditorAnnounceOnline), + ("pasteAsText", Msg::EditorPasteAsText), + ("noteMenu", Msg::EditorNoteMenu), + ("createNote", Msg::EditorCreateNote), + ("noNotesFound", Msg::EditorNoNotesFound), + ("untitled", Msg::EditorUntitled), + ("codeLanguage", Msg::EditorCodeLanguage), + ("codeAuto", Msg::EditorCodeAuto), + ("codeFormat", Msg::EditorCodeFormat), + ("codeFormatting", Msg::EditorCodeFormatting), + ("codeFormatFailed", Msg::EditorCodeFormatFailed), + ("codeFormatUnsupported", Msg::EditorCodeFormatUnsupported), + ("codeCopy", Msg::EditorCodeCopy), + ("codeCopied", Msg::EditorCodeCopied), + ("codeAutoFormat", Msg::EditorCodeAutoFormat), + ("attach", Msg::EditorAttach), + ("recordAudio", Msg::EditorRecordAudio), + ("stopRecording", Msg::EditorStopRecording), + ("mediaFailed", Msg::EditorMediaFailed), + ("micDenied", Msg::EditorMicDenied), + ("recordingNow", Msg::EditorRecordingNow), + ("recordingLost", Msg::EditorRecordingLost), + ("continueRecording", Msg::EditorContinueRecording), +]; + /// "1 note" / "3 notes". Turkish does not inflect the noun after a number: "1 not", "3 not". pub fn notes_count(lang: Lang, n: usize) -> String { match lang { @@ -412,3 +627,31 @@ pub fn lang_cookie(lang: Lang) -> Cookie<'static> { .max_age(Duration::days(LANG_COOKIE_DAYS)) .build() } + +/// The editor's strings as a JSON object, safe inside `<script type="application/json">`. +pub fn editor_strings_json(lang: Lang) -> String { + let mut out = String::from("{"); + for (i, (key, msg)) in EDITOR_MSGS.iter().enumerate() { + if i > 0 { + out.push(','); + } + for (j, s) in [*key, t(lang, *msg)].iter().enumerate() { + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '<' => out.push_str("\\u003c"), + '\n' => out.push_str("\\n"), + c => out.push(c), + } + } + out.push('"'); + if j == 0 { + out.push(':'); + } + } + } + out.push('}'); + out +} diff --git a/src/import.rs b/src/import.rs index 6121990..c7a7eac 100644 --- a/src/import.rs +++ b/src/import.rs @@ -1,5 +1,5 @@ //! Markdown import: the inverse of `export.rs`. Parses CommonMark into a -//! loro-prosemirror shaped LoroDoc (same layout as `export::to_markdown` reads). +//! note doc (`note_model::flat`, the layout `export::to_markdown` reads). //! //! Degradations (GFM bits that the schema cannot represent): //! - strikethrough: content kept, no mark @@ -9,30 +9,65 @@ //! - footnotes: not enabled, so `[^x]` stays literal text //! - soft breaks become a space, hard breaks become `hard_break` nodes //! - wiki links `[[Title]]`, `[[Title|text]]`, `[[Title#heading]]` in plain text become -//! links to `/notes/by-title/<Title>`; embeds `![[...]]` stay plain text +//! links to `/notes/by-title/<Title>` +//! - local media references (links, images, `![[file]]` embeds) become `/media/...` URLs +//! when the file was imported with the note (`rewrite_media`); other embeds `![[...]]` +//! stay plain text use std::collections::HashMap; +use std::ops::Range; use anyhow::Result; -use loro::{ - ExpandType, ExportMode, LoroDoc, LoroList, LoroMap, LoroResult, LoroText, LoroValue, - StyleConfig, StyleConfigMap, -}; -use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag}; +use loro::{ExportMode, LoroDoc}; +use note_model::links::{percent_decode, percent_encode}; +use note_model::marks::Marks; +use note_model::render::embed_of; +use note_model::schema::text_style_config; +use note_model::flat; +use note_model::write::{Block, Inline}; +use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, LinkType, Options, Parser, Tag, TagEnd}; /// Parses markdown into a fresh LoroDoc with the note layout. pub fn markdown_to_doc(md: &str) -> Result<LoroDoc> { let body = strip_front_matter(md); - let mut options = Options::empty(); - options.insert(Options::ENABLE_STRIKETHROUGH); - options.insert(Options::ENABLE_TABLES); - options.insert(Options::ENABLE_TASKLISTS); - let events: Vec<Event> = Parser::new_ext(body, options).collect(); + let events: Vec<Event> = Parser::new_ext(body, options()).collect(); let mut pos = 0; let blocks = parse_blocks(&events, &mut pos, false); build(&blocks) } +/// The editor's preview markup for the start of a markdown file. +pub fn preview_markdown(md: &str) -> String { + match markdown_to_doc(md) { + Ok(doc) => note_model::render::preview_html(&doc, 128, 100_000), + Err(_) => String::new(), + } +} + +/// Whether the markdown's first block is a heading. Only that block is parsed. +pub fn starts_with_heading(md: &str) -> bool { + matches!(Parser::new_ext(strip_front_matter(md), options()).next(), Some(Event::Start(Tag::Heading { .. }))) +} + +/// The title a doc built from `md` gets, when `md` starts with a heading: the +/// heading's plain text. Only that block is parsed. +pub fn heading_title(md: &str) -> String { + let mut raw = String::new(); + for event in Parser::new_ext(strip_front_matter(md), options()) { + match event { + Event::End(TagEnd::Heading(_)) => break, + Event::Text(t) | Event::Code(t) => raw.push_str(&t), + Event::SoftBreak | Event::HardBreak => raw.push(' '), + _ => {} + } + } + note_model::tree::title_from(&raw) +} + +fn options() -> Options { + Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TABLES | Options::ENABLE_TASKLISTS +} + /// Same as `markdown_to_doc`, exported as a full Loro update. pub fn markdown_to_update(md: &str) -> Result<Vec<u8>> { let doc = markdown_to_doc(md)?; @@ -48,12 +83,12 @@ fn note_file_href(dest: &str) -> String { let Some(stem) = path.strip_suffix(".md").filter(|_| relative) else { return dest.to_string(); }; - let decoded = crate::export::percent_decode(stem); + let decoded = percent_decode(stem); let title = decoded.rsplit('/').next().unwrap_or(&decoded).trim(); if title.is_empty() { return dest.to_string(); } - format!("/notes/by-title/{}", crate::export::percent_encode(title)) + format!("/notes/by-title/{}", percent_encode(title)) } /// Drops a leading `---` ... `---` YAML block. Unclosed blocks are kept as text. @@ -75,42 +110,183 @@ pub fn strip_front_matter(md: &str) -> &str { md } -// --------------------------------------------------------------------------- -// Intermediate tree -// --------------------------------------------------------------------------- +/// Rewrites local media references in markdown to their `/media/` URLs. `media` maps a +/// file path relative to the imported root to its URL, and `note_path` is the markdown +/// file's own path relative to that root. Inline links and images with a local destination +/// are rewritten; Obsidian embeds `![[target]]` and `![[target|alias]]` outside code become +/// an image (or a link, for files that cannot be embedded). Anything that does not resolve +/// is left as written. +pub fn rewrite_media(md: &str, note_path: &str, media: &HashMap<String, String>) -> String { + if media.is_empty() { + return md.to_string(); + } + let note_dir = note_path.rsplit_once('/').map_or("", |(dir, _)| dir); + // Lowercase basename to its URL, or None when several files share it. + let mut by_name: HashMap<String, Option<&String>> = HashMap::new(); + for (path, url) in media { + let name = path.rsplit('/').next().unwrap_or_default().to_ascii_lowercase(); + by_name.entry(name).and_modify(|slot| *slot = None).or_insert(Some(url)); + } + + let mut code: Vec<Range<usize>> = Vec::new(); + let mut edits: Vec<(Range<usize>, String)> = Vec::new(); + for (event, range) in Parser::new_ext(md, options()).into_offset_iter() { + match event { + Event::Start(Tag::CodeBlock(_)) | Event::Code(_) => code.push(range), + Event::Start(Tag::Image { link_type: LinkType::Inline, dest_url, .. }) => { + let Some(url) = resolve_media(&dest_url, note_dir, media, &by_name) else { + continue; + }; + edits.extend(dest_edit(md, &range, &dest_url, url)); + if embed_of(url).is_none() && md[range.start..].starts_with('!') { + edits.push((range.start..range.start + 1, String::new())); + } + } + Event::Start(Tag::Link { link_type: LinkType::Inline, dest_url, .. }) => { + if let Some(url) = resolve_media(&dest_url, note_dir, media, &by_name) { + edits.extend(dest_edit(md, &range, &dest_url, url)); + } + } + _ => {} + } + } -#[derive(Clone, Default, PartialEq)] -struct Marks { - strong: bool, - em: bool, - code: bool, - link: Option<(String, Option<String>)>, + // Embeds never contain `[`, `]` or a newline, so one scan per `![[` is enough. + let mut at = 0; + while let Some(found) = md[at..].find("![[") { + let open = at + found; + let inner_start = open + 3; + if in_ranges(&code, open) { + at = inner_start; + continue; + } + let rest = &md[inner_start..]; + let stop = rest.find(['[', ']', '\n']).unwrap_or(rest.len()); + if !rest[stop..].starts_with("]]") { + at = inner_start; + continue; + } + let inner = &rest[..stop]; + let end = inner_start + stop + 2; + at = end; + let (target, alias) = match inner.split_once('|') { + Some((target, alias)) => (target, Some(alias.trim())), + None => (inner, None), + }; + let Some(url) = resolve_media(target, note_dir, media, &by_name) else { + continue; + }; + let file = target.split('#').next().unwrap_or_default().trim().rsplit('/').next().unwrap_or_default(); + let embeddable = embed_of(url).is_some(); + let stem = file + .rsplit_once('.') + .filter(|(stem, _)| !stem.is_empty()) + .map_or(file, |(stem, _)| stem); + let shown = match alias { + Some(alias) if !alias.is_empty() => alias, + _ if embeddable => stem, + _ => file, + }; + let replacement = if embeddable { + format!("![{shown}]({url})") + } else { + format!("[{shown}]({url})") + }; + edits.push((open..end, replacement)); + } + + if edits.is_empty() { + return md.to_string(); + } + edits.sort_by_key(|(range, _)| range.start); + let mut out = String::with_capacity(md.len()); + let mut last = 0; + for (range, text) in edits { + if range.start < last { + continue; + } + out.push_str(&md[last..range.start]); + out.push_str(&text); + last = range.end; + } + out.push_str(&md[last..]); + out } -#[derive(Clone)] -enum Inline { - Text(String, Marks), - HardBreak, - Image { - src: String, - alt: String, - title: Option<String>, - }, +/// Finds a link destination inside its event's source and pairs it with the new URL. +/// The `<...>` brackets go with it when present. None when the destination is not found +/// literally in the source. +fn dest_edit(md: &str, range: &Range<usize>, dest: &str, url: &str) -> Option<(Range<usize>, String)> { + if dest.is_empty() { + return None; + } + let at = range.start + md[range.clone()].rfind(dest)?; + let end = at + dest.len(); + let angled = at > range.start && md.as_bytes()[at - 1] == b'<' && md.as_bytes().get(end) == Some(&b'>'); + if angled { + Some((at - 1..end + 1, format!("<{url}>"))) + } else { + Some((at..end, url.to_owned())) + } +} + +/// Whether `at` falls inside one of the sorted, disjoint ranges. +fn in_ranges(ranges: &[Range<usize>], at: usize) -> bool { + let after = ranges.partition_point(|r| r.start <= at); + after > 0 && ranges[after - 1].end > at } -enum Block { - Paragraph(Vec<Inline>), - Heading(i64, Vec<Inline>), - Quote(Vec<Block>), - Code { lang: Option<String>, text: String }, - Rule, - List { - ordered: bool, - start: i64, - items: Vec<Vec<Block>>, - }, +/// The `/media/` URL of a local reference, or None. Remote, data, mailto, fragment-only, +/// already-rewritten and markdown note targets are not media. +fn resolve_media<'a>( + target: &str, + note_dir: &str, + media: &'a HashMap<String, String>, + by_name: &HashMap<String, Option<&'a String>>, +) -> Option<&'a str> { + let target = target.trim(); + if target.is_empty() + || target.contains("://") + || target.starts_with("mailto:") + || target.starts_with("data:") + || target.starts_with('#') + || target.starts_with("/media/") + { + return None; + } + let path = percent_decode(target.split(['#', '?']).next().unwrap_or_default()); + if path.is_empty() || path.to_ascii_lowercase().ends_with(".md") { + return None; + } + let joined = normalize(&format!("{note_dir}/{path}")); + let rooted = normalize(&path); + let name = path.rsplit('/').next().unwrap_or_default().to_ascii_lowercase(); + media + .get(&joined) + .or_else(|| media.get(&rooted)) + .map(String::as_str) + .or_else(|| by_name.get(&name).copied().flatten().map(String::as_str)) } +/// Joins `.` and `..` segments of a forward-slash path. Empty segments are dropped. +fn normalize(path: &str) -> String { + let mut parts: Vec<&str> = Vec::new(); + for part in path.split('/') { + match part { + "" | "." => {} + ".." => { + parts.pop(); + } + _ => parts.push(part), + } + } + parts.join("/") +} + +// --------------------------------------------------------------------------- +// Intermediate tree +// --------------------------------------------------------------------------- + // --------------------------------------------------------------------------- // Event -> tree // --------------------------------------------------------------------------- @@ -450,141 +626,38 @@ fn heading_level(level: HeadingLevel) -> i64 { /// yields a single empty paragraph. fn build(blocks: &[Block]) -> Result<LoroDoc> { let doc = LoroDoc::new(); - - // Same expand rules as loro-prosemirror's getLoroTextStyle. - let mut styles = StyleConfigMap::new(); - styles.insert( - "strong".into(), - StyleConfig::new().expand(ExpandType::After), - ); - styles.insert("em".into(), StyleConfig::new().expand(ExpandType::After)); - styles.insert("code".into(), StyleConfig::new().expand(ExpandType::After)); - styles.insert("link".into(), StyleConfig::new().expand(ExpandType::None)); - doc.config_text_style(styles); - - let root = doc.get_map("doc"); - root.insert("nodeName", "doc")?; - root.insert_container("attributes", LoroMap::new())?; - let children = root.insert_container("children", LoroList::new())?; + doc.set_peer_id(note_model::write::BUILDER_PEER)?; + doc.config_text_style(text_style_config()); if blocks.is_empty() { - push_node(&children, "paragraph", Vec::new())?; + flat::init(&doc)?; } else { - for block in blocks { - write_block(&children, block)?; - } + flat::write(&flat::body(&doc), 0, &flat::flatten(&wikify_blocks(blocks)), false)?; } doc.commit(); Ok(doc) } -/// Appends a node to `list` and returns its `children` list. Null attributes -/// are not written. -fn push_node(list: &LoroList, name: &str, attrs: Vec<(&str, LoroValue)>) -> LoroResult<LoroList> { - let node = list.push_container(LoroMap::new())?; - node.insert("nodeName", name)?; - let attributes = node.insert_container("attributes", LoroMap::new())?; - for (key, value) in attrs { - attributes.insert(key, value)?; - } - node.insert_container("children", LoroList::new()) +/// Applies `wikilinks` to every paragraph and heading in the tree. +fn wikify_blocks(blocks: &[Block]) -> Vec<Block> { + blocks.iter().map(wikify_block).collect() } -fn write_block(list: &LoroList, block: &Block) -> LoroResult<()> { +fn wikify_block(block: &Block) -> Block { match block { - Block::Paragraph(inl) => { - let children = push_node(list, "paragraph", Vec::new())?; - write_inlines(&children, inl)?; - } - Block::Heading(level, inl) => { - let children = push_node(list, "heading", vec![("level", (*level).into())])?; - write_inlines(&children, inl)?; - } - Block::Quote(blocks) => { - let children = push_node(list, "blockquote", Vec::new())?; - for b in blocks { - write_block(&children, b)?; - } - } - Block::Code { lang, text } => { - let attrs: Vec<(&str, LoroValue)> = lang - .iter() - .map(|l| ("language", LoroValue::from(l.as_str()))) - .collect(); - let children = push_node(list, "code_block", attrs)?; - if !text.is_empty() { - let t = children.push_container(LoroText::new())?; - t.insert(0, text)?; - } - } - Block::Rule => { - push_node(list, "horizontal_rule", Vec::new())?; - } + Block::Paragraph(inl) => Block::Paragraph(wikilinks(inl)), + Block::Heading(level, inl) => Block::Heading(*level, wikilinks(inl)), + Block::Quote(blocks) => Block::Quote(wikify_blocks(blocks)), Block::List { ordered, start, items, - } => { - let children = if *ordered { - push_node(list, "ordered_list", vec![("order", (*start).into())])? - } else { - push_node(list, "bullet_list", Vec::new())? - }; - for item in items { - let item_children = push_node(&children, "list_item", Vec::new())?; - for b in item { - write_block(&item_children, b)?; - } - } - } + } => Block::List { + ordered: *ordered, + start: *start, + items: items.iter().map(|item| wikify_blocks(item)).collect(), + }, + other => other.clone(), } - Ok(()) -} - -/// Consecutive text runs share one LoroText; inline nodes get their own child. -fn write_inlines(list: &LoroList, inl: &[Inline]) -> LoroResult<()> { - let owned = wikilinks(inl); - let inl = owned.as_slice(); - let mut i = 0; - while let Some(item) = inl.get(i) { - match item { - Inline::Text(..) => { - let mut j = i; - let mut full = String::new(); - let mut spans: Vec<(std::ops::Range<usize>, Marks)> = Vec::new(); - while let Some(Inline::Text(s, m)) = inl.get(j) { - let start = full.chars().count(); - full.push_str(s); - let end = full.chars().count(); - if end > start { - spans.push((start..end, m.clone())); - } - j += 1; - } - if !full.is_empty() { - let text = list.push_container(LoroText::new())?; - text.insert(0, &full)?; - for (range, marks) in spans { - apply_marks(&text, range, &marks)?; - } - } - i = j; - } - Inline::HardBreak => { - push_node(list, "hard_break", Vec::new())?; - i += 1; - } - Inline::Image { src, alt, title } => { - let mut attrs: Vec<(&str, LoroValue)> = - vec![("src", LoroValue::from(src.as_str())), ("alt", LoroValue::from(alt.as_str()))]; - if let Some(t) = title { - attrs.push(("title", LoroValue::from(t.as_str()))); - } - push_node(list, "image", attrs)?; - i += 1; - } - } - } - Ok(()) } /// Turns `[[Title]]`, `[[Title|text]]` and `[[Title#heading]]` in plain text into links @@ -627,7 +700,7 @@ fn split_wikilinks(s: &str, marks: &Marks, out: &mut Vec<Inline>) { match parsed { Some((close, (target, text))) if !embed => { push_text(out, &rest[..open], marks); - let href = format!("/notes/by-title/{}", crate::export::percent_encode(&target)); + let href = format!("/notes/by-title/{}", percent_encode(&target)); let link = Marks { link: Some((href, None)), ..marks.clone() @@ -671,33 +744,6 @@ fn wikilink_parts(inner: &str) -> Option<(String, String)> { Some((target.to_owned(), text.to_owned())) } -fn apply_marks(text: &LoroText, range: std::ops::Range<usize>, marks: &Marks) -> LoroResult<()> { - if marks.strong { - text.mark(range.clone(), "strong", empty_map())?; - } - if marks.em { - text.mark(range.clone(), "em", empty_map())?; - } - if marks.code { - text.mark(range.clone(), "code", empty_map())?; - } - if let Some((href, title)) = &marks.link { - let mut map: HashMap<String, LoroValue> = HashMap::new(); - map.insert("href".to_owned(), LoroValue::from(href.as_str())); - let title_value = match title { - Some(t) => LoroValue::from(t.as_str()), - None => LoroValue::Null, - }; - map.insert("title".to_owned(), title_value); - text.mark(range, "link", LoroValue::from(map))?; - } - Ok(()) -} - -fn empty_map() -> LoroValue { - LoroValue::from(HashMap::<String, LoroValue>::new()) -} - #[cfg(test)] mod tests { use super::*; @@ -739,5 +785,73 @@ line two let wiki = "See **[[Alpha]]**, [**Be**ta](My%20Beta.md) and [[Gamma|g]].\n"; let doc = markdown_to_doc(wiki).unwrap(); assert_eq!(crate::export::to_markdown_with(&doc, &|_| None), wiki); + + // Links by id filled in later read the same as when resolved at once. + let ids = "See [x](/notes/abc), **[y](/notes/def)**, [*m*ix](/notes/abc) and [[Alpha]].\n"; + let doc = markdown_to_doc(ids).unwrap(); + let titles = |id: &str| (id == "abc").then(|| "Abc Note".to_owned()); + let deferred = crate::export::to_markdown_deferred(&doc).unwrap(); + assert_eq!(crate::export::resolve_deferred(&deferred, &titles), crate::export::to_markdown_with(&doc, &titles)); + } + + const LAYOUT_SAMPLE: &str = "# Heading\n\ +\n\ +Some **bold**, *italic*, `code` and [link](https://example.com).\n\ +\n\ +- Bullet one\n - Nested bullet\n- Bullet two\n\ +\n\ +3. Third\n4. Fourth\n\ +\n\ +> Quoted\n\ +\n\ +```rust\nfn main() {}\n```\n\ +\n\ +---\n\ +\n\ +line one\\\nline two\n"; + + /// Output of the markdown export before the note-model refactor. + const LAYOUT_EXPECTED: &str = "# Heading\n\nSome **bold**, *italic*, `code` and [link](https://example.com).\n\n- Bullet one\n - Nested bullet\n- Bullet two\n\n3. Third\n4. Fourth\n\n> Quoted\n\n```rust\nfn main() {}\n```\n\n---\n\nline one\\\nline two\n"; + + #[test] + fn layout_sample_is_stable() { + let doc = markdown_to_doc(LAYOUT_SAMPLE).unwrap(); + assert_eq!(crate::export::to_markdown(&doc), LAYOUT_EXPECTED); + } + + #[test] + fn media_relative_with_parent_dirs() { + let media = HashMap::from([ + ("notes/attachments/cat.png".to_owned(), "/media/a1.png".to_owned()), + ("notes/doc.pdf".to_owned(), "/media/b2.pdf".to_owned()), + ]); + let md = "![cat](../attachments/cat.png) and [doc](../doc.pdf)\n"; + assert_eq!( + rewrite_media(md, "notes/day/note.md", &media), + "![cat](/media/a1.png) and [doc](/media/b2.pdf)\n" + ); + } + + #[test] + fn media_percent_encoded_and_basename() { + let media = HashMap::from([("photos/My Cat.png".to_owned(), "/media/c3.png".to_owned())]); + let md = "![cat](My%20Cat.png) and ![[my cat.png|kitty]]\n"; + assert_eq!( + rewrite_media(md, "note.md", &media), + "![cat](/media/c3.png) and ![kitty](/media/c3.png)\n" + ); + } + + #[test] + fn media_embeds_skipped_inside_code() { + let media = HashMap::from([("x.png".to_owned(), "/media/d4.png".to_owned())]); + let md = "```\n![[x.png|alias]]\n```\n\n`![[x.png|alias]]`\n\n![[x.png|alias]]\n"; + assert_eq!( + rewrite_media(md, "n.md", &media), + "```\n![[x.png|alias]]\n```\n\n`![[x.png|alias]]`\n\n![alias](/media/d4.png)\n" + ); } } + + + diff --git a/src/main.rs b/src/main.rs index d110f01..bd64c1e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,12 +1,16 @@ mod app; mod components; mod export; +mod format; mod hub; mod i18n; mod matcher; mod import; +mod media; mod scheme; mod store; +mod zipout; +mod editor_assets; use std::sync::Arc; use std::time::Duration; @@ -40,7 +44,16 @@ async fn main() -> anyhow::Result<()> { let db_path = std::env::var("NOTE_DB").unwrap_or_else(|_| "notes.db".to_owned()); let store = Arc::new(store::Store::open(&db_path).await?); let hub = Arc::new(hub::Hub::new()); + let media = Arc::new(media::Media::open()?); spawn_trash_purge(store.clone(), hub.clone()); - topcoat::start(app::router(store, hub)).await?; + let fresh = store.clone(); + tokio::spawn(async move { fresh.keep_directory_fresh().await }); + let (builder, builder_store) = (hub.clone(), store.clone()); + tokio::spawn(async move { builder.build_pending(&builder_store).await }); + let (compacter, compacter_store) = (hub.clone(), store.clone()); + tokio::spawn(async move { compacter.compact_stale(&compacter_store).await }); + let evicter = hub.clone(); + tokio::spawn(async move { evicter.evict_idle().await }); + topcoat::start(app::router(store, hub, media)).await?; Ok(()) } diff --git a/src/matcher.rs b/src/matcher.rs index be10cd3..63dc750 100644 --- a/src/matcher.rs +++ b/src/matcher.rs @@ -35,15 +35,85 @@ impl Options { } /// A compiled query. +#[derive(Clone)] pub enum Matcher { Terms { terms: Vec<Vec<char>>, opts: Options }, Regex(Regex), } +/// Where a word a match needs lies in a word of the text: see [`Matcher::required_words`]. +#[derive(Clone, Copy)] +pub enum Part { + Whole, + /// The text's word ends with it. + End, + /// The text's word starts with it. + Start, + Inside, +} + +impl Part { + /// Whether `word` of a text can hold `piece` this way. + pub fn holds(self, word: &[char], piece: &[char]) -> bool { + match self { + Part::Whole => word == piece, + Part::End => word.ends_with(piece), + Part::Start => word.starts_with(piece), + Part::Inside => word.windows(piece.len()).any(|w| w == piece), + } + } +} + /// The query is not a valid regular expression. #[derive(Debug)] pub struct InvalidRegex; +/// Whether every match of `hir` is a run of ASCII letters and digits or decimal digits +/// (so, inside one word), with assertions that hold at least as often at a word's edges. +fn within_word(hir: ®ex_syntax::hir::Hir) -> bool { + use regex_syntax::hir::{Class, HirKind, Look}; + let alnum = |c: u32| char::from_u32(c).is_some_and(|c| c.is_ascii_alphanumeric()); + match hir.kind() { + HirKind::Empty => true, + HirKind::Literal(lit) => lit.0.iter().all(|&b| alnum(b.into())), + HirKind::Class(Class::Unicode(class)) => { + class.ranges().iter().all(|r| (r.start()..=r.end()).all(|c| alnum(c.into()))) + || class.ranges().iter().all(|r| (r.start()..=r.end()).all(|c| c.is_numeric() && c.is_alphanumeric())) + } + HirKind::Class(Class::Bytes(_)) => false, + HirKind::Look(look) => !matches!(look, Look::WordAsciiNegate | Look::WordUnicodeNegate), + HirKind::Repetition(rep) => within_word(&rep.sub), + HirKind::Capture(cap) => within_word(&cap.sub), + HirKind::Concat(hs) | HirKind::Alternation(hs) => hs.iter().all(within_word), + } +} + +/// The words of `piece`, a run of text: those at its edges may run on in the text. None +/// when it holds no word. +fn piece_words(piece: &[char]) -> Option<Vec<(Vec<char>, Part)>> { + let piece: Vec<char> = piece.iter().map(|&c| match_fold(c)).collect(); + let mut words = Vec::new(); + let mut i = 0; + while i < piece.len() { + if !piece[i].is_alphanumeric() { + i += 1; + continue; + } + let start = i; + while i < piece.len() && piece[i].is_alphanumeric() { + i += 1; + } + let part = match (start == 0, i == piece.len()) { + (true, true) => Part::Inside, + (true, false) => Part::End, + (false, true) => Part::Start, + (false, false) => Part::Whole, + }; + words.push((piece[start..i].to_vec(), part)); + } + (!words.is_empty()).then_some(words) +} + impl Matcher { /// None when the query holds nothing to search for. pub fn new(query: &str, opts: Options) -> Result<Option<Self>, InvalidRegex> { @@ -82,6 +152,50 @@ impl Matcher { Ok((!terms.is_empty()).then_some(Self::Terms { terms, opts })) } + /// The words a text must hold to match, folded like [`fold_word`], with where each + /// lies in a word of the text: any one of the alternatives, each word of it. For an + /// exact phrase its words; for a regex those of the literals every match starts + /// with. None when nothing is required. + pub fn required_words(&self) -> Option<Vec<Vec<(Vec<char>, Part)>>> { + match self { + Self::Terms { terms, opts } if opts.exact => Some(vec![piece_words(terms.first()?)?]), + Self::Terms { .. } => None, + Self::Regex(re) => { + use regex_syntax::hir::literal::{ExtractKind, Extractor}; + let hir = regex_syntax::parse(re.as_str()).ok()?; + let seq = Extractor::new().kind(ExtractKind::Prefix).extract(&hir); + seq.literals()? + .iter() + .map(|lit| { + // Folding only agrees with the regex's own case rules on ASCII. + let text = std::str::from_utf8(lit.as_bytes()).ok().filter(|t| t.is_ascii())?; + piece_words(&text.chars().collect::<Vec<_>>()) + }) + .collect() + } + } + } + + /// For a regex whose every match lies inside one word as [`words`] splits text: the + /// regex to try on folded words. A text can only match if one of its words matches it. + pub fn word_regex(&self) -> Option<Regex> { + let Self::Regex(re) = self else { return None }; + let hir = regex_syntax::parse(re.as_str()).ok()?; + if !within_word(&hir) { + return None; + } + // Folding lowercases, and maps a few letters to plain ones that are still letters. + RegexBuilder::new(re.as_str()).case_insensitive(true).size_limit(1 << 20).build().ok() + } + + /// The options of a term query, None for a regex. + pub fn options(&self) -> Option<Options> { + match self { + Self::Terms { opts, .. } => Some(*opts), + Self::Regex(_) => None, + } + } + /// The default matcher for `query`, as the palette and `[[` use it. pub fn simple(query: &str) -> Option<Self> { Self::new(query, Options::default()).ok().flatten() @@ -95,16 +209,28 @@ impl Matcher { let hay = fold_text(text, *opts); terms .iter() - .map(|t| occurrences(&hay, t, *opts).into_iter().map(|o| o.2).min()) + .map(|t| cheapest(&hay, t, *opts)) .collect() } Self::Regex(re) => vec![re.find_iter(text).any(|m| !m.is_empty()).then_some(0)], } } - /// The summed cost of every term in `text`, or None if some term doesn't occur. - pub fn cost(&self, text: &str) -> Option<usize> { - self.term_costs(text).into_iter().sum() + /// The terms, when every match lies inside one word as [`words`] splits text, so + /// the query can be matched word by word: not for case, phrase or regex searches. + pub fn word_terms(&self) -> Option<&[Vec<char>]> { + match self { + Self::Terms { terms, opts } if !opts.case && !opts.exact => Some(terms), + _ => None, + } + } + + /// The cheapest match of `term` (one of [`word_terms`](Self::word_terms)) inside + /// one folded `word`. The cheapest match of a term in a text is the cheapest in + /// any of its words. + pub fn word_cost(&self, term: &[char], word: &[char]) -> Option<usize> { + let Self::Terms { opts, .. } = self else { return None }; + cheapest(word, term, *opts) } /// Char ranges `(start, end)` of the matches in `text`, merged and sorted. @@ -120,10 +246,11 @@ impl Matcher { } Self::Regex(re) => { // Byte offsets to char indices. - let mut ranges = Vec::new(); + let (mut ranges, mut byte, mut char) = (Vec::new(), 0, 0); for m in re.find_iter(text).filter(|m| !m.is_empty()) { - let start = text[..m.start()].chars().count(); - ranges.push((start, start + m.as_str().chars().count())); + char += text[byte..m.start()].chars().count(); + byte = m.start(); + ranges.push((char, char + m.as_str().chars().count())); } ranges } @@ -142,6 +269,9 @@ impl Matcher { /// Lowercase form of one char. fn fold(c: char) -> char { + if c.is_ascii() { + return c.to_ascii_lowercase(); + } c.to_lowercase().next().unwrap_or(c) } @@ -164,6 +294,17 @@ pub fn title_fold(title: &str) -> String { title.chars().map(match_fold).collect() } +/// The words of `text` as [`Matcher::word_cost`] takes them: runs of letters and +/// digits, folded like the default search folds them. +pub fn words(text: &str) -> impl Iterator<Item = &str> { + text.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()) +} + +/// One word folded for [`Matcher::word_cost`]. +pub fn fold_word(word: &str) -> Box<[char]> { + word.chars().map(match_fold).collect() +} + fn fold_text(text: &str, opts: Options) -> Vec<char> { if opts.case { text.chars().collect() @@ -189,33 +330,56 @@ fn max_typos(len: usize) -> usize { /// substitutions and swapped neighbours). The `usize` is the match's cost: 0 exact at a /// word start, 1 exact inside a word, 1 + typos otherwise. fn occurrences(hay: &[char], term: &[char], opts: Options) -> Vec<(usize, usize, usize)> { + let mut found = Vec::new(); + each_occurrence(hay, term, opts, |o| { + found.push(o); + true + }); + found +} + +/// The cheapest of [`occurrences`], without collecting them: 0 ends the search. +fn cheapest(hay: &[char], term: &[char], opts: Options) -> Option<usize> { + let mut best: Option<usize> = None; + each_occurrence(hay, term, opts, |(_, _, cost)| { + best = Some(best.map_or(cost, |b| b.min(cost))); + cost > 0 + }); + best +} + +/// Calls `f` with each of [`occurrences`] until it returns false. +fn each_occurrence(hay: &[char], term: &[char], opts: Options, mut f: impl FnMut((usize, usize, usize)) -> bool) { let n = term.len(); if n == 0 { - return Vec::new(); + return; } let word_start = |i: usize| i == 0 || !hay[i - 1].is_alphanumeric(); let word_end = |i: usize| i == hay.len() || !hay[i].is_alphanumeric(); - let mut found = Vec::new(); + let mut any = false; if n <= hay.len() { for start in 0..=hay.len() - n { let end = start + n; - if hay[start..end] != term[..] { + if hay[start] != term[0] || hay[start..end] != term[..] { continue; } if opts.word && !(word_start(start) && word_end(end)) { continue; } - found.push((start, end, usize::from(!word_start(start)))); + any = true; + if !f((start, end, usize::from(!word_start(start)))) { + return; + } } } - if !found.is_empty() || !opts.typos() { - return found; + if any || !opts.typos() { + return; } let d = max_typos(n); // Short words only forgive swapped neighbours: "mlik" finds "milk". let swap_only = d == 0; if swap_only && n < 3 { - return found; + return; } let mut i = 0; while i < hay.len() { @@ -236,15 +400,41 @@ fn occurrences(hay: &[char], term: &[char], opts: Options) -> Vec<(usize, usize, && term[k] != term[k - 1] && (0..n).all(|x| x == k || x == k - 1 || word[x] == term[x]) }); - if swapped { - found.push((i, i + n, 2)); + if swapped && !f((i, i + n, 2)) { + return; } - } else if let Some((typos, len)) = prefix_distance(term, &hay[i..end.min(i + n + d)], d) { - found.push((i, i + len, 1 + typos)); + } else if let Some((typos, len)) = + Some(&hay[i..end.min(i + n + d)]).filter(|w| shares_enough(term, w, d)).and_then(|w| prefix_distance(term, w, d)) + && !f((i, i + len, 1 + typos)) + { + return; } i = end; } - found +} + +/// Whether `word` could be within `max` edits of `term` (or have a prefix that is): an +/// edit removes at most one char the two have in common, so more than `max` chars of +/// `term` missing from `word` rule it out. Far cheaper than [`prefix_distance`], which +/// almost every word of a search fails. +fn shares_enough(term: &[char], word: &[char], max: usize) -> bool { + if word.len() > 64 { + return true; + } + let mut used = 0u64; + let mut missing = 0; + for &c in term { + match (0..word.len()).find(|&j| used & (1 << j) == 0 && word[j] == c) { + Some(j) => used |= 1 << j, + None => { + missing += 1; + if missing > max { + return false; + } + } + } + } + true } /// The fewest edits turning `term` into some prefix of `word`, and that prefix's length, @@ -254,25 +444,27 @@ fn prefix_distance(term: &[char], word: &[char], max: usize) -> Option<(usize, u if m + max < n { return None; } - let mut d = vec![vec![0usize; m + 1]; n + 1]; - for (i, row) in d.iter_mut().enumerate() { - row[0] = i; + // One flat table, row `i` at `i * w`. + let w = m + 1; + let mut d = vec![0usize; (n + 1) * w]; + for i in 0..=n { + d[i * w] = i; } for j in 0..=m { - d[0][j] = j; + d[j] = j; } for i in 1..=n { for j in 1..=m { let cost = usize::from(term[i - 1] != word[j - 1]); - let mut v = (d[i - 1][j] + 1).min(d[i][j - 1] + 1).min(d[i - 1][j - 1] + cost); + let mut v = (d[(i - 1) * w + j] + 1).min(d[i * w + j - 1] + 1).min(d[(i - 1) * w + j - 1] + cost); if i > 1 && j > 1 && term[i - 1] == word[j - 2] && term[i - 2] == word[j - 1] { - v = v.min(d[i - 2][j - 2] + 1); + v = v.min(d[(i - 2) * w + j - 2] + 1); } - d[i][j] = v; + d[i * w + j] = v; } } (n.saturating_sub(max).max(1)..=m) - .map(|j| (d[n][j], j)) + .map(|j| (d[n * w + j], j)) .min_by_key(|&(dist, j)| (dist, j.abs_diff(n))) .filter(|&(dist, _)| dist <= max) } @@ -282,7 +474,7 @@ mod tests { use super::*; fn cost(text: &str, q: &str, opts: Options) -> Option<usize> { - Matcher::new(q, opts).unwrap().unwrap().cost(text) + Matcher::new(q, opts).unwrap().unwrap().term_costs(text).into_iter().sum() } #[test] @@ -314,7 +506,40 @@ mod tests { assert_eq!(cost("Groceries", "grcoeries", exact), None); // no typos assert_eq!(cost("order #42", r"#\d+", regex), Some(0)); assert!(Matcher::new("(", regex).is_err()); + let within = |q: &str| Matcher::new(q, regex).unwrap().unwrap().word_regex().is_some(); + assert!(within(r"\d{9}") && within(r"\bv9[0-9]+") && within("ab|cd")); + assert!(!within(r"\w+") && !within("a b") && !within(r"a\B") && !within("é")); let m = Matcher::new("ş", Options::default()).unwrap().unwrap(); assert_eq!(m.ranges("Işık"), vec![(1, 2)]); } } + +#[cfg(test)] +mod word_tests { + use super::*; + + #[test] + fn word_costs_equal_text_costs() { + let texts = [ + "Işık İzmir'de, milk and honey; asdadasxd foo_bar x2y alpha42 gamma-ray", + "Paragraph 12 with some ordinary words in it. note_12() -> usize", + "", + ]; + let queries = ["isik", "izmr", "mlik", "dadas", "alpha42", "gama", "bar", "ordinery wrds", "12", "ray gamma x2"]; + for opts in [Options::default(), Options { word: true, ..Options::default() }] { + for q in queries { + let m = Matcher::new(q, opts).unwrap().unwrap(); + for text in texts { + let words: Vec<Box<[char]>> = words(text).map(fold_word).collect(); + let by_word: Vec<Option<usize>> = m + .word_terms() + .unwrap() + .iter() + .map(|t| words.iter().filter_map(|w| m.word_cost(t, w)).min()) + .collect(); + assert_eq!(by_word, m.term_costs(text), "{q:?} in {text:?} with {opts:?}"); + } + } + } + } +} diff --git a/src/media.rs b/src/media.rs new file mode 100644 index 0000000..9df2514 --- /dev/null +++ b/src/media.rs @@ -0,0 +1,321 @@ +//! Raw-filesystem media store. Uploads are streamed to `<dir>/tmp`, hashed with blake3 as +//! they arrive, then renamed to `<dir>/files/<hash>.<ext>`. Files are served by name, so a +//! file's name is its content and a copy with the same bytes is stored once. + +pub mod webm; + +use std::collections::HashSet; +use std::fmt::Display; +use std::io; +use std::path::{Path, PathBuf}; +use std::pin::Pin; + +use bytes::Bytes; +use tokio::io::AsyncWriteExt; + +/// Largest upload taken, and largest recording take, in bytes. +pub const MAX_BYTES: u64 = 4 << 30; + +/// Stores media files under one directory. Recording takes live under `rec`, see [`Media::joined_take`]. +#[derive(Debug)] +pub struct Media { + dir: PathBuf, + /// Serialises joins, so two of one take never write the same file. + joins: tokio::sync::Mutex<()>, +} + +/// Why an upload was not stored. +#[derive(Debug)] +pub enum StoreError { + /// The body is bigger than [`MAX_BYTES`]. + TooLarge, + /// Reading the body or writing the file failed. + Failed(anyhow::Error), +} + +impl Media { + /// Opens the store at `$NOTE_MEDIA`, or `media` when that is unset, creating its folders. + pub fn open() -> io::Result<Self> { + let dir = PathBuf::from(std::env::var("NOTE_MEDIA").unwrap_or_else(|_| "media".to_owned())); + std::fs::create_dir_all(dir.join("files"))?; + std::fs::create_dir_all(dir.join("tmp"))?; + std::fs::create_dir_all(dir.join("rec"))?; + Ok(Self { dir, joins: tokio::sync::Mutex::new(()) }) + } + + /// Creates a new take of `note` and answers its id. Its folder is `rec/<id>`. + pub async fn new_take(&self, note: &str) -> io::Result<String> { + let id = session_id(note); + tokio::fs::create_dir(self.take_dir(&id)).await?; + Ok(id) + } + + /// The folder of take `id`, which holds its parts. + pub fn take_dir(&self, id: &str) -> PathBuf { + self.dir.join("rec").join(id) + } + + /// The ids of every take on disk. + pub async fn takes(&self) -> io::Result<Vec<String>> { + let mut ids = Vec::new(); + let mut entries = tokio::fs::read_dir(self.dir.join("rec")).await?; + while let Some(entry) = entries.next_entry().await? { + if let Ok(id) = entry.file_name().into_string() + && valid_session(&id) + { + ids.push(id); + } + } + Ok(ids) + } + + /// Joins the closed parts of take `id` into `joined.weba`, unless `joined.key` already + /// records the same parts. A part in `attached` is still being written and is left out. + /// Answers the joined file and its join key, or `None` when no closed part has audio. + /// The join is written to a temporary name and renamed, the key after the file, so a crash + /// between the two only means the next request joins again. + pub async fn joined_take(&self, id: &str, attached: &HashSet<u32>) -> anyhow::Result<Option<(PathBuf, String)>> { + let _lock = self.joins.lock().await; + let dir = self.take_dir(id); + let closed: Vec<(u32, u64)> = parts_in(&dir)?.into_iter().filter(|(n, _)| !attached.contains(n)).collect(); + if closed.is_empty() { + return Ok(None); + } + let key = join_key(&closed); + let joined = dir.join("joined.weba"); + if tokio::fs::read_to_string(dir.join("joined.key")).await.is_ok_and(|stored| stored == key) && joined.is_file() { + return Ok(Some((joined, key))); + } + let parts: Vec<PathBuf> = closed.iter().map(|(n, _)| part_file(&dir, *n)).collect(); + let tmp = dir.join(format!("joined-{}.tmp", uuid::Uuid::now_v7())); + let out = tmp.clone(); + if let Err(err) = tokio::task::spawn_blocking(move || webm::join(&parts, &out)).await? { + let _ = tokio::fs::remove_file(&tmp).await; + eprintln!("joining take {id} failed: {err:#}"); + return Ok(None); + } + tokio::fs::rename(&tmp, &joined).await?; + let key_tmp = dir.join(format!("joined-{}.tmp", uuid::Uuid::now_v7())); + tokio::fs::write(&key_tmp, &key).await?; + tokio::fs::rename(&key_tmp, dir.join("joined.key")).await?; + Ok(Some((joined, key))) + } + + /// Stores the body under its blake3 hash and `ext` (from [`ext_of`]). Answers with the + /// stored file name, `<hash>.<ext>`. The temporary file is removed on any error. + pub async fn store<B>(&self, ext: &str, mut body: B) -> Result<String, StoreError> + where + B: http_body::Body<Data = Bytes> + Unpin, + B::Error: Display, + { + let tmp = self.dir.join("tmp").join(uuid::Uuid::now_v7().to_string()); + let hash = match write_hashed(&tmp, &mut body).await { + Ok(hash) => hash, + Err(err) => { + let _ = tokio::fs::remove_file(&tmp).await; + return Err(err); + } + }; + let name = format!("{hash}.{ext}"); + // Renaming over an identical file leaves the same bytes under the same name. + if let Err(err) = tokio::fs::rename(&tmp, self.path(&name)).await { + let _ = tokio::fs::remove_file(&tmp).await; + return Err(failed(err)); + } + Ok(name) + } + + /// Where the file `name` lives. Check it with [`valid_name`] before serving. + pub fn path(&self, name: &str) -> PathBuf { + self.dir.join("files").join(name) + } + + /// The names of the stored files. + pub async fn list(&self) -> io::Result<Vec<String>> { + let mut names = Vec::new(); + let mut entries = tokio::fs::read_dir(self.dir.join("files")).await?; + while let Some(entry) = entries.next_entry().await? { + if let Ok(name) = entry.file_name().into_string() + && valid_name(&name) + { + names.push(name); + } + } + Ok(names) + } +} + +/// Streams `body` into the file at `tmp`, returning the blake3 hash of the bytes written. +async fn write_hashed<B>(tmp: &Path, body: &mut B) -> Result<String, StoreError> +where + B: http_body::Body<Data = Bytes> + Unpin, + B::Error: Display, +{ + let mut file = tokio::fs::File::create(tmp).await.map_err(failed)?; + let mut hasher = blake3::Hasher::new(); + let mut len: u64 = 0; + while let Some(frame) = std::future::poll_fn(|cx| http_body::Body::poll_frame(Pin::new(&mut *body), cx)).await { + let frame = frame.map_err(|err| StoreError::Failed(anyhow::anyhow!("{err}")))?; + let Ok(chunk) = frame.into_data() else { continue }; + len += chunk.len() as u64; + if len > MAX_BYTES { + return Err(StoreError::TooLarge); + } + hasher.update(&chunk); + file.write_all(&chunk).await.map_err(failed)?; + } + file.flush().await.map_err(failed)?; + Ok(hasher.finalize().to_hex().to_string()) +} + +fn failed(err: io::Error) -> StoreError { + StoreError::Failed(err.into()) +} + +/// A new take id: `<note>.<uuid v7>.weba`. The uuid sorts by creation time. +pub fn session_id(note: &str) -> String { + format!("{note}.{}.weba", uuid::Uuid::now_v7()) +} + +/// Whether `id` is a take id from [`session_id`]: a note of 1 to 64 ASCII letters, digits or +/// `-`, a uuid-shaped part of 1 to 36 hex digits or `-`, and the `weba` extension. Dots are the +/// only separators, so a path with `/` or `..` is refused. +pub fn valid_session(id: &str) -> bool { + let mut parts = id.split('.'); + let (Some(note), Some(uuid), Some(ext), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else { + return false; + }; + (1..=64).contains(¬e.len()) + && note.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') + && (1..=36).contains(&uuid.len()) + && uuid.bytes().all(|b| b.is_ascii_hexdigit() || b == b'-') + && ext == "weba" +} + +/// The file of part `n` of a take folder: `<n>.weba`, the raw MediaRecorder stream from 0. +pub fn part_file(dir: &Path, n: u32) -> PathBuf { + dir.join(format!("{n}.weba")) +} + +/// The parts of a take folder as `(number, bytes)`, in part order. Only `<n>.weba` files are parts, +/// so the joined file and temporary files are skipped. +pub fn parts_in(dir: &Path) -> io::Result<Vec<(u32, u64)>> { + let mut parts = Vec::new(); + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + let Some(n) = entry.file_name().to_str().and_then(part_number) else { continue }; + parts.push((n, entry.metadata()?.len())); + } + parts.sort_unstable(); + Ok(parts) +} + +/// The bytes of all parts of a take folder. +pub fn take_bytes(dir: &Path) -> io::Result<u64> { + Ok(parts_in(dir)?.iter().map(|(_, len)| len).sum()) +} + +/// The part number of a file name `<n>.weba`. +fn part_number(name: &str) -> Option<u32> { + let digits = name.strip_suffix(".weba")?; + if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + digits.parse().ok() +} + +/// The join key of a take's closed parts: each part as `<n>:<bytes>`, comma separated. A join +/// is current while the key of the parts on disk equals the key it was joined under. +pub fn join_key(parts: &[(u32, u64)]) -> String { + parts.iter().map(|(n, len)| format!("{n}:{len}")).collect::<Vec<_>>().join(",") +} + +/// The lowercase extension of a file name, or `bin` when there is none that is 1 to 10 +/// ASCII letters or digits. +pub fn ext_of(name: &str) -> String { + let ext = Path::new(name) + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("") + .to_ascii_lowercase(); + if is_ext(&ext) { ext } else { "bin".to_owned() } +} + +/// Whether `ext` is 1 to 10 lowercase ASCII letters or digits. +fn is_ext(ext: &str) -> bool { + (1..=10).contains(&ext.len()) && ext.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) +} + +/// The content type served inline for `ext`. `None` for every other type, which is served +/// as a download. SVG and HTML are never inline: they can run script. +pub fn content_type(ext: &str) -> Option<&'static str> { + Some(match ext { + "png" => "image/png", + "jpg" | "jpeg" => "image/jpeg", + "gif" => "image/gif", + "webp" => "image/webp", + "avif" => "image/avif", + "bmp" => "image/bmp", + "mp3" => "audio/mpeg", + "m4a" => "audio/mp4", + "wav" => "audio/wav", + "flac" => "audio/flac", + "aac" => "audio/aac", + "ogg" | "oga" | "opus" => "audio/ogg", + "weba" => "audio/webm", + "mp4" | "m4v" => "video/mp4", + "webm" => "video/webm", + "mov" => "video/quicktime", + "ogv" => "video/ogg", + "pdf" => "application/pdf", + _ => return None, + }) +} + +/// Whether `name` is exactly a 64-digit lowercase hex blake3 hash, a dot and a valid +/// extension. Anything else, such as a path with `/` or `..`, is refused. +pub fn valid_name(name: &str) -> bool { + let Some((hash, ext)) = name.split_once('.') else { + return false; + }; + hash.len() == 64 + && hash.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + && is_ext(ext) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_and_extensions() { + assert_eq!(ext_of("Photo.JPG"), "jpg"); + assert_eq!(ext_of("notes"), "bin"); + assert_eq!(ext_of("bad.e x"), "bin"); + assert_eq!(ext_of("long.abcdefghijk"), "bin"); + let hash = "a".repeat(64); + assert!(valid_name(&format!("{hash}.png"))); + assert!(!valid_name(&format!("{hash}.PNG"))); + assert!(!valid_name(&format!("../{hash}.png"))); + assert!(!valid_name(&format!("{}.png", "A".repeat(64)))); + assert!(!valid_name(&format!("{}.png", "a".repeat(63)))); + } + + #[test] + fn session_ids() { + let id = session_id("my-note"); + assert!(valid_session(&id)); + assert!(!valid_session("my-note.abc.webm")); + assert!(!valid_session("my-note.abc.weba.weba")); + assert!(!valid_session("../x.abc.weba")); + assert!(!valid_session("a/b.abc.weba")); + assert!(!valid_session("note.abc.WEBA")); + assert!(!valid_session(&format!("{}.abc.weba", "n".repeat(65)))); + } + + #[test] + fn join_keys() { + assert_eq!(join_key(&[(0, 10), (2, 5)]), "0:10,2:5"); + assert_eq!(join_key(&[]), ""); + } +} diff --git a/src/media/webm.rs b/src/media/webm.rs new file mode 100644 index 0000000..b1eeafc --- /dev/null +++ b/src/media/webm.rs @@ -0,0 +1,389 @@ +//! Joins the raw MediaRecorder parts of a recording take into one WebM. +//! +//! Each part is an EBML header, a Segment and Clusters of unknown size, and may end in a block +//! cut off by a crash. Packets are copied, never decoded: Symphonia reads them and this module +//! writes them back with known sizes. + +use std::fs::File; +use std::io::{self, BufWriter, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; + +use anyhow::bail; +use symphonia::core::codecs::CodecParameters; +use symphonia::core::codecs::audio::well_known::CODEC_ID_OPUS; +use symphonia::core::formats::{FormatOptions, FormatReader}; +use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions}; +use symphonia::default::formats::MkvReader; + +/// Largest span of one Cluster, in milliseconds. +const CLUSTER_MS: i64 = 5_000; +/// Length of a packet when the container gives none and there is no gap to measure. +const DEFAULT_GAP_MS: i64 = 20; +/// Marks an 8-byte EBML size, in the high byte of the value. +const SIZE_MARK: u64 = 1 << 56; + +const EBML: u32 = 0x1A45_DFA3; +const DOC_TYPE: u32 = 0x4282; +const DOC_TYPE_VERSION: u32 = 0x4287; +const DOC_TYPE_READ_VERSION: u32 = 0x4285; +const SEGMENT: u32 = 0x1853_8067; +const INFO: u32 = 0x1549_A966; +const TIMECODE_SCALE: u32 = 0x2AD7_B1; +const DURATION: u32 = 0x4489; +const MUXING_APP: u32 = 0x4D80; +const WRITING_APP: u32 = 0x5741; +const TRACKS: u32 = 0x1654_AE6B; +const TRACK_ENTRY: u32 = 0xAE; +const TRACK_NUMBER: u32 = 0xD7; +const TRACK_UID: u32 = 0x73C5; +const TRACK_TYPE: u32 = 0x83; +const CODEC_ID: u32 = 0x86; +const CODEC_PRIVATE: u32 = 0x63A2; +const AUDIO: u32 = 0xE1; +const SAMPLING_FREQUENCY: u32 = 0xB5; +const CHANNELS: u32 = 0x9F; +const CLUSTER: u32 = 0x1F43_B675; +const TIMECODE: u32 = 0xE7; +const SIMPLE_BLOCK: u32 = 0xA3; +const CUES: u32 = 0x1C53_BB6B; +const CUE_POINT: u32 = 0xBB; +const CUE_TIME: u32 = 0xB3; +const CUE_TRACK_POSITIONS: u32 = 0xB7; +const CUE_TRACK: u32 = 0xF7; +const CUE_CLUSTER_POSITION: u32 = 0xF1; + +/// Opus parameters of a part, written into the joined Tracks. +struct Codec { + head: Box<[u8]>, + rate: u32, + channels: u64, +} + +/// Joins `parts` in order into one WebM at `out`, which is written in place: a failed join +/// leaves a partial file, so callers write to a temporary name and rename on success. Parts +/// that cannot be opened, have no Opus track, or hold no packets are skipped. Fails when no +/// part has any packet. +pub fn join(parts: &[PathBuf], out: &Path) -> anyhow::Result<()> { + let mut muxer: Option<Muxer> = None; + // Where the next part starts, in milliseconds. + let mut shift = 0; + for path in parts { + let Some((mut reader, id, codec)) = open(path) else { continue }; + let mut start_pts = None; + // Shifted timestamp of the previous packet of this part. + let mut last: Option<i64> = None; + let mut gap = DEFAULT_GAP_MS; + // A read error is the cut-off tail of a crashed recording: it ends the part. + while let Ok(Some(packet)) = reader.next_packet() { + if packet.track_id != id { + continue; + } + let first = *start_pts.get_or_insert(packet.pts.get()); + let ts = shift + (packet.pts.get() - first).max(0); + gap = match (packet.dur.get(), last) { + (0, Some(prev)) => (ts - prev).max(0), + (0, None) => gap, + (dur, _) => dur as i64, + }; + if muxer.is_none() { + muxer = Some(Muxer::new(out, &codec)?); + } + if let Some(muxer) = muxer.as_mut() { + muxer.block(ts, &packet.data)?; + } + last = Some(ts); + } + if let Some(last) = last { + shift = last + gap; + } + } + let Some(muxer) = muxer else { bail!("no Opus packets in {} parts", parts.len()) }; + muxer.finish(shift)?; + Ok(()) +} + +/// Opens a part and finds its Opus track. `None` when it cannot be read or has no Opus track. +fn open(path: &Path) -> Option<(Box<dyn FormatReader>, u32, Codec)> { + let file = File::open(path).ok()?; + let mss = MediaSourceStream::new(Box::new(file), MediaSourceStreamOptions::default()); + let reader = MkvReader::try_new(mss, FormatOptions::default()).ok()?; + let (id, codec) = reader.tracks().iter().find_map(|track| match track.codec_params.as_ref()? { + CodecParameters::Audio(audio) if audio.codec == CODEC_ID_OPUS => Some(( + track.id, + Codec { + head: audio.extra_data.clone()?, + rate: audio.sample_rate?, + channels: audio.channels.as_ref()?.count() as u64, + }, + )), + _ => None, + })?; + Some((Box::new(reader), id, codec)) +} + +/// Writes the joined WebM. The Segment size and the Duration are not known until the end, so +/// they are written as placeholders and patched in place. +struct Muxer { + file: BufWriter<File>, + /// Bytes written so far. + pos: u64, + /// Where the Segment's data starts. + segment: u64, + /// Where the Segment's 8-byte size is. + segment_size_at: u64, + /// Where the Info's 8-byte Duration is. + duration_at: u64, + /// Start time and body of the open Cluster. + cluster: Option<(i64, Vec<u8>)>, + /// Start time and position (from the Segment's data) of each written Cluster. + cues: Vec<(i64, u64)>, +} + +impl Muxer { + /// Creates `path` and writes the EBML header, the Segment start, Info and Tracks. + fn new(path: &Path, codec: &Codec) -> io::Result<Self> { + let mut muxer = Self { + file: BufWriter::new(File::create(path)?), + pos: 0, + segment: 0, + segment_size_at: 0, + duration_at: 0, + cluster: None, + cues: Vec::new(), + }; + let header = [text(DOC_TYPE, "webm"), uint(DOC_TYPE_VERSION, 4), uint(DOC_TYPE_READ_VERSION, 2)]; + muxer.put(&element(EBML, &header.concat()))?; + muxer.put(&id_bytes(SEGMENT))?; + muxer.segment_size_at = muxer.pos; + muxer.put(&[0x01, 0, 0, 0, 0, 0, 0, 0])?; + muxer.segment = muxer.pos; + + let tail = [text(MUXING_APP, "project_note"), text(WRITING_APP, "project_note")].concat(); + // Timestamps are in milliseconds. + let info = element( + INFO, + &[uint(TIMECODE_SCALE, 1_000_000), element(DURATION, &[0u8; 8]), tail.clone()].concat(), + ); + muxer.duration_at = muxer.pos + (info.len() - tail.len() - 8) as u64; + muxer.put(&info)?; + + let audio = [float(SAMPLING_FREQUENCY, f64::from(codec.rate)), uint(CHANNELS, codec.channels)]; + let entry = [ + uint(TRACK_NUMBER, 1), + uint(TRACK_UID, 1), + uint(TRACK_TYPE, 2), + text(CODEC_ID, "A_OPUS"), + element(CODEC_PRIVATE, &codec.head), + element(AUDIO, &audio.concat()), + ]; + muxer.put(&element(TRACKS, &element(TRACK_ENTRY, &entry.concat())))?; + Ok(muxer) + } + + fn put(&mut self, bytes: &[u8]) -> io::Result<()> { + self.file.write_all(bytes)?; + self.pos += bytes.len() as u64; + Ok(()) + } + + /// Overwrites bytes already written at `at`, then goes back to the end. + fn patch(&mut self, at: u64, bytes: &[u8]) -> io::Result<()> { + self.file.seek(SeekFrom::Start(at))?; + self.file.write_all(bytes)?; + self.file.seek(SeekFrom::Start(self.pos))?; + Ok(()) + } + + /// Adds one packet at `ts` (milliseconds), starting a new Cluster when the open one is full + /// or too far behind. + fn block(&mut self, ts: i64, data: &[u8]) -> io::Result<()> { + let open = matches!(&self.cluster, Some((start, _)) if (0..CLUSTER_MS).contains(&(ts - start))); + if !open { + self.flush_cluster()?; + self.cluster = Some((ts, uint(TIMECODE, ts as u64))); + } + if let Some((start, body)) = self.cluster.as_mut() { + // Track 1, relative timecode, keyframe flag, then the packet. + let mut block = vec![0x81]; + block.extend(((ts - *start) as i16).to_be_bytes()); + block.push(0x80); + block.extend_from_slice(data); + body.extend(element(SIMPLE_BLOCK, &block)); + } + Ok(()) + } + + fn flush_cluster(&mut self) -> io::Result<()> { + if let Some((start, body)) = self.cluster.take() { + self.cues.push((start, self.pos - self.segment)); + self.put(&element(CLUSTER, &body))?; + } + Ok(()) + } + + /// Closes the last Cluster, writes Cues, and patches the Segment size and the Duration (ms). + fn finish(mut self, duration: i64) -> io::Result<()> { + self.flush_cluster()?; + let points: Vec<Vec<u8>> = self + .cues + .iter() + .map(|&(time, position)| { + let positions = [uint(CUE_TRACK, 1), uint(CUE_CLUSTER_POSITION, position)].concat(); + let point = [uint(CUE_TIME, time as u64), element(CUE_TRACK_POSITIONS, &positions)]; + element(CUE_POINT, &point.concat()) + }) + .collect(); + self.put(&element(CUES, &points.concat()))?; + let size = self.pos - self.segment; + self.patch(self.segment_size_at, &(SIZE_MARK | size).to_be_bytes())?; + self.patch(self.duration_at, &(duration as f64).to_be_bytes())?; + self.file.flush() + } +} + +/// Element ID bytes, without leading zeros. +fn id_bytes(id: u32) -> Vec<u8> { + let bytes = id.to_be_bytes(); + let skip = bytes.iter().take_while(|&&byte| byte == 0).count(); + bytes[skip..].to_vec() +} + +/// Smallest EBML size field that holds `size`. +fn size_vint(size: u64) -> Vec<u8> { + let len = (1..=8u32).find(|&len| size < (1u64 << (7 * len)) - 1).unwrap_or(8); + let value = size | (1u64 << (7 * len)); + value.to_be_bytes()[8 - len as usize..].to_vec() +} + +fn element(id: u32, body: &[u8]) -> Vec<u8> { + let mut out = id_bytes(id); + out.extend(size_vint(body.len() as u64)); + out.extend_from_slice(body); + out +} + +/// Unsigned integer, big-endian, without leading zeros. +fn uint(id: u32, value: u64) -> Vec<u8> { + let bytes = value.to_be_bytes(); + let skip = bytes.iter().take_while(|&&byte| byte == 0).count().min(7); + element(id, &bytes[skip..]) +} + +fn text(id: u32, value: &str) -> Vec<u8> { + element(id, value.as_bytes()) +} + +fn float(id: u32, value: f64) -> Vec<u8> { + element(id, &value.to_be_bytes()) +} + +#[cfg(test)] +mod tests { + use std::fs; + + use super::*; + + /// OpusHead for mono 48 kHz, used as CodecPrivate. + const OPUS_HEAD: &[u8] = b"OpusHead\x01\x01\x38\x01\x80\xBB\x00\x00\x00\x00\x00"; + const UNKNOWN_SIZE: [u8; 8] = [0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]; + + /// One SimpleBlock of 20 bytes, `rel` milliseconds into its Cluster. + fn block(rel: i64, fill: u8) -> Vec<u8> { + let mut body = vec![0x81]; + body.extend((rel as i16).to_be_bytes()); + body.push(0x80); + body.extend([fill; 20]); + element(SIMPLE_BLOCK, &body) + } + + /// A MediaRecorder-style WebM: unknown-size Segment and Clusters, one Opus track. Each + /// cluster is (start ms, [(ms, fill)]). + fn recorder(clusters: &[(i64, Vec<(i64, u8)>)]) -> Vec<u8> { + let mut out = element(EBML, &text(DOC_TYPE, "webm")); + out.extend(id_bytes(SEGMENT)); + out.extend(UNKNOWN_SIZE); + let info = [uint(TIMECODE_SCALE, 1_000_000), text(MUXING_APP, "Chrome"), text(WRITING_APP, "Chrome")]; + out.extend(element(INFO, &info.concat())); + let audio = [float(SAMPLING_FREQUENCY, 48_000.0), uint(CHANNELS, 1)].concat(); + let entry = [ + uint(TRACK_NUMBER, 1), + uint(TRACK_UID, 1), + uint(TRACK_TYPE, 2), + text(CODEC_ID, "A_OPUS"), + element(CODEC_PRIVATE, OPUS_HEAD), + element(AUDIO, &audio), + ]; + out.extend(element(TRACKS, &element(TRACK_ENTRY, &entry.concat()))); + for (start, blocks) in clusters { + out.extend(id_bytes(CLUSTER)); + out.extend(UNKNOWN_SIZE); + out.extend(uint(TIMECODE, *start as u64)); + for &(ts, fill) in blocks { + out.extend(block(ts - start, fill)); + } + } + out + } + + /// Opens a WebM and reads its duration in ms and every packet as (ms, data). + fn read(path: &Path) -> (Option<u64>, Vec<(i64, Vec<u8>)>) { + let mut reader = open(path).expect("output opens").0; + let duration = reader.media_info().duration.map(|d| d.get()); + let mut packets = Vec::new(); + while let Some(packet) = reader.next_packet().expect("packet reads") { + packets.push((packet.pts.get(), packet.data.to_vec())); + } + (duration, packets) + } + + fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("webm-{name}-{}", uuid::Uuid::now_v7())); + fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn joins_parts_with_summed_duration_and_shifted_timestamps() { + let dir = scratch("join"); + let first = dir.join("0.weba"); + let second = dir.join("1.weba"); + fs::write(&first, recorder(&[(0, vec![(0, 1), (20, 2)]), (40, vec![(40, 3)])])).unwrap(); + fs::write(&second, recorder(&[(0, vec![(0, 4), (20, 5)])])).unwrap(); + let out = dir.join("joined.weba"); + join(&[first, second], &out).unwrap(); + + // The first part is 60 ms (last packet at 40 ms plus a 20 ms gap), the second 40 ms. + let (duration, packets) = read(&out); + assert_eq!(duration, Some(100)); + let expected: Vec<(i64, Vec<u8>)> = [(0, 1), (20, 2), (40, 3), (60, 4), (80, 5)] + .into_iter() + .map(|(ts, fill)| (ts, vec![fill; 20])) + .collect(); + assert_eq!(packets, expected); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn drops_only_a_block_cut_off_at_the_end_of_a_part() { + let dir = scratch("cut"); + let first = dir.join("0.weba"); + let second = dir.join("1.weba"); + fs::write(&first, recorder(&[(0, vec![(0, 1), (20, 2)]), (40, vec![(40, 3)])])).unwrap(); + let mut cut = recorder(&[(0, vec![(0, 4), (20, 5)])]); + // Ends inside the data of the second block. + cut.truncate(cut.len() - 10); + fs::write(&second, cut).unwrap(); + let out = dir.join("joined.weba"); + join(&[first, second], &out).unwrap(); + + // The second part keeps only its first block, so it is 20 ms long. + let (duration, packets) = read(&out); + assert_eq!(duration, Some(80)); + let expected: Vec<(i64, Vec<u8>)> = [(0, 1), (20, 2), (40, 3), (60, 4)] + .into_iter() + .map(|(ts, fill)| (ts, vec![fill; 20])) + .collect(); + assert_eq!(packets, expected); + fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/src/store.rs b/src/store.rs index 3956b68..2654b6b 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1,15 +1,22 @@ //! Persistence. The only module that talks to turso. +mod directory; + use std::collections::HashMap; + +use tokio::sync::mpsc; +use std::sync::{Arc, RwLock}; use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{Context, anyhow}; -use crate::matcher::Matcher; +use crate::matcher::{Matcher, Part}; use tokio::sync::Mutex; use crate::export::LinkTarget; +use directory::{Change, Directory, Entry, Vocab}; +#[derive(Clone)] pub struct NoteMeta { pub id: String, pub title: String, @@ -21,6 +28,41 @@ pub struct NoteMeta { pub trashed_at: Option<i64>, } +/// Which notes a list shows. Every filter but `Trash` leaves the trash out. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ListFilter { + /// Every note outside the trash. + All, + /// Notes outside the trash that are in no notebook. + Unfiled, + /// Notes outside the trash that are in the notebook with this id. + Notebook(String), + /// Trashed notes, most recently trashed first. + Trash, +} + +impl ListFilter { + /// The WHERE clause for this filter, and the parameters it binds (`?1` when any). + fn clause(&self) -> (&'static str, Vec<String>) { + match self { + Self::All => ("trashed_at IS NULL", Vec::new()), + Self::Unfiled => ("trashed_at IS NULL AND notebook_id IS NULL", Vec::new()), + Self::Notebook(id) => ("trashed_at IS NULL AND notebook_id = ?1", vec![id.clone()]), + Self::Trash => ("trashed_at IS NOT NULL", Vec::new()), + } + } + + /// The ORDER BY for this filter: most recently updated first, or most recently trashed + /// first for the trash. Ties go to the newer id, so the order is an index read + /// backwards rather than a sort of every row. + fn order(&self) -> &'static str { + match self { + Self::Trash => "trashed_at DESC, id DESC", + _ => "updated_at DESC, id DESC", + } + } +} + pub struct Notebook { pub id: String, pub name: String, @@ -31,14 +73,40 @@ pub struct Notebook { pub struct DocBytes { pub snapshot: Option<Vec<u8>>, pub updates: Vec<Vec<u8>>, + /// The markdown stored with the snapshot, when no update came after it. + pub markdown: Option<String>, + /// [`crate::export::to_markdown_deferred`] of the doc, when cached for its snapshot + /// and no update came after it. Only read by [`Store::load_docs`], which then skips + /// the snapshot. + pub export: Option<String>, + /// The snapshot's last update, 0 without a snapshot. + pub upto_seq: i64, +} + +impl DocBytes { + /// Bytes held: what reading the note cost. + pub fn stored_len(&self) -> usize { + let text = |t: &Option<String>| t.as_ref().map_or(0, String::len); + self.snapshot.as_ref().map_or(0, Vec::len) + self.updates.iter().map(Vec::len).sum::<usize>() + text(&self.markdown) + text(&self.export) + } } pub struct Store { /// Single connection shared by all tasks. Calls are serialized by the mutex, /// which also keeps transactions from interleaving on one connection. conn: Mutex<turso::Connection>, + /// A second connection for single-statement reads: in WAL they do not wait for a + /// write, and a huge note's write holds `conn` for seconds. + read: Mutex<turso::Connection>, + /// Loaded on first use. See [`directory`]. + dir: Mutex<Option<Directory>>, + /// Writes committed since the directory was last read, in order. + changes: std::sync::Mutex<Vec<Change>>, + /// Notes whose text changed but is too long to index while the directory waits: + /// [`Store::keep_directory_fresh`] indexes them off its lock. + heavy: std::sync::Mutex<HashMap<String, std::time::Instant>>, /// Keeps the database handle alive for as long as the connection is used. - _db: turso::Database, + db: turso::Database, } pub(crate) fn now_millis() -> i64 { @@ -94,6 +162,14 @@ fn blob_col(row: &turso::Row, idx: usize) -> anyhow::Result<Vec<u8>> { } } +fn opt_blob_col(row: &turso::Row, idx: usize) -> anyhow::Result<Option<Vec<u8>>> { + match row.get_value(idx)? { + turso::Value::Null => Ok(None), + turso::Value::Blob(b) => Ok(Some(b)), + other => Err(anyhow!("column {idx}: expected BLOB or NULL, got {other:?}")), + } +} + fn note_from_row(row: &turso::Row) -> anyhow::Result<NoteMeta> { Ok(NoteMeta { id: text_col(row, 0)?, @@ -105,6 +181,55 @@ fn note_from_row(row: &turso::Row) -> anyhow::Result<NoteMeta> { }) } +/// Id of the notebook named `name`, ignoring case. The exact name is looked up first, +/// through the index; other casings need a scan. +async fn find_notebook(tx: &turso::transaction::Transaction<'_>, name: &str) -> anyhow::Result<Option<String>> { + let mut rows = tx.query("SELECT id FROM notebooks WHERE name = ?1 LIMIT 1", (name.to_string(),)).await?; + if let Some(row) = rows.next().await? { + return Ok(Some(text_col(&row, 0)?)); + } + drop(rows); + let key = name.to_lowercase(); + let mut rows = tx.query("SELECT id, name FROM notebooks", ()).await?; + while let Some(row) = rows.next().await? { + if text_col(&row, 1)?.to_lowercase() == key { + return Ok(Some(text_col(&row, 0)?)); + } + } + Ok(None) +} + +/// Inserts the note links of `src` inside an open transaction. +async fn insert_links( + tx: &turso::transaction::Transaction<'_>, + src: &str, + targets: &[LinkTarget], +) -> anyhow::Result<()> { + for target in targets { + match target { + LinkTarget::Id(id) => { + tx.execute( + "INSERT INTO note_links (src, dst_id, dst_title) VALUES (?1, ?2, NULL)", + (src.to_string(), id.clone()), + ) + .await?; + } + LinkTarget::Title(title) => { + let key = title_key(title); + if key.is_empty() { + continue; + } + tx.execute( + "INSERT INTO note_links (src, dst_id, dst_title) VALUES (?1, NULL, ?2)", + (src.to_string(), key), + ) + .await?; + } + } + } + Ok(()) +} + /// Deletes one note's rows inside an open transaction. async fn delete_note_rows( tx: &turso::transaction::Transaction<'_>, @@ -114,6 +239,10 @@ async fn delete_note_rows( .await?; tx.execute("DELETE FROM snapshots WHERE note_id = ?1", (note_id.to_string(),)) .await?; + tx.execute("DELETE FROM pending_docs WHERE note_id = ?1", (note_id.to_string(),)) + .await?; + tx.execute("DELETE FROM export_text WHERE note_id = ?1", (note_id.to_string(),)) + .await?; tx.execute("DELETE FROM note_text WHERE note_id = ?1", (note_id.to_string(),)) .await?; tx.execute("DELETE FROM note_versions WHERE note_id = ?1", (note_id.to_string(),)) @@ -133,6 +262,14 @@ fn notebook_from_row(row: &turso::Row) -> anyhow::Result<Notebook> { }) } +/// What [`Store::search`] found: the best hits, and whether the time budget ran out +/// before every note was read. +#[derive(Default)] +pub struct Searched { + pub hits: Vec<SearchHit>, + pub partial: bool, +} + /// A note matched by [`Store::search`], with a plain-text excerpt of its body. pub struct SearchHit { pub note: NoteMeta, @@ -143,28 +280,168 @@ pub struct SearchHit { const SNIPPET_CHARS: usize = 160; /// Characters of body text shown as a note's preview in a list. const PREVIEW_CHARS: usize = 140; +/// Characters of a note's body read for its preview. Enough for `PREVIEW_CHARS` of plain +/// text, so the rest of a long body is never loaded. +const PREVIEW_SOURCE_CHARS: usize = 2000; +/// The stored markdown of each of `ids`, by id, read on `conn`. +async fn bodies_on(conn: &turso::Connection, ids: &[String]) -> anyhow::Result<HashMap<String, String>> { + let placeholders = (1..=ids.len()).map(|i| format!("?{i}")).collect::<Vec<_>>().join(", "); + let mut rows = conn + .query(format!("SELECT note_id, body FROM note_text WHERE note_id IN ({placeholders})"), ids.to_vec()) + .await?; + let mut bodies = HashMap::new(); + while let Some(row) = rows.next().await? { + bodies.insert(text_col(&row, 0)?, text_col(&row, 1)?); + } + Ok(bodies) +} + +/// Bytes of note bodies indexed at a time when the directory is loaded. +const DIRECTORY_BATCH_BYTES: usize = 256 << 20; +/// Connections reading note texts at once for a search. +const SEARCH_READERS: usize = 8; +/// Connections reading the notes at once when the directory is loaded. +const DIRECTORY_READERS: usize = 4; +/// Note ids per `IN (...)` query, well under SQLite's parameter limit. +const PREVIEW_BATCH: usize = 500; +/// Bytes of a changed note's text above which it is indexed in the background: a +/// 100 MB note takes seconds, and every page waits for the directory meanwhile. +const HEAVY_INDEX_BYTES: i64 = 1 << 20; +/// How long such a note goes unchanged before it is indexed: while someone types in +/// it, each text flush would cost a core for a second. +const HEAVY_QUIET: std::time::Duration = std::time::Duration::from_secs(2); /// Markdown as plain text. Code fences are dropped, block markers (headings, quotes, /// list and task markers, rules) and inline syntax (emphasis, code spans, escapes) are /// removed, link and image text is kept, and lines are joined with single spaces. fn plain_text(markdown: &str) -> String { - let mut lines: Vec<String> = Vec::new(); - let mut in_fence = false; - for line in markdown.lines() { - let trimmed = line.trim(); - if trimmed.starts_with("```") || trimmed.starts_with("~~~") { - in_fence = !in_fence; - continue; + PlainChunks::new(markdown, usize::MAX).next().unwrap_or_default() +} + +/// [`plain_text`] in pieces of at least `chunk` bytes, which joined with single spaces +/// give the whole: a long note is matched a piece at a time and the rest skipped once +/// nothing better can turn up. +struct PlainChunks<'a> { + lines: std::str::Lines<'a>, + in_fence: bool, + chunk: usize, +} + +impl<'a> PlainChunks<'a> { + fn new(markdown: &'a str, chunk: usize) -> Self { + Self { lines: markdown.lines(), in_fence: false, chunk } + } +} + +impl Iterator for PlainChunks<'_> { + type Item = String; + + fn next(&mut self) -> Option<String> { + fn push(out: &mut String, text: &str) { + // Most lines are ASCII with single spaces: already what the words joined give. + let mut prev_space = false; + let simple = text.bytes().all(|b| { + let ok = b.is_ascii() && !matches!(b, b'\t' | b'\n' | b'\r' | b'\x0b' | b'\x0c') && !(b == b' ' && prev_space); + prev_space = b == b' '; + ok + }); + if simple && !text.starts_with(' ') && !text.ends_with(' ') { + if !text.is_empty() { + if !out.is_empty() { + out.push(' '); + } + out.push_str(text); + } + return; + } + for word in text.split_whitespace() { + if !out.is_empty() { + out.push(' '); + } + out.push_str(word); + } } - let text = if in_fence { - trimmed.to_owned() - } else { - strip_inline(strip_block(trimmed)) - }; - if !text.trim().is_empty() { - lines.push(text); + let mut out = String::new(); + let mut any = false; + for line in self.lines.by_ref() { + any = true; + let trimmed = line.trim(); + if trimmed.starts_with("```") || trimmed.starts_with("~~~") { + self.in_fence = !self.in_fence; + } else if self.in_fence { + push(&mut out, trimmed); + } else { + push(&mut out, &strip_inline(strip_block(trimmed))); + } + if out.len() >= self.chunk { + break; + } + } + (any && (!out.is_empty() || self.chunk == usize::MAX)).then_some(out) + } +} + +/// `matcher` against a note's title and its whole `body`, read a piece at a time: the +/// note's key and a snippet when it matches. Stops early once every term matched at +/// `floor`, the least it can cost in this note, which nothing beats. +fn match_long(title: &str, body: &str, matcher: &Matcher, floor: usize) -> Option<(SearchKey, String)> { + match_pieces(title, PlainChunks::new(body, 64 << 10), matcher, floor).0 +} + +/// [`match_long`] over plain text given in pieces joined by single spaces. Also says +/// whether every term matched at `floor`: then the rest of the text cannot change it. +fn match_pieces( + title: &str, + pieces: impl Iterator<Item = String>, + matcher: &Matcher, + floor: usize, +) -> (Option<(SearchKey, String)>, bool) { + // Text carried into the next piece, for matches across the cut. + const OVERLAP: usize = 1024; + let in_title = matcher.term_costs(title); + let mut in_text: Vec<Option<usize>> = vec![None; in_title.len()]; + let mut snip: Option<String> = None; + let mut tail = String::new(); + let mut perfect = false; + for (i, piece) in pieces.enumerate() { + let window = if tail.is_empty() { piece } else { format!("{tail} {piece}") }; + for (best, cost) in in_text.iter_mut().zip(matcher.term_costs(&window)) { + if let Some(cost) = cost { + *best = Some(best.map_or(cost, |b| b.min(cost))); + } } + if snip.is_none() && in_text.iter().any(Option::is_some) { + let s = snippet(&window, matcher); + snip = Some(if i > 0 && !s.starts_with('…') { format!("…{s}") } else { s }); + } + if in_text.iter().all(|c| c.is_some_and(|c| c <= floor)) { + perfect = true; + break; + } + let from = window.char_indices().rev().nth(OVERLAP).map_or(0, |(at, _)| at); + // From a word start, so a match there is not taken for one at a word start. + let from = if from == 0 { 0 } else { window[from..].find(' ').map_or(window.len(), |sp| from + sp + 1) }; + tail = window[from..].to_owned(); } - lines.join(" ").split_whitespace().collect::<Vec<_>>().join(" ") + let key = search_key(in_title.into_iter(), in_text.into_iter()).map(|k| (k, snip.unwrap_or_default())); + (key, perfect) +} + +/// `plain` in pieces of about 64 KB cut at spaces, the cut spaces left out. +fn plain_pieces(plain: &str) -> impl Iterator<Item = String> + '_ { + let mut rest = plain; + std::iter::from_fn(move || { + if rest.is_empty() { + return None; + } + let mut cut = (64 << 10).min(rest.len()); + while !rest.is_char_boundary(cut) { + cut += 1; + } + let cut = if cut == rest.len() { cut } else { rest[cut..].find(' ').map_or(rest.len(), |sp| cut + sp) }; + let piece = rest[..cut].to_owned(); + rest = rest.get(cut + 1..).unwrap_or(""); + Some(piece) + }) } /// Removes the block syntax at the start of one trimmed line: quote marks, heading @@ -206,7 +483,11 @@ fn strip_block(line: &str) -> &str { /// Removes inline syntax from one line: `[text](url)` and `![alt](url)` become their /// text, emphasis and code markers are dropped, `_` is kept inside words only, and a /// backslash escape yields the escaped character. -fn strip_inline(text: &str) -> String { +fn strip_inline(text: &str) -> std::borrow::Cow<'_, str> { + // Most lines have no inline syntax at all. + if !text.contains(['!', '[', '\\', '*', '`', '~', '_']) { + return text.into(); + } let chars: Vec<char> = text.chars().collect(); let mut out = String::with_capacity(text.len()); let mut i = 0; @@ -245,7 +526,7 @@ fn strip_inline(text: &str) -> String { } i += 1; } - out + out.into() } /// Parses `[label](target)` whose `[` is at `open`. Returns the label and the index just @@ -262,51 +543,259 @@ fn link_at(chars: &[char], open: usize) -> Option<(String, usize)> { /// The first `PREVIEW_CHARS` characters of a note's text after its title. The first /// non-blank line of the markdown is the title, so it is skipped. fn preview(markdown: &str) -> String { - let body = markdown - .lines() - .skip_while(|line| line.trim().is_empty()) - .skip(1) - .collect::<Vec<_>>() - .join("\n"); - plain_text(&body).chars().take(PREVIEW_CHARS).collect() + let head = markdown.char_indices().nth(PREVIEW_SOURCE_CHARS).map_or(markdown, |(i, _)| &markdown[..i]); + // The text after the first non-blank line, the title. + let mut rest = head; + loop { + let (line, after) = rest.split_once('\n').unwrap_or((rest, "")); + rest = after; + if !line.trim().is_empty() || rest.is_empty() { + break; + } + } + plain_text(rest).chars().take(PREVIEW_CHARS).collect() } -/// About `SNIPPET_CHARS` characters of plain text around the first term match. +/// About `SNIPPET_CHARS` characters of `plain` around the first term match. /// Cut ends get an ellipsis. -fn snippet(markdown: &str, matcher: &Matcher) -> String { - let plain = plain_text(markdown); - let chars: Vec<char> = plain.chars().collect(); - if chars.is_empty() { +fn snippet(plain: &str, matcher: &Matcher) -> String { + if plain.is_empty() { return String::new(); } - let center = matcher.ranges(&plain).first().map_or(0, |range| range.0); - let mut start = center.saturating_sub(SNIPPET_CHARS / 3); - let end = (start + SNIPPET_CHARS).min(chars.len()); - if end - start < SNIPPET_CHARS { - start = end.saturating_sub(SNIPPET_CHARS); + // Most hits match near the start: look there before reading the whole text. + let mut center = 0; + for window in [4 << 10, 64 << 10, usize::MAX] { + let mut end = window.min(plain.len()); + while !plain.is_char_boundary(end) { + end -= 1; + } + if let Some(range) = matcher.ranges(&plain[..end]).first() { + center = range.0; + break; + } + if end == plain.len() { + break; + } + } + let start = center.saturating_sub(SNIPPET_CHARS / 3); + let mut chars = plain.char_indices().skip(start).map(|(i, _)| i); + let Some(from) = chars.next() else { + // The match is near the end: show the last `SNIPPET_CHARS`. + let from = plain.char_indices().rev().nth(SNIPPET_CHARS - 1).map_or(0, |(i, _)| i); + return format!("{}{}", if from > 0 { "…" } else { "" }, plain[from..].trim()); + }; + let to = chars.nth(SNIPPET_CHARS - 1).unwrap_or(plain.len()); + if to == plain.len() && start > 0 { + // Too close to the end for a full window: take it from further back. + let from = plain.char_indices().rev().nth(SNIPPET_CHARS - 1).map_or(0, |(i, _)| i); + return format!("{}{}", if from > 0 { "…" } else { "" }, plain[from..].trim()); } - let body: String = chars[start..end].iter().collect(); let mut out = String::new(); - if start > 0 { + if from > 0 { out.push('…'); } - out.push_str(body.trim()); - if end < chars.len() { + out.push_str(plain[from..to].trim()); + if to < plain.len() { out.push('…'); } out } +/// Scores every row against `matcher`, in parallel, keeping their order. +type SearchKey = (usize, std::cmp::Reverse<usize>); + +/// Each term matches the title or the text, whichever is closer. Cheaper matches +/// first (exact before typos), then more terms in the title. +fn search_key(in_title: impl Iterator<Item = Option<usize>>, in_text: impl Iterator<Item = Option<usize>>) -> Option<SearchKey> { + let mut cost = 0; + let mut title_terms = 0; + for (t, x) in in_title.zip(in_text) { + match (t, x) { + (Some(t), Some(x)) if t <= x => (cost += t, title_terms += 1), + (Some(t), None) => (cost += t, title_terms += 1), + (_, Some(x)) => (cost += x, ()), + (None, None) => return None, + }; + } + Some((cost, std::cmp::Reverse(title_terms))) +} + +/// A search hit's rank: its [`SearchKey`], then the newest. +type RankKey = (SearchKey, std::cmp::Reverse<i64>); + +/// The `limit` best notes outside the trash by `matcher`, best first: see [`par_top`]. +/// Notes whose text is longer than kept in memory are left out of a case, phrase or +/// regex search here: [`Store::search`] matches them against their stored text. +fn match_top(matcher: &Matcher, slots: &[Option<Arc<Entry>>], vocab: &RwLock<Vocab>, limit: usize) -> Vec<(RankKey, Arc<Entry>)> { + let newest = |k: SearchKey, e: &Entry| (k, std::cmp::Reverse(e.updated_at)); + + match matcher.word_terms() { + Some(terms) => { + let tables = word_costs(matcher, terms, &vocab.read().unwrap()); + par_top_keyed(slots, limit, |e| { + let k = search_key( + tables.iter().map(|t| best_cost(t, e.title_words())), + tables.iter().map(|t| best_cost(t, e.text_words())), + )?; + Some(newest(k, e)) + }) + } + None => par_top_keyed(slots, limit, |e| { + if e.plain_cut { + return None; + } + let k = search_key(matcher.term_costs(e.title()).into_iter(), matcher.term_costs(e.plain()).into_iter())?; + Some(newest(k, e)) + }), + } +} + +/// The `limit` notes outside the trash with the lowest `key`, lowest first; ties go to +/// the lower id. Each thread keeps only its own best `limit`, so a query that matches +/// every note never collects them all. +fn par_top<K: Ord + Copy + Send>( + slots: &[Option<Arc<Entry>>], + limit: usize, + key: impl Fn(&Entry) -> Option<K> + Sync, +) -> Vec<Arc<Entry>> { + par_top_keyed(slots, limit, key).into_iter().map(|(_, e)| e).collect() +} + +/// [`par_top`] with the keys kept. +fn par_top_keyed<K: Ord + Copy + Send>( + slots: &[Option<Arc<Entry>>], + limit: usize, + key: impl Fn(&Entry) -> Option<K> + Sync, +) -> Vec<(K, Arc<Entry>)> { + let threads = std::thread::available_parallelism().map_or(1, |n| n.get()); + let chunk_len = slots.len().div_ceil(threads).max(1); + let key = &key; + let best: Vec<(K, &Arc<Entry>)> = std::thread::scope(|scope| { + let handles: Vec<_> = slots + .chunks(chunk_len) + .map(|chunk| { + scope.spawn(move || { + // Trimmed to the best `limit` whenever it fills, and past that only + // keys as good as the worst kept one enter: a word in every note + // would otherwise collect them all, megabytes per search. + let cap = 4 * limit.max(64); + let mut hits: Vec<(K, &Arc<Entry>)> = Vec::with_capacity(cap); + let mut worst: Option<K> = None; + for e in chunk.iter().flatten().filter(|e| e.trashed_at.is_none()) { + let Some(k) = key(e) else { continue }; + if worst.is_some_and(|w| k > w) { + continue; + } + hits.push((k, e)); + if hits.len() == cap { + hits = top_keyed(hits, limit, |e| e.id()); + worst = hits.last().map(|h| h.0); + } + } + top_keyed(hits, limit, |e| e.id()) + }) + }) + .collect(); + handles + .into_iter() + .flat_map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))) + .collect() + }); + top_keyed(best, limit, |e| e.id()).into_iter().map(|(k, e)| (k, e.clone())).collect() +} + +/// Each term's cost in every word of the vocabulary, by word id; `u8::MAX` where the +/// term does not occur in the word. +fn word_costs(matcher: &Matcher, terms: &[Vec<char>], vocab: &Vocab) -> Vec<Arc<Vec<u8>>> { + /// Term tables kept for the next searches. + const KEPT: usize = 8; + let Some(opts) = matcher.options() else { return Vec::new() }; + let threads = std::thread::available_parallelism().map_or(1, |n| n.get()); + // The costs of `term` in `words`, on every core. + let compute = |term: &[char], from: usize| -> Vec<u8> { + let n = vocab.len() - from; + let chunk_len = n.div_ceil(threads).max(1); + std::thread::scope(|scope| { + let handles: Vec<_> = (from..vocab.len()) + .step_by(chunk_len) + .map(|start| { + let ids = start..(start + chunk_len).min(vocab.len()); + scope.spawn(move || { + ids.map(|id| matcher.word_cost(term, vocab.word(id)).map_or(u8::MAX, |c| c.min(254) as u8)).collect::<Vec<u8>>() + }) + }) + .collect(); + handles.into_iter().flat_map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect() + }) + }; + terms + .iter() + .map(|term| { + let found = { + let mut kept = vocab.costs.lock().unwrap(); + let at = kept.iter().position(|(t, o, _)| **t == **term && *o == opts); + at.map(|i| kept.remove(i)) + }; + let table = match found { + Some((_, _, table)) if table.len() == vocab.len() => table, + Some((_, _, table)) => { + let mut grown = (*table).clone(); + grown.extend(compute(term, table.len())); + Arc::new(grown) + } + None => Arc::new(compute(term, 0)), + }; + let mut kept = vocab.costs.lock().unwrap(); + kept.push((term.clone().into(), opts, table.clone())); + if kept.len() > KEPT { + kept.remove(0); + } + table + }) + .collect() +} + +/// The cheapest cost in `table` among `words`, None if the term is in none of them. +fn best_cost(table: &[u8], words: &[u32]) -> Option<usize> { + let best = words.iter().map(|&w| table[w as usize]).min()?; + (best != u8::MAX).then_some(usize::from(best)) +} + +/// The `limit` items with the smallest keys, in key order, ties by `id`. Selects before +/// sorting: a common word matches every note, and sorting them all costs more than +/// matching them. +fn top<K: Ord + Copy, T>(items: Vec<(K, T)>, limit: usize, id: impl Fn(&T) -> &str) -> Vec<T> { + top_keyed(items, limit, id).into_iter().map(|(_, t)| t).collect() +} + +/// [`top`] with the keys kept. +fn top_keyed<K: Ord + Copy, T>(mut items: Vec<(K, T)>, limit: usize, id: impl Fn(&T) -> &str) -> Vec<(K, T)> { + let cmp = |a: &(K, T), b: &(K, T)| a.0.cmp(&b.0).then_with(|| id(&a.1).cmp(id(&b.1))); + if limit == 0 { + return Vec::new(); + } + if items.len() > limit { + items.select_nth_unstable_by(limit - 1, cmp); + items.truncate(limit); + } + items.sort_unstable_by(cmp); + items +} + impl Store { /// Opens (or creates) the database file and runs schema setup. pub async fn open(path: &str) -> anyhow::Result<Self> { - // The FTS index method is gated behind this flag in turso 0.8. + // The FTS index method is gated behind this flag in turso 0.8. Search no longer + // uses the index, but databases made before still have one to drop. let db = turso::Builder::new_local(path) .experimental_index_method(true) .build() .await .with_context(|| format!("opening database at {path}"))?; let conn = db.connect()?; + // WAL with NORMAL sync: a commit no longer waits for an fsync, so a power loss can + // drop the last commits but never corrupts the database. Each note save is a commit. + conn.execute("PRAGMA synchronous = NORMAL", ()).await.context("setting synchronous")?; conn.execute_batch( "CREATE TABLE IF NOT EXISTS notes ( @@ -335,6 +824,17 @@ impl Store { upto_seq INTEGER NOT NULL, markdown TEXT NOT NULL ); + -- Export markdown of a snapshot, its note links left for the export to name. + CREATE TABLE IF NOT EXISTS export_text ( + note_id TEXT PRIMARY KEY, + upto_seq INTEGER NOT NULL, + markdown TEXT NOT NULL + ); + -- Imported markdown whose doc is not built yet: see hub::ensure_doc. + CREATE TABLE IF NOT EXISTS pending_docs ( + note_id TEXT PRIMARY KEY, + markdown TEXT NOT NULL + ); CREATE TABLE IF NOT EXISTS note_text ( note_id TEXT PRIMARY KEY, title TEXT NOT NULL, @@ -346,12 +846,13 @@ impl Store { frontiers BLOB NOT NULL, PRIMARY KEY(note_id, at) ); - CREATE INDEX IF NOT EXISTS note_text_fts ON note_text USING fts(title, body); + DROP INDEX IF EXISTS note_text_fts; CREATE TABLE IF NOT EXISTS note_links ( src TEXT NOT NULL, dst_id TEXT, dst_title TEXT ); + CREATE INDEX IF NOT EXISTS notebooks_name ON notebooks(name); CREATE INDEX IF NOT EXISTS note_links_src ON note_links(src); CREATE INDEX IF NOT EXISTS note_links_dst_id ON note_links(dst_id); CREATE INDEX IF NOT EXISTS note_links_dst_title ON note_links(dst_title);", @@ -374,20 +875,51 @@ impl Store { .context("adding notes.trashed_at")?; } - // Notes saved before note_text existed: copy their snapshot markdown once. - conn.execute( - "INSERT INTO note_text (note_id, title, body) - SELECT s.note_id, n.title, s.markdown FROM snapshots s - JOIN notes n ON n.id = s.note_id - WHERE NOT EXISTS (SELECT 1 FROM note_text t WHERE t.note_id = s.note_id)", - (), + // List queries filter on trashed_at and notebook_id and sort by updated_at. These + // indexes are created after the column migrations above, which they depend on. + conn.execute_batch( + "DROP INDEX IF EXISTS notes_trashed_updated; + DROP INDEX IF EXISTS notes_notebook_trashed_updated; + CREATE INDEX IF NOT EXISTS notes_trashed_updated_id ON notes(trashed_at, updated_at, id); + CREATE INDEX IF NOT EXISTS notes_notebook_trashed_updated_id ON notes(notebook_id, trashed_at, updated_at, id);", ) .await - .context("backfilling note_text")?; + .context("creating notes indexes")?; + + // Notes saved before note_text existed: copy their snapshot markdown, once per + // database (a scan of every snapshot, seconds at a million notes). + let mut rows = conn.query("PRAGMA user_version", ()).await?; + let version = match rows.next().await? { + Some(row) => int_col(&row, 0)?, + None => 0, + }; + drop(rows); + if version < 1 { + conn.execute( + "INSERT INTO note_text (note_id, title, body) + SELECT s.note_id, n.title, s.markdown FROM snapshots s + JOIN notes n ON n.id = s.note_id + WHERE NOT EXISTS (SELECT 1 FROM note_text t WHERE t.note_id = s.note_id)", + (), + ) + .await + .context("backfilling note_text")?; + conn.execute("PRAGMA user_version = 1", ()).await.context("setting user_version")?; + } + // Cached export markdown used to be checked against its snapshot on read. Now a + // new snapshot drops it, so what was cached before cannot be trusted. + if version < 2 { + conn.execute("DELETE FROM export_text", ()).await.context("clearing export_text")?; + conn.execute("PRAGMA user_version = 2", ()).await.context("setting user_version")?; + } Ok(Self { conn: Mutex::new(conn), - _db: db, + read: Mutex::new(db.connect()?), + dir: Mutex::new(None), + changes: std::sync::Mutex::new(Vec::new()), + heavy: std::sync::Mutex::new(HashMap::new()), + db, }) } @@ -401,6 +933,190 @@ impl Store { Ok(names) } + /// Records a committed write for the directory. + fn changed(&self, change: Change) { + self.changes.lock().unwrap().push(change); + } + + /// The directory, loaded if needed and with every recorded write applied. + async fn directory(&self) -> anyhow::Result<tokio::sync::MappedMutexGuard<'_, Directory>> { + let mut dir = self.dir.lock().await; + let result = self.refresh_directory(&mut dir).await; + if result.is_err() { + // Changes may have been taken without being applied: start over next time. + *dir = None; + } + result?; + Ok(tokio::sync::MutexGuard::map(dir, |d| d.as_mut().unwrap())) + } + + async fn refresh_directory(&self, dir: &mut Option<Directory>) -> anyhow::Result<()> { + const SELECT: &str = "SELECT n.id, n.title, n.created_at, n.updated_at, n.notebook_id, n.trashed_at, + COALESCE(t.body, '') + FROM notes n LEFT JOIN note_text t ON t.note_id = n.id"; + let select_changed = format!( + "SELECT n.id, n.title, n.created_at, n.updated_at, n.notebook_id, n.trashed_at, + CASE WHEN length(t.body) > {HEAVY_INDEX_BYTES} THEN NULL ELSE COALESCE(t.body, '') END + FROM notes n LEFT JOIN note_text t ON t.note_id = n.id" + ); + if dir.is_none() { + // Whatever was committed before this point is in the full read. + self.changes.lock().unwrap().clear(); + // Held while reading: no write lands between the read and the change log. + let conn = self.conn.lock().await; + let mut rows = conn.query("SELECT min(rowid), max(rowid) FROM notes", ()).await?; + let (first, last) = match rows.next().await? { + Some(row) => (row.get::<Option<i64>>(0)?.unwrap_or(0), row.get::<Option<i64>>(1)?.unwrap_or(0)), + None => (0, 0), + }; + drop(rows); + // Indexed in batches of a bounded size, as they are read: all the bodies may + // not fit in memory. Ranges of rows are read on their own connections at once. + let (tx, rx) = std::sync::mpsc::sync_channel::<Vec<(NoteMeta, String)>>(DIRECTORY_READERS); + let indexer = std::thread::spawn(move || { + let mut loaded = Directory::default(); + for batch in rx { + loaded.put_many(batch); + } + loaded + }); + let span = (last - first) / DIRECTORY_READERS as i64 + 1; + let mut readers = tokio::task::JoinSet::new(); + for k in 0..DIRECTORY_READERS as i64 { + let (reader, tx) = (self.db.connect()?, tx.clone()); + let (from, to) = (first + k * span, first + (k + 1) * span - 1); + readers.spawn(async move { + let mut rows = reader.query(format!("{SELECT} WHERE n.rowid BETWEEN ?1 AND ?2"), (from, to)).await?; + let (mut batch, mut bytes) = (Vec::new(), 0); + while let Some(row) = rows.next().await? { + let body = text_col(&row, 6)?; + bytes += body.len() + 200; + batch.push((note_from_row(&row)?, body)); + if bytes > DIRECTORY_BATCH_BYTES / DIRECTORY_READERS { + let full = std::mem::take(&mut batch); + tokio::task::block_in_place(|| tx.send(full))?; + bytes = 0; + } + } + tokio::task::block_in_place(|| tx.send(batch))?; + anyhow::Ok(()) + }); + } + drop(tx); + while let Some(read) = readers.join_next().await { + read??; + } + drop(conn); + let mut loaded = tokio::task::block_in_place(|| indexer.join()).map_err(|_| anyhow::anyhow!("indexing notes panicked"))?; + loaded.shrink(); + *dir = Some(loaded); + } + let changes = std::mem::take(&mut *self.changes.lock().unwrap()); + if changes.is_empty() { + return Ok(()); + } + let dir = dir.as_mut().unwrap(); + // A write landing meanwhile records its change again, for the next refresh. + let conn = self.read.lock().await; + // Changed notes are re-read in batches, each note once; a deleted notebook + // first needs the notes changed before it. + let mut ids: Vec<String> = Vec::new(); + let mut seen = std::collections::HashSet::new(); + for change in changes.into_iter().map(Some).chain([None]) { + match change { + Some(Change::Note(id)) => { + if seen.insert(id.clone()) { + ids.push(id); + } + continue; + } + Some(Change::NotebookGone(_)) | None => {} + } + for chunk in ids.chunks(PREVIEW_BATCH) { + let placeholders = (1..=chunk.len()).map(|i| format!("?{i}")).collect::<Vec<_>>().join(", "); + let mut rows = conn.query(format!("{select_changed} WHERE n.id IN ({placeholders})"), chunk.to_vec()).await?; + let mut found = std::collections::HashSet::new(); + let (mut batch, mut heavy) = (Vec::new(), Vec::new()); + while let Some(row) = rows.next().await? { + let meta = note_from_row(&row)?; + found.insert(meta.id.clone()); + match opt_text_col(&row, 6)? { + Some(body) => batch.push((meta, body)), + None => heavy.push(meta), + } + } + tokio::task::block_in_place(|| dir.put_many(batch)); + for meta in heavy { + self.heavy.lock().unwrap().insert(meta.id.clone(), std::time::Instant::now()); + dir.set_meta(meta); + } + for id in chunk.iter().filter(|id| !found.contains(*id)) { + dir.remove(id); + } + } + ids.clear(); + seen.clear(); + if let Some(Change::NotebookGone(id)) = change { + dir.unfile(&id); + } + } + Ok(()) + } + + /// Loads the directory, then keeps applying writes in the background, so a request + /// after a burst of writes (a big import) does not have to. + pub async fn keep_directory_fresh(&self) { + loop { + if let Err(err) = self.directory().await { + eprintln!("note directory refresh failed: {err:#}"); + } + if let Err(err) = self.index_heavy().await { + eprintln!("indexing a long note failed: {err:#}"); + } + tokio::time::sleep(std::time::Duration::from_millis(250)).await; + } + } + + /// Indexes the long notes the directory left for later: read on a connection of + /// their own and indexed with no lock held, then put in unless edited again since. + async fn index_heavy(&self) -> anyhow::Result<()> { + let ids: Vec<String> = { + let mut heavy = self.heavy.lock().unwrap(); + let quiet: Vec<String> = heavy.iter().filter(|(_, at)| at.elapsed() >= HEAVY_QUIET).map(|(id, _)| id.clone()).collect(); + for id in &quiet { + heavy.remove(id); + } + quiet + }; + for id in ids { + let conn = self.db.connect()?; + let mut rows = conn + .query( + "SELECT n.id, n.title, n.created_at, n.updated_at, n.notebook_id, n.trashed_at, COALESCE(t.body, '') + FROM notes n LEFT JOIN note_text t ON t.note_id = n.id WHERE n.id = ?1", + [id.as_str()], + ) + .await?; + let Some(row) = rows.next().await? else { continue }; + let (meta, body) = (note_from_row(&row)?, text_col(&row, 6)?); + drop((rows, conn)); + let updated_at = meta.updated_at; + // At the lowest priority: requests and doc builds go first. + let indexer = std::thread::spawn(move || { + let _ = thread_priority::set_current_thread_priority(thread_priority::ThreadPriority::Min); + directory::prepare_one(meta, body) + }); + let prepared = tokio::task::block_in_place(|| indexer.join()).map_err(|_| anyhow!("indexing a long note panicked"))?; + let mut dir = self.dir.lock().await; + if let Some(dir) = dir.as_mut() + && dir.updated_at(&id).is_some_and(|at| at <= updated_at) + { + tokio::task::block_in_place(|| dir.put_prepared(prepared)); + } + } + Ok(()) + } + pub async fn create_note(&self, notebook_id: Option<&str>) -> anyhow::Result<NoteMeta> { let now = now_millis(); let note = NoteMeta { @@ -424,6 +1140,7 @@ impl Store { ), ) .await?; + self.changed(Change::Note(note.id.clone())); Ok(note) } @@ -448,7 +1165,7 @@ impl Store { } pub async fn list_notebooks(&self) -> anyhow::Result<Vec<Notebook>> { - let conn = self.conn.lock().await; + let conn = self.read.lock().await; let mut rows = conn .query( "SELECT id, name, created_at FROM notebooks ORDER BY name COLLATE NOCASE, id", @@ -463,7 +1180,7 @@ impl Store { } pub async fn get_notebook(&self, id: &str) -> anyhow::Result<Option<Notebook>> { - let conn = self.conn.lock().await; + let conn = self.read.lock().await; let mut rows = conn .query( "SELECT id, name, created_at FROM notebooks WHERE id = ?1", @@ -498,6 +1215,7 @@ impl Store { tx.execute("DELETE FROM notebooks WHERE id = ?1", (id.to_string(),)) .await?; tx.commit().await?; + self.changed(Change::NotebookGone(id.to_owned())); Ok(()) } @@ -508,6 +1226,7 @@ impl Store { (note_id.to_string(), notebook_id.map(str::to_string)), ) .await?; + self.changed(Change::Note(note_id.to_owned())); Ok(()) } @@ -517,6 +1236,7 @@ impl Store { let tx = conn.transaction().await?; delete_note_rows(&tx, note_id).await?; tx.commit().await?; + self.changed(Change::Note(note_id.to_owned())); Ok(()) } @@ -529,6 +1249,7 @@ impl Store { (note_id.to_string(), now_millis()), ) .await?; + self.changed(Change::Note(note_id.to_owned())); Ok(()) } @@ -540,6 +1261,7 @@ impl Store { (note_id.to_string(),), ) .await?; + self.changed(Change::Note(note_id.to_owned())); Ok(()) } @@ -574,36 +1296,46 @@ impl Store { delete_note_rows(&tx, id).await?; } tx.commit().await?; + for id in &ids { + self.changed(Change::Note(id.clone())); + } Ok(ids) } - /// Trashed notes, most recently trashed first. - pub async fn list_trash(&self) -> anyhow::Result<Vec<NoteMeta>> { - let conn = self.conn.lock().await; - let mut rows = conn - .query( - "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes - WHERE trashed_at IS NOT NULL ORDER BY trashed_at DESC, id", - (), - ) - .await?; - let mut notes = Vec::new(); - while let Some(row) = rows.next().await? { - notes.push(note_from_row(&row)?); - } + /// Notes that are not in the trash, most recently updated first. + pub async fn list_notes(&self) -> anyhow::Result<Vec<NoteMeta>> { + let mut notes: Vec<NoteMeta> = self.directory().await?.live().iter().map(|e| e.meta()).collect(); + notes.sort_by(|a, b| b.updated_at.cmp(&a.updated_at).then_with(|| a.id.cmp(&b.id))); Ok(notes) } - /// Notes that are not in the trash, most recently updated first. - pub async fn list_notes(&self) -> anyhow::Result<Vec<NoteMeta>> { + /// The most recently updated note outside the trash whose `title_key` is `key`. + pub async fn note_by_title_key(&self, key: &str) -> anyhow::Result<Option<NoteMeta>> { + let dir = self.directory().await?; + Ok(dir + .entries() + .filter(|e| e.trashed_at.is_none() && title_key(e.title()) == key) + .max_by(|a, b| a.updated_at.cmp(&b.updated_at).then_with(|| b.id().cmp(a.id()))) + .map(|e| e.meta())) + } + + /// One page of the notes `filter` selects, in the order of the list: `limit` rows + /// after the first `offset`. + pub async fn list_notes_page( + &self, + filter: ListFilter, + limit: usize, + offset: usize, + ) -> anyhow::Result<Vec<NoteMeta>> { + let (clause, params) = filter.clause(); + // Both are plain numbers, so they are written into the SQL rather than bound. + let sql = format!( + "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes + WHERE {clause} ORDER BY {} LIMIT {limit} OFFSET {offset}", + filter.order() + ); let conn = self.conn.lock().await; - let mut rows = conn - .query( - "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes - WHERE trashed_at IS NULL ORDER BY updated_at DESC, id", - (), - ) - .await?; + let mut rows = conn.query(sql, params).await?; let mut notes = Vec::new(); while let Some(row) = rows.next().await? { notes.push(note_from_row(&row)?); @@ -611,8 +1343,33 @@ impl Store { Ok(notes) } + /// How many notes `filter` selects. + pub async fn count_filter(&self, filter: &ListFilter) -> anyhow::Result<usize> { + let dir = self.directory().await?; + let c = &dir.counts; + Ok(match filter { + ListFilter::All => c.live, + ListFilter::Unfiled => c.unfiled, + ListFilter::Notebook(id) => c.notebooks.get(id).copied().unwrap_or(0), + ListFilter::Trash => c.trashed, + }) + } + + /// Counts for the sidebar: notes outside the trash, notes outside the trash in no + /// notebook, and trashed notes. + pub async fn count_notes(&self) -> anyhow::Result<(usize, usize, usize)> { + let dir = self.directory().await?; + Ok((dir.counts.live, dir.counts.unfiled, dir.counts.trashed)) + } + + /// Number of notes outside the trash in each notebook, keyed by notebook id. Notebooks + /// with no notes are absent. + pub async fn notebook_counts(&self) -> anyhow::Result<HashMap<String, usize>> { + Ok(self.directory().await?.counts.notebooks.clone()) + } + pub async fn get_note(&self, id: &str) -> anyhow::Result<Option<NoteMeta>> { - let conn = self.conn.lock().await; + let conn = self.read.lock().await; let mut rows = conn .query( "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes WHERE id = ?1", @@ -644,6 +1401,9 @@ impl Store { .await?; } tx.commit().await?; + if inserted > 0 { + self.changed(Change::Note(note_id.to_owned())); + } Ok(()) } @@ -652,13 +1412,13 @@ impl Store { let mut rows = conn .query( - "SELECT data, upto_seq FROM snapshots WHERE note_id = ?1", + "SELECT data, upto_seq, markdown FROM snapshots WHERE note_id = ?1", (note_id.to_string(),), ) .await?; - let (snapshot, upto_seq) = match rows.next().await? { - Some(row) => (Some(blob_col(&row, 0)?), int_col(&row, 1)?), - None => (None, 0), + let (snapshot, upto_seq, markdown) = match rows.next().await? { + Some(row) => (Some(blob_col(&row, 0)?), int_col(&row, 1)?, opt_text_col(&row, 2)?), + None => (None, 0, None), }; drop(rows); @@ -673,47 +1433,291 @@ impl Store { updates.push(blob_col(&row, 0)?); } - Ok(DocBytes { snapshot, updates }) + drop(rows); + let markdown = match snapshot { + Some(_) => markdown.filter(|_| updates.is_empty()), + None => { + let mut rows = conn + .query("SELECT markdown FROM pending_docs WHERE note_id = ?1", (note_id.to_string(),)) + .await?; + match rows.next().await? { + Some(row) => Some(text_col(&row, 0)?), + None => None, + } + } + }; + Ok(DocBytes { snapshot, updates, markdown, export: None, upto_seq }) + } + + /// [`load_doc`](Self::load_doc) for many notes, in the order of `ids`, with a few + /// queries per `PREVIEW_BATCH` notes rather than two per note. + /// The stored state of each of `ids`, for the export: a note whose export markdown + /// is cached for its snapshot comes without the snapshot, and so does one whose + /// stored markdown is current, unless it is in `linking`. + pub async fn load_docs(&self, ids: &[String], linking: &std::collections::HashSet<String>) -> anyhow::Result<Vec<DocBytes>> { + let empty = || DocBytes { snapshot: None, updates: Vec::new(), markdown: None, export: None, upto_seq: 0 }; + let mut docs: HashMap<String, DocBytes> = HashMap::new(); + let conn = self.conn.lock().await; + for chunk in ids.chunks(PREVIEW_BATCH) { + let placeholders = (1..=chunk.len()).map(|i| format!("?{i}")).collect::<Vec<_>>().join(", "); + let mut rows = conn + .query( + format!( + "SELECT s.note_id, s.upto_seq, CASE WHEN e.markdown IS NULL THEN s.markdown END, e.markdown, CASE WHEN e.markdown IS NULL AND s.markdown IS NULL THEN s.data END + FROM snapshots s LEFT JOIN export_text e ON e.note_id = s.note_id AND e.upto_seq = s.upto_seq + WHERE s.note_id IN ({placeholders})" + ), + chunk.to_vec(), + ) + .await?; + while let Some(row) = rows.next().await? { + let export = opt_text_col(&row, 3)?; + let snapshot = opt_blob_col(&row, 4)?; + let doc = DocBytes { snapshot, updates: Vec::new(), markdown: opt_text_col(&row, 2)?, export, upto_seq: int_col(&row, 1)? }; + docs.insert(text_col(&row, 0)?, doc); + } + drop(rows); + let mut rows = conn + .query( + format!("SELECT note_id, seq, data FROM updates WHERE note_id IN ({placeholders}) ORDER BY seq"), + chunk.to_vec(), + ) + .await?; + while let Some(row) = rows.next().await? { + let id = text_col(&row, 0)?; + let doc = docs.entry(id).or_insert_with(empty); + if int_col(&row, 1)? > doc.upto_seq { + doc.updates.push(blob_col(&row, 2)?); + doc.markdown = None; + doc.export = None; + } + } + drop(rows); + // Edited since its markdown was stored, or linking: the snapshot is needed after all. + let stale: Vec<String> = chunk + .iter() + .filter(|id| { + docs.get(*id).is_some_and(|d| { + d.snapshot.is_none() && d.export.is_none() && (d.markdown.is_none() || linking.contains(*id)) + }) + }) + .cloned() + .collect(); + for id in stale { + let mut rows = conn.query("SELECT data FROM snapshots WHERE note_id = ?1", (id.clone(),)).await?; + if let Some(row) = rows.next().await? { + docs.get_mut(&id).unwrap().snapshot = Some(blob_col(&row, 0)?); + } + } + let mut rows = conn + .query( + format!("SELECT note_id, markdown FROM pending_docs WHERE note_id IN ({placeholders})"), + chunk.to_vec(), + ) + .await?; + while let Some(row) = rows.next().await? { + docs.insert(text_col(&row, 0)?, DocBytes { markdown: Some(text_col(&row, 1)?), ..empty() }); + } + } + Ok(ids.iter().map(|id| docs.remove(id).unwrap_or_else(empty)).collect()) + } + + /// Streams every cached export markdown that is current for its snapshot, as + /// `(note id, markdown)` batches of about `batch_bytes`, read on a connection of its + /// own so other requests go on meanwhile. A note edited since its snapshot may + /// still come: see [`Store::stale_snapshots`]. + pub fn scan_export_texts(&self, batch_bytes: usize) -> anyhow::Result<mpsc::Receiver<anyhow::Result<Vec<(String, String)>>>> { + let conn = self.db.connect()?; + let (tx, rx) = mpsc::channel(2); + tokio::spawn(async move { + let result = async { + let mut rows = conn + .query( + // Joining snapshots would read their blobs: a new snapshot drops + // the row instead (see put_snapshot). + "SELECT note_id, markdown FROM export_text", + (), + ) + .await?; + let (mut batch, mut bytes) = (Vec::new(), 0); + while let Some(row) = rows.next().await? { + let md = text_col(&row, 1)?; + bytes += md.len() + 64; + batch.push((text_col(&row, 0)?, md)); + if bytes > batch_bytes { + bytes = 0; + if tx.send(Ok(std::mem::take(&mut batch))).await.is_err() { + return Ok(()); + } + } + } + let _ = tx.send(Ok(batch)).await; + anyhow::Ok(()) + } + .await; + if let Err(err) = result { + let _ = tx.send(Err(err)).await; + } + }); + Ok(rx) + } + + /// Caches export markdown (see [`DocBytes::export`]) as `(note id, snapshot's last + /// update, markdown)`. + pub async fn put_export_texts(&self, texts: &[(String, i64, String)]) -> anyhow::Result<()> { + let mut conn = self.conn.lock().await; + let tx = conn.transaction().await?; + for (id, upto_seq, markdown) in texts { + // A newer snapshot may have been written since this was rendered. + let mut rows = tx.query("SELECT upto_seq FROM snapshots WHERE note_id = ?1", (id.clone(),)).await?; + let current = match rows.next().await? { + Some(row) => int_col(&row, 0)? == *upto_seq, + None => false, + }; + drop(rows); + if !current { + continue; + } + tx.execute( + "INSERT INTO export_text (note_id, upto_seq, markdown) VALUES (?1, ?2, ?3) + ON CONFLICT(note_id) DO UPDATE SET upto_seq = excluded.upto_seq, markdown = excluded.markdown", + (id.clone(), *upto_seq, markdown.clone()), + ) + .await?; + } + tx.commit().await?; + Ok(()) + } + + /// Notes with updates newer than their snapshot: a snapshot was due when the server + /// stopped. Their docs load slower until a new snapshot covers them. + pub async fn stale_snapshots(&self) -> anyhow::Result<Vec<String>> { + // Two plain reads: turso scans every update for each note when they are joined. + let conn = self.conn.lock().await; + let mut rows = conn.query("SELECT note_id, seq FROM updates", ()).await?; + let mut newest: HashMap<String, i64> = HashMap::new(); + while let Some(row) = rows.next().await? { + let seq = int_col(&row, 1)?; + let max = newest.entry(text_col(&row, 0)?).or_insert(seq); + *max = (*max).max(seq); + } + drop(rows); + let ids: Vec<String> = newest.keys().cloned().collect(); + for chunk in ids.chunks(PREVIEW_BATCH) { + let placeholders = (1..=chunk.len()).map(|i| format!("?{i}")).collect::<Vec<_>>().join(", "); + let mut rows = conn + .query(format!("SELECT note_id, upto_seq FROM snapshots WHERE note_id IN ({placeholders})"), chunk.to_vec()) + .await?; + while let Some(row) = rows.next().await? { + let id = text_col(&row, 0)?; + if newest.get(&id).is_some_and(|max| *max <= int_col(&row, 1).unwrap_or(0)) { + newest.remove(&id); + } + } + } + Ok(newest.into_keys().collect()) + } + + /// The newest stored update's sequence number for the note, 0 when there is none. + pub async fn max_seq(&self, note_id: &str) -> anyhow::Result<i64> { + let conn = self.conn.lock().await; + let mut rows = conn + .query("SELECT COALESCE(MAX(seq), 0) FROM updates WHERE note_id = ?1", (note_id.to_string(),)) + .await?; + match rows.next().await? { + Some(row) => int_col(&row, 0), + None => Ok(0), + } + } + + /// Whether the note's stored text links to other notes. + pub async fn has_links(&self, note_id: &str) -> anyhow::Result<bool> { + let conn = self.read.lock().await; + let mut rows = conn + .query("SELECT 1 FROM note_links WHERE src = ?1 LIMIT 1", (note_id.to_string(),)) + .await?; + Ok(rows.next().await?.is_some()) + } + + /// Every note whose stored text links to other notes. + pub async fn linking_notes(&self) -> anyhow::Result<std::collections::HashSet<String>> { + let conn = self.conn.lock().await; + // Deduplicated here: turso's DISTINCT spills and thrashes on millions of rows. + let mut rows = conn.query("SELECT src FROM note_links", ()).await?; + let mut out = std::collections::HashSet::new(); + while let Some(row) = rows.next().await? { + out.insert(text_col(&row, 0)?); + } + Ok(out) + } + + /// Ids of the notes some note links to. + pub async fn link_targets(&self) -> anyhow::Result<std::collections::HashSet<String>> { + let conn = self.conn.lock().await; + let mut rows = conn.query("SELECT dst_id FROM note_links WHERE dst_id IS NOT NULL", ()).await?; + let mut out = std::collections::HashSet::new(); + while let Some(row) = rows.next().await? { + out.insert(text_col(&row, 0)?); + } + Ok(out) } - /// Stores a full snapshot plus the derived markdown and title. - /// Updates are never deleted; later loads only read updates newer than the snapshot. + /// Titles of the given notes that are outside the trash, by id. + pub async fn titles_of(&self, ids: impl IntoIterator<Item = String>) -> anyhow::Result<HashMap<String, String>> { + let dir = self.directory().await?; + Ok(ids + .into_iter() + .filter_map(|id| { + let e = dir.get(&id).filter(|e| e.trashed_at.is_none())?; + Some((id, e.title().to_owned())) + }) + .collect()) + } + + /// Stores a full snapshot that holds every update up to `upto_seq`, plus the derived + /// markdown and title. A snapshot older than the stored one is ignored, and so is + /// the result `false`. Updates are never deleted; later loads only read updates + /// newer than the snapshot. pub async fn put_snapshot( &self, note_id: &str, - snapshot: &[u8], + snapshot: Vec<u8>, + upto_seq: i64, markdown: &str, title: &str, - ) -> anyhow::Result<()> { + ) -> anyhow::Result<bool> { let mut conn = self.conn.lock().await; let tx = conn.transaction().await?; + // Only a snapshot at least as new replaces the stored one. Delete, then insert: + // an upsert reads the old row whole, and a huge note's row is hundreds of MB. let mut rows = tx - .query( - "SELECT COALESCE(MAX(seq), 0) FROM updates WHERE note_id = ?1", - (note_id.to_string(),), - ) + .query("SELECT upto_seq FROM snapshots WHERE note_id = ?1", (note_id.to_string(),)) .await?; - let max_seq = match rows.next().await? { - Some(row) => int_col(&row, 0)?, - None => 0, + let stored = match rows.next().await? { + Some(row) => Some(int_col(&row, 0)?), + None => None, }; drop(rows); - + if stored.is_some_and(|stored| stored > upto_seq) { + return Ok(false); + } + if stored.is_some() { + tx.execute("DELETE FROM snapshots WHERE note_id = ?1", (note_id.to_string(),)).await?; + } tx.execute( - "INSERT INTO snapshots (note_id, data, upto_seq, markdown) VALUES (?1, ?2, ?3, ?4) - ON CONFLICT(note_id) DO UPDATE SET - data = excluded.data, - upto_seq = excluded.upto_seq, - markdown = excluded.markdown", + "INSERT INTO snapshots (note_id, data, upto_seq, markdown) VALUES (?1, ?2, ?3, ?4)", ( note_id.to_string(), - snapshot.to_vec(), - max_seq, + snapshot, + upto_seq, markdown.to_string(), ), ) .await?; + // The snapshot holds every op of the updates up to it. + tx.execute("DELETE FROM updates WHERE note_id = ?1 AND seq <= ?2", (note_id.to_string(), upto_seq)).await?; + tx.execute("DELETE FROM export_text WHERE note_id = ?1 AND upto_seq <> ?2", (note_id.to_string(), upto_seq)).await?; tx.execute( "UPDATE notes SET title = ?2 WHERE id = ?1", (note_id.to_string(), title.to_string()), @@ -721,7 +1725,8 @@ impl Store { .await?; tx.commit().await?; - Ok(()) + self.changed(Change::Note(note_id.to_owned())); + Ok(true) } pub async fn set_title(&self, note_id: &str, title: &str) -> anyhow::Result<()> { @@ -731,13 +1736,14 @@ impl Store { (note_id.to_string(), title.to_string()), ) .await?; + self.changed(Change::Note(note_id.to_owned())); Ok(()) } - /// Upserts the searchable text of a note. Does nothing when the note no longer + /// Writes the searchable text of a note. Does nothing when the note no longer /// exists, so a flush that races a delete cannot bring the text back. pub async fn put_text(&self, note_id: &str, title: &str, body: &str) -> anyhow::Result<()> { - let conn = self.conn.lock().await; + let mut conn = self.conn.lock().await; let mut rows = conn .query("SELECT 1 FROM notes WHERE id = ?1", (note_id.to_string(),)) .await?; @@ -746,12 +1752,16 @@ impl Store { if !exists { return Ok(()); } - conn.execute( - "INSERT INTO note_text (note_id, title, body) VALUES (?1, ?2, ?3) - ON CONFLICT(note_id) DO UPDATE SET title = excluded.title, body = excluded.body", + // Delete, then insert: an upsert reads the old row whole. + let tx = conn.transaction().await?; + tx.execute("DELETE FROM note_text WHERE note_id = ?1", (note_id.to_string(),)).await?; + tx.execute( + "INSERT INTO note_text (note_id, title, body) VALUES (?1, ?2, ?3)", (note_id.to_string(), title.to_string(), body.to_string()), ) .await?; + tx.commit().await?; + self.changed(Change::Note(note_id.to_owned())); Ok(()) } @@ -770,36 +1780,159 @@ impl Store { let tx = conn.transaction().await?; tx.execute("DELETE FROM note_links WHERE src = ?1", (src.to_string(),)) .await?; - for target in targets { - match target { - LinkTarget::Id(id) => { + insert_links(&tx, src, targets).await?; + tx.commit().await?; + Ok(()) + } + + /// Creates a note from imported content in one transaction: the note row in the + /// notebook named `notebook` (matched case-insensitively, created when missing), + /// its snapshot, searchable text, links and export markdown (see [`DocBytes::export`]). + /// Returns the note id. + pub async fn import_note( + &self, + notebook: Option<&str>, + snapshot: Option<&[u8]>, + title: &str, + body: &str, + links: &[LinkTarget], + export: Option<&str>, + ) -> anyhow::Result<String> { + let mut conn = self.conn.lock().await; + let tx = conn.transaction().await?; + let notebook_id = match notebook { + Some(name) => Some(match find_notebook(&tx, name).await? { + Some(id) => id, + None => { + let id = uuid::Uuid::now_v7().to_string(); tx.execute( - "INSERT INTO note_links (src, dst_id, dst_title) VALUES (?1, ?2, NULL)", - (src.to_string(), id.clone()), + "INSERT INTO notebooks (id, name, created_at) VALUES (?1, ?2, ?3)", + (id.clone(), name.to_string(), now_millis()), ) .await?; + id } - LinkTarget::Title(title) => { - let key = title_key(title); - if key.is_empty() { - continue; - } + }), + None => None, + }; + let id = uuid::Uuid::now_v7().to_string(); + let now = now_millis(); + tx.execute( + "INSERT INTO notes (id, title, created_at, updated_at, notebook_id) VALUES (?1, ?2, ?3, ?4, ?5)", + (id.clone(), title.to_string(), now, now, notebook_id), + ) + .await?; + match snapshot { + Some(snapshot) => { + tx.execute( + "INSERT INTO snapshots (note_id, data, upto_seq, markdown) VALUES (?1, ?2, 0, ?3)", + (id.clone(), snapshot.to_vec(), body.to_string()), + ) + .await?; + if let Some(export) = export { tx.execute( - "INSERT INTO note_links (src, dst_id, dst_title) VALUES (?1, NULL, ?2)", - (src.to_string(), key), + "INSERT INTO export_text (note_id, upto_seq, markdown) VALUES (?1, 0, ?2)", + (id.clone(), export.to_string()), ) .await?; } } + None => { + tx.execute("INSERT INTO pending_docs (note_id, markdown) VALUES (?1, ?2)", (id.clone(), body.to_string())) + .await?; + } } + tx.execute( + "INSERT INTO note_text (note_id, title, body) VALUES (?1, ?2, ?3)", + (id.clone(), title.to_string(), body.to_string()), + ) + .await?; + insert_links(&tx, &id, links).await?; tx.commit().await?; + self.changed(Change::Note(id.clone())); + Ok(id) + } + + /// Notes imported without a doc yet, oldest first. + pub async fn pending_docs(&self) -> anyhow::Result<Vec<String>> { + let conn = self.conn.lock().await; + let mut rows = conn.query("SELECT note_id FROM pending_docs ORDER BY note_id", ()).await?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await? { + out.push(text_col(&row, 0)?); + } + Ok(out) + } + + /// The first `bytes` bytes or so of a pending note's markdown, cut at a line end. + pub async fn pending_head(&self, note_id: &str, bytes: usize) -> anyhow::Result<Option<String>> { + let conn = self.read.lock().await; + let mut rows = conn + .query( + "SELECT substr(markdown, 1, ?2) FROM pending_docs WHERE note_id = ?1", + (note_id.to_string(), bytes as i64), + ) + .await?; + let Some(row) = rows.next().await? else { return Ok(None) }; + let mut head = text_col(&row, 0)?; + if head.len() >= bytes + && let Some(end) = head.rfind('\n') + { + head.truncate(end + 1); + } + Ok(Some(head)) + } + + /// The imported markdown of a note whose doc is not built yet. + pub async fn pending_markdown(&self, note_id: &str) -> anyhow::Result<Option<String>> { + let conn = self.conn.lock().await; + let mut rows = conn + .query("SELECT markdown FROM pending_docs WHERE note_id = ?1", (note_id.to_string(),)) + .await?; + match rows.next().await? { + Some(row) => Ok(Some(text_col(&row, 0)?)), + None => Ok(None), + } + } + + /// Replaces a pending note's markdown with its built doc, and the text derived from + /// it. Does nothing when the note is gone or no longer pending. + pub async fn finish_pending( + &self, + note_id: &str, + snapshot: &[u8], + title: &str, + body: &str, + links: &[LinkTarget], + ) -> anyhow::Result<()> { + let mut conn = self.conn.lock().await; + let tx = conn.transaction().await?; + let id = note_id.to_string(); + if tx.execute("DELETE FROM pending_docs WHERE note_id = ?1", (id.clone(),)).await? == 0 { + return Ok(()); + } + tx.execute( + "INSERT INTO snapshots (note_id, data, upto_seq, markdown) VALUES (?1, ?2, 0, ?3)", + (id.clone(), snapshot.to_vec(), body.to_string()), + ) + .await?; + tx.execute("UPDATE notes SET title = ?2 WHERE id = ?1", (id.clone(), title.to_string())).await?; + tx.execute( + "UPDATE note_text SET title = ?2, body = ?3 WHERE note_id = ?1", + (id.clone(), title.to_string(), body.to_string()), + ) + .await?; + tx.execute("DELETE FROM note_links WHERE src = ?1", (id.clone(),)).await?; + insert_links(&tx, note_id, links).await?; + tx.commit().await?; + self.changed(Change::Note(id)); Ok(()) } /// Non-trashed notes, other than `note_id`, that link to the note by its id or by /// its title. Most recently updated first. pub async fn backlinks(&self, note_id: &str, title: &str) -> anyhow::Result<Vec<NoteMeta>> { - let conn = self.conn.lock().await; + let conn = self.read.lock().await; let mut rows = conn .query( "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes @@ -819,58 +1952,178 @@ impl Store { /// Search over titles and bodies with `matcher` (see [`crate::matcher`]): every term /// must match the title or the text. Closest matches first, then more terms in the /// title, then most recently updated. - pub async fn search(&self, matcher: &Matcher, limit: usize) -> anyhow::Result<Vec<SearchHit>> { + /// + /// Long notes are matched against their stored text, which for a pattern without a + /// literal means reading all of it. With a `budget`, that stops once the budget is + /// spent, and the result says it is partial: the best hits found so far. + pub async fn search(&self, matcher: &Matcher, limit: usize, budget: Option<std::time::Duration>) -> anyhow::Result<Searched> { if limit == 0 { - return Ok(Vec::new()); + return Ok(Searched::default()); } - // A scan rather than the FTS index: the index matches whole words only, and - // typing "asd" has to find "asdadasxd" (and "isik" find "Işık"). - let conn = self.conn.lock().await; - let mut rows = conn - .query( - "SELECT n.id, n.title, n.created_at, n.updated_at, n.notebook_id, n.trashed_at, - COALESCE(t.body, '') - FROM notes n LEFT JOIN note_text t ON t.note_id = n.id - WHERE n.trashed_at IS NULL", - (), - ) - .await?; - let mut hits = Vec::new(); - while let Some(row) = rows.next().await? { - let note = note_from_row(&row)?; - let body = text_col(&row, 6)?; - let in_title = matcher.term_costs(¬e.title); - let in_text = matcher.term_costs(&plain_text(&body)); - // Each term matches the title or the text, whichever is closer. Cheaper - // matches first (exact before typos), then more terms in the title. - let mut cost = 0; - let mut title_terms = 0; - let mut matched = true; - for (t, x) in in_title.into_iter().zip(in_text) { - match (t, x) { - (Some(t), Some(x)) if t <= x => (cost += t, title_terms += 1), - (Some(t), None) => (cost += t, title_terms += 1), - (_, Some(x)) => (cost += x, ()), - (None, None) => { - matched = false; - break; + let started = std::time::Instant::now(); + // Words are matched rather than looked up: typing "asd" has to find "asdadasxd" + // (and "isik" find "Işık"). The directory is read in place, on this worker. + let dir = self.directory().await?; + let (mut hits, cut) = tokio::task::block_in_place(|| { + let hits = match_top(matcher, dir.slots(), &dir.vocab, limit); + // With the least each can cost: no cost, unless the words say otherwise. + let mut cut: Vec<(Arc<Entry>, usize)> = match matcher.word_terms() { + Some(_) => Vec::new(), + None => dir.entries().filter(|e| e.plain_cut && e.trashed_at.is_none()).map(|e| (e.clone(), 0)).collect(), + }; + // Notes without the words a match needs are not read. An exact phrase costs + // nothing only where its first word starts a word. + if let Some(alts) = matcher.required_words().filter(|_| !cut.is_empty()) { + let vocab = dir.vocab.read().unwrap(); + let mask = |piece: &[char], part: Part| (0..vocab.len()).map(|id| part.holds(vocab.word(id), piece)).collect::<Vec<bool>>(); + let holds: Vec<Vec<Vec<bool>>> = alts.iter().map(|words| words.iter().map(|(piece, part)| mask(piece, *part)).collect()).collect(); + let starts = matches!(matcher, Matcher::Terms { .. }).then(|| match &alts[0][0] { + (piece, Part::End) => mask(piece, Part::Whole), + (piece, Part::Inside) => mask(piece, Part::Start), + _ => holds[0][0].clone(), + }); + drop(vocab); + let has = |e: &Entry, h: &[bool]| e.text_words().iter().any(|&id| h[id as usize]); + cut.retain(|(e, _)| holds.iter().any(|alt| alt.iter().all(|h| has(e, h) || e.title_words().iter().any(|&id| h[id as usize])))); + if let Some(starts) = starts { + for (e, floor) in &mut cut { + *floor = usize::from(!has(e, &starts)); } - }; + } } - if !matched { - continue; + // A regex that only matches inside words needs a word it matches. + if let Some(re) = matcher.word_regex().filter(|_| !cut.is_empty()) { + let vocab = dir.vocab.read().unwrap(); + let mut word = String::new(); + let hits: Vec<bool> = (0..vocab.len()) + .map(|id| { + word.clear(); + word.extend(vocab.word(id).iter()); + re.is_match(&word) + }) + .collect(); + drop(vocab); + cut.retain(|(e, _)| e.text_words().iter().chain(e.title_words()).any(|&id| hits[id as usize])); } - hits.push(( - (cost, std::cmp::Reverse(title_terms)), - SearchHit { - snippet: snippet(&body, matcher), - note, - }, - )); + (hits, cut) + }); + drop(dir); + // Long notes keep only their start in memory: match them against their stored + // text, a few at a time, and keep the text of those that match for the snippet. + // The best key each could get, from its title: the text matching at no cost. + // Going from the best bound, the rest can stop once `limit` hits beat it. + let bound = |e: &Entry, floor: usize| -> RankKey { + let in_title = matcher.term_costs(e.title()); + let zero = in_title.iter().filter(|c| **c == Some(0)).count(); + let cost = in_title.iter().map(|c| if *c == Some(0) { 0 } else { floor }).sum(); + ((cost, std::cmp::Reverse(zero)), std::cmp::Reverse(e.updated_at)) + }; + let mut cut: Vec<(RankKey, Arc<Entry>, usize)> = cut.into_iter().map(|(e, floor)| (bound(&e, floor), e, floor)).collect(); + cut.sort_unstable_by(|a, b| a.0.cmp(&b.0)); + // The start of each is in memory: its full text is read, on a connection of its + // own, only when the start does not settle the match. + let per_batch = std::thread::available_parallelism().map_or(1, |n| n.get()); + let (want, mut wanted) = (mpsc::channel::<Vec<String>>(1), mpsc::channel::<anyhow::Result<HashMap<String, String>>>(1)); + let (mut requests, answers) = (want.1, wanted.0); + // One connection reads some 1.5 GB/s: a few share each batch. + let readers: Vec<Arc<turso::Connection>> = (0..SEARCH_READERS).map(|_| self.db.connect().map(Arc::new)).collect::<Result<_, _>>()?; + tokio::spawn(async move { + while let Some(ids) = requests.recv().await { + let parts = ids.chunks(ids.len().div_ceil(readers.len()).max(1)).zip(&readers).map(|(part, conn)| { + let (part, conn) = (part.to_vec(), conn.clone()); + tokio::spawn(async move { bodies_on(&conn, &part).await }) + }); + let mut bodies = HashMap::new(); + let mut result = Ok(()); + for part in parts.collect::<Vec<_>>() { + match part.await.map_err(anyhow::Error::from).and_then(|r| r) { + Ok(b) => bodies.extend(b), + Err(e) => result = Err(e), + } + } + if answers.send(result.map(|_| bodies)).await.is_err() { + return; + } + } + }); + let ask = want.0; + let mut snippets: HashMap<String, String> = HashMap::new(); + type Found = Option<(SearchKey, String)>; + let par = |f: &(dyn Fn(&(Arc<Entry>, usize)) -> (Found, bool) + Sync), entries: &[(Arc<Entry>, usize)]| { + tokio::task::block_in_place(|| { + std::thread::scope(|scope| { + let handles: Vec<_> = entries.iter().map(|e| scope.spawn(move || f(e))).collect(); + handles.into_iter().map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect::<Vec<_>>() + }) + }) + }; + let from_bodies = |bodies: &HashMap<String, String>, entries: &[(Arc<Entry>, usize)]| -> Vec<Found> { + par(&|(e, floor)| (bodies.get(e.id()).and_then(|body| match_long(e.title(), body, matcher, *floor)), true), entries) + .into_iter() + .map(|(found, _)| found) + .collect() + }; + let mut found_in = |entries: Vec<(Arc<Entry>, usize)>, found: Vec<Found>, hits: &mut Vec<(RankKey, Arc<Entry>)>| { + for ((e, _), found) in entries.into_iter().zip(found) { + if let Some((k, snip)) = found { + snippets.insert(e.id().to_owned(), snip); + hits.push(((k, std::cmp::Reverse(e.updated_at)), e)); + } + } + }; + // The notes whose texts were asked for: the next batch is read while they are + // matched. + let mut asked: Vec<(Arc<Entry>, usize)> = Vec::new(); + let mut partial = false; + for batch in cut.chunks(per_batch) { + if budget.is_some_and(|b| started.elapsed() >= b) { + partial = true; + break; + } + if hits.len() >= limit { + hits = top_keyed(hits, limit, |e| e.id()); + if hits.last().is_some_and(|(k, _)| *k < batch[0].0) { + break; + } + } + let entries: Vec<(Arc<Entry>, usize)> = batch.iter().map(|(_, e, floor)| (e.clone(), *floor)).collect(); + let from_start = par(&|(e, floor)| match_pieces(e.title(), plain_pieces(e.plain()), matcher, *floor), &entries); + let (mut settled, mut settled_found, mut unsettled) = (Vec::new(), Vec::new(), Vec::new()); + for (e, (found, perfect)) in entries.into_iter().zip(from_start) { + if perfect { + settled.push(e); + settled_found.push(found); + } else { + unsettled.push(e); + } + } + found_in(settled, settled_found, &mut hits); + if !unsettled.is_empty() { + ask.send(unsettled.iter().map(|(e, _)| e.id().to_owned()).collect()).await?; + } + let previous = std::mem::replace(&mut asked, unsettled); + if !previous.is_empty() { + let bodies = wanted.1.recv().await.context("reading note texts")??; + let found = from_bodies(&bodies, &previous); + found_in(previous, found, &mut hits); + } + } + // Out of time: the batch still being read is left unread. + if !asked.is_empty() && !partial { + let bodies = wanted.1.recv().await.context("reading note texts")??; + let found = from_bodies(&bodies, &asked); + found_in(asked, found, &mut hits); } - hits.sort_by(|a, b| a.0.cmp(&b.0).then(b.1.note.updated_at.cmp(&a.1.note.updated_at))); - hits.truncate(limit); - Ok(hits.into_iter().map(|(_, hit)| hit).collect()) + let hits = top(hits, limit, |e| e.id()); + // Snippets only for the hits shown: a common word matches nearly every note. + let hits = hits + .into_iter() + .map(|e| SearchHit { + snippet: snippets.remove(e.id()).unwrap_or_else(|| snippet(e.plain(), matcher)), + note: e.meta(), + }) + .collect(); + Ok(Searched { hits, partial }) } /// Notes, not in the trash, whose title holds every word of `query`, typos allowed @@ -884,37 +2137,23 @@ impl Store { } // Matched in Rust, not with SQL LIKE, which folds only ASCII case and has no // typo tolerance: "izmir" and "izmr" have to find "İzmir". - let conn = self.conn.lock().await; - let mut rows = conn - .query( - "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes - WHERE trashed_at IS NULL ORDER BY updated_at DESC, id", - (), - ) - .await?; - let mut notes = Vec::new(); - while let Some(row) = rows.next().await? { - let note = note_from_row(&row)?; - if let Some(cost) = matcher.cost(¬e.title) { - notes.push((cost, note)); - } - } - // Stable: equal costs stay most recent first. - notes.sort_by_key(|(cost, _)| *cost); - notes.truncate(limit); - Ok(notes.into_iter().map(|(_, note)| note).collect()) + let dir = self.directory().await?; + // Closest first, then most recently updated. + let hits = tokio::task::block_in_place(|| { + let terms = matcher.word_terms().unwrap_or_default(); + let tables = word_costs(&matcher, terms, &dir.vocab.read().unwrap()); + par_top(dir.slots(), limit, |e| { + let cost = tables.iter().map(|t| best_cost(t, e.title_words())).sum::<Option<usize>>()?; + Some((cost, std::cmp::Reverse(e.updated_at))) + }) + }); + Ok(hits.into_iter().map(|e| e.meta()).collect()) } - /// Previews of every note's text, keyed by note id, for list rows. Trashed notes are - /// included; callers look up only the notes they show. - pub async fn previews(&self) -> anyhow::Result<HashMap<String, String>> { - let conn = self.conn.lock().await; - let mut rows = conn.query("SELECT note_id, body FROM note_text", ()).await?; - let mut previews = HashMap::new(); - while let Some(row) = rows.next().await? { - previews.insert(text_col(&row, 0)?, preview(&text_col(&row, 1)?)); - } - Ok(previews) + /// Previews of the given notes' text, keyed by note id, for list rows. + pub async fn previews_for(&self, ids: &[String]) -> anyhow::Result<HashMap<String, String>> { + let dir = self.directory().await?; + Ok(ids.iter().filter_map(|id| Some((id.clone(), dir.get(id)?.preview().to_string()))).collect()) } /// Stores a version of a note: the time in millis and the encoded frontiers of the doc. @@ -958,19 +2197,25 @@ impl Store { None => Ok(None), } } +} - pub async fn get_markdown(&self, note_id: &str) -> anyhow::Result<Option<String>> { - let conn = self.conn.lock().await; - let mut rows = conn - .query( - "SELECT markdown FROM snapshots WHERE note_id = ?1", - (note_id.to_string(),), - ) - .await?; - match rows.next().await? { - Some(row) => Ok(Some(text_col(&row, 0)?)), - None => Ok(None), - } + +#[cfg(test)] +mod tests { + use super::Store; + + #[tokio::test] + async fn older_snapshot_does_not_replace_newer() { + let dir = std::env::temp_dir().join(format!("note-test-{}", uuid::Uuid::now_v7())); + std::fs::create_dir_all(&dir).unwrap(); + let store = Store::open(dir.join("t.db").to_str().unwrap()).await.unwrap(); + let note = store.create_note(None).await.unwrap(); + assert!(store.put_snapshot(¬e.id, b"new".to_vec(), 5, "new", "t").await.unwrap()); + assert!(!store.put_snapshot(¬e.id, b"old".to_vec(), 3, "old", "t").await.unwrap()); + let doc = store.load_doc(¬e.id).await.unwrap(); + assert_eq!(doc.snapshot.as_deref(), Some(&b"new"[..])); + assert_eq!(doc.markdown.as_deref(), Some("new")); + let _ = std::fs::remove_dir_all(&dir); } } diff --git a/src/store/directory.rs b/src/store/directory.rs new file mode 100644 index 0000000..3aaa450 --- /dev/null +++ b/src/store/directory.rs @@ -0,0 +1,461 @@ +//! Every note's metadata and searchable plain text, kept in memory. Sidebar counts, +//! title lookups and search read it instead of scanning the notes table, which costs +//! about 1 µs a row (a second at a million notes). +//! +//! Writers never touch it: they record a [`Change`] after committing, and the next +//! reader applies the pending changes by re-reading those notes. + +use std::collections::HashMap; + +use hashbrown::HashTable; +use rustc_hash::FxHashSet; +use std::sync::{Arc, RwLock}; + +use super::{NoteMeta, plain_text, preview}; +use crate::matcher; + +/// Bytes of plain text kept in memory per note: a billion lines over a thousand notes +/// would not fit, and a megabyte each still held a gigabyte there. Words are indexed +/// from the whole text whatever its length; longer notes are matched from the store. +pub(super) const PLAIN_KEPT: usize = 64 << 10; + +pub(super) struct Entry { + /// The id, title, notebook id and searchable plain text, one after another in one + /// allocation: a million notes' separate strings cost more in headers than in text. + /// The plain text is its first [`PLAIN_KEPT`] bytes for a longer one. + text: Box<str>, + /// Where the title, the notebook id and the plain text start in `text`. + at: [u32; 3], + in_notebook: bool, + /// Whether the plain text is only the start of the text. Words are indexed from all of it. + pub plain_cut: bool, + pub created_at: i64, + pub updated_at: i64, + pub trashed_at: Option<i64>, + /// Where in the plain text the preview is: the start of the text after the title, + /// shown in lists. A copy of its own would cost as much as all the short notes' text. + preview: (u32, u32), + /// The distinct words of the title, then of the text, as [`Vocab`] ids. + words: Box<[u32]>, + title_words: u32, +} + +impl Entry { + fn new(meta: NoteMeta, plain: &str, plain_cut: bool, preview: &str, title: &[u32], text: &[u32]) -> Self { + // Any occurrence of the preview is the same text. + let preview = match plain.find(preview) { + Some(at) => (at as u32, (at + preview.len()) as u32), + None => { + let end = plain.char_indices().nth(super::PREVIEW_CHARS).map_or(plain.len(), |(i, _)| i); + (0, end as u32) + } + }; + let words = title.iter().chain(text).copied().collect(); + let mut entry = Self::packed(&meta, plain); + entry.plain_cut = plain_cut; + entry.preview = preview; + entry.words = words; + entry.title_words = title.len() as u32; + entry + } + + /// The entry's strings and times from `meta`, with `plain` as its text and no words. + fn packed(meta: &NoteMeta, plain: &str) -> Self { + let notebook = meta.notebook_id.as_deref().unwrap_or(""); + let mut text = String::with_capacity(meta.id.len() + meta.title.len() + notebook.len() + plain.len()); + let mut at = [0; 3]; + for (i, part) in [&meta.id, &meta.title, notebook, plain].into_iter().enumerate() { + if i > 0 { + at[i - 1] = text.len() as u32; + } + text.push_str(part); + } + Self { + text: text.into_boxed_str(), + at, + in_notebook: meta.notebook_id.is_some(), + plain_cut: false, + created_at: meta.created_at, + updated_at: meta.updated_at, + trashed_at: meta.trashed_at, + preview: (0, 0), + words: Box::new([]), + title_words: 0, + } + } + + pub fn id(&self) -> &str { + &self.text[..self.at[0] as usize] + } + + pub fn title(&self) -> &str { + &self.text[self.at[0] as usize..self.at[1] as usize] + } + + pub fn notebook_id(&self) -> Option<&str> { + self.in_notebook.then(|| &self.text[self.at[1] as usize..self.at[2] as usize]) + } + + pub fn plain(&self) -> &str { + &self.text[self.at[2] as usize..] + } + + pub fn meta(&self) -> NoteMeta { + NoteMeta { + id: self.id().to_owned(), + title: self.title().to_owned(), + created_at: self.created_at, + updated_at: self.updated_at, + notebook_id: self.notebook_id().map(str::to_owned), + trashed_at: self.trashed_at, + } + } + + pub fn preview(&self) -> &str { + &self.plain()[self.preview.0 as usize..self.preview.1 as usize] + } + + pub fn title_words(&self) -> &[u32] { + &self.words[..self.title_words as usize] + } + + pub fn text_words(&self) -> &[u32] { + &self.words[self.title_words as usize..] + } + + fn with_meta(&self, meta: &NoteMeta) -> Self { + Self { + plain_cut: self.plain_cut, + preview: self.preview, + words: self.words.clone(), + title_words: self.title_words, + ..Self::packed(meta, self.plain()) + } + } +} + +/// Every distinct folded word any note has had. Search matches each word once rather +/// than every occurrence in every note: a million notes share far fewer words. Words +/// are only added, so ids taken from entries stay valid. +#[derive(Default)] +pub(super) struct Vocab { + /// Ids of the words, hashed by the word: the words are not stored twice. + ids: HashTable<u32>, + /// Every word's characters one after another, and where each word ends: millions + /// of words in allocations of their own would cost more than their characters. + chars: Vec<char>, + ends: Vec<usize>, + /// Recent search terms' costs in every word, newest last: typing a query repeats + /// its earlier terms, and a palette keystroke searches texts and titles alike. + /// A table shorter than the vocabulary lacks only the words added since. + pub costs: std::sync::Mutex<Vec<(Box<[char]>, matcher::Options, Arc<Vec<u8>>)>>, +} + +/// A committed write the directory has not seen yet. +pub(super) enum Change { + /// The note was created, edited, moved, trashed, restored or deleted. + Note(String), + /// The notebook was deleted, and its notes became unfiled. + NotebookGone(String), +} + +#[derive(Default)] +pub(super) struct Counts { + /// Notes outside the trash. + pub live: usize, + /// Notes outside the trash in no notebook. + pub unfiled: usize, + pub trashed: usize, + /// Notes outside the trash per notebook id. Notebooks without notes are absent. + pub notebooks: HashMap<String, usize>, +} + +impl Counts { + fn add(&mut self, e: &Entry, n: isize) { + let bump = |c: &mut usize| *c = c.saturating_add_signed(n); + if e.trashed_at.is_some() { + bump(&mut self.trashed); + return; + } + bump(&mut self.live); + match e.notebook_id() { + None => bump(&mut self.unfiled), + Some(nb) => { + if !self.notebooks.contains_key(nb) { + self.notebooks.insert(nb.to_owned(), 0); + } + let c = self.notebooks.get_mut(nb).unwrap(); + bump(c); + if *c == 0 { + self.notebooks.remove(nb); + } + } + } + } +} + +impl Vocab { + pub fn len(&self) -> usize { + self.ends.len() + } + + pub fn word(&self, id: usize) -> &[char] { + word_in(&self.chars, &self.ends, id) + } + + fn id(&self, word: &[char]) -> Option<u32> { + self.ids.find(hash(word), |&id| self.word(id as usize) == word).copied() + } + + fn add(&mut self, word: &[char]) { + if self.id(word).is_none() { + let id = self.ends.len() as u32; + self.chars.extend_from_slice(word); + self.ends.push(self.chars.len()); + let (chars, ends) = (&self.chars, &self.ends); + self.ids.insert_unique(hash(word), id, |&id| hash(word_in(chars, ends, id as usize))); + } + } + + /// Drops the spare capacity growth left, once the words are all read. + fn shrink(&mut self) { + self.chars.shrink_to_fit(); + self.ends.shrink_to_fit(); + let (chars, ends) = (&self.chars, &self.ends); + self.ids.shrink_to_fit(|&id| hash(word_in(chars, ends, id as usize))); + } +} + +/// Word `id` of a vocabulary's characters and word ends. +fn word_in<'a>(chars: &'a [char], ends: &[usize], id: usize) -> &'a [char] { + &chars[if id == 0 { 0 } else { ends[id - 1] }..ends[id]] +} + +fn hash<T: std::hash::Hash + ?Sized>(t: &T) -> u64 { + use std::hash::BuildHasher; + rustc_hash::FxBuildHasher.hash_one(t) +} + +/// Notes' rows with their plain text and words, read without the directory. +pub(super) struct Prepared(Vec<Ready>); + +/// [`prepare`] of one note, on the calling thread only. +pub(super) fn prepare_one(meta: NoteMeta, body: String) -> Prepared { + let mut prepared = prepare_with(vec![(meta, body)], |rows, f| rows.into_iter().map(f).collect()); + prepared.0.shrink_to_fit(); + prepared +} + +/// Reads notes' plain text and words, on every core. This is the costly part of +/// indexing a note, and needs no access to the directory. +pub(super) fn prepare(rows: Vec<(NoteMeta, String)>) -> Prepared { + prepare_with(rows, |rows, f| par_map(rows, f)) +} + +type Row = (NoteMeta, String); +type Ready = (NoteMeta, String, bool, String, Vec<Box<[char]>>, Vec<Box<[char]>>); + +fn prepare_with(rows: Vec<Row>, map: impl FnOnce(Vec<Row>, &(dyn Fn(Row) -> Ready + Sync)) -> Vec<Ready>) -> Prepared { + let words = |text: &str| { + // Folded once per distinct word: a long note repeats its words millions of times. + let distinct: FxHashSet<&str> = matcher::words(text).collect(); + let mut words: Vec<Box<[char]>> = distinct.into_iter().map(matcher::fold_word).collect(); + words.sort_unstable(); + words.dedup(); + words + }; + Prepared(map(rows, &|(meta, body)| { + let mut plain = plain_text(&body); + let (title, text) = (words(&meta.title), words(&plain)); + let plain_cut = plain.len() > PLAIN_KEPT; + if plain_cut { + let mut end = PLAIN_KEPT; + while !plain.is_char_boundary(end) { + end -= 1; + } + plain.truncate(end); + } + (meta, plain, plain_cut, preview(&body), title, text) + })) +} + +#[derive(Default)] +pub(super) struct Directory { + /// Slot of each note in `slots`, hashed by the note's id. + index: HashTable<u32>, + /// The notes in a flat list, so a search can split it between threads and read it + /// in place. A removed note leaves its slot empty until a new note takes it. + slots: Vec<Option<Arc<Entry>>>, + free: Vec<usize>, + pub counts: Counts, + pub vocab: Arc<RwLock<Vocab>>, +} + +impl Directory { + /// Inserts or replaces notes from their rows and markdown bodies. The text is read + /// on every core: at startup this indexes every note. + pub fn put_many(&mut self, rows: Vec<(NoteMeta, String)>) { + self.put_prepared(prepare(rows)); + } + + /// Updates a note's metadata and keeps its words, for a note whose text is indexed + /// later; a note new to the directory has no words until then. + pub fn set_meta(&mut self, meta: NoteMeta) { + let entry = match self.remove(&meta.id) { + Some(old) => old.with_meta(&meta), + None => Entry::new(meta, "", false, "", &[], &[]), + }; + self.insert(entry); + } + + pub fn updated_at(&self, id: &str) -> Option<i64> { + self.get(id).map(|e| e.updated_at) + } + + /// Inserts or replaces notes from [`prepare`]d rows. + pub fn put_prepared(&mut self, Prepared(prepared): Prepared) { + // Words new to the vocabulary are found under the read lock, then added once. + let unknown: Vec<FxHashSet<&[char]>> = { + let vocab = self.vocab.read().unwrap(); + par_chunks(&prepared, |chunk| { + chunk + .iter() + .flat_map(|(_, _, _, _, title, text)| title.iter().chain(text)) + .filter(|w| vocab.id(w).is_none()) + .map(|w| &**w) + .collect() + }) + }; + let mut vocab = self.vocab.write().unwrap(); + for word in unknown.into_iter().flatten() { + vocab.add(word); + } + drop(vocab); + let vocab = self.vocab.read().unwrap(); + let ids_of = |words: Vec<Box<[char]>>| -> Vec<u32> { + let mut ids: Vec<u32> = words.iter().map(|w| vocab.id(w).unwrap()).collect(); + ids.sort_unstable(); + ids + }; + let entries = par_map(prepared, |(meta, plain, plain_cut, preview, title, text)| { + Entry::new(meta, &plain, plain_cut, &preview, &ids_of(title), &ids_of(text)) + }); + drop(vocab); + for entry in entries { + self.remove(entry.id()); + self.insert(entry); + } + } + + fn insert(&mut self, entry: Entry) { + self.counts.add(&entry, 1); + let h = hash(entry.id()); + let entry = Some(Arc::new(entry)); + let slot = match self.free.pop() { + Some(slot) => { + self.slots[slot] = entry; + slot + } + None => { + self.slots.push(entry); + self.slots.len() - 1 + } + }; + let slots = &self.slots; + self.index.insert_unique(h, slot as u32, |&s| hash(slots[s as usize].as_ref().unwrap().id())); + } + + /// Drops the spare capacity growth left, once every note is read. + pub fn shrink(&mut self) { + self.slots.shrink_to_fit(); + self.vocab.write().unwrap().shrink(); + } + + fn slot(&self, id: &str) -> Option<usize> { + let slots = &self.slots; + self.index.find(hash(id), |&s| slots[s as usize].as_ref().is_some_and(|e| e.id() == id)).map(|&s| s as usize) + } + + pub fn remove(&mut self, id: &str) -> Option<Arc<Entry>> { + let slots = &self.slots; + let slot = self.index.find_entry(hash(id), |&s| slots[s as usize].as_ref().is_some_and(|e| e.id() == id)).ok()?.remove().0 as usize; + let old = self.slots[slot].take()?; + self.free.push(slot); + self.counts.add(&old, -1); + Some(old) + } + + pub fn get(&self, id: &str) -> Option<&Arc<Entry>> { + self.slots[self.slot(id)?].as_ref() + } + + /// Every note, trashed ones too, with empty slots between them. + pub fn slots(&self) -> &[Option<Arc<Entry>>] { + &self.slots + } + + pub fn entries(&self) -> impl Iterator<Item = &Arc<Entry>> { + self.slots.iter().flatten() + } + + pub fn unfile(&mut self, notebook_id: &str) { + let ids: Vec<String> = self + .entries() + .filter(|e| e.notebook_id() == Some(notebook_id)) + .map(|e| e.id().to_owned()) + .collect(); + for id in ids { + let old = self.remove(&id).unwrap(); + let mut meta = old.meta(); + meta.notebook_id = None; + self.insert(old.with_meta(&meta)); + } + } + + /// Notes outside the trash. + pub fn live(&self) -> Vec<Arc<Entry>> { + self.entries().filter(|e| e.trashed_at.is_none()).cloned().collect() + } +} + +/// `f` of every item on scoped threads, in order. Threads take the next item when +/// done, so a few huge notes do not hold back the rest. +fn par_map<T: Send, U: Send>(items: Vec<T>, f: impl Fn(T) -> U + Sync) -> Vec<U> { + let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(items.len().max(1)); + let n = items.len(); + let items: Vec<std::sync::Mutex<Option<T>>> = items.into_iter().map(|t| std::sync::Mutex::new(Some(t))).collect(); + let next = std::sync::atomic::AtomicUsize::new(0); + let (items, next, f) = (&items, &next, &f); + let mut done: Vec<(usize, U)> = std::thread::scope(|scope| { + let handles: Vec<_> = (0..threads) + .map(|_| { + scope.spawn(move || { + let mut out = Vec::new(); + loop { + // Items are taken a few at a time: most are small. + let start = next.fetch_add(64, std::sync::atomic::Ordering::Relaxed); + if start >= n { + return out; + } + for (i, item) in items.iter().enumerate().skip(start).take(64) { + out.push((i, f(item.lock().unwrap().take().unwrap()))); + } + } + }) + }) + .collect(); + handles.into_iter().flat_map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect() + }); + done.sort_unstable_by_key(|(i, _)| *i); + done.into_iter().map(|(_, u)| u).collect() +} + +/// `f` of each of about one slice of `items` per core, in order. +fn par_chunks<'a, T: Sync, U: Send>(items: &'a [T], f: impl Fn(&'a [T]) -> U + Sync) -> Vec<U> { + let threads = std::thread::available_parallelism().map_or(1, |n| n.get()); + let f = &f; + std::thread::scope(|scope| { + let handles: Vec<_> = items.chunks(items.len().div_ceil(threads).max(1)).map(|chunk| scope.spawn(move || f(chunk))).collect(); + handles.into_iter().map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect() + }) +} diff --git a/src/zipout.rs b/src/zipout.rs new file mode 100644 index 0000000..dbcee6a --- /dev/null +++ b/src/zipout.rs @@ -0,0 +1,117 @@ +//! A streaming zip writer for the export. Files go out as they are added; until the +//! central directory is written at the end it keeps 32 bytes per file, with names +//! looked up again by index, so millions of files fit in little memory. + +use std::io::{self, Write}; + +use flate2::Compression; +use flate2::write::DeflateEncoder; + +const MAX32: u64 = 0xFFFF_FFFF; +/// File names are UTF-8. +const UTF8: u16 = 1 << 11; +const DEFLATE: u16 = 8; + +/// Appends each value's little-endian bytes to `buf`. +macro_rules! le { + ($buf:expr, $($v:expr),+ $(,)?) => { $( $buf.extend_from_slice(&$v.to_le_bytes()); )+ }; +} + +/// A file's compressed bytes, ready to add. +pub struct Deflated { + data: Vec<u8>, + crc: u32, + size: u64, +} + +impl Deflated { + pub fn new(bytes: &[u8]) -> io::Result<Self> { + Self::with_level(bytes, Compression::default()) + } + + /// Without compression, for media, which is already compressed. The output is still + /// a valid DEFLATE stream (stored blocks), so the zip format needs no change. + pub fn fast(bytes: &[u8]) -> io::Result<Self> { + Self::with_level(bytes, Compression::none()) + } + + fn with_level(bytes: &[u8], level: Compression) -> io::Result<Self> { + let mut enc = DeflateEncoder::new(Vec::with_capacity(bytes.len() / 4 + 64), level); + enc.write_all(bytes)?; + Ok(Self { data: enc.finish()?, crc: crc32fast::hash(bytes), size: bytes.len() as u64 }) + } +} + +struct Entry { + name: u32, + crc: u32, + csize: u64, + size: u64, + offset: u64, +} + +pub struct ZipOut<W: Write> { + out: W, + at: u64, + entries: Vec<Entry>, + date: u16, +} + +impl<W: Write> ZipOut<W> { + /// Files are dated `(year, month, day)`, at midnight. + pub fn new(out: W, (year, month, day): (i64, i64, i64)) -> Self { + let date = (((year - 1980).clamp(0, 127) as u16) << 9) | ((month as u16) << 5) | day as u16; + Self { out, at: 0, entries: Vec::new(), date } + } + + /// Writes one file; `name` is what `finish` is given to find `path` again. + pub fn add(&mut self, name: u32, path: &str, file: Deflated) -> io::Result<()> { + let csize = file.data.len() as u64; + let big = file.size >= MAX32 || csize >= MAX32; + let (c32, s32) = if big { (MAX32, MAX32) } else { (csize, file.size) }; + let mut h = Vec::with_capacity(50 + path.len()); + le!(h, 0x0403_4b50u32, if big { 45u16 } else { 20u16 }, UTF8, DEFLATE, 0u16, self.date, file.crc); + le!(h, c32 as u32, s32 as u32, path.len() as u16, if big { 20u16 } else { 0u16 }); + h.extend_from_slice(path.as_bytes()); + if big { + le!(h, 1u16, 16u16, file.size, csize); + } + self.out.write_all(&h)?; + self.out.write_all(&file.data)?; + self.entries.push(Entry { name, crc: file.crc, csize, size: file.size, offset: self.at }); + self.at += h.len() as u64 + csize; + Ok(()) + } + + /// Writes the central directory, `path` giving each file's path by its name index. + pub fn finish<'a>(mut self, path: impl Fn(u32) -> &'a str) -> io::Result<W> { + let start = self.at; + let mut h = Vec::with_capacity(256); + for e in &self.entries { + let path = path(e.name); + let big = e.size >= MAX32 || e.csize >= MAX32 || e.offset >= MAX32; + let small = |v: u64| if big { MAX32 as u32 } else { v as u32 }; + h.clear(); + le!(h, 0x0201_4b50u32, 45u16, if big { 45u16 } else { 20u16 }, UTF8, DEFLATE, 0u16, self.date, e.crc); + le!(h, small(e.csize), small(e.size), path.len() as u16, if big { 28u16 } else { 0u16 }); + le!(h, 0u16, 0u16, 0u16, 0u32, small(e.offset)); + h.extend_from_slice(path.as_bytes()); + if big { + le!(h, 1u16, 24u16, e.size, e.csize, e.offset); + } + self.out.write_all(&h)?; + self.at += h.len() as u64; + } + let (count, size) = (self.entries.len() as u64, self.at - start); + h.clear(); + if count >= 0xFFFF || size >= MAX32 || start >= MAX32 { + le!(h, 0x0606_4b50u32, 44u64, 45u16, 45u16, 0u32, 0u32, count, count, size, start); + le!(h, 0x0706_4b50u32, 0u32, self.at, 1u32); + } + let count16 = count.min(0xFFFF) as u16; + le!(h, 0x0605_4b50u32, 0u16, 0u16, count16, count16, size.min(MAX32) as u32, start.min(MAX32) as u32, 0u16); + self.out.write_all(&h)?; + self.out.flush()?; + Ok(self.out) + } +} diff --git a/vendor/loro-internal/.gitignore b/vendor/loro-internal/.gitignore new file mode 100644 index 0000000..1b5d043 --- /dev/null +++ b/vendor/loro-internal/.gitignore @@ -0,0 +1 @@ +*dhat-heap.json diff --git a/vendor/loro-internal/AGENTS.md b/vendor/loro-internal/AGENTS.md new file mode 100644 index 0000000..98bd452 --- /dev/null +++ b/vendor/loro-internal/AGENTS.md @@ -0,0 +1,121 @@ +# loro-internal Guidelines + +This crate contains Loro's unstable internal CRDT implementation. Public API +compatibility concerns still matter because `crates/loro` and `crates/loro-wasm` +wrap this crate directly, but the internal priority is preserving invariants +over graceful degradation. + +## Internal Map + +- `src/undo.rs`: one recorded item per undo/redo call, including no-ops: + [../../context/undo-history-boundaries.md](../../context/undo-history-boundaries.md). +- Undo transaction rollback and writer gate: + [../../context/undo-atomicity.md](../../context/undo-atomicity.md). +- `src/loro.rs`: document-level orchestration for commit, import/export, + checkout, barriers, state/oplog coordination, and event emission. + `apply_diff`/`revert_to` roll a failed batch back: + [../../context/apply-diff-atomicity.md](../../context/apply-diff-atomicity.md). +- `src/encoding.rs`: public/internal `ExportMode`, binary header parsing, + checksum verification, `EncodeMode` dispatch, import metadata, and the bridge + from decoded changes into `OpLog`. +- `src/encoding/`: concrete binary and JSON encoding implementations. Read + `src/encoding/AGENTS.md` and + [../../context/internal-encoding.md](../../context/internal-encoding.md) + before changing binary layout, JSON schema, import metadata, shallow snapshot, + or op/value encoding. +- `src/oplog/` and `src/dag/`: change storage, dependency ordering, pending + changes, version vectors/frontiers, shallow roots, and history traversal. + `ChangeStore` is also read without the op log lock, so keep its lock order: + [../../context/arena-parent-links.md](../../context/arena-parent-links.md). +- `src/arena.rs`: container IDs, indices, and parent links. How a parent is + found in a lazily loaded document, and the locking rules: + [../../context/arena-parent-links.md](../../context/arena-parent-links.md). + Parsed change blocks keep text and list values out of doc-wide arenas; the + trackers use `diff_calc/tracker_texts.rs` and `tracker_values.rs`: + [../../context/text-arena-growth.md](../../context/text-arena-growth.md). +- `src/utils/subscription.rs`, `src/subscription.rs`, `src/txn.rs` commit: + user callbacks that panic must not poison locks or drop events: + [../../context/callback-panics.md](../../context/callback-panics.md). +- `src/state.rs` and `src/state/`: materialized document state, container stores, + diff application, checkout/replay, deep value, dead-container tracking, and + mergeable container visibility. Read `src/state/AGENTS.md` and + [../../context/mergeable-containers.md](../../context/mergeable-containers.md) + before changing mergeable containers. +- `src/handler.rs`: typed container handlers, local operation creation, and + `MapHandler::ensure_mergeable_*`. + `src/handler/movable_list_apply_delta.rs` applies movable-list diffs for + `apply_diff`; `src/undo/movable_list.rs` preserves undo identities/anchors: + [../../context/movable-list-apply-diff.md](../../context/movable-list-apply-diff.md). +- `src/diff_calc/`: diff calculation when moving between versions. The tree + calculator's cache transitions: + [../../context/tree-checkout-window.md](../../context/tree-checkout-window.md). + Which tree diff modes carry raw ops, and how tree events are built for each: + [../../context/tree-events.md](../../context/tree-events.md). +- `src/container/richtext/`: text state with style anchors. Where local inserts + go next to anchors, the insert cursor cache, and delete `start_id`s: + [../../context/richtext-insert-positions.md](../../context/richtext-insert-positions.md). +- `docs/diff_calc.md`: design notes for diff calculation. +- `docs/critical-version-spec.md`: specification and proof skeleton for + replay-base selection (Eg-walker-aligned terminology; defines critical + version, the entry check, and the fallback sweep). +- `docs/mergeable-container-id.md`: current mergeable container id encoding. +- `tests/mergeable_container/` and `tests/mergeable_cid_encoding.rs`: focused + mergeable container regression tests. +- `src/tests/import_atomicity.rs`: import rollback and malformed-input + regressions. A failed import keeps its arena indices and drops only parent + links, values, and the dead-container cache: + [../../context/failed-import-arena-indices.md](../../context/failed-import-arena-indices.md). +- Movable-list `Move`/`Set` element validation on import, plus change-store + rollback records and KV block-range decoding: + [../../context/movable-list-op-validation.md](../../context/movable-list-op-validation.md). +- Root container visibility after import/checkout (`materialize_touched_roots`): + [../../context/root-container-visibility.md](../../context/root-container-visibility.md). +- Imported changes that reuse local op ids are checked against local history + before anything is applied (`src/oplog/known_history.rs`): + [../../context/import-peer-id-reuse.md](../../context/import-peer-id-reuse.md). +- `import_batch` force-detach, its batch-wide rollback scope, and the + never-exit-detached invariant: + [../../context/import-batch-atomicity.md](../../context/import-batch-atomicity.md). + +## Commands + +Use narrow checks first: + +- `cargo check -p loro-internal` +- `cargo test -p loro-internal --doc` +- `cargo test -p loro-internal --test mergeable_container` +- `cargo test -p loro-internal --test mergeable_cid_encoding` +- `cargo test -p loro-internal import_atomicity` + +For broad shared behavior, run the root commands from `AGENTS.md`. For changes +to import, checkout, encoding, state replay, or diff calculation, consider fuzz +coverage under `crates/fuzz` and ask before running long fuzz targets. + +## Working Rules + +- Replay-base selection uses Eg-walker terminology (arXiv:2409.14252 §3.5): + a version V is **critical** when every event outside `Events(V)` happened + after all of `Events(V)` — no concurrency crosses the cut. Non-`Checkout` + diff modes are only sound when the base satisfies this (the tree + calculator's `Checkout` path takes its window from the two versions + instead); `dag.rs`/`oplog.rs` enforce it via the + `ImportGreaterUpdates` entry check and, on conservative retreat, the + multi-head fixpoint `OpLog::latest_critical_version_below_meet`, with + the `latest_single_head_critical_version` descent as fallback. Do not + use "LCA" or "common ancestor" in new code or docs: the meet of two + versions is generally NOT a safe replay base, and a caller that needs a + critical version must ask for one (loro-dev/loro#1095). Read + `docs/critical-version-spec.md` before touching `find_replay_base` or diff + modes. + `OpLog::iter_from_replay_base_causally` may bypass the DAG when the + concurrency is register-only (`docs/diff_calc.md`, "Register-only + concurrency"); keep that check container-granular and history-based. +- Internal invariant violation should fail fast. Invalid external bytes or JSON + should return `Err`. +- Do not silently skip ops, containers, state entries, diffs, or pending changes. +- Snapshot/import paths must be atomic: if decode or state application fails, + rollback must leave the document usable. +- Preserve attached/detached document state when export paths temporarily + checkout another version. +- If a change affects `crates/loro` or `crates/loro-wasm` behavior, add or update + tests at the wrapper layer as well as the internal layer when practical. diff --git a/vendor/loro-internal/CLAUDE.md b/vendor/loro-internal/CLAUDE.md new file mode 100644 index 0000000..98bd452 --- /dev/null +++ b/vendor/loro-internal/CLAUDE.md @@ -0,0 +1,121 @@ +# loro-internal Guidelines + +This crate contains Loro's unstable internal CRDT implementation. Public API +compatibility concerns still matter because `crates/loro` and `crates/loro-wasm` +wrap this crate directly, but the internal priority is preserving invariants +over graceful degradation. + +## Internal Map + +- `src/undo.rs`: one recorded item per undo/redo call, including no-ops: + [../../context/undo-history-boundaries.md](../../context/undo-history-boundaries.md). +- Undo transaction rollback and writer gate: + [../../context/undo-atomicity.md](../../context/undo-atomicity.md). +- `src/loro.rs`: document-level orchestration for commit, import/export, + checkout, barriers, state/oplog coordination, and event emission. + `apply_diff`/`revert_to` roll a failed batch back: + [../../context/apply-diff-atomicity.md](../../context/apply-diff-atomicity.md). +- `src/encoding.rs`: public/internal `ExportMode`, binary header parsing, + checksum verification, `EncodeMode` dispatch, import metadata, and the bridge + from decoded changes into `OpLog`. +- `src/encoding/`: concrete binary and JSON encoding implementations. Read + `src/encoding/AGENTS.md` and + [../../context/internal-encoding.md](../../context/internal-encoding.md) + before changing binary layout, JSON schema, import metadata, shallow snapshot, + or op/value encoding. +- `src/oplog/` and `src/dag/`: change storage, dependency ordering, pending + changes, version vectors/frontiers, shallow roots, and history traversal. + `ChangeStore` is also read without the op log lock, so keep its lock order: + [../../context/arena-parent-links.md](../../context/arena-parent-links.md). +- `src/arena.rs`: container IDs, indices, and parent links. How a parent is + found in a lazily loaded document, and the locking rules: + [../../context/arena-parent-links.md](../../context/arena-parent-links.md). + Parsed change blocks keep text and list values out of doc-wide arenas; the + trackers use `diff_calc/tracker_texts.rs` and `tracker_values.rs`: + [../../context/text-arena-growth.md](../../context/text-arena-growth.md). +- `src/utils/subscription.rs`, `src/subscription.rs`, `src/txn.rs` commit: + user callbacks that panic must not poison locks or drop events: + [../../context/callback-panics.md](../../context/callback-panics.md). +- `src/state.rs` and `src/state/`: materialized document state, container stores, + diff application, checkout/replay, deep value, dead-container tracking, and + mergeable container visibility. Read `src/state/AGENTS.md` and + [../../context/mergeable-containers.md](../../context/mergeable-containers.md) + before changing mergeable containers. +- `src/handler.rs`: typed container handlers, local operation creation, and + `MapHandler::ensure_mergeable_*`. + `src/handler/movable_list_apply_delta.rs` applies movable-list diffs for + `apply_diff`; `src/undo/movable_list.rs` preserves undo identities/anchors: + [../../context/movable-list-apply-diff.md](../../context/movable-list-apply-diff.md). +- `src/diff_calc/`: diff calculation when moving between versions. The tree + calculator's cache transitions: + [../../context/tree-checkout-window.md](../../context/tree-checkout-window.md). + Which tree diff modes carry raw ops, and how tree events are built for each: + [../../context/tree-events.md](../../context/tree-events.md). +- `src/container/richtext/`: text state with style anchors. Where local inserts + go next to anchors, the insert cursor cache, and delete `start_id`s: + [../../context/richtext-insert-positions.md](../../context/richtext-insert-positions.md). +- `docs/diff_calc.md`: design notes for diff calculation. +- `docs/critical-version-spec.md`: specification and proof skeleton for + replay-base selection (Eg-walker-aligned terminology; defines critical + version, the entry check, and the fallback sweep). +- `docs/mergeable-container-id.md`: current mergeable container id encoding. +- `tests/mergeable_container/` and `tests/mergeable_cid_encoding.rs`: focused + mergeable container regression tests. +- `src/tests/import_atomicity.rs`: import rollback and malformed-input + regressions. A failed import keeps its arena indices and drops only parent + links, values, and the dead-container cache: + [../../context/failed-import-arena-indices.md](../../context/failed-import-arena-indices.md). +- Movable-list `Move`/`Set` element validation on import, plus change-store + rollback records and KV block-range decoding: + [../../context/movable-list-op-validation.md](../../context/movable-list-op-validation.md). +- Root container visibility after import/checkout (`materialize_touched_roots`): + [../../context/root-container-visibility.md](../../context/root-container-visibility.md). +- Imported changes that reuse local op ids are checked against local history + before anything is applied (`src/oplog/known_history.rs`): + [../../context/import-peer-id-reuse.md](../../context/import-peer-id-reuse.md). +- `import_batch` force-detach, its batch-wide rollback scope, and the + never-exit-detached invariant: + [../../context/import-batch-atomicity.md](../../context/import-batch-atomicity.md). + +## Commands + +Use narrow checks first: + +- `cargo check -p loro-internal` +- `cargo test -p loro-internal --doc` +- `cargo test -p loro-internal --test mergeable_container` +- `cargo test -p loro-internal --test mergeable_cid_encoding` +- `cargo test -p loro-internal import_atomicity` + +For broad shared behavior, run the root commands from `AGENTS.md`. For changes +to import, checkout, encoding, state replay, or diff calculation, consider fuzz +coverage under `crates/fuzz` and ask before running long fuzz targets. + +## Working Rules + +- Replay-base selection uses Eg-walker terminology (arXiv:2409.14252 §3.5): + a version V is **critical** when every event outside `Events(V)` happened + after all of `Events(V)` — no concurrency crosses the cut. Non-`Checkout` + diff modes are only sound when the base satisfies this (the tree + calculator's `Checkout` path takes its window from the two versions + instead); `dag.rs`/`oplog.rs` enforce it via the + `ImportGreaterUpdates` entry check and, on conservative retreat, the + multi-head fixpoint `OpLog::latest_critical_version_below_meet`, with + the `latest_single_head_critical_version` descent as fallback. Do not + use "LCA" or "common ancestor" in new code or docs: the meet of two + versions is generally NOT a safe replay base, and a caller that needs a + critical version must ask for one (loro-dev/loro#1095). Read + `docs/critical-version-spec.md` before touching `find_replay_base` or diff + modes. + `OpLog::iter_from_replay_base_causally` may bypass the DAG when the + concurrency is register-only (`docs/diff_calc.md`, "Register-only + concurrency"); keep that check container-granular and history-based. +- Internal invariant violation should fail fast. Invalid external bytes or JSON + should return `Err`. +- Do not silently skip ops, containers, state entries, diffs, or pending changes. +- Snapshot/import paths must be atomic: if decode or state application fails, + rollback must leave the document usable. +- Preserve attached/detached document state when export paths temporarily + checkout another version. +- If a change affects `crates/loro` or `crates/loro-wasm` behavior, add or update + tests at the wrapper layer as well as the internal layer when practical. diff --git a/vendor/loro-internal/Cargo.lock b/vendor/loro-internal/Cargo.lock new file mode 100644 index 0000000..c5c4fec --- /dev/null +++ b/vendor/loro-internal/Cargo.lock @@ -0,0 +1,2060 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.3", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +dependencies = [ + "memchr", +] + +[[package]] +name = "anes" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" + +[[package]] +name = "anstyle" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd" + +[[package]] +name = "append-only-bytes" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac436601d6bdde674a0d7fb593e829ffe7b3387c351b356dd20e2d40f5bf3ee5" + +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" +dependencies = [ + "derive_arbitrary", +] + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "arref" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ccd462b64c3c72f1be8305905a85d85403d768e8690c9b8bd3b9009a5761679" + +[[package]] +name = "atomic-polyfill" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cf2bce30dfe09ef0bfaef228b9d414faaf7e563035494d7fe092dba54b300f4" +dependencies = [ + "critical-section", +] + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "bitflags" +version = "2.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394" + +[[package]] +name = "bitmaps" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031043d04099746d8db04daf1fa424b2bc8bd69d92b25962dcde24da39ab64a2" +dependencies = [ + "typenum", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" + +[[package]] +name = "bytecount" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" + +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + +[[package]] +name = "cc" +version = "1.2.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5252b3d2648e5eedbc1a6f501e3c795e07025c1e93bbf8bbdd6eef7f447a6d54" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9" + +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] + +[[package]] +name = "clap" +version = "4.5.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eac00902d9d136acd712710d71823fb8ac8004ca445a89e73a41d45aa712931" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.5.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ad9bbf750e73b5884fb8a211a9424a1906c1e156724260fdae972f31d70e1d6" +dependencies = [ + "anstyle", + "clap_lex", +] + +[[package]] +name = "clap_lex" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675" + +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror 2.0.16", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "criterion" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c047a62b0cc3e145fa84415a3191f628e980b194c2755aa12300a4e6cbd928" +dependencies = [ + "anes", + "cast", + "ciborium", + "clap", + "criterion-plot", + "itertools 0.13.0", + "num-traits", + "oorandom", + "plotters", + "rayon", + "regex", + "serde", + "serde_json", + "tinytemplate", + "walkdir", +] + +[[package]] +name = "criterion-plot" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b1bcc0dc7dfae599d84ad0b1a55f80cde8af3725da8313b528da95ef783e338" +dependencies = [ + "cast", + "itertools 0.13.0", +] + +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossbeam-deque" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "ctor" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d2301688392eb071b0bf1a37be05c469d3cc4dbbd95df672fe28ab021e6a096" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.106", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.106", +] + +[[package]] +name = "derive_arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", +] + +[[package]] +name = "diff" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + +[[package]] +name = "ensure-cov" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33753185802e107b8fa907192af1f0eca13b1fb33327a59266d650fef29b2b4e" + +[[package]] +name = "enum-as-inner" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9720bba047d567ffc8a3cba48bf19126600e249ab7f128e9233e6376976a116" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "enum-as-inner" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.106", +] + +[[package]] +name = "enum_dispatch" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd" +dependencies = [ + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.106", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "find-msvc-tools" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd99930f64d146689264c637b5af2f0233a933bef0d8570e2526bf9e083192d" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "generator" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "605183a538e3e2a9c1038635cc5c2d194e2ee8fd0d1b66b8349fad7dbacce5a2" +dependencies = [ + "cc", + "cfg-if", + "libc", + "log", + "rustversion", + "windows", +] + +[[package]] +name = "generic-array" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "generic-btree" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0c1bce85c110ab718fd139e0cc89c51b63bd647b14a767e24bdfc77c83df79b" +dependencies = [ + "arref", + "heapless 0.9.1", + "itertools 0.11.0", + "loro-thunderdome", + "proc-macro2", + "rustc-hash", +] + +[[package]] +name = "getrandom" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasi 0.14.4+wasi-0.2.4", +] + +[[package]] +name = "half" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "459196ed295495a68f7d7fe1d84f6c4b7ff0e21fe3017b2f283c6fac3ad803c9" +dependencies = [ + "cfg-if", + "crunchy", +] + +[[package]] +name = "hash32" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67" +dependencies = [ + "byteorder", +] + +[[package]] +name = "hash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" +dependencies = [ + "byteorder", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" + +[[package]] +name = "heapless" +version = "0.7.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f" +dependencies = [ + "atomic-polyfill", + "hash32 0.2.1", + "rustc_version", + "serde", + "spin", + "stable_deref_trait", +] + +[[package]] +name = "heapless" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" +dependencies = [ + "hash32 0.3.1", + "stable_deref_trait", +] + +[[package]] +name = "heapless" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1edcd5a338e64688fbdcb7531a846cfd3476a54784dcb918a0844682bc7ada5" +dependencies = [ + "hash32 0.3.1", + "stable_deref_trait", +] + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "im" +version = "15.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0acd33ff0285af998aaf9b57342af478078f53492322fafc47450e09397e0e9" +dependencies = [ + "bitmaps", + "rand_core", + "rand_xoshiro", + "serde", + "sized-chunks", + "typenum", + "version_check", +] + +[[package]] +name = "itertools" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" + +[[package]] +name = "jobserver" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +dependencies = [ + "getrandom 0.3.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "leb128" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" + +[[package]] +name = "loom" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "419e0dc8046cb947daa77eb95ae174acfbddb7673b4151f56d1eed8e93fbfaca" +dependencies = [ + "cfg-if", + "generator", + "scoped-tls", + "serde", + "serde_json", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "loro-common" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd3f7afbafc4db85aefe9620e7e99fa49c974477563904f226ae96fc9674eade" +dependencies = [ + "arbitrary", + "enum-as-inner 0.6.1", + "js-sys", + "leb128", + "loro-rle", + "nonmax", + "rustc-hash", + "serde", + "serde_columnar", + "thiserror 1.0.69", + "tracing", + "wasm-bindgen", +] + +[[package]] +name = "loro-delta" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96f381e7fb5d4bf5605b4f4a9241f3adf61403ded978d757552004c8302cccbb" +dependencies = [ + "arrayvec", + "enum-as-inner 0.5.1", + "generic-btree", + "heapless 0.8.0", +] + +[[package]] +name = "loro-internal" +version = "1.17.1" +dependencies = [ + "append-only-bytes", + "arbitrary", + "arref", + "bytes", + "criterion", + "ctor", + "either", + "ensure-cov", + "enum-as-inner 0.6.1", + "enum_dispatch", + "generic-btree", + "getrandom 0.2.16", + "im", + "itertools 0.12.1", + "js-sys", + "leb128", + "loom", + "loro-common", + "loro-delta", + "loro-kv-store", + "loro-rle", + "loro_fractional_index", + "md5", + "miniz_oxide", + "nonmax", + "num", + "num-traits", + "once_cell", + "parking_lot", + "pest", + "pest_derive", + "postcard", + "pretty_assertions", + "rand", + "rustc-hash", + "serde", + "serde_columnar", + "serde_json", + "smallvec", + "tabled", + "thiserror 1.0.69", + "thread_local", + "tracing", + "wasm-bindgen", + "xxhash-rust", + "zstd", +] + +[[package]] +name = "loro-kv-store" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7331ebe6902effeb0c3d52aba9e30fb0118bc926faed6f3848487aab40c1a4e" +dependencies = [ + "bytes", + "ensure-cov", + "loro-common", + "lz4_flex", + "once_cell", + "quick_cache", + "rustc-hash", + "tracing", + "xxhash-rust", +] + +[[package]] +name = "loro-rle" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76400c3eea6bb39b013406acce964a8db39311534e308286c8d8721baba8ee20" +dependencies = [ + "append-only-bytes", + "num", + "smallvec", +] + +[[package]] +name = "loro-thunderdome" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3d053a135388e6b1df14e8af1212af5064746e9b87a06a345a7a779ee9695a" + +[[package]] +name = "loro_fractional_index" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aca7180674d0273ddf37049a5efcde4547fd5330d24abb7519bb9d9eb6780d5b" +dependencies = [ + "once_cell", + "rand", + "serde", +] + +[[package]] +name = "lz4_flex" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08ab2867e3eeeca90e844d1940eab391c9dc5228783db2ed999acbc0a9ed375a" +dependencies = [ + "twox-hash", +] + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "md5" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" + +[[package]] +name = "memchr" +version = "2.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" + +[[package]] +name = "miniz_oxide" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" +dependencies = [ + "adler", +] + +[[package]] +name = "nonmax" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "610a5acd306ec67f907abe5567859a3c693fb9886eb1f012ab8f2a47bef3db51" + +[[package]] +name = "nu-ansi-term" +version = "0.50.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a28e057d01f97e61255210fcff094d74ed0466038633e95017f5beb68e4399" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "oorandom" +version = "11.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" + +[[package]] +name = "papergrid" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1526bb6aa9f10ec339fb10360f22c57edf81d5678d0278e93bc12a47ffbe4b01" +dependencies = [ + "bytecount", + "fnv", + "unicode-width", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link 0.2.1", +] + +[[package]] +name = "pest" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "989e7521a040efde50c3ab6bbadafbe15ab6dc042686926be59ac35d74607df4" +dependencies = [ + "memchr", + "ucd-trie", +] + +[[package]] +name = "pest_derive" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "187da9a3030dbafabbbfb20cb323b976dc7b7ce91fcd84f2f74d6e31d378e2de" +dependencies = [ + "pest", + "pest_generator", +] + +[[package]] +name = "pest_generator" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49b401d98f5757ebe97a26085998d6c0eecec4995cad6ab7fc30ffdf4b052843" +dependencies = [ + "pest", + "pest_meta", + "proc-macro2", + "quote", + "syn 2.0.106", +] + +[[package]] +name = "pest_meta" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f27a2cfee9f9039c4d86faa5af122a0ac3851441a34865b8a043b46be0065a" +dependencies = [ + "pest", + "sha2", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "plotters" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" +dependencies = [ + "num-traits", + "plotters-backend", + "plotters-svg", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "plotters-backend" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" + +[[package]] +name = "plotters-svg" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" +dependencies = [ + "plotters-backend", +] + +[[package]] +name = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", + "heapless 0.7.17", + "serde", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "pretty_assertions" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d" +dependencies = [ + "diff", + "yansi", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro2" +version = "1.0.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quick_cache" +version = "0.6.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ad6644cb07b7f3488b9f3d2fde3b4c0a7fa367cafefb39dff93a659f76eb786" +dependencies = [ + "ahash", + "equivalent", + "hashbrown", + "parking_lot", +] + +[[package]] +name = "quote" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.16", +] + +[[package]] +name = "rand_xoshiro" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f97cdb2a36ed4183de61b2f824cc45c9f1037f28afe0a322e9fff4c108b5aaa" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rayon" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5407465600fb0548f1442edf71dd20683c6ed326200ace4b1ef0763521bb3b77" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d7fd106d8c02486a8d64e778353d1cffe08ce79ac2e82f540c86d0facf6912" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b9458fa0bfeeac22b5ca447c63aaf45f28439a709ccd244698632f9aa6394d6" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf4aa5b0f434c91fe5c7f1ecb6a5ece2130b02ad2a590589dda5146df959001" + +[[package]] +name = "rustc-hash" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6fa9c48d24d85fb3de5ad847117517440f6beceb7798af16b4a87d616b8d0" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_columnar" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a16e404f17b16d0273460350e29b02d76ba0d70f34afdc9a4fa034c97d6c6eb" +dependencies = [ + "itertools 0.11.0", + "postcard", + "serde", + "serde_columnar_derive", + "thiserror 1.0.69", +] + +[[package]] +name = "serde_columnar_derive" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45958fce4903f67e871fbf15ac78e289269b21ebd357d6fecacdba233629112e" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.106", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.143" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d401abef1d108fbd9cbaebc3e46611f4b1021f714a0597a71f41ee463f5f4a5a" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "sized-chunks" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16d69225bde7a69b235da73377861095455d298f2b970996eec25ddbb42b3d1e" +dependencies = [ + "bitmaps", + "typenum", +] + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +dependencies = [ + "serde", +] + +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +dependencies = [ + "lock_api", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tabled" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56c3ee73732ffceaea7b8f6b719ce3bb17f253fa27461ffeaf568ebd0cdb4b85" +dependencies = [ + "papergrid", + "tabled_derive", + "unicode-width", +] + +[[package]] +name = "tabled_derive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "beca1b4eaceb4f2755df858b88d9b9315b7ccfd1ffd0d7a48a52602301f01a57" +dependencies = [ + "heck 0.4.1", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3467d614147380f2e4e374161426ff399c91084acd2363eaf549172b3d5e60c0" +dependencies = [ + "thiserror-impl 2.0.16", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c5e1be1c48b9172ee610da68fd9cd2770e7a4056cb3fc98710ee6906f0c7960" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", +] + +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tinytemplate" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "tracing" +version = "0.1.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81383ab64e72a7a8b8e13130c49e3dab29def6d0c7d76a03087b3cf71c5c6903" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", +] + +[[package]] +name = "tracing-core" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2054a14f5307d601f88daf0553e1cbf472acc4f2c51afab632431cdcd72124d5" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "twox-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ea3136b675547379c4bd395ca6b938e5ad3c3d20fad76e7fe85f9e0d011419c" + +[[package]] +name = "typenum" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" + +[[package]] +name = "ucd-trie" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" + +[[package]] +name = "unicode-ident" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasi" +version = "0.14.4+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88a5f4a424faf49c3c2c344f166f0662341d470ea185e939657aaff130f0ec4a" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6" +dependencies = [ + "bumpalo", + "log", + "proc-macro2", + "quote", + "syn 2.0.106", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winapi-util" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0978bf7171b3d90bac376700cb56d606feb40f251a475a5d6634613564460b22" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "windows" +version = "0.61.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-link 0.1.3", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.1.3", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" +dependencies = [ + "windows-core", + "windows-link 0.1.3", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a47fddd13af08290e67f4acabf4b459f647552718f683a7b415d290ac744a836" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", +] + +[[package]] +name = "windows-interface" +version = "0.59.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd9211b69f8dcdfa817bfd14bf1c97c9188afa36f4750130fcdf3f400eca9fa8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", +] + +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" +dependencies = [ + "windows-core", + "windows-link 0.1.3", +] + +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-strings" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows-threading" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c573471f125075647d03df72e026074b7203790d41351cd6edc96f46bcccd36" + +[[package]] +name = "xxhash-rust" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdd20c5420375476fbd4394763288da7eb0cc0b8c11deed431a91562af7335d3" + +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + +[[package]] +name = "zerocopy" +version = "0.8.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", +] + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.16+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/vendor/loro-internal/Cargo.toml b/vendor/loro-internal/Cargo.toml new file mode 100644 index 0000000..0d93201 --- /dev/null +++ b/vendor/loro-internal/Cargo.toml @@ -0,0 +1,374 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +name = "loro-internal" +version = "1.17.1" +authors = [ + "Zixuan Chen", + "Liang Zhao", +] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Loro internal library. Do not use it directly as it's not stable." +homepage = "https://loro.dev" +documentation = "https://docs.rs/loro/" +readme = "README.md" +keywords = [ + "crdt", + "local-first", +] +categories = [] +license = "MIT" +repository = "https://github.com/loro-dev/loro/" + +[features] +counter = ["loro-common/counter"] +jsonpath = [] +logging = ["loro-common/logging"] +test_utils = [ + "arbitrary", + "tabled", +] +wasm = [ + "wasm-bindgen", + "js-sys", + "loro-common/wasm", +] + +[lib] +name = "loro_internal" +path = "src/lib.rs" +doctest = false +bench = false + +[[example]] +name = "automerge_x100" +path = "examples/automerge_x100.rs" + +[[example]] +name = "encoding" +path = "examples/encoding.rs" + +[[example]] +name = "encoding_parallel" +path = "examples/encoding_parallel.rs" + +[[example]] +name = "encoding_refactored" +path = "examples/encoding_refactored.rs" + +[[example]] +name = "event" +path = "examples/event.rs" + +[[example]] +name = "list" +path = "examples/list.rs" + +[[example]] +name = "many_actors" +path = "examples/many_actors.rs" + +[[example]] +name = "mem" +path = "examples/mem.rs" + +[[example]] +name = "obs" +path = "examples/obs.rs" + +[[example]] +name = "pending" +path = "examples/pending.rs" + +[[example]] +name = "state_size" +path = "examples/state_size.rs" + +[[example]] +name = "tree" +path = "examples/tree.rs" + +[[test]] +name = "autocommit" +path = "tests/autocommit.rs" + +[[test]] +name = "contracts" +path = "tests/contracts.rs" + +[[test]] +name = "ephemeral_store" +path = "tests/ephemeral_store.rs" + +[[test]] +name = "fugue" +path = "tests/fugue.rs" + +[[test]] +name = "handle_walk_memory" +path = "tests/handle_walk_memory.rs" + +[[test]] +name = "mergeable_cid_encoding" +path = "tests/mergeable_cid_encoding.rs" + +[[test]] +name = "mergeable_container" +path = "tests/mergeable_container.rs" + +[[test]] +name = "richtext" +path = "tests/richtext.rs" + +[[test]] +name = "test" +path = "tests/test.rs" + +[[test]] +name = "tree" +path = "tests/tree.rs" + +[[test]] +name = "undo" +path = "tests/undo.rs" + +[[test]] +name = "unknown_parent" +path = "tests/unknown_parent.rs" + +[[bench]] +name = "encode" +path = "benches/encode.rs" +harness = false + +[[bench]] +name = "event" +path = "benches/event.rs" +harness = false + +[[bench]] +name = "jsonpath" +path = "benches/jsonpath.rs" +harness = false + +[[bench]] +name = "list" +path = "benches/list.rs" +harness = false + +[[bench]] +name = "map" +path = "benches/map.rs" +harness = false + +[[bench]] +name = "pending" +path = "benches/pending.rs" +harness = false + +[[bench]] +name = "shallow_export" +path = "benches/shallow_export.rs" +harness = false + +[[bench]] +name = "text_r" +path = "benches/text_r.rs" +harness = false + +[[bench]] +name = "tree" +path = "benches/tree.rs" +harness = false + +[dependencies.append-only-bytes] +version = "0.1.12" +features = ["u32_range"] + +[dependencies.arbitrary] +version = "1" +optional = true + +[dependencies.arref] +version = "0.1.0" + +[dependencies.bytes] +version = "1" + +[dependencies.either] +version = "1" + +[dependencies.ensure-cov] +version = "0.1.0" + +[dependencies.enum-as-inner] +version = "0.6.0" + +[dependencies.enum_dispatch] +version = "0.3.11" + +[dependencies.fractional_index] +version = "1.13.0" +features = ["serde"] +package = "loro_fractional_index" + +[dependencies.generic-btree] +version = "^0.10.7" + +[dependencies.getrandom] +version = "0.2.15" + +[dependencies.im] +version = "15.1.0" +features = ["serde"] + +[dependencies.itertools] +version = "0.12.1" + +[dependencies.js-sys] +version = "0.3.60" +optional = true + +[dependencies.leb128] +version = "0.2.5" + +[dependencies.loro-common] +version = "1.17.0" + +[dependencies.loro-delta] +version = "1.13.0" +package = "loro-delta" + +[dependencies.loro-kv-store] +version = "1.17.0" + +[dependencies.md5] +version = "0.7.0" + +[dependencies.nonmax] +version = "0.5.5" + +[dependencies.num] +version = "0.4.0" + +[dependencies.num-traits] +version = "0.2" + +[dependencies.once_cell] +version = "1.18.0" + +[dependencies.parking_lot] +version = "0.12.5" + +[dependencies.pest] +version = "2.8.3" + +[dependencies.pest_derive] +version = "2.8.3" + +[dependencies.postcard] +version = "1" +features = ["use-std"] +default-features = false + +[dependencies.pretty_assertions] +version = "1.4.1" + +[dependencies.rand] +version = "0.8.5" + +[dependencies.rle] +version = "1.6.0" +package = "loro-rle" + +[dependencies.rustc-hash] +version = "2.1.1" + +[dependencies.serde] +version = "1" + +[dependencies.serde_columnar] +version = "0.3.14" +default-features = false + +[dependencies.serde_json] +version = "1.0" +features = ["float_roundtrip"] + +[dependencies.smallvec] +version = "1.8.0" +features = ["serde"] + +[dependencies.tabled] +version = "0.10.0" +optional = true + +[dependencies.thiserror] +version = "1" + +[dependencies.thread_local] +version = "1.1.8" + +[dependencies.tracing] +version = "0.1" + +[dependencies.wasm-bindgen] +version = "=0.2.100" +optional = true + +[dependencies.xxhash-rust] +version = "0.8.12" +features = ["xxh32"] + +[dev-dependencies.arbitrary] +version = "1" + +[dev-dependencies.criterion] +version = "0.7.0" +features = ["html_reports"] + +[dev-dependencies.ctor] +version = "0.1.23" + +[dev-dependencies.miniz_oxide] +version = "0.7.1" + +[dev-dependencies.rand] +version = "0.8.5" + +[dev-dependencies.tabled] +version = "0.10.0" + +[dev-dependencies.zstd] +version = "0.13.0" + +[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten"), not(target_os = "wasi")))'.dependencies.getrandom] +version = "0.2.15" +features = ["js"] + +[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten"), not(target_os = "wasi")))'.dependencies.wasm-bindgen] +version = "0.2.100" + +[target."cfg(loom)".dependencies.loom] +version = "0.7" +features = ["checkpoint"] + +[lints.rust.unexpected_cfgs] +level = "warn" +priority = 0 +check-cfg = ["cfg(loom)"] diff --git a/vendor/loro-internal/Cargo.toml.orig b/vendor/loro-internal/Cargo.toml.orig new file mode 100644 index 0000000..14e97f2 --- /dev/null +++ b/vendor/loro-internal/Cargo.toml.orig @@ -0,0 +1,134 @@ +[package] +name = "loro-internal" +version = "1.17.1" +edition = "2021" +license = "MIT" +description = "Loro internal library. Do not use it directly as it's not stable." +documentation = "https://docs.rs/loro/" +homepage = "https://loro.dev" +repository = "https://github.com/loro-dev/loro/" +authors = ["Zixuan Chen", "Liang Zhao"] +categories = [] +keywords = ["crdt", "local-first"] + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +generic-btree = { version = "^0.10.7" } +smallvec = { workspace = true } +loro-delta = { path = "../delta", version = "1.13.0", package = "loro-delta" } +rle = { path = "../rle", version = "1.6.0", package = "loro-rle" } +loro-common = { path = "../loro-common", version = "1.17.0" } +fractional_index = { path = "../fractional_index", features = [ + "serde", +], version = "1.13.0", package = "loro_fractional_index" } +loro-kv-store = { path = "../kv-store", version = "1.17.0" } +rustc-hash = { workspace = true } +serde = { workspace = true } +thiserror = { workspace = true } +enum-as-inner = { workspace = true } +serde_json = { workspace = true, features = ["float_roundtrip"] } +bytes = { workspace = true } +xxhash-rust = { workspace = true } +serde_columnar = { workspace = true } +itertools = { workspace = true } +enum_dispatch = { workspace = true } +once_cell = { workspace = true } +arbitrary = { version = "1", optional = true } +postcard = { version = "1", default-features = false, features = ["use-std"] } +append-only-bytes = { version = "0.1.12", features = ["u32_range"] } +im = { version = "15.1.0", features = ["serde"] } +tabled = { version = "0.10.0", optional = true } +wasm-bindgen = { version = "=0.2.100", optional = true } +js-sys = { version = "0.3.60", optional = true } +num = "0.4.0" +rand = { version = "0.8.5" } +getrandom = "0.2.15" +leb128 = "0.2.5" +num-traits = "0.2" +either = "1" +md5 = "0.7.0" +arref = "0.1.0" +tracing = { version = "0.1" } +nonmax = "0.5.5" +ensure-cov = { workspace = true } +pretty_assertions = "1.4.1" +thread_local = "1.1.8" +parking_lot = "0.12.5" +pest = "2.8.3" +pest_derive = "2.8.3" + +[target.'cfg(loom)'.dependencies] +loom = { version = "0.7", features = ["checkpoint"] } + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(loom)'] } + +[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten"), not(target_os = "wasi")))'.dependencies.getrandom] +version = "0.2.15" +features = ["js"] + +[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten"), not(target_os = "wasi")))'.dependencies] +wasm-bindgen = "0.2.100" + +[dev-dependencies] +arbitrary = { version = "1" } +miniz_oxide = "0.7.1" +rand = { version = "0.8.5" } +tabled = "0.10.0" +ctor = "0.1.23" +bench-utils = { path = "../bench-utils" } +dev-utils = { path = "../dev-utils" } +zstd = "0.13.0" +criterion = { version = "0.7.0", features = ["html_reports"] } + +# See https://matklad.github.io/2021/02/27/delete-cargo-integration-tests.html +[lib] +doctest = false +bench = false + +[features] +# "wasm" will use utf-16 index by default when using text related stuff; But it'll use utf-8 encoding internally. +wasm = ["wasm-bindgen", "js-sys", "loro-common/wasm"] +# whether to use list slice instead of raw str in text container +test_utils = ["arbitrary", "tabled"] +# whether enable the counter container +counter = ["loro-common/counter"] +logging = ["loro-common/logging"] +jsonpath = [] + +[[bench]] +name = "text_r" +harness = false + +[[bench]] +name = "list" +harness = false + +[[bench]] +name = "encode" +harness = false + +[[bench]] +name = "pending" +harness = false + +[[bench]] +name = "event" +harness = false + +[[bench]] +name = "map" +harness = false + +[[bench]] +name = "tree" +harness = false + +[[bench]] +name = "jsonpath" +harness = false + +[[bench]] +name = "shallow_export" +harness = false diff --git a/vendor/loro-internal/Encoding.md b/vendor/loro-internal/Encoding.md new file mode 100644 index 0000000..2815951 --- /dev/null +++ b/vendor/loro-internal/Encoding.md @@ -0,0 +1,25 @@ +# Encoding Schema + +## Header + +The header has 22 bytes. + +- (0-4 bytes) Magic Bytes: The encoding starts with `loro` as magic bytes. +- (4-20 bytes) Checksum: MD5/xxhash checksum of the encoded data, including the header starting from 20th bytes. The checksum is encoded as a 16-byte array (for xxhash, the first 12 bytes are padded with 0). The `checksum` and `magic bytes` fields are trimmed when calculating the checksum. +- (20-21 bytes) Encoding Method (2 bytes, big endian): Multiple encoding methods are available for a specific encoding version. + +## Encode Mode: Updates + +In this approach, only ops, specifically their historical record, are encoded, while document states are excluded. + +Like Automerge's format, we employ columnar encoding for operations and changes. + +Previously, operations were ordered by their Operation ID (OpId) before columnar encoding. However, sorting operations based on their respective containers initially enhance compression potential. + +## Encode Mode: Snapshot + +This mode simultaneously captures document state and historical data. Upon importing a snapshot into a new document, initialization occurs directly from the snapshot, bypassing the need for CRDT-based recalculations. + +Unlike previous snapshot encoding methods, the current binary output in snapshot mode is compatible with the updates mode. This enhances the efficiency of importing snapshots into non-empty documents, where initialization via snapshot is infeasible. + +Additionally, when feasible, we leverage the sequence of operations to construct state snapshots. In CRDTs, deducing the specific ops constituting the current container state is feasible. These ops are tagged in relation to the container, facilitating direct state reconstruction from them. This approach, pioneered by Automerge, significantly improves compression efficiency. diff --git a/vendor/loro-internal/README.md b/vendor/loro-internal/README.md new file mode 100644 index 0000000..d66d799 --- /dev/null +++ b/vendor/loro-internal/README.md @@ -0,0 +1,5 @@ +# loro-internal + +This is the internal implementation of Loro. +Its interface subject to change. You should not use it as dependency directly. +Consider use `loro` crate instead. diff --git a/vendor/loro-internal/VERSION b/vendor/loro-internal/VERSION new file mode 100644 index 0000000..507266b --- /dev/null +++ b/vendor/loro-internal/VERSION @@ -0,0 +1 @@ +1.17.1 \ No newline at end of file diff --git a/vendor/loro-internal/benches/automerge-paper.json.gz b/vendor/loro-internal/benches/automerge-paper.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..aa7f67ec0b02d5b21e8aa16a62879fc98d8b2daf GIT binary patch literal 901823 zcmV+aKLEfViwFo=9(`Z{17US^Z*66AXJsvLVQ^(~E^2dcZUF4P3wzr}mLU39@MY9% zX%^y$q~wRv+3z~G)9o4Ov39yM_gcOQNP;3P5?}yOGNb1H_IqCSM1iD0r@LqG&Nnl$ z2vni!)T#4++<#HkNm;)r@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_msqzV45Vu<)c<kF0lJde)VdSw9<g3 zmjS*k2=Sp`ikDr49X4<m-yks5zOj39?m3{Lj@II<<rXv^vfvCic{+rhcHWYm_J=Z> z@u|8u?^T(Y9y=}O4LA97O3poR*SW+$OkCM%)fVi6@kLs>*|Gjj#gR9DoITVdBCr|( zX!oc0YgO2Nw1uwUCK(d5?!V%sYWg=7H~TlmF89OXi8+F8yIlM;p`}l=1)uL)^LGht aJ(s$7{ySIV;lazp<1V55L&AKFWB&m&)!WVh literal 0 HcmV?d00001 diff --git a/vendor/loro-internal/benches/encode.rs b/vendor/loro-internal/benches/encode.rs new file mode 100644 index 0000000..96e2ea0 --- /dev/null +++ b/vendor/loro-internal/benches/encode.rs @@ -0,0 +1,398 @@ +use criterion::{criterion_group, criterion_main, Criterion}; +#[cfg(feature = "test_utils")] +mod sync { + + use super::*; + use bench_utils::{get_automerge_actions, TextAction}; + use loro_internal::{cursor::PosType, encoding::ExportMode, LoroDoc}; + + pub fn b4(c: &mut Criterion) { + let actions = get_automerge_actions(); + let mut b = c.benchmark_group("encode_with_sync"); + b.sample_size(10); + b.bench_function("update", |b| { + b.iter(|| { + let c1 = LoroDoc::new(); + c1.set_peer_id(1).unwrap(); + let c2 = LoroDoc::new(); + c2.set_peer_id(2).unwrap(); + let t1 = c1.get_text("text"); + let t2 = c2.get_text("text"); + for (i, action) in actions.iter().enumerate() { + if i > 2000 { + break; + } + let TextAction { pos, ins, del } = action; + if i % 2 == 0 { + let mut txn = c1.txn().unwrap(); + t1.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + t1.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + + let update = c1.export(ExportMode::updates(&c2.oplog_vv())).unwrap(); + c2.import(&update).unwrap(); + } else { + let mut txn = c2.txn().unwrap(); + t2.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + t2.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + let update = c2.export(ExportMode::updates(&c1.oplog_vv())).unwrap(); + c1.import(&update).unwrap(); + } + } + }) + }); + } +} +#[cfg(feature = "test_utils")] +mod run { + use super::*; + use bench_utils::TextAction; + use loro_internal::{cursor::PosType, encoding::ExportMode, LoroDoc}; + use std::hint::black_box; + + pub fn b4(c: &mut Criterion) { + let loro = LoroDoc::default(); + let mut ran = false; + let mut ensure_ran = || { + if !ran { + let actions = bench_utils::get_automerge_actions(); + let text = loro.get_text("text"); + for TextAction { pos, ins, del } in actions.iter() { + let mut txn = loro.txn().unwrap(); + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + } + ran = true; + } + }; + + let mut b = c.benchmark_group("encode"); + b.sample_size(10); + b.bench_function("B4_encode_updates", |b| { + ensure_ran(); + b.iter(|| { + let _ = loro.export(ExportMode::all_updates()).unwrap(); + }) + }); + b.bench_function("B4_decode_updates", |b| { + ensure_ran(); + let buf = loro.export(ExportMode::all_updates()).unwrap(); + + b.iter(|| { + let store2 = LoroDoc::default(); + store2.import(&buf).unwrap(); + }) + }); + b.bench_function("B4_decode_updates detached mode", |b| { + ensure_ran(); + let buf = loro.export(ExportMode::all_updates()).unwrap(); + + b.iter(|| { + let store2 = LoroDoc::default(); + store2.detach(); + store2.import(&buf).unwrap(); + }) + }); + b.bench_function("B4_encode_snapshot", |b| { + ensure_ran(); + b.iter(|| { + let _ = loro.export(ExportMode::Snapshot).unwrap(); + }) + }); + b.bench_function("B4_decode_snapshot", |b| { + ensure_ran(); + let buf = loro.export(ExportMode::Snapshot).unwrap(); + b.iter(|| { + let store2 = LoroDoc::default(); + store2.import(&buf).unwrap(); + }) + }); + + b.bench_function("B4_encode_json_update", |b| { + ensure_ran(); + b.iter(|| { + let _ = loro + .export_json_updates(&Default::default(), &loro.oplog_vv(), true) + .unwrap(); + }) + }); + b.bench_function("B4_decode_json_update", |b| { + ensure_ran(); + let json = loro + .export_json_updates(&Default::default(), &loro.oplog_vv(), true) + .unwrap(); + b.iter(|| { + let store2 = LoroDoc::default(); + store2.import_json_updates(json.clone()).unwrap(); + }) + }); + } + + fn build_issue_992_source_doc(paragraphs: usize) -> LoroDoc { + let doc = LoroDoc::new(); + doc.set_peer_id(1).unwrap(); + let text = doc.get_text("codemirror"); + let mut chunks = Vec::with_capacity(paragraphs); + for i in 0..paragraphs { + chunks.push(format!( + "# Section {i}\nParagraph {i} line A with repeated markdown content.\nParagraph {i} line B with **bold** and _italic_ markers.\n\n" + )); + } + text.insert(0, &chunks.concat(), PosType::Unicode).unwrap(); + doc.commit_then_renew(); + + for i in 0..6 { + text.insert( + text.len_unicode(), + &format!("Tail block {i}: {}\n", "x".repeat(2048)), + PosType::Unicode, + ) + .unwrap(); + doc.commit_then_renew(); + } + + for i in 0..3 { + let current = text.to_string(); + let next = current.replace(&format!("Section {i}"), &format!("Section {i} updated")) + + &format!("\nreplace-round-{i}:{}", "y".repeat(1024)); + text.delete(0, text.len_unicode(), PosType::Unicode) + .unwrap(); + text.insert(0, &next, PosType::Unicode).unwrap(); + doc.commit_then_renew(); + } + + doc + } + + fn clone_doc(doc: &LoroDoc) -> LoroDoc { + LoroDoc::from_snapshot(&doc.export(ExportMode::Snapshot).unwrap()).unwrap() + } + + fn build_issue_992_shallow_tail_doc(paragraphs: usize, tail_rounds: usize) -> LoroDoc { + let source = build_issue_992_source_doc(paragraphs); + let source = clone_doc(&source); + let shallow_bytes = source + .export(ExportMode::shallow_snapshot(&source.oplog_frontiers())) + .unwrap(); + let shallow_doc = LoroDoc::from_snapshot(&shallow_bytes).unwrap(); + let text = shallow_doc.get_text("codemirror"); + + for i in 0..tail_rounds { + let current = text.to_string(); + let next = current.replace(&format!("Section {i}"), &format!("Section {i} tail-{i}")) + + &format!("\npost-shallow-tail-{i}:{}", "z".repeat(4096)); + text.delete(0, text.len_unicode(), PosType::Unicode) + .unwrap(); + text.insert(0, &next, PosType::Unicode).unwrap(); + shallow_doc.commit_then_renew(); + } + + shallow_doc + } + + pub fn issue_992_shallow_snapshot_tail(c: &mut Criterion) { + let mut b = c.benchmark_group("encode_regression"); + b.sample_size(10); + + // This mirrors https://github.com/loro-dev/loro/issues/992: import a shallow + // snapshot, perform a few full-document text replacements, then export snapshot. + // The fixture is intentionally below the original report size so a regression is + // visible without making the default benchmark prohibitively slow. + let shallow_tail_doc = build_issue_992_shallow_tail_doc(1000, 2); + b.bench_function("issue_992_shallow_tail_snapshot_export", |b| { + b.iter(|| { + black_box(shallow_tail_doc.export(ExportMode::Snapshot).unwrap().len()); + }) + }); + } +} + +mod import { + use criterion::{BatchSize, Criterion}; + use loro_common::LoroValue; + use loro_internal::{cursor::PosType, encoding::ExportMode, LoroDoc}; + + #[allow(dead_code)] + pub fn causal_iter(c: &mut Criterion) { + let mut b = c.benchmark_group("causal_iter"); + b.sample_size(10); + b.bench_function("parallel_500", |b| { + b.iter(|| { + let c1 = LoroDoc::new(); + c1.set_peer_id(1).unwrap(); + let c2 = LoroDoc::new(); + c1.set_peer_id(2).unwrap(); + + let text1 = c1.get_text("text"); + let text2 = c2.get_text("text"); + for _ in 0..500 { + text1 + .insert_with_txn(&mut c1.txn().unwrap(), 0, "1", PosType::Unicode) + .unwrap(); + text2 + .insert_with_txn(&mut c2.txn().unwrap(), 0, "2", PosType::Unicode) + .unwrap(); + } + + let updates = c2.export(ExportMode::updates(&c1.oplog_vv())).unwrap(); + c1.import(&updates).unwrap() + }) + }); + } + + struct BinaryImportFixture { + base_update: Vec<u8>, + incremental_update: Vec<u8>, + } + + fn text_split_fixture(fragments: usize) -> BinaryImportFixture { + const CHUNK_LEN: usize = 256; + const PEER_A: u64 = 1; + const PEER_B: u64 = 2; + + let doc_len = CHUNK_LEN * fragments; + let doc_a = LoroDoc::new(); + doc_a.set_peer_id(PEER_A).unwrap(); + let text_a = doc_a.get_text("text"); + let mut txn = doc_a.txn().unwrap(); + text_a + .insert_with_txn(&mut txn, 0, &"a".repeat(doc_len), PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + let base_update = doc_a.export(ExportMode::all_updates()).unwrap(); + + let doc_b = LoroDoc::new(); + doc_b.set_peer_id(PEER_B).unwrap(); + let text_b = doc_b.get_text("text"); + doc_b.import(&base_update).unwrap(); + let base_vv = doc_b.oplog_vv(); + let mut txn = doc_b.txn().unwrap(); + for i in 0..(fragments - 1) { + let pos = (i + 1) * CHUNK_LEN + i; + text_b + .insert_with_txn(&mut txn, pos, "x", PosType::Unicode) + .unwrap(); + } + txn.commit().unwrap(); + let incremental_update = doc_b.export(ExportMode::updates(&base_vv)).unwrap(); + + BinaryImportFixture { + base_update, + incremental_update, + } + } + + fn list_diff_fixture(items: usize, inserts: usize) -> BinaryImportFixture { + const PEER_A: u64 = 11; + const PEER_B: u64 = 12; + + let doc_a = LoroDoc::new(); + doc_a.set_peer_id(PEER_A).unwrap(); + let list_a = doc_a.get_list("list"); + let mut txn = doc_a.txn().unwrap(); + for i in 0..items { + list_a + .insert_with_txn(&mut txn, i, LoroValue::I64(i as i64)) + .unwrap(); + } + txn.commit().unwrap(); + let base_update = doc_a.export(ExportMode::all_updates()).unwrap(); + + let doc_b = LoroDoc::new(); + doc_b.set_peer_id(PEER_B).unwrap(); + let list_b = doc_b.get_list("list"); + doc_b.import(&base_update).unwrap(); + let base_vv = doc_b.oplog_vv(); + let mut txn = doc_b.txn().unwrap(); + for i in 0..inserts { + let len = items + i; + let pos = (i * 7) % len; + list_b + .insert_with_txn(&mut txn, pos, LoroValue::I64(-((i as i64) + 1))) + .unwrap(); + } + txn.commit().unwrap(); + let incremental_update = doc_b.export(ExportMode::updates(&base_vv)).unwrap(); + + BinaryImportFixture { + base_update, + incremental_update, + } + } + + fn import_attached(fixture: &BinaryImportFixture) { + let doc = LoroDoc::new(); + doc.import(&fixture.base_update).unwrap(); + doc.import(&fixture.incremental_update).unwrap(); + } + + fn import_detached(fixture: &BinaryImportFixture) { + let doc = LoroDoc::new(); + doc.import(&fixture.base_update).unwrap(); + doc.detach(); + doc.import(&fixture.incremental_update).unwrap(); + } + + fn checkout_after_detached_import(fixture: &BinaryImportFixture) { + let doc = LoroDoc::new(); + doc.import(&fixture.base_update).unwrap(); + doc.detach(); + doc.import(&fixture.incremental_update).unwrap(); + doc.checkout_to_latest(); + } + + #[allow(dead_code)] + pub fn import_regression(c: &mut Criterion) { + let text_fixture = text_split_fixture(1024); + let list_fixture = list_diff_fixture(4096, 1024); + + let mut b = c.benchmark_group("import_regression"); + b.sample_size(10); + + b.bench_function("text_split_attached_import_1024", |b| { + b.iter_batched(|| &text_fixture, import_attached, BatchSize::SmallInput) + }); + b.bench_function("text_split_detached_import_1024", |b| { + b.iter_batched(|| &text_fixture, import_detached, BatchSize::SmallInput) + }); + b.bench_function("text_split_checkout_1024", |b| { + b.iter_batched( + || &text_fixture, + checkout_after_detached_import, + BatchSize::SmallInput, + ) + }); + b.bench_function("list_attached_import_4096x1024", |b| { + b.iter_batched(|| &list_fixture, import_attached, BatchSize::SmallInput) + }); + b.bench_function("list_checkout_4096x1024", |b| { + b.iter_batched( + || &list_fixture, + checkout_after_detached_import, + BatchSize::SmallInput, + ) + }); + } +} + +pub fn dumb(_c: &mut Criterion) {} + +#[cfg(feature = "test_utils")] +criterion_group!( + benches, + run::b4, + run::issue_992_shallow_snapshot_tail, + sync::b4, + import::causal_iter, + import::import_regression +); +#[cfg(not(feature = "test_utils"))] +criterion_group!(benches, dumb); +criterion_main!(benches); diff --git a/vendor/loro-internal/benches/event.rs b/vendor/loro-internal/benches/event.rs new file mode 100644 index 0000000..892a191 --- /dev/null +++ b/vendor/loro-internal/benches/event.rs @@ -0,0 +1,48 @@ +use criterion::{criterion_group, criterion_main, Criterion}; +#[cfg(feature = "test_utils")] +mod event { + use super::*; + + use loro_internal::{ListHandler, LoroDoc}; + use std::sync::Arc; + + fn create_sub_container(handler: ListHandler, children_num: usize) -> Vec<ListHandler> { + let mut ans = vec![]; + for idx in 0..children_num { + let child_handler = handler + .insert_container(idx, ListHandler::new_detached()) + .unwrap(); + ans.push(child_handler); + } + ans + } + + pub fn resolved_container(c: &mut Criterion) { + let mut b = c.benchmark_group("resolved"); + b.sample_size(10); + b.bench_function("subContainer in event", |b| { + let children_num = 80; + let deep = 3; + b.iter(|| { + let loro = LoroDoc::default(); + loro.start_auto_commit(); + let _g = loro.subscribe_root(Arc::new(|_e| {})); + let mut handlers = vec![loro.get_list("list")]; + for _ in 0..deep { + handlers = handlers + .into_iter() + .flat_map(|h| create_sub_container(h, children_num)) + .collect(); + } + }) + }); + } +} + +pub fn dumb(_c: &mut Criterion) {} + +#[cfg(feature = "test_utils")] +criterion_group!(benches, event::resolved_container); +#[cfg(not(feature = "test_utils"))] +criterion_group!(benches, dumb); +criterion_main!(benches); diff --git a/vendor/loro-internal/benches/jsonpath.rs b/vendor/loro-internal/benches/jsonpath.rs new file mode 100644 index 0000000..23696b0 --- /dev/null +++ b/vendor/loro-internal/benches/jsonpath.rs @@ -0,0 +1,317 @@ +use criterion::{criterion_group, criterion_main, Criterion}; + +#[cfg(feature = "test_utils")] +mod jsonpath { + use criterion::Criterion; + use loro_internal::{ListHandler, LoroDoc, MapHandler}; + use std::hint::black_box; + + // Sizes to test: small, medium, large + const SIZES: [usize; 3] = [100, 500, 2000]; + + /// Setup a large document with: + /// - books[0..size] with title, author, price, available + /// - '1984' by George Orwell every ~100 items + /// - Nested structure under $.catalog.fiction.books for recursive tests + fn setup_large_doc(size: usize) -> LoroDoc { + let doc = LoroDoc::new_auto_commit(); + let store = doc.get_map("store"); + let books = store + .insert_container("books", ListHandler::new_detached()) + .unwrap(); + + for i in 0..size { + let book = books + .insert_container(i, MapHandler::new_detached()) + .unwrap(); + let title = if i % 100 == 42 { + "1984" + } else { + &format!("Book {}", i) + }; + let author = if i % 100 == 42 { + "George Orwell" + } else { + &format!("Author {}", i % 10) + }; + let price = 5.0 + (i % 25) as f64; + let available = i % 4 != 0; + + book.insert("title", title).unwrap(); + book.insert("author", author).unwrap(); + book.insert("price", price).unwrap(); + book.insert("available", available).unwrap(); + } + + // Add nested structure for $..title and recursive filters + let catalog = doc.get_map("catalog"); + let fiction = catalog + .insert_container("fiction", MapHandler::new_detached()) + .unwrap(); + let nested_books = fiction + .insert_container("books", ListHandler::new_detached()) + .unwrap(); + for i in 0..10 { + let b = nested_books + .insert_container(i, MapHandler::new_detached()) + .unwrap(); + b.insert("title", format!("Nested {}", i)).unwrap(); + b.insert("price", 12.0 + i as f64).unwrap(); + } + + doc + } + + /// Benchmark a single JSONPath query across all sizes + fn bench_pattern<F>(c: &mut Criterion, group_name: &str, query: &str, setup: F) + where + F: Fn(usize) -> LoroDoc, + { + let mut group = c.benchmark_group(group_name); + group.sample_size(if group_name.contains("large") { 20 } else { 50 }); + + for &size in &SIZES { + let doc = setup(size); + let name = format!("{} (size={})", query, size); + group.bench_function(&name, |b| { + b.iter(|| { + let result = doc.jsonpath(query).unwrap(); + black_box(result); + }) + }); + } + group.finish(); + } + + pub fn child_selector(c: &mut Criterion) { + bench_pattern( + c, + "Child Selector", + "$.store.books[0].title", + setup_large_doc, + ); + } + + pub fn wildcard(c: &mut Criterion) { + bench_pattern(c, "Wildcard", "$.store.books[*].title", setup_large_doc); + } + + pub fn recursive_descent(c: &mut Criterion) { + bench_pattern(c, "Recursive Descent", "$..title", setup_large_doc); + } + + pub fn quoted_keys(c: &mut Criterion) { + bench_pattern( + c, + "Quoted Keys", + "$.store['books'][0]['title']", + setup_large_doc, + ); + } + + pub fn string_filter(c: &mut Criterion) { + bench_pattern( + c, + "String Filter", + "$.store.books[?(@.title == '1984')].title", + setup_large_doc, + ); + } + + pub fn logical_operator(c: &mut Criterion) { + bench_pattern( + c, + "Logical Operator", + "$.store.books[?(@.author == 'George Orwell' && @.price < 10)].title", + setup_large_doc, + ); + } + + pub fn union_operation(c: &mut Criterion) { + bench_pattern( + c, + "Union Operation", + "$.store.books[0,2].title", + setup_large_doc, + ); + } + + pub fn slice_operation(c: &mut Criterion) { + let mut group = c.benchmark_group("Slice Operation"); + + for &size in &SIZES { + let doc = setup_large_doc(size); + + // Small slice + group.bench_function(format!("$.store.books[0:3].title (size={})", size), |b| { + b.iter(|| { + let result = doc.jsonpath("$.store.books[0:3].title").unwrap(); + black_box(result); + }) + }); + + // Large slice (half) + let half = size / 2; + group.bench_function( + format!("$.store.books[0:{}].title (size={})", half, size), + |b| { + b.iter(|| { + let result = doc + .jsonpath(&format!("$.store.books[0:{}].title", half)) + .unwrap(); + black_box(result); + }) + }, + ); + + // Negative slice + group.bench_function(format!("$.store.books[-10:].title (size={})", size), |b| { + b.iter(|| { + let result = doc.jsonpath("$.store.books[-10:].title").unwrap(); + black_box(result); + }) + }); + } + group.finish(); + } + + pub fn complex_filter(c: &mut Criterion) { + bench_pattern( + c, + "Complex Filter", + "$.store.books[?(@.price >= 10 && @.available == true && @.title contains '1984')].title", + setup_large_doc, + ); + } + + pub fn recursive_mapped_filter(c: &mut Criterion) { + bench_pattern( + c, + "Recursive Mapped Filter", + "$.store.books[?(@.price > 10)].title", + setup_large_doc, + ); + } + + pub fn recursive_filter(c: &mut Criterion) { + bench_pattern( + c, + "Recursive Filter", + "$..[?(@.price > 10)].title", + setup_large_doc, + ); + } + + // === Legacy / Extra: Keep your original ones (now size-scaled) === + + pub fn index_selector(c: &mut Criterion) { + let mut group = c.benchmark_group("Index Selector"); + group.sample_size(50); + + for &size in &SIZES { + let doc = setup_large_doc(size); + let idx = (size as i64 / 2).min(42); // Safe index + group.bench_function(format!("positive index {} (size={})", idx, size), |b| { + b.iter(|| { + let result = doc + .jsonpath(&format!("$.store.books[{}].title", idx)) + .unwrap(); + black_box(result); + }) + }); + + group.bench_function(format!("negative index -10 (size={})", size), |b| { + b.iter(|| { + let result = doc.jsonpath("$.store.books[-10].title").unwrap(); + black_box(result); + }) + }); + } + group.finish(); + } + + pub fn union_key_selector(c: &mut Criterion) { + let mut group = c.benchmark_group("Union Key Selector"); + group.sample_size(50); + + for &size in &SIZES { + let doc = setup_large_doc(size); + group.bench_function(format!("two keys single item (size={})", size), |b| { + b.iter(|| { + let result = doc.jsonpath("$.store.books[42]['title','author']").unwrap(); + black_box(result); + }) + }); + + group.bench_function(format!("three keys slice (size={})", size), |b| { + b.iter(|| { + let result = doc + .jsonpath("$.store.books[0:10]['title','author','price']") + .unwrap(); + black_box(result); + }) + }); + } + group.finish(); + } + + pub fn mixed_selectors(c: &mut Criterion) { + bench_pattern( + c, + "Mixed Selectors", + "$.store.books[0,5:15,20].title", + setup_large_doc, + ); + } + + pub fn real_world_patterns(c: &mut Criterion) { + let mut group = c.benchmark_group("Real World Patterns"); + group.sample_size(50); + + for &size in &SIZES { + let doc = setup_large_doc(size); + group.bench_function(format!("last 10 items (size={})", size), |b| { + b.iter(|| { + let result = doc.jsonpath("$.store.books[-10:].title").unwrap(); + black_box(result); + }) + }); + + group.bench_function(format!("pagination page 1 (size={})", size), |b| { + b.iter(|| { + let result = doc.jsonpath("$.store.books[0:20].title").unwrap(); + black_box(result); + }) + }); + } + group.finish(); + } + + // === Master Group === + pub fn all_benches(c: &mut Criterion) { + child_selector(c); + wildcard(c); + recursive_descent(c); + quoted_keys(c); + string_filter(c); + logical_operator(c); + union_operation(c); + slice_operation(c); + complex_filter(c); + recursive_mapped_filter(c); + recursive_filter(c); + index_selector(c); + union_key_selector(c); + mixed_selectors(c); + real_world_patterns(c); + } +} + +pub fn dumb(_c: &mut Criterion) {} + +#[cfg(feature = "test_utils")] +criterion_group!(benches, jsonpath::all_benches); +#[cfg(not(feature = "test_utils"))] +criterion_group!(benches, dumb); + +criterion_main!(benches); diff --git a/vendor/loro-internal/benches/list.rs b/vendor/loro-internal/benches/list.rs new file mode 100644 index 0000000..4e2a7cc --- /dev/null +++ b/vendor/loro-internal/benches/list.rs @@ -0,0 +1,119 @@ +use criterion::{criterion_group, criterion_main, Criterion}; +#[cfg(feature = "test_utils")] +mod run { + use super::*; + use arbitrary::Arbitrary; + use arbitrary::Unstructured; + use loro_internal::cursor::PosType; + use loro_internal::loro::ExportMode; + use loro_internal::LoroDoc; + use loro_internal::LoroValue; + use rand::Rng; + use rand::SeedableRng; + + pub fn many_list_containers(c: &mut Criterion) { + #[derive(Arbitrary)] + struct Action { + container: u8, + actor: u8, + pos: u8, + value: u8, + sync: u8, + } + + let mut rgn = rand::rngs::StdRng::seed_from_u64(0); + let mut bytes = Vec::new(); + for _ in 0..10000 { + bytes.push(rgn.gen::<u8>()); + } + + let mut gen = Unstructured::new(&bytes); + let actions: [Action; 200] = gen.arbitrary().unwrap(); + let mut b = c.benchmark_group("10 list containers"); + b.sample_size(10); + b.bench_function("sync random inserts to 10 list containers", |b| { + b.iter(|| { + let mut actors: Vec<_> = (0..10).map(|_| LoroDoc::default()).collect(); + for action in actions.iter() { + let len = actors.len(); + let actor = &mut actors[action.actor as usize % len]; + let container = action.container % 10; + if container % 2 == 0 { + let text = actor.get_text(container.to_string().as_str()); + let mut txn = actor.txn().unwrap(); + text.insert_with_txn( + &mut txn, + (action.pos as usize) % text.len_unicode().max(1), + action.value.to_string().as_str(), + PosType::Unicode, + ) + .unwrap(); + } else { + let list = actor.get_list(container.to_string().as_str()); + let mut txn = actor.txn().unwrap(); + list.insert_with_txn( + &mut txn, + (action.pos as usize) % list.len().max(1), + action.value.to_string().as_str().into(), + ) + .unwrap(); + } + + let a = (action.actor as usize) % len; + let b = (action.sync as usize) % len; + if a != b { + let (a, b) = arref::array_mut_ref!(&mut actors, [a, b]); + a.import(&b.export(ExportMode::updates(&a.oplog_vv())).unwrap()) + .unwrap(); + } + } + + for i in 1..actors.len() { + let (a, b) = arref::array_mut_ref!(&mut actors, [0, i]); + a.import(&b.export(ExportMode::updates(&a.oplog_vv())).unwrap()) + .unwrap(); + } + for i in 1..actors.len() { + let (a, b) = arref::array_mut_ref!(&mut actors, [i, 0]); + a.import(&b.export(ExportMode::updates(&a.oplog_vv())).unwrap()) + .unwrap(); + } + }) + }); + } + + pub fn many_actors(c: &mut Criterion) { + let mut b = c.benchmark_group("many_actors"); + b.sample_size(10); + b.bench_function("100 actors", |b| { + b.iter(|| { + let mut actors: Vec<_> = (0..100).map(|_| LoroDoc::default()).collect(); + for (i, actor) in actors.iter_mut().enumerate() { + let list = actor.get_list("list"); + let value: LoroValue = i.to_string().into(); + let mut txn = actor.txn().unwrap(); + list.insert_with_txn(&mut txn, 0, value).unwrap(); + } + + for i in 1..actors.len() { + let (a, b) = arref::array_mut_ref!(&mut actors, [0, i]); + a.import(&b.export(ExportMode::updates(&a.oplog_vv())).unwrap()) + .unwrap(); + } + + for i in 1..actors.len() { + let (a, b) = arref::array_mut_ref!(&mut actors, [0, i]); + b.import(&a.export(ExportMode::updates(&b.oplog_vv())).unwrap()) + .unwrap(); + } + }) + }); + } +} +pub fn dumb(_c: &mut Criterion) {} + +#[cfg(feature = "test_utils")] +criterion_group!(benches, run::many_list_containers, run::many_actors); +#[cfg(not(feature = "test_utils"))] +criterion_group!(benches, dumb); +criterion_main!(benches); diff --git a/vendor/loro-internal/benches/map.rs b/vendor/loro-internal/benches/map.rs new file mode 100644 index 0000000..18daac9 --- /dev/null +++ b/vendor/loro-internal/benches/map.rs @@ -0,0 +1,85 @@ +use criterion::{criterion_group, criterion_main, Criterion}; +#[cfg(feature = "test_utils")] +mod map { + use super::*; + use loro_internal::{loro::ExportMode, LoroDoc}; + use rand::{rngs::StdRng, Rng}; + + pub fn tree_move(c: &mut Criterion) { + let mut b = c.benchmark_group("map crdt"); + b.sample_size(10); + b.bench_function("create 10^4 key", |b| { + let size = 10000; + b.iter(|| { + let loro = LoroDoc::new_auto_commit(); + let map = loro.get_map("map"); + for i in 0..size { + map.insert(&i.to_string(), i).unwrap(); + } + loro.commit_then_renew(); + }) + }); + + b.bench_function("map checkout 10^3", |b| { + let loro = LoroDoc::new_auto_commit(); + let map = loro.get_map("map"); + let mut versions = vec![]; + let size = 10000; + let mut rng: StdRng = rand::SeedableRng::seed_from_u64(0); + for i in 0..size { + versions.push(loro.oplog_frontiers()); + map.insert(&rng.gen::<u8>().to_string(), i).unwrap(); + loro.commit_then_renew(); + } + + b.iter(|| { + for _ in 0..1000 { + let i = rng.gen::<usize>() % 1000; + let f = &versions[i]; + loro.checkout(f).unwrap(); + } + }) + }); + + b.bench_function("realtime map set", |b| { + let doc_a = LoroDoc::default(); + let doc_b = LoroDoc::default(); + let map_a = doc_a.get_map("map"); + let map_b = doc_b.get_map("map"); + let n = 1000; + b.iter(|| { + for t in 0..n { + if t % 2 == 0 { + let mut txn = doc_a.txn().unwrap(); + map_a.insert_with_txn(&mut txn, "key", t.into()).unwrap(); + doc_b + .import( + &doc_a + .export(ExportMode::updates(&doc_b.oplog_vv())) + .unwrap(), + ) + .unwrap(); + } else { + let mut txn = doc_b.txn().unwrap(); + map_b.insert_with_txn(&mut txn, "key", t.into()).unwrap(); + doc_a + .import( + &doc_b + .export(ExportMode::updates(&doc_a.oplog_vv())) + .unwrap(), + ) + .unwrap(); + } + } + }) + }); + } +} + +pub fn dumb(_c: &mut Criterion) {} + +#[cfg(feature = "test_utils")] +criterion_group!(benches, map::tree_move); +#[cfg(not(feature = "test_utils"))] +criterion_group!(benches, dumb); +criterion_main!(benches); diff --git a/vendor/loro-internal/benches/pending.rs b/vendor/loro-internal/benches/pending.rs new file mode 100644 index 0000000..0cede19 --- /dev/null +++ b/vendor/loro-internal/benches/pending.rs @@ -0,0 +1,47 @@ +use criterion::{criterion_group, criterion_main, Criterion}; +#[cfg(feature = "test_utils")] +mod pending { + use super::*; + use bench_utils::TextAction; + use loro_internal::{cursor::PosType, loro::ExportMode, LoroDoc, VersionVector}; + + pub fn b4(c: &mut Criterion) { + let mut b = c.benchmark_group("B4 pending decode"); + b.sample_size(10); + b.bench_function("detached mode", |b| { + let loro = LoroDoc::default(); + let mut latest_vv = VersionVector::default(); + let mut updates = vec![]; + let actions = bench_utils::get_automerge_actions(); + let action_length = actions.len(); + let text = loro.get_text("text"); + for chunks in actions.chunks(action_length / 5) { + for TextAction { pos, ins, del } in chunks { + let mut txn = loro.txn().unwrap(); + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + updates.push(loro.export(ExportMode::updates(&latest_vv)).unwrap()); + latest_vv = loro.oplog_vv(); + } + } + updates.reverse(); + b.iter(|| { + let store2 = LoroDoc::default(); + store2.detach(); + for update in updates.iter() { + store2.import(update).unwrap(); + } + }) + }); + } +} + +pub fn dumb(_c: &mut Criterion) {} + +#[cfg(feature = "test_utils")] +criterion_group!(benches, pending::b4); +#[cfg(not(feature = "test_utils"))] +criterion_group!(benches, dumb); +criterion_main!(benches); diff --git a/vendor/loro-internal/benches/shallow_export.rs b/vendor/loro-internal/benches/shallow_export.rs new file mode 100644 index 0000000..b6acbd3 --- /dev/null +++ b/vendor/loro-internal/benches/shallow_export.rs @@ -0,0 +1,164 @@ +use criterion::{criterion_group, criterion_main, Criterion}; +use loro_internal::{encoding::ExportMode, version::Frontiers, LoroDoc}; +use std::hint::black_box; + +/// Build a doc shaped like a real workspace export: a root list of +/// `OUTER_DOCS` maps, each with a nested list of `INNER_ITEMS` maps, each +/// holding `TEXTS_PER_ITEM` short text containers. Every text is written with +/// `OPS_PER_TEXT` single-character inserts to simulate streaming edits. +/// +/// With the defaults this produces ~66k containers and ~720k ops. +fn build_structured_doc() -> (LoroDoc, Frontiers) { + const OUTER_DOCS: usize = 200; + const INNER_ITEMS: usize = 30; + const TEXTS_PER_ITEM: usize = 10; + const OPS_PER_TEXT: usize = 12; + + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let root = doc.get_list("docs"); + let mut mid = None; + for i in 0..OUTER_DOCS { + let map = root + .insert_container(i, loro_internal::handler::MapHandler::new_detached()) + .unwrap(); + let items = map + .insert_container("items", loro_internal::handler::ListHandler::new_detached()) + .unwrap(); + for j in 0..INNER_ITEMS { + let item = items + .insert_container(j, loro_internal::handler::MapHandler::new_detached()) + .unwrap(); + for k in 0..TEXTS_PER_ITEM { + let text = item + .insert_container( + &format!("t{k}"), + loro_internal::handler::TextHandler::new_detached(), + ) + .unwrap(); + for n in 0..OPS_PER_TEXT { + text.insert(n, "x", loro_internal::cursor::PosType::Unicode) + .unwrap(); + } + } + } + if i == OUTER_DOCS / 2 { + mid = Some(doc.oplog_frontiers()); + } + } + (doc, mid.unwrap()) +} + +fn shallow_export(c: &mut Criterion) { + let (doc, mid_frontiers) = build_structured_doc(); + let mut g = c.benchmark_group("shallow_export"); + g.sample_size(10); + g.bench_function("full_snapshot", |b| { + b.iter(|| black_box(doc.export(ExportMode::Snapshot).unwrap())) + }); + g.bench_function("shallow_snapshot", |b| { + b.iter(|| { + black_box( + doc.export(ExportMode::shallow_snapshot(&mid_frontiers)) + .unwrap(), + ) + }) + }); + g.finish(); +} + +/// A document imported from a snapshot and never read stays lazy: exporting a +/// shallow snapshot at the latest version must not materialize the whole +/// state. Each iteration exports from a freshly imported doc, so this measures +/// the cold path (setup time is excluded). +fn shallow_export_lazy(c: &mut Criterion) { + let (doc, _) = build_structured_doc(); + let full = doc.export(ExportMode::Snapshot).unwrap(); + let latest = doc.oplog_frontiers(); + let mut g = c.benchmark_group("shallow_export_lazy"); + g.sample_size(10); + g.bench_function("at_latest", |b| { + b.iter_batched( + || { + let lazy = LoroDoc::new(); + lazy.import(&full).unwrap(); + lazy + }, + |lazy| black_box(lazy.export(ExportMode::shallow_snapshot(&latest)).unwrap()), + criterion::BatchSize::LargeInput, + ) + }); + g.finish(); +} + +/// Regression guard for the forward-replay gate's prefix bound: a huge +/// pre-root prefix of unrelated scalar overwrites must not be re-encoded and +/// replayed just because the retained tail clears the 65536-op threshold. +/// With the prefix/tail ratio and absolute caps this export stays on the +/// checkout path, whose cost is bounded by the tail. +fn shallow_export_scalar_prefix_heavy(c: &mut Criterion) { + const PREFIX_OPS: usize = 2_000_000; + + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let map = doc.get_map("m"); + for i in 0..PREFIX_OPS { + map.insert("k", i as i64).unwrap(); + } + let f = doc.oplog_frontiers(); + // One big-atom insert past the 65536-op retained threshold. + doc.get_text("t") + .insert( + 0, + &"x".repeat(70_000), + loro_internal::cursor::PosType::Unicode, + ) + .unwrap(); + + let mut g = c.benchmark_group("shallow_export_scalar_prefix"); + g.sample_size(10); + g.bench_function("export", |b| { + b.iter(|| black_box(doc.export(ExportMode::shallow_snapshot(&f)).unwrap())) + }); + g.finish(); +} + +/// Regression guard for the gate's byte bound: a byte-heavy but low-op prefix +/// (few large Map values) must not be replayed just because the retained tail +/// clears the op threshold — a Map write is one atom regardless of value +/// size. With the encoded-byte cap this export stays on the checkout path. +fn shallow_export_byte_prefix_heavy(c: &mut Criterion) { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let map = doc.get_map("m"); + // 64 distinct 1 MiB values to the same key: 64 atoms, ~64 MiB of prefix + // history. Distinct values matter — identical strings dedup in the arena. + for i in 0..64 { + let big = format!("{i:08}{}", "v".repeat(1 << 20)); + map.insert("k", big.as_str()).unwrap(); + } + let f = doc.oplog_frontiers(); + doc.get_text("t") + .insert( + 0, + &"x".repeat(70_000), + loro_internal::cursor::PosType::Unicode, + ) + .unwrap(); + + let mut g = c.benchmark_group("shallow_export_byte_prefix"); + g.sample_size(10); + g.bench_function("export", |b| { + b.iter(|| black_box(doc.export(ExportMode::shallow_snapshot(&f)).unwrap())) + }); + g.finish(); +} + +criterion_group!( + benches, + shallow_export, + shallow_export_lazy, + shallow_export_scalar_prefix_heavy, + shallow_export_byte_prefix_heavy +); +criterion_main!(benches); diff --git a/vendor/loro-internal/benches/text_r.rs b/vendor/loro-internal/benches/text_r.rs new file mode 100644 index 0000000..96c2e65 --- /dev/null +++ b/vendor/loro-internal/benches/text_r.rs @@ -0,0 +1,432 @@ +use criterion::{criterion_group, criterion_main, Criterion}; + +#[cfg(feature = "test_utils")] +mod run { + use std::hint::black_box; + use std::sync::Arc; + + use super::*; + use bench_utils::TextAction; + use loro_common::LoroValue; + use loro_internal::{cursor::PosType, loro::ExportMode, LoroDoc}; + + pub fn b4(c: &mut Criterion) { + let actions = bench_utils::get_automerge_actions(); + let mut b = c.benchmark_group("refactored direct_apply"); + b.sample_size(10); + b.bench_function("B4", |b| { + b.iter(|| { + let loro = LoroDoc::default(); + let text = loro.get_text("text"); + let mut txn = loro.txn().unwrap(); + + for TextAction { pos, ins, del } in actions.iter() { + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + } + }) + }); + + b.bench_function("B4 with 100K actors history", |b| { + let store = LoroDoc::default(); + for i in 0..100_000 { + store.set_peer_id(i).unwrap(); + let list = store.get_list("list"); + let value: LoroValue = i.to_string().into(); + let mut txn = store.txn().unwrap(); + list.insert_with_txn(&mut txn, 0, value).unwrap(); + txn.commit().unwrap(); + } + + let update = store.export(ExportMode::Snapshot).unwrap(); + drop(store); + b.iter_batched( + || { + let loro = LoroDoc::default(); + loro.import(&update).unwrap(); + loro + }, + |loro| { + let text = loro.get_text("text"); + let mut txn = loro.txn().unwrap(); + + for TextAction { pos, ins, del } in actions.iter() { + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + } + }, + criterion::BatchSize::SmallInput, + ) + }); + + b.bench_function("B4 Obs", |b| { + b.iter(|| { + let loro = LoroDoc::default(); + let text = loro.get_text("text"); + let _g = loro.subscribe_root(Arc::new(move |event| { + black_box(event); + })); + let mut txn = loro.txn().unwrap(); + for TextAction { pos, ins, del } in actions.iter() { + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + } + }) + }); + + b.bench_function("B4 encode snapshot", |b| { + let loro = LoroDoc::default(); + let text = loro.get_text("text"); + + let mut n = 0; + let mut txn = loro.txn().unwrap(); + for TextAction { pos, ins, del } in actions.iter() { + if n == 10 { + n = 0; + drop(txn); + txn = loro.txn().unwrap(); + } + n += 1; + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + } + txn.commit().unwrap(); + + b.iter(|| { + loro.export(ExportMode::Snapshot).unwrap(); + }); + }); + + b.bench_function("B4 encode updates", |b| { + let loro = LoroDoc::default(); + let text = loro.get_text("text"); + + let mut n = 0; + let mut txn = loro.txn().unwrap(); + for TextAction { pos, ins, del } in actions.iter() { + if n == 10 { + n = 0; + drop(txn); + txn = loro.txn().unwrap(); + } + n += 1; + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + } + txn.commit().unwrap(); + + b.iter(|| { + loro.export(ExportMode::all_updates()).unwrap(); + }); + }); + + b.bench_function("B4 decode snapshot", |b| { + let loro = LoroDoc::default(); + let text = loro.get_text("text"); + let mut n = 0; + let mut txn = loro.txn().unwrap(); + for TextAction { pos, ins, del } in actions.iter() { + if n == 10 { + n = 0; + drop(txn); + txn = loro.txn().unwrap(); + } + n += 1; + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + } + txn.commit().unwrap(); + + let data = loro.export(ExportMode::Snapshot).unwrap(); + b.iter(|| { + let l = LoroDoc::new(); + l.import(&data).unwrap(); + }); + }); + + b.bench_function("B4 import updates", |b| { + let loro = LoroDoc::default(); + let text = loro.get_text("text"); + + let mut n = 0; + let mut txn = loro.txn().unwrap(); + for TextAction { pos, ins, del } in actions.iter() { + if n == 10 { + n = 0; + drop(txn); + txn = loro.txn().unwrap(); + } + n += 1; + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + } + txn.commit().unwrap(); + + let data = loro.export(ExportMode::all_updates()).unwrap(); + b.iter(|| { + let l = LoroDoc::new(); + l.import(&data).unwrap(); + }); + }); + + // b.bench_function("B4 utf16", |b| { + // b.iter(|| { + // let loro = LoroDoc::new(); + // let text = loro.get_text("text"); + // let mut txn = loro.txn().unwrap(); + + // for TextAction { pos, ins, del } in actions.iter() { + // text.delete_utf16(&mut txn, *pos, *del).unwrap(); + // text.insert_utf16(&mut txn, *pos, ins).unwrap(); + // } + // }) + // }); + + b.bench_function("B4_Per100_Txn", |b| { + b.iter(|| { + let loro = LoroDoc::default(); + let text = loro.get_text("text"); + let mut n = 0; + let mut txn = loro.txn().unwrap(); + for TextAction { pos, ins, del } in actions.iter() { + if n == 100 { + n = 0; + drop(txn); + txn = loro.txn().unwrap(); + } + n += 1; + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + } + }) + }); + + b.bench_function("B4 One Op One Txn", |b| { + b.iter(|| { + let loro = LoroDoc::default(); + let text = loro.get_text("text"); + { + for TextAction { pos, ins, del } in actions.iter() { + let mut txn = loro.txn().unwrap(); + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + } + } + }) + }); + + b.bench_function("B4 One Op One Txn Obs", |b| { + b.iter(|| { + let loro = LoroDoc::default(); + let text = loro.get_text("text"); + let _g = loro.subscribe_root(Arc::new(move |event| { + black_box(event); + })); + { + for TextAction { pos, ins, del } in actions.iter() { + let mut txn = loro.txn().unwrap(); + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + } + } + }) + }); + + b.bench_function("B4DirectSync", |b| { + b.iter(|| { + let loro = LoroDoc::default(); + let loro_b = LoroDoc::default(); + let text = loro.get_text("text"); + for TextAction { pos, ins, del } in actions.iter() { + { + let mut txn = loro.txn().unwrap(); + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + } + + loro_b + .import( + &loro + .export(ExportMode::updates(&loro_b.oplog_vv())) + .unwrap(), + ) + .unwrap(); + } + }) + }); + + drop(b); + let mut b = c.benchmark_group("refactored-sync"); + b.bench_function("B4Parallel", |b| { + b.iter(|| { + let loro = LoroDoc::default(); + let loro_b = LoroDoc::default(); + let text = loro.get_text("text"); + let text2 = loro_b.get_text("text"); + let mut i = 0; + for TextAction { pos, ins, del } in actions.iter() { + let pos = *pos; + let del = *del; + i += 1; + if i > 1000 { + break; + } + + { + let mut txn = loro.txn().unwrap(); + text.delete_with_txn(&mut txn, pos, del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, pos, ins, PosType::Unicode) + .unwrap(); + } + + { + let mut txn = loro_b.txn().unwrap(); + text2 + .delete_with_txn(&mut txn, pos, del, PosType::Unicode) + .unwrap(); + text2 + .insert_with_txn(&mut txn, pos, ins, PosType::Unicode) + .unwrap(); + } + loro_b + .import( + &loro + .export(ExportMode::updates(&loro_b.oplog_vv())) + .unwrap(), + ) + .unwrap(); + loro.import( + &loro_b + .export(ExportMode::updates(&loro.oplog_vv())) + .unwrap(), + ) + .unwrap(); + } + }) + }); + + let b = b.sample_size(10); + b.bench_function("DecodeUpdates B4Parallel", |b| { + let loro = LoroDoc::default(); + let loro_b = LoroDoc::default(); + let text = loro.get_text("text"); + let text2 = loro_b.get_text("text"); + for TextAction { pos, ins, del } in actions.iter() { + let pos = *pos; + let del = *del; + { + let mut txn = loro.txn().unwrap(); + text.delete_with_txn(&mut txn, pos, del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, pos, ins, PosType::Unicode) + .unwrap(); + } + + { + let mut txn = loro_b.txn().unwrap(); + text2 + .delete_with_txn(&mut txn, pos, del, PosType::Unicode) + .unwrap(); + text2 + .insert_with_txn(&mut txn, pos, ins, PosType::Unicode) + .unwrap(); + } + loro_b + .import( + &loro + .export(ExportMode::updates(&loro_b.oplog_vv())) + .unwrap(), + ) + .unwrap(); + loro.import( + &loro_b + .export(ExportMode::updates(&loro.oplog_vv())) + .unwrap(), + ) + .unwrap(); + } + let data = loro.export(ExportMode::all_updates()).unwrap(); + b.iter(|| { + let loro = LoroDoc::default(); + loro.import(&data).unwrap(); + }) + }); + b.bench_function("DecodeSnapshot B4Parallel", |b| { + let loro = LoroDoc::default(); + let loro_b = LoroDoc::default(); + let text = loro.get_text("text"); + let text2 = loro_b.get_text("text"); + for TextAction { pos, ins, del } in actions.iter() { + let pos = *pos; + let del = *del; + { + let mut txn = loro.txn().unwrap(); + text.delete_with_txn(&mut txn, pos, del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, pos, ins, PosType::Unicode) + .unwrap(); + } + + { + let mut txn = loro_b.txn().unwrap(); + text2 + .delete_with_txn(&mut txn, pos, del, PosType::Unicode) + .unwrap(); + text2 + .insert_with_txn(&mut txn, pos, ins, PosType::Unicode) + .unwrap(); + } + loro_b + .import( + &loro + .export(ExportMode::updates(&loro_b.oplog_vv())) + .unwrap(), + ) + .unwrap(); + loro.import( + &loro_b + .export(ExportMode::updates(&loro.oplog_vv())) + .unwrap(), + ) + .unwrap(); + } + let data = loro.export(ExportMode::Snapshot).unwrap(); + b.iter(|| { + let loro = LoroDoc::default(); + loro.import(&data).unwrap(); + }) + }); + } +} +pub fn dumb(_c: &mut Criterion) {} + +#[cfg(feature = "test_utils")] +criterion_group!(benches, run::b4); +#[cfg(not(feature = "test_utils"))] +criterion_group!(benches, dumb); +criterion_main!(benches); diff --git a/vendor/loro-internal/benches/tree.rs b/vendor/loro-internal/benches/tree.rs new file mode 100644 index 0000000..a55f976 --- /dev/null +++ b/vendor/loro-internal/benches/tree.rs @@ -0,0 +1,166 @@ +use criterion::{criterion_group, criterion_main, Criterion}; + +mod tree { + use super::*; + use criterion::{AxisScale, BenchmarkId, PlotConfiguration}; + use loro_internal::{encoding::ExportMode, LoroDoc, TreeParentId}; + use rand::{rngs::StdRng, Rng}; + + pub fn tree_move(c: &mut Criterion) { + let mut group = c.benchmark_group("movable tree"); + let plot_config = PlotConfiguration::default().summary_scale(AxisScale::Logarithmic); + group.plot_config(plot_config); + group.sample_size(10); + + for i in 3..=6 { + let input = 10u64.pow(i); + group.bench_with_input( + BenchmarkId::new("create node append", input), + &input, + |b, i| { + b.iter(|| { + let loro = LoroDoc::new_auto_commit(); + let tree = loro.get_tree("tree"); + for idx in 0..*i { + tree.create_at(TreeParentId::Root, idx as usize).unwrap(); + } + }) + }, + ); + + group.bench_with_input( + BenchmarkId::new("move node append", input), + &input, + |b, i| { + let loro = LoroDoc::new_auto_commit(); + let tree = loro.get_tree("tree"); + const SIZE: usize = 1000; + let mut rng: StdRng = rand::SeedableRng::seed_from_u64(0); + let mut ids = vec![]; + for _ in 0..SIZE { + let pos = rng.gen::<usize>() % (ids.len() + 1); + ids.push(tree.create_at(TreeParentId::Root, pos).unwrap()); + } + + b.iter(|| { + for _ in 0..*i { + tree.create_at(TreeParentId::Root, 0).unwrap(); + let i = rng.gen::<usize>() % SIZE; + let j = rng.gen::<usize>() % SIZE; + tree.mov(ids[i], TreeParentId::Node(ids[j])) + .unwrap_or_default(); + } + }) + }, + ); + } + + group.bench_function("1000 node checkout 10^3", |b| { + let loro = LoroDoc::default(); + loro.start_auto_commit(); + let tree = loro.get_tree("tree"); + let mut ids = vec![]; + let mut versions = vec![]; + let size = 1000; + for _ in 0..size { + ids.push(tree.create(TreeParentId::Root).unwrap()) + } + let mut rng: StdRng = rand::SeedableRng::seed_from_u64(0); + let mut n = 1000; + while n > 0 { + let i = rng.gen::<usize>() % size; + let j = rng.gen::<usize>() % size; + if tree.mov(ids[i], TreeParentId::Node(ids[j])).is_ok() { + versions.push(loro.oplog_frontiers()); + n -= 1; + }; + } + b.iter(|| { + for _ in 0..1000 { + let i = rng.gen::<usize>() % 1000; + let f = &versions[i]; + loro.checkout(f).unwrap(); + } + }) + }); + + group.bench_function("300 deep node random checkout 10^3", |b| { + let depth = 300; + let loro = LoroDoc::default(); + loro.start_auto_commit(); + let tree = loro.get_tree("tree"); + let mut ids = vec![]; + let mut versions = vec![]; + let id1 = tree.create(TreeParentId::Root).unwrap(); + ids.push(id1); + versions.push(loro.oplog_frontiers()); + for _ in 1..depth { + let id = tree + .create(TreeParentId::Node(*ids.last().unwrap())) + .unwrap(); + ids.push(id); + versions.push(loro.oplog_frontiers()); + } + let mut rng: StdRng = rand::SeedableRng::seed_from_u64(0); + b.iter(|| { + for _ in 0..1000 { + let i = rng.gen::<usize>() % depth; + let f = &versions[i]; + loro.checkout(f).unwrap(); + } + }) + }); + + group.bench_function("realtime tree move", |b| { + let doc_a = LoroDoc::default(); + let doc_b = LoroDoc::default(); + doc_a.start_auto_commit(); + doc_b.start_auto_commit(); + let tree_a = doc_a.get_tree("tree"); + let tree_b = doc_b.get_tree("tree"); + let mut ids = vec![]; + let size = 1000; + for _ in 0..size { + ids.push(tree_a.create(TreeParentId::Root).unwrap()) + } + doc_b + .import(&doc_a.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + let mut rng: StdRng = rand::SeedableRng::seed_from_u64(0); + let n = 1000; + b.iter(|| { + for t in 0..n { + let i = rng.gen::<usize>() % size; + let j = rng.gen::<usize>() % size; + if t % 2 == 0 { + tree_a + .mov(ids[i], TreeParentId::Node(ids[j])) + .unwrap_or_default(); + doc_b + .import( + &doc_a + .export(ExportMode::updates(&doc_b.oplog_vv())) + .unwrap(), + ) + .unwrap(); + } else { + tree_b + .mov(ids[i], TreeParentId::Node(ids[j])) + .unwrap_or_default(); + doc_a + .import( + &doc_b + .export(ExportMode::updates(&doc_a.oplog_vv())) + .unwrap(), + ) + .unwrap(); + } + } + }) + }); + group.finish(); + } +} + +criterion_group!(benches, tree::tree_move); +criterion_main!(benches); diff --git a/vendor/loro-internal/deno.json b/vendor/loro-internal/deno.json new file mode 100644 index 0000000..6edf0b3 --- /dev/null +++ b/vendor/loro-internal/deno.json @@ -0,0 +1,10 @@ +{ + "tasks": { + "test": "cargo nextest run --features test_utils", + "deny": "cargo deny check", + "fuzz": "cargo +nightly fuzz run", + "mem": "deno run -A ./scripts/run_mem.ts", + "flame": "CARGO_PROFILE_RELEASE_DEBUG=true cargo flamegraph --example encoding_refactored --root", + "bench": "cargo bench --features test_utils" + } +} diff --git a/vendor/loro-internal/deno.lock b/vendor/loro-internal/deno.lock new file mode 100644 index 0000000..5a95611 --- /dev/null +++ b/vendor/loro-internal/deno.lock @@ -0,0 +1,134 @@ +{ + "version": "3", + "redirects": { + "https://deno.land/std/fmt/printf.ts": "https://deno.land/std@0.105.0/fmt/printf.ts", + "https://deno.land/std/path/mod.ts": "https://deno.land/std@0.105.0/path/mod.ts", + "https://deno.land/std/testing/asserts.ts": "https://deno.land/std@0.105.0/testing/asserts.ts", + "https://x.nest.land/std@0.73.0/path/mod.ts": "https://lra6z45nakk5lnu3yjchp7tftsdnwwikwr65ocha5eojfnlgu4sa.arweave.net/XEHs860CldW2m8JEd_5lnIbbWQq0fdcI4OkckrVmpyQ/path/mod.ts" + }, + "remote": { + "https://deno.land/std@0.105.0/_util/assert.ts": "2f868145a042a11d5ad0a3c748dcf580add8a0dbc0e876eaa0026303a5488f58", + "https://deno.land/std@0.105.0/_util/os.ts": "dfb186cc4e968c770ab6cc3288bd65f4871be03b93beecae57d657232ecffcac", + "https://deno.land/std@0.105.0/fmt/colors.ts": "d2f8355f00a74404668fc5a1e4a92983ce1a9b0a6ac1d40efbd681cb8f519586", + "https://deno.land/std@0.105.0/fmt/printf.ts": "7ec612e9b89958b8f7710129f74f502327aad285a9e48ee5297f5882fbc3a078", + "https://deno.land/std@0.105.0/path/_constants.ts": "1247fee4a79b70c89f23499691ef169b41b6ccf01887a0abd131009c5581b853", + "https://deno.land/std@0.105.0/path/_interface.ts": "1fa73b02aaa24867e481a48492b44f2598cd9dfa513c7b34001437007d3642e4", + "https://deno.land/std@0.105.0/path/_util.ts": "2e06a3b9e79beaf62687196bd4b60a4c391d862cfa007a20fc3a39f778ba073b", + "https://deno.land/std@0.105.0/path/common.ts": "eaf03d08b569e8a87e674e4e265e099f237472b6fd135b3cbeae5827035ea14a", + "https://deno.land/std@0.105.0/path/glob.ts": "3b84af55c53febacf6afe214c095624b22a56b6f57d7312157479cc783a0de65", + "https://deno.land/std@0.105.0/path/mod.ts": "4465dc494f271b02569edbb4a18d727063b5dbd6ed84283ff906260970a15d12", + "https://deno.land/std@0.105.0/path/posix.ts": "b81974c768d298f8dcd2c720229639b3803ca4a241fa9a355c762fa2bc5ef0c1", + "https://deno.land/std@0.105.0/path/separator.ts": "8fdcf289b1b76fd726a508f57d3370ca029ae6976fcde5044007f062e643ff1c", + "https://deno.land/std@0.105.0/path/win32.ts": "f4a3d4a3f2c9fe894da046d5eac48b5e789a0ebec5152b2c0985efe96a9f7ae1", + "https://deno.land/std@0.105.0/testing/_diff.ts": "5d3693155f561d1a5443ac751ac70aab9f5d67b4819a621d4b96b8a1a1c89620", + "https://deno.land/std@0.105.0/testing/asserts.ts": "e4311d45d956459d4423bc267208fe154b5294989da2ed93257b6a85cae0427e", + "https://deno.land/std@0.106.0/_util/assert.ts": "2f868145a042a11d5ad0a3c748dcf580add8a0dbc0e876eaa0026303a5488f58", + "https://deno.land/std@0.106.0/_util/os.ts": "dfb186cc4e968c770ab6cc3288bd65f4871be03b93beecae57d657232ecffcac", + "https://deno.land/std@0.106.0/fs/_util.ts": "f2ce811350236ea8c28450ed822a5f42a0892316515b1cd61321dec13569c56b", + "https://deno.land/std@0.106.0/fs/copy.ts": "631bbafbfe6cba282158abc8aeb7e8251cc69a7ec28ce12878ea1b75fec2add4", + "https://deno.land/std@0.106.0/fs/empty_dir.ts": "5f08b263dd064dc7917c4bbeb13de0f5505a664b9cdfe312fa86e7518cfaeb84", + "https://deno.land/std@0.106.0/fs/ensure_dir.ts": "b7c103dc41a3d1dbbb522bf183c519c37065fdc234831a4a0f7d671b1ed5fea7", + "https://deno.land/std@0.106.0/fs/ensure_file.ts": "c06031af24368e80c330897e4b8e9109efc8602ffabc8f3e2306be07529e1d13", + "https://deno.land/std@0.106.0/fs/ensure_link.ts": "26e54363508b822afd87a3f6e873bbbcd6b5993dd638f8170758c16262a75065", + "https://deno.land/std@0.106.0/fs/ensure_symlink.ts": "c07b6d19ef58b6f5c671ffa942e7f9be50315f4f78e2f9f511626fd2e13beccc", + "https://deno.land/std@0.106.0/fs/eol.ts": "afaebaaac36f48c423b920c836551997715672b80a0fee9aa7667c181a94f2df", + "https://deno.land/std@0.106.0/fs/exists.ts": "b0d2e31654819cc2a8d37df45d6b14686c0cc1d802e9ff09e902a63e98b85a00", + "https://deno.land/std@0.106.0/fs/expand_glob.ts": "73e7b13f01097b04ed782b3d63863379b718417417758ba622e282b1e5300b91", + "https://deno.land/std@0.106.0/fs/mod.ts": "26eee4b52a8c516e37d464094b080ff6822883e7f01ff0ba0a72b8dcd54b9927", + "https://deno.land/std@0.106.0/fs/move.ts": "4623058e39bbbeb3ad30aeff9c974c55d2d574ad7c480295c12b04c244686a99", + "https://deno.land/std@0.106.0/fs/walk.ts": "b91c655c60d048035f9cae0e6177991ab3245e786e3ab7d20a5b60012edf2126", + "https://deno.land/std@0.106.0/path/_constants.ts": "1247fee4a79b70c89f23499691ef169b41b6ccf01887a0abd131009c5581b853", + "https://deno.land/std@0.106.0/path/_interface.ts": "1fa73b02aaa24867e481a48492b44f2598cd9dfa513c7b34001437007d3642e4", + "https://deno.land/std@0.106.0/path/_util.ts": "2e06a3b9e79beaf62687196bd4b60a4c391d862cfa007a20fc3a39f778ba073b", + "https://deno.land/std@0.106.0/path/common.ts": "eaf03d08b569e8a87e674e4e265e099f237472b6fd135b3cbeae5827035ea14a", + "https://deno.land/std@0.106.0/path/glob.ts": "3b84af55c53febacf6afe214c095624b22a56b6f57d7312157479cc783a0de65", + "https://deno.land/std@0.106.0/path/mod.ts": "4465dc494f271b02569edbb4a18d727063b5dbd6ed84283ff906260970a15d12", + "https://deno.land/std@0.106.0/path/posix.ts": "b81974c768d298f8dcd2c720229639b3803ca4a241fa9a355c762fa2bc5ef0c1", + "https://deno.land/std@0.106.0/path/separator.ts": "8fdcf289b1b76fd726a508f57d3370ca029ae6976fcde5044007f062e643ff1c", + "https://deno.land/std@0.106.0/path/win32.ts": "f4a3d4a3f2c9fe894da046d5eac48b5e789a0ebec5152b2c0985efe96a9f7ae1", + "https://deno.land/std@0.198.0/_util/os.ts": "d932f56d41e4f6a6093d56044e29ce637f8dcc43c5a90af43504a889cf1775e3", + "https://deno.land/std@0.198.0/assert/assert.ts": "9a97dad6d98c238938e7540736b826440ad8c1c1e54430ca4c4e623e585607ee", + "https://deno.land/std@0.198.0/assert/assertion_error.ts": "4d0bde9b374dfbcbe8ac23f54f567b77024fb67dbb1906a852d67fe050d42f56", + "https://deno.land/std@0.198.0/path/_basename.ts": "057d420c9049821f983f784fd87fa73ac471901fb628920b67972b0f44319343", + "https://deno.land/std@0.198.0/path/_constants.ts": "e49961f6f4f48039c0dfed3c3f93e963ca3d92791c9d478ac5b43183413136e0", + "https://deno.land/std@0.198.0/path/_dirname.ts": "355e297236b2218600aee7a5301b937204c62e12da9db4b0b044993d9e658395", + "https://deno.land/std@0.198.0/path/_extname.ts": "eaaa5aae1acf1f03254d681bd6a8ce42a9cb5b7ff2213a9d4740e8ab31283664", + "https://deno.land/std@0.198.0/path/_format.ts": "4a99270d6810f082e614309164fad75d6f1a483b68eed97c830a506cc589f8b4", + "https://deno.land/std@0.198.0/path/_from_file_url.ts": "7e4e5626089785adddb061f1b9f4932d6b21c7df778e7449531a11e32048245c", + "https://deno.land/std@0.198.0/path/_interface.ts": "6471159dfbbc357e03882c2266d21ef9afdb1e4aa771b0545e90db58a0ba314b", + "https://deno.land/std@0.198.0/path/_is_absolute.ts": "05dac10b5e93c63198b92e3687baa2be178df5321c527dc555266c0f4f51558c", + "https://deno.land/std@0.198.0/path/_join.ts": "fd78555bc34d5f188918fc7018dfe8fe2df5bbad94a3b30a433666c03934d77f", + "https://deno.land/std@0.198.0/path/_normalize.ts": "a19ec8706b2707f9dd974662a5cd89fad438e62ab1857e08b314a8eb49a34d81", + "https://deno.land/std@0.198.0/path/_parse.ts": "0f9b0ff43682dd9964eb1c4398610c4e165d8db9d3ac9d594220217adf480cfa", + "https://deno.land/std@0.198.0/path/_relative.ts": "27bdeffb5311a47d85be26d37ad1969979359f7636c5cd9fcf05dcd0d5099dc5", + "https://deno.land/std@0.198.0/path/_resolve.ts": "3bf0287d62488cad08c3c219a9708c4a4c658c65d7b4400fd99afdc3ba10a64d", + "https://deno.land/std@0.198.0/path/_to_file_url.ts": "739bfda583598790b2e77ce227f2bb618f6ebdb939788cea47555b43970ec58c", + "https://deno.land/std@0.198.0/path/_to_namespaced_path.ts": "0d5f4caa2ed98ef7a8786286df6af804b50e38859ae897b5b5b4c8c5930a75c8", + "https://deno.land/std@0.198.0/path/_util.ts": "4e191b1bac6b3bf0c31aab42e5ca2e01a86ab5a0d2e08b75acf8585047a86221", + "https://deno.land/std@0.198.0/path/basename.ts": "6f08fbb90dbfcf320765b3abb01f995b1723f75e2534acfd5380e202c802a3aa", + "https://deno.land/std@0.198.0/path/common.ts": "ee7505ab01fd22de3963b64e46cff31f40de34f9f8de1fff6a1bd2fe79380000", + "https://deno.land/std@0.198.0/path/dirname.ts": "098996822a31b4c46e1eb52a19540d3c6f9f54b772fc8a197939eeabc29fca2f", + "https://deno.land/std@0.198.0/path/extname.ts": "9b83c62fd16505739541f7a3ab447d8972da39dbf668d47af2f93206c2480893", + "https://deno.land/std@0.198.0/path/format.ts": "cb22f95cc7853d590b87708cc9441785e760d711188facff3d225305a8213aca", + "https://deno.land/std@0.198.0/path/from_file_url.ts": "a6221cfc928928ec4d9786d767dfac98fa2ab746af0786446c9834a07b98817e", + "https://deno.land/std@0.198.0/path/glob.ts": "d479e0a695621c94d3fd7fe7abd4f9499caf32a8de13f25073451c6ef420a4e1", + "https://deno.land/std@0.198.0/path/is_absolute.ts": "6b3d36352eb7fa29edb53f9e7b09b1aeb022a3c5465764f6cc5b8c41f9736197", + "https://deno.land/std@0.198.0/path/join.ts": "4a2867ff2f3c81ffc9eb3d56dade16db6f8bd3854f269306d23dad4115089c84", + "https://deno.land/std@0.198.0/path/mod.ts": "7765507696cb321994cdacfc19ee3ba61e8e3ebf4bd98fa75a276cf5dc18ce2a", + "https://deno.land/std@0.198.0/path/normalize.ts": "7d992cd262b2deefa842d93a8ba2ed51f3949ba595b1d07f627ac2cddbc74808", + "https://deno.land/std@0.198.0/path/parse.ts": "031fe488b3497fb8312fc1dc3c3d6c2d80707edd9c661e18ee9fd20f95edf322", + "https://deno.land/std@0.198.0/path/posix.ts": "0a1c1952d132323a88736d03e92bd236f3ed5f9f079e5823fae07c8d978ee61b", + "https://deno.land/std@0.198.0/path/relative.ts": "7db80c5035016174267da16321a742d76e875215c317859a383b12f413c6f5d6", + "https://deno.land/std@0.198.0/path/resolve.ts": "103b62207726a27f28177f397008545804ecb20aaf00623af1f622b18cd80b9f", + "https://deno.land/std@0.198.0/path/separator.ts": "0fb679739d0d1d7bf45b68dacfb4ec7563597a902edbaf3c59b50d5bcadd93b1", + "https://deno.land/std@0.198.0/path/to_file_url.ts": "dd32f7a01bbf3b15b5df46796659984b372973d9b2d7d59bcf0eb990763a0cb5", + "https://deno.land/std@0.198.0/path/to_namespaced_path.ts": "4e643ab729bf49ccdc166ad48d2de262ff462938fcf2a44a4425588f4a0bd690", + "https://deno.land/std@0.198.0/path/win32.ts": "8b3f80ef7a462511d5e8020ff490edcaa0a0d118f1b1e9da50e2916bdd73f9dd", + "https://deno.land/x/cliui@v7.0.4-deno/build/lib/index.d.ts": "4f04923352ce24027ad6fe25c85249e0b0cc5c29fe18d62024d004c59d9e41ee", + "https://deno.land/x/cliui@v7.0.4-deno/build/lib/index.js": "fb6030c7b12602a4fca4d81de3ddafa301ba84fd9df73c53de6f3bdda7b482d5", + "https://deno.land/x/cliui@v7.0.4-deno/build/lib/string-utils.js": "b3eb9d2e054a43a3064af17332fb1839a7dadb205c5371af4789616afb1a117f", + "https://deno.land/x/cliui@v7.0.4-deno/deno.ts": "d07bc3338661f8011e3a5fd215061d17a52107a5383c29f40ce0c1ecb8bb8cc3", + "https://deno.land/x/dirname@1.1.2/types.ts": "c1ed1667545bc4b1d69bdb2fc26a5fa8edae3a56e3081209c16a408a322a2319", + "https://deno.land/x/escalade@v3.0.3/sync.ts": "493bc66563292c5c10c4a75a467a5933f24dad67d74b0f5a87e7b988fe97c104", + "https://deno.land/x/y18n@v5.0.0-deno/build/lib/index.d.ts": "11f40d97041eb271cc1a1c7b296c6e7a068d4843759575e7416f0d14ebf8239c", + "https://deno.land/x/y18n@v5.0.0-deno/build/lib/index.js": "92c4624714aa508d33c6d21c0b0ffa072369a8b306e5f8c7727662f570bbd026", + "https://deno.land/x/y18n@v5.0.0-deno/deno.ts": "80997f0709a0b43d29931e2b33946f2bbc32b13fd82f80a5409628455427e28d", + "https://deno.land/x/y18n@v5.0.0-deno/lib/platform-shims/deno.ts": "8fa2c96ac03734966260cfd2c5bc240e41725c913e5b64a0297aede09f52b39d", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/argsert.js": "eb085555452eac3ff300935994a42f35d16e04cf698cb775cb5ad4f5653c0627", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/command.js": "499c95cecd5e93f627e0b5ce66a193c9a595adc10fbafe0581a9725e38324dee", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/completion-templates.js": "f84823b1daa0ed0189e4f823f6a4fd29ad58de6a05771004918368fd62bb2b3f", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/completion.js": "c91772b89907ebf1a462804305d12d3b9deade75cd1b319c06831ac0bf5abd27", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/middleware.js": "cef3f017d5ff61c340c65b8422f5ab9600ba381aa656df634d1a3edf0f967527", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/parse-command.js": "327242c0afae207b7aefa13133439e3b321d7db4229febc5b7bd5285770ac7f7", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/typings/common-types.js": "9618b81a86acb88a61fd9988e9bc3ec21c5250d94fc2231ba7d898e71500789d", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/usage.js": "61071feb99ac220f1b27036406ae8e4f9ee606b373a5f3bcb60042c7bcfbd0d8", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/utils/apply-extends.js": "64640dce92669705abead3bdbe2c46c8318c8623843a55e4726fb3c55ff9dd1d", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/utils/is-promise.js": "be45baa3090c5106dd4e442cceef6b357a268783a2ee28ec10fe131a8cd8db72", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/utils/levenshtein.js": "d8638efc3376b5f794b1c8df6ef4f3d484b29d919127c7fdc242400e3cfded91", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/utils/maybe-async-result.js": "31cf4026279e14c87d16faa14ac758f35c8cc5795d29393c5ce07120f5a3caf6", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/utils/obj-filter.js": "5523fb2288d1e86ed48c460e176770b49587554df4ae2405b468c093786b040b", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/utils/set-blocking.js": "6fa8ffc3299f456e42902736bae35fbc1f2dc96b3905a02ba9629f5bd9f80af1", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/utils/which-module.js": "9267633b2c9f8990b2c699101b641e59ae59932e0dee5270613c0508bfa13c5d", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/validation.js": "3dc366de2eb23bc9457ed3e120b69db9d801251bef3dc19f93e4c0380ac0198c", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/yargs-factory.js": "a3e629d7d063b5ac007b18a0d8e9ad2ca72ca4d702c5c46822fbbdfdd6c512df", + "https://deno.land/x/yargs@v17.1.1-deno/build/lib/yerror.js": "1d9dead374fe06c8f13f2e4adafc002b8a15682b7185abf29638f1be96fd9dfc", + "https://deno.land/x/yargs@v17.1.1-deno/deno-types.ts": "62f5c61899c6da491890c8c84fd9580cfbfa2a83f5a70f6dc74727bbfb148623", + "https://deno.land/x/yargs@v17.1.1-deno/deno.ts": "f3df0bfd08ba367ec36dc59ef6cab1a391ace49ad44387ec5fe5d76289af08af", + "https://deno.land/x/yargs@v17.1.1-deno/lib/platform-shims/deno.ts": "b5a48b40d5c64fe66f5a77f87ebaf4413eea828ccd8159feeac370b3eef9a356", + "https://deno.land/x/yargs_parser@v20.2.4-deno/build/lib/string-utils.js": "12fc056b23703bc370aae5b179dc5abee53fca277abc30eaf76f78d2546d6413", + "https://deno.land/x/yargs_parser@v20.2.4-deno/build/lib/tokenize-arg-string.js": "7e0875b11795b8e217386e45f14b24a6e501ebbc62e15aa469aa8829d4d0ee61", + "https://deno.land/x/yargs_parser@v20.2.4-deno/build/lib/yargs-parser-types.d.ts": "434deb76c6632b3b6cbc4c6f153f8aca04e06055ae9c6b24b40218cbc42688d9", + "https://deno.land/x/yargs_parser@v20.2.4-deno/build/lib/yargs-parser.js": "453200a7dfbb002e605d8009b7dad30f2b1d93665e046ab89c073a4fe63dfd48", + "https://deno.land/x/yargs_parser@v20.2.4-deno/deno.ts": "ad53c0c82c3982c4fc5be9472384b259e0a32ce1f7ae0f68de7b2445df5642fc", + "https://lra6z45nakk5lnu3yjchp7tftsdnwwikwr65ocha5eojfnlgu4sa.arweave.net/XEHs860CldW2m8JEd_5lnIbbWQq0fdcI4OkckrVmpyQ/_util/assert.ts": "e1f76e77c5ccb5a8e0dbbbe6cce3a56d2556c8cb5a9a8802fc9565af72462149", + "https://lra6z45nakk5lnu3yjchp7tftsdnwwikwr65ocha5eojfnlgu4sa.arweave.net/XEHs860CldW2m8JEd_5lnIbbWQq0fdcI4OkckrVmpyQ/path/_constants.ts": "aba480c4a2c098b6374fdd5951fea13ecc8aaaf8b8aa4dae1871baa50243d676", + "https://lra6z45nakk5lnu3yjchp7tftsdnwwikwr65ocha5eojfnlgu4sa.arweave.net/XEHs860CldW2m8JEd_5lnIbbWQq0fdcI4OkckrVmpyQ/path/_interface.ts": "67b276380d297a7cedc3c17f7a0bf122edcfc96a3e1f69de06f379d85ba0e2c0", + "https://lra6z45nakk5lnu3yjchp7tftsdnwwikwr65ocha5eojfnlgu4sa.arweave.net/XEHs860CldW2m8JEd_5lnIbbWQq0fdcI4OkckrVmpyQ/path/_util.ts": "7820a788b35c26dfc27ff329df12507fc0553ae92727009597046f6cf856b4fa", + "https://lra6z45nakk5lnu3yjchp7tftsdnwwikwr65ocha5eojfnlgu4sa.arweave.net/XEHs860CldW2m8JEd_5lnIbbWQq0fdcI4OkckrVmpyQ/path/common.ts": "e4ec66a7416d56f60331b66e27a8a4f08c7b1cf48e350271cb69754a01cf5c04", + "https://lra6z45nakk5lnu3yjchp7tftsdnwwikwr65ocha5eojfnlgu4sa.arweave.net/XEHs860CldW2m8JEd_5lnIbbWQq0fdcI4OkckrVmpyQ/path/glob.ts": "54fea22f0f47dee07399d22e18a34a84eaf4b8a3771bbed96db43bbec71ef237", + "https://lra6z45nakk5lnu3yjchp7tftsdnwwikwr65ocha5eojfnlgu4sa.arweave.net/XEHs860CldW2m8JEd_5lnIbbWQq0fdcI4OkckrVmpyQ/path/mod.ts": "6de8885c2534757097818e302becd1cefcbc4c28ac022cc279e612ee04e8cfd1", + "https://lra6z45nakk5lnu3yjchp7tftsdnwwikwr65ocha5eojfnlgu4sa.arweave.net/XEHs860CldW2m8JEd_5lnIbbWQq0fdcI4OkckrVmpyQ/path/posix.ts": "7c2539b5d9e22b47f02ccc5b6ef11e3975a5c60f49d2241271eaa5936e6082a0", + "https://lra6z45nakk5lnu3yjchp7tftsdnwwikwr65ocha5eojfnlgu4sa.arweave.net/XEHs860CldW2m8JEd_5lnIbbWQq0fdcI4OkckrVmpyQ/path/separator.ts": "9dd15d46ff84a16e13554f56af7fee1f85f8d0f379efbbe60ac066a60561f036", + "https://lra6z45nakk5lnu3yjchp7tftsdnwwikwr65ocha5eojfnlgu4sa.arweave.net/XEHs860CldW2m8JEd_5lnIbbWQq0fdcI4OkckrVmpyQ/path/win32.ts": "47114c941681ecbabab4ec355cb41d525fb5a14175cc47a5c76fdc5eaee2685a" + } +} diff --git a/vendor/loro-internal/docs/critical-version-spec.md b/vendor/loro-internal/docs/critical-version-spec.md new file mode 100644 index 0000000..d4014bf --- /dev/null +++ b/vendor/loro-internal/docs/critical-version-spec.md @@ -0,0 +1,705 @@ +# 重放基准与 critical version:Loro 历史图遍历算法的规格与证明骨架 + +状态:草稿 v3,2026-09-01(新增多头回退:L13、公理 A6)。对应 `crates/loro-internal/src/dag.rs` 中的 +`_find_meet_and_mode`(含 PR #1058 与 tips 去重修复之后的版本);多头回退 L13 的实现在 +`crates/loro-internal/src/oplog.rs`。 + +这份文档是自包含的:读者不需要了解 Loro、CRDT 或本仓库的代码。 +需要的全部预备知识是:集合、有向图、数学归纳法,以及"堆/优先队列"这个数据结构。 +文档先讲问题从哪里来(第 1 章),再给出数学模型(第 2 章)、算法(第 3 章)、 +我们承诺的性质即"规格"(第 4 章)、证明骨架(第 5 章),最后是待定问题(第 6 章) +和词汇表(第 7 章)。写作顺序都是**先直观解释、再数学定义**。 + +--- + +## 1. 问题从哪里来 + +### 1.1 多人协作编辑与操作历史 + +Loro 是一个协作编辑库。它要解决的场景是:几个人(或几台设备)同时编辑同一份 +文档——比如一份购物清单——而且允许离线编辑,之后再同步。同步之后, +所有人看到的结果必须完全一致。实现这一点的数学工具叫 CRDT, +但本文档不需要你懂 CRDT,只需要懂下面这个更基本的东西:**操作历史**。 + +每个参与者(叫一个 **peer**,可以理解为"一台设备上的一个副本") +做的每一次修改都是一个**操作(op)**。操作不会被覆盖或删除,只会不断追加, +所以整个文档的历史就是所有人产生的所有操作的集合。 + +每个操作有一个全局唯一的编号:**(p, c)**,读作"第 p 个 peer 的第 c 个操作", +文本形式记作 **c@p**(counter 在前,与 Loro 代码输出一致;见第 2 章记法约定)。 +同一个 peer 的 c 从 0 开始,每做一个操作加一。 + +操作之间有一种天然的先后关系:**做某个操作时,作者已经看到了哪些别的操作**。 +比如 Bob 在看到 Alice 写下"牛奶"之后才补了一句"鸡蛋",那么"鸡蛋"这个操作 +就**依赖**"牛奶"那个操作。反过来,如果两个人离线时各改各的, +互相都没看见对方的修改,这两个操作就是**并发的(concurrent)**——谁也不依赖谁。 + +把每个操作画成一个点、依赖画成有向边,整个历史就是一张**有向无环图(DAG)**。 + +一个具体的小例子(A = Alice,B = Bob;箭头为 **happened-before** 方向, +由早指向晚——与 Eg-walker 论文一致;注意存储时每个事件记录的是反向的 +"父事件"引用): + +``` +A0 "加入苹果" ──→ A1 "加入牛奶" ──→ A2 "加入面包" + │ + └────────────→ B0 "加入鸡蛋" +``` + +- A1 依赖 A0(同一个人的下一个操作,天然依赖上一个); +- B0 是 Bob 看到 A1 之后做的,所以 B0 依赖 A1; +- A2 是 Alice 在**没看到** B0 的情况下做的,所以 A2 只依赖 A1。 +- A2 和 B0 互相都不依赖:它们是并发的。 + +### 1.2 版本与前沿(frontier) + +"文档在某一时刻的版本"是什么?直观上:**一个操作集合**——这一时刻已经发生 +(且被这个副本看到)的所有操作。这种集合有个重要特点:**因果闭合**—— +你看到了某个操作,就必然看到了它依赖的一切操作(否则你根本无法理解它)。 + +因果闭合的集合不需要逐个元素列出来,只要报出它的"最新端点"就够了: +比如上图中"Bob 视角的版本"是 {A0, A1, B0},只要说"我最新到 B0"即可, +因为 B0 的全部祖先自动包含在内。这组最新端点就叫**前沿(frontier)**。 +一个前沿里不会有谁是谁的祖先(否则那个祖先是多余的), +这种"两两互不为祖先"的集合在数学上叫**反链(antichain)**。 + +前沿可以有多个端点:上图中 Alice 同步了 B0 之后,她的版本是全部 5 个操作, +前沿是 {A2, B0}——两个并发的端点,谁也代表不了谁。 + +### 1.3 要解决的问题:给两个版本找"重放起点" + +Loro 里有两个高频动作: + +- **import(导入)**:收到别人发来的更新,把新操作合并进本地历史; +- **checkout(检出/时间旅行)**:把文档切换到历史上任意一个版本。 + +两者的核心都是同一个计算:**给定旧版本 L 和新版本 R(各用一个前沿表示), +算出文档状态从 L 到 R 的"差量"(diff)**。计算差量的通用办法是**重放**: +从两个版本**共同拥有**的历史中选一个起点,把起点之后的操作按因果顺序重演一遍, +一边重演一边算出状态差。 + +于是问题变成:**重放起点选哪里?** + +- 起点选得**太老**:要白白重演大量双方本来就共有的历史。这不是理论担忧—— + 本仓库最近修的一个真实 bug(PR #1058)就是起点被错误地退到了历史开头, + 导致导入一个 124 字节的小更新要重演全部历史、耗时是正常情况的几百倍。 +- 起点选**错**(比如漏掉某条并发分支的分岔点):差量会算错, + 文档内容错乱。这比慢严重得多。 + +直觉上理想的起点是两个版本公共操作中"最靠上"的那些——本文档记作 +meet(版本格的最大下界前沿,第 2 章 D8 给精确定义;它是一个反链, +不一定是单点)。但 meet 只是**候选**:起点还必须满足一个"切得开"的 +条件(critical version,D8b),meet 不满足时要向更早处回退—— +这正是场景④"保守回退"的由来,严格定义见 4.1 节。 + +除了起点,调用方还需要知道第二件事:**R 是否完全包含 L**? +如果是(典型情况:导入的更新完全建立在本地版本之上),差量计算可以走快路径 +(不需要重建复杂的中间结构);如果否(存在并发),必须走慢而稳的路径。 +算法把这个判断以"模式"(mode)的形式一并返回: + +- `Linear`:R 包含 L,且新增部分是一条无分叉的直线; +- `ImportGreaterUpdates`(下文简称 IGU):R 包含 L; +- `Checkout`:其余所有情况(存在并发、或时间倒流),走保守路径。 + +### 1.4 为什么这个问题不平凡:三个陷阱 + +**陷阱一:隐式依赖造出"冗余路径"。** +同一个 peer 的第 c 个操作天然依赖第 c−1 个,这条边**不会被显式存储** +(存了就太浪费了),遍历时要自己补上。这会造出"一个祖先、两条到达路径"的局面: + +``` +0@1 ──→ 0@2(中转) ──→ 1@1 + │ ↑ + └──────(隐式:同 peer 前驱)─┘ +``` + +peer 1 做完 0@1 后,peer 2 基于它做了 0@2;然后 peer 1 看到 0@2 又做了 1@1。 +1@1 显式依赖 0@2,同时隐式依赖自己的前驱 0@1。从 1@1 出发往下走会分出两条路: +显式路经 0@2 到 0@1,隐式路直达 0@1。第二条路是**冗余**的——它到达的一切 +都能从第一条路到达。但一个只看"这条路走到死也没碰到对方"的简单算法 +会把冗余路误判成**并发分支**,进而把重放起点错误地退到历史开头。 +这正是 PR #1058 修复的 bug。区分"冗余路"和"真并发分支"是本算法最微妙的部分。 + +**陷阱二:操作是按"段"存储的。** +为了效率,同一个 peer 连续的一串操作打包成一个**节点**(内部叫 Change)存储, +遍历时弹出的是一整段。而别的路径的依赖可能恰好指向这一段的**中间**某个操作。 +算法必须保证"整段前进"不会大步跨过别人指向的中间点(3.3 节的"对齐"机制)。 + +**陷阱三:性能约束。** +历史可以有百万级操作。遍历的开销必须只和"两个版本附近的区域"成正比, +不能做全图搜索。手段是给每个操作配一个 **lamport 时间戳**(2.1 节), +永远从"时间戳最大"的未处理条目开始处理——像水面从高处向低处退去, +两个版本的探索会在 meet 附近自然会合,不必触碰更深的历史。 + +--- + +## 2. 数学模型 + +本章把上面的直观图景变成精确定义。每个定义前先用一句话回顾直观含义。 + +**D1(操作 id)** 操作的编号是二元组 (p, c) ∈ P × ℕ,P 是 peer 的集合。 + +**记法约定** 具体 id 的文本形式一律写作 **c@p**(counter 在前、peer 在后), +与代码中 `ID` 的 Display 输出一致(`loro-common/src/id.rs`)。数学元组仍写 +(p, c),读作"peer p 的第 c 个操作";若行文需要 peer 在前的紧凑形式,写 +P⟨p⟩_C⟨c⟩,**绝不写 p@c**,以免与标准文本形混淆。叙事中的字母形 +(A0 = Alice 的第 0 个操作)仅用于故事。 + +**D2(节点划分;公理 A2)** *——"连续操作打包存储"。* +每个 peer 的操作序列被划分为若干互不重叠的连续区间,每个区间叫一个**节点** +N = [s, e)(含 s 不含 e)。每个操作恰好属于一个节点。节点携带一个 +**显式依赖集** deps(N) ⊆ Ids,语义上挂在节点的第一个操作 (p, s) 上。 + +**D3(父事件 parents 与事件图;Eg-walker §2.2)** +*——"做这个操作前刚看到的最新操作们"。* +每个事件 e 携带**父事件集** parents(e)(论文记 e.parents;Loro 代码称 deps): +- 隐式父:(p, c−1) ∈ parents((p, c)),对一切 c > 0; +- 显式父:deps(N) ⊆ parents((p, s)),s 是节点 N 的起点。 +事件与父引用构成**事件图(event graph)**:一张 DAG,每个节点是一个事件 +(一次操作 + 唯一 id + 父事件 id 集,论文 §2.2)。 + +**D4(happened-before → 与并发 ∥;Eg-walker §2.2)** +*——"由早指向晚的因果链"。* +a **happened before** b(记 **a → b**)当且仅当沿父引用存在从 b 回到 a 的 +有向路径:a → b ⟺ a ∈ parents(b) ∨ ∃e: a → e ∧ e ∈ parents(b)。 +箭头方向沿用论文与 Lamport:**由早指向晚**(父引用存储方向与之相反)。 +**并发**:a ∥ b ⟺ a ≠ b ∧ a ↛ b ∧ b ↛ a(论文 §2.2)。 +引理中常用的自反版本 **≤**:v ≤ u ⟺ v = u ∨ v → u。 +祖先闭包沿用论文记法 **Events(·)**(§2.3): +Events(V) = V ∪ { e₁ ∣ ∃e₂ ∈ V: e₁ → e₂ }。 +为行文简短,本文把 Events({u}) 记作 ancestry(u)、Events(F) 记作 ancestry(F)。 + +**D5(lamport 时间戳;公理 A1)** *——"逻辑时钟:你依赖的东西一定比你早"。* +函数 lamport : Ids → ℕ 满足: +- 沿父引用严格递减:a ∈ parents(b) ⟹ lamport(a) < lamport(b); +- 节点内逐操作加一:lamport(p, c+1) = lamport(p, c) + 1。 + +由传递性立即得到本文档最常用的推论: + +> **L0**:v → u(v happened before u) ⟹ lamport(v) < lamport(u)。 + +注意反过来**不成立**:lamport 小不代表 happened-before(并发操作的 lamport 也可比较大小)。 + +**D6(前沿 / version;Eg-walker §2.3)** 有限反链(成员两两并发)。 +论文把因果闭子图 G′ 的前沿称为它的 **version**: +Version(G′) = { e₁ ∈ G′ ∣ ∄e₂ ∈ G′: e₁ → e₂ }(没有后继的事件全体)。 +前沿与因果闭集互逆:Events(Version(G′)) = G′,Version(Events(F)) = F。 +算法输入是两个前沿 L 和 R。 + +**D7(版本与版本向量)** *——"版本 = 因果闭合的操作集 = 每个 peer 报一个前缀长度"。* +称操作集 S 是**因果闭**的,若 u ∈ S 且 v ≤ u 则 v ∈ S。ancestry(F) 总是因果闭的。 +由隐式边,因果闭集在每个 peer 上必是前缀 {(p,0), …, (p,k−1)}, +所以一个因果闭集可以用"每个 peer 一个数字 k(p)"紧凑表示——这就是**版本向量**。 +两个版本的包含关系等价于逐 peer 比较数字: + +> vv(R) ⊇ vv(L) ⟺ ancestry(L) ⊆ ancestry(R)。 + +**D8(公共历史与 meet 前沿)** C(L, R) = ancestry(L) ∩ ancestry(R)。 +两个因果闭集的交仍是因果闭的。定义 **meet(L, R) := Max(C(L,R))**, +即 C 中的极大元全体——版本格(因果闭集按 ⊆ 构成的格)中两版本最大下界 +的前沿,这是一个反链。测试里的"oracle"(暴力对照实现)算的就是这个对象。 + +命名说明:本文档与代码曾把它借称为 "LCA",2026-08-01 起已全面弃用: +代码中 `iter_from_lca_causally` 改名 `iter_from_replay_base_causally`、 +`lca_vv` 改名 `replay_base_vv`、回退函数命名为 +`latest_single_head_critical_version`,文档改名 +`critical-version-spec.md`。理由:经典 LCA 是图上两个**节点**的最深公共 +祖先(单点),而这里的对象是两个**版本**在格上的最大下界;更重要的是, +meet 只是算法的**候选**,不是算法真正要交付的东西(见 D8b 与 4.1 节)。 +2026-09-21 起,剩下沿用“公共祖先”的名字也全部改掉:`find_common_ancestor` 改名 +`find_replay_base`,`_find_common_ancestor_new` 改名 `_find_meet_and_mode`, +旧版 `_find_common_ancestor` 改名 `_walk_to_meet`。它们在 Checkout 模式下交付的 +只是 meet,不一定是 critical version(见 S3、Q7);浅快照选根就曾因为 +“公共祖先”这个名字误用了它(loro-dev/loro#1095)。所以新名字只说明它是重放基准, +是否 critical 取决于 diff 模式(`DiffMode`),需要 critical version 的调用者应直接用 +`latest_single_head_critical_version`(L11)。 + +1.1 节例子中:L = {A2},R = {B0},C = {A0, A1},meet = {A1}。 + +**D8b(critical version;Eg-walker,arXiv:2409.14252 §3.5)** +*——"能把历史一刀两断的版本"。* +版本 V 在事件图 G 中是 **critical** 的,当且仅当它把 G 划分为 +G₁ = Events(V)(V 的祖先闭包)与 G₂ = G − G₁,使得 G₁ 中每个事件都 +happened-before G₂ 中每个事件:∀e₁∈G₁, ∀e₂∈G₂: e₁ → e₂。 +等价说法:切口两侧没有任何一对并发事件。空版本 ∅ 平凡地 critical +(G₁ 为空,条件真空成立)。 + +重放起点的**合法性判据**正是它:以 B 为起点重放区域 G − Events(B) 时 +tracker 无需 B 以下的任何位置上下文 ⟺ B 在联合图 +ancestry(L) ∪ ancestry(R) 中 critical。Eg-walker 合并新事件时取 +"发生在双方之前的**最晚** critical version"为起点(§3.6 的 V_crit)。 + +**D9(段 / OrdIdSpan)** *——"节点的一个前缀切片"。* +⟨N, e⟩ 表示节点 N 内的操作段 [s .. e](含两端)。记 +id_last = (p, e),lamport_last = lamport(p, e)。 +from_dag_node(u) := 包含 u 的节点在 u 处截断的段。 +**段的 deps 恒等于所属节点的 deps**(挂在节点起点上),与截断位置无关—— +这一点很重要:截掉段的尾部不会丢失任何依赖边。 + +**D10(浅历史 / trimmed;公理 A5)** *——"太老的历史可能已被裁剪掉"。* +可用操作集 D ⊆ Ids;查询函数 get 在 D 之外返回"不存在"。 +输入前沿的成员都在 D 内,但节点的 deps 可以指向 D 外(裁剪边界)。 + +**A6(deps 完整前沿公理)** *——"提交时记录的是作者当时看到的全部最新端点"。* +每个节点 N 的显式 deps 是作者提交时的完整前沿,因此其祖先闭包覆盖 +作者自己的前缀:vv(deps(N))[peer(N)] ≥ start(N)。仅对**本地创建**的 +change 强制:attached 提交路径天然满足,detached editing 由 +`check_change_greater_than_last_peer_id` 检查;导入数据不作校验 +(`import`/`import_json_updates` 接受 deps 不覆盖作者自身前缀的 +change)。本公理的作用是让两种祖先关系重合:DAG 的隐式同 peer 边 +(D8b、L11 单头扫描所用)与重放交给差量计算器的逐 op 上下文 +(显式 deps 的闭包 ∪ 作者自身前缀,见 L13)。L13 的 soundness 与 +最大性都在后一种祖先关系内成立、不依赖 A6;A6 只用于"归零即证单头 +扫描亦无解"这一步(L13(ii))。运行时不做断言。 + +--- + +## 3. 算法 + +### 3.1 直观图景:两支探险队下山 + +把事件图想成一座山:lamport 时间戳是海拔,事件越晚海拔越高 +(A1:happened-before 箭头由山下指向山上);队员沿**父引用**向山下走。 + +- 给左版本 L 派一支**红队**,从 L 的每个前沿端点出发; + 给右版本 R 派一支**蓝队**,从 R 的端点出发。 +- 所有队员放进同一个**优先队列**,永远先处理**海拔最高**的那个队员。 + 队员每一步沿依赖边往山下走(一个队员分出几条依赖就分裂成几个队员)。 +- **红蓝两队在同一个操作上相遇 → 该点染紫**:它同时在两侧的因果历史中,收进候选集 ans, + 并且**不再继续往下走**(紫点以下全是更老的公共历史,无需探索—— + 这是性能的关键,也是后面一切微妙性的来源)。 +- 某个队员**走到了死路**——走到没有依赖的根,或者队列里已经没有别人了—— + 却始终没碰到对方颜色,说明什么? + +最后一问正是陷阱一。有两种可能: + +1. 这个队员代表一条**真正的并发分支**(对方版本里根本没有这段历史)—— + 此时必须放弃候选起点、保守回退(把起点退到最老,模式 Checkout); +2. 这个队员只是一条**冗余路**(1.4 节的隐式前驱路径):它要到达的地方, + 别的队友早就经由紫点到达了。它"死"只是因为紫点不再展开、没人来接应它。 + 此时**不应该**回退。 + +区分办法(**tips 机制**):每个队员身上带一块牌子(tips), +写着"我是从哪个岔路口分出来的"。队员死亡时,查它的牌子: + +> 岔路口 ∈ 已找到紫点的祖先集? +> 是 → 整条死路都在公共历史里,冗余,虚惊一场; +> 否 → 真并发分支,保守回退。 + +这个检查本身也是一次山上的小规模走查(从紫点出发往下、按海拔剪枝), +它只在有死路时发生。 + +### 3.2 精确描述 + +堆条目为三元组 e = (span, type, tips):span 是一个段(D9), +type ∈ {A(红,来自 L), B(蓝,来自 R), Shared(紫)},tips ⊆ Ids。 +堆按 (lamport_last, peer, 更短的段优先) 的字典序弹出最大者。 + +**初始化**:L 的每个成员 u 以 (from_dag_node(u), A, tips₀) 入堆;R 同理入堆为 B。 +其中 tips₀:若该侧前沿有多个端点,则为 {u}(每个端点自成一个"岔路口"); +单端点时为空集(这条路还没分过岔)。 + +**主循环**——弹出 e = (n, t, tips),依次执行: + +1. **聚合**:只要堆顶条目与 n 的段相等、或 id_last 相同:把它也弹出并合并进 e; + 两者 type 不同 ⟹ t := Shared;tips 取并集(**去重**——不去重会指数爆炸, + 这是本次 review 修复的性能 bug)。 +2. **会合**:若 t = Shared:ans 收进 id_last(n);continue(不展开)。 +3. **死亡(队空)**:若堆已空:记录 unmatched(tips 非空记 tips, + 否则记 id_last(n) 自身);break。 +4. **偏序线索**:若 t = A(红队员在堆非空时被单独弹出,说明左侧有右侧 + 尚未包含的操作):is_right_greater := false。 +5. **对齐**(设堆顶为 o): + a. 若 n 包含 id_last(o) 且 t ≠ type(o):把 n 截断为以 id_last(o) 结尾, + 重新入堆;continue。 *(对方指向我的中间:先切到对齐,下一轮聚合。)* + b. 否则若 len(n) > 1:把 n 收缩到 lamport_last 不超过 o 的 lamport_last + (且至少缩短 1,即取 min(按海拔对齐的长度, len − 1)),重新入堆;continue。 + *(长段不许大步跨过任何海拔更高的旁人。"len − 1"上限处理海拔并列: + 并列时按海拔对齐算出的长度等于自身,若原样重入堆即死循环; + 上限强制严格进展,这正是 L10 终止度量在此分支下降的原因。 + 丢弃的段尾是安全的:依赖边挂在节点起点上(D9),截尾不丢边; + 且以段尾为终点的条目会先被聚合分支合并,未来也不再有指向该海拔的 + 新条目(L1),故段尾不可能是任何会合点。)* +6. **展开**:parents* := 显式 deps(N) ∪ {隐式前驱(若未被显式依赖覆盖)} + (即 e.parents,D3;代码中称 deps)。 + - 可解析且非空:每个 d ∈ parents* 以 (from_dag_node(d), t, tips_d) 入堆; + 其中 tips_d:若 tips = ∅ 且 |parents*| > 1(**第一次分岔**), + 则 tips_d = {id_last(d)}(在岔路口发牌子);否则继承 tips。 + is_linear := false。 + - 不可解析(依赖被裁剪,D10):unresolved := true;continue。 + - parents* = ∅(走到根)且堆非空:记录 unmatched(同步骤 3);continue。 + +**收尾**: +- ans := ans 的极大元反链(去掉互为祖先的冗余成员); +- uncovered := unresolved ∨ ¬( unmatched 中每个 tip ∈ ancestry(ans) )。 + 覆盖判定用**单次**多源走查:从 ans 的所有成员出发向下, + 按"尚未证实的 tips 的最小 lamport"剪枝(L0 保证剪枝安全); +- 若 uncovered 且 ans 的依赖未触及裁剪边界: + ans := 并集图上最晚的单头 critical version(L11 扫描;不存在则 ∅); +- 若 uncovered:is_right_greater := false; + 否则若 ans = L:is_right_greater := true; +- mode := Checkout(若 ¬is_right_greater);否则 Linear(若 is_linear 仍为真); + 否则 IGU。 + +此外实现里还有三个**快速路径**(R 为空、L 为空、L 与 R 都是单点且同 peer), +它们绕过主循环直接返回。每个都需要独立的小证明(见 Q6)。 + +### 3.3 三个机制再各给一个直观注解 + +**聚合**:站在同一位置的队员合并成一人;红 + 蓝 = 紫。合并同时合并牌子(去重)。 + +**对齐(回应陷阱二)**:一个段是"一列纵队"。规则 5b 说:纵队每轮最多下行到 +与堆中次高者平齐的海拔,绝不越过;规则 5a 说:若对方明确指着我纵队中间的 +某个人,我先在那个人处断开。两条规则合起来保证: +**任何指向段中间的会合都不会被跳过**。为什么"迟到的指针"不存在? +因为指向 (p, c) 的条目是由它的某个 depender 展开时入堆的, +而 depender 的海拔严格高于 (p, c)(L0);再加上"堆的最高海拔单调下降"(L1), +指针必然在覆盖 (p, c) 的段消亡之前就已入堆。这就是第 5 章的 L3。 + +**tips 与覆盖检查(回应陷阱一)**:牌子只在"第一次分岔"时发放, +之后一路继承;两条路合流时牌子取并。于是不变式是: +**一条路径死亡时,它走过的每个操作都是它某块牌子的祖先**(L6)。 +所以"牌子 ∈ ancestry(紫点)"就足以证明整条死路都泡在公共历史里(L7)—— +检查牌子(少数几个点)而不必检查整条路径(可能很长)。 + +### 3.4 模式判定的含义 + +- is_right_greater 想回答"ancestry(L) ⊆ ancestry(R) 且起点可以就用 L"。 + 它有两个信息来源:走查过程中红队员是否曾被单独弹出(步骤 4), + 以及收尾时死路是否全部被覆盖、ans 是否恰好等于 L。 +- is_linear 想回答"新增历史是一条无分叉直线":任何一次依赖展开都会把它清 false。 +- 三种模式对下游意味着:Linear/IGU → 从 L 直接重放、走快路径; + Checkout → 从 ans(可能为 ∅ = 历史开头)重放、走保守路径。 + +--- + +## 4. 规格:我们向调用方承诺什么 + +| 编号 | 陈述 | 直观含义 | +|---|---|---| +| S1 | ans ⊆ C(L,R) | 给出的起点确实是双方共有的历史 | +| S2 | ans 是反链 | 起点集合里没有冗余成员 | +| S3 | mode ∈ {Linear, IGU} ⟹ ans = L ∧ ancestry(L) ⊆ ancestry(R) | 宣布"快路径可用"时,R 确实完整包含 L,且起点就是 L | +| S3L | mode = Linear ⟹ 上述之外还有 \|ans\| ≤ 1,且新区 ancestry(R)∖ancestry(L) 是 ≤-全序链 | 宣布"直线"时新历史真的无分叉(表述待定,见 Q2) | +| S4 | mode ≠ Checkout ⟹ 新区每个事件 ≥ L 的全部头(已强化,见下) | 由入场检查(L12)保证 | +| S5a | mode = Checkout ⟹ 只承诺 S1 ∧ S2(ans = ∅ 合法) | 保守模式下起点允许偏老,偏老只影响速度不影响正确性 | +| S5b | 猜想 C1:走查无死路 ⟹ ans = meet(L,R)(精确) | 常规情形下起点不多退一步(是否纳入规格待定,见 Q1) | +| T | 算法总终止 | | + +**S4(已强化,2026-08-01)**:mode ≠ Checkout ⟹ 新区每个事件都 +因果晚于 L 的**全部**头(即 L 对并集图 critical)。 + +> **oplog 层的按容器放宽(2026-09-07)**:本条是对 `find_replay_base` +> 的承诺,不变。但 `OpLog::iter_from_replay_base_causally` 在调用它之前会先 +> 用版本向量做同一个入场检查(`OpLog::uncovered_entry_parents`),并检查 +> "与新区并发的旧历史"和新区各自触及的容器:若二者只在寄存器容器 +> (Map、Counter)上重叠,则直接以 L 为起点、以 IGU 模式重放,不再进入 +> DAG 走查。这不违反 tracker 的要求——每个 Text/List/Tree 容器仍然满足 +> "其重放区内的 op 与其 ancestry(L) 内的 op 不并发";重叠的 Map 由差量 +> 计算器改用 history cache 逐 key 精确求值。见 `docs/diff_calc.md` +> "Register-only concurrency"。 + +历史背景:本条曾是"非目标声明"——旧版只承诺版本级包含 +(vv(R) ⊇ vv(L)),把逐操作并发交给下游守卫兜底。两个反例都会通过: + +``` +反例一(同 peer 段截断):L = {A5, L2},R = {r},deps(r) = {A9, L2}, + A6..A9 与 L2 并发; +反例二(movable tree 线上 issue):L = {B6, A0},新区 A1..A3 只依赖 + A0、与 B6 并发。 +``` + +后者证明了 Tree 计算器的 IGU 快速路径**没有**守卫(不同于 text/list +的 `mark_source_not_in_op_context`):A1 未与 B4..B6 打擂台就被采纳, +增量状态与全量重放分叉。现由**入场检查**(L12)在多头 L 时强制验证, +两个反例都会被降级为 Checkout + L11 安全基准;单头 L 由 L9 的覆盖 +论证自动满足本条。 + +### 4.1 算法真正在找什么(严格版,按 Eg-walker 的语言) + +算法的候选是 meet(L,R)(D8),但合法重放起点的严格判据是 +**critical version**(D8b):起点 B 合法 ⟺ B 在联合图 +ancestry(L) ∪ ancestry(R) 中 critical ⟺ 重放区域里没有任何事件与 +ancestry(B) 中的事件并发。Eg-walker 的理论最优是"发生在双方之前的 +最晚 critical version"(§3.6 的 V_crit)。据此把算法的行为分三类: + +1. **meet 恰好 critical**(场景①③的常规形状):候选即答案, + "找 meet"与"找合法起点"重合。 +2. **meet 不 critical,且走查探测到证据**(uncovered 死路,场景④): + 回退到**并集图上最晚的单头 critical version**(已实现,2026-08-01): + 复用主循环的聚合/对齐机件,从 L ∪ R 做一次单色下山扫描; + 待处理堆首次收窄为单个段的时刻,其 id_last 即所求(引理 L11)。 + 若某条链在堆非空时死于根或裁剪边界,其端点与其下一切事件并发, + 之后不再可能有合法单头切口——立即放弃并返回 ∅(即旧行为; + 场景④的双根正是此情形)。扫描只在回退真正发生时执行, + 代价不超过随后重放区域的一次遍历。 + 2026-09 起升级为**两级搜索**:先在 oplog 层做一次**多头**不动点 + 下降(`OpLog::latest_critical_version_below_meet`,引理 L13) + ——从 meet 出发,对区域内每个 change 取其切口上方首个 op 的重放 + 上下文,反复与不覆盖 v 的上下文求交集,收敛点即 ≤ meet 的最大 + critical version(多头亦可)。每个 change 每次被切口移入时检查 + 一次(L13(iii)),代价不超过随后重放同一区域的代价,故不设预算。 + 依赖触及裁剪边界、切口低于浅历史文档的种子版本、或切口经 + frontiers 往返后不等于自身(只在 A6 被违反时可能)才退回上述 + 单头扫描。不动点若归零,可证单头扫描同样无解(L13(ii)),直接取 + ∅、跳过全图扫描。 + 与 Eg-walker 的 V_crit 相比仍有的取舍:只在 ≤ meet 的范围内搜索 + (长期离线分叉的回归仍落在分岔点,代价 O(分歧量)、一次性)。 + 认证通过的基准以 + replay_base_is_critical 标记传给差量计算器;text/list 据此直接 + 信任未知段 tracker(守卫条件被 criticality 蕴含;list 另限定 + 非浅历史文档),守卫只对未认证的基准继续兜底。 +3. **meet 不 critical,但走查未探测到**(2026-08-01 起大幅收窄): + IGU 候选(ans = L 且无死路)现在必须通过**入场检查**(L12): + 新区每个入场 change 的因果父集必须版本覆盖 L 的全部头, + 不过则降级并调用 L11 扫描取安全基准。这消灭了原第 3 类中影响 + IGU 的全部已知构造(S4 的两个反例)。仍然遗留的是 **Checkout + 模式下 ans = meet 非 critical** 的情形(双根 x ∥ y 菱形:四条路 + 全部会合、无死路,meet = {x,y},但区域内有事件与 y 并发): + text/list 依赖下游守卫兜底——本类不受 2026-09 变更影响:L13 只在 + 第 2 类(保守回退)触发,本类的 meet 基准永远不会被认证为 + critical,守卫(base == from ∧ ¬source_not_in_op_context)仍是 + 唯一保障。Tree 的 Checkout 路径不再依赖基准,见 Q7。 + +因此严格的安全陈述是**双层契约**:「(ans, mode) + 下游守卫」合起来 +保证收敛;单看走查,无条件承诺的只有 S1/S2/S3/T。用论文语言可以把 +守卫公理写准(这就是 Q3 要拍板的边界): + +> **守卫公理(接口)**:对任意被重放的 change c,若 vv(c) ⊉ vv(起点), +> 则 tracker 以完整上下文重建后再应用 c,其效果与从任一合法 +> critical version 重放一致。 + +--- + +## 5. 引理骨架(未来 Lean 里的定理清单) + +每条引理:直观一句话 → 精确陈述 → 证明思路。 + +**L0(海拔与 happened-before)** *越晚的事件海拔严格更高。* +v → u ⟹ lamport(v) < lamport(u)。 +证明:沿父引用逐条严格递减(A1),传递。 + +**L1(无迟到)** *水位只降不升;新入堆者总在水位之下。* +堆中最大 lamport_last 随时间单调不增;且任何一次 push 的条目, +其 lamport_last 严格小于 push 发生时刻的堆最大值。 +证明:三类 push——展开(新条目是被弹条目的父事件,L0 给出严格更小)、 +对齐重入(收缩后 ≤ 原值)、聚合不 push。弹出只移除最大者。归纳。 +推论:**水位一旦降到 λ 之下,海拔 ≥ λ 的条目永远不会再出现。** + +**L2(锁步)** *长纵队不越人。* +len > 1 的段只能通过聚合被吸收或通过对齐被收缩; +只有收缩到 len = 1(即只剩节点起点)时才会展开依赖; +且届时堆中不存在 lamport 更高的未处理条目。 +证明:直接读主循环的分支结构——步骤 5b 拦截一切 len > 1 且未聚合的段。 + +**L3(会合对齐定理)** *该相遇的一定会相遇,哪怕会合点在段中间。* +若操作 u 既 ∈ 红队探索范围又 ∈ 蓝队探索范围, +则两侧条目必在 u 处(经对齐与聚合)合并为 Shared。 +证明思路:指向 u 的条目由某 depender 展开产生,lamport(depender) > lamport(u) +(L0);由 L1,该 push 发生时水位 > lamport(u),而覆盖 u 的段 +按 L2 要到水位 = lamport(节点起点) ≤ lamport(u) 时才消亡—— +所以两个条目必有同时在堆的时刻;此后对齐规则 5a/5b 使两者 id_last 相等, +聚合规则将其合并。(分侧讨论 A/B/双向、以及等海拔并列的情形。) + +**L4(颜色不变式)** *红队只踩左山,蓝队只踩右山,紫点必是公共的。* +任意时刻:A 型条目的段 ⊆ ancestry(L);B 型 ⊆ ancestry(R); +Shared 仅由 A 与 B 条目聚合产生。 +证明:对"初始化、截断、收缩、展开"四种状态变迁归纳; +段是节点前缀 + 段的 deps 属于节点起点(D9)保证展开不越界。 +**⟹ S1**。 + +**L5(极大化正确性)** 收尾的 shrink 恰好输出输入集合的极大元反链。**⟹ S2**。 + +**L6(牌子上界)** *死路走过的每一步都是某块牌子的祖先。* +一条路径自最近一次牌子发放(初始化多端点、或第一次分岔)之后 +访问的每个操作 u,满足 ∃ t ∈ tips,u ≤ t。 +证明:对"继承、合并取并、截断"归纳;发牌时刻 tips = {路径当前最新端}成立。 + +**L7(覆盖 ⟹ 冗余)** *牌子泡在紫水里,整条路都泡在紫水里。* +死路径的每个 tip ∈ ancestry(ans) ⟹ 该路径访问过的全部操作 ∈ ancestry(ans) ⊆ C。 +证明:L6 + ancestry 的传递性(u ≤ t ≤ ans 成员)。 + +**L8(覆盖走查正确性)** 收尾的多源剪枝走查返回真 ⟺ tips ⊆ ancestry(ans)。 +证明:完备性——走查是从 ans 出发沿父引用(逆 → 方向)的可达性搜索; +剪枝安全性——被剪节点的一切祖先 lamport 低于剩余 tips 的最小 lamport(L0), +不可能"包含"任何剩余 tip。 + +**L9(模式一致性)** 收尾后 is_right_greater = true ⟺ ans = L ∧ 无 uncovered。 +关键子引理:**红条目一旦在堆非空时被单独弹出,ans ≠ L**—— +因为该 L 成员随后要么被截短(id_last 变小)、要么被展开消耗, +再也不会以完整 id 进入 ans。 +另一方向:ans = L ∧ 全覆盖 ⟹ L 的每个成员都聚合成了紫点 +⟹ L ⊆ ancestry(R) ⟹(D7)vv(R) ⊇ vv(L)。**结合 L3、L6–L8 ⟹ S3**。 + +**L10(终止)** 度量:堆条目按 (lamport_last, len) 取字典序, +整个堆构成一个多重集,用 Dershowitz–Manna 多重集序比较。 +每轮循环:聚合/弹出移除元素;对齐以严格更小的元素替换; +展开以有限个严格更小(lamport_last 更小,L0)的元素替换被弹元素。 +多重集序良基 ⟹ 终止。**⟹ T**。(mathlib 已有 Dershowitz–Manna 序。) + +**L11(回退扫描的正确性)** *堆是未探索区域的切口; +切口收窄成单个段的瞬间,段尾就是最晚的单头 critical version。* +设从 L ∪ R 出发做单色下山扫描(聚合与对齐机件同主循环), +且此前没有链在堆非空时死于根或裁剪边界。若某次弹出并聚合后堆恰为空, +记被弹段的 id_last = v,则 {v} 在并集图 Events(L) ∪ Events(R) 中 +critical,且 v 是最晚的单头 critical version。证明要点: +(a) **切口不变式**:任意时刻,每个已发现未处理的事件都 ≤ 某个堆中条目 +(同 L1 的推入论证);堆空 ⟹ 未发现事件全部 ≤ v。 +(b) **已处理事件 ≥ v**:每个已处理事件的每条向下路径都经由对齐/聚合 +汇入唯一幸存的段;截断分支保证段尾取所有汇入点的最小 counter, +故所有已处理事件 happened-after (p, e) = v。 +(c) **根死亡毒化**:某链在堆非空时死于根 r,则对其后任何候选 v: +v ≤ r 不可能(r 无祖先),r ≤ v 不可能(v 在 r 之后弹出 ⟹ +lamport(v) ≤ lamport(r),而 r → v 要求严格更大,L0),故 r ∥ v, +{v} 不 critical——必须放弃。裁剪死亡同理(链的延续未知,保守放弃)。 +最晚性:扫描按 lamport 降序推进,首个满足条件的时刻即最高的切口。 + +*L11 的另一个消费者(2026-09-21)*:浅快照的根选择 `calc_shallow_doc_start` +(`src/encoding/shallow_snapshot.rs`)直接用 L11 取根。shallow snapshot 保留从根 +一直到最新版本的全部 op,故取 L = 请求版本、R = 最新版本;state-only 只保留到 +目标版本,故 L = R = 目标版本。浅格式只存根处状态和根以上的 op,与根并发的 op +两边都放不进去,所以这里要的正是 critical 而不是 meet(loro-dev/loro#1095)。 +此前按两两 meet 归约选根,在两种形状上会选出非 critical 的根:奇数个彼此独立的头 +(落单的头被当成了根),以及"过去版本 + 之后才合入、从其下方分叉的分支"。 +`crates/loro/tests/shallow_root_critical.rs` 按定义逐 op 检查这一性质。 + +**L12(入场检查的正确性)** *新区经由"入场 change"挂到旧历史上; +入场者看全了 L,其一切后代自动看全。* +设 IGU 候选成立(ans = L、无 uncovered)。定义入场 change 为新区中 +因果父集(显式 deps ∪ 隐式同 peer 前驱)全部落在 Events(L) 内的 +change。断言:新区每个事件 ≥ L 的全部头 ⟺ 每个入场 change 的父集 +版本覆盖 L。 +证明要点:(⇐)新区任意事件 e 沿因果链下行必经某入场 change c, +e ≥ c ≥ Events(父集) ⊇ L;(⇒)入场 change 自身是新区事件。 +跨节点straddle 情形(节点前半旧、后半新):多头 L 下节点中部的新 op +只有隐式父,其父若覆盖 L 全部头则该父 ≥ 每个头、又 ≤ 某头, +与反链性矛盾——故按节点起点父集判定与逐 op 判定等价。 +快路径:父集与 L 集合相等 ⟹ 覆盖(O(|L|),日常导入的主流形状)。 + +**L13(多头不动点的正确性)** *从 meet 向下收紧,直到一刀两断。* +祖先关系取重放交给差量计算器的逐 op 上下文:op x 的上下文 +ctx(x) = vv(deps(change(x))) ∪ 作者自身在 x 之前的全部 op(正是 +`iter_from_replay_base_causally` 逐 op 交出的 vv,也是 tracker 信任 +基准时所依赖的关系;A6 成立时它与 D8b 的隐式同 peer 边祖先关系重合)。 +设 v₀ = vv(from) ∩ vv(to)(两因果闭集之交仍因果闭,即 meet 的版本 +向量)。迭代:对区域 merged − v 的每个 change C,取 x = C 在 v 之上的 +首个 op(max(start(C), v[peer(C)])),若 ctx(x) ⊉ v 则 v ← v ∩ ctx(x)。 +C 的后续 op 上下文 ⊇ ctx(x)(同 deps、更长前缀),故只需查 x。 +不动点 v* 满足: +(i) *soundness*:区域内每个 op 的上下文 ⊇ v* ⟹ 每个 op 因果晚于 v* +的全部 op ⟹ v* 在上述祖先关系下 critical;这正是差量计算器消费的 +性质(重放循环的调试断言逐 op 检查 ctx ⊇ base)。 +(ii) *保持性与最大性*:任一(同一祖先关系下)critical 切口 W ≤ v 在 +每步交集后仍 ≤ v——x 在 v 之上、故在 W 之上,W critical ⟹ +ctx(x) ⊇ W ⟹ W ⊆ v ∩ ctx(x)。故 v* 是 ≤ meet 的最大 critical +version。v* 归零即证 ≤ meet 无非空 critical 切口;在 A6 下两种祖先 +关系重合,单头扫描的结果也是 ≤ meet 的 critical 切口(L11 + 每个头 +≥ 它),必同样无解。 +(iii) *终止与单遍扫描*:每次收紧至少使某 peer 的计数严格减小, +良基。且收紧不改变已得出的判定:已覆盖 v 的 ctx(x) 也覆盖更小的 +v(同 peer 分量由前缀覆盖,其余分量单调),违规者收紧后按构造覆盖 +v。故只需扫描收紧新暴露的区间 [v_new, v_old);跨切口的 change 在 +其 peer 的切口每次移入时各被检查一次,判定不变。访问总数 ≤ +区域 change 数 + 收紧次数,每次访问一次 vv 查表——不超过随后重放 +同一区域的代价,故无需预算。 +(iv) *可用性*:v* 由 ctx 的交集得到;ctx 在 A6 下因果闭(deps 闭包 +已含前缀),否则可能不闭,此时 v* 经 frontiers 往返不等于自身, +接线处退回单头扫描而不信任它。浅历史文档另要求 v* ⊇ 种子版本 +(`shallow_since_frontiers` 的 vv),否则同样退回。 + +**依赖图**: +S1 ← L4;S2 ← L5;S3 ← L9 ← {L3, L6, L7, L8};T ← L10 ← L0; +L13 ← {D8b};L13(ii) 的"归零 ⟹ 单头扫描亦无解" ← {L11, A6}; +S5b(C1) ← L3 + "无死路 ⟹ Max(C) 的每个成员被双侧到达"(未证,猜想)。 + +**引理与现有测试的对应**(代码一致性的桥): +四套随机 oracle 测试 ≈ S1/S2/S3 的随机检验; +三个定向单测(trimmed、左多头、右多头)分别钉 L9 的三个分支; +criss-cross ladder 测试钉"tips 去重后复杂度线性"(性能声明,不进证明范围)。 +`src/tests/replay_base.rs` 的定向单测钉 L13 及其接线:criss-cross 上 +多头基准命中最后同步点、单头扫描停在初始分岔、不相交历史归零、 +切口落在同一 change 内部(style 对之间)仍收敛。 + +--- + +## 6. 待定问题(需要维护者拍板) + +- **Q1** 猜想 C1(无死路 ⟹ ans = 精确 meet)要不要写进规格? + 现有 oracle 在 Checkout 模式下不检查精确性,纳入则需补测试。 +- **Q2** Linear 的外延表述("新区是 ≤-全序链且因果晚于 L") + 与差量计算器的实际假设是否一致? +- **Q3**(已部分解决,2026-08-01)movable tree issue 证明守卫公理对 + Tree 不成立,故不再把守卫当作 IGU 正确性的依据:入场检查(L12)使 + S3/S4 直接成立。守卫仍是 text/list 在 Checkout 模式下的兜底,其公理 + 化留给 Q7。 +- **Q7**(2026-08-01 判为安全;2026-09-28 推翻并改掉)Checkout 模式下 + meet 非 critical 时 Tree 的 checkout_diff 是否一致?原机制按 meet 前沿 + 的 change 起点 lamport 开窗,窗外 op 静默跳过。原论证称"与 meet 头并发 + 的 op 必产生 uncovered 死路 → L11 扫描 → critical 基准",但这不成立: + 并发 op 的依赖可以先走进 meet 之下的公共历史而会合,不留死路。反例 + (`crates/loro/tests/tree_checkout_path.rs`):`0@3`(lamport 1,建树 + 节点,依赖 `0@1`)与 meet 头 `2@2`(lamport 2)并发;从 `[3@2]` 切到 + `[1@1]` 时 meet = `[2@2]`、无死路,窗口从 2 起,`0@3` 永不被撤回;反方向 + 则前进时漏掉父节点的创建而应用子节点的创建,带订阅者时在 + `TreeState::apply_diff_and_convert` panic。修法:Tree 不再用重放基准, + 而取 from/to 两个版本对称差中最小的 lamport 作窗口(每个 peer 的差段 + 只看首个 op,O(peers)),撤回窗口内全部缓存 op,再按 (lamport, peer) + 顺序应用 to 的窗口内 op;窗口下的 op 两侧相同。此后 Tree 的 Checkout + 路径与基准选择无关,本问题关闭。详见 + `context/tree-checkout-window.md`;随机回归 + `crates/fuzz/tests/checkout_path.rs` 覆盖全部版本对。 +- **Q10**(新,2026-09)L13 的搜索只在 ≤ meet 的范围内进行,长期离线 + 分叉后的每次导入仍付出 O(分歧量)(分岔点确为最晚 critical + version,无状态的基准选择无法更好)。是否值得为这一形状缓存 + tracker,请维护者定夺。 +- **Q8**(已解决,2026-08-01:澄清而非改行为)深入推演后确认这是 + **刻意的双模式设计**:顶层返回值是**方向模式**(origin),其唯一消费者 + `DocState::apply_diff` 只用它做方向敏感的死容器缓存策略(Checkout 可能 + 倒退 → 全清;其余模式必为前进 → 只清 alive 标记),语义正确;逐容器的 + `InternalContainerDiff::diff_mode` 才是**计算模式**(各计算器如实上报, + Persist 降级后亦然),`need_check`/`need_compare` 消费的是它,配套一致。 + 风险只在"易混淆",已修:`calc_diff_internal` 内部局部量改名 + `calc_mode`,两处消费点各加不变式注释。 +- **Q9**(新,维护性)`find_path` 使用独立的旧版 `_walk_to_meet` + 实现(仅服务诊断 API `find_id_spans_between`,不参与状态变更; + relay 形状实证输出精确)。双实现存在漂移风险,建议择机合并或改为 + vv 差集直接计算。 +- **Q4** trimmed 情形:uncovered 但 ans 触及裁剪边界时保留非空 ans, + 其安全性依赖 oplog 层把重放起点钳制到浅历史根部。 + 规格按"走查 + 钳制成对成立"写,还是要求走查单独成立? +- **Q5** Lean 先证**模型层**(本文档的数学对象), + Rust 代码一致性由穷举小规模 oracle 测试桥接——可接受, + 还是希望直接做 Rust 代码级验证(Verus/Creusot,成本高得多)? +- **Q6** 三个快速路径:纳入证明范围,还是从代码中删除以换取更小的可信基? + 其中"单-单同 peer"窥孔的证明要用到 A2 划分公理,是三者中最绕的。 + +--- + +## 7. 词汇表 + +| 术语 | 含义 | +|---|---| +| CRDT | 一类允许离线并发编辑、合并后自动一致的数据结构;本文档不依赖其细节 | +| peer | 一个参与编辑的副本/设备 | +| op(操作) | 一次不可再分的修改,编号 (p, c) | +| Change / 节点 | 同一 peer 连续操作的存储打包单位 | +| span / 段 | 节点的一个前缀切片,遍历的基本单位 | +| lamport | 逻辑时间戳:沿 happened-before 严格递增(a → b ⟹ lamport(a) < lamport(b)) | +| parents / deps | 事件的父事件集(论文记 e.parents;Loro 代码称 deps) | +| happened-before → | a → b:a 在 b 的因果过去(由早指向晚,Lamport 方向;Eg-walker §2.2) | +| ∥(并发) | a ∥ b ⟺ a ≠ b ∧ a ↛ b ∧ b ↛ a | +| Events(V) / Version(G) | 论文记法(§2.3):版本的祖先闭包 / 因果闭子图的前沿,两者互逆 | +| V_crit | Eg-walker §3.6:合并的理论最优起点——发生在双方之前的最晚 critical version(Loro 实现:≤ meet 的多头不动点 L13,单头扫描 L11 兜底) | +| frontier / 前沿 | 用"最新端点"反链表示一个版本 | +| 反链 | 集合中两两互不为祖先 | +| 因果闭集 | 包含成员的所有祖先的操作集;与合法版本一一对应 | +| 版本向量 | 因果闭集的紧凑表示:每 peer 一个前缀长度 | +| C(L,R) | 两版本的公共历史 ancestry(L) ∩ ancestry(R) | +| meet 前沿 | C 的极大元反链——版本格最大下界;算法的候选起点(旧文借称 "LCA",不严格) | +| critical version | 能把事件图一刀两断的版本(Eg-walker §3.5);重放起点的合法性判据,∅ 平凡成立 | +| import / checkout | 导入远端更新 / 切换到任意历史版本 | +| 重放(replay) | 从起点按因果序重演操作以计算状态差 | +| tips / 牌子 | 路径携带的分岔点标记,用于死路的冗余性判定 | +| unmatched / 死路 | 未与对方会合而终止的路径 | +| uncovered | 存在牌子不在 ans 祖先集内的死路 ⟹ 真并发 ⟹ 保守回退 | +| trimmed / 浅历史 | 早期历史被裁剪,依赖可能指向不可用区 | diff --git a/vendor/loro-internal/docs/diff_calc.md b/vendor/loro-internal/docs/diff_calc.md new file mode 100644 index 0000000..9a1a949 --- /dev/null +++ b/vendor/loro-internal/docs/diff_calc.md @@ -0,0 +1,125 @@ +# Internal Diff Calculation + +Diff calculation produces the state patch between two versions. Checkout, +forking, import, and revert all use this path. + +## Replay base and changed containers + +`OpLog::iter_from_replay_base_causally` first chooses a replay base. The safe +base is a **critical version** in the Eg-walker sense (arXiv:2409.14252 §3.5): +a version that no concurrency crosses. When a concurrent branch invalidates +the candidate, the DAG retreats the base to the latest single-head critical +version, which can be older than the meet of the two versions. + +An old base is not evidence that every container in the replay range changed. +`DiffCalculator::calc_diff_internal` derives the changed container set from the +version-vector difference and routes common history only to those calculators. +Otherwise each unchanged List/Text/MovableList can trigger its own full-history +tracker rebuild. + +The DAG walk follows explicit dependencies plus the implicit previous counter +of the same peer. An implicit path may be redundant when an explicit relay +dependency already contains that predecessor. The walk remembers the dependency +tip where an unmatched path split and performs a targeted ancestor lookup from +the candidate common frontiers: + +- a covered tip is another route into already-common history, so `from` remains + the replay base; +- an uncovered tip is a real concurrent branch, so the conservative base is + retained. + +This lookup runs only for unmatched branch tips and prunes by visited DAG nodes +and Lamport time. It does not calculate a causal version for every new peer and +does not compare each one with the complete `from` version vector. + +## Register-only concurrency + +`to ⊇ from` does not imply the `ImportGreaterUpdates` contract: the new ops +may be concurrent with part of `from` (a stale unmerged head is the common +shape). The DAG alone can only demote such an import to `Checkout` and +retreat the base to a critical version, which replays the whole branch and +makes Text/List rebuild trackers from empty on every import. + +`OpLog::iter_from_replay_base_causally` therefore checks the concurrency at +container granularity before consulting the DAG: + +1. `OpLog::uncovered_entry_parents` finds the entry changes of the new region + whose causal parents do not cover all of `from` (the version-vector form + of spec lemma L12; it scans only the new changes). Old history outside + `⋂ Events(parents)` may be concurrent with a new op; everything else is + causally before the whole new region. +2. `OpLog::register_only_concurrency` scans the ops in that concurrent old + history and in the new region. If every container present on both sides + is a register (Map, Counter), the import replays from `from` in + `ImportGreaterUpdates` mode. + +Registers are harmless because their diffs need no positional context, but the +overlapping maps must still be resolved from the history cache (the calculator +is started in `Import` mode for them): persisted state drops the lamport +metadata of deleted roots and dead containers, so comparing lamports against +the state is not sound for concurrent ops. Containers with no concurrent old +ops keep the fast path; they are not marked `source_not_in_op_context`. + +On a shallow doc the history cache seeds a map's shallow-root entries only +when that map is first resolved (`ContainerHistoryCache::ensure_shallow_map_seeded`), +so the first concurrent map import costs O(that map), not O(every map in the +shallow root). Regression and perf test: `crates/loro/tests/shallow_lazy_map_checkout_index.rs`. + +Anything else (a text, list, movable list, tree or unknown container with ops +on both sides) falls back to the DAG's conservative answer exactly as before. +So does a shallow doc whose concurrent old history reaches below the shallow +root: later imports must causally follow the root +(`import_deps_before_shallow_root`), but the snapshot itself can retain +changes concurrent with the root (independent peer chains), and the trimmed +ops in `from` cannot be scanned for containers. The regression test is +`shallow_doc_accepts_cross_peer_op_whose_deps_include_boundary`. + +Map diffs in `Checkout`/`Import` mode only look up the keys written inside the +replayed span, and skip replayed ops that both versions already contain, so +their cost follows the update instead of the map size. + +## Winner metadata, not just values + +Map and MovableList states store the winning op's lamport/peer (map entry, +movable-list `value_id`) next to the value. A checkout must move that metadata +even when both versions hold an equal value written by different ops (a value +rewritten after the target, e.g. by `revert_to`). + +`MapDiffCalculator` (Checkout/Import) compares the winners at `from` and `to` +by op id only (`MapHistoryCache::changed_winners_for_keys`): the same winner is +skipped without reading any value, and a different winner is emitted with the +`to` value. The `from` value is never fetched, because the state applying the +diff is already at `from` (the isolated-import fast path diffs from the empty +version, where every winner is new). `MapState` writes each entry with one +`insert` and reports a change only when the previous value differs, so an +equal-value entry is a silent metadata update and events still only report +value changes. `MovableListState` does the same for element values. This keeps +equal-value checkouts at the cost of `main` before the fix: the added state +write per key is paid for by the dropped `from` value lookup (loro-dev/loro#1124; +benchmark: `crates/loro/examples/map_equal_value_bench.rs`). + +Skipping those entries left the later op's metadata in the checked-out state. +Shallow and state-only exports build their root state through such a checkout, +so the root state carried a lamport/peer that is not in the root version. On +import, `ensure_shallow_map_seeded` inserted that entry into the map checkout +index, where it compared equal to the retained later op (the index is keyed by +container, key, lamport and peer) and was dropped, so `checkout(root)` lost the +key whenever its root-time writer was trimmed. `get_last_editor` after a +checkout was wrong for the same reason. Regression tests: +`crates/loro/tests/shallow_checkout_equal_value.rs`. + +## Diff modes + +- `Checkout` is the general and slowest mode. It can move in either direction + and may use `ContainerHistoryCache`. +- `Import` requires `to > from`, but some imported operations may be concurrent + with `from`. +- `ImportGreaterUpdates` additionally guarantees that every imported operation + is causally after `from`, so the replay base is `from`. +- `Linear` additionally guarantees that imported operations are ordered, so + diff calculation does not need to build CRDT trackers. + +List, Text, and MovableList still rebuild their trackers from CRDT IDs when +retreating, when their source context is incomplete, or when shallow history +requires it. That fallback is a correctness requirement, not a replay-base +optimization. diff --git a/vendor/loro-internal/docs/mergeable-container-id.md b/vendor/loro-internal/docs/mergeable-container-id.md new file mode 100644 index 0000000..c741bee --- /dev/null +++ b/vendor/loro-internal/docs/mergeable-container-id.md @@ -0,0 +1,87 @@ +# Mergeable Container ID Encoding + +Mergeable child containers are represented as synthetic `ContainerID::Root` +values. The root name is internal and starts with the reserved namespace prefix: + +```text +🤝:<payload> +``` + +The child container type is not encoded in `<payload>`. It is carried by +`ContainerID::Root.container_type`, exactly like ordinary root containers. + +## Payload + +`<payload>` is a flattened map path: + +```text +payload = base-parent ">" key-1 ">" key-2 ... +``` + +There is no version byte in this format. It replaces the previous unpublished +encoding. + +`<base-parent>` is the nearest non-mergeable map ancestor: + +```text +$<escaped-root-name> +@<peer-base36>:<counter-base36> +``` + +`$` means the base parent is a root map. The rest of the segment is the escaped +root name. `@` means the base parent is a normal op-created map. The peer id and +counter are canonical lowercase base36 encoded to keep the payload compact. +Leading zeroes, uppercase digits, and `-0` are rejected by the parser because +`new_mergeable` never emits them. + +Every following segment is one escaped map key. Intermediate mergeable parents +are always maps, so their type is omitted. The final container's type is the +`Root.container_type` field. + +For example: + +```text +Root map "state", key "note-1", child map: +🤝:$state>note-1 with Root.container_type = Map + +Nested key "body" under that mergeable map, child text: +🤝:$state>note-1>body with Root.container_type = Text +``` + +Parsing `🤝:$state>note-1>body` as a `Text` returns: + +```text +parent = Root("🤝:$state>note-1", Map) +key = "body" +container_type = Text +``` + +This keeps nesting growth linear in the total path length. It does not embed the +full serialized parent cid at each level. + +## Escaping + +Segments are escaped before being placed in the synthetic root name: + +```text +\ -> \\ +> -> \> +/ -> \s +NUL -> \0 +``` + +`>` is the only structural delimiter. `\` introduces an escape. `/` and NUL are +also escaped so synthetic root names keep the same safety property as the old +hex encoding: they do not contain raw slash or raw NUL bytes. + +The parser rejects dangling backslashes, unknown escapes, raw slash, and raw NUL. +This prevents malformed synthetic roots from being treated as mergeable ids. + +## Marker Relationship + +The parent map slot still stores the binary mergeable marker. The marker binds +`(parent container id, key, child type)` through its digest and is not changed by +this encoding. + +The root name encoding only controls the deterministic identity of the child +container. Visibility remains controlled by the parent map slot marker. diff --git a/vendor/loro-internal/examples/automerge_x100.rs b/vendor/loro-internal/examples/automerge_x100.rs new file mode 100644 index 0000000..c8468f1 --- /dev/null +++ b/vendor/loro-internal/examples/automerge_x100.rs @@ -0,0 +1,41 @@ +use loro_internal::{cursor::PosType, loro::ExportMode, LoroDoc, VersionVector}; +use std::hint::black_box; + +fn main() { + use bench_utils::TextAction; + use std::time::Instant; + + let actions = bench_utils::get_automerge_actions(); + let loro = LoroDoc::default(); + loro.start_auto_commit(); + let start = Instant::now(); + // loro.subscribe_deep(Box::new(|_| ())); + let text = loro.get_text("text"); + let n = 100; + let mut v = VersionVector::new(); + for _ in 0..n { + for TextAction { del, ins, pos } in actions.iter() { + text.delete(*pos, *del, PosType::Unicode).unwrap(); + text.insert(*pos, ins, PosType::Unicode).unwrap(); + } + loro.commit_then_renew(); + black_box(loro.export(ExportMode::updates(&v))).unwrap(); + v = loro.oplog_vv(); + } + println!("Apply time {:?}", start.elapsed()); + loro.diagnose_size(); + drop(actions); + let start = Instant::now(); + let snapshot = loro.export(ExportMode::Snapshot).unwrap(); + println!("Snapshot encoding time {}", start.elapsed().as_millis()); + let compressed = zstd::encode_all(&mut snapshot.as_slice(), 0).unwrap(); + println!( + "Snapshot encoding time including compression {}", + start.elapsed().as_millis() + ); + println!("Snapshot size {}", snapshot.len()); + println!("Snapshot size after compression {}", compressed.len()); + let start = Instant::now(); + let _doc = LoroDoc::from_snapshot(&snapshot); + println!("Snapshot importing time {:?}", start.elapsed()); +} diff --git a/vendor/loro-internal/examples/encoding.rs b/vendor/loro-internal/examples/encoding.rs new file mode 100644 index 0000000..96670dc --- /dev/null +++ b/vendor/loro-internal/examples/encoding.rs @@ -0,0 +1,155 @@ +use std::time::Instant; + +use bench_utils::TextAction; +use loro_internal::{cursor::PosType, loro::ExportMode, LoroDoc}; + +fn main() { + let actions = bench_utils::get_automerge_actions(); + + // let loro = LoroDoc::default(); + // let loro_b = LoroDoc::default(); + // let text = loro.get_text("text"); + // let mut i = 0; + // let start = Instant::now(); + // for TextAction { pos, ins, del } in actions.iter() { + // { + // let mut txn = loro.txn().unwrap(); + // text.delete(&mut txn, *pos, *del).unwrap(); + // text.insert(&mut txn, *pos, ins).unwrap(); + // } + + // loro_b + // .import(&loro.export(ExportMode::updates(&loro_b.oplog_vv())).unwrap()) + // .unwrap(); + // i += 1; + // if i == 30000 { + // break; + // } + // } + + // println!("{}ms", start.elapsed().as_millis()); + + let loro = LoroDoc::default(); + let text = loro.get_text("text"); + + for TextAction { pos, ins, del } in actions.iter() { + let mut txn = loro.txn().unwrap(); + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + } + + let start = Instant::now(); + let snapshot = loro.export(ExportMode::Snapshot).unwrap(); + println!("Snapshot time {}ms", start.elapsed().as_millis()); + let output = miniz_oxide::deflate::compress_to_vec(&snapshot, 6); + println!( + "Snapshot+compression time {}ms", + start.elapsed().as_millis() + ); + + println!( + "snapshot size {} after compression {}", + snapshot.len(), + output.len(), + ); + + let start = Instant::now(); + let shallow_snapshot = loro + .export(ExportMode::shallow_snapshot(&loro.oplog_frontiers())) + .unwrap(); + println!("Shallow Snapshot time {}ms", start.elapsed().as_millis()); + let output = miniz_oxide::deflate::compress_to_vec(&shallow_snapshot, 6); + println!( + "Shallow Snapshot+compression time {}ms", + start.elapsed().as_millis() + ); + + println!( + "Shallow snapshot size {} after compression {}", + shallow_snapshot.len(), + output.len(), + ); + + let updates = loro.export(ExportMode::all_updates()).unwrap(); + let output = miniz_oxide::deflate::compress_to_vec(&updates, 6); + println!( + "updates size {} after compression {}", + updates.len(), + output.len(), + ); + + let json_updates = serde_json::to_string( + &loro + .export_json_updates(&Default::default(), &loro.oplog_vv(), true) + .unwrap(), + ) + .unwrap(); + let output = miniz_oxide::deflate::compress_to_vec(json_updates.as_bytes(), 6); + println!( + "json updates size {} after compression {}", + json_updates.len(), + output.len(), + ); + + // { + // // Delta encoding + + { + // Delta encoding + + let start = Instant::now(); + for _ in 0..10 { + loro.export(ExportMode::all_updates()).unwrap(); + } + + println!("Avg encode {}ms", start.elapsed().as_millis() as f64 / 10.0); + + let data = loro.export(ExportMode::all_updates()).unwrap(); + let start = Instant::now(); + let n = 5; + for _ in 0..n { + let b = LoroDoc::default(); + b.detach(); + b.import(&data).unwrap(); + } + + println!( + "Avg normal decode {}ms (without applying)", + start.elapsed().as_millis() as f64 / (n as f64) + ); + println!("size len={}", data.len()); + let d = miniz_oxide::deflate::compress_to_vec(&data, 10); + println!("size after compress len={}", d.len()); + } + + // { + // // Snapshot encoding + // // println!("\n=======================\nSnapshot Encoding:"); + + // // let start = Instant::now(); + // // for _ in 0..10 { + // // loro.export(ExportMode::Snapshot); + // // } + + // // println!("Avg encode {}ms", start.elapsed().as_millis() as f64 / 10.0); + + // // let data = loro.export(ExportMode::Snapshot); + // // let start = Instant::now(); + // // let times = 300; + // // for _ in 0..times { + // // let b = LoroDoc::default(); + // // b.import(&data).unwrap(); + // // } + + // // println!( + // // "Avg decode {}ms", + // // start.elapsed().as_millis() as f64 / times as f64 + // // ); + // // println!("size len={}", data.len()); + // // let d = miniz_oxide::deflate::compress_to_vec(&data, 10); + // // println!("size after compress len={}", d.len()); + // } +} diff --git a/vendor/loro-internal/examples/encoding_parallel.rs b/vendor/loro-internal/examples/encoding_parallel.rs new file mode 100644 index 0000000..79224d9 --- /dev/null +++ b/vendor/loro-internal/examples/encoding_parallel.rs @@ -0,0 +1,90 @@ +use bench_utils::{get_automerge_actions, TextAction}; +use loro_internal::{cursor::PosType, encoding::ExportMode, LoroDoc}; + +// #[allow(dead_code)] +// fn parallel() { +// let mut rng: StdRng = SeedableRng::seed_from_u64(1); + +// let actions = get_automerge_actions(); +// let mut loro = LoroCore::new(Default::default(), Some(1)); +// let mut loro_b = LoroCore::new(Default::default(), Some(2)); +// let mut i = 0; +// for TextAction { pos, ins, del } in actions.iter() { +// i += 1; +// if i > 1000 { +// break; +// } +// let pos = *pos; +// let del = *del; +// let mut text = loro.get_text("text"); +// text.delete(&loro, pos, del).unwrap(); +// text.insert(&loro, pos, ins).unwrap(); +// let mut text = loro_b.get_text("text"); +// let r = rng.gen_range(1..11); +// for _ in 0..r { +// text.delete(&loro_b, pos, del).unwrap(); +// text.insert(&loro_b, pos, ins).unwrap(); +// } +// loro_b.import(loro.export(loro_b.vv_cloned())); +// loro.import(loro_b.export(loro.vv_cloned())); +// } +// let encoded = loro.encode_with_cfg(EncodeMode::RleUpdates(VersionVector::new())); +// println!("parallel doc size {} bytes", encoded.len()); +// let encoded = loro.encode_all(); +// println!("parallel doc size {} bytes", encoded.len()); +// } + +// #[allow(dead_code)] +// fn real_time() { +// let actions = get_automerge_actions(); +// let mut c1 = LoroCore::new(Default::default(), Some(0)); +// let mut c2 = LoroCore::new(Default::default(), Some(1)); +// let mut t1 = c1.get_text("text"); +// let mut t2 = c2.get_text("text"); +// for (i, action) in actions.iter().enumerate() { +// if i > 2000 { +// break; +// } +// let TextAction { pos, ins, del } = action; +// if i % 2 == 0 { +// t1.delete(&c1, *pos, *del).unwrap(); +// t1.insert(&c1, *pos, ins).unwrap(); +// let update = c1.encode_with_cfg(EncodeMode::Updates(c2.vv_cloned())); +// c2.decode(&update).unwrap(); +// } else { +// t2.delete(&c2, *pos, *del).unwrap(); +// t2.insert(&c2, *pos, ins).unwrap(); +// let update = c2.encode_with_cfg(EncodeMode::Updates(c1.vv_cloned())); +// c1.decode(&update).unwrap(); +// } +// } +// } + +fn main() { + let actions = get_automerge_actions(); + let loro = LoroDoc::default(); + let loro_b = LoroDoc::default(); + let text = loro.get_text("text"); + let mut count = 0; + for TextAction { pos, ins, del } in actions.iter() { + { + let mut txn = loro.txn().unwrap(); + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + } + + loro_b + .import( + &loro + .export(ExportMode::updates(&loro_b.oplog_vv())) + .unwrap(), + ) + .unwrap(); + count += 1; + if count % 1000 == 0 { + println!("{count}"); + } + } +} diff --git a/vendor/loro-internal/examples/encoding_refactored.rs b/vendor/loro-internal/examples/encoding_refactored.rs new file mode 100644 index 0000000..44d43b2 --- /dev/null +++ b/vendor/loro-internal/examples/encoding_refactored.rs @@ -0,0 +1,115 @@ +use bench_utils::TextAction; +use loro_internal::{cursor::PosType, loro::ExportMode, LoroDoc}; +use std::hint::black_box; + +fn main() { + log_size(); + // bench_decode(); + // bench_decode_updates(); +} + +#[allow(unused)] +fn log_size() { + let actions = bench_utils::get_automerge_actions(); + { + let loro = LoroDoc::default(); + let text = loro.get_text("text"); + let mut txn = loro.txn().unwrap(); + + for TextAction { pos, ins, del } in actions.iter() { + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + } + txn.commit().unwrap(); + let snapshot = loro.export(ExportMode::Snapshot).unwrap(); + let updates = loro.export(ExportMode::all_updates()).unwrap(); + let json_updates = serde_json::to_string( + &loro + .export_json_updates(&Default::default(), &loro.oplog_vv(), true) + .unwrap(), + ) + .unwrap(); + println!("\n"); + println!("Snapshot size={}", snapshot.len()); + println!("Updates size={}", updates.len()); + println!("Json Updates size={}", json_updates.len()); + println!("\n"); + loro.diagnose_size(); + } + println!("\n"); + println!("\n"); + println!("\n"); + { + println!("One Transaction Per Action"); + let loro = LoroDoc::default(); + let text = loro.get_text("text"); + + for TextAction { pos, ins, del } in actions.iter() { + let mut txn = loro.txn().unwrap(); + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + } + let snapshot = loro.export(ExportMode::Snapshot).unwrap(); + let updates = loro.export(ExportMode::all_updates()).unwrap(); + println!("\n"); + println!("Snapshot size={}", snapshot.len()); + println!("Updates size={}", updates.len()); + println!("\n"); + loro.diagnose_size(); + } +} + +#[allow(unused)] +fn bench_decode() { + println!("Bench decode"); + let actions = bench_utils::get_automerge_actions(); + { + let mut loro = LoroDoc::default(); + let text = loro.get_text("text"); + loro.start_auto_commit(); + + for _ in 0..10 { + for TextAction { pos, ins, del } in actions.iter() { + text.delete(*pos, *del, PosType::Unicode).unwrap(); + text.insert(*pos, ins, PosType::Unicode).unwrap(); + } + } + let snapshot = loro.export(ExportMode::Snapshot).unwrap(); + // for _ in 0..100 { + // black_box(loro.export(ExportMode::Snapshot)); + // } + + for _ in 0..100 { + let loro = LoroDoc::new(); + loro.import(black_box(&snapshot)).unwrap(); + } + } +} + +#[allow(unused)] +fn bench_decode_updates() { + let actions = bench_utils::get_automerge_actions(); + let loro = LoroDoc::default(); + let text = loro.get_text("text"); + + #[allow(warnings)] + for TextAction { pos, ins, del } in actions.iter() { + let mut txn = loro.txn().unwrap(); + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + } + + let updates = loro.export(ExportMode::all_updates()).unwrap(); + for _ in 0..10 { + let loro = LoroDoc::new(); + loro.import(black_box(&updates)).unwrap(); + } +} diff --git a/vendor/loro-internal/examples/event.rs b/vendor/loro-internal/examples/event.rs new file mode 100644 index 0000000..b1fb85e --- /dev/null +++ b/vendor/loro-internal/examples/event.rs @@ -0,0 +1,66 @@ +use std::sync::Arc; + +use loro_internal::{ + cursor::PosType, + event::Diff, + handler::{Handler, ValueOrHandler}, + ListHandler, LoroDoc, MapHandler, TextHandler, ToJson, TreeHandler, +}; + +fn main() { + let doc = LoroDoc::new(); + doc.start_auto_commit(); + let list = doc.get_list("list"); + let _g = doc.subscribe_root(Arc::new(|e| { + for container_diff in e.events { + match &container_diff.diff { + Diff::List(list) => { + for item in list.iter() { + if let loro_delta::DeltaItem::Replace { value, .. } = item { + for v in value.iter() { + match v { + ValueOrHandler::Handler(h) => { + // You can directly obtain the handler and perform some operations. + if matches!(h, Handler::Map(_)) { + let text = h + .as_map() + .unwrap() + .insert_container( + "text", + TextHandler::new_detached(), + ) + .unwrap(); + text.insert(0, "created from event", PosType::Unicode) + .unwrap(); + } + } + ValueOrHandler::Value(value) => { + println!("insert value {value:?}"); + } + } + } + } + } + } + Diff::Map(map) => { + println!("map container updates {:?}", map.updated); + } + _ => {} + } + } + })); + list.insert(0, "abc").unwrap(); + list.insert_container(1, ListHandler::new_detached()) + .unwrap(); + list.insert_container(2, MapHandler::new_detached()) + .unwrap(); + list.insert_container(3, TextHandler::new_detached()) + .unwrap(); + list.insert_container(4, TreeHandler::new_detached()) + .unwrap(); + doc.commit_then_renew(); + assert_eq!( + doc.get_deep_value().to_json(), + r#"{"list":["abc",[],{"text":"created from event"},"",[]]}"# + ); +} diff --git a/vendor/loro-internal/examples/list.rs b/vendor/loro-internal/examples/list.rs new file mode 100644 index 0000000..b31373e --- /dev/null +++ b/vendor/loro-internal/examples/list.rs @@ -0,0 +1,23 @@ +use std::time::Instant; +// #[global_allocator] +// static ALLOC: dhat::Alloc = dhat::Alloc; + +use loro_internal::{encoding::ExportMode, LoroDoc}; + +fn main() { + // let p = dhat::Profiler::builder().trim_backtraces(None).build(); + let start = Instant::now(); + let actor = LoroDoc::default(); + let mut output = Vec::new(); + let list = actor.get_list("list"); + let mut last_vv = actor.oplog_vv(); + for i in 0..10000 { + let mut txn = actor.txn().unwrap(); + list.insert_with_txn(&mut txn, i, i.to_string().into()) + .unwrap(); + output.push(actor.export(ExportMode::updates(&last_vv.clone())).unwrap()); + last_vv = actor.oplog_vv(); + } + println!("{} ms", start.elapsed().as_millis()); + // drop(p) +} diff --git a/vendor/loro-internal/examples/many_actors.rs b/vendor/loro-internal/examples/many_actors.rs new file mode 100644 index 0000000..fd36b1f --- /dev/null +++ b/vendor/loro-internal/examples/many_actors.rs @@ -0,0 +1,60 @@ +use std::time::Instant; + +use loro_internal::{loro::ExportMode, LoroDoc, LoroValue}; +// #[global_allocator] +// static ALLOC: dhat::Alloc = dhat::Alloc; + +fn main() { + // with_100k_actors_then_action(); + import_with_many_actors(); +} + +#[allow(unused)] +fn import_with_many_actors() { + let store = LoroDoc::default(); + for i in 0..10000 { + store.set_peer_id(i); + let list = store.get_list("list"); + let value: LoroValue = i.to_string().into(); + let mut txn = store.txn().unwrap(); + list.insert_with_txn(&mut txn, 0, value).unwrap(); + txn.commit().unwrap(); + } + + { + let start = Instant::now(); + let bytes = store.export(ExportMode::Snapshot).unwrap(); + LoroDoc::default().import(&bytes).unwrap(); + println!("{} ms", start.elapsed().as_millis()); + } + + // let profiler = dhat::Profiler::builder().trim_backtraces(None).build(); + // let start = Instant::now(); + // let mut actor = LoroDoc::default(); + // actor.import_batch(&updates).unwrap(); + // println!("{} bytes", updates.iter().map(|x| x.len()).sum::<usize>()); + // // dbg!(actor.get_state_deep_value()); + // println!("{} ms", start.elapsed().as_millis()); + // drop(profiler); +} + +#[allow(unused)] +fn with_100k_actors_then_action() { + let store = LoroDoc::default(); + for i in 0..100_000 { + store.set_peer_id(i); + let list = store.get_list("list"); + let value: LoroValue = i.to_string().into(); + let mut txn = store.txn().unwrap(); + list.insert_with_txn(&mut txn, 0, value).unwrap(); + txn.commit().unwrap(); + } + + for i in 0..200_000 { + let list = store.get_list("list"); + let value: LoroValue = i.to_string().into(); + let mut txn = store.txn().unwrap(); + list.insert_with_txn(&mut txn, 0, value).unwrap(); + txn.commit().unwrap(); + } +} diff --git a/vendor/loro-internal/examples/mem.rs b/vendor/loro-internal/examples/mem.rs new file mode 100644 index 0000000..b7bda99 --- /dev/null +++ b/vendor/loro-internal/examples/mem.rs @@ -0,0 +1,110 @@ +// #[global_allocator] +// static ALLOC: dhat::Alloc = dhat::Alloc; + +// use std::time::Instant; + +// use bench_utils::TextAction; +// use loro_internal::LoroDoc; + +// fn apply_automerge(times: usize) { +// let actions = bench_utils::get_automerge_actions(); +// let start = Instant::now(); +// let profiler = dhat::Profiler::builder().trim_backtraces(None).build(); +// let mut loro = LoroCore::default(); +// let mut text = loro.get_text("text"); +// println!("Apply Automerge Dataset 1X"); +// for _i in 0..times { +// for TextAction { pos, ins, del } in actions.iter() { +// text.delete(&loro, *pos, *del).unwrap(); +// text.insert(&loro, *pos, ins).unwrap(); +// } +// } +// drop(profiler); +// println!("Used: {} ms", start.elapsed().as_millis()); +// } + +// fn concurrent_actors(actor_num: usize) { +// let mut actors: Vec<LoroCore> = Vec::new(); +// for _ in 0..actor_num { +// actors.push(LoroCore::default()); +// } + +// let mut updates = Vec::new(); +// for actor in actors.iter_mut() { +// let mut list = actor.get_list("list"); +// list.insert(actor, 0, 1).unwrap(); +// updates.push(actor.encode_all()); +// } + +// let mut a = actors.drain(0..1).next().unwrap(); +// drop(actors); +// let profiler = dhat::Profiler::builder().trim_backtraces(None).build(); +// for update in updates { +// a.decode(&update).unwrap(); +// } +// drop(profiler); +// } + +// fn realtime_sync(actor_num: usize, action_num: usize) { +// let actions = bench_utils::gen_realtime_actions(action_num, actor_num, 100); +// let profiler = dhat::Profiler::builder().trim_backtraces(None).build(); +// let mut actors = Vec::new(); +// for _ in 0..actor_num { +// actors.push(LoroDoc::default()); +// } + +// for action in actions { +// match action { +// bench_utils::Action::Text { client, action } => { +// let mut text = actors[client].get_text("text"); +// let bench_utils::TextAction { pos, ins, del } = action; +// let pos = pos % (text.len() + 1); +// let del = del.min(text.len() - pos); +// text.delete(&actors[client], pos, del).unwrap(); +// text.insert(&actors[client], pos, &ins).unwrap(); +// } +// bench_utils::Action::SyncAll => { +// let mut updates = Vec::new(); +// for i in 1..actor_num { +// let (a, b) = arref::array_mut_ref!(&mut actors, [0, i]); +// updates.push(b.encode_from(a.vv_cloned())); +// } +// for update in updates { +// // TODO: use import batch here +// actors[0].decode(&update).unwrap(); +// } +// for i in 1..actor_num { +// let (a, b) = arref::array_mut_ref!(&mut actors, [0, i]); +// b.decode(&a.encode_from(b.vv_cloned())).unwrap(); +// } +// } +// } +// } +// drop(profiler); +// } + +pub fn main() { + // let args: Vec<_> = std::env::args().collect(); + // if args.len() < 2 { + // apply_automerge(1); + // return; + // } + + // match args[1].as_str() { + // "automerge" => { + // apply_automerge(1); + // } + // "100_concurrent" => { + // concurrent_actors(100); + // } + // "200_concurrent" => { + // concurrent_actors(200); + // } + // "10_actor_sync_1000_actions" => realtime_sync(10, 1000), + // "20_actor_sync_1000_actions" => realtime_sync(20, 1000), + // "10_actor_sync_2000_actions" => realtime_sync(10, 2000), + // _ => { + // panic!("Unknown command `{}`", args.join(" ")); + // } + // } +} diff --git a/vendor/loro-internal/examples/obs.rs b/vendor/loro-internal/examples/obs.rs new file mode 100644 index 0000000..fee6d7d --- /dev/null +++ b/vendor/loro-internal/examples/obs.rs @@ -0,0 +1,26 @@ +use bench_utils::TextAction; + +use loro_internal::{cursor::PosType, LoroDoc}; + +fn main() { + let actions = bench_utils::get_automerge_actions(); + let start = std::time::Instant::now(); + for _ in 0..10 { + let loro = LoroDoc::default(); + let text = loro.get_text("text"); + // loro.subscribe_deep(Arc::new(move |event| { + // black_box(event); + // })); + for TextAction { pos, ins, del } in actions.iter() { + let mut txn = loro.txn().unwrap(); + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + } + + text.diagnose(); + } + + println!("time: {:?}", start.elapsed()); +} diff --git a/vendor/loro-internal/examples/pending.rs b/vendor/loro-internal/examples/pending.rs new file mode 100644 index 0000000..a2e5bae --- /dev/null +++ b/vendor/loro-internal/examples/pending.rs @@ -0,0 +1,33 @@ +use bench_utils::TextAction; +use loro_internal::{cursor::PosType, encoding::ExportMode, LoroDoc, VersionVector}; + +pub fn main() { + let loro = LoroDoc::default(); + let mut latest_vv = VersionVector::default(); + let mut updates = vec![]; + let actions = bench_utils::get_automerge_actions(); + let action_length = actions.len(); + let text = loro.get_text("text"); + for chunks in actions.chunks(action_length / 10) { + for TextAction { pos, ins, del } in chunks { + let mut txn = loro.txn().unwrap(); + text.delete_with_txn(&mut txn, *pos, *del, PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, *pos, ins, PosType::Unicode) + .unwrap(); + let update = loro.export(ExportMode::updates(&latest_vv)).unwrap(); + updates.push(update); + latest_vv = loro.oplog_vv(); + } + } + + println!("done encoding"); + updates.reverse(); + let start = std::time::Instant::now(); + let store2 = LoroDoc::default(); + store2.detach(); + for update in updates.iter() { + store2.import(update).unwrap(); + } + println!("Elapsed {}", start.elapsed().as_millis()); +} diff --git a/vendor/loro-internal/examples/state_size.rs b/vendor/loro-internal/examples/state_size.rs new file mode 100644 index 0000000..099025d --- /dev/null +++ b/vendor/loro-internal/examples/state_size.rs @@ -0,0 +1,127 @@ +use loro_common::{LoroResult, LoroValue}; +use loro_internal::{loro::ExportMode, LoroDoc}; +use rand::{thread_rng, Rng}; + +#[derive(Debug, Clone, Copy)] +enum Kind { + Map, + List, + MovableList, + Text, + Tree, + Counter, +} + +fn empty_state() -> Vec<u8> { + let doc = LoroDoc::new_auto_commit(); + doc.export(ExportMode::StateOnly(None)).unwrap() +} + +fn create_elem_sequentially(n: usize, kind: Kind) -> LoroResult<Vec<u8>> { + let doc = LoroDoc::new_auto_commit(); + for i in 0..n { + match kind { + Kind::Map => { + doc.get_map("map").insert(&i.to_string(), i as u32)?; + } + Kind::List => { + doc.get_list("list").push(i as u32)?; + } + Kind::MovableList => { + doc.get_movable_list("movable_list") + .push(LoroValue::from(i as u32))?; + } + Kind::Text => { + let text = doc.get_text("text"); + text.insert_unicode(text.len_unicode(), &i.to_string())?; + } + Kind::Tree => { + doc.get_tree("tree").enable_fractional_index(0); + doc.get_tree("tree") + .create(loro_internal::TreeParentId::Root)?; + } + Kind::Counter => { + #[cfg(feature = "counter")] + { + doc.get_counter("counter").increment(i as f64)?; + } + } + } + } + let bytes = doc.export(ExportMode::StateOnly(None)).unwrap(); + Ok(bytes) +} + +fn create_elem_randomly(n: usize, kind: Kind) -> LoroResult<Vec<u8>> { + let doc = LoroDoc::new_auto_commit(); + let mut rng = thread_rng(); + for _ in 0..n / 5 { + for _ in 0..5 { + match kind { + Kind::Map => { + let i = rng.gen::<usize>() % 1000; + doc.get_map("map").insert(&i.to_string(), i as u32)?; + } + Kind::List => { + let list = doc.get_list("list"); + let i = rng.gen::<usize>() % (list.len() + 1); + list.insert(i, i as u32)?; + } + Kind::MovableList => { + let list = doc.get_movable_list("movable_list"); + let i = rng.gen::<usize>() % (list.len() + 1); + list.insert(i, i as u32)?; + } + Kind::Text => { + let text = doc.get_text("text"); + let i = rng.gen::<usize>() % (text.len_unicode() + 1); + text.insert_unicode(i, &i.to_string())?; + } + Kind::Tree => { + doc.get_tree("tree").enable_fractional_index(0); + doc.get_tree("tree") + .create(loro_internal::TreeParentId::Root)?; + } + Kind::Counter => { + #[cfg(feature = "counter")] + { + doc.get_counter("counter").increment(rng.gen::<f64>())?; + } + } + } + } + doc.set_peer_id(rng.gen::<u64>()).unwrap(); + } + let bytes = doc.export(ExportMode::StateOnly(None)).unwrap(); + Ok(bytes) +} + +fn main() -> LoroResult<()> { + for kind in [ + Kind::Map, + Kind::List, + Kind::MovableList, + Kind::Text, + #[allow(unused)] + Kind::Tree, + #[cfg(feature = "counter")] + Kind::Counter, + ] { + println!("============================="); + println!("{kind:?}"); + println!("============================="); + + for (title, bytes) in [ + ("empty", empty_state()), + ("10 items", create_elem_sequentially(10, kind)?), + ( + "1000 items sequentially", + create_elem_sequentially(1000, kind)?, + ), + ("1000 items randomly", create_elem_randomly(1000, kind)?), + ] { + println!("{}: {} bytes", title, bytes.len()) + } + } + Ok(()) +} diff --git a/vendor/loro-internal/examples/tree.rs b/vendor/loro-internal/examples/tree.rs new file mode 100644 index 0000000..bc2c2d6 --- /dev/null +++ b/vendor/loro-internal/examples/tree.rs @@ -0,0 +1,83 @@ +use std::time::Instant; + +use loro_internal::{encoding::ExportMode, LoroDoc, TreeParentId}; +use rand::{rngs::StdRng, Rng}; + +#[allow(unused)] +fn checkout() { + let depth = 300; + let loro = LoroDoc::new_auto_commit(); + let tree = loro.get_tree("tree"); + let mut ids = vec![]; + let mut versions = vec![]; + let id1 = tree.create_at(TreeParentId::Root, 0).unwrap(); + ids.push(id1); + versions.push(loro.oplog_frontiers()); + for _ in 1..depth { + let id = tree + .create_at(TreeParentId::Node(*ids.last().unwrap()), 0) + .unwrap(); + ids.push(id); + versions.push(loro.oplog_frontiers()); + } + let mut rng: StdRng = rand::SeedableRng::seed_from_u64(0); + + for _ in 0..1000 { + let i = rng.gen::<usize>() % depth; + let f = &versions[i]; + loro.checkout(f).unwrap(); + } +} + +#[allow(unused)] +fn mov() { + let loro = LoroDoc::new_auto_commit(); + let tree = loro.get_tree("tree"); + let mut ids = vec![]; + let size = 10000; + for _ in 0..size { + ids.push(tree.create_at(TreeParentId::Root, 0).unwrap()) + } + let mut rng: StdRng = rand::SeedableRng::seed_from_u64(0); + let n = 100000; + + for _ in 0..n { + let i = rng.gen::<usize>() % size; + let j = rng.gen::<usize>() % size; + let children_num = tree.children_num(&TreeParentId::Node(ids[j])).unwrap_or(0); + tree.move_to(ids[i], TreeParentId::Node(ids[j]), children_num) + .unwrap_or_default(); + } + println!( + "encode snapshot size {:?}", + loro.export(ExportMode::Snapshot).unwrap().len() + ); + println!( + "encode updates size {:?}", + loro.export(ExportMode::all_updates()).unwrap().len() + ); +} + +#[allow(unused)] +fn create() { + let size = 100000; + let loro = LoroDoc::default(); + let tree = loro.get_tree("tree"); + for _ in 0..size { + tree.create_at(TreeParentId::Root, 0).unwrap(); + } + println!( + "encode snapshot size {:?}\n", + loro.export(ExportMode::Snapshot).unwrap().len() + ); + println!( + "encode updates size {:?}", + loro.export(ExportMode::all_updates()).unwrap().len() + ); +} + +fn main() { + let s = Instant::now(); + mov(); + println!("{} ms", s.elapsed().as_millis()); +} diff --git a/vendor/loro-internal/proptest-regressions/dag/test.txt b/vendor/loro-internal/proptest-regressions/dag/test.txt new file mode 100644 index 0000000..54efd86 --- /dev/null +++ b/vendor/loro-internal/proptest-regressions/dag/test.txt @@ -0,0 +1,10 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 6fa5e507d2f2f20cb7f5d8a40762b5dfbe9832884ba1ec4fdd98afb3618a1495 # shrinks to before_merged_insertions = [], after_merged_insertions = [] +cc 33ec71c1f62792545519d525dcd8cdd8a4a666640aada85fc78bfe2d2b92591d # shrinks to mut interactions = [Interaction { dag_idx: 0, merge_with: None, len: 1 }, Interaction { dag_idx: 1, merge_with: None, len: 2 }, Interaction { dag_idx: 1, merge_with: Some(0), len: 1 }] +cc cbbf51fd3f0bad25aede701c73321a1ead8738e3052655595bd29aa378bc0655 # shrinks to interactions = [Interaction { dag_idx: 1, merge_with: None, len: 3 }, Interaction { dag_idx: 1, merge_with: None, len: 3 }, Interaction { dag_idx: 4, merge_with: Some(1), len: 1 }, Interaction { dag_idx: 0, merge_with: None, len: 1 }, Interaction { dag_idx: 2, merge_with: Some(0), len: 1 }, Interaction { dag_idx: 0, merge_with: None, len: 1 }, Interaction { dag_idx: 2, merge_with: Some(0), len: 1 }, Interaction { dag_idx: 3, merge_with: Some(0), len: 1 }] +cc eee5bb7b82641d1eab5da8ab36320aafb72768c9cafb531c0b16f37061d56527 # shrinks to before_merged_insertions = [Interaction { dag_idx: 0, merge_with: None, len: 1 }], after_merged_insertions = [Interaction { dag_idx: 0, merge_with: None, len: 1 }] diff --git a/vendor/loro-internal/scripts/fuzz.ts b/vendor/loro-internal/scripts/fuzz.ts new file mode 100644 index 0000000..86f7f10 --- /dev/null +++ b/vendor/loro-internal/scripts/fuzz.ts @@ -0,0 +1,36 @@ +import * as path from "https://deno.land/std@0.105.0/path/mod.ts"; +const __dirname = path.dirname(path.fromFileUrl(import.meta.url)); +import { resolve } from "https://deno.land/std@0.198.0/path/mod.ts"; + +const validTargets = Array.from( + Deno.readDirSync(resolve(__dirname, "../fuzz/fuzz_targets")), +).map((x) => x.name.replace(/.rs$/, "")); + +const targets = + Deno.args.length === 0 + ? validTargets + : Deno.args.filter((x) => validTargets.includes(x)); + +const promises = []; +for (const target of targets) { + const cmd = [ + "cargo", + "+nightly", + "fuzz", + "run", + target, + "--", + "-max_total_time=1", + ]; + console.log("🔨" + cmd.join(" ")); + promises.push( + Deno.run({ + cmd, + stdout: "inherit", + stderr: "inherit", + cwd: resolve(__dirname, ".."), + }).status(), + ); +} + +await Promise.allSettled(promises); diff --git a/vendor/loro-internal/scripts/mem.ts b/vendor/loro-internal/scripts/mem.ts new file mode 100644 index 0000000..384ba2b --- /dev/null +++ b/vendor/loro-internal/scripts/mem.ts @@ -0,0 +1,49 @@ +import * as path from "https://deno.land/std@0.105.0/path/mod.ts"; +const __dirname = path.dirname(path.fromFileUrl(import.meta.url)); +import { resolve } from "https://deno.land/std@0.105.0/path/mod.ts"; + +export const Tasks = [ + "100_concurrent", + "200_concurrent", + "automerge", + "10_actor_sync_1000_actions", + "20_actor_sync_1000_actions", + "10_actor_sync_2000_actions", +]; + +export interface Result { + task: string; + maxBytes: number; + endBytes: number; +} + +// run `cargo run --example mem -r -- ${task}` +export async function run(task: string): Promise<Result> { + const cmd = `cargo run --example mem -r -- ${task}`; + const process = Deno.run({ + cmd: cmd.split(" "), + cwd: resolve(__dirname, ".."), + stdout: "piped", + stderr: "piped", + }); + + const output = new TextDecoder().decode(await process.stderrOutput()); + try { + // extract "2,555,555" from `dhat: At t-gmax: 2,555,555 bytes` + const maxBytes = parseInt( + output.match(/dhat: At t-gmax:\s+((\d+,?)+) bytes/)![1].replace(/,/g, ""), + ); + const endBytes = parseInt( + output.match(/dhat: At t-end:\s+((\d+,?)+) bytes/)![1].replace(/,/g, ""), + ); + return { + task, + maxBytes, + endBytes, + }; + } catch (e) { + console.error(e); + console.log(output); + throw e; + } +} diff --git a/vendor/loro-internal/scripts/run_mem.ts b/vendor/loro-internal/scripts/run_mem.ts new file mode 100644 index 0000000..c1476b9 --- /dev/null +++ b/vendor/loro-internal/scripts/run_mem.ts @@ -0,0 +1,9 @@ +import { run, Tasks } from "./mem.ts"; + +const output = []; +for (const task of Tasks) { + const result = await run(task); + output.push(result); +} + +console.log(output); diff --git a/vendor/loro-internal/src/allocation/bfs.rs b/vendor/loro-internal/src/allocation/bfs.rs new file mode 100644 index 0000000..47fae08 --- /dev/null +++ b/vendor/loro-internal/src/allocation/bfs.rs @@ -0,0 +1,386 @@ +#![allow(dead_code)] +use crate::{ + dag::{Dag, DagNode}, + id::ID, + version::Frontiers, +}; + +use rustc_hash::FxHashSet; +use std::collections::BinaryHeap; + +#[derive(Debug, PartialEq, Eq)] +struct SortBase { + id: ID, + lamport: u32, +} + +impl PartialOrd for SortBase { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for SortBase { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.lamport.cmp(&other.lamport) + } +} + +pub struct BfsBody { + queue: BinaryHeap<SortBase>, + visited: FxHashSet<ID>, +} + +pub fn calc_critical_version_bfs<T: DagNode, D: Dag<Node = T>>( + graph: &D, + start_list: &Frontiers, +) -> Vec<ID> { + let mut runner = BfsBody::new(); + runner.run(graph, start_list) +} + +impl BfsBody { + fn new() -> Self { + Self { + queue: BinaryHeap::new(), + visited: FxHashSet::default(), + } + } + + fn run<T: DagNode, D: Dag<Node = T>>(&mut self, graph: &D, start_list: &Frontiers) -> Vec<ID> { + let mut start_end_set: FxHashSet<ID> = start_list.iter().collect(); + for start in start_list.iter() { + self.queue.push(SortBase { + id: start, + lamport: graph.get(start).unwrap().lamport(), + }); + } + let mut result: Vec<ID> = Vec::new(); + while let Some(SortBase { id, lamport: _ }) = self.queue.pop() { + if self.queue.is_empty() { + result.push(id); + } + let node = graph.get(id).unwrap(); + if node.deps().is_empty() { + start_end_set.insert(id); + } else { + for to_id in node.deps().iter() { + if self.visited.contains(&to_id) { + continue; + } + self.visited.insert(to_id); + self.queue.push(SortBase { + id: to_id, + lamport: graph.get(to_id).unwrap().lamport(), + }); + } + } + } + result + .iter() + .filter(|id| !start_end_set.contains(id)) + .cloned() + .collect() + } +} + +#[cfg(test)] +mod additional_tests { + use std::collections::BTreeMap; + + use loro_common::{HasId, HasIdSpan}; + use rle::{HasLength, Sliceable}; + + use super::*; + use crate::{ + change::Lamport, + span::{HasLamport, HasLamportSpan}, + version::VersionVector, + }; + + #[derive(Clone, Debug)] + struct TestNode { + id: ID, + lamport: Lamport, + deps: Frontiers, + } + + impl DagNode for TestNode { + fn deps(&self) -> &Frontiers { + &self.deps + } + } + + impl HasId for TestNode { + fn id_start(&self) -> ID { + self.id + } + } + + impl HasLamport for TestNode { + fn lamport(&self) -> Lamport { + self.lamport + } + } + + impl HasLength for TestNode { + fn content_len(&self) -> usize { + 1 + } + } + + impl Sliceable for TestNode { + fn slice(&self, _from: usize, _to: usize) -> Self { + self.clone() + } + } + + #[derive(Debug)] + struct TestDag { + nodes: BTreeMap<ID, TestNode>, + vv: VersionVector, + frontier: Frontiers, + } + + impl TestDag { + fn new(nodes: impl IntoIterator<Item = TestNode>, frontier: Frontiers) -> Self { + let mut vv = VersionVector::default(); + let nodes = nodes + .into_iter() + .map(|node| { + vv.set_end(node.id_end()); + (node.id_start(), node) + }) + .collect(); + Self { + nodes, + vv, + frontier, + } + } + } + + impl Dag for TestDag { + type Node = TestNode; + + fn get(&self, id: ID) -> Option<Self::Node> { + self.nodes.get(&id).cloned() + } + + fn frontier(&self) -> &Frontiers { + &self.frontier + } + + fn vv(&self) -> &VersionVector { + &self.vv + } + + fn contains(&self, id: ID) -> bool { + self.nodes.contains_key(&id) + } + } + + fn node(peer: u64, counter: i32, lamport: Lamport, deps: Frontiers) -> TestNode { + TestNode { + id: ID::new(peer, counter), + lamport, + deps, + } + } + + #[test] + fn sort_base_prioritizes_larger_lamport_in_binary_heap() { + let mut heap = BinaryHeap::new(); + heap.push(SortBase { + id: ID::new(1, 0), + lamport: 10, + }); + heap.push(SortBase { + id: ID::new(2, 0), + lamport: 20, + }); + + assert_eq!(heap.pop().unwrap().id, ID::new(2, 0)); + assert_eq!(heap.pop().unwrap().id, ID::new(1, 0)); + } + + #[test] + fn bfs_critical_versions_include_linear_cut_points() { + let root = node(1, 0, 0, Frontiers::default()); + let middle = node(1, 1, 1, root.id.into()); + let head = node(1, 2, 2, middle.id.into()); + let dag = TestDag::new( + vec![root.clone(), middle.clone(), head.clone()], + head.id.into(), + ); + + let critical = calc_critical_version_bfs(&dag, &head.id.into()); + assert_eq!(critical, vec![middle.id]); + } + + #[test] + fn bfs_critical_versions_skip_start_and_leaf_nodes_in_diamond_graphs() { + let root = node(1, 0, 0, Frontiers::default()); + let left = node(2, 0, 1, root.id.into()); + let right = node(3, 0, 2, root.id.into()); + let merge = node(4, 0, 3, Frontiers::from([left.id, right.id])); + let dag = TestDag::new( + vec![root.clone(), left.clone(), right.clone(), merge.clone()], + merge.id.into(), + ); + + let critical = calc_critical_version_bfs(&dag, &merge.id.into()); + assert!(critical.is_empty()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{ + cmp::Ordering, + collections::{HashMap, HashSet}, + sync::Arc, + }; + + use crate::{ + change::Lamport, + id::{Counter, PeerID}, + span::{HasId, HasLamport}, + }; + use rle::{HasLength, Sliceable}; + + #[derive(Debug, Clone, PartialEq, Eq)] + struct TestNode { + id: ID, + lamport: Lamport, + len: usize, + deps: Arc<Frontiers>, + } + + impl TestNode { + fn new(id: ID, lamport: Lamport, deps: Frontiers) -> Self { + Self { + id, + lamport, + len: 1, + deps: Arc::new(deps), + } + } + } + + impl DagNode for TestNode { + fn deps(&self) -> &Frontiers { + &self.deps + } + } + + impl Sliceable for TestNode { + fn slice(&self, _from: usize, _to: usize) -> Self { + self.clone() + } + } + + impl HasLamport for TestNode { + fn lamport(&self) -> Lamport { + self.lamport + } + } + + impl HasId for TestNode { + fn id_start(&self) -> ID { + self.id + } + } + + impl HasLength for TestNode { + fn content_len(&self) -> usize { + self.len + } + } + + #[derive(Debug)] + struct TestDag { + nodes: HashMap<PeerID, Vec<TestNode>>, + version_vec: crate::version::VersionVector, + } + + impl TestDag { + fn new(nodes: Vec<TestNode>) -> Self { + let mut map: HashMap<PeerID, Vec<TestNode>> = HashMap::new(); + let mut vv = crate::version::VersionVector::new(); + for node in nodes { + vv.insert(node.id.peer, node.id.counter + node.len as Counter); + map.entry(node.id.peer).or_default().push(node); + } + for nodes in map.values_mut() { + nodes.sort_by(|a, b| match a.id.counter.cmp(&b.id.counter) { + Ordering::Equal => a.len.cmp(&b.len), + other => other, + }); + } + Self { + nodes: map, + version_vec: vv, + } + } + } + + impl Dag for TestDag { + type Node = TestNode; + + fn get(&self, id: ID) -> Option<Self::Node> { + let arr = self.nodes.get(&id.peer)?; + arr.binary_search_by(|node| { + if node.id.counter > id.counter { + Ordering::Greater + } else if node.id.counter + node.len as i32 <= id.counter { + Ordering::Less + } else { + Ordering::Equal + } + }) + .ok() + .map(|idx| arr[idx].clone()) + } + + fn frontier(&self) -> &Frontiers { + panic!("frontier is not used in bfs tests") + } + + fn vv(&self) -> &crate::version::VersionVector { + &self.version_vec + } + + fn contains(&self, id: ID) -> bool { + self.version_vec.includes_id(id) + } + } + + fn id(peer: PeerID, counter: Counter) -> ID { + ID::new(peer, counter) + } + + fn frontier(ids: &[ID]) -> Frontiers { + let mut frontier = Frontiers::new(); + for id in ids { + frontier.push(*id); + } + frontier + } + + #[test] + fn dedupes_shared_dependencies_and_filters_terminal_nodes() { + let graph = TestDag::new(vec![ + TestNode::new(id(1, 0), 10, frontier(&[id(2, 0), id(3, 0)])), + TestNode::new(id(2, 0), 8, frontier(&[id(4, 0)])), + TestNode::new(id(3, 0), 7, frontier(&[id(4, 0)])), + TestNode::new(id(4, 0), 1, Frontiers::new()), + ]); + + let result = calc_critical_version_bfs(&graph, &frontier(&[id(1, 0)])); + + assert!(result.is_empty()); + assert_eq!(graph.get(id(4, 0)).unwrap().deps().len(), 0); + } +} diff --git a/vendor/loro-internal/src/allocation/dfs.rs b/vendor/loro-internal/src/allocation/dfs.rs new file mode 100644 index 0000000..da41c5c --- /dev/null +++ b/vendor/loro-internal/src/allocation/dfs.rs @@ -0,0 +1,416 @@ +use std::collections::HashSet; + +use crate::{ + dag::{Dag, DagNode}, + id::ID, + version::Frontiers, +}; + +fn get_all_points<T: DagNode, D: Dag<Node = T>>(graph: &D, points: &mut HashSet<ID>, current: &ID) { + points.insert(*current); + for to_id in graph.get(*current).unwrap().deps().iter() { + get_all_points(graph, points, &to_id); + } +} + +pub fn get_end_list<T: DagNode, D: Dag<Node = T>>(graph: &D, start_list: &Frontiers) -> Frontiers { + let mut end_set: HashSet<ID> = HashSet::new(); + for start_id in start_list.iter() { + end_dfs(graph, &start_id, &mut end_set); + } + end_set.into_iter().collect() +} + +fn end_dfs<T: DagNode, D: Dag<Node = T>>(graph: &D, current: &ID, end_set: &mut HashSet<ID>) { + let binding = graph.get(*current).unwrap(); + let deps = binding.deps(); + if deps.is_empty() { + end_set.insert(*current); + } + for to_id in deps.iter() { + end_dfs(graph, &to_id, end_set); + } +} + +pub fn calc_critical_version_dfs<T: DagNode, D: Dag<Node = T>>( + graph: &D, + start_list: &Frontiers, + end_list: &Frontiers, +) -> Vec<ID> { + let mut result: Vec<ID> = vec![]; + let mut points: HashSet<ID> = HashSet::new(); + let start_list_set: HashSet<ID> = HashSet::from_iter(start_list.iter()); + let end_list_set: HashSet<ID> = HashSet::from_iter(end_list.iter()); + for start_id in start_list.iter() { + get_all_points(graph, &mut points, &start_id); + } + for escape in points { + let mut flag = false; + for start_id in start_list.iter() { + if dfs(graph, &start_id, &escape, &end_list_set) { + flag = true; + break; + } + } + if flag { + continue; + } + if !end_list_set.contains(&escape) && !start_list_set.contains(&escape) { + result.push(escape); + } + } + result +} + +fn dfs<T: DagNode, D: Dag<Node = T>>( + graph: &D, + current: &ID, + escape: &ID, + end_list_set: &HashSet<ID>, +) -> bool { + if current == escape { + return false; + } + if end_list_set.contains(current) { + return true; + } + for to_id in graph.get(*current).unwrap().deps().iter() { + if dfs(graph, &to_id, escape, end_list_set) { + return true; + } + } + false +} + +#[cfg(test)] +mod additional_tests { + use std::collections::BTreeMap; + + use loro_common::{HasId, HasIdSpan}; + use rle::{HasLength, Sliceable}; + + use super::*; + use crate::{ + change::Lamport, + span::{HasLamport, HasLamportSpan}, + version::VersionVector, + }; + + #[derive(Clone, Debug)] + struct TestNode { + id: ID, + lamport: Lamport, + deps: Frontiers, + } + + impl DagNode for TestNode { + fn deps(&self) -> &Frontiers { + &self.deps + } + } + + impl HasId for TestNode { + fn id_start(&self) -> ID { + self.id + } + } + + impl HasLamport for TestNode { + fn lamport(&self) -> Lamport { + self.lamport + } + } + + impl HasLength for TestNode { + fn content_len(&self) -> usize { + 1 + } + } + + impl Sliceable for TestNode { + fn slice(&self, _from: usize, _to: usize) -> Self { + self.clone() + } + } + + #[derive(Debug)] + struct TestDag { + nodes: BTreeMap<ID, TestNode>, + vv: VersionVector, + frontier: Frontiers, + } + + impl TestDag { + fn new(nodes: impl IntoIterator<Item = TestNode>, frontier: Frontiers) -> Self { + let mut vv = VersionVector::default(); + let nodes = nodes + .into_iter() + .map(|node| { + vv.set_end(node.id_end()); + (node.id_start(), node) + }) + .collect(); + Self { + nodes, + vv, + frontier, + } + } + } + + impl Dag for TestDag { + type Node = TestNode; + + fn get(&self, id: ID) -> Option<Self::Node> { + self.nodes.get(&id).cloned() + } + + fn frontier(&self) -> &Frontiers { + &self.frontier + } + + fn vv(&self) -> &VersionVector { + &self.vv + } + + fn contains(&self, id: ID) -> bool { + self.nodes.contains_key(&id) + } + } + + fn node(peer: u64, counter: i32, lamport: Lamport, deps: Frontiers) -> TestNode { + TestNode { + id: ID::new(peer, counter), + lamport, + deps, + } + } + + #[test] + fn end_list_collects_dependency_leaves_from_all_start_frontiers() { + let a = node(1, 0, 0, Frontiers::default()); + let b = node(1, 1, 1, a.id.into()); + let c = node(2, 0, 2, a.id.into()); + let d = node(3, 0, 3, Frontiers::from([b.id, c.id])); + let e = node(4, 0, 4, c.id.into()); + let dag = TestDag::new( + vec![a.clone(), b.clone(), c.clone(), d.clone(), e.clone()], + Frontiers::from([d.id, e.id]), + ); + + let ends = get_end_list(&dag, &Frontiers::from([d.id, e.id])); + assert_eq!(ends, Frontiers::from(a.id)); + } + + #[test] + fn dfs_critical_versions_include_linear_cut_points() { + let root = node(1, 0, 0, Frontiers::default()); + let middle = node(1, 1, 1, root.id.into()); + let head = node(1, 2, 2, middle.id.into()); + let dag = TestDag::new( + vec![root.clone(), middle.clone(), head.clone()], + head.id.into(), + ); + + let critical = calc_critical_version_dfs(&dag, &head.id.into(), &root.id.into()); + assert_eq!(critical, vec![middle.id]); + } + + #[test] + fn dfs_critical_versions_exclude_diamond_branches_with_alternate_paths() { + let root = node(1, 0, 0, Frontiers::default()); + let left = node(2, 0, 1, root.id.into()); + let right = node(3, 0, 2, root.id.into()); + let merge = node(4, 0, 3, Frontiers::from([left.id, right.id])); + let dag = TestDag::new( + vec![root.clone(), left.clone(), right.clone(), merge.clone()], + merge.id.into(), + ); + + let critical = calc_critical_version_dfs(&dag, &merge.id.into(), &root.id.into()); + assert!(critical.is_empty()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{ + cmp::Ordering, + collections::{HashMap, HashSet}, + sync::Arc, + }; + + use crate::{ + change::Lamport, + id::{Counter, PeerID}, + span::{HasId, HasLamport}, + }; + use rle::{HasLength, Sliceable}; + + #[derive(Debug, Clone, PartialEq, Eq)] + struct TestNode { + id: ID, + lamport: Lamport, + len: usize, + deps: Arc<Frontiers>, + } + + impl TestNode { + fn new(id: ID, lamport: Lamport, deps: Frontiers) -> Self { + Self { + id, + lamport, + len: 1, + deps: Arc::new(deps), + } + } + } + + impl DagNode for TestNode { + fn deps(&self) -> &Frontiers { + &self.deps + } + } + + impl Sliceable for TestNode { + fn slice(&self, _from: usize, _to: usize) -> Self { + self.clone() + } + } + + impl HasLamport for TestNode { + fn lamport(&self) -> Lamport { + self.lamport + } + } + + impl HasId for TestNode { + fn id_start(&self) -> ID { + self.id + } + } + + impl HasLength for TestNode { + fn content_len(&self) -> usize { + self.len + } + } + + #[derive(Debug)] + struct TestDag { + nodes: HashMap<PeerID, Vec<TestNode>>, + version_vec: crate::version::VersionVector, + } + + impl TestDag { + fn new(nodes: Vec<TestNode>) -> Self { + let mut map: HashMap<PeerID, Vec<TestNode>> = HashMap::new(); + let mut vv = crate::version::VersionVector::new(); + for node in nodes { + vv.insert(node.id.peer, node.id.counter + node.len as Counter); + map.entry(node.id.peer).or_default().push(node); + } + for nodes in map.values_mut() { + nodes.sort_by(|a, b| match a.id.counter.cmp(&b.id.counter) { + Ordering::Equal => a.len.cmp(&b.len), + other => other, + }); + } + Self { + nodes: map, + version_vec: vv, + } + } + } + + impl Dag for TestDag { + type Node = TestNode; + + fn get(&self, id: ID) -> Option<Self::Node> { + let arr = self.nodes.get(&id.peer)?; + arr.binary_search_by(|node| { + if node.id.counter > id.counter { + Ordering::Greater + } else if node.id.counter + node.len as i32 <= id.counter { + Ordering::Less + } else { + Ordering::Equal + } + }) + .ok() + .map(|idx| arr[idx].clone()) + } + + fn frontier(&self) -> &Frontiers { + panic!("frontier is not used in dfs tests") + } + + fn vv(&self) -> &crate::version::VersionVector { + &self.version_vec + } + + fn contains(&self, id: ID) -> bool { + self.version_vec.includes_id(id) + } + } + + fn id(peer: PeerID, counter: Counter) -> ID { + ID::new(peer, counter) + } + + fn frontier(ids: &[ID]) -> Frontiers { + let mut frontier = Frontiers::new(); + for id in ids { + frontier.push(*id); + } + frontier + } + + fn as_set(ids: Vec<ID>) -> HashSet<ID> { + ids.into_iter().collect() + } + + #[test] + fn get_end_list_collects_all_leaf_nodes_reachable_from_start() { + let graph = TestDag::new(vec![ + TestNode::new(id(1, 0), 10, frontier(&[id(2, 0), id(3, 0)])), + TestNode::new(id(2, 0), 7, Frontiers::new()), + TestNode::new(id(3, 0), 8, Frontiers::new()), + ]); + + let ends = get_end_list(&graph, &frontier(&[id(1, 0)])); + + assert_eq!(ends.len(), 2); + assert!(ends.contains(&id(2, 0))); + assert!(ends.contains(&id(3, 0))); + assert!(!ends.contains(&id(1, 0))); + } + + #[test] + fn calc_critical_version_dfs_returns_non_start_nodes_when_no_end_is_present() { + let graph = TestDag::new(vec![ + TestNode::new(id(1, 0), 10, frontier(&[id(2, 0), id(3, 0)])), + TestNode::new(id(2, 0), 7, Frontiers::new()), + TestNode::new(id(3, 0), 8, Frontiers::new()), + ]); + + let result = calc_critical_version_dfs(&graph, &frontier(&[id(1, 0)]), &Frontiers::new()); + + assert_eq!(as_set(result), as_set(vec![id(2, 0), id(3, 0)])); + } + + #[test] + fn calc_critical_version_dfs_skips_candidates_when_an_end_is_on_every_start_path() { + let graph = TestDag::new(vec![ + TestNode::new(id(1, 0), 10, frontier(&[id(2, 0), id(3, 0)])), + TestNode::new(id(2, 0), 7, Frontiers::new()), + TestNode::new(id(3, 0), 8, Frontiers::new()), + ]); + + let result = + calc_critical_version_dfs(&graph, &frontier(&[id(1, 0)]), &frontier(&[id(2, 0)])); + + assert!(result.is_empty()); + } +} diff --git a/vendor/loro-internal/src/allocation/mod.rs b/vendor/loro-internal/src/allocation/mod.rs new file mode 100644 index 0000000..be34ae5 --- /dev/null +++ b/vendor/loro-internal/src/allocation/mod.rs @@ -0,0 +1,10 @@ +#![allow(dead_code)] +#![allow(unused)] + +mod bfs; +pub(crate) use bfs::calc_critical_version_bfs as calc_critical_version; + +// Only for testing +mod dfs; +pub(crate) use dfs::calc_critical_version_dfs; +pub(crate) use dfs::get_end_list; diff --git a/vendor/loro-internal/src/arena.rs b/vendor/loro-internal/src/arena.rs new file mode 100644 index 0000000..90f3022 --- /dev/null +++ b/vendor/loro-internal/src/arena.rs @@ -0,0 +1,1037 @@ +mod str_arena; +use self::str_arena::{StrArena, StrArenaCheckpoint}; +use crate::sync::{Mutex, MutexGuard, RwLock, RwLockWriteGuard}; +use crate::{ + change::Lamport, + container::{ + idx::ContainerIdx, + list::list_op::{InnerListOp, ListOp}, + map::MapSet, + ContainerID, + }, + id::Counter, + op::{InnerContent, ListSlice, Op, RawOp, RawOpContent, ValueSlice}, +}; +use append_only_bytes::BytesSlice; +use loro_common::{PeerID, ID}; +use rustc_hash::FxHashMap; +use std::fmt; +use std::{ + num::NonZeroU16, + ops::{Range, RangeBounds}, + sync::Arc, +}; + +pub(crate) struct LoadAllFlag; +type ParentResolver = dyn Fn(ContainerID) -> Option<ContainerID> + Send + Sync + 'static; +/// Loads the change holding the op with the given ID, if the op log has it. Parsing a change +/// registers the parent link of every container its ops create, and a normal container's ID is +/// the ID of the op that created it. It answers [`CreatorOp::Corrupt`] if the op log has the +/// change but cannot parse it. See `context/arena-parent-links.md`. +type CreatorResolver = dyn Fn(&SharedArena, ID) -> CreatorOp + Send + Sync + 'static; + +/// What the op log's history knows about an op ID, answered by the [`CreatorResolver`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum CreatorOp { + /// The change holding the op is parsed, so the parent of every container the op creates + /// is registered. + Loaded, + /// The history has no op with this ID: it was not received or committed yet, or it is + /// before the shallow root. + Absent, + /// A change block holds the op but cannot be decoded or parsed, so nothing is known about + /// the containers it creates. The op log records the block and reports it from the next + /// fallible entry point (import, export, checkout); the lookup itself answers like + /// `Absent` instead of panicking under the state lock. + Corrupt, +} + +#[derive(Default)] +struct ArenaContainers { + container_idx_to_id: Vec<ContainerID>, + /// Cached container depth. `None` means unknown or waiting on an unknown parent depth. + /// Use `get_depth()` for authoritative reads; direct access is only a cache fast path. + depth: Vec<Option<NonZeroU16>>, + container_id_to_idx: FxHashMap<ContainerID, ContainerIdx>, + /// The parent of each container. + parents: FxHashMap<ContainerIdx, Option<ContainerIdx>>, + /// All retention roots: top-level user roots **and** mergeable cids. Used by + /// alive-container / shallow-snapshot retention walks that must see both. + root_c_idx: Vec<ContainerIdx>, + /// Subset of `root_c_idx` containing only top-level (non-mergeable) roots. This is the + /// list user-facing APIs enumerate (`preferred_root_containers`, `get_value`, + /// `get_deep_value`, jsonpath, ...). Keeping it pre-filtered means those paths do + /// not pay a per-mergeable `is_mergeable()` parse on every call. + top_level_root_c_idx: Vec<ContainerIdx>, + /// Optional resolver used when querying parent for a container that has not been registered yet. + /// If set, `get_parent` will try this resolver to lazily fetch and register the parent. + /// + /// Locking: the resolver may read the state KV store. Code that loads from KV must snapshot + /// KV data and release the KV lock before taking the arena lock. + parent_resolver: Option<Arc<ParentResolver>>, + /// Set by the op log. Used after `parent_resolver` when a container's parent is still + /// unknown, e.g. the meta of a tree node that was never alive in a document loaded from a + /// snapshot, whose change blocks are parsed lazily. + /// + /// Locking: it takes the change store's locks and parses changes, which registers + /// containers in this arena, so it must be called without holding the arena lock. It runs + /// without the op log lock; see `ChangeStore::creator_resolver`. + creator_resolver: Option<Arc<CreatorResolver>>, +} + +#[derive(Default)] +struct InnerSharedArena { + // Container metadata is a single consistency domain. Keep it under one + // mutex so container id/index/parent/depth updates cannot acquire locks in + // inconsistent orders. + containers: RwLock<ArenaContainers>, + str: Arc<Mutex<StrArena>>, +} + +impl fmt::Debug for InnerSharedArena { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("InnerSharedArena") + .field("containers", &"<Mutex<_>>") + .field("str", &"<Arc<Mutex<_>>>") + .finish() + } +} + +/// This is shared between [OpLog] and [AppState]. +/// +#[derive(Debug, Clone)] +pub struct SharedArena { + inner: Arc<InnerSharedArena>, +} + +pub(crate) struct SharedArenaRollback { + container_len: usize, + str: StrArenaCheckpoint, +} + +/// How far the arena reached when something that refers into it was built, e.g. a parsed +/// change block: it can only refer to containers and text allocated before. +#[derive(Debug, Clone, Copy, Default)] +pub(crate) struct ArenaExtent { + containers: usize, + str_bytes: usize, +} + +impl SharedArenaRollback { + /// Whether rolling back to this checkpoint keeps everything within `extent`. + pub(crate) fn keeps(&self, extent: ArenaExtent) -> bool { + extent.containers <= self.container_len && extent.str_bytes <= self.str.bytes_len() + } +} + +#[derive(Debug)] +pub struct StrAllocResult { + /// unicode start + pub start: usize, + /// unicode end + pub end: usize, +} + +impl ArenaContainers { + /// Add a freshly-registered cid to the retention-root tracking vectors. + /// + /// Centralizes the `root_c_idx ⊇ top_level_root_c_idx` invariant: `root_c_idx` is the set of + /// retention roots (top-level user roots **and** mergeable cids) that seed the alive-walk for + /// shallow snapshot; `top_level_root_c_idx` is the user-visible subset enumerated by + /// `preferred_root_containers` etc. Every push to either vector should go through this method, + /// so the invariant is maintained by construction rather than by remembering to push to two + /// vectors at every call site. + fn push_root(&mut self, idx: ContainerIdx, is_mergeable: bool) { + self.root_c_idx.push(idx); + if !is_mergeable { + self.top_level_root_c_idx.push(idx); + } + } + + fn register_container(&mut self, id: &ContainerID) -> ContainerIdx { + if let Some(&idx) = self.container_id_to_idx.get(id) { + return idx; + } + + let idx = self.container_idx_to_id.len(); + self.container_idx_to_id.push(id.clone()); + let idx = ContainerIdx::from_index_and_type(idx as u32, id.container_type()); + self.container_id_to_idx.insert(id.clone(), idx); + // Resolve the cid's kind once. `is_mergeable` is non-trivial for mergeable names, + // so we avoid calling it twice on the same id. + let mergeable_parts = if id.is_root() { + id.parse_mergeable() + } else { + None + }; + match (id.is_root(), mergeable_parts) { + (true, None) => { + self.push_root(idx, false); + self.parents.insert(idx, None); + self.depth.push(NonZeroU16::new(1)); + } + (true, Some((parent_id, _key, _kind))) => { + // Mergeable Roots are retention roots AND logical children. Push to `root_c_idx` + // so shallow snapshot's `retain_keys` does not GC the loser of a concurrent-kind + // conflict (whose state is reachable only by its deterministic cid, not through + // the parent marker); then `set_parent` for path/event resolution. They are + // deliberately absent from `top_level_root_c_idx` so user-facing root + // enumeration does not have to filter them out. + self.push_root(idx, true); + self.depth.push(None); + let parent_idx = self.register_container(&parent_id); + self.set_parent(idx, Some(parent_idx)); + } + (false, _) => { + self.depth.push(None); + } + } + idx + } + + fn set_parent(&mut self, child: ContainerIdx, parent: Option<ContainerIdx>) { + self.parents.insert(child, parent); + + match parent { + Some(p) => { + // Keep parent linking side-effect free. Calling `get_depth()` here may invoke the + // lazy parent resolver, which can acquire the state KV lock. Import/load paths may + // be assembling parent edges from KV snapshots, so resolving depth here would make + // arena -> KV and KV -> arena lock orders coexist. + if let Some(d) = self.depth[p.to_index() as usize] { + self.depth[child.to_index() as usize] = NonZeroU16::new(d.get() + 1); + } else { + self.depth[child.to_index() as usize] = None; + } + } + None => { + self.depth[child.to_index() as usize] = NonZeroU16::new(1); + } + } + } + + fn get_depth(&mut self, target: ContainerIdx) -> Option<NonZeroU16> { + if let Some(d) = self.depth[target.to_index() as usize] { + return Some(d); + } + + let parent: Option<ContainerIdx> = if let Some(p) = self.parents.get(&target) { + *p + } else { + let id = self + .container_idx_to_id + .get(target.to_index() as usize) + .unwrap() + .clone(); + if id.is_root() && !id.is_mergeable() { + None + } else { + // Mergeable Roots get registered via the main `register_container` path, which + // already wires their parent edge — they should never reach here with a missing + // `parents` entry. But for ordinary children whose parent isn't in the arena + // yet, fall back to the resolver. + let resolver = self.parent_resolver.clone()?; + let parent_id = resolver(id)?; + // Route through `register_container` so a freshly-discovered parent (especially + // a mergeable cid) lands in `root_c_idx`, gets its own parent edge wired up, + // and has `parents` initialized — instead of being half-registered with just + // `idx_to_id` / `id_to_idx` / `depth` and silently missing from retention walks. + let parent_idx = + if let Some(idx) = self.container_id_to_idx.get(&parent_id).copied() { + // Already in the arena. For a top-level root that was hand-registered + // somewhere else without a `parents` entry, ensure it has one. + if parent_id.is_root() && !parent_id.is_mergeable() { + self.parents.entry(idx).or_insert(None); + if self.depth[idx.to_index() as usize].is_none() { + self.depth[idx.to_index() as usize] = NonZeroU16::new(1); + } + } + idx + } else { + self.register_container(&parent_id) + }; + + Some(parent_idx) + } + }; + + let d = match parent { + Some(p) => NonZeroU16::new(self.get_depth(p)?.get() + 1), + None => NonZeroU16::new(1), + }; + self.depth[target.to_index() as usize] = d; + d + } + + fn container_id(&self, idx: ContainerIdx) -> Option<ContainerID> { + self.container_idx_to_id + .get(idx.to_index() as usize) + .cloned() + } +} + +pub(crate) struct ArenaGuards<'a> { + containers: RwLockWriteGuard<'a, ArenaContainers>, +} + +impl ArenaGuards<'_> { + pub fn register_container(&mut self, id: &ContainerID) -> ContainerIdx { + self.containers.register_container(id) + } + + pub fn set_parent(&mut self, child: ContainerIdx, parent: Option<ContainerIdx>) { + self.containers.set_parent(child, parent); + } +} + +impl SharedArena { + #[allow(clippy::new_without_default)] + pub fn new() -> Self { + Self { + inner: Arc::new(InnerSharedArena::default()), + } + } + + pub fn fork(&self) -> Self { + Self { + inner: Arc::new(InnerSharedArena { + containers: RwLock::new({ + let containers = self.inner.containers.read(); + ArenaContainers { + container_idx_to_id: containers.container_idx_to_id.clone(), + depth: containers.depth.clone(), + container_id_to_idx: containers.container_id_to_idx.clone(), + parents: containers.parents.clone(), + root_c_idx: containers.root_c_idx.clone(), + top_level_root_c_idx: containers.top_level_root_c_idx.clone(), + parent_resolver: containers.parent_resolver.clone(), + // It reads the source document's op log. + creator_resolver: None, + } + }), + str: self.inner.str.clone(), + }), + } + } + + /// See [`ArenaExtent`]. + pub(crate) fn extent(&self) -> ArenaExtent { + ArenaExtent { + containers: self.inner.containers.read().container_idx_to_id.len(), + str_bytes: self.inner.str.lock().bytes_len(), + } + } + + pub(crate) fn checkpoint_for_rollback(&self) -> SharedArenaRollback { + let containers = self.inner.containers.read(); + let container_len = containers.container_idx_to_id.len(); + drop(containers); + let str = self.inner.str.lock().checkpoint(); + SharedArenaRollback { container_len, str } + } + + /// Call it through the op log's change store (`ChangeStore::rollback_arena` and friends), + /// which does it under the lock the creator resolver parses under and drops the parsed + /// changes that may refer to what this removes. See `context/arena-parent-links.md`. + /// + /// Container indices are never freed: a container registered since the checkpoint keeps + /// its index. `DocState` (store entries, caches) and handlers on other threads may hold + /// it, and a new container that reused it would inherit their state (loro-dev/loro#1164). + /// What the failed import may have told the arena about those containers is dropped: the + /// parent links of normal containers registered since the checkpoint, and links to them. + /// The resolvers find the links again from the kept history or the state. Roots keep their + /// links, which their IDs determine. Text is truncated; only parsed changes refer to it. See `context/failed-import-arena-indices.md`. + pub(crate) fn rollback(&self, checkpoint: SharedArenaRollback) { + { + let mut guard = self.inner.containers.write(); + let containers = &mut *guard; + let container_len = checkpoint.container_len; + if containers.container_idx_to_id.len() > container_len { + let ids = &containers.container_idx_to_id; + containers.parents.retain(|child, parent| { + let child_is_new = (child.to_index() as usize) >= container_len; + let parent_is_new = + parent.is_some_and(|p| (p.to_index() as usize) >= container_len); + !((child_is_new || parent_is_new) && ids[child.to_index() as usize].is_normal()) + }); + // A cached depth may have been computed through a dropped link, also for the + // descendants of a container registered before the checkpoint. Roots and + // links that are kept give the same depth again. + containers.depth.fill(None); + } + } + + self.inner.str.lock().rollback(checkpoint.str); + } + + pub(crate) fn with_guards(&self, f: impl FnOnce(&mut ArenaGuards)) { + let mut guards = self.get_arena_guards(); + f(&mut guards); + } + + fn get_arena_guards(&self) -> ArenaGuards<'_> { + ArenaGuards { + containers: self.inner.containers.write(), + } + } + + pub fn register_container(&self, id: &ContainerID) -> ContainerIdx { + self.inner.containers.write().register_container(id) + } + + pub fn get_container_id(&self, idx: ContainerIdx) -> Option<ContainerID> { + self.inner.containers.read().container_id(idx) + } + + /// Fast map from `ContainerID` to `ContainerIdx` for containers already registered + /// in the arena. + /// + /// Important: This is not an existence check. Absence here does not imply that a + /// container does not exist, since registration can be lazy and containers may + /// be persisted only in the state KV store until first use. + /// + /// For existence-aware lookup that consults persisted state and performs lazy + /// registration, prefer `DocState::resolve_idx`. + pub fn id_to_idx(&self, id: &ContainerID) -> Option<ContainerIdx> { + self.inner + .containers + .read() + .container_id_to_idx + .get(id) + .copied() + } + + #[inline] + pub fn idx_to_id(&self, id: ContainerIdx) -> Option<ContainerID> { + self.inner.containers.read().container_id(id) + } + + #[inline] + pub fn with_idx_to_id<R>(&self, f: impl FnOnce(&Vec<ContainerID>) -> R) -> R { + let containers = self.inner.containers.read(); + f(&containers.container_idx_to_id) + } + + pub fn alloc_str(&self, str: &str) -> StrAllocResult { + let mut text_lock = self.inner.str.lock(); + _alloc_str(&mut text_lock, str) + } + + /// return slice and unicode index + pub fn alloc_str_with_slice(&self, str: &str) -> (BytesSlice, StrAllocResult) { + let mut text_lock = self.inner.str.lock(); + _alloc_str_with_slice(&mut text_lock, str) + } + + /// alloc str without extra info + pub fn alloc_str_fast(&self, bytes: &[u8]) { + let mut text_lock = self.inner.str.lock(); + text_lock.alloc(std::str::from_utf8(bytes).unwrap()); + } + + /// Bytes held by the string arena; it only ever grows. + #[cfg(test)] + pub(crate) fn str_len_bytes(&self) -> usize { + self.inner.str.lock().len_bytes() + } + + #[inline] + pub fn utf16_len(&self) -> usize { + self.inner.str.lock().len_utf16() + } + + #[inline] + pub fn set_parent(&self, child: ContainerIdx, parent: Option<ContainerIdx>) { + self.inner.containers.write().set_parent(child, parent); + } + + /// Forget the parent links of the normal containers whose creating op is `peer`'s op at + /// `start_counter` or later, after such ops were discarded (a rolled back local + /// transaction). The next op at that id may create the container under another parent, + /// and until then the container has no parent, so it reads as deleted without being + /// cached as deleted. The registrations stay: other code may hold their indices. The + /// caller removes their state. See `context/apply-diff-atomicity.md`. + pub(crate) fn forget_parents_of_discarded_ops(&self, peer: PeerID, start_counter: Counter) { + let mut containers = self.inner.containers.write(); + let discarded: Vec<ContainerIdx> = containers + .container_idx_to_id + .iter() + .enumerate() + .filter(|(_, id)| { + matches!(id, ContainerID::Normal { peer: p, counter, .. } + if *p == peer && *counter >= start_counter) + }) + .map(|(i, id)| ContainerIdx::from_index_and_type(i as u32, id.container_type())) + .collect(); + for idx in discarded { + containers.parents.remove(&idx); + containers.depth[idx.to_index() as usize] = None; + } + } + + pub fn log_hierarchy(&self) { + if cfg!(debug_assertions) { + let containers = self.inner.containers.read(); + for (c, p) in containers.parents.iter() { + tracing::info!( + "container {:?} {:?} {:?}", + c, + containers.container_id(*c), + p.and_then(|x| containers.container_id(x)) + ); + } + } + } + + pub fn log_all_containers(&self) { + let containers = self.inner.containers.read(); + containers.container_id_to_idx.iter().for_each(|(id, idx)| { + tracing::info!("container {:?} {:?}", id, idx); + }); + containers + .container_idx_to_id + .iter() + .enumerate() + .for_each(|(i, id)| { + tracing::info!("container {} {:?}", i, id); + }); + } + + /// The parent of `child`, or `None` for a top-level root. + /// + /// Also `None` for a normal container that no op in the history creates (an ID from the + /// user that is not a container, an op not received yet, or a container that is not in + /// the state of a shallow document and whose creating op was trimmed): no path leads to + /// it, so it is treated like a container whose parent no longer holds it. A history that + /// has the op but cannot parse it panics instead (see [`CreatorResolver`]). + pub fn get_parent(&self, child: ContainerIdx) -> Option<ContainerIdx> { + match self.resolve_parent(child) { + Some(parent) => parent, + None => { + assert!( + self.inner.containers.read().creator_resolver.is_some(), + "InternalError: Parent is not registered" + ); + None + } + } + } + + /// Finds and registers `child`'s parent edge: the registered edge, else the state KV + /// (`parent_resolver`), else the change that created it (`creator_resolver`). + /// + /// Returns `Some(parent)` when the edge is known (`parent` is `None` for a top-level root) + /// and `None` when no source knows the container. + fn resolve_parent(&self, child: ContainerIdx) -> Option<Option<ContainerIdx>> { + let (child_id, resolver, creator_resolver) = { + let containers = self.inner.containers.read(); + let child_id = containers.container_id(child).unwrap(); + if child_id.is_root() && !child_id.is_mergeable() { + // TODO: PERF: we can speed this up by use a special bit in ContainerIdx to indicate + // whether the target is a root container + return Some(None); + } + + // Try fast path first + if let Some(p) = containers.parents.get(&child).copied() { + return Some(p); + } + + // Fallback: try to resolve parent lazily via the resolvers if provided. + ( + child_id, + containers.parent_resolver.clone(), + containers.creator_resolver.clone(), + ) + }; + if let Some(resolver) = resolver { + if let Some(parent_id) = resolver(child_id.clone()) { + let parent_idx = self.register_container(&parent_id); + self.set_parent(child, Some(parent_idx)); + return Some(Some(parent_idx)); + } + } + + if let (Some(resolver), ContainerID::Normal { peer, counter, .. }) = + (creator_resolver, &child_id) + { + return match resolver(self, ID::new(*peer, *counter)) { + // Registered unless the op does not create this container. + CreatorOp::Loaded => self.get_registered_parent(child), + CreatorOp::Absent | CreatorOp::Corrupt => None, + }; + } + + None + } + + /// The index of a normal container that is not registered yet but that an op in the + /// history creates. Loading that op's change registers the container and its parent. + pub(crate) fn find_created_container(&self, id: &ContainerID) -> Option<ContainerIdx> { + if let Some(idx) = self.id_to_idx(id) { + return Some(idx); + } + let ContainerID::Normal { peer, counter, .. } = id else { + return None; + }; + let resolver = self.inner.containers.read().creator_resolver.clone()?; + match resolver(self, ID::new(*peer, *counter)) { + CreatorOp::Loaded => self.id_to_idx(id), + CreatorOp::Absent | CreatorOp::Corrupt => None, + } + } + + /// Return the parent edge already stored in the arena without invoking the lazy resolver. + /// + /// The outer `Option` distinguishes an unregistered edge from a registered root edge. + pub(crate) fn get_registered_parent( + &self, + child: ContainerIdx, + ) -> Option<Option<ContainerIdx>> { + self.inner.containers.read().parents.get(&child).copied() + } + + /// Call `f` on each ancestor of `container`, including `container` itself. + /// + /// f(ContainerIdx, is_first) + pub fn with_ancestors(&self, container: ContainerIdx, mut f: impl FnMut(ContainerIdx, bool)) { + let mut container = Some(container); + let mut is_first = true; + while let Some(c) = container { + f(c, is_first); + is_first = false; + container = self.get_parent(c) + } + } + + #[inline] + pub fn slice_by_unicode(&self, range: impl RangeBounds<usize>) -> BytesSlice { + self.inner.str.lock().slice_by_unicode(range) + } + + #[inline] + pub fn slice_by_utf8(&self, range: impl RangeBounds<usize>) -> BytesSlice { + self.inner.str.lock().slice_bytes(range) + } + + #[inline] + pub fn slice_str_by_unicode_range(&self, range: Range<usize>) -> String { + let mut s = self.inner.str.lock(); + let s: &mut StrArena = &mut s; + let mut ans = String::with_capacity(range.len()); + ans.push_str(s.slice_str_by_unicode(range)); + ans + } + + #[inline] + pub fn with_text_slice(&self, range: Range<usize>, mut f: impl FnMut(&str)) { + f(self.inner.str.lock().slice_str_by_unicode(range)) + } + + pub fn convert_single_op( + &self, + container: &ContainerID, + peer: PeerID, + counter: Counter, + lamport: Lamport, + content: RawOpContent, + ) -> Op { + let container = self.register_container(container); + self.inner_convert_op(content, peer, counter, lamport, container) + } + + pub fn can_import_snapshot(&self) -> bool { + self.inner.str.lock().is_empty() + } + + fn inner_convert_op( + &self, + content: RawOpContent<'_>, + _peer: PeerID, + counter: i32, + _lamport: Lamport, + container: ContainerIdx, + ) -> Op { + match content { + crate::op::RawOpContent::Map(MapSet { key, value }) => Op { + counter, + container, + content: crate::op::InnerContent::Map(MapSet { key, value }), + }, + crate::op::RawOpContent::List(list) => match list { + ListOp::Insert { slice, pos } => match slice { + ListSlice::RawData(values) => Op { + counter, + container, + content: crate::op::InnerContent::List(InnerListOp::Insert { + slice: ValueSlice::new(values.into_owned()), + pos, + }), + }, + ListSlice::RawStr { str, unicode_len } => { + let (slice, _) = self.alloc_str_with_slice(&str); + Op { + counter, + container, + content: crate::op::InnerContent::List(InnerListOp::InsertText { + slice, + unicode_len: unicode_len as u32, + pos: pos as u32, + }), + } + } + }, + ListOp::Delete(span) => Op { + counter, + container, + content: crate::op::InnerContent::List(InnerListOp::Delete(span)), + }, + ListOp::StyleStart { + start, + end, + info, + key, + value, + } => Op { + counter, + container, + content: InnerContent::List(InnerListOp::StyleStart { + start, + end, + key, + info, + value, + }), + }, + ListOp::StyleEnd => Op { + counter, + container, + content: InnerContent::List(InnerListOp::StyleEnd), + }, + ListOp::Move { + from, + to, + elem_id: from_id, + } => Op { + counter, + container, + content: InnerContent::List(InnerListOp::Move { + from, + to, + elem_id: from_id, + }), + }, + ListOp::Set { elem_id, value } => Op { + counter, + container, + content: InnerContent::List(InnerListOp::Set { elem_id, value }), + }, + }, + crate::op::RawOpContent::Tree(tree) => Op { + counter, + container, + content: crate::op::InnerContent::Tree(tree.clone()), + }, + #[cfg(feature = "counter")] + crate::op::RawOpContent::Counter(c) => Op { + counter, + container, + content: crate::op::InnerContent::Future(crate::op::FutureInnerContent::Counter(c)), + }, + crate::op::RawOpContent::Unknown { prop, value } => Op { + counter, + container, + content: crate::op::InnerContent::Future(crate::op::FutureInnerContent::Unknown { + prop, + value: Box::new(value), + }), + }, + } + } + + #[inline] + pub fn convert_raw_op(&self, op: &RawOp) -> Op { + self.inner_convert_op( + op.content.clone(), + op.id.peer, + op.id.counter, + op.lamport, + op.container, + ) + } + + #[inline] + pub fn export_containers(&self) -> Vec<ContainerID> { + self.inner.containers.read().container_idx_to_id.clone() + } + + pub fn export_parents(&self) -> Vec<Option<ContainerIdx>> { + let containers = self.inner.containers.read(); + containers + .container_idx_to_id + .iter() + .enumerate() + .map(|(x, id)| { + let idx = ContainerIdx::from_index_and_type(x as u32, id.container_type()); + let parent_idx = containers.parents.get(&idx)?; + *parent_idx + }) + .collect() + } + + /// Returns all the possible root containers of the docs + /// + /// We need to load all the cached kv in DocState before we can ensure all root contains are covered. + /// So we need the flag type here. + /// + /// This includes mergeable cids (which are also retention roots). Callers that only want + /// user-visible top-level roots should use [`Self::top_level_root_containers`]. + #[inline] + pub(crate) fn root_containers(&self, _f: LoadAllFlag) -> Vec<ContainerIdx> { + self.inner.containers.read().root_c_idx.clone() + } + + /// Returns only the user-visible top-level root containers (excludes mergeable cids). + /// + /// Used by `preferred_root_containers`, `get_value` / `get_deep_value`, jsonpath, etc. — + /// any path that enumerates the doc's top-level roots. Pre-filtering at registration time + /// keeps these calls O(top_level_roots) instead of O(top_level_roots + mergeable_cids). + #[inline] + pub(crate) fn top_level_root_containers(&self, _f: LoadAllFlag) -> Vec<ContainerIdx> { + self.inner.containers.read().top_level_root_c_idx.clone() + } + + // TODO: this can return a u16 directly now, since the depths are always valid + pub(crate) fn get_depth(&self, container: ContainerIdx) -> Option<NonZeroU16> { + if let Some(d) = self.inner.containers.read().depth[container.to_index() as usize] { + return Some(d); + } + + // `ArenaContainers::get_depth` runs under the arena lock, where the creator resolver + // cannot run, so resolve the missing parent links first. + let mut c = container; + // Every step goes one level up, and no valid chain is deeper than `u16::MAX`. + let mut steps = 0usize; + loop { + steps += 1; + assert!( + steps <= u16::MAX as usize + 1, + "InternalError: the parent links of {:?} form a cycle", + self.idx_to_id(container) + ); + { + let containers = self.inner.containers.read(); + if containers.depth[c.to_index() as usize].is_some() { + break; + } + match containers.parents.get(&c).copied() { + Some(Some(p)) => { + c = p; + continue; + } + Some(None) => break, + None => {} + } + } + match self.resolve_parent(c) { + Some(Some(p)) => c = p, + _ => break, + } + } + self.inner.containers.write().get_depth(container) + } +} + +fn _alloc_str_with_slice( + text_lock: &mut MutexGuard<'_, StrArena>, + str: &str, +) -> (BytesSlice, StrAllocResult) { + let start = text_lock.len_bytes(); + let ans = _alloc_str(text_lock, str); + (text_lock.slice_bytes(start..), ans) +} + +fn _alloc_str(text_lock: &mut MutexGuard<'_, StrArena>, str: &str) -> StrAllocResult { + let start = text_lock.len_unicode(); + text_lock.alloc(str); + StrAllocResult { + start, + end: text_lock.len_unicode(), + } +} + +fn _slice_str(range: Range<usize>, s: &mut StrArena) -> String { + let mut ans = String::with_capacity(range.len()); + ans.push_str(s.slice_str_by_unicode(range)); + ans +} + +impl SharedArena { + /// Register or clear a resolver to lazily determine a container's parent when missing. + /// + /// - The resolver receives the child `ContainerIdx` and returns an optional `ContainerID` of its parent. + /// - If the resolver returns `Some`, `SharedArena` will register the parent in the arena and link it. + /// - If the resolver is `None` or returns `None`, `get_parent` will panic for non-root containers as before. + pub fn set_parent_resolver<F>(&self, resolver: Option<F>) + where + F: Fn(ContainerID) -> Option<ContainerID> + Send + Sync + 'static, + { + self.inner.containers.write().parent_resolver = + resolver.map(|f| Arc::new(f) as Arc<ParentResolver>); + } + + /// Register the op log's [`CreatorResolver`]. See `creator_resolver` in `ArenaContainers`. + pub(crate) fn set_creator_resolver<F>(&self, resolver: F) + where + F: Fn(&SharedArena, ID) -> CreatorOp + Send + Sync + 'static, + { + self.inner.containers.write().creator_resolver = Some(Arc::new(resolver)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use loro_common::ContainerType; + use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }; + + /// When a non-mergeable child is registered, then later asks for its depth and the parent + /// resolver yields a mergeable cid, the mergeable parent must be registered through the + /// retention-root path (push to `root_c_idx`, recursively link its own parent) — exactly the + /// same way the main `register_container` path would handle a freshly-encountered mergeable + /// cid. Without this, shallow snapshot's alive-walk would silently GC the mergeable parent's + /// state. + #[test] + fn get_depth_resolver_registers_mergeable_parent_as_retention_root() { + let arena = SharedArena::new(); + + let top_root = ContainerID::new_root("state", ContainerType::Map); + let mergeable_parent = ContainerID::new_mergeable(&top_root, "profile", ContainerType::Map); + let child = ContainerID::new_normal(loro_common::ID::new(1, 0), ContainerType::List); + + let mergeable_parent_for_resolver = mergeable_parent.clone(); + let child_for_resolver = child.clone(); + arena.set_parent_resolver(Some(move |q: ContainerID| { + if q == child_for_resolver { + Some(mergeable_parent_for_resolver.clone()) + } else { + None + } + })); + + let child_idx = arena.register_container(&child); + let _ = arena.get_depth(child_idx); + + let flag = LoadAllFlag; + let mergeable_idx = arena + .id_to_idx(&mergeable_parent) + .expect("resolver should have registered the mergeable parent"); + assert!( + arena.root_containers(flag).contains(&mergeable_idx), + "mergeable parent discovered via resolver must be a retention root" + ); + + let flag = LoadAllFlag; + assert!( + !arena + .top_level_root_containers(flag) + .contains(&mergeable_idx), + "mergeable parent must not appear in user-facing top-level enumeration" + ); + + let flag = LoadAllFlag; + let top_root_idx = arena + .id_to_idx(&top_root) + .expect("mergeable parent's own grandparent must also be registered"); + assert!( + arena + .top_level_root_containers(flag) + .contains(&top_root_idx), + "the mergeable parent's grandparent (a top-level root) must be in the top-level list" + ); + } + + /// The creator resolver parses changes, which registers containers in the arena, so + /// `get_parent` and `get_depth` must call it without holding the arena lock. + #[test] + fn creator_resolver_runs_outside_the_arena_lock() { + let arena = SharedArena::new(); + let root = ContainerID::new_root("tree", ContainerType::Tree); + let meta = ContainerID::new_normal(ID::new(1, 3), ContainerType::Map); + let meta_for_resolver = meta.clone(); + arena.set_creator_resolver(move |arena: &SharedArena, id: ID| { + assert_eq!(id, ID::new(1, 3)); + // What parsing the change does: register the container and its parent. + let parent = arena.register_container(&root); + let child = arena.register_container(&meta_for_resolver); + arena.set_parent(child, Some(parent)); + CreatorOp::Loaded + }); + + let meta_idx = arena.register_container(&meta); + assert_eq!(arena.get_depth(meta_idx).map(|d| d.get()), Some(2)); + let root_idx = arena.id_to_idx(&ContainerID::new_root("tree", ContainerType::Tree)); + assert_eq!(arena.get_parent(meta_idx), root_idx); + } + + #[test] + fn a_container_that_no_op_creates_has_no_parent() { + for answer in [CreatorOp::Loaded, CreatorOp::Absent, CreatorOp::Corrupt] { + // `Loaded`: the op exists but creates something else. + let arena = SharedArena::new(); + arena.set_creator_resolver(move |_: &SharedArena, _: ID| answer); + let id = ContainerID::new_normal(ID::new(1, 3), ContainerType::Map); + let idx = arena.register_container(&id); + assert_eq!(arena.get_parent(idx), None); + assert_eq!(arena.get_depth(idx), None); + let missing = ContainerID::new_normal(ID::new(1, 4), ContainerType::Text); + assert_eq!(arena.find_created_container(&missing), None); + } + } + + #[test] + #[should_panic(expected = "form a cycle")] + fn a_parent_cycle_fails_fast() { + let arena = SharedArena::new(); + let a = + arena.register_container(&ContainerID::new_normal(ID::new(1, 0), ContainerType::Map)); + let b = + arena.register_container(&ContainerID::new_normal(ID::new(1, 1), ContainerType::Map)); + arena.set_parent(a, Some(b)); + arena.set_parent(b, Some(a)); + arena.get_depth(a); + } + + /// Without an op log to ask, an unknown parent is still an internal error. + #[test] + #[should_panic(expected = "Parent is not registered")] + fn unknown_parent_without_a_creator_resolver_panics() { + let arena = SharedArena::new(); + let idx = + arena.register_container(&ContainerID::new_normal(ID::new(1, 3), ContainerType::Map)); + arena.get_parent(idx); + } + + #[test] + fn set_parent_does_not_resolve_missing_parent_depth() { + let arena = SharedArena::new(); + let parent = ContainerID::new_normal(loro_common::ID::new(1, 0), ContainerType::Map); + let child = ContainerID::new_mergeable(&parent, "field", ContainerType::Text); + let resolver_called = Arc::new(AtomicBool::new(false)); + let called = resolver_called.clone(); + arena.set_parent_resolver(Some(move |_| { + called.store(true, Ordering::SeqCst); + None + })); + + arena.register_container(&child); + + assert!( + !resolver_called.load(Ordering::SeqCst), + "registering a mergeable child must not invoke the lazy parent resolver" + ); + } +} diff --git a/vendor/loro-internal/src/arena/str_arena.rs b/vendor/loro-internal/src/arena/str_arena.rs new file mode 100644 index 0000000..e5bc63a --- /dev/null +++ b/vendor/loro-internal/src/arena/str_arena.rs @@ -0,0 +1,253 @@ +use std::ops::{Bound, RangeBounds}; + +use append_only_bytes::{AppendOnlyBytes, BytesSlice}; + +use crate::container::richtext::richtext_state::unicode_to_utf8_index; +const INDEX_INTERVAL: u32 = 128; + +#[derive(Default, Debug, Clone)] +pub(crate) struct StrArena { + bytes: AppendOnlyBytes, + unicode_indexes: Vec<Index>, + len: Index, +} + +#[derive(Debug, Clone)] +pub(crate) struct StrArenaCheckpoint { + bytes_len: usize, + unicode_indexes_len: usize, + len: Index, +} + +#[derive(Debug, Default, Clone, Copy)] +struct Index { + bytes: u32, + utf16: u32, + unicode: u32, +} + +impl StrArenaCheckpoint { + pub(super) fn bytes_len(&self) -> usize { + self.bytes_len + } +} + +impl StrArena { + pub(super) fn bytes_len(&self) -> usize { + self.bytes.len() + } + + #[inline] + pub fn is_empty(&self) -> bool { + self.len.bytes == 0 + } + + #[inline] + #[allow(dead_code)] + pub fn len_bytes(&self) -> usize { + self.len.bytes as usize + } + + #[inline] + pub fn len_utf16(&self) -> usize { + self.len.utf16 as usize + } + + #[inline] + pub fn len_unicode(&self) -> usize { + self.len.unicode as usize + } + + pub fn alloc(&mut self, input: &str) { + // Pieces of a bit over INDEX_INTERVAL bytes, measured by lead-byte counts. + // (project_note patch: was a per-char walk) + let b = input.as_bytes(); + let mut start = 0; + while start < b.len() { + let mut end = (start + INDEX_INTERVAL as usize + 1).min(b.len()); + while !input.is_char_boundary(end) { + end += 1; + } + let (unicode, utf16) = crate::utils::utf16::str_lens(&b[start..end]); + self._alloc(&input[start..end], utf16 as u32, unicode as i32); + start = end; + } + } + + fn _alloc(&mut self, input: &str, utf16: u32, unicode_len: i32) { + let s = input; + self.len.bytes += s.len() as u32; + self.len.utf16 += utf16; + self.len.unicode += unicode_len as u32; + self.bytes.push_str(s); + let cur_len = self.len; + + let index = &mut self.unicode_indexes; + if index.is_empty() { + index.push(Index { + bytes: 0, + utf16: 0, + unicode: 0, + }); + } + + let last = index.last().unwrap(); + if cur_len.bytes - last.bytes > INDEX_INTERVAL { + self.unicode_indexes.push(cur_len); + } + } + + #[inline] + pub fn slice_by_unicode(&mut self, range: impl RangeBounds<usize>) -> BytesSlice { + let (start, end) = self.unicode_range_to_utf8_range(range); + self.bytes.slice(start..end) + } + + #[inline] + pub fn slice_str_by_unicode(&mut self, range: impl RangeBounds<usize>) -> &str { + let (start, end) = self.unicode_range_to_utf8_range(range); + // SAFETY: we know that the range is valid + unsafe { std::str::from_utf8_unchecked(&self.bytes[start..end]) } + } + + fn unicode_range_to_utf8_range(&mut self, range: impl RangeBounds<usize>) -> (usize, usize) { + if self.is_empty() { + return (0, 0); + } + + let start = match range.start_bound() { + Bound::Included(&i) => { + unicode_to_byte_index(&self.unicode_indexes, i as u32, &self.bytes) + } + Bound::Excluded(&_i) => unreachable!(), + Bound::Unbounded => 0, + }; + + let end = match range.end_bound() { + Bound::Included(&i) => { + unicode_to_byte_index(&self.unicode_indexes, i as u32 + 1, &self.bytes) + } + Bound::Excluded(&i) => { + unicode_to_byte_index(&self.unicode_indexes, i as u32, &self.bytes) + } + Bound::Unbounded => self.len.bytes as usize, + }; + + (start, end) + } + + #[inline] + pub fn slice_bytes(&self, range: impl RangeBounds<usize>) -> BytesSlice { + self.bytes.slice(range) + } + + #[inline] + pub(crate) fn checkpoint(&self) -> StrArenaCheckpoint { + StrArenaCheckpoint { + bytes_len: self.bytes.len(), + unicode_indexes_len: self.unicode_indexes.len(), + len: self.len, + } + } + + pub(crate) fn rollback(&mut self, checkpoint: StrArenaCheckpoint) { + if checkpoint.bytes_len == 0 { + *self = Self::default(); + return; + } + + if checkpoint.bytes_len < self.bytes.len() { + let mut bytes = AppendOnlyBytes::with_capacity(checkpoint.bytes_len); + bytes.push_slice(&self.bytes[..checkpoint.bytes_len]); + self.bytes = bytes; + } + self.unicode_indexes + .truncate(checkpoint.unicode_indexes_len); + self.len = checkpoint.len; + } +} + +fn unicode_to_byte_index(index: &[Index], unicode_index: u32, bytes: &AppendOnlyBytes) -> usize { + let i = match index.binary_search_by_key(&unicode_index, |x| x.unicode) { + Ok(i) => i, + Err(i) => i - 1, + }; + + let index = index[i]; + if index.unicode == unicode_index { + return index.bytes as usize; + } + + // SAFETY: we know that the index must be valid, because we record and calculate the valid index + let s = unsafe { std::str::from_utf8_unchecked(&bytes[index.bytes as usize..]) }; + unicode_to_utf8_index(s, (unicode_index - index.unicode) as usize).unwrap() + + index.bytes as usize +} + +#[cfg(test)] +mod test { + use std::ops::Deref; + + use super::*; + + #[test] + fn test() { + let mut arena = StrArena::default(); + arena.alloc("Hello"); + let slice = arena.slice_by_unicode(0..5); + assert_eq!(slice.deref(), b"Hello"); + arena.alloc("World"); + let slice = arena.slice_by_unicode(5..10); + assert_eq!(slice.deref(), b"World"); + } + + #[test] + fn parse_unicode_correctly() { + let mut arena = StrArena::default(); + arena.alloc("Hello"); + arena.alloc("World"); + arena.alloc("你好"); + arena.alloc("世界"); + let slice = arena.slice_by_unicode(0..4); + assert_eq!(slice.deref(), b"Hell"); + + let slice = arena.slice_by_unicode(4..8); + assert_eq!(slice.deref(), b"oWor"); + + let slice = arena.slice_by_unicode(8..10); + assert_eq!(slice.deref(), b"ld"); + + let slice = arena.slice_by_unicode(10..12); + assert_eq!(slice.deref(), "你好".as_bytes()); + + let slice = arena.slice_by_unicode(12..14); + assert_eq!(slice.deref(), "世界".as_bytes()); + } + + #[test] + fn slice_long_unicode_correctly() { + let mut arena = StrArena::default(); + let src = "一二34567八九零"; + for s in std::iter::repeat_n(src, 100) { + arena.alloc(s); + } + + let slice = arena.slice_by_unicode(110..120); + assert_eq!(slice.deref(), src.as_bytes()); + let slice = arena.slice_by_unicode(111..121); + assert_eq!(slice.deref(), "二34567八九零一".as_bytes()); + } + + #[test] + fn rollback_truncates_bytes_without_losing_prefix() { + let mut arena = StrArena::default(); + arena.alloc("hello"); + let checkpoint = arena.checkpoint(); + arena.alloc(" transient"); + arena.rollback(checkpoint); + arena.alloc("!"); + + let slice = arena.slice_by_unicode(..); + assert_eq!(slice.deref(), b"hello!"); + } +} diff --git a/vendor/loro-internal/src/awareness.rs b/vendor/loro-internal/src/awareness.rs new file mode 100644 index 0000000..581b278 --- /dev/null +++ b/vendor/loro-internal/src/awareness.rs @@ -0,0 +1,873 @@ +//! Ephemeral presence utilities. +//! +//! `EphemeralStore` is the recommended API: a timestamped, last-write-wins key-value +//! store for transient presence data (cursors, selections, etc.). It supports: +//! - Per-key timeouts: expired entries are skipped by `encode`/`encode_all` and removed +//! by `remove_outdated`. +//! - Import/export via `encode`/`apply` for syncing between peers. +//! - Subscriptions for both local updates (raw bytes to send) and merged updates. +//! +//! The legacy `Awareness` type remains for backward compatibility but is deprecated in +//! favor of `EphemeralStore`. +use crate::sync::Mutex; +use std::sync::atomic::AtomicI64; +use std::sync::Arc; + +use loro_common::{LoroValue, PeerID}; +use rustc_hash::FxHashMap; +use serde::de::{DeserializeSeed, EnumAccess, MapAccess, SeqAccess, VariantAccess}; +use serde::{Deserialize, Deserializer, Serialize}; + +use crate::change::{get_sys_timestamp, Timestamp}; +use crate::{SubscriberSetWithQueue, Subscription}; + +/// `Awareness` is a structure that tracks the ephemeral state of peers. +/// +/// It can be used to synchronize cursor positions, selections, and the names of the peers. +/// +/// The state of a specific peer is expected to be removed after a specified timeout. Use +/// `remove_outdated` to eliminate outdated states. +#[derive(Debug, Clone)] +#[deprecated(since = "1.4.6", note = "Use `EphemeralStore` instead.")] +pub struct Awareness { + peer: PeerID, + peers: FxHashMap<PeerID, PeerInfo>, + timeout: i64, +} + +#[derive(Debug, Clone)] +pub struct PeerInfo { + pub state: LoroValue, + pub counter: i32, + // This field is generated locally + pub timestamp: i64, +} + +#[derive(Serialize, Deserialize)] +struct EncodedPeerInfo { + peer: PeerID, + counter: i32, + record: LoroValue, +} + +#[derive(Deserialize)] +struct DecodedPeerInfo { + peer: PeerID, + counter: i32, + #[serde(deserialize_with = "deserialize_depth_limited_loro_value")] + record: LoroValue, +} + +#[allow(deprecated)] +impl Awareness { + pub fn new(peer: PeerID, timeout: i64) -> Awareness { + Awareness { + peer, + timeout, + peers: FxHashMap::default(), + } + } + + pub fn encode(&self, peers: &[PeerID]) -> Vec<u8> { + let mut peers_info = Vec::new(); + let now = get_sys_timestamp() as Timestamp; + for peer in peers { + if let Some(peer_info) = self.peers.get(peer) { + if now - peer_info.timestamp > self.timeout { + continue; + } + + let encoded_peer_info = EncodedPeerInfo { + peer: *peer, + record: peer_info.state.clone(), + counter: peer_info.counter, + }; + peers_info.push(encoded_peer_info); + } + } + + postcard::to_allocvec(&peers_info).unwrap() + } + + pub fn encode_all(&self) -> Vec<u8> { + let mut peers_info = Vec::new(); + let now = get_sys_timestamp() as Timestamp; + for (peer, peer_info) in self.peers.iter() { + if now - peer_info.timestamp > self.timeout { + continue; + } + + let encoded_peer_info = EncodedPeerInfo { + peer: *peer, + record: peer_info.state.clone(), + counter: peer_info.counter, + }; + peers_info.push(encoded_peer_info); + } + + postcard::to_allocvec(&peers_info).unwrap() + } + + /// Try to apply encoded updates imported from another peer/process. + /// + /// Returns (updated, added). + pub fn try_apply( + &mut self, + encoded_peers_info: &[u8], + ) -> Result<(Vec<PeerID>, Vec<PeerID>), Box<str>> { + let peers_info: Vec<DecodedPeerInfo> = postcard::from_bytes(encoded_peers_info) + .map_err(|err| format!("Failed to decode awareness data: {err}").into_boxed_str())?; + let mut changed_peers = Vec::new(); + let mut added_peers = Vec::new(); + let now = get_sys_timestamp() as Timestamp; + for peer_info in peers_info { + match self.peers.get(&peer_info.peer) { + Some(x) if x.counter >= peer_info.counter || peer_info.peer == self.peer => { + // do nothing + } + _ => { + let old = self.peers.insert( + peer_info.peer, + PeerInfo { + counter: peer_info.counter, + state: peer_info.record, + timestamp: now, + }, + ); + if old.is_some() { + changed_peers.push(peer_info.peer); + } else { + added_peers.push(peer_info.peer); + } + } + } + } + + Ok((changed_peers, added_peers)) + } + + /// Returns (updated, added) + pub fn apply(&mut self, encoded_peers_info: &[u8]) -> (Vec<PeerID>, Vec<PeerID>) { + self.try_apply(encoded_peers_info) + .expect("Failed to decode awareness data") + } + + pub fn set_local_state(&mut self, value: impl Into<LoroValue>) { + self._set_local_state(value.into()); + } + + fn _set_local_state(&mut self, value: LoroValue) { + let peer = self.peers.entry(self.peer).or_insert_with(|| PeerInfo { + state: Default::default(), + counter: 0, + timestamp: 0, + }); + + peer.state = value; + peer.counter += 1; + peer.timestamp = get_sys_timestamp() as Timestamp; + } + + pub fn get_local_state(&self) -> Option<LoroValue> { + self.peers.get(&self.peer).map(|x| x.state.clone()) + } + + pub fn remove_outdated(&mut self) -> Vec<PeerID> { + let now = get_sys_timestamp() as Timestamp; + let mut removed = Vec::new(); + self.peers.retain(|id, v| { + if now - v.timestamp > self.timeout { + removed.push(*id); + false + } else { + true + } + }); + + removed + } + + pub fn get_all_states(&self) -> &FxHashMap<PeerID, PeerInfo> { + &self.peers + } + + pub fn peer(&self) -> PeerID { + self.peer + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EphemeralEventTrigger { + Local, + Import, + Timeout, +} + +#[derive(Debug, Clone)] +pub struct EphemeralStoreEvent { + pub by: EphemeralEventTrigger, + pub added: Arc<Vec<String>>, + pub updated: Arc<Vec<String>>, + pub removed: Arc<Vec<String>>, +} + +pub type LocalEphemeralCallback = Box<dyn Fn(&Vec<u8>) -> bool + Send + Sync + 'static>; +pub type EphemeralSubscriber = Box<dyn Fn(&EphemeralStoreEvent) -> bool + Send + Sync + 'static>; + +/// `EphemeralStore` is a structure that tracks ephemeral key-value state across peers. +/// +/// - Use it for syncing lightweight presence/state like cursors, selections, and UI hints. +/// - Each key uses timestamp-based LWW (Last-Write-Wins) conflict resolution. +/// - Timeout unit: milliseconds. +/// - After timeout: entries are considered expired. They are omitted from +/// `encode`/`encode_all`, and calling [`remove_outdated`] will purge them and +/// notify subscribers with `EphemeralEventTrigger::Timeout`. +/// +/// In Rust, you are responsible for periodically calling [`remove_outdated`] +/// if you want timed-out entries to be removed and corresponding events to be +/// emitted. In the WASM/TS wrapper, a timer runs automatically while the store +/// is non-empty. +/// +/// See: https://loro.dev/docs/tutorial/ephemeral +/// +/// # Example +/// +/// ```rust +/// use loro_internal::awareness::EphemeralStore; +/// +/// let mut store = EphemeralStore::new(1000); +/// store.set("key", "value"); +/// let encoded = store.encode("key"); +/// let mut store2 = EphemeralStore::new(1000); +/// store.subscribe_local_updates(Box::new(|data| { +/// println!("local update: {:?}", data); +/// true +/// })); +/// store2.apply(&encoded); +/// assert_eq!(store2.get("key"), Some("value".into())); +/// ``` +#[derive(Debug, Clone)] +pub struct EphemeralStore { + inner: Arc<EphemeralStoreInner>, +} + +impl EphemeralStore { + /// Create a new `EphemeralStore`. + /// + /// - `timeout`: inactivity timeout in milliseconds. If a key does not + /// receive updates within this duration, it is considered expired. It + /// will be skipped by `encode`/`encode_all`, and removed when + /// [`remove_outdated`] is called (triggering a `Timeout` event to + /// subscribers). + pub fn new(timeout: i64) -> Self { + Self { + inner: Arc::new(EphemeralStoreInner::new(timeout)), + } + } + + /// Encode the latest value of `key`. + /// + /// Expired keys (past timeout) are omitted and produce an empty payload. + pub fn encode(&self, key: &str) -> Vec<u8> { + self.inner.encode(key) + } + + /// Encode all non-expired keys. + /// + /// Entries that have exceeded the timeout are not included in the payload. + pub fn encode_all(&self) -> Vec<u8> { + self.inner.encode_all() + } + + /// Apply encoded updates imported from another peer/process. + /// + /// Subscribers receive an event with `by = Import` and the lists of + /// `added`/`updated`/`removed` keys as appropriate. + pub fn apply(&self, data: &[u8]) -> Result<(), Box<str>> { + self.inner.apply(data) + } + + pub fn set(&self, key: &str, value: impl Into<LoroValue>) { + self.inner.set(key, value) + } + + pub fn delete(&self, key: &str) { + self.inner.delete(key) + } + + pub fn get(&self, key: &str) -> Option<LoroValue> { + self.inner.get(key) + } + + /// Remove entries whose last update timestamp has exceeded the timeout. + /// + /// If any keys are removed, subscribers receive an event with + /// `by = Timeout` and the `removed` keys. This does not run automatically + /// in Rust; call it on your own schedule. + pub fn remove_outdated(&self) { + self.inner.remove_outdated() + } + + pub fn get_all_states(&self) -> FxHashMap<String, LoroValue> { + self.inner.get_all_states() + } + + pub fn keys(&self) -> Vec<String> { + self.inner.keys() + } + + /// Subscribe to local ephemeral/awareness updates. + /// + /// The callback receives encoded update bytes whenever local ephemeral state changes. + /// This is useful for syncing awareness information like cursor positions, selections, + /// or presence data to other peers in real-time. + /// + /// **Auto-unsubscription**: If the callback returns `false`, the subscription will be + /// automatically removed, providing a convenient way to implement one-time or conditional + /// subscriptions in Rust. + /// + /// # Parameters + /// - `callback`: Function that receives `&Vec<u8>` (encoded ephemeral updates) and returns `bool` + /// - Return `true` to keep the subscription active + /// - Return `false` to automatically unsubscribe + /// + /// # Example + /// ```rust + /// use loro_internal::awareness::EphemeralStore; + /// use std::sync::{Arc, Mutex}; + /// + /// let store = EphemeralStore::new(30000); + /// let update_count = Arc::new(Mutex::new(0)); + /// let count_clone = update_count.clone(); + /// + /// // Subscribe and collect first 3 updates, then auto-unsubscribe + /// let sub = store.subscribe_local_updates(Box::new(move |bytes| { + /// println!("Received {} bytes of ephemeral data", bytes.len()); + /// let mut count = count_clone.lock().unwrap(); + /// *count += 1; + /// *count < 3 // Auto-unsubscribe after 3 updates + /// })); + /// + /// store.set("cursor", 42); + /// ``` + pub fn subscribe_local_updates(&self, callback: LocalEphemeralCallback) -> Subscription { + self.inner.subscribe_local_updates(callback) + } + + pub fn subscribe(&self, callback: EphemeralSubscriber) -> Subscription { + self.inner.subscribe(callback) + } +} + +struct EphemeralStoreInner { + states: Mutex<FxHashMap<String, State>>, + local_subs: SubscriberSetWithQueue<(), LocalEphemeralCallback, Vec<u8>>, + subscribers: SubscriberSetWithQueue<(), EphemeralSubscriber, EphemeralStoreEvent>, + timeout: AtomicI64, +} + +impl std::fmt::Debug for EphemeralStoreInner { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "AwarenessV2 {{ states: {:?}, timeout: {:?} }}", + self.states, self.timeout + ) + } +} + +#[derive(Serialize, Deserialize)] +struct EncodedState<'a> { + #[serde(borrow)] + key: &'a str, + value: Option<LoroValue>, + timestamp: i64, +} + +#[derive(Deserialize)] +struct DecodedState<'a> { + #[serde(borrow)] + key: &'a str, + #[serde(deserialize_with = "deserialize_optional_depth_limited_loro_value")] + value: Option<LoroValue>, + timestamp: i64, +} + +const EPHEMERAL_VALUE_MAX_DEPTH: usize = 512; + +fn deserialize_optional_depth_limited_loro_value<'de, D>( + deserializer: D, +) -> Result<Option<LoroValue>, D::Error> +where + D: Deserializer<'de>, +{ + Option::<DepthLimitedLoroValue>::deserialize(deserializer) + .map(|value| value.map(DepthLimitedLoroValue::into_inner)) +} + +fn deserialize_depth_limited_loro_value<'de, D>(deserializer: D) -> Result<LoroValue, D::Error> +where + D: Deserializer<'de>, +{ + LoroValueSeed { + remaining_depth: EPHEMERAL_VALUE_MAX_DEPTH, + } + .deserialize(deserializer) +} + +struct DepthLimitedLoroValue(LoroValue); + +impl DepthLimitedLoroValue { + fn into_inner(self) -> LoroValue { + self.0 + } +} + +impl<'de> Deserialize<'de> for DepthLimitedLoroValue { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + deserialize_depth_limited_loro_value(deserializer).map(Self) + } +} + +#[derive(Clone, Copy)] +struct LoroValueSeed { + remaining_depth: usize, +} + +impl LoroValueSeed { + fn nested<E>(self) -> Result<Self, E> + where + E: serde::de::Error, + { + let remaining_depth = self + .remaining_depth + .checked_sub(1) + .ok_or_else(|| E::custom("LoroValue nesting depth exceeded"))?; + Ok(Self { remaining_depth }) + } +} + +impl<'de> DeserializeSeed<'de> for LoroValueSeed { + type Value = LoroValue; + + fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + if deserializer.is_human_readable() { + return Err(serde::de::Error::custom( + "human-readable LoroValue is not supported by the awareness decoder", + )); + } + + deserializer.deserialize_enum( + "LoroValue", + &[ + "Null", + "Bool", + "Double", + "I32", + "String", + "List", + "Map", + "Container", + "Binary", + ], + LoroValueSeedVisitor { seed: self }, + ) + } +} + +struct LoroValueSeedVisitor { + seed: LoroValueSeed, +} + +impl<'de> serde::de::Visitor<'de> for LoroValueSeedVisitor { + type Value = LoroValue; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("a depth-limited LoroValue") + } + + fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error> + where + A: EnumAccess<'de>, + { + match data.variant()? { + (DepthLimitedLoroValueField::Null, v) => { + v.unit_variant()?; + Ok(LoroValue::Null) + } + (DepthLimitedLoroValueField::Bool, v) => v.newtype_variant().map(LoroValue::Bool), + (DepthLimitedLoroValueField::Double, v) => v.newtype_variant().map(LoroValue::Double), + (DepthLimitedLoroValueField::I32, v) => v.newtype_variant().map(LoroValue::I64), + (DepthLimitedLoroValueField::String, v) => v + .newtype_variant() + .map(|value: String| LoroValue::String(value.into())), + (DepthLimitedLoroValueField::List, v) => v + .newtype_variant_seed(LoroListSeed { + value_seed: self.seed.nested()?, + }) + .map(|value| LoroValue::List(value.into())), + (DepthLimitedLoroValueField::Map, v) => v + .newtype_variant_seed(LoroMapSeed { + value_seed: self.seed.nested()?, + }) + .map(|value| LoroValue::Map(value.into())), + (DepthLimitedLoroValueField::Container, v) => { + v.newtype_variant().map(LoroValue::Container) + } + (DepthLimitedLoroValueField::Binary, v) => v + .newtype_variant() + .map(|value: Vec<u8>| LoroValue::Binary(value.into())), + } + } +} + +#[derive(Deserialize)] +enum DepthLimitedLoroValueField { + Null, + Bool, + Double, + I32, + String, + List, + Map, + Container, + Binary, +} + +struct LoroListSeed { + value_seed: LoroValueSeed, +} + +impl<'de> DeserializeSeed<'de> for LoroListSeed { + type Value = Vec<LoroValue>; + + fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_seq(LoroListVisitor { + value_seed: self.value_seed, + }) + } +} + +struct LoroListVisitor { + value_seed: LoroValueSeed, +} + +impl<'de> serde::de::Visitor<'de> for LoroListVisitor { + type Value = Vec<LoroValue>; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("a depth-limited LoroValue list") + } + + fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> + where + A: SeqAccess<'de>, + { + let mut list = Vec::new(); + while let Some(value) = seq.next_element_seed(self.value_seed)? { + list.push(value); + } + Ok(list) + } +} + +struct LoroMapSeed { + value_seed: LoroValueSeed, +} + +impl<'de> DeserializeSeed<'de> for LoroMapSeed { + type Value = FxHashMap<String, LoroValue>; + + fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_map(LoroMapVisitor { + value_seed: self.value_seed, + }) + } +} + +struct LoroMapVisitor { + value_seed: LoroValueSeed, +} + +impl<'de> serde::de::Visitor<'de> for LoroMapVisitor { + type Value = FxHashMap<String, LoroValue>; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("a depth-limited LoroValue map") + } + + fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> + where + A: MapAccess<'de>, + { + let mut value = FxHashMap::default(); + while let Some(key) = map.next_key()? { + let entry = map.next_value_seed(self.value_seed)?; + value.insert(key, entry); + } + Ok(value) + } +} + +#[derive(Debug, Clone)] +struct State { + state: Option<LoroValue>, + timestamp: i64, +} + +impl EphemeralStoreInner { + pub fn new(timeout: i64) -> EphemeralStoreInner { + EphemeralStoreInner { + timeout: AtomicI64::new(timeout), + states: Mutex::new(FxHashMap::default()), + local_subs: SubscriberSetWithQueue::new(), + subscribers: SubscriberSetWithQueue::new(), + } + } + + pub fn encode(&self, key: &str) -> Vec<u8> { + let mut peers_info = Vec::new(); + let now = get_sys_timestamp() as Timestamp; + let states = self.states.lock(); + if let Some(peer_state) = states.get(key) { + if now - peer_state.timestamp > self.timeout.load(std::sync::atomic::Ordering::Relaxed) + { + return vec![]; + } + let encoded_peer_info = EncodedState { + key, + value: peer_state.state.clone(), + timestamp: peer_state.timestamp, + }; + peers_info.push(encoded_peer_info); + } + + postcard::to_allocvec(&peers_info).unwrap() + } + + pub fn encode_all(&self) -> Vec<u8> { + let mut peers_info = Vec::new(); + let now = get_sys_timestamp() as Timestamp; + let states = self.states.lock(); + for (key, peer_state) in states.iter() { + if now - peer_state.timestamp > self.timeout.load(std::sync::atomic::Ordering::Relaxed) + { + continue; + } + let encoded_peer_info = EncodedState { + key, + value: peer_state.state.clone(), + timestamp: peer_state.timestamp, + }; + peers_info.push(encoded_peer_info); + } + postcard::to_allocvec(&peers_info).unwrap() + } + + pub fn apply(&self, data: &[u8]) -> Result<(), Box<str>> { + let peers_info = match postcard::from_bytes::<Vec<DecodedState>>(data) { + Ok(ans) => ans, + Err(err) => return Err(format!("Failed to decode data: {}", err).into()), + }; + + let mut updated_keys = Vec::new(); + let mut added_keys = Vec::new(); + let mut removed_keys = Vec::new(); + let now = get_sys_timestamp() as Timestamp; + let timeout = self.timeout.load(std::sync::atomic::Ordering::Relaxed); + let mut states = self.states.lock(); + for DecodedState { + key, + value: record, + timestamp, + } in peers_info + { + if now - timestamp > timeout { + continue; + } + + match states.get_mut(key) { + Some(peer_info) if peer_info.timestamp >= timestamp => { + // do nothing + } + _ => { + let old = states.insert( + key.to_string(), + State { + state: record.clone(), + timestamp, + }, + ); + match (old, record) { + (Some(_), Some(_)) => updated_keys.push(key.to_string()), + (None, Some(_)) => added_keys.push(key.to_string()), + (Some(_), None) => removed_keys.push(key.to_string()), + (None, None) => {} + } + } + } + } + + drop(states); + if !self.subscribers.inner().is_empty() { + self.subscribers.emit( + &(), + EphemeralStoreEvent { + by: EphemeralEventTrigger::Import, + added: Arc::new(added_keys), + updated: Arc::new(updated_keys), + removed: Arc::new(removed_keys), + }, + ); + } + + Ok(()) + } + + pub fn set(&self, key: &str, value: impl Into<LoroValue>) { + self._set_local_state(key, Some(value.into())); + } + + pub fn delete(&self, key: &str) { + self._set_local_state(key, None); + } + + pub fn get(&self, key: &str) -> Option<LoroValue> { + let states = self.states.lock(); + states.get(key).and_then(|x| x.state.clone()) + } + + pub fn remove_outdated(&self) { + let now = get_sys_timestamp() as Timestamp; + let mut removed = Vec::new(); + let mut states = self.states.lock(); + states.retain(|key, state| { + if now - state.timestamp > self.timeout.load(std::sync::atomic::Ordering::Relaxed) { + if state.state.is_some() { + removed.push(key.clone()); + } + false + } else { + true + } + }); + drop(states); + if !self.subscribers.inner().is_empty() { + self.subscribers.emit( + &(), + EphemeralStoreEvent { + by: EphemeralEventTrigger::Timeout, + added: Arc::new(Vec::new()), + updated: Arc::new(Vec::new()), + removed: Arc::new(removed), + }, + ); + } + } + + pub fn get_all_states(&self) -> FxHashMap<String, LoroValue> { + let states = self.states.lock(); + states + .iter() + .filter(|(_, v)| v.state.is_some()) + .map(|(k, v)| (k.clone(), v.state.clone().unwrap())) + .collect() + } + + pub fn keys(&self) -> Vec<String> { + let states = self.states.lock(); + states + .keys() + .filter(|&k| states.get(k).unwrap().state.is_some()) + .map(|s| s.to_string()) + .collect() + } + + /// Subscribe to local ephemeral state updates. + /// + /// The callback receives encoded update bytes whenever the local peer's ephemeral state + /// is modified. This enables real-time synchronization of awareness data like cursor + /// positions, user presence, or temporary collaborative state. + /// + /// **Auto-unsubscription**: If the callback returns `false`, the subscription will be + /// automatically removed, making it easy to implement conditional or temporary subscriptions. + /// + /// # Parameters + /// - `callback`: Function that receives `&Vec<u8>` and returns `bool` + /// - Return `true` to maintain the subscription + /// - Return `false` to automatically unsubscribe + /// + /// # Returns + /// A `Subscription` that can be used to manually unsubscribe if needed. + pub fn subscribe_local_updates(&self, callback: LocalEphemeralCallback) -> Subscription { + let (sub, activate) = self.local_subs.inner().insert((), callback); + activate(); + sub + } + + pub fn subscribe(&self, callback: EphemeralSubscriber) -> Subscription { + let (sub, activate) = self.subscribers.inner().insert((), callback); + activate(); + sub + } + + fn _set_local_state(&self, key: &str, value: Option<LoroValue>) { + let is_delete = value.is_none(); + let mut states = self.states.lock(); + let old = states.insert( + key.to_string(), + State { + state: value, + timestamp: get_sys_timestamp() as Timestamp, + }, + ); + + drop(states); + if !self.local_subs.inner().is_empty() { + self.local_subs.emit(&(), self.encode(key)); + } + if !self.subscribers.inner().is_empty() { + if old.is_some() { + self.subscribers.emit( + &(), + EphemeralStoreEvent { + by: EphemeralEventTrigger::Local, + added: Arc::new(Vec::new()), + updated: if !is_delete { + Arc::new(vec![key.to_string()]) + } else { + Arc::new(Vec::new()) + }, + removed: if !is_delete { + Arc::new(Vec::new()) + } else { + Arc::new(vec![key.to_string()]) + }, + }, + ); + } else if !is_delete { + self.subscribers.emit( + &(), + EphemeralStoreEvent { + by: EphemeralEventTrigger::Local, + added: Arc::new(vec![key.to_string()]), + updated: Arc::new(Vec::new()), + removed: Arc::new(Vec::new()), + }, + ); + } + } + } +} diff --git a/vendor/loro-internal/src/change.rs b/vendor/loro-internal/src/change.rs new file mode 100644 index 0000000..72edc4a --- /dev/null +++ b/vendor/loro-internal/src/change.rs @@ -0,0 +1,329 @@ +//! [Change]s are merged ops. +//! +//! Every [Change] has deps on other [Change]s. All [Change]s in the document thus form a DAG. +//! +//! Note: `dep` can only point to the end of the other [Change]. This is the invariant of [Change]s. + +use crate::{ + dag::DagNode, + estimated_size::EstimatedSize, + id::{Counter, ID}, + op::Op, + span::{HasId, HasLamport}, + version::Frontiers, +}; +use loro_common::{HasCounter, HasCounterSpan, PeerID}; +use num::traits::AsPrimitive; +use rle::{HasIndex, HasLength, Mergable, RleVec, Sliceable}; +use smallvec::SmallVec; + +pub type Timestamp = i64; +pub type Lamport = u32; + +/// A `Change` contains a list of [Op]s. +/// +/// When undo/redo we should always undo/redo a whole [Change]. +// PERF change slice and getting length is kinda slow I guess +#[derive(Debug, Clone, PartialEq)] +pub struct Change<O = Op> { + /// id of the first op in the change + pub(crate) id: ID, + /// Lamport timestamp of the change. It can be calculated from deps + pub(crate) lamport: Lamport, + pub(crate) deps: Frontiers, + /// [Unix time](https://en.wikipedia.org/wiki/Unix_time) + /// It is the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970. + pub(crate) timestamp: Timestamp, + pub(crate) commit_msg: Option<Arc<str>>, + pub(crate) ops: RleVec<[O; 1]>, +} + +pub(crate) struct ChangeRef<'a, O = Op> { + pub(crate) id: &'a ID, + pub(crate) lamport: &'a Lamport, + pub(crate) deps: &'a Frontiers, + pub(crate) timestamp: &'a Timestamp, + pub(crate) commit_msg: &'a Option<Arc<str>>, + pub(crate) ops: &'a RleVec<[O; 1]>, +} + +impl<'a, O> ChangeRef<'a, O> { + pub fn from_change(change: &'a Change<O>) -> Self { + Self { + id: &change.id, + lamport: &change.lamport, + deps: &change.deps, + timestamp: &change.timestamp, + commit_msg: &change.commit_msg, + ops: &change.ops, + } + } +} + +impl<O> Change<O> { + pub fn new( + ops: RleVec<[O; 1]>, + deps: Frontiers, + id: ID, + lamport: Lamport, + timestamp: Timestamp, + ) -> Self { + Change { + ops, + deps, + id, + lamport, + timestamp, + commit_msg: None, + } + } + + #[inline] + pub fn ops(&self) -> &RleVec<[O; 1]> { + &self.ops + } + + #[inline] + pub fn deps(&self) -> &Frontiers { + &self.deps + } + + #[inline] + pub fn peer(&self) -> PeerID { + self.id.peer + } + + #[inline] + pub fn lamport(&self) -> Lamport { + self.lamport + } + + #[inline] + pub fn timestamp(&self) -> Timestamp { + self.timestamp + } + + #[inline] + pub fn id(&self) -> ID { + self.id + } + + #[inline] + pub fn deps_on_self(&self) -> bool { + if let Some(id) = self.deps.as_single() { + id.peer == self.id.peer + } else { + false + } + } + + pub fn message(&self) -> Option<&Arc<str>> { + self.commit_msg.as_ref() + } +} + +impl<O: EstimatedSize> EstimatedSize for Change<O> { + /// Estimate the storage size of the change in bytes + #[inline] + fn estimate_storage_size(&self) -> usize { + let id_size = 2; + let lamport_size = 1; + let timestamp_size = 1; + let deps_size = (self.deps.len().max(1) - 1) * 4; + let ops_size = self + .ops + .iter() + .map(|op| op.estimate_storage_size()) + .sum::<usize>(); + id_size + lamport_size + timestamp_size + ops_size + deps_size + } +} + +impl<O: Mergable + HasLength + HasIndex + Debug> HasIndex for Change<O> { + type Int = Counter; + + fn get_start_index(&self) -> Self::Int { + self.id.counter + } +} + +impl<O> HasId for Change<O> { + fn id_start(&self) -> ID { + self.id + } +} + +impl<O> HasCounter for Change<O> { + fn ctr_start(&self) -> Counter { + self.id.counter + } +} + +impl<O> HasLamport for Change<O> { + fn lamport(&self) -> Lamport { + self.lamport + } +} + +impl<O> Mergable for Change<O> { + fn is_mergable(&self, _other: &Self, _conf: &()) -> bool + where + Self: Sized, + { + false + } + + fn merge(&mut self, _other: &Self, _conf: &()) + where + Self: Sized, + { + unreachable!() + } +} + +impl<O: Mergable + HasLength + HasIndex + Debug> Change<O> { + pub fn len(&self) -> usize { + self.ops.span().as_() + } + + pub fn is_empty(&self) -> bool { + self.ops.is_empty() + } +} + +use std::{fmt::Debug, sync::Arc}; +impl<O: Mergable + HasLength + HasIndex + Debug> HasLength for Change<O> { + fn content_len(&self) -> usize { + self.ops.span().as_() + } +} + +impl<O: Mergable + HasLength + HasIndex + Sliceable + HasCounter + Debug> Sliceable for Change<O> { + // TODO: feels slow, need to confirm whether this affects performance + fn slice(&self, from: usize, to: usize) -> Self { + assert!(from < to); + assert!(to <= self.atom_len()); + let from_counter = self.id.counter + from as Counter; + let to_counter = self.id.counter + to as Counter; + let ops = { + if from >= to { + RleVec::new() + } else { + let mut ans: SmallVec<[_; 1]> = SmallVec::new(); + let mut start_index = 0; + if self.ops.len() >= 8 { + let result = self + .ops + .binary_search_by(|op| op.ctr_end().cmp(&from_counter)); + start_index = match result { + Ok(i) => i, + Err(i) => i, + }; + } + + for i in start_index..self.ops.len() { + let op = &self.ops[i]; + if op.ctr_start() >= to_counter { + break; + } + if op.ctr_end() <= from_counter { + continue; + } + + let start_offset = + ((from_counter - op.ctr_start()).max(0) as usize).min(op.atom_len()); + let end_offset = + ((to_counter - op.ctr_start()).max(0) as usize).min(op.atom_len()); + assert_ne!(start_offset, end_offset); + ans.push(op.slice(start_offset, end_offset)) + } + + RleVec::from(ans) + } + }; + assert_eq!(ops.first().unwrap().ctr_start(), from_counter); + assert_eq!(ops.last().unwrap().ctr_end(), to_counter); + Self { + ops, + deps: if from > 0 { + Frontiers::from_id(self.id.inc(from as Counter - 1)) + } else { + self.deps.clone() + }, + id: self.id.inc(from as Counter), + lamport: self.lamport + from as Lamport, + timestamp: self.timestamp, + commit_msg: self.commit_msg.clone(), + } + } +} + +impl DagNode for Change { + fn deps(&self) -> &Frontiers { + &self.deps + } +} + +impl Change { + pub fn can_merge_right(&self, other: &Self, merge_interval: i64) -> bool { + if other.id.peer == self.id.peer + && other.id.counter == self.id.counter + self.content_len() as Counter + && other.deps.len() == 1 + && other.deps.as_single().unwrap().peer == self.id.peer + && other.timestamp - self.timestamp <= merge_interval + && self.commit_msg == other.commit_msg + { + debug_assert!(other.timestamp >= self.timestamp); + debug_assert!(other.lamport == self.lamport + self.len() as Lamport); + true + } else { + false + } + } +} + +/// [Unix time](https://en.wikipedia.org/wiki/Unix_time) +/// It is the number of milliseconds that have elapsed since 00:00:00 UTC on 1 January 1970. +#[cfg(any( + not(target_arch = "wasm32"), + target_os = "emscripten", + target_os = "wasi" +))] +pub(crate) fn get_sys_timestamp() -> f64 { + use std::time::{SystemTime, UNIX_EPOCH}; + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() + .as_() +} + +/// [Unix time](https://en.wikipedia.org/wiki/Unix_time) +/// It is the number of milliseconds that have elapsed since 00:00:00 UTC on 1 January 1970. +#[cfg(all( + target_arch = "wasm32", + not(target_os = "emscripten"), + not(target_os = "wasi") +))] +pub fn get_sys_timestamp() -> f64 { + use wasm_bindgen::prelude::wasm_bindgen; + #[wasm_bindgen] + extern "C" { + // Use `js_namespace` here to bind `console.log(..)` instead of just + // `log(..)` + #[wasm_bindgen(js_namespace = Date)] + pub fn now() -> f64; + } + + now() +} + +#[cfg(test)] +mod test { + use super::*; + #[test] + fn size_of_change() { + let size = std::mem::size_of::<Change>(); + println!("{}", size); + } +} diff --git a/vendor/loro-internal/src/change_meta.rs b/vendor/loro-internal/src/change_meta.rs new file mode 100644 index 0000000..93e9cbd --- /dev/null +++ b/vendor/loro-internal/src/change_meta.rs @@ -0,0 +1,98 @@ +use std::{cmp::Ordering, sync::Arc}; + +use loro_common::HasLamport; +use rle::HasLength; + +use crate::{ + change::{Change, Lamport, Timestamp}, + id::ID, + version::Frontiers, +}; + +/// `Change` is a grouped continuous operations that share the same id, timestamp, commit message. +/// +/// - The id of the `Change` is the id of its first op. +/// - The second op's id is `{ peer: change.id.peer, counter: change.id.counter + 1 }` +/// +/// The same applies on `Lamport`: +/// +/// - The lamport of the `Change` is the lamport of its first op. +/// - The second op's lamport is `change.lamport + 1` +/// +/// The length of the `Change` is how many operations it contains +#[derive(Debug, Clone)] +pub struct ChangeMeta { + /// Lamport timestamp of the Change + pub lamport: Lamport, + /// The first Op id of the Change + pub id: ID, + /// [Unix time](https://en.wikipedia.org/wiki/Unix_time) + /// It is the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970. + pub timestamp: Timestamp, + /// The commit message of the change + pub message: Option<Arc<str>>, + /// The dependencies of the first op of the change + pub deps: Frontiers, + /// The total op num inside this change + pub len: usize, +} + +impl PartialEq for ChangeMeta { + fn eq(&self, other: &Self) -> bool { + self.lamport == other.lamport && self.id == other.id + } +} + +impl Eq for ChangeMeta {} + +impl PartialOrd for ChangeMeta { + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for ChangeMeta { + fn cmp(&self, other: &Self) -> Ordering { + (self.lamport + self.len as Lamport) + .cmp(&(other.lamport + other.len as Lamport)) + .then(self.id.peer.cmp(&other.id.peer)) + } +} + +impl HasLamport for ChangeMeta { + fn lamport(&self) -> loro_common::Lamport { + self.lamport + } +} + +impl HasLength for ChangeMeta { + fn content_len(&self) -> usize { + self.len + } +} + +impl ChangeMeta { + pub fn from_change(c: &Change) -> Self { + Self { + id: c.id(), + lamport: c.lamport(), + timestamp: c.timestamp(), + message: c.message().cloned(), + deps: c.deps().clone(), + len: c.len(), + } + } + + /// Get the commit message in &str + pub fn message(&self) -> &str { + match self.message.as_ref() { + Some(m) => m, + None => "", + } + } + + /// Get the commit timestamp in seconds since Unix epoch. + pub fn timestamp(&self) -> crate::change::Timestamp { + self.timestamp + } +} diff --git a/vendor/loro-internal/src/configure.rs b/vendor/loro-internal/src/configure.rs new file mode 100644 index 0000000..d12203d --- /dev/null +++ b/vendor/loro-internal/src/configure.rs @@ -0,0 +1,337 @@ +use crate::sync::{Mutex, RwLock}; +use loro_common::ContainerID; +use rustc_hash::FxHashSet; + +pub use crate::container::richtext::config::{StyleConfig, StyleConfigMap}; +use crate::LoroDoc; +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering}; +use std::sync::Arc; + +#[cfg(not(test))] +pub(crate) const DEFAULT_DECODED_VALUE_CACHE_LIMIT: usize = 2048; +// Keep eviction tests small without changing the production default. +#[cfg(test)] +pub(crate) const DEFAULT_DECODED_VALUE_CACHE_LIMIT: usize = 16; + +#[derive(Clone, Debug)] +pub struct Configure { + pub(crate) text_style_config: Arc<RwLock<StyleConfigMap>>, + record_timestamp: Arc<AtomicBool>, + pub(crate) merge_interval_in_s: Arc<AtomicI64>, + pub(crate) editable_detached_mode: Arc<AtomicBool>, + pub(crate) deleted_root_containers: Arc<Mutex<FxHashSet<ContainerID>>>, + pub(crate) hide_empty_root_containers: Arc<AtomicBool>, + decoded_value_cache_limit: Arc<AtomicUsize>, +} + +impl LoroDoc { + pub(crate) fn set_config(&self, config: &Configure) { + // Forks need both explicit styles and the fallback for unused keys. + // config_text_style intentionally only replaces the explicit map. + let text_style_config = config.text_style_config.read().clone(); + *self.config.text_style_config.write() = text_style_config; + self.set_record_timestamp(config.record_timestamp()); + self.set_change_merge_interval(config.merge_interval()); + self.set_detached_editing(config.detached_editing()); + self.set_decoded_value_cache_limit(config.decoded_value_cache_limit()); + } +} + +impl Default for Configure { + fn default() -> Self { + Self { + text_style_config: Arc::new(RwLock::new(StyleConfigMap::default_rich_text_config())), + record_timestamp: Arc::new(AtomicBool::new(false)), + editable_detached_mode: Arc::new(AtomicBool::new(false)), + merge_interval_in_s: Arc::new(AtomicI64::new(1000)), + deleted_root_containers: Arc::new(Mutex::new(Default::default())), + hide_empty_root_containers: Arc::new(AtomicBool::new(false)), + decoded_value_cache_limit: Arc::new(AtomicUsize::new( + DEFAULT_DECODED_VALUE_CACHE_LIMIT, + )), + } + } +} + +impl Configure { + pub fn fork(&self) -> Self { + Self { + text_style_config: Arc::new(RwLock::new(self.text_style_config.read().clone())), + record_timestamp: Arc::new(AtomicBool::new( + self.record_timestamp + .load(std::sync::atomic::Ordering::Relaxed), + )), + merge_interval_in_s: Arc::new(AtomicI64::new( + self.merge_interval_in_s + .load(std::sync::atomic::Ordering::Relaxed), + )), + editable_detached_mode: Arc::new(AtomicBool::new( + self.editable_detached_mode + .load(std::sync::atomic::Ordering::Relaxed), + )), + deleted_root_containers: Arc::new(Mutex::new( + self.deleted_root_containers.lock().clone(), + )), + hide_empty_root_containers: Arc::new(AtomicBool::new( + self.hide_empty_root_containers + .load(std::sync::atomic::Ordering::Relaxed), + )), + decoded_value_cache_limit: Arc::new(AtomicUsize::new(self.decoded_value_cache_limit())), + } + } + + pub fn text_style_config(&self) -> &Arc<RwLock<StyleConfigMap>> { + &self.text_style_config + } + + pub(crate) fn decoded_value_cache_limit(&self) -> usize { + self.decoded_value_cache_limit.load(Ordering::Relaxed) + } + + pub(crate) fn set_decoded_value_cache_limit(&self, limit: usize) { + self.decoded_value_cache_limit + .store(limit, Ordering::Relaxed); + } + + pub fn record_timestamp(&self) -> bool { + self.record_timestamp + .load(std::sync::atomic::Ordering::Relaxed) + } + + pub fn set_record_timestamp(&self, record: bool) { + self.record_timestamp + .store(record, std::sync::atomic::Ordering::Relaxed); + } + + pub fn detached_editing(&self) -> bool { + self.editable_detached_mode + .load(std::sync::atomic::Ordering::Relaxed) + } + + pub fn set_detached_editing(&self, mode: bool) { + self.editable_detached_mode + .store(mode, std::sync::atomic::Ordering::Relaxed); + } + + pub fn merge_interval(&self) -> i64 { + self.merge_interval_in_s + .load(std::sync::atomic::Ordering::Relaxed) + } + + pub fn set_merge_interval(&self, interval: i64) { + self.merge_interval_in_s + .store(interval, std::sync::atomic::Ordering::Relaxed); + } + + pub fn set_hide_empty_root_containers(&self, hide: bool) { + self.hide_empty_root_containers + .store(hide, std::sync::atomic::Ordering::Relaxed); + } +} + +#[derive(Debug)] +pub struct DefaultRandom; + +#[cfg(test)] +use std::sync::atomic::AtomicU64; +#[cfg(test)] +static mut TEST_RANDOM: AtomicU64 = AtomicU64::new(0); + +impl SecureRandomGenerator for DefaultRandom { + fn fill_byte(&self, dest: &mut [u8]) { + #[cfg(all(not(test), not(loom)))] + getrandom::getrandom(dest).unwrap(); + + // Loom requires every execution of a model to be deterministic, so + // peer ids come from a counter that loom resets per execution. + #[cfg(all(not(test), loom))] + { + loom::lazy_static! { + static ref LOOM_RANDOM: std::sync::atomic::AtomicU64 = + std::sync::atomic::AtomicU64::new(0); + } + let bytes = LOOM_RANDOM + .fetch_add(1, std::sync::atomic::Ordering::Relaxed) + .to_le_bytes(); + dest.copy_from_slice(&bytes[..dest.len()]); + } + + #[cfg(test)] + // SAFETY: this is only used in test + unsafe { + #[allow(static_mut_refs)] + let bytes = TEST_RANDOM + .fetch_add(1, std::sync::atomic::Ordering::Release) + .to_le_bytes(); + dest.copy_from_slice(&bytes[..dest.len()]); + } + } +} + +pub trait SecureRandomGenerator: Send + Sync { + fn fill_byte(&self, dest: &mut [u8]); + fn next_u64(&self) -> u64 { + let mut buf = [0u8; 8]; + self.fill_byte(&mut buf); + u64::from_le_bytes(buf) + } + + fn next_u32(&self) -> u32 { + let mut buf = [0u8; 4]; + self.fill_byte(&mut buf); + u32::from_le_bytes(buf) + } + + fn next_i64(&self) -> i64 { + let mut buf = [0u8; 8]; + self.fill_byte(&mut buf); + i64::from_le_bytes(buf) + } + + fn next_i32(&self) -> i32 { + let mut buf = [0u8; 4]; + self.fill_byte(&mut buf); + i32::from_le_bytes(buf) + } +} + +#[cfg(test)] +mod tests { + use std::sync::{atomic::Ordering, Mutex, OnceLock}; + + use loro_common::{ContainerID, ContainerType, InternalString}; + + use crate::container::richtext::ExpandType; + + use super::*; + + fn random_lock() -> &'static Mutex<()> { + static LOCK: OnceLock<Mutex<()>> = OnceLock::new(); + LOCK.get_or_init(|| Mutex::new(())) + } + + #[test] + fn configure_default_values_and_setters_match_the_public_contract() { + let config = Configure::default(); + + assert!(!config.record_timestamp()); + assert!(!config.detached_editing()); + assert_eq!(config.merge_interval(), 1000); + assert_eq!( + config.decoded_value_cache_limit(), + DEFAULT_DECODED_VALUE_CACHE_LIMIT + ); + assert!(!config.hide_empty_root_containers.load(Ordering::Relaxed)); + assert!(config.deleted_root_containers.lock().is_empty()); + + let styles = config.text_style_config.read(); + assert_eq!( + styles.get(&InternalString::from("bold")), + Some(StyleConfig { + expand: ExpandType::After, + }) + ); + assert_eq!( + styles.get(&InternalString::from("italic")), + Some(StyleConfig { + expand: ExpandType::After, + }) + ); + assert_eq!( + styles.get(&InternalString::from("link")), + Some(StyleConfig { + expand: ExpandType::None, + }) + ); + assert_eq!(styles.get(&InternalString::from("missing")), None); + + config.set_record_timestamp(true); + config.set_detached_editing(true); + config.set_merge_interval(42); + config.set_hide_empty_root_containers(true); + + assert!(config.record_timestamp()); + assert!(config.detached_editing()); + assert_eq!(config.merge_interval(), 42); + assert!(config.hide_empty_root_containers.load(Ordering::Relaxed)); + } + + #[test] + fn configure_fork_copies_current_state_and_then_diverges() { + let config = Configure::default(); + config.set_record_timestamp(true); + config.set_detached_editing(true); + config.set_merge_interval(25); + config.set_decoded_value_cache_limit(8192); + config.set_hide_empty_root_containers(true); + config + .deleted_root_containers + .lock() + .insert(ContainerID::Root { + name: InternalString::from("root"), + container_type: ContainerType::Map, + }); + config.text_style_config.write().insert( + InternalString::from("custom"), + StyleConfig { + expand: ExpandType::None, + }, + ); + + let forked = config.fork(); + + assert!(forked.record_timestamp()); + assert!(forked.detached_editing()); + assert_eq!(forked.merge_interval(), 25); + assert_eq!(forked.decoded_value_cache_limit(), 8192); + assert!(forked.hide_empty_root_containers.load(Ordering::Relaxed)); + assert_eq!(forked.deleted_root_containers.lock().len(), 1); + assert_eq!( + forked + .text_style_config + .read() + .get(&InternalString::from("custom")), + Some(StyleConfig { + expand: ExpandType::None, + }) + ); + + config.set_record_timestamp(false); + config.set_detached_editing(false); + config.set_merge_interval(99); + config.set_decoded_value_cache_limit(0); + config.set_hide_empty_root_containers(false); + config.deleted_root_containers.lock().clear(); + config + .text_style_config + .write() + .insert(InternalString::from("fork-only"), StyleConfig::default()); + + assert!(forked.record_timestamp()); + assert!(forked.detached_editing()); + assert_eq!(forked.merge_interval(), 25); + assert_eq!(forked.decoded_value_cache_limit(), 8192); + assert!(forked.hide_empty_root_containers.load(Ordering::Relaxed)); + assert_eq!(forked.deleted_root_containers.lock().len(), 1); + assert!(forked + .text_style_config + .read() + .get(&InternalString::from("fork-only")) + .is_none()); + } + + #[test] + fn default_random_test_mode_uses_the_incrementing_counter_for_integer_helpers() { + let _guard = random_lock().lock().unwrap(); + let random = DefaultRandom; + + let a = random.next_u64(); + let b = random.next_u32(); + let c = random.next_i64(); + let d = random.next_i32(); + + assert_eq!(b as u64, (a + 1) as u32 as u64); + assert_eq!(c as u64, a + 2); + assert_eq!(d as u64, (a + 3) as u32 as u64); + } +} diff --git a/vendor/loro-internal/src/container.rs b/vendor/loro-internal/src/container.rs new file mode 100644 index 0000000..3e8ea7d --- /dev/null +++ b/vendor/loro-internal/src/container.rs @@ -0,0 +1,314 @@ +//! CRDT [Container]. Each container may have different CRDT type [ContainerType]. +//! Each [Op] has an associated container. It's the [Container]'s responsibility to +//! calculate the state from the [Op]s. +//! +//! Every [Container] can take a [Snapshot], which contains [crate::LoroValue] that describes the state. +//! +use crate::{arena::SharedArena, InternalString, ID}; + +pub mod list; +pub mod map; +pub mod richtext; +pub mod tree; +pub mod idx { + use super::super::ContainerType; + + /// Inner representation for ContainerID. + /// It contains the unique index for the container and the type of the container. + /// It uses top 4 bits to represent the type of the container. + /// + /// It's only used inside this crate and should not be exposed to the user. + /// + /// TODO: make this type private in this crate only + /// + /// + // During a transaction, we may create some containers which are deleted later. And these containers also need a unique ContainerIdx. + // So when we encode snapshot, we need to sort the containers by ContainerIdx and change the `container` of ops to the index of containers. + // An empty store decodes the snapshot, it will create these containers in a sequence of natural numbers so that containers and ops can correspond one-to-one + // + // TODO: PERF: use NonZeroU32 to save memory + #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)] + pub struct ContainerIdx(u32); + + impl std::fmt::Debug for ContainerIdx { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "ContainerIdx({} {})", self.get_type(), self.to_index()) + } + } + + impl std::fmt::Display for ContainerIdx { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "ContainerIdx({} {})", self.get_type(), self.to_index()) + } + } + + impl ContainerIdx { + pub(crate) const TYPE_MASK: u32 = 0b11111 << 27; + pub(crate) const INDEX_MASK: u32 = !Self::TYPE_MASK; + + #[allow(unused)] + pub(crate) fn get_type(self) -> ContainerType { + let a = (self.0 & Self::TYPE_MASK) >> 27; + if self.is_unknown() { + Self::parse_unknown_type(a) + } else { + ContainerType::try_from_u8(a as u8).unwrap() + } + } + + #[allow(unused)] + pub(crate) fn to_index(self) -> u32 { + self.0 & Self::INDEX_MASK + } + + pub(crate) fn from_index_and_type(index: u32, container_type: ContainerType) -> Self { + let prefix: u32 = if matches!(container_type, ContainerType::Unknown(_)) { + Self::unknown_to_prefix(container_type) + } else { + container_type.to_u8() as u32 + } << 27; + + Self(prefix | index) + } + + pub(crate) fn is_unknown(&self) -> bool { + self.0 >> 31 == 1 + } + + // The type_value is >>27 first, so it's 5 bits. + // we want to get the last 4 bits. so we use 0b1111 to get the last 4 bits. + fn parse_unknown_type(type_value: u32) -> ContainerType { + ContainerType::Unknown((type_value & 0b1111) as u8) + } + + // we use the top 5 bits to represent the type of the container. + // the first bit is whether it's an unknown type. + // So when we convert an unknown type to a prefix, we need to set the first bit to 1. + fn unknown_to_prefix(c: ContainerType) -> u32 { + if let ContainerType::Unknown(c) = c { + (0b10000 | c) as u32 + } else { + unreachable!() + } + } + } +} +use idx::ContainerIdx; + +pub use loro_common::ContainerType; + +pub use loro_common::ContainerID; + +#[derive(Debug)] +pub enum ContainerIdRaw { + Root { name: InternalString }, + Normal { id: ID }, +} + +pub trait IntoContainerId { + fn into_container_id(self, arena: &SharedArena, kind: ContainerType) -> ContainerID; +} + +impl IntoContainerId for String { + fn into_container_id(self, _arena: &SharedArena, kind: ContainerType) -> ContainerID { + ContainerID::Root { + name: InternalString::from(self.as_str()), + container_type: kind, + } + } +} + +impl IntoContainerId for &str { + fn into_container_id(self, _arena: &SharedArena, kind: ContainerType) -> ContainerID { + ContainerID::Root { + name: InternalString::from(self), + container_type: kind, + } + } +} + +impl IntoContainerId for ContainerID { + fn into_container_id(self, _arena: &SharedArena, _kind: ContainerType) -> ContainerID { + self + } +} + +impl IntoContainerId for &ContainerID { + fn into_container_id(self, _arena: &SharedArena, _kind: ContainerType) -> ContainerID { + self.clone() + } +} + +impl IntoContainerId for ContainerIdx { + fn into_container_id(self, arena: &SharedArena, kind: ContainerType) -> ContainerID { + assert_eq!(self.get_type(), kind); + arena.get_container_id(self).unwrap() + } +} + +impl IntoContainerId for &ContainerIdx { + fn into_container_id(self, arena: &SharedArena, kind: ContainerType) -> ContainerID { + assert_eq!(self.get_type(), kind); + arena.get_container_id(*self).unwrap() + } +} + +impl From<String> for ContainerIdRaw { + fn from(value: String) -> Self { + ContainerIdRaw::Root { name: value.into() } + } +} + +impl<'a> From<&'a str> for ContainerIdRaw { + fn from(value: &'a str) -> Self { + ContainerIdRaw::Root { name: value.into() } + } +} + +impl From<&ContainerID> for ContainerIdRaw { + fn from(id: &ContainerID) -> Self { + match id { + ContainerID::Root { name, .. } => ContainerIdRaw::Root { name: name.clone() }, + ContainerID::Normal { peer, counter, .. } => ContainerIdRaw::Normal { + id: ID::new(*peer, *counter), + }, + } + } +} + +impl From<ContainerID> for ContainerIdRaw { + fn from(id: ContainerID) -> Self { + match id { + ContainerID::Root { name, .. } => ContainerIdRaw::Root { name }, + ContainerID::Normal { peer, counter, .. } => ContainerIdRaw::Normal { + id: ID::new(peer, counter), + }, + } + } +} + +impl ContainerIdRaw { + pub fn with_type(self, container_type: ContainerType) -> ContainerID { + match self { + ContainerIdRaw::Root { name } => ContainerID::Root { + name, + container_type, + }, + ContainerIdRaw::Normal { id } => ContainerID::Normal { + peer: id.peer, + counter: id.counter, + container_type, + }, + } + } +} + +#[cfg(test)] +mod test { + use super::idx::ContainerIdx; + use super::*; + + #[test] + fn container_id_convert() { + let container_id = ContainerID::new_normal(ID::new(12, 12), ContainerType::List); + let s = container_id.to_string(); + assert_eq!(s, "cid:12@12:List"); + let actual = ContainerID::try_from(s.as_str()).unwrap(); + assert_eq!(actual, container_id); + + let container_id = ContainerID::new_root("123", ContainerType::Map); + let s = container_id.to_string(); + assert_eq!(s, "cid:root-123:Map"); + let actual = ContainerID::try_from(s.as_str()).unwrap(); + assert_eq!(actual, container_id); + + let container_id = ContainerID::new_root("kkk", ContainerType::Text); + let s = container_id.to_string(); + assert_eq!(s, "cid:root-kkk:Text"); + let actual = ContainerID::try_from(s.as_str()).unwrap(); + assert_eq!(actual, container_id); + } + + #[test] + fn container_idx_preserves_type_bits_and_index_bits() { + let idx = ContainerIdx::from_index_and_type(42, ContainerType::Text); + assert_eq!(idx.get_type(), ContainerType::Text); + assert_eq!(idx.to_index(), 42); + assert!(!idx.is_unknown()); + assert_eq!(idx.to_string(), "ContainerIdx(Text 42)"); + assert_eq!(format!("{idx:?}"), "ContainerIdx(Text 42)"); + + let max_index = + ContainerIdx::from_index_and_type(ContainerIdx::INDEX_MASK, ContainerType::MovableList); + assert_eq!(max_index.get_type(), ContainerType::MovableList); + assert_eq!(max_index.to_index(), ContainerIdx::INDEX_MASK); + + let unknown = ContainerIdx::from_index_and_type(7, ContainerType::Unknown(13)); + assert!(unknown.is_unknown()); + assert_eq!(unknown.get_type(), ContainerType::Unknown(13)); + assert_eq!(unknown.to_index(), 7); + assert_eq!(unknown.to_string(), "ContainerIdx(Unknown(13) 7)"); + } + + #[test] + fn container_id_raw_reapplies_type_for_root_and_normal_ids() { + let root = ContainerIdRaw::from("notes").with_type(ContainerType::Map); + assert_eq!(root, ContainerID::new_root("notes", ContainerType::Map)); + + let normal_id = ID::new(7, 11); + let normal = ContainerIdRaw::from(ContainerID::new_normal(normal_id, ContainerType::List)) + .with_type(ContainerType::Text); + assert_eq!( + normal, + ContainerID::new_normal(normal_id, ContainerType::Text) + ); + + let root_again = ContainerIdRaw::from(&root).with_type(ContainerType::Tree); + assert_eq!( + root_again, + ContainerID::new_root("notes", ContainerType::Tree) + ); + } + + #[test] + fn into_container_id_uses_root_names_ids_and_arena_indexes() { + let arena = SharedArena::new(); + assert_eq!( + "workspace".into_container_id(&arena, ContainerType::Map), + ContainerID::new_root("workspace", ContainerType::Map) + ); + assert_eq!( + String::from("text").into_container_id(&arena, ContainerType::Text), + ContainerID::new_root("text", ContainerType::Text) + ); + + let normal = ContainerID::new_normal(ID::new(1, 2), ContainerType::List); + assert_eq!( + (&normal).into_container_id(&arena, ContainerType::Map), + normal + ); + assert_eq!( + normal + .clone() + .into_container_id(&arena, ContainerType::Text), + normal + ); + + let idx = arena.register_container(&normal); + assert_eq!(idx.into_container_id(&arena, ContainerType::List), normal); + assert_eq!( + (&idx).into_container_id(&arena, ContainerType::List), + normal + ); + } + + #[test] + #[should_panic(expected = "assertion `left == right` failed")] + fn into_container_id_rejects_mismatched_index_type() { + let arena = SharedArena::new(); + let id = ContainerID::new_root("items", ContainerType::List); + let idx = arena.register_container(&id); + + let _ = idx.into_container_id(&arena, ContainerType::Map); + } +} diff --git a/vendor/loro-internal/src/container/list/list_op.rs b/vendor/loro-internal/src/container/list/list_op.rs new file mode 100644 index 0000000..8aa332e --- /dev/null +++ b/vendor/loro-internal/src/container/list/list_op.rs @@ -0,0 +1,818 @@ +use std::ops::Range; + +use append_only_bytes::BytesSlice; +use enum_as_inner::EnumAsInner; +use loro_common::{ContainerType, HasId, HasIdSpan, IdLp, LoroError, LoroResult, LoroValue, ID}; +use rle::{HasLength, Mergable, Sliceable}; +use serde::{Deserialize, Serialize}; + +use crate::{ + container::richtext::richtext_state::unicode_to_utf8_index, + container::richtext::tracker::UNKNOWN_SPAN_LEN, + container::richtext::TextStyleInfoFlag, + op::{ListSlice, ValueSlice}, + InternalString, +}; + +/// `len` and `pos` is measured in unicode char for text. +// Note: It will be encoded into binary format, so the order of its fields should not be changed. +#[derive(EnumAsInner, Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum ListOp<'a> { + Insert { + slice: ListSlice<'a>, + pos: usize, + }, + Delete(DeleteSpanWithId), + Move { + from: u32, + to: u32, + elem_id: IdLp, + }, + Set { + elem_id: IdLp, + value: LoroValue, + }, + /// StyleStart and StyleEnd must be paired because the end of a style must take an OpID position. + StyleStart { + start: u32, + end: u32, + key: InternalString, + info: TextStyleInfoFlag, + value: LoroValue, + }, + StyleEnd, +} + +#[derive(EnumAsInner, Debug, Clone)] +pub enum InnerListOp { + // TODO: this is only used for list now? We should rename it to InsertList + Insert { + slice: ValueSlice, + pos: usize, + }, + // Note: len may not equal to slice.len() because for text len is unicode len while the slice + // is utf8 bytes. + InsertText { + slice: BytesSlice, + unicode_len: u32, + pos: u32, + }, + Delete(DeleteSpanWithId), + Move { + from: u32, + /// Element id + elem_id: IdLp, + to: u32, + }, + Set { + elem_id: IdLp, + value: LoroValue, + }, + /// StyleStart and StyleEnd must be paired. + /// The next op of StyleStart must be StyleEnd. + StyleStart { + start: u32, + end: u32, + key: InternalString, + value: LoroValue, + info: TextStyleInfoFlag, + }, + StyleEnd, +} + +impl ListOp<'_> { + pub fn new_del(id_start: ID, pos: usize, len: usize) -> Self { + assert!(len != 0); + Self::Delete(DeleteSpanWithId::new(id_start, pos as isize, len as isize)) + } +} + +impl InnerListOp { + /// Reject positions that no real sequence can reach. + /// + /// Diff calculation replays ops on a tracker whose unreplayed history is one + /// placeholder span of [`UNKNOWN_SPAN_LEN`] items, and positions past it panic + /// inside the tracker. Positions are op-index based (deleted items included), so + /// a valid document stays many orders of magnitude below this. Smaller + /// out-of-bounds positions are rejected later by state validation. + pub(crate) fn check_positions(&self) -> LoroResult<()> { + const MAX_POS: i64 = UNKNOWN_SPAN_LEN as i64 - 1; + let in_range = |pos: i64| (0..=MAX_POS).contains(&pos); + let ok = match self { + InnerListOp::Insert { pos, .. } => in_range(*pos as i64), + InnerListOp::InsertText { pos, .. } => in_range(*pos as i64), + InnerListOp::Delete(span) => { + in_range(span.start() as i64) && in_range(span.last() as i64) + } + InnerListOp::Move { from, to, .. } => in_range(*from as i64) && in_range(*to as i64), + InnerListOp::StyleStart { start, end, .. } => { + in_range(*start as i64) && in_range(*end as i64) + } + InnerListOp::Set { .. } | InnerListOp::StyleEnd => true, + }; + if ok { + Ok(()) + } else { + Err(LoroError::DecodeError( + format!("Sequence op position is out of range: {self:?}").into_boxed_str(), + )) + } + } + + pub fn new_del(id: ID, pos: usize, len: isize) -> Self { + assert!(len != 0); + Self::Delete(DeleteSpanWithId { + id_start: id, + span: DeleteSpan { + pos: pos as isize, + signed_len: len, + }, + }) + } + + pub(crate) fn estimate_storage_size(&self, container_type: ContainerType) -> usize { + match self { + InnerListOp::Insert { slice, .. } => match container_type { + ContainerType::MovableList | ContainerType::List => 4 * slice.atom_len(), + ContainerType::Text => slice.atom_len(), + _ => unreachable!(), + }, + InnerListOp::InsertText { slice, .. } => slice.len(), + InnerListOp::Delete(..) => 8, + InnerListOp::Move { .. } => 8, + InnerListOp::Set { .. } => 7, + InnerListOp::StyleStart { .. } => 10, + InnerListOp::StyleEnd => 1, + } + } +} + +impl HasLength for DeleteSpan { + fn content_len(&self) -> usize { + self.signed_len.unsigned_abs() + } +} + +/// Delete span that the initial id is `id_start`. +/// +/// This span may be reversed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct DeleteSpanWithId { + /// This is the target id with the smallest counter no matter whether the span is reversed. + /// So it's always the id of the leftmost element of the target span. + pub id_start: ID, + /// The deleted position span + pub span: DeleteSpan, +} + +impl DeleteSpanWithId { + pub fn new(id_start: ID, pos: isize, len: isize) -> Self { + debug_assert!(len != 0); + Self { + id_start, + span: DeleteSpan { + pos, + signed_len: len, + }, + } + } + + #[inline] + pub fn start(&self) -> isize { + self.span.start() + } + + #[inline] + pub fn end(&self) -> isize { + self.span.end() + } + + #[inline] + pub fn last(&self) -> isize { + self.span.last() + } + + #[inline] + pub fn is_reversed(&self) -> bool { + self.span.is_reversed() + } +} + +impl HasLength for DeleteSpanWithId { + fn content_len(&self) -> usize { + self.span.content_len() + } +} + +impl HasId for DeleteSpanWithId { + fn id_start(&self) -> ID { + self.id_start + } +} + +impl Mergable for DeleteSpanWithId { + /// If two spans are mergeable, their ids should be continuous. + /// LHS's end id should be equal to RHS's start id. + /// But their spans may be in a reversed order. + fn is_mergable(&self, rhs: &Self, _conf: &()) -> bool + where + Self: Sized, + { + let this = self.span; + let other = rhs.span; + // merge continuous deletions: + // note that the previous deletions will affect the position of the later deletions + match (self.span.bidirectional(), rhs.span.bidirectional()) { + (true, true) => { + (this.pos == other.pos && self.id_start.inc(1) == rhs.id_start) + || (this.pos == other.pos + 1 && self.id_start == rhs.id_start.inc(1)) + } + (true, false) => { + if this.pos == other.prev_pos() { + if other.signed_len > 0 { + self.id_start.inc(1) == rhs.id_start + } else { + self.id_start == rhs.id_end() + } + } else { + false + } + } + (false, true) => { + if this.next_pos() == other.pos { + if this.signed_len > 0 { + self.id_end() == rhs.id_start + } else { + self.id_start == rhs.id_start.inc(1) + } + } else { + false + } + } + (false, false) => { + if this.next_pos() == other.pos && this.direction() == other.direction() { + if self.span.signed_len > 0 { + self.id_end() == rhs.id_start + } else { + self.id_start == rhs.id_end() + } + } else { + false + } + } + } + } + + fn merge(&mut self, rhs: &Self, _conf: &()) + where + Self: Sized, + { + self.id_start.counter = rhs.id_start.counter.min(self.id_start.counter); + self.span.merge(&rhs.span, &()) + } +} + +impl Sliceable for DeleteSpanWithId { + fn slice(&self, from: usize, to: usize) -> Self { + Self { + id_start: if self.span.signed_len > 0 { + self.id_start.inc(from as i32) + } else { + // If the span is reversed, the id_start should be affected by `to` + // + // Example: + // + // a b c + // - - - <-- deletions happen backward + // 0 1 2 <-- counter of the IDs + // ↑ + // id_start + // + // If from=1, to=2 + // a b c + // - - - <-- deletions happen backward + // 0 1 2 <-- counter of the IDs + // ↑ + // id_start + self.id_start.inc((self.atom_len() - to) as i32) + }, + span: self.span.slice(from, to), + } + } +} + +/// `len` can be negative so that we can merge text deletions efficiently. +/// It looks like [crate::span::CounterSpan], but how should they merge ([Mergable] impl) and slice ([Sliceable] impl) are very different +/// +/// len cannot be zero; +/// +/// pos: 5, len: -3 eq a range of (2, 5] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +// Note: It will be encoded into binary format, so the order of its fields should not be changed. +pub struct DeleteSpan { + pub pos: isize, + pub signed_len: isize, +} + +impl DeleteSpan { + pub fn new(pos: isize, len: isize) -> Self { + debug_assert!(len != 0); + Self { + pos, + signed_len: len, + } + } + + #[inline(always)] + pub fn start(&self) -> isize { + if self.signed_len > 0 { + self.pos + } else { + self.pos + 1 + self.signed_len + } + } + + #[inline(always)] + pub fn last(&self) -> isize { + if self.signed_len > 0 { + self.pos + self.signed_len - 1 + } else { + self.pos + } + } + + #[inline(always)] + pub fn end(&self) -> isize { + if self.signed_len > 0 { + self.pos + self.signed_len + } else { + self.pos + 1 + } + } + + #[inline(always)] + pub fn to_range(self) -> Range<isize> { + self.start()..self.end() + } + + #[inline(always)] + pub fn to_urange(self) -> Range<usize> { + self.start() as usize..self.end() as usize + } + + #[inline(always)] + pub fn bidirectional(&self) -> bool { + self.signed_len.abs() == 1 + } + + #[inline(always)] + pub fn is_reversed(&self) -> bool { + self.signed_len < 0 + } + + #[inline(always)] + pub fn direction(&self) -> isize { + if self.signed_len > 0 { + 1 + } else { + -1 + } + } + + #[inline(always)] + pub fn next_pos(&self) -> isize { + if self.signed_len > 0 { + self.start() + } else { + self.start() - 1 + } + } + + #[inline(always)] + pub fn prev_pos(&self) -> isize { + if self.signed_len > 0 { + self.pos + } else { + self.end() + } + } + + pub fn len(&self) -> usize { + self.signed_len.unsigned_abs() + } +} + +impl Mergable for DeleteSpan { + fn is_mergable(&self, other: &Self, _conf: &()) -> bool + where + Self: Sized, + { + // merge continuous deletions: + // note that the previous deletions will affect the position of the later deletions + match (self.bidirectional(), other.bidirectional()) { + (true, true) => self.pos == other.pos || self.pos == other.pos + 1, + (true, false) => self.pos == other.prev_pos(), + (false, true) => self.next_pos() == other.pos, + (false, false) => self.next_pos() == other.pos && self.direction() == other.direction(), + } + } + + fn merge(&mut self, other: &Self, _conf: &()) + where + Self: Sized, + { + match (self.bidirectional(), other.bidirectional()) { + (true, true) => { + if self.pos == other.pos { + self.signed_len = 2; + } else if self.pos == other.pos + 1 { + self.signed_len = -2; + } else { + unreachable!() + } + } + (true, false) => { + assert!(self.pos == other.prev_pos()); + self.signed_len = other.signed_len + other.direction(); + } + (false, true) => { + assert!(self.next_pos() == other.pos); + self.signed_len += self.direction(); + } + (false, false) => { + assert!(self.next_pos() == other.pos && self.direction() == other.direction()); + self.signed_len += other.signed_len; + } + } + } +} + +impl Sliceable for DeleteSpan { + fn slice(&self, from: usize, to: usize) -> Self { + if self.signed_len > 0 { + Self::new(self.pos, to as isize - from as isize) + } else { + Self::new(self.pos - from as isize, from as isize - to as isize) + } + } +} + +impl Mergable for ListOp<'_> { + fn is_mergable(&self, _other: &Self, _conf: &()) -> bool + where + Self: Sized, + { + match self { + ListOp::Insert { pos, slice } => match _other { + ListOp::Insert { + pos: other_pos, + slice: other_slice, + } => pos + slice.content_len() == *other_pos && slice.is_mergable(other_slice, &()), + _ => false, + }, + &ListOp::Delete(span) => match _other { + ListOp::Delete(other_span) => span.is_mergable(other_span, &()), + _ => false, + }, + ListOp::StyleStart { .. } + | ListOp::StyleEnd { .. } + | ListOp::Move { .. } + | ListOp::Set { .. } => false, + } + } + + fn merge(&mut self, _other: &Self, _conf: &()) + where + Self: Sized, + { + match self { + ListOp::Insert { slice, .. } => match _other { + ListOp::Insert { + slice: other_slice, .. + } => { + slice.merge(other_slice, &()); + } + _ => unreachable!(), + }, + ListOp::Delete(span) => match _other { + ListOp::Delete(other_span) => span.merge(other_span, &()), + _ => unreachable!(), + }, + ListOp::StyleStart { .. } + | ListOp::StyleEnd { .. } + | ListOp::Move { .. } + | ListOp::Set { .. } => { + unreachable!() + } + } + } +} + +impl HasLength for ListOp<'_> { + fn content_len(&self) -> usize { + match self { + ListOp::Insert { slice, .. } => slice.content_len(), + ListOp::Delete(span) => span.atom_len(), + ListOp::StyleStart { .. } + | ListOp::StyleEnd { .. } + | ListOp::Move { .. } + | ListOp::Set { .. } => 1, + } + } +} + +impl Sliceable for ListOp<'_> { + fn slice(&self, from: usize, to: usize) -> Self { + match self { + ListOp::Insert { slice, pos } => ListOp::Insert { + slice: slice.slice(from, to), + pos: *pos + from, + }, + ListOp::Delete(span) => ListOp::Delete(span.slice(from, to)), + a @ (ListOp::StyleStart { .. } + | ListOp::StyleEnd { .. } + | ListOp::Move { .. } + | ListOp::Set { .. }) => a.clone(), + } + } +} + +impl Mergable for InnerListOp { + fn is_mergable(&self, other: &Self, _conf: &()) -> bool + where + Self: Sized, + { + match (self, other) { + ( + InnerListOp::Insert { pos, slice, .. }, + InnerListOp::Insert { + pos: other_pos, + slice: other_slice, + .. + }, + ) => pos + slice.content_len() == *other_pos && slice.is_mergable(other_slice, &()), + (InnerListOp::Delete(span), InnerListOp::Delete(other_span)) => { + span.is_mergable(other_span, &()) + } + ( + InnerListOp::InsertText { + slice, + pos, + unicode_len: len, + }, + InnerListOp::InsertText { + slice: other_slice, + pos: other_pos, + unicode_len: _, + }, + ) => pos + len == *other_pos && slice.can_merge(other_slice), + _ => false, + } + } + + fn merge(&mut self, other: &Self, _conf: &()) + where + Self: Sized, + { + match (self, other) { + ( + InnerListOp::Insert { slice, .. }, + InnerListOp::Insert { + slice: other_slice, .. + }, + ) => { + slice.merge(other_slice, &()); + } + (InnerListOp::Delete(span), InnerListOp::Delete(other_span)) => { + span.merge(other_span, &()) + } + ( + InnerListOp::InsertText { + slice, + unicode_len: len, + .. + }, + InnerListOp::InsertText { + slice: other_slice, + unicode_len: other_len, + .. + }, + ) => { + slice.merge(other_slice, &()); + *len += *other_len; + } + _ => unreachable!(), + } + } +} + +impl HasLength for InnerListOp { + fn content_len(&self) -> usize { + match self { + InnerListOp::Insert { slice, .. } => slice.content_len(), + InnerListOp::InsertText { + unicode_len: len, .. + } => *len as usize, + InnerListOp::Delete(span) => span.atom_len(), + InnerListOp::StyleStart { .. } + | InnerListOp::StyleEnd + | InnerListOp::Move { .. } + | InnerListOp::Set { .. } => 1, + } + } +} + +impl Sliceable for InnerListOp { + fn slice(&self, from: usize, to: usize) -> Self { + match self { + InnerListOp::Insert { slice, pos } => InnerListOp::Insert { + slice: slice.slice(from, to), + pos: *pos + from, + }, + InnerListOp::InsertText { + slice, + unicode_len, + pos, + } => InnerListOp::InsertText { + slice: { + // SAFETY: we know it's a valid utf8 string + let s = unsafe { std::str::from_utf8_unchecked(slice) }; + let total_unicode_len = *unicode_len as usize; + let total_bytes_len = slice.len(); + let (from_byte, to_byte) = if total_bytes_len == total_unicode_len { + // ASCII fast path: unicode index equals byte offset. + (from, to) + } else { + let from_byte = if from == 0 { + 0 + } else { + unicode_to_utf8_index(s, from).expect("unicode index should be valid") + }; + let to_byte = if to == total_unicode_len { + total_bytes_len + } else { + unicode_to_utf8_index(s, to).expect("unicode index should be valid") + }; + (from_byte, to_byte) + }; + + slice.slice(from_byte, to_byte) + }, + unicode_len: (to - from) as u32, + pos: *pos + from as u32, + }, + InnerListOp::Delete(span) => InnerListOp::Delete(span.slice(from, to)), + InnerListOp::StyleStart { .. } + | InnerListOp::StyleEnd + | InnerListOp::Move { .. } + | InnerListOp::Set { .. } => { + assert!(from == 0 && to == 1); + self.clone() + } + } + } +} + +#[cfg(test)] +mod test { + use append_only_bytes::BytesSlice; + use loro_common::ID; + use rle::{HasLength as _, Mergable, Sliceable}; + use std::time::Instant; + + use crate::{container::list::list_op::DeleteSpanWithId, op::ListSlice}; + + use super::{DeleteSpan, InnerListOp, ListOp}; + + #[test] + fn fix_fields_order() { + let list_op = vec![ + ListOp::Insert { + pos: 0, + slice: ListSlice::from_borrowed_str(""), + }, + ListOp::Delete(DeleteSpanWithId::new(ID::new(0, 0), 0, 3)), + ]; + let actual = postcard::to_allocvec(&list_op).unwrap(); + let list_op_buf = vec![2, 0, 1, 0, 0, 0, 1, 0, 0, 0, 6]; + assert_eq!(&actual, &list_op_buf); + assert_eq!( + postcard::from_bytes::<Vec<ListOp>>(&list_op_buf).unwrap(), + list_op + ); + + let delete_span = DeleteSpan { + pos: 0, + signed_len: 3, + }; + let delete_span_buf = vec![0, 6]; + assert_eq!( + postcard::from_bytes::<DeleteSpan>(&delete_span_buf).unwrap(), + delete_span + ); + } + + #[test] + fn test_del_span_merge_slice() { + let a = DeleteSpan::new(0, 100); + let mut b = a.slice(0, 1); + let c = a.slice(1, 100); + b.merge(&c, &()); + assert_eq!(b, a); + + // reverse + let a = DeleteSpan::new(99, -100); + let mut b = a.slice(0, 1); + let c = a.slice(1, 100); + b.merge(&c, &()); + assert_eq!(b, a); + + // merge bidirectional + let mut a = DeleteSpan::new(1, -1); + let b = DeleteSpan::new(1, -1); + assert!(a.is_mergable(&b, &())); + a.merge(&b, &()); + assert_eq!(a, DeleteSpan::new(1, 2)); + + let mut a = DeleteSpan::new(1, -1); + let b = DeleteSpan::new(0, -1); + assert_eq!(b.to_range(), 0..1); + assert!(a.is_mergable(&b, &())); + a.merge(&b, &()); + assert_eq!(a, DeleteSpan::new(1, -2)); + + // not merging + let a = DeleteSpan::new(4, 1); + let b = DeleteSpan::new(5, 2); + assert!(!a.is_mergable(&b, &())); + + // next/prev span + let a = DeleteSpan::new(6, -2); + assert_eq!(a.next_pos(), 4); + assert_eq!(a.prev_pos(), 7); + let a = DeleteSpan::new(6, 2); + assert_eq!(a.next_pos(), 6); + assert_eq!(a.prev_pos(), 6); + assert!(a.slice(0, 1).is_mergable(&a.slice(1, 2), &())); + + // neg merge + let mut a = DeleteSpan::new(1, 1); + let b = DeleteSpan::new(0, 1); + a.merge(&b, &()); + assert_eq!(a, DeleteSpan::new(1, -2)); + assert_eq!(a.slice(0, 1), DeleteSpan::new(1, -1)); + assert_eq!(a.slice(1, 2), DeleteSpan::new(0, -1)); + assert_eq!(a.slice(0, 1).to_range(), 1..2); + assert_eq!(a.slice(1, 2).to_range(), 0..1); + } + + #[test] + fn mergeable() { + let a = DeleteSpan::new(14852, 1); + let mut a_with_id = DeleteSpanWithId { + id_start: ID::new(0, 9), + span: a, + }; + let b = DeleteSpan::new(14851, 1); + let b_with_id = DeleteSpanWithId { + id_start: ID::new(0, 8), + span: b, + }; + assert!(a_with_id.is_mergable(&b_with_id, &())); + a_with_id.merge(&b_with_id, &()); + assert!(a_with_id.span.signed_len == -2); + } + + #[test] + #[ignore] + fn perf_insert_text_slice_split_suffix() { + // Run with: + // cargo test -p loro-internal perf_insert_text_slice_split_suffix -- --ignored --nocapture + const TEXT_LEN: usize = 2 * 1024 * 1024; + const CHUNK_UNICODE_LEN: usize = 4096; + + let text = "a".repeat(TEXT_LEN); + let slice = BytesSlice::from_bytes(text.as_bytes()); + let mut op = InnerListOp::InsertText { + slice, + unicode_len: TEXT_LEN as u32, + pos: 0, + }; + + let start = Instant::now(); + let mut total = 0usize; + while op.content_len() > CHUNK_UNICODE_LEN { + let end = CHUNK_UNICODE_LEN.min(op.content_len()); + let _prefix = op.slice(0, end); + op = op.slice(end, op.content_len()); + total += end; + } + total += op.content_len(); + let elapsed = start.elapsed(); + assert_eq!(total, TEXT_LEN); + println!( + "perf_insert_text_slice_split_suffix: text_len={}, chunk_unicode_len={}, elapsed={:?}", + TEXT_LEN, CHUNK_UNICODE_LEN, elapsed + ); + } +} diff --git a/vendor/loro-internal/src/container/list/mod.rs b/vendor/loro-internal/src/container/list/mod.rs new file mode 100644 index 0000000..1da3d62 --- /dev/null +++ b/vendor/loro-internal/src/container/list/mod.rs @@ -0,0 +1 @@ +pub(crate) mod list_op; diff --git a/vendor/loro-internal/src/container/map/map_content.rs b/vendor/loro-internal/src/container/map/map_content.rs new file mode 100644 index 0000000..993718a --- /dev/null +++ b/vendor/loro-internal/src/container/map/map_content.rs @@ -0,0 +1,42 @@ +use rle::{HasLength, Mergable, Sliceable}; +use serde::{Deserialize, Serialize}; + +use crate::{InternalString, LoroValue}; + +// Note: It will be encoded into binary format, so the order of its fields should not be changed. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct MapSet { + pub(crate) key: InternalString, + // the key is deleted if value is None + pub(crate) value: Option<LoroValue>, +} + +impl Mergable for MapSet {} +impl Sliceable for MapSet { + fn slice(&self, from: usize, to: usize) -> Self { + assert!(from == 0 && to == 1); + self.clone() + } +} +impl HasLength for MapSet { + fn content_len(&self) -> usize { + 1 + } +} + +#[cfg(test)] +mod test { + use super::MapSet; + #[test] + fn fix_fields_order() { + let map_set = vec![MapSet { + key: "key".to_string().into(), + value: Some("value".to_string().into()), + }]; + let map_set_buf = vec![1, 3, 107, 101, 121, 1, 4, 5, 118, 97, 108, 117, 101]; + assert_eq!( + postcard::from_bytes::<Vec<MapSet>>(&map_set_buf).unwrap(), + map_set + ); + } +} diff --git a/vendor/loro-internal/src/container/map/mod.rs b/vendor/loro-internal/src/container/map/mod.rs new file mode 100644 index 0000000..1a66786 --- /dev/null +++ b/vendor/loro-internal/src/container/map/mod.rs @@ -0,0 +1,3 @@ +mod map_content; + +pub(crate) use map_content::MapSet; diff --git a/vendor/loro-internal/src/container/richtext.rs b/vendor/loro-internal/src/container/richtext.rs new file mode 100644 index 0000000..20bbfb1 --- /dev/null +++ b/vendor/loro-internal/src/container/richtext.rs @@ -0,0 +1,300 @@ +//! # Index +//! +//! There are several types of indexes: +//! +//! - Unicode index: the index of a unicode code point in the text. +//! - Entity index: unicode index + style anchor index. Each unicode code point or style anchor is an entity. +//! - Utf16 index +//! +//! In [crate::op::Op], we always use entity index to persist richtext ops. +//! +//! The users of this type can only operate on unicode index or utf16 index, but calculated entity index will be provided. + +pub(crate) mod config; +mod fugue_span; +pub(crate) mod richtext_state; +pub(crate) mod str_slice; +mod style_range_map; +#[cfg(all(test, miri))] +mod tinyvec; +pub(crate) mod tracker; + +use crate::{change::Lamport, delta::StyleMeta, utils::string_slice::StringSlice, InternalString}; +use fugue_span::*; +use loro_common::{Counter, IdFull, IdLp, LoroValue, PeerID, ID}; +use serde::{Deserialize, Serialize}; +use std::fmt::Debug; + +pub(crate) use fugue_span::{RichtextChunk, RichtextChunkValue}; +pub(crate) use richtext_state::RichtextState; +pub(crate) use style_range_map::Styles; +pub(crate) use tracker::{CrdtRopeDelta, Tracker as RichtextTracker}; + +/// This is the data structure that represents a span of rich text. +/// It's used to communicate with the frontend. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct RichtextSpan { + pub text: StringSlice, + pub attributes: StyleMeta, +} + +/// This is used to communicate with the frontend. +#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct Style { + pub key: InternalString, + pub data: LoroValue, +} + +// TODO: change visibility back to crate after #116 is done +#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct StyleOp { + pub(crate) lamport: Lamport, + pub(crate) peer: PeerID, + pub(crate) cnt: Counter, + pub(crate) key: InternalString, + pub(crate) value: LoroValue, + pub(crate) info: TextStyleInfoFlag, +} + +#[derive(Debug, Hash, Eq, PartialEq, Clone, Serialize, Deserialize)] +pub(crate) enum StyleKey { + Key(InternalString), +} + +impl StyleKey { + pub fn key(&self) -> &InternalString { + match self { + Self::Key(key) => key, + } + } +} + +impl StyleOp { + pub fn to_style(&self) -> Style { + Style { + key: self.key.clone(), + data: self.value.clone(), + } + } + + pub fn to_value(&self) -> LoroValue { + self.value.clone() + } + + pub(crate) fn get_style_key(&self) -> StyleKey { + StyleKey::Key(self.key.clone()) + } + + #[cfg(test)] + pub fn new_for_test(n: isize, key: &str, value: LoroValue, info: TextStyleInfoFlag) -> Self { + Self { + lamport: n as Lamport, + peer: n as PeerID, + cnt: n as Counter, + key: key.to_string().into(), + value, + info, + } + } + + #[inline(always)] + pub fn id(&self) -> ID { + ID::new(self.peer, self.cnt) + } + + pub fn idlp(&self) -> IdLp { + IdLp::new(self.peer, self.lamport) + } + + pub fn id_full(&self) -> IdFull { + IdFull::new(self.peer, self.cnt, self.lamport) + } +} + +impl PartialOrd for StyleOp { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for StyleOp { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.lamport + .cmp(&other.lamport) + .then(self.peer.cmp(&other.peer)) + } +} + +/// TODO: We can remove this type already +/// +/// A compact representation of a rich text style config. +/// +/// Note: we assume style with the same key has the same `Mergeable` and `isContainer` value. +/// +/// - 0 (1st bit) +/// - Expand Before (2nd bit): when inserting new text before this style, whether the new text should inherit this style. +/// - Expand After (3rd bit): when inserting new text after this style, whether the new text should inherit this style. +/// - 0 (4th bit): +/// - 0 (5th bit): +/// - 0 (6th bit) +/// - 0 (7th bit) +/// - 0 (8th bit): +#[derive(Default, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)] +pub struct TextStyleInfoFlag { + data: u8, +} + +impl Debug for TextStyleInfoFlag { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TextStyleInfo") + // write data in binary format + .field("data", &format!("{:#010b}", self.data)) + .field("expand_before", &self.expand_before()) + .field("expand_after", &self.expand_after()) + .finish() + } +} + +const EXPAND_BEFORE_MASK: u8 = 0b0000_0010; +const EXPAND_AFTER_MASK: u8 = 0b0000_0100; +const ALIVE_MASK: u8 = 0b1000_0000; + +/// Whether to expand the style when inserting new text around it. +/// +/// - Before: when inserting new text before this style, the new text should inherit this style. +/// - After: when inserting new text after this style, the new text should inherit this style. +/// - Both: when inserting new text before or after this style, the new text should inherit this style. +/// - None: when inserting new text before or after this style, the new text should **not** inherit this style. +#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)] +pub enum ExpandType { + Before, + After, + Both, + None, +} + +#[derive( + Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, serde::Serialize, serde::Deserialize, +)] +pub enum AnchorType { + Start, + End, +} + +impl ExpandType { + #[inline(always)] + pub const fn expand_before(&self) -> bool { + matches!(self, ExpandType::Before | ExpandType::Both) + } + + #[inline(always)] + pub const fn expand_after(&self) -> bool { + matches!(self, ExpandType::After | ExpandType::Both) + } + + /// 'before'|'after'|'both'|'none' + pub fn try_from_str(s: &str) -> Option<Self> { + match s { + "before" => Some(ExpandType::Before), + "after" => Some(ExpandType::After), + "both" => Some(ExpandType::Both), + "none" => Some(ExpandType::None), + _ => None, + } + } + + /// Toggle expand type between for deletion and for creation + /// + /// For a style that expand after, when we delete the style, we need to have another style that expands after to nullify it, + /// so that the expand behavior is not changed. + /// + /// Before -> Before + /// After -> After + /// Both -> None + /// None -> Both + /// + /// Because the creation of text styles and the deletion of the text styles have reversed expand type. + /// This method is useful to convert between the two + pub const fn reverse(self) -> Self { + match self { + ExpandType::Before => ExpandType::Before, + ExpandType::After => ExpandType::After, + ExpandType::Both => ExpandType::None, + ExpandType::None => ExpandType::Both, + } + } +} + +impl TextStyleInfoFlag { + /// When inserting new text around this style, prefer inserting after it. + #[inline(always)] + pub const fn expand_before(self) -> bool { + self.data & EXPAND_BEFORE_MASK != 0 + } + + /// When inserting new text around this style, prefer inserting before it. + #[inline(always)] + pub const fn expand_after(self) -> bool { + self.data & EXPAND_AFTER_MASK != 0 + } + + pub const fn expand_type(self) -> ExpandType { + match (self.expand_before(), self.expand_after()) { + (true, true) => ExpandType::Both, + (true, false) => ExpandType::Before, + (false, true) => ExpandType::After, + (false, false) => ExpandType::None, + } + } + + /// This method tells that when we can insert text before/after this style anchor, whether we insert the new text before the anchor. + #[inline] + pub fn prefer_insert_before(self, anchor_type: AnchorType) -> bool { + match anchor_type { + AnchorType::Start => { + // If we need to expand the style, the new text should be inserted **after** the start anchor + !self.expand_before() + } + AnchorType::End => { + // If we need to expand the style, the new text should be inserted **before** the end anchor + self.expand_after() + } + } + } + + pub const fn new(expand_type: ExpandType) -> Self { + let mut data = ALIVE_MASK; + if expand_type.expand_before() { + data |= EXPAND_BEFORE_MASK; + } + if expand_type.expand_after() { + data |= EXPAND_AFTER_MASK; + } + + TextStyleInfoFlag { data } + } + + #[inline(always)] + pub const fn to_delete(self) -> Self { + TextStyleInfoFlag::new(self.expand_type().reverse()) + } + + pub const BOLD: TextStyleInfoFlag = TextStyleInfoFlag::new(ExpandType::After); + pub const LINK: TextStyleInfoFlag = TextStyleInfoFlag::new(ExpandType::None); + pub const COMMENT: TextStyleInfoFlag = TextStyleInfoFlag::new(ExpandType::None); + + pub const fn to_byte(&self) -> u8 { + self.data + } + + pub const fn from_byte(data: u8) -> Self { + Self { data } + } +} + +#[cfg(test)] +mod test { + + #[test] + fn test() {} +} diff --git a/vendor/loro-internal/src/container/richtext/config.rs b/vendor/loro-internal/src/container/richtext/config.rs new file mode 100644 index 0000000..8c89264 --- /dev/null +++ b/vendor/loro-internal/src/container/richtext/config.rs @@ -0,0 +1,133 @@ +use loro_common::InternalString; +use rustc_hash::FxHashMap; + +use super::{ExpandType, TextStyleInfoFlag}; + +#[derive(Debug, Default, Clone)] +pub struct StyleConfigMap { + pub(crate) map: FxHashMap<InternalString, StyleConfig>, + pub(crate) default_style: Option<StyleConfig>, +} + +impl StyleConfigMap { + pub fn new() -> Self { + Self { + map: FxHashMap::default(), + default_style: None, + } + } + + pub fn insert(&mut self, key: InternalString, value: StyleConfig) { + if key.contains(':') { + panic!("style key should not contain ':'"); + } + + self.map.insert(key, value); + } + + pub fn get(&self, key: &InternalString) -> Option<StyleConfig> { + self.map.get(key).copied().or(self.default_style) + } + + pub fn get_style_flag(&self, key: &InternalString) -> Option<TextStyleInfoFlag> { + self._get_style_flag(key, false) + } + + pub fn get_style_flag_for_unmark(&self, key: &InternalString) -> Option<TextStyleInfoFlag> { + self._get_style_flag(key, true) + } + + fn _get_style_flag(&self, key: &InternalString, is_del: bool) -> Option<TextStyleInfoFlag> { + let f = |x: StyleConfig| { + TextStyleInfoFlag::new(if is_del { x.expand.reverse() } else { x.expand }) + }; + if let Some(index) = key.find(':') { + let key = key[..index].into(); + self.map.get(&key).copied().or(self.default_style).map(f) + } else { + self.map.get(key).copied().or(self.default_style).map(f) + } + } + + pub fn default_rich_text_config() -> Self { + let mut map = Self { + map: FxHashMap::default(), + default_style: None, + }; + + map.map.insert( + "bold".into(), + StyleConfig { + expand: ExpandType::After, + }, + ); + + map.map.insert( + "italic".into(), + StyleConfig { + expand: ExpandType::After, + }, + ); + + map.map.insert( + "underline".into(), + StyleConfig { + expand: ExpandType::After, + }, + ); + + map.map.insert( + "link".into(), + StyleConfig { + expand: ExpandType::None, + }, + ); + + map.map.insert( + "highlight".into(), + StyleConfig { + expand: ExpandType::None, + }, + ); + + map.map.insert( + "comment".into(), + StyleConfig { + expand: ExpandType::None, + }, + ); + + map.map.insert( + "code".into(), + StyleConfig { + expand: ExpandType::None, + }, + ); + + map + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct StyleConfig { + pub expand: ExpandType, +} + +impl StyleConfig { + pub fn new() -> Self { + Self { + expand: ExpandType::None, + } + } + + pub fn expand(mut self, expand: ExpandType) -> Self { + self.expand = expand; + self + } +} + +impl Default for StyleConfig { + fn default() -> Self { + Self::new() + } +} diff --git a/vendor/loro-internal/src/container/richtext/fugue_span.rs b/vendor/loro-internal/src/container/richtext/fugue_span.rs new file mode 100644 index 0000000..6968078 --- /dev/null +++ b/vendor/loro-internal/src/container/richtext/fugue_span.rs @@ -0,0 +1,386 @@ +use std::ops::Range; + +use generic_btree::rle::{CanRemove, HasLength, Mergeable, Sliceable, TryInsert}; +use loro_common::{CompactId, Counter, HasId, IdFull, IdSpan, Lamport, ID}; +use serde::{Deserialize, Serialize}; + +use super::{tracker::UNKNOWN_PEER_ID, AnchorType}; + +#[derive(Clone, PartialEq, Eq, Copy, Serialize, Deserialize)] +pub(crate) struct RichtextChunk { + start: u32, + end: u32, +} + +impl std::fmt::Debug for RichtextChunk { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RichtextChunk") + .field("value", &self.value()) + .finish() + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Copy)] +pub(crate) enum RichtextChunkKind { + Text, + StyleAnchor, + Unknown, + /// Move anchor is a special anchor that is used to mark the FugueSpan created + /// by a move operation. + MoveAnchor, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum RichtextChunkValue { + Text(Range<u32>), + StyleAnchor { + id: u32, + anchor_type: AnchorType, + }, + Unknown(u32), + /// Move anchor is a special anchor that is used to mark the FugueSpan created + /// by a move operation. + MoveAnchor, +} + +impl RichtextChunk { + pub(crate) const UNKNOWN: u32 = u32::MAX; + pub(crate) const START_STYLE_ANCHOR: u32 = u32::MAX - 1; + pub(crate) const END_STYLE_ANCHOR: u32 = u32::MAX - 2; + pub(crate) const MOVE_ANCHOR: u32 = u32::MAX - 3; + + #[inline] + pub fn new_text(range: Range<u32>) -> Self { + Self { + start: range.start, + end: range.end, + } + } + + #[inline] + pub fn new_style_anchor(idx: u32, anchor_type: AnchorType) -> Self { + match anchor_type { + AnchorType::Start => Self { + start: Self::START_STYLE_ANCHOR, + end: idx, + }, + AnchorType::End => Self { + start: Self::END_STYLE_ANCHOR, + end: idx, + }, + } + } + + #[inline] + pub fn new_unknown(len: u32) -> Self { + Self { + start: Self::UNKNOWN, + end: len, + } + } + + #[inline] + pub fn new_move() -> Self { + Self { + start: Self::MOVE_ANCHOR, + end: Self::MOVE_ANCHOR, + } + } + + #[inline] + pub(crate) fn kind(&self) -> RichtextChunkKind { + match self.start { + Self::START_STYLE_ANCHOR => RichtextChunkKind::StyleAnchor, + Self::END_STYLE_ANCHOR => RichtextChunkKind::StyleAnchor, + Self::UNKNOWN => RichtextChunkKind::Unknown, + Self::MOVE_ANCHOR => RichtextChunkKind::MoveAnchor, + _ => RichtextChunkKind::Text, + } + } + + #[inline(always)] + pub fn len(&self) -> usize { + match self.start { + Self::UNKNOWN => self.end as usize, + Self::START_STYLE_ANCHOR | Self::END_STYLE_ANCHOR | Self::MOVE_ANCHOR => 1, + _ => (self.end - self.start) as usize, + } + } + + #[inline] + pub(crate) fn value(&self) -> RichtextChunkValue { + match self.start { + Self::UNKNOWN => RichtextChunkValue::Unknown(self.end), + Self::START_STYLE_ANCHOR => RichtextChunkValue::StyleAnchor { + id: self.end, + anchor_type: AnchorType::Start, + }, + Self::END_STYLE_ANCHOR => RichtextChunkValue::StyleAnchor { + id: self.end, + anchor_type: AnchorType::End, + }, + Self::MOVE_ANCHOR => RichtextChunkValue::MoveAnchor, + _ => RichtextChunkValue::Text(self.start..self.end), + } + } +} + +impl Mergeable for RichtextChunk { + fn can_merge(&self, rhs: &Self) -> bool { + match (self.kind(), rhs.kind()) { + (RichtextChunkKind::Text, RichtextChunkKind::Text) => self.end == rhs.start, + (RichtextChunkKind::Unknown, RichtextChunkKind::Unknown) => true, + _ => false, + } + } + + fn merge_right(&mut self, rhs: &Self) { + match (self.kind(), rhs.kind()) { + (RichtextChunkKind::Text, RichtextChunkKind::Text) => self.end = rhs.end, + (RichtextChunkKind::Unknown, RichtextChunkKind::Unknown) => self.end += rhs.end, + _ => unreachable!(), + } + } + + fn merge_left(&mut self, left: &Self) { + match (self.kind(), left.kind()) { + (RichtextChunkKind::Text, RichtextChunkKind::Text) => self.start = left.start, + (RichtextChunkKind::Unknown, RichtextChunkKind::Unknown) => self.end += left.end, + _ => unreachable!(), + } + } +} + +impl HasLength for RichtextChunk { + #[inline(always)] + fn rle_len(&self) -> usize { + self.len() + } +} + +impl Sliceable for RichtextChunk { + fn _slice(&self, range: Range<usize>) -> Self { + match self.kind() { + RichtextChunkKind::Text => { + assert!( + range.len() <= self.len(), + "range: {:?}, self: {:?}", + range, + self + ); + Self { + start: self.start + range.start as u32, + end: self.start + range.end as u32, + } + } + RichtextChunkKind::StyleAnchor | RichtextChunkKind::MoveAnchor => { + assert_eq!(range.len(), 1); + *self + } + RichtextChunkKind::Unknown => { + assert!(range.len() <= self.len()); + Self { + start: Self::UNKNOWN, + end: range.len() as u32, + } + } + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Copy)] +pub(super) struct FugueSpan { + pub id: IdFull, + /// Sometimes, the id of the span is just a placeholder. + /// This field is used to track the real id of the span. + /// We know the real id when deletion happens because we + /// have the start_id info for each deletion. + pub real_id: Option<CompactId>, + /// The status at the current version + pub status: Status, + /// The status at the `new` version. + /// It's used when calculating diff. + pub diff_status: Option<Status>, + pub origin_left: Option<CompactId>, + pub origin_right: Option<CompactId>, + pub content: RichtextChunk, +} + +pub(super) enum DiffStatus { + NotChanged, + Created, + Deleted, +} + +impl FugueSpan { + #[inline(always)] + pub fn id_span(&self) -> IdSpan { + IdSpan::new( + self.id.peer, + self.id.counter, + self.id.counter + self.content.len() as Counter, + ) + } + + #[inline] + pub fn diff(&self) -> DiffStatus { + if self.diff_status.is_none() { + return DiffStatus::NotChanged; + } + + match ( + self.status.is_activated(), + self.diff_status.unwrap().is_activated(), + ) { + (true, false) => DiffStatus::Deleted, + (false, true) => DiffStatus::Created, + _ => DiffStatus::NotChanged, + } + } + + pub fn is_activated_in_diff(&self) -> bool { + match self.diff_status { + Some(d) => d.is_activated(), + None => self.status.is_activated(), + } + } + + pub(crate) fn real_id(&self) -> ID { + if let Some(id) = self.real_id { + id.to_id() + } else { + self.id.id() + } + } +} + +impl Sliceable for FugueSpan { + fn _slice(&self, range: Range<usize>) -> Self { + Self { + id: self.id.inc(range.start as Counter), + real_id: self.real_id.map(|x| x.inc(range.start as Counter)), + status: self.status, + diff_status: self.diff_status, + origin_left: if range.start == 0 { + self.origin_left + } else { + Some( + self.id + .inc((range.start - 1) as Counter) + .id() + .try_into() + .unwrap(), + ) + }, + origin_right: self.origin_right, + content: self.content._slice(range), + } + } +} + +impl HasLength for FugueSpan { + #[inline(always)] + fn rle_len(&self) -> usize { + self.content.len() + } +} + +impl Mergeable for FugueSpan { + fn can_merge(&self, rhs: &Self) -> bool { + self.id.peer == rhs.id.peer + && self.status == rhs.status + && self.diff_status == rhs.diff_status + && self.id.counter + self.content.len() as Counter == rhs.id.counter + && self.id.lamport + self.content.len() as Lamport == rhs.id.lamport + && rhs.origin_left.is_some() + && rhs.origin_left.unwrap().peer == self.id.peer + && rhs.origin_left.unwrap().counter.get() + == self.id.counter + self.content.len() as Counter - 1 + && self.origin_right == rhs.origin_right + && self.content.can_merge(&rhs.content) + && ((self.real_id.is_none() && rhs.real_id.is_none()) + || (self.real_id.is_some() + && rhs.real_id.is_some() + && self.real_id.unwrap().inc(self.content.len() as i32) + == rhs.real_id.unwrap())) + } + + fn merge_right(&mut self, rhs: &Self) { + self.content.merge_right(&rhs.content); + } + + fn merge_left(&mut self, left: &Self) { + self.id = left.id; + self.real_id = left.real_id; + self.origin_left = left.origin_left; + self.content.merge_left(&left.content); + } +} + +impl TryInsert for FugueSpan { + fn try_insert(&mut self, _pos: usize, elem: Self) -> Result<(), Self> + where + Self: Sized, + { + Err(elem) + } +} + +impl CanRemove for FugueSpan { + fn can_remove(&self) -> bool { + self.content.len() == 0 + } +} + +impl FugueSpan { + #[allow(unused)] + pub fn new(id: IdFull, content: RichtextChunk) -> Self { + Self { + id, + real_id: if id.peer == UNKNOWN_PEER_ID { + None + } else { + Some(id.id().try_into().unwrap()) + }, + status: Status::default(), + diff_status: None, + origin_left: None, + origin_right: None, + content, + } + } + + #[inline(always)] + pub fn is_activated(&self) -> bool { + self.status.is_activated() + } + + #[inline] + pub fn activated_len(&self) -> usize { + if self.is_activated() { + self.content.len() + } else { + 0 + } + } +} + +impl HasId for FugueSpan { + fn id_start(&self) -> ID { + self.id.id() + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Default, Hash, Copy)] +pub(super) struct Status { + /// is this span from a future operation + pub future: bool, + pub delete_times: i16, +} + +impl Status { + #[inline(always)] + pub fn is_activated(&self) -> bool { + self.delete_times == 0 && !self.future + } +} diff --git a/vendor/loro-internal/src/container/richtext/richtext_state.rs b/vendor/loro-internal/src/container/richtext/richtext_state.rs new file mode 100644 index 0000000..5ce2e0f --- /dev/null +++ b/vendor/loro-internal/src/container/richtext/richtext_state.rs @@ -0,0 +1,3690 @@ +use append_only_bytes::BytesSlice; +use generic_btree::{ + rle::{CanRemove, HasLength, Mergeable, Sliceable, TryInsert}, + BTree, BTreeTrait, Cursor, LeafIndex, +}; +use loro_common::{Counter, IdFull, IdSpan, LoroError, LoroResult, LoroValue, ID}; +use query::{ByteQuery, ByteQueryT}; +use rustc_hash::{FxHashMap, FxHashSet}; +use serde::{ser::SerializeStruct, Serialize}; +use smallvec::SmallVec; +use std::{ + fmt::{Display, Formatter}, + ops::{Bound, RangeBounds}, +}; +use std::{ + ops::{Add, AddAssign, Range, Sub}, + str::Utf8Error, + sync::Arc, +}; +use tracing::instrument; + +use crate::{ + container::richtext::style_range_map::EMPTY_STYLES, + delta::{DeltaValue, StyleMeta}, + utils::query_by_len::{EntityIndexQueryWithEventIndex, IndexQueryWithEntityIndex, QueryByLen}, +}; + +use self::query::{ + EntityQuery, EntityQueryT, EventIndexQuery, EventIndexQueryT, UnicodeQuery, UnicodeQueryT, + Utf16Query, Utf16QueryT, +}; + +use super::{ + style_range_map::{IterAnchorItem, StyleRangeMap, Styles}, + AnchorType, RichtextSpan, StyleKey, StyleOp, +}; + +pub(crate) use crate::cursor::PosType; + +#[derive(Clone, Debug, Default)] +pub(crate) struct RichtextState { + tree: BTree<RichtextTreeTrait>, + style_ranges: Option<Box<StyleRangeMap>>, + cached_cursor: Option<CachedCursor>, +} + +impl Display for RichtextState { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + for span in self.tree.iter() { + match span { + RichtextStateChunk::Style { .. } => {} + RichtextStateChunk::Text(s) => { + f.write_str(s.as_str())?; + } + } + } + + Ok(()) + } +} + +use cache::CachedCursor; + +mod cache { + use super::*; + + #[derive(Clone, Debug)] + pub(super) struct CachedCursor { + leaf: LeafIndex, + index: FxHashMap<PosType, usize>, + } + + impl RichtextState { + pub(super) fn clear_cache(&mut self) { + self.cached_cursor = None; + } + + pub(super) fn record_cache( + &mut self, + leaf: LeafIndex, + pos: usize, + pos_type: PosType, + entity_offset: usize, + entity_index: Option<usize>, + ) { + let offset = if entity_offset != 0 { + let elem = self.tree.get_elem(leaf).unwrap(); + entity_offset_to_pos_type_offset(pos_type, elem, entity_offset) + } else { + 0 + }; + + let pos = pos - offset; + match &mut self.cached_cursor { + Some(c) => { + if c.leaf == leaf { + c.index.insert(pos_type, pos); + } else { + c.leaf = leaf; + c.index.clear(); + c.index.insert(pos_type, pos); + } + } + None => { + self.cached_cursor = Some(CachedCursor { + leaf, + index: FxHashMap::default(), + }); + self.cached_cursor + .as_mut() + .unwrap() + .index + .insert(pos_type, pos); + } + } + if let Some(entity_index) = entity_index { + self.cached_cursor + .as_mut() + .unwrap() + .index + .insert(PosType::Entity, entity_index - entity_offset); + } + } + + pub(super) fn try_get_cache_or_clean( + &mut self, + index: usize, + pos_type: PosType, + ) -> Option<Cursor> { + let mut cursor = self.cached_cursor.take(); + let ans = 'block: { + match &mut cursor { + Some(c) => { + let cache_index = c.index.get(&pos_type); + if let Some(cache_index) = cache_index { + if index < *cache_index { + return None; + } + } + + let cached_index = match c.index.entry(pos_type) { + std::collections::hash_map::Entry::Vacant(vacant_entry) => { + let index = self.get_index_from_cursor( + Cursor { + leaf: c.leaf, + offset: 0, + }, + pos_type, + )?; + vacant_entry.insert(index); + index + } + std::collections::hash_map::Entry::Occupied(occupied_entry) => { + *occupied_entry.get() + } + }; + + if index < cached_index { + return None; + } + + if cached_index == index { + break 'block Some(Cursor { + leaf: c.leaf, + offset: 0, + }); + } + + let elem = self.tree.get_elem(c.leaf)?; + let elem_len = elem.len_with(pos_type); + if cached_index + elem_len == index { + let offset = elem.len_with(PosType::Entity); + break 'block Some(Cursor { + leaf: c.leaf, + offset, + }); + } + + if index > cached_index + elem_len { + return None; + } + + let offset = + pos_type_offset_to_entity_offset(pos_type, elem, index - cached_index)?; + Some(Cursor { + leaf: c.leaf, + offset, + }) + } + None => None, + } + }; + + self.cached_cursor = cursor; + #[cfg(debug_assertions)] + { + if let Some(c) = ans.as_ref() { + let actual = self.get_index_from_cursor(*c, pos_type); + assert_eq!(actual.unwrap(), index); + } + } + ans + } + + pub(super) fn get_cache_entity_index(&mut self) -> Option<usize> { + self.get_cache_leaf_start_index(PosType::Entity) + } + + /// Index (in `pos_type` units) of the start of the currently cached leaf, + /// computing it once via `get_index_from_cursor` and memoizing it on the + /// cached cursor for reuse by later same-leaf queries. + pub(super) fn get_cache_leaf_start_index(&mut self, pos_type: PosType) -> Option<usize> { + let mut cursor = self.cached_cursor.take()?; + let ans = { + let leaf = cursor.leaf; + match cursor.index.entry(pos_type) { + std::collections::hash_map::Entry::Vacant(vacant_entry) => { + let index = + self.get_index_from_cursor(Cursor { leaf, offset: 0 }, pos_type)?; + vacant_entry.insert(index); + index + } + std::collections::hash_map::Entry::Occupied(occupied_entry) => { + *occupied_entry.get() + } + } + }; + + self.cached_cursor = Some(cursor); + Some(ans) + } + + /// Resolve the `pos_type` index of an arbitrary cursor using the cached + /// leaf, avoiding a full `visit_previous_caches` walk when the cursor + /// lands in the currently cached leaf. Returns `None` (miss) otherwise. + pub(super) fn cursor_index_via_cache( + &mut self, + cursor: Cursor, + pos_type: PosType, + ) -> Option<usize> { + match &self.cached_cursor { + Some(c) if c.leaf == cursor.leaf => {} + _ => return None, + } + let leaf_start = self.get_cache_leaf_start_index(pos_type)?; + if cursor.offset == 0 { + return Some(leaf_start); + } + let elem = self.tree.get_elem(cursor.leaf)?; + Some(leaf_start + entity_offset_to_pos_type_offset(pos_type, elem, cursor.offset)) + } + + pub(crate) fn check_cache(&self) { + #[cfg(debug_assertions)] + { + if let Some(c) = &self.cached_cursor { + for (pos_type, index) in &c.index { + let actual = self.get_index_from_cursor( + Cursor { + leaf: c.leaf, + offset: 0, + }, + *pos_type, + ); + + assert_eq!(actual.unwrap(), *index); + } + } + } + } + } +} + +pub(crate) use text_chunk::TextChunk; +mod text_chunk { + use std::ops::Range; + + use append_only_bytes::BytesSlice; + use loro_common::{IdFull, ID}; + + /// Largest text element kept in the state tree (project_note patch). + pub(crate) const MAX_CHUNK_BYTES: usize = 2048; + + #[derive(Clone, PartialEq)] + pub(crate) struct TextChunk { + bytes: BytesSlice, + unicode_len: i32, + utf16_len: i32, + id: IdFull, + } + + impl std::fmt::Debug for TextChunk { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TextChunk") + .field("text", &self.as_str()) + .field("unicode_len", &self.unicode_len) + .field("utf16_len", &self.utf16_len) + .field("id", &self.id) + .finish() + } + } + + impl TextChunk { + pub fn new(bytes: BytesSlice, id: IdFull) -> Self { + // ASCII: every length is the byte length. (project_note patch) + if bytes.is_ascii() { + let len = bytes.len() as i32; + return Self { unicode_len: len, bytes, utf16_len: len, id }; + } + let (unicode_len, utf16_len) = crate::utils::utf16::str_lens(&bytes); + Self { + unicode_len: unicode_len as i32, + bytes, + utf16_len: utf16_len as i32, + id, + } + } + + /// Splits into pieces of at most [`MAX_CHUNK_BYTES`] (on char boundaries), so + /// that offset conversions inside one tree element stay short. (project_note patch) + pub fn into_pieces(self) -> Vec<Self> { + if self.bytes.len() <= MAX_CHUNK_BYTES { + return vec![self]; + } + let s = self.as_str(); + let mut out = Vec::with_capacity(s.len() / MAX_CHUNK_BYTES + 1); + let mut id = self.id; + let mut start = 0; + while start < s.len() { + let mut end = (start + MAX_CHUNK_BYTES).min(s.len()); + while !s.is_char_boundary(end) { + end -= 1; + } + let (unicode, utf16) = crate::utils::utf16::str_lens(&s.as_bytes()[start..end]); + let (unicode, utf16) = (unicode as i32, utf16 as i32); + out.push(Self { bytes: self.bytes.slice_clone(start..end), unicode_len: unicode, utf16_len: utf16, id }); + id = id.inc(unicode); + start = end; + } + out + } + + #[inline] + pub fn id(&self) -> ID { + self.id.id() + } + + #[inline] + #[allow(unused)] + pub fn id_full(&self) -> IdFull { + self.id + } + + #[inline] + pub fn bytes(&self) -> &BytesSlice { + &self.bytes + } + + #[inline] + pub fn as_str(&self) -> &str { + // SAFETY: We know that the text is valid UTF-8 + unsafe { std::str::from_utf8_unchecked(&self.bytes) } + } + + #[inline] + pub fn len(&self) -> i32 { + self.unicode_len + } + + #[inline] + pub fn utf8_len(&self) -> i32 { + self.bytes.len() as i32 + } + + #[inline] + pub fn unicode_len(&self) -> i32 { + self.unicode_len + } + + #[inline] + pub fn utf16_len(&self) -> i32 { + self.utf16_len + } + + #[inline] + pub fn event_len(&self) -> i32 { + if cfg!(feature = "wasm") { + self.utf16_len + } else { + self.unicode_len + } + } + + /// Convert a unicode index on this text to an event index + pub fn convert_unicode_offset_to_event_offset(&self, offset: usize) -> usize { + if cfg!(feature = "wasm") { + let mut event_offset = 0; + for (i, c) in self.as_str().chars().enumerate() { + if i == offset { + return event_offset; + } + event_offset += c.len_utf16(); + } + event_offset + } else { + offset + } + } + + pub fn new_empty() -> Self { + Self { + unicode_len: 0, + bytes: BytesSlice::empty(), + utf16_len: 0, + // This is a dummy value. + // It's fine because the length is 0. We never actually use this value. + id: IdFull::NONE_ID, + } + } + + /// Whether every char in this chunk is in the Basic Multilingual Plane, + /// i.e. each char is a single UTF-16 code unit. When true, UTF-16 offsets + /// equal unicode offsets, so conversions are O(1) instead of O(offset). + #[inline] + fn is_all_bmp(&self) -> bool { + self.utf16_len == self.unicode_len + } + + /// Whether this chunk is pure ASCII, i.e. each char is a single byte. + /// When true, byte offsets equal unicode offsets. + #[inline] + fn is_all_ascii(&self) -> bool { + self.bytes.len() as i32 == self.unicode_len + } + + /// Convert a UTF-16 offset within this chunk to a unicode offset. + /// + /// O(1) when the chunk has no astral-plane characters; otherwise it + /// scans up to `utf16_offset` chars. Mirrors [`utf16_to_unicode_index`]. + pub fn utf16_offset_to_unicode(&self, utf16_offset: usize) -> Result<usize, usize> { + if self.is_all_bmp() { + return Ok(utf16_offset); + } + super::utf16_to_unicode_index(self.as_str(), utf16_offset) + } + + /// Convert a UTF-8 (byte) offset within this chunk to a unicode offset. + /// O(1) when the chunk is pure ASCII. + pub fn utf8_offset_to_unicode(&self, utf8_offset: usize) -> Result<usize, usize> { + if self.is_all_ascii() { + return Ok(utf8_offset); + } + super::utf8_to_unicode_index(self.as_str(), utf8_offset) + } + + /// Convert a unicode offset within this chunk to a UTF-16 offset. + /// O(1) when the chunk has no astral-plane characters. + pub fn unicode_offset_to_utf16(&self, unicode_offset: usize) -> Option<usize> { + if self.is_all_bmp() { + return Some(unicode_offset); + } + super::unicode_to_utf16_index(self.as_str(), unicode_offset) + } + + /// Convert a unicode offset within this chunk to a UTF-8 (byte) offset. + /// O(1) when the chunk is pure ASCII. + pub fn unicode_offset_to_utf8(&self, unicode_offset: usize) -> Option<usize> { + if self.is_all_ascii() { + return Some(unicode_offset); + } + super::unicode_to_utf8_index(self.as_str(), unicode_offset) + } + + /// Slice this chunk by unicode offsets, returning the substring. + /// O(1) byte lookup when the chunk is pure ASCII. + pub fn unicode_slice(&self, start: usize, end: usize) -> Result<&str, ()> { + if self.is_all_ascii() { + return self.as_str().get(start..end).ok_or(()); + } + super::unicode_slice(self.as_str(), start, end) + } + + pub(crate) fn delete_by_entity_index( + &mut self, + unicode_offset: usize, + unicode_len: usize, + ) -> (Option<Self>, usize) { + let s = self.as_str(); + let mut start_byte = 0; + let mut end_byte = self.bytes().len(); + let start_unicode_index = unicode_offset; + let end_unicode_index = unicode_offset + unicode_len; + let mut start_utf16_index = 0; + let mut current_utf16_index = 0; + let mut current_utf8_index = 0; + for (current_unicode_index, c) in s.chars().enumerate() { + if current_unicode_index == start_unicode_index { + start_utf16_index = current_utf16_index; + start_byte = current_utf8_index; + } + + if current_unicode_index == end_unicode_index { + end_byte = current_utf8_index; + break; + } + + current_utf16_index += c.len_utf16(); + current_utf8_index += c.len_utf8(); + } + + self.utf16_len -= (current_utf16_index - start_utf16_index) as i32; + + let event_len = if cfg!(feature = "wasm") { + current_utf16_index - start_utf16_index + } else { + unicode_len + }; + + self.unicode_len -= unicode_len as i32; + let next = match (start_byte == 0, end_byte == self.bytes.len()) { + (true, true) => { + self.bytes = BytesSlice::empty(); + None + } + (true, false) => { + self.bytes.slice_(end_byte..); + self.id = self.id.inc(end_unicode_index as i32); + None + } + (false, true) => { + self.bytes.slice_(..start_byte); + None + } + (false, false) => { + let next = self.bytes.slice_clone(end_byte..); + let next = Self::new(next, self.id.inc(end_unicode_index as i32)); + self.unicode_len -= next.unicode_len; + self.utf16_len -= next.utf16_len; + self.bytes.slice_(..start_byte); + Some(next) + } + }; + + self.check(); + if let Some(next) = next.as_ref() { + next.check(); + } + (next, event_len) + } + + fn check(&self) { + if !cfg!(any(debug_assertions, test)) { + return; + } + + let bytes_len = self.bytes.len() as i32; + if bytes_len == self.unicode_len { + assert_eq!(self.utf16_len, self.unicode_len); + return; + } + + assert_eq!(self.unicode_len, self.as_str().chars().count() as i32); + assert_eq!( + self.utf16_len, + self.as_str().chars().map(|c| c.len_utf16()).sum::<usize>() as i32 + ); + } + + pub(crate) fn entity_range_to_event_range(&self, range: Range<usize>) -> Range<usize> { + if cfg!(feature = "wasm") { + assert!(range.start <= range.end); + if range.start == 0 && range.end == self.unicode_len as usize { + return 0..self.utf16_len as usize; + } + + let mut start = 0; + let mut end = 0; + let mut utf16_index = 0; + for (unicode_index, c) in self.as_str().chars().enumerate() { + if unicode_index == range.start { + start = utf16_index; + } + if unicode_index == range.end { + end = utf16_index; + break; + } + + utf16_index += c.len_utf16(); + } + + if end == 0 { + end = utf16_index; + } + + start..end + } else { + range + } + } + } + + impl generic_btree::rle::HasLength for TextChunk { + fn rle_len(&self) -> usize { + self.unicode_len as usize + } + } + + impl generic_btree::rle::Sliceable for TextChunk { + fn _slice(&self, range: Range<usize>) -> Self { + assert!(range.start < range.end); + let total_unicode_len = self.unicode_len as usize; + if range.start == 0 && range.end == total_unicode_len { + return self.clone(); + } + + // Fast path for ASCII text: unicode index == byte index, and utf16 index == unicode index. + if self.is_all_ascii() { + let ans = Self { + unicode_len: range.len() as i32, + bytes: self.bytes.slice_clone(range.start..range.end), + utf16_len: range.len() as i32, + id: self.id.inc(range.start as i32), + }; + ans.check(); + return ans; + } + + // Fast path for slicing a suffix/prefix to avoid scanning the whole chunk. + if range.end == total_unicode_len { + let mut utf16_offset = 0; + let mut start_byte = self.bytes.len(); + for (unicode_index, (byte_index, c)) in self.as_str().char_indices().enumerate() { + if unicode_index == range.start { + start_byte = byte_index; + break; + } + utf16_offset += c.len_utf16(); + } + + let ans = Self { + unicode_len: (total_unicode_len - range.start) as i32, + bytes: self.bytes.slice_clone(start_byte..), + utf16_len: self.utf16_len - utf16_offset as i32, + id: self.id.inc(range.start as i32), + }; + ans.check(); + return ans; + } + + if range.start == 0 { + let mut utf16_len = 0; + let mut end_byte = self.bytes.len(); + for (unicode_index, (byte_index, c)) in self.as_str().char_indices().enumerate() { + if unicode_index == range.end { + end_byte = byte_index; + break; + } + utf16_len += c.len_utf16(); + } + + let ans = Self { + unicode_len: range.end as i32, + bytes: self.bytes.slice_clone(..end_byte), + utf16_len: utf16_len as i32, + id: self.id, + }; + ans.check(); + return ans; + } + + // General middle slice. + let mut utf16_len = 0; + let mut start = 0; + let mut end = 0; + let mut started = false; + let mut last_unicode_index = 0; + for (unicode_index, (i, c)) in self.as_str().char_indices().enumerate() { + if unicode_index == range.start { + start = i; + started = true; + } + + if unicode_index == range.end { + end = i; + break; + } + if started { + utf16_len += c.len_utf16(); + } + + last_unicode_index = unicode_index; + } + + assert!(started); + if end == 0 { + assert_eq!(last_unicode_index + 1, range.end); + end = self.bytes.len(); + } + + let ans = Self { + unicode_len: range.len() as i32, + bytes: self.bytes.slice_clone(start..end), + utf16_len: utf16_len as i32, + id: self.id.inc(range.start as i32), + }; + ans.check(); + ans + } + + fn split(&mut self, pos: usize) -> Self { + let mut utf16_len = 0; + let mut byte_offset = 0; + for (unicode_index, (i, c)) in self.as_str().char_indices().enumerate() { + if unicode_index == pos { + byte_offset = i; + break; + } + + utf16_len += c.len_utf16(); + } + let right = Self { + unicode_len: self.unicode_len - pos as i32, + bytes: self.bytes.slice_clone(byte_offset..), + utf16_len: self.utf16_len - utf16_len as i32, + id: self.id.inc(pos as i32), + }; + + self.unicode_len = pos as i32; + self.utf16_len = utf16_len as i32; + self.bytes.slice_(..byte_offset); + right.check(); + self.check(); + right + } + } + + impl generic_btree::rle::Mergeable for TextChunk { + fn can_merge(&self, rhs: &Self) -> bool { + self.bytes.can_merge(&rhs.bytes) + && self.id.inc(self.unicode_len) == rhs.id + && self.bytes.len() + rhs.bytes.len() <= MAX_CHUNK_BYTES + } + + fn merge_right(&mut self, rhs: &Self) { + self.bytes.try_merge(&rhs.bytes).unwrap(); + self.utf16_len += rhs.utf16_len; + self.unicode_len += rhs.unicode_len; + self.check(); + } + + fn merge_left(&mut self, left: &Self) { + let mut new = left.bytes.clone(); + new.try_merge(&self.bytes).unwrap(); + self.bytes = new; + self.utf16_len += left.utf16_len; + self.unicode_len += left.unicode_len; + self.id = left.id; + self.check(); + } + } +} + +// TODO: change visibility back to crate after #116 is done +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum RichtextStateChunk { + Text(TextChunk), + Style { + style: Arc<StyleOp>, + anchor_type: AnchorType, + }, +} + +impl Default for RichtextStateChunk { + fn default() -> Self { + Self::new_empty() + } +} + +impl RichtextStateChunk { + pub fn new_text(s: BytesSlice, id: IdFull) -> Self { + Self::Text(TextChunk::new(s, id)) + } + + /// Splits an oversized text element; other elements come back as they are. + pub(crate) fn into_pieces(self) -> Vec<Self> { + match self { + Self::Text(t) => t.into_pieces().into_iter().map(Self::Text).collect(), + s => vec![s], + } + } + + pub fn new_empty() -> Self { + Self::Text(TextChunk::new_empty()) + } + + pub fn new_style(style: Arc<StyleOp>, anchor_type: AnchorType) -> Self { + Self::Style { style, anchor_type } + } + + pub(crate) fn get_id_span(&self) -> IdSpan { + match self { + RichtextStateChunk::Text(t) => { + let id = t.id(); + IdSpan::new(id.peer, id.counter, id.counter + t.unicode_len() as Counter) + } + RichtextStateChunk::Style { style, anchor_type } => match anchor_type { + AnchorType::Start => style.id().into(), + AnchorType::End => { + let id = style.id(); + id.to_span(1) + } + }, + } + } + + pub(crate) fn counter(&self) -> Counter { + match self { + RichtextStateChunk::Text(t) => t.id().counter, + RichtextStateChunk::Style { style, anchor_type } => match anchor_type { + AnchorType::Start => style.id().counter, + AnchorType::End => { + let id = style.id(); + id.counter + 1 + } + }, + } + } + + pub fn entity_range_to_event_range(&self, range: Range<usize>) -> Range<usize> { + match self { + RichtextStateChunk::Text(t) => t.entity_range_to_event_range(range), + RichtextStateChunk::Style { .. } => { + assert_eq!(range.start, 0); + assert_eq!(range.end, 1); + 0..1 + } + } + } + + pub fn len_with(&self, pos_type: PosType) -> usize { + match self { + RichtextStateChunk::Text(t) => match pos_type { + PosType::Bytes => t.utf8_len() as usize, + PosType::Utf16 => t.utf16_len() as usize, + PosType::Event if cfg!(feature = "wasm") => t.utf16_len() as usize, + PosType::Event => t.unicode_len() as usize, + PosType::Entity => t.unicode_len() as usize, + PosType::Unicode => t.unicode_len() as usize, + }, + RichtextStateChunk::Style { .. } => { + if let PosType::Entity = pos_type { + 1 + } else { + 0 + } + } + } + } +} + +impl loro_delta::delta_trait::DeltaValue for RichtextStateChunk {} + +impl DeltaValue for RichtextStateChunk { + fn value_extend(&mut self, other: Self) -> Result<(), Self> { + Err(other) + } + + fn take(&mut self, length: usize) -> Self { + let mut right = self.split(length); + std::mem::swap(self, &mut right); + right + } + + fn length(&self) -> usize { + self.rle_len() + } +} + +impl Serialize for RichtextStateChunk { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + match self { + RichtextStateChunk::Text(text) => { + let mut state = serializer.serialize_struct("RichtextStateChunk", 3)?; + state.serialize_field("type", "Text")?; + state.serialize_field("unicode_len", &text.unicode_len())?; + state.serialize_field("text", text.as_str())?; + state.end() + } + RichtextStateChunk::Style { style, anchor_type } => { + let mut state = serializer.serialize_struct("RichtextStateChunk", 3)?; + state.serialize_field("type", "Style")?; + state.serialize_field("style", &style.key)?; + state.serialize_field("anchor_type", anchor_type)?; + state.end() + } + } + } +} + +impl RichtextStateChunk { + pub fn try_new(s: BytesSlice, id: IdFull) -> Result<Self, Utf8Error> { + std::str::from_utf8(&s)?; + Ok(RichtextStateChunk::Text(TextChunk::new(s, id))) + } + + pub fn from_style(style: Arc<StyleOp>, anchor_type: AnchorType) -> Self { + Self::Style { style, anchor_type } + } + + pub fn as_str(&self) -> Option<&str> { + match self { + RichtextStateChunk::Text(text) => Some(text.as_str()), + _ => None, + } + } +} + +impl HasLength for RichtextStateChunk { + fn rle_len(&self) -> usize { + match self { + RichtextStateChunk::Text(s) => s.rle_len(), + RichtextStateChunk::Style { .. } => 1, + } + } +} + +impl Mergeable for RichtextStateChunk { + fn can_merge(&self, rhs: &Self) -> bool { + match (self, rhs) { + (RichtextStateChunk::Text(l), RichtextStateChunk::Text(r)) => l.can_merge(r), + _ => false, + } + } + + fn merge_right(&mut self, rhs: &Self) { + match (self, rhs) { + (RichtextStateChunk::Text(l), RichtextStateChunk::Text(r)) => l.merge_right(r), + _ => unreachable!(), + } + } + + fn merge_left(&mut self, left: &Self) { + match (self, left) { + (RichtextStateChunk::Text(this), RichtextStateChunk::Text(left)) => { + this.merge_left(left) + } + _ => unreachable!(), + } + } +} + +impl Sliceable for RichtextStateChunk { + fn _slice(&self, range: Range<usize>) -> Self { + match self { + RichtextStateChunk::Text(s) => RichtextStateChunk::Text(s._slice(range)), + RichtextStateChunk::Style { style, anchor_type } => { + assert_eq!(range.start, 0); + assert_eq!(range.end, 1); + RichtextStateChunk::Style { + style: style.clone(), + anchor_type: *anchor_type, + } + } + } + } + + fn split(&mut self, pos: usize) -> Self { + match self { + RichtextStateChunk::Text(s) => RichtextStateChunk::Text(s.split(pos)), + RichtextStateChunk::Style { .. } => { + unreachable!() + } + } + } +} + +impl TryInsert for RichtextStateChunk { + fn try_insert(&mut self, _pos: usize, elem: Self) -> Result<(), Self> + where + Self: Sized, + { + Err(elem) + } +} + +impl CanRemove for RichtextStateChunk { + fn can_remove(&self) -> bool { + self.rle_len() == 0 + } +} + +//TODO: start/end can be scanned in one loop, but now it takes twice the time +fn unicode_slice(s: &str, start_index: usize, end_index: usize) -> Result<&str, ()> { + let (Some(start), Some(end)) = ( + unicode_to_utf8_index(s, start_index), + unicode_to_utf8_index(s, end_index), + ) else { + return Err(()); + }; + Ok(&s[start..end]) +} + +pub(crate) fn unicode_to_utf8_index(s: &str, unicode_index: usize) -> Option<usize> { + if unicode_index <= s.len() && s.as_bytes()[..unicode_index].is_ascii() { + return Some(unicode_index); + } + let mut current_unicode_index = 0; + for (byte_index, _) in s.char_indices() { + if current_unicode_index == unicode_index { + return Some(byte_index); + } + current_unicode_index += 1; + } + + if current_unicode_index == unicode_index { + return Some(s.len()); + } + + None +} + +pub(crate) fn unicode_to_utf16_index(s: &str, unicode_index: usize) -> Option<usize> { + if unicode_index <= s.len() && s.as_bytes()[..unicode_index].is_ascii() { + return Some(unicode_index); + } + if unicode_index == 0 { + return Some(0); + } + + let mut current_unicode_index = 0; + let mut current_utf16_index = 0; + for c in s.chars() { + let len = c.len_utf16(); + current_unicode_index += 1; + current_utf16_index += len; + if current_unicode_index == unicode_index { + return Some(current_utf16_index); + } + } + + None +} + +pub(crate) fn utf16_to_utf8_index(s: &str, utf16_index: usize) -> Option<usize> { + if utf16_index <= s.len() && s.as_bytes()[..utf16_index].is_ascii() { + return Some(utf16_index); + } + if utf16_index == 0 { + return Some(0); + } + + let mut current_utf16_index = 0; + for (byte_index, c) in s.char_indices() { + let len = c.len_utf16(); + current_utf16_index += len; + if current_utf16_index == utf16_index { + return Some(byte_index + c.len_utf8()); + } + } + + if current_utf16_index == utf16_index { + return Some(s.len()); + } + + None +} + +/// Returns the unicode index of the character at the given utf16 index. +/// +/// If the given utf16 index is not at the correct boundary, returns the unicode index of the +/// character before the given utf16 index. +pub(crate) fn utf16_to_unicode_index(s: &str, utf16_index: usize) -> Result<usize, usize> { + if utf16_index <= s.len() && s.as_bytes()[..utf16_index].is_ascii() { + return Ok(utf16_index); + } + if utf16_index == 0 { + return Ok(0); + } + + let mut current_utf16_index = 0; + let mut current_unicode_index = 0; + for (i, c) in s.chars().enumerate() { + current_utf16_index += c.len_utf16(); + if current_utf16_index == utf16_index { + return Ok(i + 1); + } + if current_utf16_index > utf16_index { + loro_common::info!("WARNING: UTF16 MISMATCHED!"); + return Err(i); + } + current_unicode_index = i + 1; + } + + loro_common::info!("WARNING: UTF16 MISMATCHED!"); + Err(current_unicode_index) +} + +pub(crate) fn utf8_to_unicode_index(s: &str, utf8_index: usize) -> Result<usize, usize> { + if utf8_index <= s.len() && s.as_bytes()[..utf8_index].is_ascii() { + return Ok(utf8_index); + } + if utf8_index == 0 { + return Ok(0); + } + + let mut current_utf8_index = 0; + let mut current_unicode_index = 0; + for (i, c) in s.chars().enumerate() { + let char_start = current_utf8_index; + current_utf8_index += c.len_utf8(); + + if utf8_index == char_start { + return Ok(i); + } + + if utf8_index < current_utf8_index { + loro_common::info!("WARNING: UTF-8 index is in the middle of a codepoint!"); + return Err(i); + } + current_unicode_index = i + 1; + } + + if current_utf8_index == utf8_index { + Ok(current_unicode_index) + } else { + Err(current_unicode_index) + } +} + +#[derive(Clone, Debug, Copy, PartialEq, Eq, Default)] +pub(crate) struct PosCache { + pub(super) unicode_len: i32, + pub(super) bytes: i32, + pub(super) utf16_len: i32, + pub(crate) entity_len: i32, +} + +impl PosCache { + pub(crate) fn event_len(&self) -> i32 { + if cfg!(feature = "wasm") { + self.utf16_len + } else { + self.unicode_len + } + } + + #[allow(unused)] + fn get_len(&self, pos_type: PosType) -> i32 { + match pos_type { + PosType::Bytes => self.bytes, + PosType::Unicode => self.unicode_len, + PosType::Utf16 => self.utf16_len, + PosType::Entity => self.entity_len, + PosType::Event => self.event_len(), + } + } +} + +impl AddAssign for PosCache { + fn add_assign(&mut self, rhs: Self) { + self.unicode_len += rhs.unicode_len; + self.bytes += rhs.bytes; + self.utf16_len += rhs.utf16_len; + self.entity_len += rhs.entity_len; + } +} + +impl Add for PosCache { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self { + bytes: self.bytes + rhs.bytes, + unicode_len: self.unicode_len + rhs.unicode_len, + utf16_len: self.utf16_len + rhs.utf16_len, + entity_len: self.entity_len + rhs.entity_len, + } + } +} + +impl Sub for PosCache { + type Output = Self; + + fn sub(self, rhs: Self) -> Self::Output { + Self { + bytes: self.bytes - rhs.bytes, + unicode_len: self.unicode_len - rhs.unicode_len, + utf16_len: self.utf16_len - rhs.utf16_len, + entity_len: self.entity_len - rhs.entity_len, + } + } +} + +impl CanRemove for PosCache { + fn can_remove(&self) -> bool { + self.bytes == 0 + } +} + +pub(crate) struct RichtextTreeTrait; + +#[derive(Debug)] +pub(crate) struct EntityRangeInfo { + pub id_start: ID, + pub entity_start: usize, + pub entity_end: usize, + pub event_len: usize, +} + +/// Entity ranges produced by a single text query. Inline storage avoids a heap +/// allocation on the per-op delete hot path, where a contiguous delete is +/// usually a single merged range. +pub(crate) type EntityRanges = SmallVec<[EntityRangeInfo; 2]>; + +impl EntityRangeInfo { + pub fn entity_len(&self) -> usize { + self.entity_end - self.entity_start + } +} + +impl BTreeTrait for RichtextTreeTrait { + type Elem = RichtextStateChunk; + + type Cache = PosCache; + + type CacheDiff = PosCache; + + fn calc_cache_internal( + cache: &mut Self::Cache, + caches: &[generic_btree::Child<Self>], + ) -> Self::CacheDiff { + let mut new_cache = PosCache::default(); + for child in caches { + new_cache += child.cache; + } + + let diff = new_cache - *cache; + *cache = new_cache; + diff + } + + #[inline(always)] + fn merge_cache_diff(diff1: &mut Self::CacheDiff, diff2: &Self::CacheDiff) { + *diff1 += *diff2; + } + + #[inline(always)] + fn apply_cache_diff(cache: &mut Self::Cache, diff: &Self::CacheDiff) { + *cache += *diff; + } + + #[inline] + fn get_elem_cache(elem: &Self::Elem) -> Self::Cache { + match elem { + RichtextStateChunk::Text(s) => PosCache { + bytes: s.bytes().len() as i32, + unicode_len: s.unicode_len(), + utf16_len: s.utf16_len(), + entity_len: s.unicode_len(), + }, + RichtextStateChunk::Style { .. } => PosCache { + bytes: 0, + unicode_len: 0, + utf16_len: 0, + entity_len: 1, + }, + } + } + + #[inline(always)] + fn new_cache_to_diff(cache: &Self::Cache) -> Self::CacheDiff { + *cache + } + + #[inline(always)] + fn sub_cache(cache_lhs: &Self::Cache, cache_rhs: &Self::Cache) -> Self::CacheDiff { + PosCache { + bytes: cache_lhs.bytes - cache_rhs.bytes, + unicode_len: cache_lhs.unicode_len - cache_rhs.unicode_len, + utf16_len: cache_lhs.utf16_len - cache_rhs.utf16_len, + entity_len: cache_lhs.entity_len - cache_rhs.entity_len, + } + } +} + +// This query implementation will prefer right element when both left element and right element are valid. +mod query { + use crate::utils::query_by_len::{IndexQuery, QueryByLen}; + + use super::*; + + pub(super) type EndQuery<T> = IndexQuery<T, RichtextTreeTrait, true>; + + #[cfg(not(feature = "wasm"))] + pub(super) type EventIndexQuery = UnicodeQuery; + #[cfg(feature = "wasm")] + pub(super) type EventIndexQuery = Utf16Query; + + #[cfg(not(feature = "wasm"))] + pub(super) type EventIndexQueryT = UnicodeQueryT; + #[cfg(feature = "wasm")] + pub(super) type EventIndexQueryT = Utf16QueryT; + + pub(super) struct UnicodeQueryT; + pub(super) type UnicodeQuery = IndexQuery<UnicodeQueryT, RichtextTreeTrait>; + + impl QueryByLen<RichtextTreeTrait> for UnicodeQueryT { + fn get_cache_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize { + cache.unicode_len as usize + } + + fn get_elem_len(elem: &<RichtextTreeTrait as BTreeTrait>::Elem) -> usize { + match elem { + RichtextStateChunk::Text(s) => s.rle_len(), + RichtextStateChunk::Style { .. } => 0, + } + } + + fn get_offset_and_found( + left: usize, + elem: &<RichtextTreeTrait as BTreeTrait>::Elem, + ) -> (usize, bool) { + match elem { + RichtextStateChunk::Text(s) => { + if s.rle_len() >= left { + return (left, true); + } + + (left, false) + } + RichtextStateChunk::Style { .. } => (1, false), + } + } + + fn get_cache_entity_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize { + cache.entity_len as usize + } + } + + pub(crate) struct Utf16QueryT; + pub(crate) type Utf16Query = IndexQuery<Utf16QueryT, RichtextTreeTrait>; + + impl QueryByLen<RichtextTreeTrait> for Utf16QueryT { + fn get_cache_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize { + cache.utf16_len as usize + } + + fn get_elem_len(elem: &<RichtextTreeTrait as BTreeTrait>::Elem) -> usize { + match elem { + RichtextStateChunk::Text(s) => s.utf16_len() as usize, + RichtextStateChunk::Style { .. } => 0, + } + } + + fn get_offset_and_found( + left: usize, + elem: &<RichtextTreeTrait as BTreeTrait>::Elem, + ) -> (usize, bool) { + match elem { + RichtextStateChunk::Text(s) => { + if left == 0 { + return (0, true); + } + + // Allow left to not at the correct utf16 boundary. If so fallback to the last position. + // TODO: if we remove the use of query(pos-1), we won't need this fallback behavior + // WARNING: Unable to report error!!! + let offset = s.utf16_offset_to_unicode(left).unwrap_or_else(|e| e); + (offset, true) + } + RichtextStateChunk::Style { .. } => (1, false), + } + } + + fn get_cache_entity_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize { + cache.entity_len as usize + } + } + + pub(super) struct EntityQueryT; + pub(super) type EntityQuery = IndexQuery<EntityQueryT, RichtextTreeTrait>; + + impl QueryByLen<RichtextTreeTrait> for EntityQueryT { + fn get_cache_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize { + cache.entity_len as usize + } + + fn get_elem_len(elem: &<RichtextTreeTrait as BTreeTrait>::Elem) -> usize { + match elem { + RichtextStateChunk::Text(s) => s.rle_len(), + RichtextStateChunk::Style { .. } => 1, + } + } + + fn get_offset_and_found( + left: usize, + elem: &<RichtextTreeTrait as BTreeTrait>::Elem, + ) -> (usize, bool) { + match elem { + RichtextStateChunk::Text(s) => { + if s.rle_len() >= left { + return (left, true); + } + + (left, false) + } + RichtextStateChunk::Style { .. } => { + if left == 0 { + return (0, true); + } + + (left, false) + } + } + } + + fn get_cache_entity_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize { + cache.entity_len as usize + } + } + + pub(super) struct ByteQueryT; + pub(super) type ByteQuery = IndexQuery<ByteQueryT, RichtextTreeTrait>; + impl QueryByLen<RichtextTreeTrait> for ByteQueryT { + fn get_cache_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize { + cache.bytes as usize + } + fn get_elem_len(elem: &<RichtextTreeTrait as BTreeTrait>::Elem) -> usize { + match elem { + RichtextStateChunk::Text(s) => s.utf8_len() as usize, + RichtextStateChunk::Style { .. } => 0, + } + } + + fn get_offset_and_found( + left: usize, + elem: &<RichtextTreeTrait as BTreeTrait>::Elem, + ) -> (usize, bool) { + match elem { + RichtextStateChunk::Text(s) => { + if left == 0 { + return (0, true); + } + + // Allow left to not at the correct utf16 boundary. If so fallback to the last position. + // TODO: if we remove the use of query(pos-1), we won't need this fallback behavior + // WARNING: Unable to report error!!! + let offset = s.utf8_offset_to_unicode(left).unwrap_or_else(|e| e); + (offset, true) + } + RichtextStateChunk::Style { .. } => (1, false), + } + } + + fn get_cache_entity_len(cache: &<RichtextTreeTrait as BTreeTrait>::Cache) -> usize { + cache.entity_len as usize + } + } +} + +/// Whether new text inserted right in front of this anchor stays in front of +/// it: the start of an unmark (case 1 of `find_best_insert_pos`), or an anchor +/// that prefers inserts before it (case 2). +fn insert_stays_before_anchor(style: &StyleOp, anchor_type: AnchorType) -> bool { + (anchor_type == AnchorType::Start && (style.value.is_null() || style.value.is_false())) + || style.info.prefer_insert_before(anchor_type) +} + +impl RichtextState { + pub(crate) fn from_chunks<I: Iterator<Item = impl Into<RichtextStateChunk>>>(i: I) -> Self { + Self { + tree: i.collect(), + style_ranges: Default::default(), + cached_cursor: None, + } + } + + pub(crate) fn get_entity_index_for_text_insert( + &mut self, + pos: usize, + pos_type: PosType, + ) -> Result<(usize, Option<Cursor>), LoroError> { + self.check_cache(); + let result = { + if self.tree.is_empty() { + return Ok((0, None)); + } + + // A cached cursor next to a style anchor would skip the anchor + // rules of `find_best_insert_pos`. + let cached = self + .try_get_cache_or_clean(pos, pos_type) + .filter(|c| !self.has_styles() || !self.anchor_rules_may_move_insert(*c)); + if let Some(c) = cached { + let entity_index = self.get_cache_entity_index().unwrap(); + Ok((entity_index + c.offset, Some(c))) + } else { + let (c, entity_index) = match pos_type { + PosType::Bytes => self.find_best_insert_pos::<ByteQueryT>(pos), + PosType::Unicode => self.find_best_insert_pos::<UnicodeQueryT>(pos), + PosType::Utf16 => self.find_best_insert_pos::<Utf16QueryT>(pos), + PosType::Entity => self.find_best_insert_pos::<EntityQueryT>(pos), + PosType::Event => self.find_best_insert_pos::<EventIndexQueryT>(pos), + }; + + if let Some(c) = c { + debug_assert_eq!( + self.get_index_from_cursor(c, PosType::Entity).unwrap(), + entity_index + ); + self.record_cache( + c.leaf, + entity_index, + PosType::Entity, + c.offset, + Some(entity_index), + ); + } + Ok((entity_index, c)) + } + }; + self.check_cache(); + result + } + + /// Whether the anchor rules of `find_best_insert_pos` could put an insert + /// somewhere other than `cursor`. They cannot inside a text chunk, between + /// two text chunks, or at the end of a text chunk followed by an anchor + /// that new text stays in front of (the rules stop at that anchor). + fn anchor_rules_may_move_insert(&self, cursor: Cursor) -> bool { + let Some(elem) = self.tree.get_elem(cursor.leaf) else { + return true; + }; + if !matches!(elem, RichtextStateChunk::Text { .. }) { + return true; + } + if cursor.offset == 0 { + return self.tree.prev_elem(cursor).is_some_and(|prev| { + matches!( + self.tree.get_elem(prev.leaf), + Some(RichtextStateChunk::Style { .. }) + ) + }); + } + if cursor.offset < elem.rle_len() { + return false; + } + match self + .tree + .next_elem(cursor) + .and_then(|next| self.tree.get_elem(next.leaf)) + { + Some(RichtextStateChunk::Style { style, anchor_type }) => { + !insert_stays_before_anchor(style, *anchor_type) + } + _ => false, + } + } + + pub(crate) fn has_styles(&self) -> bool { + self.style_ranges + .as_ref() + .map(|x| x.has_style()) + .unwrap_or(false) + } + + pub(crate) fn range_has_style_key(&mut self, range: Range<usize>, key: &StyleKey) -> bool { + self.check_cache(); + let result = match self.style_ranges.as_ref() { + Some(s) => s.range_contains_key(range, key), + None => false, + }; + self.check_cache(); + result + } + + /// Whether every position in the entity range already resolves `key` to + /// `value`, in which case a mark with that key and value can be skipped. + pub(crate) fn range_has_style_key_value( + &mut self, + range: Range<usize>, + key: &str, + value: &LoroValue, + ) -> bool { + self.check_cache(); + let result = match self.style_ranges.as_ref() { + Some(s) => s.range_has_key_value(range, key, value), + None => false, + }; + self.check_cache(); + result + } + + /// Return the entity range and text styles at the given range. + /// If in the target range the leaves are not in the same span, the returned styles would be None + pub(crate) fn get_entity_range_and_text_styles_at_range( + &mut self, + range: Range<usize>, + pos_type: PosType, + ) -> (Range<usize>, Option<&Styles>) { + self.check_cache(); + let result = { + if self.tree.is_empty() { + return (0..0, None); + } + + let (start, _) = self + .get_entity_index_for_text_insert(range.start, pos_type) + .unwrap(); + let (end, _) = self + .get_entity_index_for_text_insert(range.end, pos_type) + .unwrap(); + if self.has_styles() { + ( + start..end, + self.style_ranges + .as_ref() + .unwrap() + .get_styles_of_range(start..end), + ) + } else { + (start..end, None) + } + }; + self.check_cache(); + result + } + + /// Get the insert text styles at the given entity index if we insert text at that position + /// + // TODO: PERF we can avoid this calculation by getting it when inserting new text + // but that requires a lot of changes + pub(crate) fn get_styles_at_entity_index_for_insert( + &mut self, + entity_index: usize, + ) -> StyleMeta { + self.check_cache(); + let result = { + if !self.has_styles() { + return Default::default(); + } + + self.style_ranges + .as_mut() + .unwrap() + .get_styles_for_insert(entity_index) + }; + self.check_cache(); + result + } + + /// This is used to accept changes from DiffCalculator + pub(crate) fn insert_at_entity_index( + &mut self, + entity_index: usize, + text: BytesSlice, + id: IdFull, + ) -> Cursor { + if text.len() > text_chunk::MAX_CHUNK_BYTES { + // Insert the pieces back to front at the same index; they end up in order. + let pieces = RichtextStateChunk::try_new(text, id).unwrap().into_pieces(); + let mut last = None; + for p in pieces.into_iter().rev() { + let RichtextStateChunk::Text(t) = p else { unreachable!() }; + last = Some(self.insert_at_entity_index(entity_index, t.bytes().clone(), t.id_full())); + } + return last.unwrap(); + } + self.check_cache(); + let result = { + let elem = RichtextStateChunk::try_new(text, id).unwrap(); + self.style_ranges + .as_mut() + .map(|x| x.insert(entity_index, elem.rle_len())); + let q = &entity_index; + if let Some(c) = self.try_get_cache_or_clean(entity_index, PosType::Entity) { + let p = self.tree.prefer_left(c).unwrap_or(c); + self.tree.insert_by_path(p, elem).0 + } else { + match self.tree.query::<EntityQuery>(q) { + Some(result) => { + let p = self + .tree + .prefer_left(result.cursor) + .unwrap_or(result.cursor); + self.tree.insert_by_path(p, elem).0 + } + None => self.tree.push(elem), + } + } + }; + self.record_cache( + result.leaf, + entity_index, + PosType::Entity, + result.offset, + None, + ); + self.check_cache(); + result + } + + /// This is used to accept changes from DiffCalculator. + /// + /// Return (event_index, styles) + pub(crate) fn insert_elem_at_entity_index( + &mut self, + entity_index: usize, + elem: RichtextStateChunk, + ) -> (usize, &Styles) { + let mut pieces = elem.into_pieces(); + let elem = pieces.remove(0); + for p in pieces.into_iter().rev() { + self.insert_elem_at_entity_index(entity_index, p); + } + self.clear_cache(); + let result = { + debug_assert!( + entity_index <= self.len_entity(), + "entity_index={} len={} self={:#?}", + entity_index, + self.len_entity(), + &self + ); + + let (c, f) = self + .tree + .query_with_finder_return::<EntityIndexQueryWithEventIndex>(&entity_index); + let cursor = c.map(|x| x.cursor); + let event_index = f.event_index; + self.clear_cache(); + + match cursor { + Some(cursor) => { + let styles = self + .style_ranges + .as_mut() + .map(|x| x.insert(entity_index, elem.rle_len())) + .unwrap_or(&EMPTY_STYLES); + self.tree.insert_by_path(cursor, elem); + (event_index, styles) + } + None => { + let styles = self + .style_ranges + .as_mut() + .map(|x| x.insert(entity_index, elem.rle_len())) + .unwrap_or(&EMPTY_STYLES); + self.tree.push(elem); + (0, styles) + } + } + }; + result + } + + /// Convert cursor position to event index: + /// + /// - If feature="wasm", index is utf16 index, + /// - If feature!="wasm", index is unicode index, + pub(crate) fn cursor_to_event_index(&self, cursor: Cursor) -> usize { + self.check_cache(); + let result = self.get_index_from_cursor(cursor, PosType::Event).unwrap(); + self.check_cache(); + result + } + + /// Cache-aware (`&mut`) variant of [`Self::cursor_to_event_index`] for the + /// per-op insert hot path. When the cursor lands in the currently cached + /// leaf, this reuses the memoized event-index start instead of doing a fresh + /// `visit_previous_caches` walk on every insert. + pub(crate) fn cursor_to_event_index_cached(&mut self, cursor: Cursor) -> usize { + self.check_cache(); + let ans = match self.cursor_index_via_cache(cursor, PosType::Event) { + Some(i) => { + debug_assert_eq!( + i, + self.get_index_from_cursor(cursor, PosType::Event).unwrap() + ); + i + } + None => self.get_index_from_cursor(cursor, PosType::Event).unwrap(), + }; + self.check_cache(); + ans + } + + pub(crate) fn cursor_to_unicode_index(&self, cursor: Cursor) -> usize { + self.check_cache(); + let result = self + .get_index_from_cursor(cursor, PosType::Unicode) + .unwrap(); + self.check_cache(); + result + } + + /// This method only updates `style_ranges`. + /// When this method is called, the style start anchor and the style end anchor should already have been inserted. + pub(crate) fn annotate_style_range(&mut self, range: Range<usize>, style: Arc<StyleOp>) { + self.check_cache(); + self.clear_cache(); + self.ensure_style_ranges_mut().annotate(range, style, None); + self.check_cache(); + } + + /// This method only updates `style_ranges`. + /// When this method is called, the style start anchor and the style end anchor should already have been inserted. + /// + /// This method will return the event of this annotation in event length + pub(crate) fn annotate_style_range_with_event( + &mut self, + range: Range<usize>, + style: Arc<StyleOp>, + ) -> impl Iterator<Item = (StyleMeta, usize)> + '_ { + self.check_cache(); + self.clear_cache(); + let mut ranges_in_entity_index: Vec<(StyleMeta, Range<usize>)> = Vec::new(); + let mut start = range.start; + let end = range.end; + self.ensure_style_ranges_mut().annotate( + range, + style, + Some(&mut |s, len| { + let range = start..start + len; + start += len; + ranges_in_entity_index.push((s.into(), range)); + }), + ); + + assert_eq!(ranges_in_entity_index.last().unwrap().1.end, end); + let mut converter = ContinuousIndexConverter::new(self); + let result = ranges_in_entity_index + .into_iter() + .filter_map(move |(meta, range)| { + let start = converter.convert_entity_index_to_event_index(range.start); + let end = converter.convert_entity_index_to_event_index(range.end); + if end == start { + return None; + } + + Some((meta, end - start)) + }); + self.check_cache(); + result + } + + /// init style ranges if not initialized + fn ensure_style_ranges_mut(&mut self) -> &mut StyleRangeMap { + self.clear_cache(); + let result = { + if self.style_ranges.is_none() { + self.style_ranges = Some(Box::default()); + } + + self.style_ranges.as_mut().unwrap() + }; + result + } + + pub(crate) fn get_char_by_event_index(&self, pos: usize) -> Result<char, ()> { + self.check_cache(); + let result = { + let cursor = self.tree.query::<EventIndexQuery>(&pos).unwrap().cursor; + let Some(str) = &self.tree.get_elem(cursor.leaf) else { + return Err(()); + }; + if cfg!(not(feature = "wasm")) { + let mut char_iter = str.as_str().unwrap().chars(); + match &mut char_iter.nth(cursor.offset) { + Some(c) => Ok(*c), + None => Err(()), + } + } else { + let s = str.as_str().unwrap(); + let utf16offset = unicode_to_utf16_index(s, cursor.offset).unwrap(); + // Convert utf16 offset to actual character by finding the character at that position + let char_iter = s.chars(); + let mut current_utf16_offset = 0; + + for c in char_iter { + if current_utf16_offset == utf16offset { + return Ok(c); + } + current_utf16_offset += c.len_utf16(); + if current_utf16_offset > utf16offset { + return Err(()); + } + } + Err(()) + } + }; + self.check_cache(); + result + } + + /// Find the best insert position based on the rich-text CRDT algorithm. + /// + /// The result is only different from `query` when there are style anchors around the insert pos. + /// Returns the right neighbor of the insert pos and the entity index. + /// + /// 1. Insertions occur before style anchors that contain the beginning of new marks. + /// 2. Insertions occur before style anchors that contain the end of bold-like marks + /// 3. Insertions occur after style anchors that contain the end of link-like marks + /// + /// Rule 1 should be satisfied before rules 2 and 3 to avoid creating a new style out of nowhere + /// + /// The current method will scan forward to find the last position that satisfies 1 and 2. + /// Then it scans backward to find the first position that satisfies 3. + fn find_best_insert_pos<Q: QueryByLen<RichtextTreeTrait>>( + &self, + pos: usize, + ) -> (Option<generic_btree::Cursor>, usize) { + type Query<Q> = IndexQueryWithEntityIndex<Q, RichtextTreeTrait>; + if self.tree.is_empty() { + return (None, 0); + } + + // There are a range of elements may share the same unicode index + // because style anchors' lengths are zero in unicode index. + + // Find the start and the end of the range, and entity index of left cursor + let (left, right, mut entity_index) = if pos == 0 { + let left = self.tree.start_cursor().unwrap(); + let mut right = left; + let mut elem = self.tree.get_elem(right.leaf).unwrap(); + let entity_index = 0; + if matches!(elem, RichtextStateChunk::Text { .. }) { + return (Some(right), 0); + } else { + while Q::get_elem_len(elem) == 0 { + match self.tree.next_elem(right) { + Some(r) => { + right = r; + elem = self.tree.get_elem(right.leaf).unwrap(); + } + None => { + right.offset = elem.rle_len(); + break; + } + } + } + + (left, right, entity_index) + } + } else { + // The query prefers right when there are empty elements (style anchors) + // So the nodes between (pos-1) and pos are all style anchors. + let (q, f) = self.tree.query_with_finder_return::<Query<Q>>(&(pos - 1)); + let q = q.unwrap(); + let mut entity_index = f.entity_index(); + + let elem = self.tree.get_elem(q.leaf()).unwrap(); + let mut right = q.cursor; + right.offset += 1; + entity_index += 1; + if elem.rle_len() > right.offset { + // The cursor is in the middle of a style anchor + return (Some(right), entity_index); + } + + match self.tree.next_elem(q.cursor) { + // If next is None, we know the range is empty, return directly + None => return (self.tree.end_cursor(), entity_index), + Some(x) => { + assert_eq!(right.offset, elem.rle_len()); + right = x; + let mut elem = self.tree.get_elem(right.leaf).unwrap(); + if matches!(elem, RichtextStateChunk::Text { .. }) { + return (Some(right), entity_index); + } + + let left = x; + while matches!(elem, RichtextStateChunk::Style { .. }) { + match self.tree.next_elem(right) { + Some(r) => { + right = r; + elem = self.tree.get_elem(right.leaf).unwrap(); + } + None => { + // this is last element + right.offset = 1; + break; + } + } + } + + (left, right, entity_index) + } + } + }; + + let mut iter = left; + + // need to scan from left to right + let mut visited = Vec::new(); + while iter != right { + let Some(elem) = self.tree.get_elem(iter.leaf) else { + break; + }; + + let (style, anchor_type) = match elem { + RichtextStateChunk::Text { .. } => unreachable!(), + RichtextStateChunk::Style { style, anchor_type } => (style, *anchor_type), + }; + + visited.push((style, anchor_type, iter, entity_index)); + if insert_stays_before_anchor(style, anchor_type) { + // case 1 or 2. + break; + } + + iter = match self.tree.next_elem(iter) { + Some(x) => x, + None => self.tree.end_cursor().unwrap(), + }; + entity_index += 1; + } + + while let Some((style, anchor_type, top_elem, top_entity_index)) = visited.pop() { + if !style.info.prefer_insert_before(anchor_type) { + // case 3. + break; + } + + iter = top_elem; + entity_index = top_entity_index; + } + + (Some(iter), entity_index) + } + + fn get_entity_index_from_path(&self, right: generic_btree::Cursor) -> usize { + self.get_index_from_cursor(right, PosType::Entity).unwrap() + } + + pub fn get_index_from_cursor( + &self, + cursor: generic_btree::Cursor, + pos_type: PosType, + ) -> Option<usize> { + let mut index = 0; + self.tree + .visit_previous_caches(cursor, |cache| match cache { + generic_btree::PreviousCache::NodeCache(c) => { + index += c.get_len(pos_type) as usize; + } + generic_btree::PreviousCache::PrevSiblingElem(c) => { + index += c.len_with(pos_type); + } + generic_btree::PreviousCache::ThisElemAndOffset { elem, offset } => { + if offset != 0 { + index += entity_offset_to_pos_type_offset(pos_type, elem, offset) + } + } + }); + + Some(index) + } + + pub(crate) fn get_text_entity_ranges( + &self, + pos: usize, + len: usize, + pos_type: PosType, + ) -> LoroResult<EntityRanges> { + self.check_cache(); + let result = { + if self.tree.is_empty() { + return Ok(EntityRanges::new()); + } + + if len == 0 { + return Ok(EntityRanges::new()); + } + + if pos + len > self.len(pos_type) { + return Ok(EntityRanges::new()); + } + + let mut ans: EntityRanges = SmallVec::new(); + let (start, end) = match pos_type { + PosType::Bytes => ( + self.tree.query::<ByteQuery>(&pos).unwrap().cursor, + self.tree.query::<ByteQuery>(&(pos + len)).unwrap().cursor, + ), + PosType::Unicode => ( + self.tree.query::<UnicodeQuery>(&pos).unwrap().cursor, + self.tree + .query::<UnicodeQuery>(&(pos + len)) + .unwrap() + .cursor, + ), + PosType::Utf16 => ( + self.tree.query::<Utf16Query>(&pos).unwrap().cursor, + self.tree.query::<Utf16Query>(&(pos + len)).unwrap().cursor, + ), + PosType::Entity => ( + self.tree.query::<EntityQuery>(&pos).unwrap().cursor, + self.tree.query::<EntityQuery>(&(pos + len)).unwrap().cursor, + ), + PosType::Event => ( + self.tree.query::<EventIndexQuery>(&pos).unwrap().cursor, + self.tree + .query::<EventIndexQuery>(&(pos + len)) + .unwrap() + .cursor, + ), + }; + + // TODO: assert end cursor is valid + let mut entity_index = self.get_entity_index_from_path(start); + for span in self.tree.iter_range(start..end) { + let start = span.start.unwrap_or(0); + let end = span.end.unwrap_or(span.elem.rle_len()); + if end == 0 { + break; + } + + let len = end - start; + match span.elem { + RichtextStateChunk::Text(s) => { + let event_len = s.entity_range_to_event_range(start..end).len(); + let id = s.id().inc(start as i32); + match ans.last_mut() { + // Every entity of a range is text, so its IDs advance by + // the entity length (not the UTF-16 event length). + Some(last) + if last.entity_end == entity_index + && last.id_start.inc(last.entity_len() as i32) == id => + { + last.entity_end += len; + last.event_len += event_len; + } + _ => { + ans.push(EntityRangeInfo { + id_start: id, + entity_start: entity_index, + entity_end: entity_index + len, + event_len, + }); + } + } + entity_index += len; + } + RichtextStateChunk::Style { .. } => { + entity_index += 1; + } + } + } + + Ok(ans) + }; + self.check_cache(); + result + } + + pub(crate) fn get_text_slice_by_event_index( + &self, + pos: usize, + len: usize, + ) -> LoroResult<String> { + self.check_cache(); + let result = { + if self.tree.is_empty() { + return Ok(String::new()); + } + + if len == 0 { + return Ok(String::new()); + } + + if pos + len > self.len_event() { + return Err(LoroError::OutOfBound { + pos: pos + len, + len: self.len_event(), + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }); + } + + let mut ans = String::new(); + let (start, end) = ( + self.tree.query::<EventIndexQuery>(&pos).unwrap().cursor, + self.tree + .query::<query::EndQuery<EventIndexQueryT>>(&(pos + len)) + .unwrap() + .cursor, + ); + + for span in self.tree.iter_range(start..end) { + let start = span.start.unwrap_or(0); + let end = span.end.unwrap_or(span.elem.rle_len()); + if end == 0 { + break; + } + + if let RichtextStateChunk::Text(s) = span.elem { + match s.unicode_slice(start, end) { + Ok(x) => ans.push_str(x), + Err(()) => { + return Err(LoroError::UTF16InUnicodeCodePoint { pos: pos + len }) + } + } + } + } + + Ok(ans) + }; + self.check_cache(); + result + } + + pub(crate) fn slice_delta( + &self, + start_index: usize, + end_index: usize, + pos_type: PosType, + ) -> LoroResult<Vec<(String, StyleMeta)>> { + if end_index < start_index { + return Err(LoroError::EndIndexLessThanStartIndex { + start: start_index, + end: end_index, + }); + } + + if end_index == start_index { + return Ok(Vec::new()); + } + + self.check_cache(); + let result = { + // 1. Convert start/end pos to cursors + let (start_query, end_query) = match pos_type { + PosType::Event => ( + self.tree.query::<EventIndexQuery>(&start_index), + self.tree + .query::<query::EndQuery<EventIndexQueryT>>(&end_index), + ), + PosType::Bytes => ( + self.tree.query::<ByteQuery>(&start_index), + self.tree.query::<query::EndQuery<ByteQueryT>>(&end_index), + ), + PosType::Unicode => ( + self.tree.query::<UnicodeQuery>(&start_index), + self.tree + .query::<query::EndQuery<UnicodeQueryT>>(&end_index), + ), + PosType::Utf16 => ( + self.tree.query::<Utf16Query>(&start_index), + self.tree.query::<query::EndQuery<Utf16QueryT>>(&end_index), + ), + PosType::Entity => ( + self.tree.query::<EntityQuery>(&start_index), + self.tree.query::<EntityQuery>(&end_index), + ), + }; + + let start_cursor = start_query + .ok_or(LoroError::OutOfBound { + pos: start_index, + len: self.len(pos_type), + info: "".into(), + })? + .cursor; + let end_cursor = end_query + .ok_or(LoroError::OutOfBound { + pos: end_index, + len: self.len(pos_type), + info: "".into(), + })? + .cursor; + + // 2. Get start entity index + let mut current_entity_index = self + .get_index_from_cursor(start_cursor, PosType::Entity) + .unwrap(); + // We need end entity index for style iterator + let end_entity_index = self + .get_index_from_cursor(end_cursor, PosType::Entity) + .unwrap(); + + // 3. Setup style iterator + let mut style_range_iter: Box<dyn Iterator<Item = (Range<usize>, &Styles)>> = + match &self.style_ranges { + Some(s) => { + let mut idx = current_entity_index; + Box::new(s.iter_range(current_entity_index..end_entity_index).map( + move |elem_slice| { + let len = elem_slice.end.unwrap_or(elem_slice.elem.len) + - elem_slice.start.unwrap_or(0); + let range = idx..idx + len; + idx += len; + (range, &elem_slice.elem.styles) + }, + )) + } + None => Box::new(Some((0..usize::MAX / 2, &*EMPTY_STYLES)).into_iter()), + }; + + let mut cur_style_range = style_range_iter.next(); + let mut cur_styles: Option<StyleMeta> = + cur_style_range.as_ref().map(|x| StyleMeta::from(x.1)); + + let mut ans: Vec<(String, StyleMeta)> = Vec::new(); + + // 4. Iterate tree range + for span in self.tree.iter_range(start_cursor..end_cursor) { + match &span.elem { + RichtextStateChunk::Text(t) => { + let chunk_len = + span.end.unwrap_or(span.elem.rle_len()) - span.start.unwrap_or(0); // length in rle_len (unicode_len) + let mut processed_len = 0; + + while processed_len < chunk_len { + while let Some((inner_cur_range, _)) = cur_style_range.as_ref() { + if current_entity_index >= inner_cur_range.end { + cur_style_range = style_range_iter.next(); + cur_styles = + cur_style_range.as_ref().map(|x| StyleMeta::from(x.1)); + } else { + break; + } + } + + if cur_style_range.is_none() { + cur_styles = Some(StyleMeta::default()); + cur_style_range = + Some((current_entity_index..usize::MAX, &*EMPTY_STYLES)); + } + + let (inner_cur_range, _) = cur_style_range.as_ref().unwrap(); + + let remaining_text = chunk_len - processed_len; + let remaining_style = inner_cur_range.end - current_entity_index; + let take_len = remaining_text.min(remaining_style); + + let slice_start = span.start.unwrap_or(0) + processed_len; + let slice_end = slice_start + take_len; + + let text_content = + t.unicode_slice(slice_start, slice_end).map_err(|_| { + LoroError::OutOfBound { + pos: slice_end, + len: t.unicode_len() as usize, + info: "Slice delta out of bound".into(), + } + })?; + + let styles = cur_styles.as_ref().unwrap(); + if let Some(last) = ans.last_mut() { + if &last.1 == styles { + last.0.push_str(text_content); + processed_len += take_len; + current_entity_index += take_len; + continue; + } + } + + ans.push((text_content.to_string(), styles.clone())); + + processed_len += take_len; + current_entity_index += take_len; + } + } + RichtextStateChunk::Style { .. } => { + current_entity_index += 1; + } + } + } + + Ok(ans) + }; + self.check_cache(); + result + } + + // PERF: can be splitted into two methods. One is without cursor_to_event_index + // PERF: can be speed up a lot by detecting whether the range is in a single leaf first + /// This is used to accept changes from DiffCalculator + #[instrument(skip(self, f))] + pub(crate) fn drain_by_entity_index( + &mut self, + pos: usize, + len: usize, + mut f: Option<&mut dyn FnMut(RichtextStateChunk)>, + ) -> DrainInfo { + let result = { + assert!( + pos + len <= self.len_entity(), + "pos: {}, len: {}, self.len(): {}", + pos, + len, + &self.len_entity(), + ); + + self.clear_cache(); + // PERF: may use cache to speed up + let range = pos..pos + len; + let (start, start_f) = self + .tree + .query_with_finder_return::<EntityIndexQueryWithEventIndex>(&range.start); + let start_cursor = start.unwrap().cursor(); + let elem = self.tree.get_elem(start_cursor.leaf).unwrap(); + + /// This struct remove the corresponding style ranges if the start style anchor is removed + struct StyleRangeUpdater<'a> { + style_ranges: Option<&'a mut StyleRangeMap>, + current_index: usize, + start: usize, + end: usize, + } + + impl<'a> StyleRangeUpdater<'a> { + fn update(&mut self, elem: &RichtextStateChunk) { + match &elem { + RichtextStateChunk::Text(t) => { + self.current_index += t.unicode_len() as usize; + } + RichtextStateChunk::Style { style, anchor_type } => { + if matches!(anchor_type, AnchorType::End) { + self.end = self.end.max(self.current_index); + if let Some(s) = self.style_ranges.as_mut() { + let start = + s.remove_style_scanning_backward(style, self.current_index); + self.start = self.start.min(start); + } + } + + self.current_index += 1; + } + } + } + + fn new( + style_ranges: Option<&'a mut Box<StyleRangeMap>>, + start_index: usize, + ) -> Self { + Self { + style_ranges: style_ranges.map(|x| &mut **x), + current_index: start_index, + end: 0, + start: usize::MAX, + } + } + + fn get_affected_range(&self, pos: usize) -> Option<Range<usize>> { + if self.start == usize::MAX { + None + } else { + let start = self.start.min(pos); + let end = self.end.min(pos); + if start == end { + None + } else { + Some(start..end) + } + } + } + } + + if elem.rle_len() >= start_cursor.offset + len { + // drop in place + let mut event_len = 0; + let mut updater = StyleRangeUpdater::new(self.style_ranges.as_mut(), pos); + self.tree.update_leaf(start_cursor.leaf, |elem| { + updater.update(&*elem); + match elem { + RichtextStateChunk::Text(text) => { + if let Some(f) = f { + let span = + text.slice(start_cursor.offset..start_cursor.offset + len); + f(RichtextStateChunk::Text(span)); + } + let (next, event_len_) = + text.delete_by_entity_index(start_cursor.offset, len); + event_len = event_len_; + (true, next.map(RichtextStateChunk::Text), None) + } + RichtextStateChunk::Style { .. } => { + if let Some(f) = f { + let v = std::mem::replace( + elem, + RichtextStateChunk::Text(TextChunk::new_empty()), + ); + f(v); + } else { + *elem = RichtextStateChunk::Text(TextChunk::new_empty()); + } + (true, None, None) + } + } + }); + + let affected_range = updater.get_affected_range(pos); + if let Some(s) = self.style_ranges.as_mut() { + s.delete(pos..pos + len); + } + + DrainInfo { + start_event_index: start_f.event_index, + end_event_index: (start_f.event_index + event_len), + affected_style_range: affected_range.map(|entity_range| { + ( + entity_range.clone(), + self.entity_index_to_event_index(entity_range.start) + ..self.entity_index_to_event_index(entity_range.end), + ) + }), + } + } else { + let (end, end_f) = self + .tree + .query_with_finder_return::<EntityIndexQueryWithEventIndex>(&range.end); + let mut updater = StyleRangeUpdater::new(self.style_ranges.as_mut(), pos); + for iter in generic_btree::iter::Drain::new(&mut self.tree, start, end) { + updater.update(&iter); + if let Some(f) = f.as_mut() { + f(iter) + } + } + + let affected_range = updater.get_affected_range(pos); + if let Some(s) = self.style_ranges.as_mut() { + s.delete(pos..pos + len); + } + + DrainInfo { + start_event_index: start_f.event_index, + end_event_index: end_f.event_index, + affected_style_range: affected_range.map(|entity_range| { + ( + entity_range.clone(), + self.entity_index_to_event_index(entity_range.start) + ..self.entity_index_to_event_index(entity_range.end), + ) + }), + } + } + }; + result + } + + pub fn entity_index_to_event_index(&self, index: usize) -> usize { + if index == 0 { + // the tree maybe empty + return 0; + } + let cursor = self.tree.query::<EntityQuery>(&index).unwrap(); + self.cursor_to_event_index(cursor.cursor) + } + + pub fn index_to_event_index(&self, index: usize, pos_type: PosType) -> usize { + if self.tree.is_empty() { + return 0; + } + + let cursor = match pos_type { + PosType::Entity => self.tree.query::<EntityQuery>(&index).unwrap(), + PosType::Utf16 => self.tree.query::<Utf16Query>(&index).unwrap(), + PosType::Bytes => self.tree.query::<ByteQuery>(&index).unwrap(), + PosType::Event => return index, + PosType::Unicode => self.tree.query::<UnicodeQuery>(&index).unwrap(), + }; + + self.cursor_to_event_index(cursor.cursor) + } + + pub fn event_index_to_unicode_index(&self, index: usize) -> usize { + if !cfg!(feature = "wasm") { + return index; + } + + let Some(cursor) = self.tree.query::<EventIndexQuery>(&index) else { + return 0; + }; + + self.cursor_to_unicode_index(cursor.cursor) + } + + /// Convert an event-index position into the index of `pos_type`. + /// + /// This runs in O(log n) by querying the tree once and reading the prefix + /// caches from the resulting cursor, instead of materializing the whole + /// prefix string. + pub fn event_index_to_index(&self, event_index: usize, pos_type: PosType) -> usize { + if self.tree.is_empty() { + return 0; + } + + let cursor = self.tree.query::<EventIndexQuery>(&event_index).unwrap(); + self.get_index_from_cursor(cursor.cursor, pos_type).unwrap() + } + + #[allow(unused)] + pub(crate) fn check(&self) { + if !cfg!(any(debug_assertions, test)) { + return; + } + + self.tree.check(); + self.check_consistency_between_content_and_style_ranges(); + self.check_style_anchors_appear_in_pairs(); + } + + pub(crate) fn mark_with_entity_index(&mut self, range: Range<usize>, style: Arc<StyleOp>) { + self.check_cache(); + self.clear_cache(); + if self.tree.is_empty() { + panic!("Cannot mark an empty tree"); + } + + self.insert_elem_at_entity_index( + range.end, + RichtextStateChunk::from_style(style.clone(), AnchorType::End), + ); + self.insert_elem_at_entity_index( + range.start, + RichtextStateChunk::from_style(style.clone(), AnchorType::Start), + ); + // end_entity_index + 2, because + // 1. We inserted a start anchor before end_entity_index, so we need to +1 + // 2. We need to include the end anchor in the range, so we need to +1 + self.ensure_style_ranges_mut() + .annotate(range.start..range.end + 2, style, None); + self.check_cache(); + } + + pub fn iter(&self) -> impl Iterator<Item = RichtextSpan> + '_ { + let mut entity_index = 0; + let mut style_range_iter: Box<dyn Iterator<Item = (Range<usize>, &Styles)>> = + match &self.style_ranges { + Some(s) => Box::new(s.iter()), + None => Box::new(Some((0..usize::MAX / 2, &*EMPTY_STYLES)).into_iter()), + }; + let mut cur_style_range = style_range_iter.next(); + let mut cur_styles: Option<StyleMeta> = + cur_style_range.as_ref().map(|x| StyleMeta::from(x.1)); + + self.tree.iter().filter_map(move |x| match x { + RichtextStateChunk::Text(s) => { + let mut styles = Default::default(); + while let Some((inner_cur_range, _)) = cur_style_range.as_ref() { + if entity_index < inner_cur_range.start { + break; + } + + if entity_index < inner_cur_range.end { + styles = cur_styles.as_ref().unwrap().clone(); + break; + } else { + cur_style_range = style_range_iter.next(); + cur_styles = cur_style_range.as_ref().map(|x| StyleMeta::from(x.1)); + } + } + + entity_index += s.rle_len(); + Some(RichtextSpan { + text: s.bytes().clone().into(), + attributes: styles, + }) + } + RichtextStateChunk::Style { .. } => { + entity_index += 1; + None + } + }) + } + + #[inline] + pub fn iter_chunk(&self) -> impl Iterator<Item = &RichtextStateChunk> { + self.tree.iter() + } + + pub fn get_richtext_value(&self) -> LoroValue { + self.check_cache(); + let result = { + let mut ans: Vec<LoroValue> = Vec::new(); + let mut last_attributes: Option<LoroValue> = None; + for span in self.iter() { + let attributes: LoroValue = span.attributes.to_value(); + if let Some(last) = last_attributes.as_ref() { + if &attributes == last { + let hash_map = ans.last_mut().unwrap().as_map_mut().unwrap(); + let s = hash_map + .make_mut() + .get_mut("insert") + .unwrap() + .as_string_mut() + .unwrap(); + s.make_mut().push_str(span.text.as_str()); + continue; + } + } + + let mut value = FxHashMap::default(); + value.insert( + "insert".into(), + LoroValue::String(span.text.as_str().into()), + ); + + if !attributes.as_map().unwrap().is_empty() { + value.insert("attributes".into(), attributes.clone()); + } + + ans.push(LoroValue::Map(value.into())); + last_attributes = Some(attributes); + } + + LoroValue::List(ans.into()) + }; + self.check_cache(); + result + } + + #[allow(unused)] + pub fn to_vec(&self) -> Vec<RichtextSpan> { + self.iter().collect() + } + + #[cfg(test)] + #[allow(unused)] + pub(crate) fn debug(&self) { + dbg!(&self.tree); + dbg!(&self.style_ranges); + } + + #[inline(always)] + pub fn len_unicode(&self) -> usize { + self.tree.root_cache().unicode_len as usize + } + + #[inline(always)] + pub fn len_utf16(&self) -> usize { + self.tree.root_cache().utf16_len as usize + } + + #[inline(always)] + pub fn len_utf8(&self) -> usize { + self.tree.root_cache().bytes as usize + } + + #[inline(always)] + pub fn is_empty(&self) -> bool { + self.tree.root_cache().entity_len == 0 + } + + #[inline(always)] + pub fn len_entity(&self) -> usize { + self.tree.root_cache().entity_len as usize + } + + #[inline(always)] + pub(crate) fn content_node_len(&self) -> usize { + self.tree.node_len() + } + + pub fn diagnose(&self) { + println!( + "rope_nodes: {}, style_nodes: {}, text_len: {}", + self.tree.node_len(), + self.style_ranges + .as_ref() + .map(|x| x.tree.node_len()) + .unwrap_or(0), + self.tree.root_cache().bytes + ); + } + + /// Check if the content and style ranges are consistent. + /// + /// Panic if inconsistent. + pub(crate) fn check_consistency_between_content_and_style_ranges(&self) { + if !cfg!(debug_assertions) { + return; + } + + // A start anchor whose end is not in the state (a version that holds a + // mark's `StyleStart` but not its `StyleEnd`, loro-dev/loro#1165) styles + // nothing, so it has no style range. + let closed: FxHashSet<&Arc<StyleOp>> = self + .iter_chunk() + .filter_map(|c| match c { + RichtextStateChunk::Style { + style, + anchor_type: AnchorType::End, + } => Some(style), + _ => None, + }) + .collect(); + let mut entity_index_to_style_anchor: FxHashMap<usize, &RichtextStateChunk> = + FxHashMap::default(); + let mut index = 0; + for c in self.iter_chunk() { + if let RichtextStateChunk::Style { style, .. } = c { + if closed.contains(style) { + entity_index_to_style_anchor.insert(index, c); + } + } + + index += c.length() + } + + if let Some(s) = &self.style_ranges { + for IterAnchorItem { + index, + op, + anchor_type: iter_anchor_type, + } in s.iter_anchors() + { + let c = entity_index_to_style_anchor + .remove(&index) + .unwrap_or_else(|| { + panic!( + "Inconsistency found {} {:?} {:?}", + index, iter_anchor_type, &op + ); + }); + + match c { + RichtextStateChunk::Text(_) => { + unreachable!() + } + RichtextStateChunk::Style { style, anchor_type } => { + assert_eq!(style, &op); + assert_eq!(&iter_anchor_type, anchor_type); + } + } + } + } + + assert!( + entity_index_to_style_anchor.is_empty(), + "Inconsistency found. Some anchors are not reflected in style ranges {:#?}", + &entity_index_to_style_anchor + ); + } + + /// Every end anchor must follow its start anchor. A start anchor may lack its end. + pub(crate) fn check_style_anchors_appear_in_pairs(&self) { + if !cfg!(any(debug_assertions, test)) { + return; + } + + let mut start_ops: FxHashSet<&Arc<StyleOp>> = Default::default(); + for item in self.iter_chunk() { + match item { + RichtextStateChunk::Text(_) => {} + RichtextStateChunk::Style { style, anchor_type } => match anchor_type { + AnchorType::Start => { + start_ops.insert(style); + } + AnchorType::End => { + assert!(start_ops.remove(style), "End anchor without start anchor"); + } + }, + } + } + // A start anchor without its end is allowed: a version can hold a mark's + // `StyleStart` op but not its `StyleEnd` op (loro-dev/loro#1165). + let _ = start_ops; + } + + /// Iter style ranges in the given range in entity index + pub(crate) fn iter_range( + &self, + range: impl RangeBounds<usize>, + ) -> impl Iterator<Item = IterRangeItem<'_>> + '_ { + self.check_cache(); + let result = { + let start = match range.start_bound() { + Bound::Included(x) => *x, + Bound::Excluded(x) => x + 1, + Bound::Unbounded => 0, + }; + let end = match range.end_bound() { + Bound::Included(x) => x + 1, + Bound::Excluded(x) => *x, + Bound::Unbounded => self.len_entity(), + }; + assert!(end > start); + assert!(end <= self.len_entity()); + + let mut style_iter = self + .style_ranges + .as_ref() + .map(|x| x.iter_range(range)) + .into_iter() + .flatten(); + + let start = self.tree.query::<EntityQuery>(&start).unwrap(); + let end = self.tree.query::<EntityQuery>(&end).unwrap(); + let mut content_iter = self.tree.iter_range(start.cursor..end.cursor); + let mut style_left_len = usize::MAX; + let mut cur_style = style_iter + .next() + .map(|x| { + style_left_len = x.elem.len - x.start.unwrap_or(0); + &x.elem.styles + }) + .unwrap_or(&*EMPTY_STYLES); + let mut chunk = content_iter.next(); + let mut offset = 0; + let mut chunk_left_len = chunk + .as_ref() + .map(|x| { + let len = x.elem.rle_len(); + offset = x.start.unwrap_or(0); + x.end.map(|v| v.min(len)).unwrap_or(len) - offset + }) + .unwrap_or(0); + std::iter::from_fn(move || { + if chunk_left_len == 0 { + chunk = content_iter.next(); + chunk_left_len = chunk + .as_ref() + .map(|x| { + let len = x.elem.rle_len(); + x.end.map(|v| v.min(len)).unwrap_or(len) + }) + .unwrap_or(0); + offset = 0; + } + + let iter_chunk = chunk.as_ref()?; + + let styles = cur_style; + let iter_len; + let event_range; + if chunk_left_len >= style_left_len { + iter_len = style_left_len; + event_range = iter_chunk + .elem + .entity_range_to_event_range(offset..offset + iter_len); + chunk_left_len -= style_left_len; + offset += style_left_len; + style_left_len = 0; + } else { + iter_len = chunk_left_len; + event_range = iter_chunk + .elem + .entity_range_to_event_range(offset..offset + iter_len); + style_left_len -= chunk_left_len; + chunk_left_len = 0; + } + + if style_left_len == 0 { + cur_style = style_iter + .next() + .map(|x| { + style_left_len = x.elem.len; + &x.elem.styles + }) + .unwrap_or(&*EMPTY_STYLES); + } + + Some(IterRangeItem { + chunk: iter_chunk.elem, + styles, + entity_len: iter_len, + event_len: event_range.len(), + }) + }) + }; + self.check_cache(); + result + } + + pub(crate) fn get_stable_position_at_event_index( + &self, + pos: usize, + kind: PosType, + ) -> Option<ID> { + self.check_cache(); + let result = { + if pos >= self.len(kind) { + return None; + } + + let cursor = match kind { + PosType::Event => self.tree.query::<EventIndexQuery>(&pos)?, + PosType::Unicode => self.tree.query::<UnicodeQuery>(&pos)?, + _ => unreachable!("stable text positions use event or Unicode indices"), + }; + + // A WASM event index is a UTF-16 offset. The tree query rounds an + // offset inside a surrogate pair down to the scalar's start, so + // compare it back to reject non-boundaries before selecting an ID. + if self.get_index_from_cursor(cursor.cursor, kind)? != pos { + return None; + } + + let range_len = if kind == PosType::Event && cfg!(feature = "wasm") { + self.get_char_by_event_index(pos).ok()?.len_utf16() + } else { + 1 + }; + let v = &self.get_text_entity_ranges(pos, range_len, kind).unwrap(); + let a = v.first()?; + Some(a.id_start) + }; + self.check_cache(); + result + } + + pub(crate) fn len_event(&self) -> usize { + self.check_cache(); + let result = { + if cfg!(feature = "wasm") { + self.len_utf16() + } else { + self.len_unicode() + } + }; + self.check_cache(); + result + } + + pub(crate) fn len(&self, pos_type: PosType) -> usize { + self.check_cache(); + let result = { + match pos_type { + PosType::Unicode => self.len_unicode(), + PosType::Utf16 => self.len_utf16(), + PosType::Entity => self.len_entity(), + PosType::Event => self.len_event(), + PosType::Bytes => self.len_utf8(), + } + }; + self.check_cache(); + result + } +} + +fn entity_offset_to_pos_type_offset( + pos_type: PosType, + elem: &RichtextStateChunk, + offset: usize, +) -> usize { + match pos_type { + PosType::Bytes => match elem { + RichtextStateChunk::Text(t) => t.unicode_offset_to_utf8(offset).unwrap(), + RichtextStateChunk::Style { .. } => 0, + }, + PosType::Unicode => match elem { + RichtextStateChunk::Text(_) => offset, + RichtextStateChunk::Style { .. } => 0, + }, + PosType::Utf16 => match elem { + RichtextStateChunk::Text(t) => t.unicode_offset_to_utf16(offset).unwrap(), + RichtextStateChunk::Style { .. } => 0, + }, + PosType::Entity => offset, + PosType::Event => match elem { + RichtextStateChunk::Text(t) => { + if cfg!(feature = "wasm") { + t.unicode_offset_to_utf16(offset).unwrap() + } else { + offset + } + } + RichtextStateChunk::Style { .. } => 0, + }, + } +} + +fn pos_type_offset_to_entity_offset( + pos_type: PosType, + elem: &RichtextStateChunk, + offset: usize, +) -> Option<usize> { + match pos_type { + PosType::Bytes => match elem { + RichtextStateChunk::Text(t) => t.utf8_offset_to_unicode(offset).ok(), + RichtextStateChunk::Style { .. } => { + if offset > 0 { + None + } else { + Some(0) + } + } + }, + PosType::Unicode => Some(offset), + PosType::Utf16 => match elem { + RichtextStateChunk::Text(t) => t.utf16_offset_to_unicode(offset).ok(), + RichtextStateChunk::Style { .. } => { + if offset > 0 { + None + } else { + Some(0) + } + } + }, + PosType::Entity => { + if offset > elem.rle_len() { + None + } else { + Some(offset) + } + } + PosType::Event => match elem { + RichtextStateChunk::Text(t) => { + if cfg!(feature = "wasm") { + t.utf16_offset_to_unicode(offset).ok() + } else if offset < t.unicode_len() as usize { + Some(offset) + } else { + None + } + } + RichtextStateChunk::Style { .. } => { + if offset > 0 { + None + } else { + Some(0) + } + } + }, + } +} + +pub(crate) struct DrainInfo { + pub start_event_index: usize, + pub end_event_index: usize, + // entity range, event range + pub affected_style_range: Option<(Range<usize>, Range<usize>)>, +} + +pub(crate) struct IterRangeItem<'a> { + pub(crate) chunk: &'a RichtextStateChunk, + pub(crate) styles: &'a Styles, + pub(crate) entity_len: usize, + pub(crate) event_len: usize, +} + +use converter::ContinuousIndexConverter; +mod converter { + use generic_btree::{rle::HasLength, Cursor}; + + use super::{query::EntityQuery, RichtextState}; + + /// Convert entity index into event index. + /// It assumes the entity_index are in ascending order + pub(super) struct ContinuousIndexConverter<'a> { + state: &'a RichtextState, + last_entity_index_cache: Option<ConverterCache>, + } + + struct ConverterCache { + entity_index: usize, + cursor: Cursor, + event_index: usize, + cursor_elem_len: usize, + } + + impl<'a> ContinuousIndexConverter<'a> { + pub fn new(state: &'a RichtextState) -> Self { + Self { + state, + last_entity_index_cache: None, + } + } + + pub fn convert_entity_index_to_event_index(&mut self, entity_index: usize) -> usize { + self.state.check_cache(); + let result = { + if let Some(last) = self.last_entity_index_cache.as_ref() { + if last.entity_index == entity_index { + return last.event_index; + } + + assert!(entity_index > last.entity_index); + if last.cursor.offset + entity_index - last.entity_index < last.cursor_elem_len + { + // in the same cursor + return self.state.cursor_to_event_index(Cursor { + leaf: last.cursor.leaf, + offset: last.cursor.offset + entity_index - last.entity_index, + }); + } + } + + let cursor = self + .state + .tree + .query::<EntityQuery>(&entity_index) + .unwrap() + .cursor; + let ans = self.state.cursor_to_event_index(cursor); + let len = self.state.tree.get_elem(cursor.leaf).unwrap().rle_len(); + self.last_entity_index_cache = Some(ConverterCache { + entity_index, + cursor, + event_index: ans, + cursor_elem_len: len, + }); + ans + }; + self.state.check_cache(); + result + } + } +} + +#[cfg(test)] +mod insert_pos_cache_test; + +#[cfg(test)] +mod test { + use append_only_bytes::AppendOnlyBytes; + use serde_json::json; + + use crate::{container::richtext::TextStyleInfoFlag, ToJson}; + + use super::*; + + #[derive(Debug, Default, Clone)] + struct SimpleWrapper { + state: RichtextState, + bytes: AppendOnlyBytes, + } + + impl SimpleWrapper { + fn insert(&mut self, pos: usize, text: &str) { + let start = self.bytes.len(); + self.bytes.push_str(text); + { + let state = &mut self.state; + let text = self.bytes.slice(start..); + let (entity_index, _) = state + .get_entity_index_for_text_insert(pos, PosType::Unicode) + .unwrap(); + state.insert_at_entity_index(entity_index, text, IdFull::new(0, 0, 0)); + }; + } + + fn delete(&mut self, pos: usize, len: usize) { + let ranges = self + .state + .get_text_entity_ranges(pos, len, PosType::Unicode) + .unwrap(); + for range in ranges.into_iter().rev() { + self.state.drain_by_entity_index( + range.entity_start, + range.entity_end - range.entity_start, + None, + ); + } + } + + fn mark(&mut self, range: Range<usize>, style: Arc<StyleOp>) { + let (start, _) = self + .state + .get_entity_index_for_text_insert(range.start, PosType::Unicode) + .unwrap(); + let (end, _) = self + .state + .get_entity_index_for_text_insert(range.end, PosType::Unicode) + .unwrap(); + self.state.mark_with_entity_index(start..end, style); + } + } + + fn bold(n: isize) -> Arc<StyleOp> { + Arc::new(StyleOp::new_for_test( + n, + "bold", + true.into(), + TextStyleInfoFlag::BOLD, + )) + } + + fn comment(n: isize) -> Arc<StyleOp> { + Arc::new(StyleOp::new_for_test( + n, + &format!("comment:{}", n), + "comment".into(), + TextStyleInfoFlag::COMMENT, + )) + } + + fn unbold(n: isize) -> Arc<StyleOp> { + Arc::new(StyleOp::new_for_test( + n, + "bold", + LoroValue::Null, + TextStyleInfoFlag::BOLD.to_delete(), + )) + } + + fn link(n: isize) -> Arc<StyleOp> { + Arc::new(StyleOp::new_for_test( + n, + "link", + true.into(), + TextStyleInfoFlag::LINK, + )) + } + + #[test] + fn test() { + let mut wrapper = SimpleWrapper::default(); + wrapper.insert(0, "Hello World!"); + wrapper.mark(0..5, bold(0)); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([ + { + "insert": "Hello", + "attributes": { + "bold": true + } + }, + { + "insert": " World!" + } + ]) + ); + wrapper.mark(2..7, link(1)); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([ + { + "insert": "He", + "attributes": { + "bold": true + } + }, + { + "insert": "llo", + "attributes": { + "bold": true, + "link": true + } + }, + { + "insert": " W", + "attributes": { + "link": true + } + }, + { + "insert": "orld!" + } + + ]) + ); + } + + #[test] + fn delete_text() { + let mut wrapper = SimpleWrapper::default(); + wrapper.insert(0, "Hello World!"); + assert_eq!(wrapper.state.len_unicode(), 12); + assert_eq!(wrapper.state.len_entity(), 12); + wrapper.delete(0, 5); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([ + { + "insert": " World!" + } + ]) + ); + + assert_eq!(wrapper.state.len_unicode(), 7); + assert_eq!(wrapper.state.len_entity(), 7); + wrapper.delete(1, 1); + + assert_eq!(wrapper.state.len_unicode(), 6); + assert_eq!(wrapper.state.len_entity(), 6); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([ + { + "insert": " orld!" + } + ]) + ); + + wrapper.delete(5, 1); + assert_eq!(wrapper.state.len_unicode(), 5); + assert_eq!(wrapper.state.len_entity(), 5); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([ + { + "insert": " orld" + } + ]) + ); + + wrapper.delete(0, 5); + assert_eq!(wrapper.state.len_unicode(), 0); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([]) + ); + } + + #[test] + #[ignore] + fn insert_cache_hit() { + let mut wrapper = SimpleWrapper::default(); + wrapper.insert(0, "H"); + wrapper.insert(1, "H"); + dbg!(&wrapper); + wrapper.insert(2, "e"); + dbg!(&wrapper); + wrapper.insert(3, "k"); + wrapper.state.diagnose(); + } + + #[test] + fn bold_should_expand() { + let mut wrapper = SimpleWrapper::default(); + wrapper.insert(0, "Hello World!"); + wrapper.mark(0..5, bold(0)); + wrapper.insert(5, " Test"); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([ + { + "insert": "Hello Test", + "attributes": { + "bold": true + } + }, + { + "insert": " World!" + } + ]) + ); + } + + #[test] + fn link_should_not_expand() { + let mut wrapper = SimpleWrapper::default(); + wrapper.insert(0, "Hello World!"); + wrapper.mark(0..5, link(0)); + wrapper.insert(5, " Test"); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([ + { + "insert": "Hello", + "attributes": { + "link": true + } + }, + { + "insert": " Test World!" + }, + ]) + ); + } + + #[test] + fn continuous_text_insert_should_be_merged() { + let mut wrapper = SimpleWrapper::default(); + wrapper.insert(0, "Hello"); + wrapper.insert(5, " World!"); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([ + { + "insert": "Hello World!" + }, + ]) + ); + } + + #[test] + fn continuous_text_insert_should_be_merged_and_have_bold() { + let mut wrapper = SimpleWrapper::default(); + wrapper.insert(0, "Hello"); + wrapper.mark(0..5, bold(0)); + wrapper.insert(5, " World!"); + dbg!(&wrapper.state); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([ + { + "insert": "Hello World!", + "attributes": { + "bold": true + } + }, + ]) + ); + } + + #[test] + fn continuous_text_insert_should_not_be_merged_when_prev_is_link() { + let mut wrapper = SimpleWrapper::default(); + wrapper.insert(0, "Hello"); + wrapper.mark(0..5, link(0)); + wrapper.insert(5, " World!"); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([ + { + "insert": "Hello", + "attributes": { + "link": true + } + }, + { + + "insert": " World!", + } + ]) + ); + } + + #[test] + fn delete_bold() { + let mut wrapper = SimpleWrapper::default(); + wrapper.insert(0, "Hello World!"); + wrapper.mark(0..12, bold(0)); + wrapper.mark(5..12, unbold(1)); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([ + { + "insert": "Hello", + "attributes": { + "bold": true + } + }, + { + "insert": " World!" + } + ]) + ); + wrapper.insert(5, "A"); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([ + { + "insert": "HelloA", + "attributes": { + "bold": true + } + }, + { + "insert": " World!", + } + ]) + ); + + wrapper.insert(0, "A"); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([ + { + "insert": "A", + }, + { + "insert": "HelloA", + "attributes": { + "bold": true + } + }, + { + "insert": " World!", + } + ]) + ); + } + + #[test] + fn bold_and_link_at_the_same_place() { + let mut wrapper = SimpleWrapper::default(); + wrapper.insert(0, "Hello"); + wrapper.mark(0..5, link(0)); + wrapper.mark(0..5, bold(1)); + wrapper.insert(5, "A"); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([ + { + "insert": "Hello", + "attributes": { + "bold": true, + "link": true + } + }, + { + "insert": "A", + "attributes": { + "bold": true, + } + }, + ]) + ); + } + + #[test] + fn test_comments() { + let mut wrapper = SimpleWrapper::default(); + wrapper.insert(0, "Hello World!"); + wrapper.mark(0..5, comment(0)); + wrapper.mark(1..6, comment(1)); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([ + { + "insert": "H", + "attributes": { + "comment:0": "comment", + }, + }, + { + "insert": "ello", + "attributes": { + "comment:0": "comment", + "comment:1": "comment", + }, + }, + + { + "insert": " ", + "attributes": { + "comment:1": "comment", + }, + }, + { + "insert": "World!", + } + ]) + ); + } + + #[test] + fn remove_style_anchors_should_also_delete_style() { + let mut wrapper = SimpleWrapper::default(); + wrapper.insert(0, "Hello World!"); + wrapper.mark(0..5, bold(0)); + let mut count = 0; + wrapper.state.drain_by_entity_index( + 0, + 7, + Some(&mut |span| { + if matches!(span, RichtextStateChunk::Style { .. }) { + count += 1; + } + }), + ); + + assert_eq!(count, 2); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([{ + "insert": " World!" + }]) + ); + } + + #[test] + fn remove_start_anchor_should_remove_style() { + let mut wrapper = SimpleWrapper::default(); + wrapper.insert(0, "Hello World!"); + wrapper.mark(0..5, bold(0)); + wrapper.state.drain_by_entity_index(6, 1, None); + wrapper.state.drain_by_entity_index(0, 1, None); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([{ + "insert": "Hello World!" + }]) + ); + } + + #[test] + fn remove_start_anchor_in_the_middle_should_remove_style() { + let mut wrapper = SimpleWrapper::default(); + wrapper.insert(0, "Hello World!"); + wrapper.mark(2..5, bold(0)); + wrapper.state.drain_by_entity_index(6, 1, None); + wrapper.state.drain_by_entity_index(1, 2, None); + assert_eq!( + wrapper.state.get_richtext_value().to_json_value(), + json!([{ + "insert": "Hllo World!" + }]) + ); + } +} diff --git a/vendor/loro-internal/src/container/richtext/richtext_state/insert_pos_cache_test.rs b/vendor/loro-internal/src/container/richtext/richtext_state/insert_pos_cache_test.rs new file mode 100644 index 0000000..53b9d93 --- /dev/null +++ b/vendor/loro-internal/src/container/richtext/richtext_state/insert_pos_cache_test.rs @@ -0,0 +1,172 @@ +//! `get_entity_index_for_text_insert` can start from the cursor cached by an +//! earlier lookup. That shortcut must never move an insert across a style +//! anchor, so these tests compare every cached answer with a cold lookup +//! (`find_best_insert_pos`) on documents full of anchors. + +use loro_common::LoroValue; +use rand::{rngs::StdRng, seq::SliceRandom, Rng, SeedableRng}; + +use super::{PosType, RichtextState}; +use crate::{ + container::richtext::{ + config::{StyleConfig, StyleConfigMap}, + ExpandType, + }, + handler::{HandlerTrait, TextHandler}, + LoroDoc, +}; + +/// One key per expand type. +const STYLES: [(&str, ExpandType); 4] = [ + ("after", ExpandType::After), + ("before", ExpandType::Before), + ("both", ExpandType::Both), + ("none", ExpandType::None), +]; + +/// BMP, astral, ZWJ sequences, flags, and modifiers. +const SNIPPETS: [&str; 9] = ["a", "bc", "é", "中", "😀", "𝒳y", "👍🏽", "👨‍👩‍👧", "🇨🇳"]; + +const POS_TYPES: [PosType; 5] = [ + PosType::Bytes, + PosType::Unicode, + PosType::Utf16, + PosType::Event, + PosType::Entity, +]; + +const MAX_LEN: usize = 40; + +fn random_edit(rng: &mut StdRng, text: &TextHandler) { + let len = text.len_unicode(); + match rng.gen_range(0..10) { + 0..=3 if len < MAX_LEN => { + let s = SNIPPETS.choose(rng).unwrap(); + text.insert(rng.gen_range(0..=len), s, PosType::Unicode) + .unwrap(); + } + 0..=4 if len > 0 => { + let pos = rng.gen_range(0..len); + let del = rng.gen_range(1..=(len - pos).min(4)); + text.delete(pos, del, PosType::Unicode).unwrap(); + } + _ if len > 0 => { + let start = rng.gen_range(0..len); + let end = rng.gen_range(start + 1..=len); + let (key, _) = *STYLES.choose(rng).unwrap(); + let value = match rng.gen_range(0..5) { + 0 => LoroValue::Null, + 1 => false.into(), + 2 => "v".into(), + _ => true.into(), + }; + if rng.gen_bool(0.2) { + text.unmark(start, end, key, PosType::Unicode).unwrap(); + } else { + text.mark(start, end, key, value, PosType::Unicode).unwrap(); + } + if rng.gen_bool(0.2) { + // Leaves the anchors of the style next to each other. + text.delete(start, end - start, PosType::Unicode).unwrap(); + } + } + _ => text.insert(0, "a", PosType::Unicode).unwrap(), + } +} + +fn boundaries(text: &str, pos_type: PosType, entity_len: usize) -> Vec<usize> { + let unit_len = |c: char| match pos_type { + PosType::Bytes => c.len_utf8(), + PosType::Unicode => 1, + PosType::Utf16 => c.len_utf16(), + PosType::Event if cfg!(feature = "wasm") => c.len_utf16(), + PosType::Event => 1, + PosType::Entity => unreachable!(), + }; + if pos_type == PosType::Entity { + return (0..=entity_len).collect(); + } + let mut ans = vec![0]; + for c in text.chars() { + ans.push(ans.last().unwrap() + unit_len(c)); + } + ans +} + +fn cold_lookup(state: &RichtextState, pos: usize, pos_type: PosType) -> usize { + let mut cold = state.clone(); + cold.clear_cache(); + cold.get_entity_index_for_text_insert(pos, pos_type) + .unwrap() + .0 +} + +fn assert_cache_matches_cold_lookup(state: &mut RichtextState, text: &str, context: &str) { + for pos_type in POS_TYPES { + let positions = boundaries(text, pos_type, state.len_entity()); + // Starting from the cursor the last edit left behind. + for &pos in &positions { + let expected = cold_lookup(state, pos, pos_type); + let (actual, _) = state + .clone() + .get_entity_index_for_text_insert(pos, pos_type) + .unwrap(); + assert_eq!( + actual, expected, + "{context}: {pos_type:?} {pos} from the edit's cursor in {text:?}" + ); + } + // Starting from the cursor of the previous position, as when typing. + let mut warm = state.clone(); + for &pos in &positions { + let expected = cold_lookup(&warm, pos, pos_type); + let (actual, cursor) = warm + .get_entity_index_for_text_insert(pos, pos_type) + .unwrap(); + assert_eq!( + actual, expected, + "{context}: {pos_type:?} {pos} from the previous position in {text:?}" + ); + if let Some(cursor) = cursor { + assert_eq!( + warm.get_index_from_cursor(cursor, PosType::Entity), + Some(actual) + ); + } + } + } +} + +#[test] +fn cached_insert_position_matches_cold_lookup_near_style_anchors() { + let seeds: u64 = std::env::var("LORO_INSERT_CACHE_SEEDS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(12); + for seed in 0..seeds { + let mut rng = StdRng::seed_from_u64(seed); + let doc = LoroDoc::new_auto_commit(); + let mut styles = StyleConfigMap::new(); + for (key, expand) in STYLES { + styles.insert(key.into(), StyleConfig::new().expand(expand)); + } + doc.config_text_style(styles); + let text = doc.get_text("text"); + for step in 0..60 { + random_edit(&mut rng, &text); + if rng.gen_bool(0.3) { + doc.commit_then_renew(); + } + let value = text.to_string(); + // The clone keeps the cursor cache of the document's state. + let mut state = doc.app_state().lock().with_state_mut(text.idx(), |s| { + s.as_richtext_state_mut().unwrap().inner_state_mut().clone() + }); + assert_cache_matches_cold_lookup( + &mut state, + &value, + &format!("seed {seed} step {step}"), + ); + } + } +} diff --git a/vendor/loro-internal/src/container/richtext/str_slice.rs b/vendor/loro-internal/src/container/richtext/str_slice.rs new file mode 100644 index 0000000..e47b70b --- /dev/null +++ b/vendor/loro-internal/src/container/richtext/str_slice.rs @@ -0,0 +1,48 @@ +use append_only_bytes::{AppendOnlyBytes, BytesSlice}; + +/// It's just a wrapper around [BytesSlice] that makes sure +/// the content of the bytes is a valid utf-8 string +pub(crate) struct StrSlice(BytesSlice); + +impl StrSlice { + #[allow(unused)] + pub fn new(bytes: BytesSlice) -> Option<Self> { + let _str = std::str::from_utf8(&bytes).ok()?; + Some(Self(bytes)) + } + + pub fn new_from_str(str: &str) -> Self { + let mut a = AppendOnlyBytes::new(); + a.push_str(str); + Self(a.slice(..)) + } + + pub fn bytes(&self) -> &BytesSlice { + &self.0 + } + + pub fn as_str(&self) -> &str { + // SAFETY: We ensure that the content is always valid utf8 + unsafe { std::str::from_utf8_unchecked(&self.0) } + } + + pub fn split_at_unicode_pos(&self, pos: usize) -> (Self, Self) { + let s = self.as_str(); + let mut split_at = self.0.len(); + // ASCII: chars are bytes. (project_note patch) + if pos <= s.len() && s.as_bytes()[..pos].is_ascii() { + return (Self(self.0.slice_clone(..pos)), Self(self.0.slice_clone(pos..))); + } + for (u, (i, _)) in s.char_indices().enumerate() { + if u == pos { + split_at = i; + break; + } + } + + ( + Self(self.0.slice_clone(..split_at)), + Self(self.0.slice_clone(split_at..)), + ) + } +} diff --git a/vendor/loro-internal/src/container/richtext/style_range_map.rs b/vendor/loro-internal/src/container/richtext/style_range_map.rs new file mode 100644 index 0000000..350fae0 --- /dev/null +++ b/vendor/loro-internal/src/container/richtext/style_range_map.rs @@ -0,0 +1,690 @@ +//! This map a Range<usize> to a set of style +//! + +use std::{ + collections::BTreeSet, + ops::{ControlFlow, Deref, DerefMut, Range, RangeBounds}, + sync::Arc, +}; + +use generic_btree::{ + rle::{CanRemove, HasLength, Mergeable, Sliceable, TryInsert}, + BTree, BTreeTrait, ElemSlice, LengthFinder, UseLengthFinder, +}; +use rustc_hash::FxHashMap; + +use once_cell::sync::Lazy; + +use crate::delta::StyleMeta; + +use super::{AnchorType, StyleKey, StyleOp}; + +/// This struct keep the mapping of ranges to numbers +/// +/// It's initialized with usize::MAX/2 length. +#[derive(Debug, Clone)] +pub(super) struct StyleRangeMap { + pub(super) tree: BTree<RangeNumMapTrait>, + has_style: bool, +} + +#[derive(Debug, Clone)] +pub(super) struct RangeNumMapTrait; + +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub(crate) struct Styles { + pub(crate) styles: FxHashMap<StyleKey, StyleValue>, +} + +impl Styles { + pub(crate) fn has_key_value(&self, key: &str, value: &loro_common::LoroValue) -> bool { + match self.get(&StyleKey::Key(key.into())) { + Some(v) => match v.get() { + Some(v) => &v.value == value, + _ => false, + }, + _ => false, + } + } + + /// Infer the anchors between the neighbor styles. + /// Returns the last anchor of the left style and the first anchor of the right style. + fn infer_anchors(&self, next: &Self) -> (Option<Arc<StyleOp>>, Option<Arc<StyleOp>>) { + let mut left_anchor = None; + let mut right_anchor = None; + let empty_set: BTreeSet<_> = Default::default(); + for (key, set) in self.styles.iter() { + let right_set = next.styles.get(key).map(|x| &x.set).unwrap_or(&empty_set); + for diff in set.set.difference(right_set) { + assert!(left_anchor.is_none(), "left anchor should be unique"); + left_anchor = Some(diff.clone()); + } + } + + for (key, set) in next.styles.iter() { + let left_set = self.styles.get(key).map(|x| &x.set).unwrap_or(&empty_set); + for diff in set.set.difference(left_set) { + assert!(right_anchor.is_none(), "right anchor should be unique"); + right_anchor = Some(diff.clone()); + } + } + + (left_anchor, right_anchor) + } +} + +impl Deref for Styles { + type Target = FxHashMap<StyleKey, StyleValue>; + + fn deref(&self) -> &Self::Target { + &self.styles + } +} + +impl DerefMut for Styles { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.styles + } +} + +pub(super) static EMPTY_STYLES: Lazy<Styles> = Lazy::new(Default::default); + +#[derive(Debug, Clone)] +pub(crate) struct Elem { + pub(crate) styles: Styles, + pub(crate) len: usize, +} + +#[derive(Clone, Default, Debug, PartialEq, Eq)] +pub(crate) struct StyleValue { + // we need a set here because we need to calculate the intersection of styles when + // users insert new text between two style sets + set: BTreeSet<Arc<StyleOp>>, +} + +impl StyleValue { + pub fn insert(&mut self, value: Arc<StyleOp>) { + self.set.insert(value); + } + + pub fn get(&self) -> Option<&Arc<StyleOp>> { + self.set.last() + } +} + +impl Default for StyleRangeMap { + fn default() -> Self { + Self::new() + } +} + +type YieldStyle<'a> = Option<&'a mut dyn FnMut(&Styles, usize)>; + +impl StyleRangeMap { + pub fn new() -> Self { + let mut tree = BTree::new(); + tree.push(Elem { + styles: Default::default(), + len: usize::MAX / 4, + }); + + Self { + tree, + has_style: false, + } + } + + pub fn annotate( + &mut self, + range: Range<usize>, + style: Arc<StyleOp>, + mut yield_style: YieldStyle, + ) { + let range = self.tree.range::<LengthFinder>(range); + if range.is_none() { + unreachable!(); + } + + self.has_style = true; + let range = range.unwrap(); + self.tree + .update(range.start.cursor..range.end.cursor, &mut |x| { + if let Some(set) = x.styles.get_mut(&style.get_style_key()) { + set.set.insert(style.clone()); + } else { + let key = style.get_style_key(); + let mut value = StyleValue::default(); + value.insert(style.clone()); + x.styles.insert(key, value); + } + + if let Some(y) = yield_style.as_mut() { + y(&x.styles, x.len); + } + None + }); + } + + /// Get the styles of the range. If the range is not in the same leaf, return None. + pub(crate) fn get_styles_of_range(&self, range: Range<usize>) -> Option<&Styles> { + if !self.has_style { + return None; + } + + let right = self + .tree + .query::<LengthFinder>(&(range.end - 1)) + .unwrap() + .cursor; + let left = self + .tree + .query::<LengthFinder>(&range.start) + .unwrap() + .cursor; + if left.leaf == right.leaf { + Some(&self.tree.get_elem(left.leaf).unwrap().styles) + } else { + None + } + } + + pub(crate) fn range_contains_key(&self, range: Range<usize>, key: &StyleKey) -> bool { + if range.is_empty() || !self.has_style { + return false; + } + + let mut query = self.tree.query::<LengthFinder>(&range.start).unwrap(); + let mut pos = range.start; + loop { + let elem = self.tree.get_elem(query.cursor.leaf).unwrap(); + if elem.styles.contains_key(key) { + return true; + } + + let remaining_in_elem = elem.len - query.cursor.offset; + let next_pos = pos + remaining_in_elem; + if next_pos >= range.end { + break; + } + + match self.tree.next_elem(query.cursor) { + Some(next_cursor) => { + pos = next_pos; + query.cursor = next_cursor; + } + None => break, + } + } + + false + } + + /// Whether every position in the range already resolves `key` to `value`. + /// + /// Unlike [`Self::get_styles_of_range`], this works when the range spans + /// multiple style ranges, so callers can skip marks that would not change + /// anything (each redundant mark op leaves a pair of style anchors in the + /// state forever). + pub(crate) fn range_has_key_value( + &self, + range: Range<usize>, + key: &str, + value: &loro_common::LoroValue, + ) -> bool { + if range.is_empty() || !self.has_style { + return false; + } + + let mut query = self.tree.query::<LengthFinder>(&range.start).unwrap(); + let mut pos = range.start; + loop { + let elem = self.tree.get_elem(query.cursor.leaf).unwrap(); + let remaining_in_elem = elem.len - query.cursor.offset; + if remaining_in_elem > 0 && !elem.styles.has_key_value(key, value) { + return false; + } + + let next_pos = pos + remaining_in_elem; + if next_pos >= range.end { + break; + } + + match self.tree.next_elem(query.cursor) { + Some(next_cursor) => { + pos = next_pos; + query.cursor = next_cursor; + } + None => break, + } + } + + true + } + + /// Insert entities at `pos` with length of `len` + /// + /// # Internal + /// + /// When inserting new text, we need to calculate the StyleSet of the new text based on the StyleSet before and after the insertion position. + /// (It should be the intersection of the StyleSet before and after). The proof is as follows: + /// + /// Suppose when inserting text at position pos, the style set at positions pos - 1 and pos are called leftStyleSet and rightStyleSet respectively. + /// + /// - If there is a style x that exists in leftStyleSet but not in rightStyleSet, it means that the position pos - 1 is the end anchor of x. + /// The newly inserted text is after the end anchor of x, so the StyleSet of the new text should not include this style. + /// - If there is a style x that exists in rightStyleSet but not in leftStyleSet, it means that the position pos is the start anchor of x. + /// The newly inserted text is before the start anchor of x, so the StyleSet of the new text should not include this style. + /// - If both leftStyleSet and rightStyleSet contain style x, it means that the newly inserted text is within the style range, so the StyleSet should include x. + pub fn insert(&mut self, pos: usize, len: usize) -> &Styles { + if !self.has_style { + return &EMPTY_STYLES; + } + + if pos == 0 { + self.tree.prepend(Elem { + len, + styles: Default::default(), + }); + return &EMPTY_STYLES; + } + + if pos as isize == *self.tree.root_cache() { + self.tree.push(Elem { + len, + styles: Default::default(), + }); + return &EMPTY_STYLES; + } + + let right = self.tree.query::<LengthFinder>(&pos).unwrap().cursor; + let left = self.tree.query::<LengthFinder>(&(pos - 1)).unwrap().cursor; + if left.leaf == right.leaf { + // left and right are in the same element, we can increase the length of the element directly + self.tree.update_leaf(left.leaf, |x| { + x.len += len; + (true, None, None) + }); + return &self.tree.get_elem(left.leaf).unwrap().styles; + } + + // insert by the intersection of left styles and right styles + let mut styles = self.tree.get_elem(left.leaf).unwrap().styles.clone(); + let right_styles = &self.tree.get_elem(right.leaf).unwrap().styles; + styles.retain(|key, value| { + if let Some(right_value) = right_styles.get(key) { + value.set.retain(|x| right_value.set.contains(x)); + return !value.set.is_empty(); + } + + false + }); + + let (target, _) = self.tree.insert_by_path(right, Elem { len, styles }); + &self.tree.get_elem(target.leaf).unwrap().styles + } + + /// Return the style sets beside `index` and get the intersection of them. + pub fn get_styles_for_insert(&self, index: usize) -> StyleMeta { + if index == 0 || !self.has_style { + return StyleMeta::default(); + } + + let left = self + .tree + .query::<LengthFinder>(&(index - 1)) + .unwrap() + .cursor; + let right = self.tree.shift_path_by_one_offset(left).unwrap(); + if left.leaf == right.leaf { + let styles = &self.tree.get_elem(left.leaf).unwrap().styles; + styles.into() + } else { + let mut styles = self.tree.get_elem(left.leaf).unwrap().styles.clone(); + let right_styles = &self.tree.get_elem(right.leaf).unwrap().styles; + styles.retain(|key, value| { + if let Some(right_value) = right_styles.get(key) { + value.set.retain(|x| right_value.set.contains(x)); + return !value.set.is_empty(); + } + + false + }); + + styles.into() + } + } + + pub fn iter(&self) -> impl Iterator<Item = (Range<usize>, &Styles)> + '_ { + let mut index = 0; + self.tree.iter().filter_map(move |elem| { + let len = elem.len; + let value = &elem.styles; + let range = index..index + len; + index += len; + if elem.styles.is_empty() { + return None; + } + + Some((range, value)) + }) + } + + /// Update the styles from `pos` to the start of the document. + fn update_styles_scanning_backward( + &mut self, + pos: usize, + mut f: impl FnMut(&mut Elem) -> ControlFlow<()>, + ) { + let mut cursor = self.tree.query::<LengthFinder>(&pos).map(|x| x.cursor); + while let Some(inner_cursor) = cursor { + cursor = self.tree.prev_elem(inner_cursor); + let node = self.tree.get_elem_mut(inner_cursor.leaf).unwrap(); + match f(node) { + ControlFlow::Continue(_) => {} + ControlFlow::Break(_) => { + break; + } + } + } + } + + pub(crate) fn iter_range( + &self, + range: impl RangeBounds<usize>, + ) -> impl Iterator<Item = ElemSlice<'_, Elem>> + '_ { + let start = match range.start_bound() { + std::ops::Bound::Included(x) => *x, + std::ops::Bound::Excluded(x) => *x + 1, + std::ops::Bound::Unbounded => 0, + }; + + let end = match range.end_bound() { + std::ops::Bound::Included(x) => *x + 1, + std::ops::Bound::Excluded(x) => *x, + std::ops::Bound::Unbounded => usize::MAX, + }; + + let start = self.tree.query::<LengthFinder>(&start).unwrap(); + let end = self.tree.query::<LengthFinder>(&end).unwrap(); + self.tree.iter_range(start.cursor..end.cursor) + } + + /// Return the expected style anchors with their indexes. + pub(super) fn iter_anchors(&self) -> impl Iterator<Item = IterAnchorItem> + '_ { + let mut index = 0; + let empty_styles = &EMPTY_STYLES; + let mut last: Option<&Elem> = None; + let mut vec = Vec::new(); + for cur in self.tree.iter() { + let last_styles = last.map(|x| &x.styles).unwrap_or(empty_styles); + let (left_anchor, right_anchor) = last_styles.infer_anchors(&cur.styles); + if let Some(left) = left_anchor { + vec.push(IterAnchorItem { + index: index - 1, + op: left.clone(), + anchor_type: AnchorType::End, + }); + } + if let Some(right) = right_anchor { + vec.push(IterAnchorItem { + index, + op: right.clone(), + anchor_type: AnchorType::Start, + }); + } + + last = Some(cur); + index += cur.len; + } + + let last_styles = last.map(|x| &x.styles).unwrap_or(empty_styles); + let (left_anchor, right_anchor) = last_styles.infer_anchors(empty_styles); + if let Some(left) = left_anchor { + vec.push(IterAnchorItem { + index: index - 1, + op: left.clone(), + anchor_type: AnchorType::End, + }); + } + if let Some(right) = right_anchor { + vec.push(IterAnchorItem { + index, + op: right.clone(), + anchor_type: AnchorType::Start, + }); + } + + vec.into_iter() + } + + /// Remove the style scanning backward, return the start_entity_index + pub fn remove_style_scanning_backward( + &mut self, + to_remove: &Arc<StyleOp>, + last_index: usize, + ) -> usize { + let mut removed_len = 0; + self.update_styles_scanning_backward(last_index, |elem| { + removed_len += elem.len; + let styles = &mut elem.styles; + let key = to_remove.get_style_key(); + let mut has_removed = false; + if let Some(value) = styles.get_mut(&key) { + has_removed = value.set.remove(to_remove); + if value.set.is_empty() { + styles.remove(&key); + } + } + + if has_removed { + ControlFlow::Continue(()) + } else { + ControlFlow::Break(()) + } + }); + + last_index + 1 - removed_len + } + + pub fn delete(&mut self, range: Range<usize>) { + if !self.has_style { + return; + } + + let start = self.tree.query::<LengthFinder>(&range.start).unwrap(); + let end = self.tree.query::<LengthFinder>(&range.end).unwrap(); + if start.cursor.leaf == end.cursor.leaf { + // delete in the same element + self.tree.update_leaf(start.cursor.leaf, |x| { + x.len -= range.len(); + (true, None, None) + }); + return; + } + + self.tree.drain(start..end); + } + + pub(crate) fn has_style(&self) -> bool { + self.has_style + } +} + +pub(super) struct IterAnchorItem { + pub(super) index: usize, + pub(super) op: Arc<StyleOp>, + pub(super) anchor_type: AnchorType, +} + +impl UseLengthFinder<RangeNumMapTrait> for RangeNumMapTrait { + fn get_len(cache: &isize) -> usize { + *cache as usize + } +} + +impl HasLength for Elem { + fn rle_len(&self) -> usize { + self.len + } +} + +impl Mergeable for Elem { + fn can_merge(&self, rhs: &Self) -> bool { + self.styles == rhs.styles || rhs.len == 0 + } + + fn merge_right(&mut self, rhs: &Self) { + self.len += rhs.len + } + + fn merge_left(&mut self, left: &Self) { + self.len += left.len; + } +} + +impl Sliceable for Elem { + fn _slice(&self, range: std::ops::Range<usize>) -> Self { + let len = range.len(); + Elem { + styles: self.styles.clone(), + len, + } + } +} + +impl TryInsert for Elem { + fn try_insert(&mut self, _pos: usize, elem: Self) -> Result<(), Self> + where + Self: Sized, + { + if self.styles == elem.styles { + self.len += elem.len; + Ok(()) + } else { + Err(elem) + } + } +} + +impl CanRemove for Elem { + fn can_remove(&self) -> bool { + self.len == 0 + } +} + +impl BTreeTrait for RangeNumMapTrait { + type Elem = Elem; + type Cache = isize; + type CacheDiff = isize; + const USE_DIFF: bool = true; + + fn calc_cache_internal( + cache: &mut Self::Cache, + caches: &[generic_btree::Child<Self>], + ) -> isize { + let new_cache = caches.iter().map(|c| c.cache).sum(); + let diff = new_cache - *cache; + *cache = new_cache; + diff + } + + fn merge_cache_diff(diff1: &mut Self::CacheDiff, diff2: &Self::CacheDiff) { + *diff1 += diff2; + } + + fn apply_cache_diff(cache: &mut Self::Cache, diff: &Self::CacheDiff) { + *cache += diff; + } + + fn get_elem_cache(elem: &Self::Elem) -> Self::Cache { + elem.len as isize + } + + fn new_cache_to_diff(cache: &Self::Cache) -> Self::CacheDiff { + *cache + } + + fn sub_cache(cache_lhs: &Self::Cache, cache_rhs: &Self::Cache) -> Self::CacheDiff { + *cache_lhs - *cache_rhs + } +} + +#[cfg(test)] +mod test { + use loro_common::PeerID; + + use crate::{change::Lamport, container::richtext::TextStyleInfoFlag}; + + use super::*; + + fn new_style(n: i32) -> Arc<StyleOp> { + Arc::new(StyleOp { + lamport: n as Lamport, + peer: n as PeerID, + cnt: n, + key: n.to_string().into(), + info: TextStyleInfoFlag::default(), + value: loro_common::LoroValue::Bool(true), + }) + } + + #[test] + fn test_basic_insert() { + let mut map = StyleRangeMap::default(); + map.annotate(1..10, new_style(1), None); + { + map.insert(0, 1); + assert_eq!(map.iter().count(), 1); + for (range, map) in map.iter() { + assert_eq!(range, 2..11); + assert_eq!(map.len(), 1); + } + } + { + map.insert(11, 1); + assert_eq!(map.iter().count(), 1); + for (range, map) in map.iter() { + assert_eq!(range, 2..11); + assert_eq!(map.len(), 1); + } + } + { + map.insert(10, 1); + assert_eq!(map.iter().count(), 1); + for (range, map) in map.iter() { + assert_eq!(range, 2..12); + assert_eq!(map.len(), 1); + } + } + } + + #[test] + fn delete_style() { + let mut map = StyleRangeMap::default(); + map.annotate(1..10, new_style(1), None); + { + map.delete(0..2); + assert_eq!(map.iter().count(), 1); + for (range, map) in map.iter() { + assert_eq!(range, 0..8); + assert_eq!(map.len(), 1); + } + } + { + map.delete(2..4); + for (range, map) in map.iter() { + assert_eq!(range, 0..6); + assert_eq!(map.len(), 1); + } + assert_eq!(map.iter().count(), 1); + } + { + map.delete(6..8); + assert_eq!(map.iter().count(), 1); + for (range, map) in map.iter() { + assert_eq!(range, 0..6); + assert_eq!(map.len(), 1); + } + } + } +} diff --git a/vendor/loro-internal/src/container/richtext/tinyvec.rs b/vendor/loro-internal/src/container/richtext/tinyvec.rs new file mode 100644 index 0000000..6f852fe --- /dev/null +++ b/vendor/loro-internal/src/container/richtext/tinyvec.rs @@ -0,0 +1,289 @@ +use std::{fmt::Debug, mem::MaybeUninit}; + +pub(crate) struct TinyVec<T, const N: usize> { + len: u8, + data: [MaybeUninit<T>; N], +} + +impl<T: Debug, const N: usize> Debug for TinyVec<T, N> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_list().entries(self.iter()).finish() + } +} + +impl<T: Clone, const N: usize> Clone for TinyVec<T, N> { + fn clone(&self) -> Self { + let mut result = Self::new(); + for item in self.iter() { + result + .push(item.clone()) + .ok() + .expect("TinyVec clone should fit in the same capacity"); + } + result + } +} + +impl<T, const N: usize> std::ops::Index<usize> for TinyVec<T, N> { + type Output = T; + + fn index(&self, index: usize) -> &Self::Output { + assert!(index < self.len as usize); + // SAFETY: This is safe because we know that the data is initialized + unsafe { self.data[index].assume_init_ref() } + } +} + +impl<T, const N: usize> TinyVec<T, N> { + #[inline] + pub fn new() -> Self { + if N > u8::MAX as usize { + panic!("TinyVec size too large"); + } + + Self { + len: 0, + // SAFETY: This initialization is copied from std + // SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid. + data: unsafe { MaybeUninit::<[MaybeUninit<T>; N]>::uninit().assume_init() }, + } + } + + pub fn push(&mut self, value: T) -> Result<(), T> { + if self.len == N as u8 { + return Err(value); + } + + self.data[self.len as usize] = MaybeUninit::new(value); + self.len += 1; + Ok(()) + } + + #[inline(always)] + pub fn get(&self, index: usize) -> &T { + &self[index] + } + + pub fn pop(&mut self) -> Option<T> { + if self.len == 0 { + None + } else { + self.len -= 1; + // SAFETY: This is safe because we know that the last element is initialized + Some(unsafe { self.data[self.len as usize].assume_init_read() }) + } + } + + #[inline(always)] + pub fn len(&self) -> usize { + self.len as usize + } + + #[inline(always)] + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + pub fn iter(&self) -> impl Iterator<Item = &T> { + let mut index = 0; + std::iter::from_fn(move || { + if index < self.len as usize { + let result = &self[index]; + index += 1; + Some(result) + } else { + None + } + }) + } + + pub fn can_merge(&self, other: &Self) -> bool { + if self.len() + other.len() > N { + return false; + } + + self.len() + other.len() <= self.data.len() + } + + pub fn merge(&mut self, other: &Self) + where + T: Clone, + { + if !self.can_merge(other) { + panic!("TinyVec cannot merge"); + } + + for item in other.iter() { + self.push(item.clone()) + .ok() + .expect("TinyVec merge should fit after can_merge"); + } + } + + pub fn merge_left(&mut self, left: &Self) + where + T: Clone, + { + if !self.can_merge(left) { + panic!("TinyVec cannot merge"); + } + + let mut result = Self::new(); + for item in left.iter().chain(self.iter()) { + result + .push(item.clone()) + .ok() + .expect("TinyVec merge_left should fit after can_merge"); + } + *self = result; + } + + pub fn slice(&self, start: usize, end: usize) -> Self + where + T: Clone, + { + assert!(start <= end && end <= self.len as usize); + let mut result = Self::new(); + for item in self.iter().skip(start).take(end - start) { + result + .push(item.clone()) + .ok() + .expect("TinyVec slice should fit in the same capacity"); + } + result + } + + #[inline] + pub fn split(&mut self, pos: usize) -> Self { + assert!(pos <= self.len()); + let old_len = self.len(); + let mut result = Self::new(); + for i in pos..old_len { + // SAFETY: indexes below old_len are initialized. The value is moved + // into result and self.len is truncated below before self is dropped. + let value = unsafe { self.data[i].assume_init_read() }; + result + .push(value) + .ok() + .expect("TinyVec split should fit in the same capacity"); + } + self.len = pos as u8; + result + } +} + +impl<T: Clone, const N: usize> TinyVec<T, N> { + pub fn to_vec(&self) -> Vec<T> { + let mut result = Vec::with_capacity(self.len as usize); + for i in 0..self.len as usize { + result.push(self[i].clone()); + } + result + } +} + +impl<T: PartialEq, const N: usize> PartialEq for TinyVec<T, N> { + fn eq(&self, other: &Self) -> bool { + if self.len != other.len { + return false; + } + + for i in 0..self.len as usize { + if self[i] != other[i] { + return false; + } + } + + true + } +} + +impl<T: Eq, const N: usize> Eq for TinyVec<T, N> {} + +impl<T, const N: usize> Drop for TinyVec<T, N> { + fn drop(&mut self) { + for i in 0..self.len as usize { + // SAFETY: This is safe because we know that the element is initialized + unsafe { std::ptr::drop_in_place(self.data[i].as_mut_ptr()) }; + } + } +} + +#[cfg(test)] +mod test { + use std::sync::Arc; + + use super::TinyVec; + + #[test] + fn pop_should_drop() { + let mut arr: TinyVec<_, 2> = TinyVec::new(); + let elem = Arc::new(10); + assert_eq!(Arc::strong_count(&elem), 1); + arr.push(elem.clone()).unwrap(); + assert_eq!(Arc::strong_count(&elem), 2); + arr.pop(); + assert_eq!(Arc::strong_count(&elem), 1); + } + + #[test] + fn dropping_should_drop_all_elem() { + let mut arr: TinyVec<_, 2> = TinyVec::new(); + let elem = Arc::new(10); + assert_eq!(Arc::strong_count(&elem), 1); + arr.push(elem.clone()).unwrap(); + assert_eq!(Arc::strong_count(&elem), 2); + drop(arr); + assert_eq!(Arc::strong_count(&elem), 1); + } + + #[test] + fn split() { + let mut arr: TinyVec<u8, 8> = TinyVec::new(); + arr.push(1).unwrap(); + arr.push(2).unwrap(); + arr.push(3).unwrap(); + arr.push(4).unwrap(); + let new = arr.split(2); + assert_eq!(arr.to_vec(), vec![1, 2]); + assert_eq!(new.to_vec(), vec![3, 4]); + } + + #[test] + fn slice() { + let mut arr: TinyVec<u8, 8> = TinyVec::new(); + arr.push(1).unwrap(); + arr.push(2).unwrap(); + arr.push(3).unwrap(); + arr.push(4).unwrap(); + arr.push(5).unwrap(); + let arr = arr; + let new = arr.slice(2, 4); + assert_eq!(new.to_vec(), vec![3, 4]); + } + + #[test] + fn clone() { + let mut arr: TinyVec<u8, 8> = TinyVec::new(); + arr.push(1).unwrap(); + arr.push(2).unwrap(); + arr.push(3).unwrap(); + arr.push(4).unwrap(); + arr.push(5).unwrap(); + let arr = arr; + let new = arr.clone(); + assert_eq!(arr, new); + assert_eq!(new.to_vec(), [1, 2, 3, 4, 5]); + } + + #[cfg(miri)] + #[test] + fn clone_of_owned_values_does_not_duplicate_ownership_with_raw_copy() { + let mut arr: TinyVec<Box<i32>, 2> = TinyVec::new(); + arr.push(Box::new(1)).unwrap(); + + let cloned = arr.clone(); + drop(arr); + drop(cloned); + } +} diff --git a/vendor/loro-internal/src/container/richtext/tracker.rs b/vendor/loro-internal/src/container/richtext/tracker.rs new file mode 100644 index 0000000..942f287 --- /dev/null +++ b/vendor/loro-internal/src/container/richtext/tracker.rs @@ -0,0 +1,896 @@ +use std::ops::ControlFlow; + +use generic_btree::{ + rle::{HasLength as _, Sliceable}, + LeafIndex, +}; +use loro_common::{Counter, HasId, HasIdSpan, IdFull, IdSpan, Lamport, PeerID, ID}; +use rle::HasLength as _; +use tracing::instrument; + +use crate::{cursor::AbsolutePosition, VersionVector}; + +use self::{crdt_rope::CrdtRope, id_to_cursor::IdToCursor}; + +use super::{ + fugue_span::{FugueSpan, Status}, + RichtextChunk, +}; + +mod crdt_rope; +mod id_to_cursor; + +/// Length of the placeholder span that stands for history the tracker has not +/// replayed (`Tracker::new_with_unknown`). Op positions must stay below it; see +/// `InnerListOp::check_positions`. +pub(crate) const UNKNOWN_SPAN_LEN: u32 = u32::MAX / 4; + +pub(crate) use crdt_rope::CrdtRopeDelta; + +#[derive(Debug)] +pub(crate) struct Tracker { + applied_vv: VersionVector, + current_vv: VersionVector, + rope: CrdtRope, + id_to_cursor: IdToCursor, +} + +impl Default for Tracker { + fn default() -> Self { + Self::new_with_unknown() + } +} + +pub(super) const UNKNOWN_PEER_ID: PeerID = u64::MAX; +impl Tracker { + pub fn new_with_unknown() -> Self { + let mut this = Self { + rope: CrdtRope::new(), + id_to_cursor: IdToCursor::default(), + applied_vv: Default::default(), + current_vv: Default::default(), + }; + + let result = this.rope.tree.push(FugueSpan { + content: RichtextChunk::new_unknown(UNKNOWN_SPAN_LEN), + id: IdFull::new(UNKNOWN_PEER_ID, 0, 0), + real_id: None, + status: Status::default(), + diff_status: None, + origin_left: None, + origin_right: None, + }); + this.id_to_cursor.insert_without_split( + ID::new(UNKNOWN_PEER_ID, 0), + id_to_cursor::Cursor::new_insert(result.leaf, UNKNOWN_SPAN_LEN as usize), + ); + this + } + + #[allow(unused)] + fn new() -> Self { + Self::new_empty() + } + + pub(crate) fn new_empty() -> Self { + Self { + rope: CrdtRope::new(), + id_to_cursor: IdToCursor::default(), + applied_vv: Default::default(), + current_vv: Default::default(), + } + } + + #[inline] + pub fn all_vv(&self) -> &VersionVector { + &self.applied_vv + } + + #[inline] + pub fn current_vv(&self) -> &VersionVector { + &self.current_vv + } + + pub(crate) fn insert(&mut self, op_id: IdFull, pos: usize, content: RichtextChunk) { + self.insert_with(op_id, pos, content.len(), |skip| { + if skip == 0 { + content + } else { + content.slice(skip..) + } + }); + } + + /// [`Self::insert`] for an op of `len` atoms whose content is built by + /// `content(skip)` for the part after its first `skip` atoms, which the + /// tracker has not applied yet. `content` is not called when the whole op + /// was applied. A caller that records the content elsewhere (the diff + /// calculators' text and value tables) then records each atom once, + /// however often a checkout replays the op. + pub(crate) fn insert_with( + &mut self, + mut op_id: IdFull, + mut pos: usize, + len: usize, + content: impl FnOnce(usize) -> RichtextChunk, + ) { + let mut skip = 0; + if let ControlFlow::Break(_) = self.skip_applied(op_id.id(), len, |applied_counter_end| { + skip = (applied_counter_end - op_id.counter) as usize; + }) { + return; + } + + op_id.lamport += skip as Lamport; + op_id.counter += skip as Counter; + pos += skip; + let content = content(skip); + debug_assert_eq!(content.len(), len - skip); + self._insert(pos, content, op_id); + } + + fn _insert(&mut self, pos: usize, content: RichtextChunk, op_id: IdFull) { + self._insert_inner(pos, content, op_id, true); + } + + pub(crate) fn insert_seeded(&mut self, pos: usize, content: RichtextChunk, op_id: IdFull) { + self._insert_inner(pos, content, op_id, false); + } + + fn _insert_inner( + &mut self, + pos: usize, + content: RichtextChunk, + op_id: IdFull, + update_vv: bool, + ) { + let result = self.rope.insert( + pos, + FugueSpan { + content, + id: op_id, + real_id: if op_id.peer == UNKNOWN_PEER_ID { + None + } else { + Some(op_id.id().try_into().unwrap()) + }, + status: Status::default(), + diff_status: None, + origin_left: None, + origin_right: None, + }, + |id| self.id_to_cursor.get_insert(id).unwrap(), + ); + self.id_to_cursor.insert( + op_id.id(), + id_to_cursor::Cursor::new_insert(result.leaf, content.len()), + ); + + self.update_insert_by_split(&result.splitted.arr); + + if update_vv { + let end_id = op_id.inc(content.len() as Counter); + self.current_vv.extend_to_include_end_id(end_id.id()); + self.applied_vv.extend_to_include_end_id(end_id.id()); + } + } + + fn update_insert_by_split(&mut self, split: &[LeafIndex]) { + match split.len() { + 0 => {} + 1 => { + let new_leaf_idx = split[0]; + let leaf = self.rope.tree().get_elem(new_leaf_idx).unwrap(); + self.id_to_cursor + .update_insert(leaf.id_span(), new_leaf_idx); + } + _ => { + let mut updates = Vec::with_capacity(split.len()); + for &new_leaf_idx in split { + let leaf = self.rope.tree().get_elem(new_leaf_idx).unwrap(); + updates.push((leaf.id_span(), new_leaf_idx)); + } + self.id_to_cursor.update_insert_batch(&mut updates); + } + } + } + + /// Delete the element from pos..pos+len + /// + /// If `reverse` is true, the deletion happens from the end of the range to the start. + /// So the first op is the one that deletes element at `pos+len-1`, the last op + /// is the one that deletes element at `pos`. + /// + /// - op_id: the first op that perform the deletion + /// - target_start_id: in the target deleted span, it's the first id of the span + /// - pos: the start pos of the deletion in the target span + /// - len: the length of the deletion span + /// - reverse: if true, the kth op delete the last kth element of the span + pub(crate) fn delete( + &mut self, + mut op_id: ID, + mut target_start_id: ID, + pos: usize, + mut len: usize, + reverse: bool, + ) { + if let ControlFlow::Break(_) = self.skip_applied(op_id, len, |applied_counter_end: i32| { + // the op is partially included, need to slice the op + let start = (applied_counter_end - op_id.counter) as usize; + op_id.counter = applied_counter_end; + if !reverse { + target_start_id = target_start_id.inc(start as i32); + } + // Okay, this looks pretty weird, but it's correct. + // If it's reverse, we don't need to change the target_start_id, because target_start_id always pointing towards the + // leftmost element of the span. After applying the initial part of the deletion, which starts from the right side, + // the target_start_id will be still pointing towards the same leftmost element, thus no need to change. + len -= start; + // If reverse, don't need to change the pos, because it's deleting backwards. + // If not reverse, we don't need to change the pos either, because the `start` chars after it are already deleted + }) { + return; + } + + // tracing::info!("after forwarding pos={} len={}", pos, len); + + self._delete(target_start_id, pos, len, reverse, op_id); + } + + fn _delete(&mut self, target_start_id: ID, pos: usize, len: usize, reverse: bool, op_id: ID) { + let mut ans = Vec::new(); + let split = self + .rope + .delete(target_start_id, pos, len, reverse, &mut |span| { + let mut id_span = span.id_span(); + if reverse { + id_span.reverse(); + } + ans.push(id_span); + }); + + let mut cur_id = op_id; + for id_span in ans { + let len = id_span.atom_len(); + self.id_to_cursor + .insert(cur_id, id_to_cursor::Cursor::Delete(id_span)); + cur_id = cur_id.inc(len as Counter); + } + + debug_assert_eq!(cur_id.counter - op_id.counter, len as Counter); + for s in split { + self.update_insert_by_split(&s.arr); + } + + let end_id = op_id.inc(len as Counter); + self.current_vv.extend_to_include_end_id(end_id); + self.applied_vv.extend_to_include_end_id(end_id); + } + + fn skip_applied( + &mut self, + op_id: ID, + len: usize, + mut f: impl FnMut(Counter), + ) -> ControlFlow<()> { + let last_id = op_id.inc(len as Counter - 1); + let applied_counter_end = self.applied_vv.get(&last_id.peer).copied().unwrap_or(0); + if applied_counter_end > op_id.counter { + if !self.current_vv.includes_id(last_id) { + // PERF: may be slow + let mut updates = Default::default(); + let cnt_start = self.current_vv.get(&op_id.peer).copied().unwrap_or(0); + self.forward( + IdSpan::new(op_id.peer, cnt_start, op_id.counter + len as Counter), + &mut updates, + ); + self.batch_update(updates, false); + } + + if applied_counter_end > last_id.counter { + self.current_vv.extend_to_include_last_id(last_id); + return ControlFlow::Break(()); + } + + f(applied_counter_end); + } + ControlFlow::Continue(()) + } + + /// Internally it's delete at the src and insert at the dst. + /// + /// But it needs special behavior for id_to_cursor data structure + /// + #[instrument(skip(self))] + pub(crate) fn move_item( + &mut self, + op_id: IdFull, + deleted_id: ID, + from_pos: usize, + to_pos: usize, + ) { + if let ControlFlow::Break(_) = self.skip_applied(op_id.id(), 1, |_| unreachable!()) { + return; + } + + // We record the **fake** id of the deleted item, and store it in the `id_to_cursor`. + // This is because when we retreat, we need to know the **fake** id of the deleted item, + // so that we can look up the insert pos in `id_to_cursor` + // + // > `id_to_cursor` only stores the mappings from **fake** insert id to the leaf index. + // > **Fake** means the id may be a temporary placeholder, created with UNKNOWN_PEER_ID. + let mut fake_delete_id = None; + let split = self.rope.delete(deleted_id, from_pos, 1, false, &mut |s| { + debug_assert_eq!(s.rle_len(), 1); + fake_delete_id = Some(s.id.id()); + }); + + for s in split { + self.update_insert_by_split(&s.arr); + } + + let result = self.rope.insert( + to_pos, + FugueSpan { + // we need to use the special move content to avoid + // its merging with other [FugueSpan], which will make + // id_to_cursor need to track its split. + // It would be much harder to implement correctly + content: RichtextChunk::new_move(), + id: op_id, + real_id: if op_id.peer == UNKNOWN_PEER_ID { + None + } else { + Some(op_id.id().try_into().unwrap()) + }, + status: Status::default(), + diff_status: None, + origin_left: None, + origin_right: None, + }, + |id| self.id_to_cursor.get_insert(id).unwrap(), + ); + self.update_insert_by_split(&result.splitted.arr); + + self.id_to_cursor.insert( + op_id.id(), + id_to_cursor::Cursor::new_move(result.leaf, fake_delete_id.unwrap()), + ); + + let end_id = op_id.inc(1); + self.current_vv.extend_to_include_end_id(end_id.id()); + self.applied_vv.extend_to_include_end_id(end_id.id()); + } + + #[inline] + pub(crate) fn checkout(&mut self, vv: &VersionVector) { + self._checkout(vv, false); + } + + fn _checkout(&mut self, vv: &VersionVector, on_diff_status: bool) { + // tracing::info!("Checkout to {:?} from {:?}", vv, self.current_vv); + if on_diff_status { + self.rope.clear_diff_status(); + } + + let current_vv = std::mem::take(&mut self.current_vv); + let (retreat, forward) = current_vv.diff_iter(vv); + let mut updates = Vec::new(); + for span in retreat { + for c in self.id_to_cursor.iter(span) { + match c { + id_to_cursor::IterCursor::Insert { leaf, id_span } => { + updates.push(crdt_rope::LeafUpdate { + leaf, + id_span, + set_future: Some(true), + delete_times_diff: 0, + }) + } + id_to_cursor::IterCursor::Delete(span) => { + for to_del in self.id_to_cursor.iter(span) { + match to_del { + id_to_cursor::IterCursor::Insert { leaf, id_span } => { + updates.push(crdt_rope::LeafUpdate { + leaf, + id_span, + set_future: None, + delete_times_diff: -1, + }) + } + id_to_cursor::IterCursor::Move { + from_id: _, + to_leaf, + new_op_id, + } => updates.push(crdt_rope::LeafUpdate { + leaf: to_leaf, + id_span: new_op_id.to_span(1), + set_future: None, + delete_times_diff: -1, + }), + _ => unreachable!(), + } + } + } + id_to_cursor::IterCursor::Move { + from_id: from, + to_leaf: to, + new_op_id: op_id, + } => { + let mut visited = false; + for to_del in self.id_to_cursor.iter(IdSpan::new( + from.peer, + from.counter, + from.counter + 1, + )) { + visited = true; + + match to_del { + id_to_cursor::IterCursor::Move { + from_id: _, + to_leaf: to, + new_op_id: op_id, + } => updates.push(crdt_rope::LeafUpdate { + leaf: to, + id_span: op_id.to_span(1), + set_future: None, + delete_times_diff: -1, + }), + // Un delete the from + id_to_cursor::IterCursor::Insert { leaf, id_span } => { + debug_assert_eq!(id_span.atom_len(), 1); + debug_assert_eq!(id_span.counter.start, from.counter); + updates.push(crdt_rope::LeafUpdate { + leaf, + id_span, + set_future: None, + delete_times_diff: -1, + }) + } + _ => unreachable!(), + } + } + assert!(visited); + // insert the new + updates.push(crdt_rope::LeafUpdate { + leaf: to, + id_span: IdSpan::new(op_id.peer, op_id.counter, op_id.counter + 1), + set_future: Some(true), + delete_times_diff: 0, + }); + } + } + } + } + + for span in forward { + self.forward(span, &mut updates); + } + + if !on_diff_status { + self.current_vv = vv.clone(); + } else { + self.current_vv = current_vv; + } + + self.batch_update(updates, on_diff_status); + } + + fn batch_update(&mut self, updates: Vec<crdt_rope::LeafUpdate>, on_diff_status: bool) { + let leaf_indexes = self.rope.update(updates, on_diff_status); + self.update_insert_by_split(&leaf_indexes); + } + + fn forward(&mut self, span: loro_common::IdSpan, updates: &mut Vec<crdt_rope::LeafUpdate>) { + for c in self.id_to_cursor.iter(span) { + match c { + id_to_cursor::IterCursor::Insert { leaf, id_span } => { + updates.push(crdt_rope::LeafUpdate { + leaf, + id_span, + set_future: Some(false), + delete_times_diff: 0, + }) + } + id_to_cursor::IterCursor::Delete(span) => { + for to_del in self.id_to_cursor.iter(span) { + match to_del { + id_to_cursor::IterCursor::Insert { leaf, id_span } => { + updates.push(crdt_rope::LeafUpdate { + leaf, + id_span, + set_future: None, + delete_times_diff: 1, + }) + } + id_to_cursor::IterCursor::Move { + from_id: _, + to_leaf, + new_op_id, + } => updates.push(crdt_rope::LeafUpdate { + leaf: to_leaf, + id_span: new_op_id.to_span(1), + set_future: None, + delete_times_diff: 1, + }), + _ => unreachable!(), + } + } + } + id_to_cursor::IterCursor::Move { + from_id: from, + to_leaf: to, + new_op_id: op_id, + } => { + for to_del in self.id_to_cursor.iter(IdSpan::new( + from.peer, + from.counter, + from.counter + 1, + )) { + match to_del { + id_to_cursor::IterCursor::Move { + from_id: _, + to_leaf: to, + new_op_id: op_id, + } => updates.push(crdt_rope::LeafUpdate { + leaf: to, + id_span: op_id.to_span(1), + set_future: None, + delete_times_diff: 1, + }), + id_to_cursor::IterCursor::Insert { leaf, id_span } => { + updates.push(crdt_rope::LeafUpdate { + leaf, + id_span, + set_future: None, + delete_times_diff: 1, + }) + } + _ => unreachable!(), + } + } + + updates.push(crdt_rope::LeafUpdate { + leaf: to, + id_span: IdSpan::new(op_id.peer, op_id.counter, op_id.counter + 1), + set_future: Some(false), + delete_times_diff: 0, + }); + } + } + } + } + + #[allow(unused)] + pub(crate) fn check(&self) { + if !cfg!(debug_assertions) { + return; + } + + self.check_vv_correctness(); + self.check_id_to_cursor_insertions_correctness(); + } + + fn check_vv_correctness(&self) { + if !cfg!(debug_assertions) { + return; + } + + for span in self.rope.tree().iter() { + if span.id.peer == UNKNOWN_PEER_ID { + continue; + } + + let id_span = span.id_span(); + assert!(self.all_vv().includes_id(id_span.id_last())); + if span.status.future { + assert!(!self.current_vv.includes_id(id_span.id_start())); + } else { + assert!(self.current_vv.includes_id(id_span.id_last())); + } + } + } + + // It can only check the correctness of insertions in id_to_cursor. + // The deletions are not checked. + fn check_id_to_cursor_insertions_correctness(&self) { + if !cfg!(debug_assertions) { + return; + } + + for rope_elem in self.rope.tree().iter() { + let id_span = rope_elem.id_span(); + let leaf_from_start = self.id_to_cursor.get_insert(id_span.id_start()).unwrap(); + let leaf_from_last = self.id_to_cursor.get_insert(id_span.id_last()).unwrap(); + assert_eq!(leaf_from_start, leaf_from_last); + let elem_from_id_to_cursor_map = self.rope.tree().get_elem(leaf_from_last).unwrap(); + assert_eq!(rope_elem, elem_from_id_to_cursor_map); + } + + for content in self.id_to_cursor.iter_all() { + match content { + id_to_cursor::IterCursor::Insert { leaf, id_span } => { + let leaf = self.rope.tree().get_elem(leaf).unwrap(); + let span = leaf.id_span(); + span.contains(id_span.id_start()); + span.contains(id_span.id_last()); + } + id_to_cursor::IterCursor::Delete(_) => {} + id_to_cursor::IterCursor::Move { .. } => {} + } + } + } + + pub(crate) fn get_target_id_latest_index_at_new_version( + &self, + id: ID, + ) -> Option<AbsolutePosition> { + // TODO: PERF this can be sped up from O(n) to O(log(n)) but I'm not sure if it's worth it + let mut index = 0; + for span in self.rope.tree.iter() { + let is_activated = span.is_activated_in_diff(); + let span_id = span.real_id(); + let id_span = span_id.to_span(span.rle_len()); + if id_span.contains(id) { + if is_activated { + index += (id.counter - id_span.counter.start) as usize; + } + + return Some(AbsolutePosition { + pos: index, + side: if is_activated { + crate::cursor::Side::Middle + } else { + crate::cursor::Side::Left + }, + }); + } + + if is_activated { + index += span.rle_len(); + } + } + + None + } + + // #[tracing::instrument(skip(self), level = "info")] + pub(crate) fn diff( + &mut self, + from: &VersionVector, + to: &VersionVector, + ) -> impl Iterator<Item = CrdtRopeDelta> + '_ { + // tracing::info!("Init: {:#?}, ", &self); + self._checkout(from, false); + self._checkout(to, true); + // self.id_to_cursor.diagnose(); + // tracing::trace!("Trace::diff {:#?}, ", &self); + + self.rope.get_diff() + } + + pub(crate) fn len(&self) -> usize { + self.rope.len() + } + + pub(crate) fn active_real_span_at(&self, pos: usize) -> Option<(ID, usize)> { + self.rope.active_real_span_at(pos) + } + + pub(crate) fn active_segments_of_real_id_span( + &self, + target_start: ID, + len: usize, + ) -> Vec<(ID, usize, usize)> { + let target_end = target_start.counter + len as Counter; + let mut index = 0; + let mut ans = Vec::new(); + + for span in self.rope.tree().iter() { + if !span.is_activated() { + continue; + } + + let span_len = span.rle_len(); + let real_id = span.real_id(); + if real_id.peer == UNKNOWN_PEER_ID { + index += span_len; + continue; + } + + if real_id.peer == target_start.peer { + let span_end = real_id.counter + span_len as Counter; + let overlap_start = real_id.counter.max(target_start.counter); + let overlap_end = span_end.min(target_end); + if overlap_start < overlap_end { + let offset = (overlap_start - real_id.counter) as usize; + let len = (overlap_end - overlap_start) as usize; + ans.push(( + ID::new(target_start.peer, overlap_start), + index + offset, + len, + )); + } + } + + index += span_len; + } + + ans + } + + pub(crate) fn mark_shallow_root_applied(&mut self, vv: &VersionVector) { + self.applied_vv = vv.clone(); + self.current_vv = vv.clone(); + } +} + +#[cfg(test)] +mod test { + use crate::{container::richtext::RichtextChunk, vv}; + use generic_btree::rle::HasLength; + + use super::*; + use std::time::Instant; + + #[test] + fn test_len() { + let mut t = Tracker::new(); + t.insert(IdFull::new(1, 0, 0), 0, RichtextChunk::new_text(0..2)); + assert_eq!(t.rope.len(), 2); + t.checkout(&Default::default()); + assert_eq!(t.rope.len(), 0); + t.insert(IdFull::new(2, 0, 0), 0, RichtextChunk::new_text(2..4)); + let v = vv!(1 => 2, 2 => 2); + t.checkout(&v); + assert_eq!(&t.applied_vv, &v); + assert_eq!(t.rope.len(), 4); + } + + /// A re-replayed op whose prefix the tracker has gets content built only + /// for the rest; a fully applied one gets none built. + #[test] + fn insert_with_builds_content_only_for_the_unapplied_suffix() { + let mut t = Tracker::new(); + t.insert(IdFull::new(1, 0, 0), 0, RichtextChunk::new_text(0..2)); + + let mut skipped = None; + t.insert_with(IdFull::new(1, 0, 0), 0, 4, |skip| { + skipped = Some(skip); + RichtextChunk::new_text(10..12) + }); + assert_eq!(skipped, Some(2)); + assert_eq!(t.rope.len(), 4); + + t.insert_with(IdFull::new(1, 0, 0), 0, 4, |_| { + panic!("a fully applied op must not build content") + }); + assert_eq!(t.rope.len(), 4); + } + + #[test] + fn test_retreat_and_forward_delete() { + let mut t = Tracker::new(); + t.insert(IdFull::new(1, 0, 0), 0, RichtextChunk::new_text(0..10)); + t.delete(ID::new(2, 0), ID::NONE_ID, 0, 10, true); + t.checkout(&vv!(1 => 10, 2=>5)); + assert_eq!(t.rope.len(), 5); + t.checkout(&vv!(1 => 10, 2=>0)); + assert_eq!(t.rope.len(), 10); + t.checkout(&vv!(1 => 10, 2=>10)); + assert_eq!(t.rope.len(), 0); + t.checkout(&vv!(1 => 10, 2=>0)); + assert_eq!(t.rope.len(), 10); + } + + #[test] + fn repeated_tail_splits_keep_id_to_cursor_consistent() { + let mut t = Tracker::new(); + t.insert(IdFull::new(1, 0, 0), 0, RichtextChunk::new_text(0..300)); + + for (i, pos) in [100, 201, 252, 278].into_iter().enumerate() { + let op_id = IdFull::new(2, i as Counter, i as Lamport); + let start = 1000 + i as u32; + t.insert(op_id, pos, RichtextChunk::new_text(start..start + 1)); + } + + t.check(); + } + + #[test] + fn test_checkout_in_doc_with_del_span() { + let mut t = Tracker::new(); + t.insert(IdFull::new(1, 0, 0), 0, RichtextChunk::new_text(0..10)); + t.delete(ID::new(2, 0), ID::NONE_ID, 0, 10, false); + t.checkout(&vv!(1 => 10, 2=>4)); + let v: Vec<FugueSpan> = t.rope.tree().iter().copied().collect(); + assert_eq!(v.len(), 2); + assert!(!v[0].is_activated()); + assert_eq!(v[0].rle_len(), 4); + assert!(v[1].is_activated()); + assert_eq!(v[1].rle_len(), 6); + } + + #[test] + #[ignore] + fn perf_update_insert_by_split_quadratic() { + // Run with: + // cargo test -p loro-internal perf_update_insert_by_split_quadratic -- --ignored --nocapture + const CHUNK_LEN: usize = 256; + let fragments: usize = std::env::var("LORO_PERF_FRAGMENTS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(8192); + const PEER_A: PeerID = 1; + const PEER_B: PeerID = 2; + + let doc_len = CHUNK_LEN * fragments; + + let mut t = Tracker::new(); + t.insert( + IdFull::new(PEER_A, 0, 0), + 0, + RichtextChunk::new_text(0..doc_len as u32), + ); + t.id_to_cursor.diagnose(); + + let start = Instant::now(); + let expected_fragment_updates = (fragments as u64) * ((fragments - 1) as u64) / 2; + + for i in 0..(fragments - 1) { + let pos = (i + 1) * CHUNK_LEN + i; + let op_id = IdFull::new(PEER_B, i as Counter, i as Lamport); + let chunk = RichtextChunk::new_text( + (doc_len as u32 + i as u32)..(doc_len as u32 + i as u32 + 1), + ); + t.insert(op_id, pos, chunk); + } + + let elapsed = start.elapsed(); + let before_vv = vv!(PEER_A => doc_len as Counter); + let after_vv = vv!(PEER_A => doc_len as Counter, PEER_B => (fragments - 1) as Counter); + let diff_start = Instant::now(); + let diff_len = t.diff(&before_vv, &after_vv).count(); + let diff_elapsed = diff_start.elapsed(); + assert_eq!(t.rope.tree().iter().count(), 1 + 2 * (fragments - 1)); + println!( + "perf_update_insert_by_split_quadratic: doc_len={}, fragments={}, expected_fragment_updates={}, insert_elapsed={:?}, diff_items={}, diff_elapsed={:?}", + doc_len, fragments, expected_fragment_updates, elapsed, diff_len, diff_elapsed + ); + } + + #[test] + #[ignore] + fn perf_update_insert_by_split_quadratic_unknown() { + // Run with: + // LORO_PERF_FRAGMENTS=8192 cargo test -p loro-internal perf_update_insert_by_split_quadratic_unknown -- --ignored --nocapture + const CHUNK_LEN: usize = 256; + let fragments: usize = std::env::var("LORO_PERF_FRAGMENTS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(8192); + const PEER_B: PeerID = 2; + + let doc_len = CHUNK_LEN * fragments; + + let mut t = Tracker::new_with_unknown(); + t.checkout(&vv!()); + t.id_to_cursor.diagnose(); + + let start = Instant::now(); + for i in 0..(fragments - 1) { + let pos = (i + 1) * CHUNK_LEN + i; + let op_id = IdFull::new(PEER_B, i as Counter, i as Lamport); + let chunk = RichtextChunk::new_text( + (doc_len as u32 + i as u32)..(doc_len as u32 + i as u32 + 1), + ); + t.insert(op_id, pos, chunk); + } + + let elapsed = start.elapsed(); + println!( + "perf_update_insert_by_split_quadratic_unknown: doc_len={}, fragments={}, elapsed={:?}", + doc_len, fragments, elapsed + ); + } +} diff --git a/vendor/loro-internal/src/container/richtext/tracker/crdt_rope.rs b/vendor/loro-internal/src/container/richtext/tracker/crdt_rope.rs new file mode 100644 index 0000000..3e3576c --- /dev/null +++ b/vendor/loro-internal/src/container/richtext/tracker/crdt_rope.rs @@ -0,0 +1,953 @@ +use std::cmp::Ordering; + +use generic_btree::{ + rle::{CanRemove, HasLength, Sliceable}, + BTree, BTreeTrait, Cursor, FindResult, LeafIndex, Query, SplittedLeaves, +}; +use itertools::Itertools; +use loro_common::{Counter, HasCounter, HasCounterSpan, HasIdSpan, IdSpan, Lamport, ID}; +use smallvec::{smallvec, SmallVec}; + +use crate::container::richtext::{fugue_span::DiffStatus, FugueSpan, RichtextChunk, Status}; + +use super::UNKNOWN_PEER_ID; + +#[derive(Debug, Default, Clone)] +pub(super) struct CrdtRope { + pub(super) tree: BTree<CrdtRopeTrait>, +} + +pub(super) struct InsertResult { + #[allow(unused)] + pub content: FugueSpan, + pub leaf: LeafIndex, + pub splitted: SplittedLeaves, +} + +impl CrdtRope { + pub fn new() -> Self { + Self { tree: BTree::new() } + } + + #[inline(always)] + #[allow(unused)] + pub fn len(&self) -> usize { + self.tree.root_cache().len as usize + } + + #[inline(always)] + pub(super) fn tree(&self) -> &BTree<CrdtRopeTrait> { + &self.tree + } + + pub(super) fn active_real_span_at(&self, pos: usize) -> Option<(ID, usize)> { + if pos >= self.len() { + return None; + } + + let start = self + .tree + .query::<ActiveLenQueryPreferRight>(&(pos as i32))?; + let cursor = start.cursor; + let elem = self.tree.get_elem(cursor.leaf)?; + if !elem.is_activated() || cursor.offset >= elem.rle_len() { + return None; + } + + Some(( + elem.real_id().inc(cursor.offset as Counter), + elem.rle_len() - cursor.offset, + )) + } + + pub(super) fn insert( + &mut self, + pos: usize, + mut content: FugueSpan, + find_elem: impl Fn(ID) -> LeafIndex, + ) -> InsertResult { + if self.tree.is_empty() { + assert_eq!(pos, 0); + let leaf = self.tree.push(content).leaf; + return InsertResult { + content, + leaf, + splitted: SplittedLeaves::default(), + }; + } + + // tracing::span!(tracing::Level::INFO, "Inserting {} len={}", content.id, content.rle_len()); + + let pos = pos as i32; + let start = self.tree.query::<ActiveLenQueryPreferLeft>(&pos).unwrap(); + + let (parent_right_leaf, in_between) = { + // calculate origin_left and origin_right + // origin_left is the alive op at `pos-1`, origin_right is the first non-future op between `pos-1` and `pos`. + + // `start` may point to a zero len node that's before the active index. + let origin_left = if start.cursor.offset == 0 { + // get left leaf node if offset == 0, so we can calculate the origin_left + if let Some(left) = self.tree.prev_elem(start.cursor) { + let left_node = self.tree.get_leaf(left.leaf.into()); + assert!(left_node.elem().rle_len() > 0); + Some( + left_node + .elem() + .id + .inc(left_node.elem().rle_len() as Counter - 1) + .id(), + ) + } else { + None + } + } else { + let left_node = self.tree.get_leaf(start.leaf().into()); + assert!(left_node.elem().rle_len() >= start.offset()); + Some(left_node.elem().id.inc(start.offset() as Counter - 1).id()) + }; + + let (origin_right, parent_right_leaf, in_between) = { + let mut in_between = Vec::new(); + let mut origin_right = None; + let mut parent_right_idx = None; + for iter in self.tree.iter_range(start.cursor..) { + if let Some(offset) = iter.start { + if offset >= iter.elem.rle_len() { + continue; + } + } + + if !iter.elem.status.future { + origin_right = + Some(iter.elem.id.inc(iter.start.unwrap_or(0) as Counter).id()); + let parent_right = match iter.start { + Some(offset) if offset > 0 => { + // It's guaranteed that origin_right's origin_left == this.origin_left. + // Because the first non-future node is just the leaf node in `start.cursor` node (iter.start.is_some()) + // Thus parent_right = origin_right + Some(origin_right) + } + _ => { + // Otherwise, we need to test whether origin_right's origin_left == this.origin_left + if iter.elem.origin_left.map(|x| x.to_id()) == origin_left { + Some(origin_right) + } else { + None + } + } + }; + parent_right_idx = parent_right.map(|_| iter.cursor().leaf); + break; + } + + // elem must be from future + in_between.push((iter.cursor().leaf, *iter.elem)); + } + + (origin_right, parent_right_idx, in_between) + }; + + content.origin_left = origin_left.map(|x| x.try_into().unwrap()); + content.origin_right = origin_right.map(|x| x.try_into().unwrap()); + (parent_right_leaf, in_between) + }; + + let mut insert_pos = start.cursor; + + if !in_between.is_empty() { + // find insert pos + let mut scanning = false; + let mut visited: SmallVec<[IdSpan; 4]> = Default::default(); + for (other_leaf, other_elem) in in_between.iter() { + // tracing::info!("Visiting {}", &other_elem.id); + let other_origin_left = other_elem.origin_left; + if other_origin_left != content.origin_left + && other_origin_left + .map(|left| visited.iter().all(|x| !x.contains_id(left.to_id()))) + .unwrap_or(true) + { + // The other_elem's origin_left must be at the left side of content's origin_left. + // So the content must be at the left side of other_elem. + + // tracing::info!("Break because the node's origin_left is at the left side of new_elem's origin left"); + break; + } + + visited.push(IdSpan::new( + other_elem.id.peer, + other_elem.id.counter, + other_elem.id.counter + other_elem.rle_len() as Counter, + )); + + if content.origin_left == other_origin_left { + if other_elem.origin_right == content.origin_right { + // tracing::info!("Same right parent"); + // Same right parent + if other_elem.id.peer > content.id.peer { + // tracing::info!("Break on larger peer"); + break; + } else { + scanning = false; + } + } else { + // tracing::info!("Different right parent"); + // Different right parent, we need to compare the right parents' position + + let other_parent_right_idx = + if let Some(other_origin_right) = other_elem.origin_right { + let elem_idx = find_elem(other_origin_right.to_id()); + let elem = self.tree.get_elem(elem_idx).unwrap(); + // It must be the start of the elem + assert_eq!(elem.id.id(), other_origin_right.to_id()); + if elem.origin_left == content.origin_left { + Some(elem_idx) + } else { + None + } + } else { + None + }; + + match self.cmp_pos(other_parent_right_idx, parent_right_leaf) { + Ordering::Less => { + // tracing::info!("Less"); + scanning = true; + } + Ordering::Equal if other_elem.id.peer > content.id.peer => { + // tracing::info!("Break on eq"); + break; + } + _ => { + // tracing::info!("Scanning"); + scanning = false; + } + } + } + } + + if !scanning { + insert_pos = Cursor { + leaf: *other_leaf, + offset: other_elem.rle_len(), + }; + // tracing::info!("updating insert pos {:?}", &insert_pos); + } + } + } + + // tracing::info!("Inserting at {:?}", insert_pos); + // + let (cursor, splitted) = self.tree.insert_by_path(insert_pos, content); + InsertResult { + content, + leaf: cursor.leaf, + splitted, + } + } + + /// Delete the span at `pos` with `len`. + /// + /// The `start_id` is used to mark the real_id in the [FugueSpan]. + /// + /// - If reversed is true, the deletion will be done in reversed order. + /// But the start_id always refers to the first delete op's id. + /// - If reversed is true, the returned `SplittedLeaves` will be in reversed order. + pub(super) fn delete( + &mut self, + mut start_id: ID, + pos: usize, + len: usize, + reversed: bool, + notify_deleted_span: &mut dyn FnMut(&FugueSpan), + ) -> SmallVec<[SplittedLeaves; 1]> { + if len == 0 { + return Default::default(); + } + + if reversed && len > 1 { + // TODO: PERF: optimize this + let mut ans = SmallVec::with_capacity(len); + for i in (0..len).rev() { + let a = self.delete( + start_id.inc(i as i32), + pos + i, + 1, + false, + notify_deleted_span, + ); + + ans.extend(a); + } + + return ans; + } + + let start = self + .tree + .query::<ActiveLenQueryPreferRight>(&(pos as i32)) + .unwrap(); + // avoid pointing to the end of the node + let start = start.cursor; + let elem = self.tree.get_elem_mut(start.leaf).unwrap(); + if elem.rle_len() >= start.offset + len { + // tracing::info!("len={} offset={} l={} ", elem.rle_len(), start.offset, len,); + let (_, splitted) = self.tree.update_leaf(start.leaf, |elem| { + let (a, b) = elem.update_with_split(start.offset..start.offset + len, |elem| { + assert!(elem.is_activated()); + debug_assert_eq!(len, elem.rle_len()); + notify_deleted_span(elem); + elem.status.delete_times += 1; + if elem.real_id.is_none() { + elem.real_id = Some(start_id.try_into().unwrap()); + } + + start_id = start_id.inc(elem.rle_len() as i32); + }); + + (true, a, b) + }); + + return smallvec![splitted]; + } + + let end = self + .tree + .query::<ActiveLenQueryPreferLeft>(&((pos + len) as i32)) + .unwrap(); + smallvec![self.tree.update(start..end.cursor(), &mut |elem| { + if elem.is_activated() { + notify_deleted_span(elem); + elem.status.delete_times += 1; + if elem.real_id.is_none() { + elem.real_id = Some(start_id.try_into().unwrap()); + } + + start_id = start_id.inc(elem.rle_len() as i32); + Some(Cache { + len: -(elem.rle_len() as i32), + changed_num: 0, + }) + } else { + None + } + })] + } + + #[allow(unused)] + pub(crate) fn diagnose(&self) { + println!("crdt_rope number of tree nodes = {}", self.tree.node_len()); + } + + /// Update the leaf with given `id_span` + /// + /// Return the new leaf indexes that are created by splitting the old leaf nodes + pub(super) fn update( + &mut self, + mut updates: Vec<LeafUpdate>, + on_diff_status: bool, + ) -> Vec<LeafIndex> { + updates.sort_by_key(|x| x.leaf); + let mut tree_update_info = Vec::with_capacity(updates.len()); + for (leaf, group) in &updates.into_iter().group_by(|x| x.leaf) { + let elem = self.tree.get_elem(leaf).unwrap(); + for u in group { + debug_assert_eq!(u.id_span.peer, elem.id.peer); + let start = (u.id_span.ctr_start() - elem.id.counter).max(0); + let end = (u.id_span.ctr_end() - elem.id.counter).max(0); + let len = elem.rle_len(); + + tree_update_info.push((leaf, (start as usize).min(len)..(end as usize).min(len), u)) + } + } + + self.tree + .update_leaves_with_arg_in_ranges(tree_update_info, |elem, arg| { + let status = if on_diff_status { + if elem.diff_status.is_none() { + elem.diff_status = Some(elem.status); + } + elem.diff_status.as_mut().unwrap() + } else { + &mut elem.status + }; + + if let Some(f) = arg.set_future { + status.future = f; + } + + status.delete_times += arg.delete_times_diff; + }) + } + + pub(super) fn clear_diff_status(&mut self) { + self.tree.update_cache_and_elem_with_filter( + |cache| { + let drill = cache.changed_num > 0; + cache.changed_num = 0; + drill + }, + |elem| { + elem.diff_status = None; + }, + ); + } + + pub(super) fn get_diff(&self) -> impl Iterator<Item = CrdtRopeDelta> + '_ { + let mut last_pos = 0; + let mut iter = self + .tree + .iter_with_filter(|cache| (cache.changed_num > 0, cache.len)); + let mut next = None; + std::iter::from_fn(move || { + if let Some(next) = next.take() { + return Some(next); + } + + #[allow(clippy::while_let_on_iterator)] + while let Some((index, elem)) = iter.next() { + // The elements will not be changed by this method. + // This index is current index of the elem (calculated by `status` field rather than `diff_status` field) + match elem.diff() { + DiffStatus::NotChanged => {} + DiffStatus::Created => { + let rt = Some(CrdtRopeDelta::Insert { + chunk: elem.content, + id: elem.real_id.map(|x| x.to_id()).unwrap(), + lamport: if elem.id.peer == UNKNOWN_PEER_ID { + None + } else { + Some(elem.id.lamport) + }, + }); + if index > last_pos { + next = rt; + let len = index - last_pos; + // last pos = index, because the creation has not been applied to the elem + last_pos = index; + return Some(CrdtRopeDelta::Retain(len as usize)); + } else { + return rt; + } + } + DiffStatus::Deleted => { + let rt = Some(CrdtRopeDelta::Delete(elem.rle_len())); + if index > last_pos { + next = rt; + let len = index - last_pos; + // last pos = index + len, because the deletion has not been applied to the elem + last_pos = index + elem.rle_len() as i32; + return Some(CrdtRopeDelta::Retain(len as usize)); + } else { + last_pos = index + elem.rle_len() as i32; + return rt; + } + } + } + } + + None + }) + } + + fn cmp_pos( + &self, + parent_right: Option<LeafIndex>, + other_parent_right: Option<LeafIndex>, + ) -> Ordering { + match (parent_right, other_parent_right) { + (Some(a), Some(b)) => self + .tree + .compare_pos(Cursor { leaf: a, offset: 0 }, Cursor { leaf: b, offset: 0 }), + (Some(_), None) => Ordering::Less, + (None, Some(_)) => Ordering::Greater, + (None, None) => Ordering::Equal, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Copy)] +pub(crate) enum CrdtRopeDelta { + Retain(usize), + Insert { + chunk: RichtextChunk, + id: ID, + /// This is a optional field, because we may not know the correct lamport + /// for chunk id with UNKNOWN_PEER_ID. + /// + /// This case happens when the chunk is created by default placeholder and + /// the deletion happens that marks the chunk with its start_id. But it doesn't + /// know the correct lamport for the chunk. + lamport: Option<Lamport>, + }, + Delete(usize), +} + +#[derive(Debug, Clone, Copy)] +pub(super) struct CrdtRopeTrait; + +#[derive(Debug, Default, Clone, PartialEq, Eq, Copy)] +pub(super) struct Cache { + pub(super) len: i32, + pub(super) changed_num: i32, +} + +impl CanRemove for Cache { + fn can_remove(&self) -> bool { + self.len == 0 && self.changed_num == 0 + } +} + +impl BTreeTrait for CrdtRopeTrait { + type Elem = FugueSpan; + type Cache = Cache; + type CacheDiff = Cache; + const USE_DIFF: bool = true; + + #[inline(always)] + fn calc_cache_internal( + cache: &mut Self::Cache, + caches: &[generic_btree::Child<Self>], + ) -> Self::CacheDiff { + let new_len = caches.iter().map(|x| x.cache.len).sum(); + let new_changed_num = caches.iter().map(|x| x.cache.changed_num).sum(); + let len_diff = new_len - cache.len; + let changed_num_diff = new_changed_num - cache.changed_num; + cache.len = new_len; + cache.changed_num = new_changed_num; + Cache { + len: len_diff, + changed_num: changed_num_diff, + } + } + + #[inline(always)] + fn apply_cache_diff(cache: &mut Self::Cache, diff: &Self::CacheDiff) { + cache.len += diff.len; + cache.changed_num += diff.changed_num; + } + + #[inline(always)] + fn merge_cache_diff(diff1: &mut Self::CacheDiff, diff2: &Self::CacheDiff) { + diff1.len += diff2.len; + diff1.changed_num += diff2.changed_num; + } + + #[inline(always)] + fn get_elem_cache(elem: &Self::Elem) -> Self::Cache { + Cache { + len: elem.activated_len() as i32, + changed_num: if elem.diff_status.is_some() { 1 } else { 0 }, + } + } + + #[inline(always)] + fn new_cache_to_diff(cache: &Self::Cache) -> Self::CacheDiff { + *cache + } + + fn sub_cache(cache_lhs: &Self::Cache, cache_rhs: &Self::Cache) -> Self::CacheDiff { + Cache { + len: cache_lhs.len - cache_rhs.len, + changed_num: cache_lhs.changed_num - cache_rhs.changed_num, + } + } +} + +/// Query for start position, prefer left. +/// +/// If there are zero length spans (deleted, or spans from future) at the +/// active index, the query will return the position of the first non-zero length +/// content before them. +/// +/// NOTE: it may points to the end of a leaf node (with offset = rle_len) while the next leaf node is available. +struct ActiveLenQueryPreferLeft { + left: i32, +} + +impl Query<CrdtRopeTrait> for ActiveLenQueryPreferLeft { + type QueryArg = i32; + + fn init(target: &Self::QueryArg) -> Self { + debug_assert!(*target >= 0); + ActiveLenQueryPreferLeft { left: *target } + } + + fn find_node( + &mut self, + _: &Self::QueryArg, + child_caches: &[generic_btree::Child<CrdtRopeTrait>], + ) -> generic_btree::FindResult { + let mut left = self.left; + for (i, child) in child_caches.iter().enumerate() { + let cache = &child.cache; + if left <= cache.len { + // Prefer left. So if both `cache.len` and `left` equal zero, return here. + self.left = left; + return generic_btree::FindResult::new_found(i, left as usize); + } + + left -= cache.len; + } + + if let Some(last) = child_caches.last() { + left += last.cache.len; + self.left = left; + FindResult::new_missing(child_caches.len() - 1, left as usize) + } else { + // TODO: this should be impossible + unreachable!() + } + } + + fn confirm_elem( + &mut self, + _: &Self::QueryArg, + elem: &<CrdtRopeTrait as BTreeTrait>::Elem, + ) -> (usize, bool) { + if elem.is_activated() { + (self.left as usize, (self.left as usize) < elem.rle_len()) + } else { + // prefer left on zero length spans + (0, self.left == 0) + } + } +} + +/// Query for start position, prefer right +/// +/// If there are zero length spans (deleted, or spans from future) at the +/// active index, the query will return the position of the first non-zero length +/// content after them. +struct ActiveLenQueryPreferRight { + left: i32, +} + +impl Query<CrdtRopeTrait> for ActiveLenQueryPreferRight { + type QueryArg = i32; + + fn init(target: &Self::QueryArg) -> Self { + debug_assert!(*target >= 0); + Self { left: *target } + } + + fn find_node( + &mut self, + _: &Self::QueryArg, + child_caches: &[generic_btree::Child<CrdtRopeTrait>], + ) -> generic_btree::FindResult { + let mut left = self.left; + for (i, child) in child_caches.iter().enumerate() { + let cache = &child.cache; + if left < cache.len { + // Prefer left. So if both `cache.len` and `left` equal zero, return here. + self.left = left; + return generic_btree::FindResult::new_found(i, left as usize); + } + + left -= cache.len; + } + + if let Some(last) = child_caches.last() { + left += last.cache.len; + self.left = left; + FindResult::new_missing(child_caches.len() - 1, left as usize) + } else { + // TODO: this should be impossible + unreachable!() + } + } + + fn confirm_elem( + &mut self, + _: &Self::QueryArg, + elem: &<CrdtRopeTrait as BTreeTrait>::Elem, + ) -> (usize, bool) { + if elem.is_activated() { + (self.left as usize, (self.left as usize) < elem.rle_len()) + } else { + (self.left as usize, self.left == 0) + } + } +} + +/// This struct describe the ways to update a leaf's status +#[derive(Clone, Debug, Copy)] +pub(super) struct LeafUpdate { + pub leaf: LeafIndex, + /// `id_span` should only contains a subset of the leaf content + pub id_span: IdSpan, + /// if `set_future` is `None`, the `future` field will not be changed + pub set_future: Option<bool>, + pub delete_times_diff: i16, +} + +impl LeafUpdate { + #[allow(unused)] + fn apply_to(&self, s: &mut Status) { + s.delete_times += self.delete_times_diff; + if let Some(f) = self.set_future { + s.future = f; + } + } +} + +#[cfg(test)] +mod test { + use std::ops::Range; + + use loro_common::{CompactId, Counter, IdFull, PeerID, ID}; + + use crate::container::richtext::RichtextChunk; + + use super::*; + + fn span(id: u32, range: Range<u32>) -> FugueSpan { + FugueSpan::new( + IdFull::new(id as PeerID, 0 as Counter, 0), + RichtextChunk::new_text(range), + ) + } + + #[allow(unused)] + fn unknown_span(id: u32, len: usize) -> FugueSpan { + FugueSpan::new( + IdFull::new(id as PeerID, 0 as Counter, 0), + RichtextChunk::new_unknown(len as u32), + ) + } + + fn future_span(id: u32, range: Range<u32>) -> FugueSpan { + let mut fugue = FugueSpan::new( + IdFull::new(id as PeerID, 0 as Counter, 0), + RichtextChunk::new_text(range), + ); + + fugue.status.future = true; + fugue + } + + fn dead_span(id: u32, range: Range<u32>) -> FugueSpan { + let mut span = FugueSpan::new( + IdFull::new(id as PeerID, 0 as Counter, 0), + RichtextChunk::new_text(range), + ); + + span.status.delete_times += 1; + span + } + + #[test] + fn len_test() { + let mut rope = CrdtRope::new(); + rope.insert(0, span(0, 0..10), |_| panic!()); + assert_eq!(rope.len(), 10); + rope.insert(5, span(1, 0..10), |_| panic!()); + assert_eq!(rope.len(), 20); + rope.insert(20, span(1, 0..10), |_| panic!()); + assert_eq!(rope.len(), 30); + for i in 3..30 { + assert_eq!(rope.len(), i * 10); + rope.insert( + i, + span(i as u32, i as u32 * 10..(i as u32 + 1) * 10), + |_| panic!(), + ); + } + } + + #[test] + fn content_insert_middle() { + let mut rope = CrdtRope::new(); + rope.insert(0, span(0, 0..10), |_| panic!()); + rope.insert(5, span(1, 10..20), |_| panic!()); + let arr: Vec<_> = rope.tree.iter().collect(); + assert_eq!(arr.len(), 3); + assert_eq!(arr[0].rle_len(), 5); + assert_eq!(arr[1].rle_len(), 10); + assert_eq!(arr[2].rle_len(), 5); + + assert_eq!(arr[0].id.counter, 0); + assert_eq!(arr[0].id.peer, 0); + assert_eq!(arr[1].id.counter, 0); + assert_eq!(arr[1].id.peer, 1); + assert_eq!(arr[2].id.counter, 5); + assert_eq!(arr[2].id.peer, 0); + } + + #[test] + fn content_insert_should_ignore_tombstone() { + let mut rope = CrdtRope::new(); + rope.insert(0, span(0, 0..10), |_| panic!()); + // 0..10 + + rope.insert(5, dead_span(1, 10..20), |_| panic!()); + // 0..5, 10..20(dead), 5..10 + + rope.insert(10, span(0, 20..30), |_| panic!()); + // 0..5, 10..20(dead), 5..10, 20..30 + + let arr: Vec<_> = rope.tree.iter().collect(); + assert_eq!(arr.len(), 4); + assert_eq!(arr[0].rle_len(), 5); + assert_eq!(arr[1].rle_len(), 10); + assert_eq!(arr[1].activated_len(), 0); + assert_eq!(arr[2].rle_len(), 5); + assert_eq!(arr[3].rle_len(), 10); + } + + #[test] + fn get_origin_left_and_right() { + let mut rope = CrdtRope::new(); + rope.insert(0, span(0, 0..10), |_| panic!()); + let fugue = rope.insert(5, span(1, 10..20), |_| panic!()).content; + assert_eq!(fugue.origin_left, Some(CompactId::new(0, 4))); + assert_eq!(fugue.origin_right, Some(CompactId::new(0, 5))); + } + + #[test] + fn get_origin_left_and_right_among_tombstones() { + let mut rope = CrdtRope::new(); + rope.insert(0, span(0, 0..10), |_| panic!()); + assert_eq!(rope.len(), 10); + rope.delete(ID::NONE_ID, 5, 2, false, &mut |_| {}); + assert_eq!(rope.len(), 8); + let fugue = rope.insert(6, span(1, 10..20), |_| panic!()).content; + assert_eq!(fugue.origin_left, Some(CompactId::new(0, 7))); + assert_eq!(fugue.origin_right, Some(CompactId::new(0, 8))); + let fugue = rope.insert(5, span(1, 10..11), |_| panic!()).content; + assert_eq!(fugue.origin_left, Some(CompactId::new(0, 4))); + assert_eq!(fugue.origin_right, Some(CompactId::new(0, 5))); + } + + #[test] + fn should_ignore_future_spans_when_getting_origin_left() { + { + // insert future + let mut rope = CrdtRope::new(); + rope.insert(0, span(0, 0..10), |_| panic!()); + rope.insert(5, future_span(1, 10..20), |_| panic!()); + let fugue = rope.insert(5, span(1, 10..20), |_| panic!()).content; + assert_eq!(fugue.origin_left, Some(CompactId::new(0, 4))); + assert_eq!(fugue.origin_right, Some(CompactId::new(0, 5))); + } + { + // insert deleted + let mut rope = CrdtRope::new(); + rope.insert(0, span(0, 0..10), |_| panic!()); + rope.insert(5, dead_span(1, 10..20), |_| panic!()); + let fugue = rope.insert(5, span(1, 10..20), |_| panic!()).content; + assert_eq!(fugue.origin_left, Some(CompactId::new(0, 4))); + assert_eq!(fugue.origin_right, Some(CompactId::new(1, 0))); + } + } + + #[test] + fn update() { + let mut rope = CrdtRope::new(); + let result = rope.insert(0, span(0, 0..10), |_| panic!()); + let split = rope.update( + vec![LeafUpdate { + leaf: result.leaf, + id_span: IdSpan::new(0, 2, 8), + set_future: None, + delete_times_diff: 1, + }], + false, + ); + + assert_eq!(rope.len(), 4); + assert_eq!(split.len(), 2); + let split = rope.update( + vec![LeafUpdate { + leaf: split[0], + id_span: IdSpan::new(0, 2, 8), + set_future: None, + delete_times_diff: -1, + }], + false, + ); + + assert_eq!(rope.len(), 10); + assert_eq!(split.len(), 0); + } + + #[test] + fn checkout() { + let mut rope = CrdtRope::new(); + let result1 = rope.insert(0, span(0, 0..10), |_| panic!()); + let result2 = rope.insert(10, dead_span(1, 10..20), |_| panic!()); + rope.update( + vec![ + LeafUpdate { + leaf: result1.leaf, + id_span: IdSpan::new(0, 2, 8), + set_future: None, + delete_times_diff: 1, + }, + LeafUpdate { + leaf: result2.leaf, + id_span: IdSpan::new(1, 0, 3), + set_future: None, + delete_times_diff: -1, + }, + ], + true, + ); + let vec: Vec<_> = rope.get_diff().collect(); + assert_eq!( + vec![ + CrdtRopeDelta::Retain(2), + CrdtRopeDelta::Delete(6), + CrdtRopeDelta::Retain(2), + CrdtRopeDelta::Insert { + chunk: RichtextChunk::new_text(10..13), + id: ID::new(1, 0), + lamport: Some(0) + } + ], + vec, + ); + } + + #[test] + fn checkout_future() { + let mut rope = CrdtRope::new(); + let result = rope.insert(0, future_span(0, 0..10), |_| panic!()); + rope.update( + vec![LeafUpdate { + leaf: result.leaf, + id_span: IdSpan::new(0, 2, 10), + set_future: Some(false), + delete_times_diff: 0, + }], + true, + ); + let vec: Vec<_> = rope.get_diff().collect(); + assert_eq!( + vec![CrdtRopeDelta::Insert { + chunk: RichtextChunk::new_text(2..10), + id: ID::new(0, 2), + lamport: Some(2) + }], + vec, + ); + } + + #[test] + fn checkout_future_with_delete() { + let mut rope = CrdtRope::new(); + let result = rope.insert(0, future_span(0, 0..10), |_| panic!()); + rope.update( + vec![LeafUpdate { + leaf: result.leaf, + id_span: IdSpan::new(0, 2, 10), + set_future: Some(false), + delete_times_diff: 1, + }], + true, + ); + let vec: Vec<_> = rope.get_diff().collect(); + assert!(vec.is_empty()); + } +} diff --git a/vendor/loro-internal/src/container/richtext/tracker/id_to_cursor.rs b/vendor/loro-internal/src/container/richtext/tracker/id_to_cursor.rs new file mode 100644 index 0000000..d716069 --- /dev/null +++ b/vendor/loro-internal/src/container/richtext/tracker/id_to_cursor.rs @@ -0,0 +1,1222 @@ +use generic_btree::{ + rle::{HasLength, Mergeable}, + LeafIndex, +}; +use loro_common::{Counter, IdSpan, PeerID, ID}; +use rle::{HasLength as RHasLength, Mergable as RMergeable, Sliceable}; +use rustc_hash::FxHashMap; +use smallvec::smallvec; + +use self::insert_set::InsertSet; + +// If we make this too large, we may have too many cursors inside a fragment +// and trigger the worst case +const MAX_FRAGMENT_LEN: usize = 256; +#[cfg(not(test))] +const SMALL_SET_MAX_LEN: usize = 32; +#[cfg(test)] +const SMALL_SET_MAX_LEN: usize = 4; + +/// This struct maintains the mapping of Op `ID` to +/// +/// - `LeafIndex` from crdt_rope, if the Op is an Insert +/// - The IdSpan deleted by the Op, if the Op is a Delete +#[derive(Debug, Default)] +pub(super) struct IdToCursor { + map: FxHashMap<PeerID, Vec<Fragment>>, +} + +static EMPTY_VEC: Vec<Fragment> = vec![]; +impl IdToCursor { + pub fn insert_without_split(&mut self, id: ID, cursor: Cursor) { + let list = self.map.entry(id.peer).or_default(); + list.push(Fragment { + counter: id.counter, + cursor, + }); + } + + pub fn insert(&mut self, id: ID, cursor: Cursor) { + let list = self.map.entry(id.peer).or_default(); + if let Some(last) = list.last_mut() { + let last_end = last.counter + last.cursor.rle_len() as Counter; + debug_assert!(last_end <= id.counter, "id:{}, {:#?}", id, &self); + if last_end == id.counter + && last.cursor.can_merge(&cursor) + && last.cursor.rle_len() + cursor.rle_len() < MAX_FRAGMENT_LEN + { + last.cursor.merge_right(&cursor); + return; + } + } + + if let Cursor::Insert(InsertSet::Small(set)) = cursor { + if set.len > MAX_FRAGMENT_LEN as u32 { + assert!(set.set.len() == 1); + let insert = set.set[0]; + let mut counter = id.counter; + for start in (0..set.len).step_by(MAX_FRAGMENT_LEN) { + let end = (start + MAX_FRAGMENT_LEN as u32).min(set.len); + let len = (end - start) as usize; + list.push(Fragment { + counter, + cursor: Cursor::new_insert(insert.leaf, len), + }); + counter += len as Counter; + } + } else { + list.push(Fragment { + counter: id.counter, + cursor: Cursor::Insert(InsertSet::Small(set)), + }); + } + } else { + list.push(Fragment { + counter: id.counter, + cursor, + }); + } + } + + /// Update the given id_span to the new_leaf + /// + /// id_span should be within the same `Cursor` and should be a `Insert` + pub fn update_insert(&mut self, id_span: IdSpan, new_leaf: LeafIndex) { + debug_assert!(!id_span.is_reversed()); + let list = self.map.get_mut(&id_span.peer).unwrap(); + let last = list.last().unwrap(); + debug_assert!(last.counter + last.cursor.rle_len() as Counter > id_span.counter.max()); + let mut index = match list.binary_search_by_key(&id_span.counter.start, |x| x.counter) { + Ok(index) => index, + Err(index) => index.saturating_sub(1), + }; + + let mut start_counter = id_span.counter.start; + while start_counter < id_span.counter.end + && index < list.len() + && start_counter < list[index].counter_end() + { + let fragment = &mut list[index]; + let from = (start_counter - fragment.counter) as usize; + let to = + ((id_span.counter.end - fragment.counter) as usize).min(fragment.cursor.rle_len()); + + fragment.cursor.update_insert(from, to, new_leaf); + start_counter += (to - from) as Counter; + index += 1; + } + + assert_eq!(start_counter, id_span.counter.end); + } + + pub fn update_insert_batch(&mut self, updates: &mut [(IdSpan, LeafIndex)]) { + if updates.is_empty() { + return; + } + + if updates.len() == 1 { + let (span, leaf) = updates[0]; + self.update_insert(span, leaf); + return; + } + + let mut per_peer: FxHashMap<PeerID, Vec<(IdSpan, LeafIndex)>> = FxHashMap::default(); + for &(id_span, new_leaf) in updates.iter() { + per_peer + .entry(id_span.peer) + .or_default() + .push((id_span, new_leaf)); + } + + for (peer, peer_updates) in per_peer { + let Some(list) = self.map.get_mut(&peer) else { + continue; + }; + + let mut per_fragment: FxHashMap<usize, Vec<(usize, usize, LeafIndex)>> = + FxHashMap::default(); + + for (id_span, new_leaf) in peer_updates { + debug_assert!(!id_span.is_reversed()); + let mut index = + match list.binary_search_by_key(&id_span.counter.start, |x| x.counter) { + Ok(index) => index, + Err(index) => index.saturating_sub(1), + }; + + let mut start_counter = id_span.counter.start; + while start_counter < id_span.counter.end + && index < list.len() + && start_counter < list[index].counter_end() + { + let fragment = &list[index]; + let from = (start_counter - fragment.counter) as usize; + let to = ((id_span.counter.end - fragment.counter) as usize) + .min(fragment.cursor.rle_len()); + + if from != to { + per_fragment + .entry(index) + .or_default() + .push((from, to, new_leaf)); + } + + start_counter += (to - from) as Counter; + index += 1; + } + + assert_eq!(start_counter, id_span.counter.end); + } + + let mut fragment_indexes: Vec<usize> = per_fragment.keys().copied().collect(); + fragment_indexes.sort_unstable(); + for index in fragment_indexes { + let updates = per_fragment.get(&index).unwrap(); + list[index].cursor.update_insert_many(updates); + } + } + } + + pub fn iter_all(&self) -> impl Iterator<Item = IterCursor> + '_ { + self.map.iter().flat_map(|(peer, list)| { + list.iter() + .flat_map(move |f| -> Box<dyn Iterator<Item = IterCursor>> { + match &f.cursor { + Cursor::Insert(set) => set.iter_all(*peer, f.counter), + Cursor::Delete(span) => { + let start_counter = f.counter; + let end_counter = f.counter + span.atom_len() as Counter; + let id_span = IdSpan::new(*peer, start_counter, end_counter); + Box::new(std::iter::once(IterCursor::Delete(id_span))) + } + Cursor::Move { from, to } => Box::new(std::iter::once(IterCursor::Move { + from_id: *from, + to_leaf: *to, + new_op_id: ID::new(*peer, f.counter), + })), + } + }) + }) + } + + pub fn iter(&self, mut iter_id_span: IdSpan) -> impl Iterator<Item = IterCursor> + '_ { + iter_id_span.normalize_(); + let list = self.map.get(&iter_id_span.peer).unwrap_or(&EMPTY_VEC); + // Index in the list + let mut index = 0; + let mut insert_set_iter: Option<Box<dyn Iterator<Item = IterCursor>>> = None; + + if !list.is_empty() { + index = match list.binary_search_by_key(&iter_id_span.counter.start, |x| x.counter) { + Ok(index) => index, + Err(index) => index.saturating_sub(1), + }; + } + + std::iter::from_fn(move || loop { + if index >= list.len() { + return None; + } + + // Always iterate the insert set's iterator first if it exists + // It's on the top of the stack + if let Some(iter) = insert_set_iter.as_mut() { + let Some(next) = iter.next() else { + index += 1; + insert_set_iter = None; + continue; + }; + + return Some(next); + } + + let f = &list[index]; + let iter_counter = f.counter; + if iter_counter >= iter_id_span.counter.end { + return None; + } + + if iter_counter + f.cursor.rle_len() as Counter <= iter_id_span.counter.start { + index += 1; + continue; + } + + match &f.cursor { + Cursor::Insert(set) => { + insert_set_iter = Some(set.iter_range( + ID::new(iter_id_span.peer, iter_counter), + iter_id_span.counter.start, + iter_id_span.counter.end, + )); + continue; + } + Cursor::Delete(span) => { + index += 1; + let from = (iter_id_span.counter.start - iter_counter) + .max(0) + .min(span.atom_len() as Counter); + let to = (iter_id_span.counter.end - iter_counter) + .max(0) + .min(span.atom_len() as Counter); + if from == to { + continue; + } + + return Some(IterCursor::Delete(span.slice(from as usize, to as usize))); + } + Cursor::Move { from, to } => { + index += 1; + let op_id = ID::new(iter_id_span.peer, f.counter); + return Some(IterCursor::Move { + from_id: *from, + to_leaf: *to, + new_op_id: op_id, + }); + } + } + }) + } + + pub fn get_insert(&self, id: ID) -> Option<LeafIndex> { + let list = self.map.get(&id.peer)?; + let index = match list.binary_search_by_key(&id.counter, |x| x.counter) { + Ok(index) => index, + Err(index) => index - 1, + }; + + list[index] + .cursor + .get_insert((id.counter - list[index].counter) as usize) + } + + #[allow(unused)] + pub fn diagnose(&self) { + let fragment_num = self.map.iter().map(|x| x.1.len()).sum::<usize>(); + let insert_pieces = self + .map + .iter() + .flat_map(|x| x.1.iter()) + .map(|x| match &x.cursor { + Cursor::Insert(set) => set.len(), + Cursor::Delete(_) => 0, + Cursor::Move { .. } => 0, + }) + .sum::<usize>(); + let max_insert_len = self + .map + .iter() + .map(|x| { + x.1.iter() + .filter_map(|x| match &x.cursor { + Cursor::Insert(set) => Some(set.len()), + _ => None, + }) + .max() + .unwrap_or(0) + }) + .max() + .unwrap_or(0); + println!( + "fragments:{}, insert_pieces:{}, max_insert_len:{}", + fragment_num, insert_pieces, max_insert_len + ); + } +} + +#[derive(Debug)] +pub(super) struct Fragment { + pub(super) counter: Counter, + pub(super) cursor: Cursor, +} + +impl PartialEq for Fragment { + fn eq(&self, other: &Self) -> bool { + self.counter == other.counter + } +} + +impl Eq for Fragment {} + +impl PartialOrd for Fragment { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for Fragment { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.counter.cmp(&other.counter) + } +} + +impl Fragment { + fn counter_end(&self) -> Counter { + self.counter + self.cursor.rle_len() as Counter + } +} + +#[derive(Debug, Clone, Copy)] +pub(super) enum IterCursor { + Insert { + leaf: LeafIndex, + id_span: IdSpan, + }, + // deleted id_span, the start may be greater than the end + Delete(IdSpan), + // Move from `from ID` to `to LeafIndex` with `op_id` + Move { + from_id: ID, + to_leaf: LeafIndex, + new_op_id: ID, + }, +} + +#[derive(Debug)] +pub(super) enum Cursor { + Insert(InsertSet), + Delete(IdSpan), + Move { + from: ID, + to: LeafIndex, + // to id is the same as the current op_id + }, +} + +mod insert_set { + + use super::*; + use generic_btree::{ + rle::{CanRemove, TryInsert}, + BTree, BTreeTrait, LengthFinder, UseLengthFinder, + }; + use smallvec::SmallVec; + + #[derive(Debug)] + pub(crate) enum InsertSet { + Small(SmallInsertSet), + Large(LargeInsertSet), + } + + impl InsertSet { + pub(crate) fn new(leaf: LeafIndex, len: usize) -> Self { + Self::Small(SmallInsertSet { + set: smallvec![Insert { + leaf, + len: len as u32 + }], + len: len as u32, + }) + } + + pub(crate) fn update(&mut self, from: usize, to: usize, new_leaf: LeafIndex) { + self.upgrade_if_needed(); + match self { + Self::Small(set) => { + set.update(from, to, new_leaf); + } + Self::Large(set) => { + set.update(from, to, new_leaf); + } + } + } + + pub(crate) fn update_many(&mut self, updates: &[(usize, usize, LeafIndex)]) { + if updates.is_empty() { + return; + } + + if updates.len() == 1 { + let (from, to, leaf) = updates[0]; + self.update(from, to, leaf); + return; + } + + let len = self.len(); + if len > MAX_FRAGMENT_LEN { + for &(from, to, leaf) in updates { + self.update(from, to, leaf); + } + return; + } + + let mut dense: SmallVec<[LeafIndex; MAX_FRAGMENT_LEN]> = SmallVec::with_capacity(len); + match self { + InsertSet::Small(set) => { + for insert in set.set.iter() { + for _ in 0..insert.len { + dense.push(insert.leaf); + } + } + } + InsertSet::Large(set) => { + for insert in set.tree.iter() { + for _ in 0..insert.len { + dense.push(insert.leaf); + } + } + } + } + debug_assert_eq!(dense.len(), len); + + for &(from, to, leaf) in updates { + debug_assert!(from <= to); + debug_assert!(to <= len); + for i in from..to { + dense[i] = leaf; + } + } + + let mut new_set: SmallVec<[Insert; 1]> = SmallVec::new(); + if !dense.is_empty() { + let mut cur_leaf = dense[0]; + let mut cur_len: usize = 1; + for &leaf in dense.iter().skip(1) { + if leaf == cur_leaf { + cur_len += 1; + } else { + new_set.push(Insert { + leaf: cur_leaf, + len: cur_len as u32, + }); + cur_leaf = leaf; + cur_len = 1; + } + } + new_set.push(Insert { + leaf: cur_leaf, + len: cur_len as u32, + }); + } + + *self = InsertSet::Small(SmallInsertSet { + set: new_set, + len: len as u32, + }); + } + + pub(crate) fn get_insert(&self, pos: usize) -> Option<LeafIndex> { + match self { + Self::Small(set) => { + let mut index = 0; + for insert in set.set.iter() { + if index + insert.len as usize > pos { + return Some(insert.leaf); + } + index += insert.len as usize; + } + + unreachable!() + } + Self::Large(set) => set.get_insert(pos), + } + } + + pub(crate) fn len(&self) -> usize { + match self { + Self::Small(set) => set.len as usize, + Self::Large(set) => *set.tree.root_cache() as usize, + } + } + + pub(crate) fn iter_all( + &self, + peer: PeerID, + counter: Counter, + ) -> Box<dyn Iterator<Item = IterCursor> + '_> { + match self { + InsertSet::Small(set) => { + let mut offset = 0; + Box::new(set.set.iter().map(move |elem| { + let ans = IterCursor::Insert { + leaf: elem.leaf, + id_span: IdSpan::new( + peer, + counter + offset as Counter, + counter + offset as Counter + elem.len as Counter, + ), + }; + + offset += elem.len; + ans + })) + } + InsertSet::Large(set) => { + let mut offset = 0; + Box::new(set.tree.iter().map(move |elem| { + let ans = IterCursor::Insert { + leaf: elem.leaf, + id_span: IdSpan::new( + peer, + counter + offset as Counter, + counter + offset as Counter + elem.len as Counter, + ), + }; + + offset += elem.len; + ans + })) + } + } + } + + /// Iterate the given target span range, the start id of the InsertSet is cur_id + pub(crate) fn iter_range( + &self, + cur_id: ID, + target_start_counter: i32, + target_end_counter: i32, + ) -> Box<dyn Iterator<Item = IterCursor> + '_> { + match self { + InsertSet::Small(set) => { + let mut offset = 0; + Box::new(set.set.iter().filter_map(move |elem| { + let id_span = IdSpan::new( + cur_id.peer, + (cur_id.counter + offset as Counter) + .max(target_start_counter) + .min(target_end_counter), + (cur_id.counter + offset as Counter + elem.len as Counter) + .max(target_start_counter) + .min(target_end_counter), + ); + + offset += elem.len; + if id_span.atom_len() == 0 { + return None; + } + + let ans = IterCursor::Insert { + leaf: elem.leaf, + id_span, + }; + + Some(ans) + })) + } + InsertSet::Large(set) => { + // let mut offset = 0; + // Box::new(set.tree.iter().filter_map(move |elem| { + // let id_span = IdSpan::new( + // cur_id.peer, + // (cur_id.counter + offset as Counter) + // .max(target_start_counter) + // .min(target_end_counter), + // (cur_id.counter + offset as Counter + elem.len as Counter) + // .max(target_start_counter) + // .min(target_end_counter), + // ); + + // offset += elem.len; + // if id_span.atom_len() == 0 { + // return None; + // } + + // let ans = IterCursor::Insert { + // leaf: elem.leaf, + // id_span, + // }; + + // Some(ans) + // })); + let offset = (target_start_counter - cur_id.counter).max(0); + let (start, mut start_counter) = if offset > 0 { + match set.tree.query::<LengthFinder>(&(offset as usize)) { + Some(start) => ( + std::ops::Bound::Included(start.cursor), + // NOTE: Can this be wrong? + target_start_counter - start.cursor.offset as Counter, + ), + _ => (std::ops::Bound::Unbounded, cur_id.counter), + } + } else { + (std::ops::Bound::Unbounded, cur_id.counter) + }; + + Box::new( + set.tree + .iter_range((start, std::ops::Bound::Unbounded)) + .map(move |b| { + let id_span = IdSpan::new( + cur_id.peer, + (start_counter) + .max(target_start_counter) + .min(target_end_counter), + (start_counter + b.elem.rle_len() as Counter) + .max(target_start_counter) + .min(target_end_counter), + ); + + start_counter += b.elem.rle_len() as Counter; + if id_span.atom_len() == 0 { + return None; + } + + let ans = IterCursor::Insert { + leaf: b.elem.leaf, + id_span, + }; + + Some(ans) + }) + .take_while(|x| x.is_some()) + .map(|x| x.unwrap()), + ) + } + } + } + + fn upgrade_if_needed(&mut self) { + match self { + InsertSet::Small(set) => { + if set.set.len() < SMALL_SET_MAX_LEN { + return; + } + + let set = std::mem::take(&mut set.set); + let tree_set = LargeInsertSet::init_from_small(set); + *self = InsertSet::Large(tree_set); + } + InsertSet::Large(_) => {} + } + } + } + + #[derive(Debug)] + pub(crate) struct SmallInsertSet { + pub set: SmallVec<[Insert; 1]>, + pub len: u32, + } + + impl SmallInsertSet { + fn update(&mut self, from: usize, to: usize, new_leaf: LeafIndex) { + if from == to { + return; + } + + let mut cur_scan_index: usize = 0; + let old_set = std::mem::take(&mut self.set); + let mut new_set = SmallVec::with_capacity(old_set.len() + 2); + let mut new_leaf_inserted = false; + for insert in old_set.iter() { + if new_leaf_inserted { + let end = cur_scan_index + insert.len as usize; + if end <= to { + cur_scan_index = end; + continue; + } + + if cur_scan_index >= to { + new_set.push(*insert); + } else { + new_set.push(Insert { + leaf: insert.leaf, + len: (end - to) as u32, + }); + } + + cur_scan_index = end; + continue; + } + + if cur_scan_index + insert.len as usize <= from { + new_set.push(*insert); + cur_scan_index += insert.len as usize; + } else { + debug_assert!(!new_leaf_inserted); + let elem_end = cur_scan_index + insert.len as usize; + if cur_scan_index < from { + new_set.push(Insert { + leaf: insert.leaf, + len: (from - cur_scan_index) as u32, + }); + cur_scan_index = from; + } + + if elem_end > to { + new_set.push(Insert { + leaf: new_leaf, + len: (to - cur_scan_index) as u32, + }); + new_set.push(Insert { + leaf: insert.leaf, + len: (elem_end - to) as u32, + }); + } else { + new_set.push(Insert { + leaf: new_leaf, + len: (to - cur_scan_index) as u32, + }); + } + + new_leaf_inserted = true; + cur_scan_index = elem_end; + } + } + + self.set = new_set; + debug_assert_eq!( + self.len, + self.set.iter().map(|x| x.len as usize).sum::<usize>() as u32 + ); + } + } + + pub(super) struct InsertSetBTreeTrait; + impl CanRemove for Insert { + fn can_remove(&self) -> bool { + self.len == 0 + } + } + + impl generic_btree::rle::Mergeable for Insert { + fn can_merge(&self, rhs: &Self) -> bool { + self.leaf == rhs.leaf + } + + fn merge_right(&mut self, rhs: &Self) { + self.len += rhs.len; + } + + fn merge_left(&mut self, left: &Self) { + self.len += left.len; + } + } + + impl HasLength for Insert { + fn rle_len(&self) -> usize { + self.len as usize + } + } + + impl generic_btree::rle::Sliceable for Insert { + fn _slice(&self, range: std::ops::Range<usize>) -> Self { + Insert { + leaf: self.leaf, + len: range.len() as u32, + } + } + } + + impl TryInsert for Insert { + fn try_insert(&mut self, _: usize, elem: Self) -> Result<(), Self> { + if self.leaf == elem.leaf { + self.len += elem.len; + Ok(()) + } else { + Err(elem) + } + } + } + + impl BTreeTrait for InsertSetBTreeTrait { + type Elem = Insert; + + type Cache = i32; + + type CacheDiff = i32; + + fn calc_cache_internal( + cache: &mut Self::Cache, + caches: &[generic_btree::Child<Self>], + ) -> Self::CacheDiff { + let new: Self::Cache = caches.iter().map(|x| *x.cache()).sum(); + let diff = new - *cache; + *cache = new; + diff + } + + fn apply_cache_diff(cache: &mut Self::Cache, diff: &Self::CacheDiff) { + *cache += *diff; + } + + fn merge_cache_diff(diff1: &mut Self::CacheDiff, diff2: &Self::CacheDiff) { + *diff1 += *diff2; + } + + fn get_elem_cache(elem: &Self::Elem) -> Self::Cache { + elem.len as i32 + } + + fn new_cache_to_diff(cache: &Self::Cache) -> Self::CacheDiff { + *cache + } + + fn sub_cache(cache_lhs: &Self::Cache, cache_rhs: &Self::Cache) -> Self::CacheDiff { + *cache_lhs - *cache_rhs + } + } + + impl UseLengthFinder<InsertSetBTreeTrait> for InsertSetBTreeTrait { + fn get_len(cache: &i32) -> usize { + *cache as usize + } + } + + #[derive(Debug)] + pub(crate) struct LargeInsertSet { + tree: Box<BTree<InsertSetBTreeTrait>>, + } + + impl LargeInsertSet { + pub fn new() -> Self { + Self { + tree: Box::new(BTree::new()), + } + } + + fn update(&mut self, from: usize, to: usize, new_leaf: LeafIndex) { + if from == to { + return; + } + + let Some(from) = self.tree.query::<LengthFinder>(&from) else { + return; + }; + let to = self + .tree + .query::<LengthFinder>(&to) + .map(|x| x.cursor) + .or_else(|| self.tree.end_cursor()) + .unwrap(); + + self.tree.update(from.cursor..to, &mut |x| { + x.leaf = new_leaf; + None + }); + } + + fn get_insert(&self, pos: usize) -> Option<LeafIndex> { + let c = self.tree.query::<LengthFinder>(&pos)?.cursor; + Some(self.tree.get_elem(c.leaf)?.leaf) + } + + fn init_from_small(set: SmallVec<[Insert; 1]>) -> LargeInsertSet { + let mut tree_set = LargeInsertSet::new(); + for item in set.into_iter() { + tree_set.tree.push(item); + } + + tree_set + } + } +} + +#[derive(Debug, Clone, Copy)] +pub(super) struct Insert { + leaf: LeafIndex, + len: u32, +} + +impl Cursor { + pub fn new_insert(leaf: LeafIndex, len: usize) -> Self { + Self::Insert(InsertSet::new(leaf, len)) + } + + pub fn new_move(leaf: LeafIndex, from_id: ID) -> Self { + Self::Move { + to: leaf, + from: from_id, + } + } + + #[allow(unused)] + pub fn new_delete(id_span: IdSpan) -> Self { + Self::Delete(id_span) + } + + fn update_insert(&mut self, from: usize, to: usize, new_leaf: LeafIndex) { + // tracing::info!( + // "set_insert: from={}, to={}, new_leaf={:?}", + // from, + // to, + // &new_leaf + // ); + + assert!(from <= to); + assert!(to <= self.rle_len()); + match self { + Self::Insert(set) => { + set.update(from, to, new_leaf); + } + Self::Move { .. } => { + unreachable!("update_insert on Move") + } + _ => unreachable!(), + } + } + + fn update_insert_many(&mut self, updates: &[(usize, usize, LeafIndex)]) { + match self { + Self::Insert(set) => { + set.update_many(updates); + } + Self::Move { .. } => { + unreachable!("update_insert_many on Move") + } + _ => unreachable!(), + } + } + + fn get_insert(&self, pos: usize) -> Option<LeafIndex> { + if pos >= self.rle_len() { + return None; + } + + match self { + Cursor::Insert(set) => set.get_insert(pos), + Cursor::Move { to, .. } => { + assert!(pos == 0); + Some(*to) + } + Cursor::Delete(_) => unreachable!(), + } + } +} + +impl HasLength for Cursor { + fn rle_len(&self) -> usize { + match self { + Cursor::Insert(set) => set.len(), + Cursor::Delete(d) => d.atom_len(), + Cursor::Move { .. } => 1, + } + } +} + +impl Mergeable for Cursor { + fn can_merge(&self, rhs: &Self) -> bool { + match (self, rhs) { + (Self::Insert(InsertSet::Small(a)), Self::Insert(InsertSet::Small(b))) => { + a.set.last().unwrap().leaf == b.set.first().unwrap().leaf && b.len == 1 + } + (Self::Delete(a), Self::Delete(b)) => a.is_mergable(b, &()), + _ => false, + } + } + + fn merge_right(&mut self, rhs: &Self) { + match (self, rhs) { + (Self::Insert(InsertSet::Small(a)), Self::Insert(InsertSet::Small(b))) => { + assert!(b.len == 1); + a.set.last_mut().unwrap().len += b.set.first().unwrap().len; + a.len += b.len; + } + (Self::Delete(a), Self::Delete(b)) => { + a.merge(b, &()); + } + _ => unreachable!(), + } + } + + fn merge_left(&mut self, _: &Self) { + unreachable!(); + } +} + +#[cfg(test)] +mod test { + use std::{any::Any, ops::Range, panic::AssertUnwindSafe}; + + use super::*; + use generic_btree::{ + rle::{CanRemove, TryInsert}, + BTree, BTreeTrait, UseLengthFinder, + }; + use smallvec::smallvec; + + #[derive(Debug, Clone)] + struct DummyElem; + + impl generic_btree::rle::HasLength for DummyElem { + fn rle_len(&self) -> usize { + 1 + } + } + + impl generic_btree::rle::Sliceable for DummyElem { + fn _slice(&self, range: Range<usize>) -> Self { + assert_eq!(range.start, 0); + assert_eq!(range.end, 1); + DummyElem + } + + fn split(&mut self, _pos: usize) -> Self { + unreachable!() + } + } + + impl generic_btree::rle::Mergeable for DummyElem { + fn can_merge(&self, _rhs: &Self) -> bool { + false + } + + fn merge_right(&mut self, _rhs: &Self) { + unreachable!() + } + + fn merge_left(&mut self, _left: &Self) { + unreachable!() + } + } + + impl TryInsert for DummyElem { + fn try_insert(&mut self, _pos: usize, elem: Self) -> Result<(), Self> { + Err(elem) + } + } + + impl CanRemove for DummyElem { + fn can_remove(&self) -> bool { + false + } + } + + struct DummyTree; + + impl BTreeTrait for DummyTree { + type Elem = DummyElem; + type Cache = isize; + type CacheDiff = isize; + const USE_DIFF: bool = true; + + fn calc_cache_internal( + cache: &mut Self::Cache, + caches: &[generic_btree::Child<Self>], + ) -> Self::CacheDiff { + let new_cache = caches.iter().map(|child| child.cache).sum::<isize>(); + let diff = new_cache - *cache; + *cache = new_cache; + diff + } + + fn apply_cache_diff(cache: &mut Self::Cache, diff: &Self::CacheDiff) { + *cache += diff; + } + + fn merge_cache_diff(diff1: &mut Self::CacheDiff, diff2: &Self::CacheDiff) { + *diff1 += diff2; + } + + fn get_elem_cache(_elem: &Self::Elem) -> Self::Cache { + 1 + } + + fn new_cache_to_diff(cache: &Self::Cache) -> Self::CacheDiff { + *cache + } + + fn sub_cache(cache_lhs: &Self::Cache, cache_rhs: &Self::Cache) -> Self::CacheDiff { + cache_lhs - cache_rhs + } + } + + impl UseLengthFinder<DummyTree> for DummyTree { + fn get_len(cache: &isize) -> usize { + *cache as usize + } + } + + fn dummy_leaf() -> LeafIndex { + let mut tree = BTree::<DummyTree>::new(); + tree.push(DummyElem).leaf + } + + fn dummy_leaves(n: usize) -> Vec<LeafIndex> { + let mut tree = BTree::<DummyTree>::new(); + (0..n).map(|_| tree.push(DummyElem).leaf).collect() + } + + fn panic_message(payload: Box<dyn Any + Send>) -> String { + if let Some(msg) = payload.downcast_ref::<String>() { + msg.clone() + } else if let Some(msg) = payload.downcast_ref::<&str>() { + msg.to_string() + } else { + "<non-string panic>".to_string() + } + } + + #[test] + fn test_id_to_cursor() { + let _map = IdToCursor::default(); + } + + #[test] + fn zero_len_fragment_panics_with_left_0_right_3() { + let peer = 1; + let mut map = IdToCursor::default(); + map.map.insert( + peer, + vec![ + Fragment { + counter: 0, + cursor: Cursor::Insert(insert_set::InsertSet::Small( + insert_set::SmallInsertSet { + set: smallvec![], + len: 0, + }, + )), + }, + Fragment { + counter: 3, + cursor: Cursor::new_insert(dummy_leaf(), 1), + }, + ], + ); + + let err = std::panic::catch_unwind(AssertUnwindSafe(|| { + map.update_insert(IdSpan::new(peer, 0, 3), dummy_leaf()); + })) + .expect_err("expected zero-length fragment to trip the invariant"); + let msg = panic_message(err); + assert!(msg.contains("left == right"), "{msg}"); + assert!(msg.contains("left: 0"), "{msg}"); + assert!(msg.contains("right: 3"), "{msg}"); + } + + #[test] + fn zero_width_small_update_keeps_insert_set_non_empty() { + let leaf = dummy_leaf(); + let mut set = insert_set::InsertSet::new(leaf, 3); + set.update(0, 0, dummy_leaf()); + + match set { + insert_set::InsertSet::Small(set) => { + assert_eq!(set.len, 3); + assert_eq!(set.set.len(), 1); + assert_eq!(set.set[0].len, 3); + } + insert_set::InsertSet::Large(_) => panic!("expected small insert set"), + } + } + + #[test] + fn large_update_can_replace_the_tail_range() { + let leaves = dummy_leaves(4); + let mut set = insert_set::InsertSet::Small(insert_set::SmallInsertSet { + set: smallvec![ + Insert { + leaf: leaves[0], + len: 100, + }, + Insert { + leaf: leaves[1], + len: 100, + }, + Insert { + leaf: leaves[2], + len: 100, + } + ], + len: 300, + }); + set.update(0, 1, leaves[3]); + let new_leaf = leaves[3]; + set.update_many(&[(200, 300, new_leaf)]); + + assert_ne!(set.get_insert(199), Some(new_leaf)); + for i in 200..300 { + assert_eq!(set.get_insert(i), Some(new_leaf)); + } + } +} diff --git a/vendor/loro-internal/src/container/tree/bool_rle_vec.rs b/vendor/loro-internal/src/container/tree/bool_rle_vec.rs new file mode 100644 index 0000000..c3609d7 --- /dev/null +++ b/vendor/loro-internal/src/container/tree/bool_rle_vec.rs @@ -0,0 +1,442 @@ +// TODO: use boolrle to encode the has_effects array +#![allow(dead_code)] +use std::io::{Read, Write}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct BoolRleVec { + /// For the number of the nth item (0-indexed): + /// - if n is odd, the item is the run length of consecutive `true` values + /// - if n is even, the item is the run length of consecutive `false` values + rle_vec: Vec<u32>, + len: usize, +} + +impl BoolRleVec { + pub fn push(&mut self, value: bool) { + self.len += 1; + if self.rle_vec.is_empty() { + self.rle_vec.push(0); + } + + let last_index = self.rle_vec.len() - 1; + let is_last_run_true = last_index % 2 == 1; + + if (value && is_last_run_true) || (!value && !is_last_run_true) { + // If the new value matches the last run, increment its length + self.rle_vec[last_index] += 1; + } else { + // If the new value doesn't match, start a new run + self.rle_vec.push(1); + } + } + + pub fn pop(&mut self) -> Option<bool> { + while let Some(last) = self.rle_vec.last() { + if *last == 0 { + self.rle_vec.pop(); + } else { + break; + } + } + + if self.rle_vec.is_empty() { + return None; + } + + self.len -= 1; + let last_index = self.rle_vec.len() - 1; + let is_last_run_true = last_index % 2 == 1; + self.rle_vec[last_index] -= 1; + if self.rle_vec[last_index] == 0 { + self.rle_vec.pop(); + } + + Some(is_last_run_true) + } + + pub fn drop_last_n(&mut self, n: usize) { + if n > self.len { + panic!("Attempted to drop more elements than exist in the vector"); + } + + let mut remaining = n; + while remaining > 0 { + if let Some(last) = self.rle_vec.last_mut() { + if *last <= remaining as u32 { + remaining -= *last as usize; + self.rle_vec.pop(); + } else { + *last -= remaining as u32; + remaining = 0; + } + } else { + break; + } + } + + self.len -= n; + + // Remove any trailing zero-length runs + while self.rle_vec.last().is_some_and(|&x| x == 0) { + self.rle_vec.pop(); + } + } + + pub fn merge(&mut self, other: &BoolRleVec) { + if self.is_empty() { + self.rle_vec = other.rle_vec.clone(); + self.len = other.len; + return; + } + + if other.is_empty() { + return; + } + + // Align the end of self with the start of other + let self_last_run_true = self.rle_vec.len().is_multiple_of(2); + if self_last_run_true { + self.rle_vec.extend_from_slice(&other.rle_vec); + } else { + *self.rle_vec.last_mut().unwrap() += other.rle_vec[0]; + self.rle_vec.extend_from_slice(&other.rle_vec[1..]); + } + + self.len += other.len; + } + + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + pub fn iter(&self) -> BoolRleVecIter<'_> { + BoolRleVecIter { + rle_vec: self, + index: 0, + offset: 0, + } + } + + pub fn new() -> Self { + Self { + rle_vec: Default::default(), + len: 0, + } + } + + pub fn encode<W: Write>(&self, writer: &mut W) -> Result<(), std::io::Error> { + leb128::write::unsigned(writer, self.rle_vec.len() as u64)?; + for item in &self.rle_vec { + leb128::write::unsigned(writer, *item as u64)?; + } + + Ok(()) + } + + pub fn decode<R: Read>(reader: &mut R) -> Result<Self, std::io::Error> { + let len = leb128::read::unsigned(reader) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))? + as usize; + let mut rle_vec = Vec::with_capacity(len); + let mut total_len = 0; + for _ in 0..len { + let v = leb128::read::unsigned(reader) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))? + as u32; + rle_vec.push(v); + total_len += v; + } + + Ok(Self { + rle_vec, + len: total_len as usize, + }) + } +} + +pub(crate) struct BoolRleVecIter<'a> { + rle_vec: &'a BoolRleVec, + index: usize, + offset: u32, +} + +impl Iterator for BoolRleVecIter<'_> { + type Item = bool; + + fn next(&mut self) -> Option<Self::Item> { + if self.index >= self.rle_vec.rle_vec.len() { + return None; + } + + let run_length = self.rle_vec.rle_vec[self.index]; + if run_length == 0 { + self.index += 1; + self.offset = 0; + return self.next(); + } + + let value = self.index % 2 == 1; + self.offset += 1; + if self.offset >= run_length { + self.index += 1; + self.offset = 0; + } + + Some(value) + } + + fn nth(&mut self, n: usize) -> Option<Self::Item> { + self.offset += n as u32; + while self.index < self.rle_vec.rle_vec.len() + && self.offset >= self.rle_vec.rle_vec[self.index] + { + self.offset -= self.rle_vec.rle_vec[self.index]; + self.index += 1; + } + + self.next() + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_bool_rle_vec() { + let truth = [true, true, false, false, true, true]; + let mut rle_vec = BoolRleVec::new(); + for t in truth.iter() { + rle_vec.push(*t); + } + + let iter = rle_vec.iter(); + for (a, b) in truth.iter().zip(iter) { + assert_eq!(*a, b); + } + + let mut encoded = Vec::new(); + rle_vec.encode(&mut encoded).unwrap(); + let decoded = BoolRleVec::decode(&mut encoded.as_slice()).unwrap(); + assert_eq!(rle_vec, decoded); + } + + #[test] + fn test_bool_rle_vec_skip() { + let truth = [true, true, false, false, true, true]; + let mut rle_vec = BoolRleVec::new(); + for t in truth.iter() { + rle_vec.push(*t); + } + + let iter = rle_vec.iter(); + for (a, b) in truth.iter().skip(3).zip(iter.skip(3)) { + assert_eq!(*a, b); + } + } + + #[test] + fn test_bool_rle_vec_empty() { + let rle_vec = BoolRleVec::new(); + assert_eq!(rle_vec.len(), 0); + assert!(rle_vec.iter().next().is_none()); + } + + #[test] + fn test_bool_rle_vec_single_element() { + let mut rle_vec = BoolRleVec::new(); + rle_vec.push(true); + assert_eq!(rle_vec.len(), 1); + assert_eq!(rle_vec.iter().next(), Some(true)); + } + + #[test] + fn test_bool_rle_vec_alternating() { + let mut rle_vec = BoolRleVec::new(); + rle_vec.push(true); + rle_vec.push(false); + rle_vec.push(true); + rle_vec.push(false); + assert_eq!(rle_vec.len(), 4); + assert_eq!( + rle_vec.iter().collect::<Vec<_>>(), + vec![true, false, true, false] + ); + } + + #[test] + fn test_bool_rle_vec_long_run() { + let mut rle_vec = BoolRleVec::new(); + for _ in 0..1000 { + rle_vec.push(true); + } + rle_vec.push(false); + assert_eq!(rle_vec.len(), 1001); + assert_eq!(rle_vec.iter().filter(|&x| x).count(), 1000); + assert_eq!(rle_vec.iter().filter(|&x| !x).count(), 1); + } + + #[test] + fn test_bool_rle_vec_nth() { + let mut rle_vec = BoolRleVec::new(); + rle_vec.push(true); + rle_vec.push(true); + rle_vec.push(false); + rle_vec.push(false); + rle_vec.push(true); + let mut iter = rle_vec.iter(); + assert_eq!(iter.nth(2), Some(false)); + assert_eq!(iter.nth(1), Some(true)); + assert_eq!(iter.next(), None); + } + + #[test] + fn test_bool_rle_vec_iter_skip() { + let mut rle_vec = BoolRleVec::new(); + rle_vec.push(true); + rle_vec.push(true); + rle_vec.push(false); + rle_vec.push(false); + rle_vec.push(true); + rle_vec.push(false); + + // Test skipping zero elements + let iter = rle_vec.iter(); + assert_eq!( + iter.collect::<Vec<_>>(), + vec![true, true, false, false, true, false] + ); + + // Test skipping some elements + let iter = rle_vec.iter().skip(2); + assert_eq!(iter.collect::<Vec<_>>(), vec![false, false, true, false]); + + // Test skipping all elements + let mut iter = rle_vec.iter().skip(6); + assert_eq!(iter.next(), None); + + // Test skipping more than available elements + let mut iter = rle_vec.iter().skip(10); + assert_eq!(iter.next(), None); + + // Test skipping with a long run + let mut long_rle_vec = BoolRleVec::new(); + for _ in 0..1000 { + long_rle_vec.push(true); + } + long_rle_vec.push(false); + long_rle_vec.push(true); + + let iter = long_rle_vec.iter().skip(999); + assert_eq!(iter.collect::<Vec<_>>(), vec![true, false, true]); + } + + #[test] + fn test_bool_rle_vec_merge() { + // Test merging two empty vectors + let mut vec1 = BoolRleVec::new(); + let vec2 = BoolRleVec::new(); + vec1.merge(&vec2); + assert!(vec1.is_empty()); + + // Test merging an empty vector with a non-empty one + let mut vec1 = BoolRleVec::new(); + let mut vec2 = BoolRleVec::new(); + vec2.push(true); + vec2.push(false); + vec1.merge(&vec2); + assert_eq!(vec1.iter().collect::<Vec<_>>(), vec![true, false]); + + // Test merging two non-empty vectors + let mut vec1 = BoolRleVec::new(); + let mut vec2 = BoolRleVec::new(); + vec1.push(true); + vec1.push(true); + vec2.push(false); + vec2.push(true); + vec1.merge(&vec2); + assert_eq!( + vec1.iter().collect::<Vec<_>>(), + vec![true, true, false, true] + ); + + // Test merging with alignment (last run of vec1 matches first run of vec2) + let mut vec1 = BoolRleVec::new(); + let mut vec2 = BoolRleVec::new(); + vec1.push(true); + vec1.push(false); + vec2.push(false); + vec2.push(true); + vec1.merge(&vec2); + assert_eq!( + vec1.iter().collect::<Vec<_>>(), + vec![true, false, false, true] + ); + + // Test merging with long runs + let mut vec1 = BoolRleVec::new(); + let mut vec2 = BoolRleVec::new(); + for _ in 0..100 { + vec1.push(true); + } + for _ in 0..100 { + vec2.push(false); + } + vec1.merge(&vec2); + assert_eq!(vec1.len(), 200); + assert_eq!(vec1.rle_vec.len(), 3); + assert_eq!(vec1.iter().take(100).filter(|&x| x).count(), 100); + assert_eq!(vec1.iter().skip(100).filter(|&x| !x).count(), 100); + } + + #[test] + fn test_drop_last_n() { + // Test dropping from a single run + let mut vec = BoolRleVec::new(); + for _ in 0..5 { + vec.push(true); + } + vec.drop_last_n(3); + assert_eq!(vec.iter().collect::<Vec<_>>(), vec![true, true]); + + // Test dropping across multiple runs + let mut vec = BoolRleVec::new(); + vec.push(true); + vec.push(true); + vec.push(false); + vec.push(false); + vec.push(true); + vec.drop_last_n(3); + assert_eq!(vec.iter().collect::<Vec<_>>(), vec![true, true]); + + // Test dropping entire vector + let mut vec = BoolRleVec::new(); + vec.push(true); + vec.push(false); + vec.drop_last_n(2); + assert!(vec.is_empty()); + + // Test dropping from long runs + let mut vec = BoolRleVec::new(); + for _ in 0..100 { + vec.push(true); + } + for _ in 0..100 { + vec.push(false); + } + vec.drop_last_n(150); + assert_eq!(vec.len(), 50); + assert!(vec.iter().all(|x| x)); + + // Test dropping zero elements + let mut vec = BoolRleVec::new(); + vec.push(true); + vec.push(false); + vec.drop_last_n(0); + assert_eq!(vec.iter().collect::<Vec<_>>(), vec![true, false]); + } +} diff --git a/vendor/loro-internal/src/container/tree/mod.rs b/vendor/loro-internal/src/container/tree/mod.rs new file mode 100644 index 0000000..d9f97a1 --- /dev/null +++ b/vendor/loro-internal/src/container/tree/mod.rs @@ -0,0 +1,3 @@ +pub(crate) mod bool_rle_vec; +pub(crate) mod tree_ds; +pub(crate) mod tree_op; diff --git a/vendor/loro-internal/src/container/tree/tree_ds.rs b/vendor/loro-internal/src/container/tree/tree_ds.rs new file mode 100644 index 0000000..0191299 --- /dev/null +++ b/vendor/loro-internal/src/container/tree/tree_ds.rs @@ -0,0 +1,115 @@ +#![allow(unused)] + +use loro_common::{IdFull, IdLp, TreeID}; +use rustc_hash::FxHashMap; + +use crate::VersionVector; + +use super::bool_rle_vec::BoolRleVec; + +pub(crate) struct TreeLinearHistory { + ops: Vec<TreeOpWrap>, + has_effect: BoolRleVec, + target_to_op_idx: FxHashMap<TreeID, usize>, +} + +struct TreeOpWrap { + op: TreeOp, + last_effective_update_on_target: Option<usize>, +} + +pub(crate) struct TreeOp { + pub id: IdFull, + pub target: TreeID, +} + +pub(crate) struct PoppedTreeOp { + pub op: TreeOp, + pub has_effect: bool, + pub last_update_on_target: Option<IdFull>, +} + +impl TreeLinearHistory { + pub fn new() -> Self { + Self { + ops: Vec::new(), + has_effect: BoolRleVec::new(), + target_to_op_idx: FxHashMap::default(), + } + } + + pub fn from_vec(ops: Vec<TreeOp>, has_effect: BoolRleVec) -> Self { + let mut this = Self::new(); + for (op, e) in ops.into_iter().zip(has_effect.iter()) { + this.push(op, e); + } + + this + } + + pub fn push(&mut self, op: TreeOp, has_effect: bool) { + if has_effect { + let last = self.target_to_op_idx.insert(op.target, self.ops.len()); + self.ops.push(TreeOpWrap { + op, + last_effective_update_on_target: last, + }); + } else { + self.ops.push(TreeOpWrap { + op, + last_effective_update_on_target: None, + }); + } + + self.has_effect.push(has_effect); + } + + pub fn pop_util(&mut self, threshold: IdLp) -> Vec<PoppedTreeOp> { + let index = match self + .ops + .binary_search_by(|op_wrap| op_wrap.op.id.idlp().cmp(&threshold)) + { + Ok(index) => index, + Err(index) => index, + }; + + self._pop_util(index) + } + + // Some of them need to be pushed back later if they are inside the vv + #[must_use] + pub fn pop_until_all_inside_vv(&mut self, vv: &VersionVector) -> Vec<PoppedTreeOp> { + for (i, op_wrap) in self.ops.iter().enumerate() { + if vv.get(&op_wrap.op.id.peer).unwrap() <= &op_wrap.op.id.counter { + return self._pop_util(i); + } + } + + vec![] + } + + fn _pop_util(&mut self, index: usize) -> Vec<PoppedTreeOp> { + todo!() + } + + pub fn last_update_on(&self, target: TreeID) -> Option<IdFull> { + self.target_to_op_idx + .get(&target) + .and_then(|&idx| self.ops.get(idx)) + .map(|op_wrap| op_wrap.op.id) + } + + pub fn greatest_idlp(&self) -> Option<IdLp> { + self.ops.last().map(|op| op.op.id.idlp()) + } + + #[inline] + pub fn len(&self) -> usize { + self.ops.len() + } + + #[inline] + pub fn get_bool_rle_vec(&self) -> &BoolRleVec { + &self.has_effect + } +} diff --git a/vendor/loro-internal/src/container/tree/tree_op.rs b/vendor/loro-internal/src/container/tree/tree_op.rs new file mode 100644 index 0000000..5f7fe3c --- /dev/null +++ b/vendor/loro-internal/src/container/tree/tree_op.rs @@ -0,0 +1,75 @@ +use fractional_index::FractionalIndex; +use loro_common::TreeID; +use rle::{HasLength, Mergable}; +use serde::{Deserialize, Serialize}; + +use crate::state::TreeParentId; + +/// The operation of movable tree. +/// +/// In the movable tree, there are three actions: +/// - **Create**: target tree id will be generated by [`Transaction`], and parent tree id is `None`. +/// - **Move**: move target tree node a child node of the specified parent node. +/// - **Delete**: move target tree node to [`loro_common::DELETED_TREE_ROOT`]. +/// +/// +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub enum TreeOp { + Create { + target: TreeID, + parent: Option<TreeID>, + position: FractionalIndex, + }, + Move { + target: TreeID, + parent: Option<TreeID>, + position: FractionalIndex, + }, + Delete { + target: TreeID, + }, +} + +impl TreeOp { + pub(crate) fn target(&self) -> TreeID { + match self { + TreeOp::Create { target, .. } => *target, + TreeOp::Move { target, .. } => *target, + TreeOp::Delete { target, .. } => *target, + } + } + + #[allow(unused)] + pub(crate) fn parent(&self) -> Option<TreeID> { + match self { + TreeOp::Create { parent, .. } => *parent, + TreeOp::Move { parent, .. } => *parent, + TreeOp::Delete { .. } => Some(TreeID::delete_root()), + } + } + + pub(crate) fn parent_id(&self) -> TreeParentId { + match self { + TreeOp::Create { parent, .. } => TreeParentId::from(*parent), + TreeOp::Move { parent, .. } => TreeParentId::from(*parent), + TreeOp::Delete { .. } => TreeParentId::Deleted, + } + } + + pub(crate) fn fractional_index(&self) -> Option<FractionalIndex> { + match self { + TreeOp::Create { position, .. } | TreeOp::Move { position, .. } => { + Some(position.clone()) + } + TreeOp::Delete { .. } => None, + } + } +} + +impl HasLength for TreeOp { + fn content_len(&self) -> usize { + 1 + } +} + +impl Mergable for TreeOp {} diff --git a/vendor/loro-internal/src/cursor.rs b/vendor/loro-internal/src/cursor.rs new file mode 100644 index 0000000..709037d --- /dev/null +++ b/vendor/loro-internal/src/cursor.rs @@ -0,0 +1,111 @@ +use loro_common::{ContainerID, ID}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct Cursor { + // It's option because it's possible that the given container is empty. + pub id: Option<ID>, + pub container: ContainerID, + /// The target position is at the left, middle, or right of the given id. + /// + /// Side info can help to model the selection + pub side: Side, + /// The position of the cursor in the container when the cursor is created. + /// For text, this is the unicode codepoint index + /// This value is not encoded + pub(crate) origin_pos: usize, +} + +#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Side { + Left = -1, + #[default] + Middle = 0, + Right = 1, +} + +impl Side { + pub fn from_i32(i: i32) -> Option<Self> { + match i { + -1 => Some(Side::Left), + 0 => Some(Side::Middle), + 1 => Some(Side::Right), + _ => None, + } + } + + pub fn to_i32(&self) -> i32 { + *self as i32 + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PosQueryResult { + pub update: Option<Cursor>, + pub current: AbsolutePosition, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AbsolutePosition { + pub pos: usize, + /// The target position is at the left, middle, or right of the given pos. + pub side: Side, +} + +/// Why a cursor could not be resolved to an absolute position. +/// +/// Non-exhaustive: `HistoryUnreadable` means the lookup had to read history +/// that cannot be parsed. It is not the same as a missing id. Downstream +/// matches need a wildcard arm. +#[derive(Debug, Clone, Copy, thiserror::Error)] +#[non_exhaustive] +pub enum CannotFindRelativePosition { + #[error("Cannot find relative position. The container is deleted.")] + ContainerDeleted, + #[error("Cannot find relative position. It may be that the given id is deleted and the relative history is cleared.")] + HistoryCleared, + #[error("Cannot find relative position. The id is not found.")] + IdNotFound, + /// The lookup needed a change block that cannot be parsed. + #[error("Cannot find relative position because the document history cannot be read.")] + HistoryUnreadable, +} + +impl Cursor { + pub fn new(id: Option<ID>, container: ContainerID, side: Side, origin_pos: usize) -> Self { + Self { + id, + container, + side, + origin_pos, + } + } + + pub fn encode(&self) -> Vec<u8> { + postcard::to_allocvec(self).unwrap() + } + + /// Decode a cursor, rejecting negative position counters as invalid encoding. + pub fn decode(data: &[u8]) -> Result<Self, postcard::Error> { + let cursor: Self = postcard::from_bytes(data)?; + if cursor.id.is_some_and(|id| id.counter < 0) { + return Err(postcard::Error::DeserializeBadEncoding); + } + Ok(cursor) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PosType { + /// The index is based on the length of the text in bytes(UTF-8). + Bytes, + /// The index is based on the length of the text in Unicode Code Points. + Unicode, + /// The index is based on the length of the text in UTF-16 code units. + Utf16, + /// The index is based on the length of the text in events. + /// It is determined by the `wasm` feature. + Event, + /// The index is based on the entity index. + Entity, +} diff --git a/vendor/loro-internal/src/dag.rs b/vendor/loro-internal/src/dag.rs new file mode 100644 index 0000000..ff19449 --- /dev/null +++ b/vendor/loro-internal/src/dag.rs @@ -0,0 +1,2024 @@ +//! DAG (Directed Acyclic Graph) is a common data structure in distributed system. +//! +//! This mod contains the DAGs in our CRDT. It's not a general DAG, it has some specific properties that +//! we used to optimize the speed: +//! - Each node has lamport clock. +//! - Each node has its ID (client_id, counter). +//! - We use ID to refer to node rather than content addressing (hash) +//! +use std::{ + borrow::Cow, + collections::{BinaryHeap, HashMap}, + fmt::Debug, +}; + +use loro_common::{IdSpanVector, LoroError, LoroResult}; +use rle::{HasLength, Sliceable}; +use rustc_hash::{FxHashMap, FxHashSet}; +mod iter; +pub(crate) use iter::DagCausalIter; +mod mermaid; +#[cfg(feature = "test_utils")] +mod test; +#[cfg(feature = "test_utils")] +pub use test::{fuzz_alloc_tree, Interaction}; + +use crate::{ + change::Lamport, + diff_calc::DiffMode, + id::{Counter, PeerID, ID}, + span::{CounterSpan, HasId, HasIdSpan, HasLamport, HasLamportSpan, IdSpan}, + version::{Frontiers, VersionVector, VersionVectorDiff}, +}; + +use self::{ + iter::{iter_dag, iter_dag_with_vv, DagIterator, DagIteratorVV}, + mermaid::dag_to_mermaid, +}; + +pub(crate) trait DagNode: HasLamport + HasId + HasLength + Debug + Sliceable { + fn deps(&self) -> &Frontiers; + + #[allow(unused)] + #[inline] + fn get_lamport_from_counter(&self, c: Counter) -> Lamport { + self.lamport() + c as Lamport - self.id_start().counter as Lamport + } +} + +/// Dag (Directed Acyclic Graph). +/// +/// We have following invariance in DAG +/// - All deps' lamports are smaller than current node's lamport +pub(crate) trait Dag: Debug { + type Node: DagNode; + + fn get(&self, id: ID) -> Option<Self::Node>; + fn try_get(&self, id: ID) -> LoroResult<Option<Self::Node>> { + Ok(self.get(id)) + } + #[allow(unused)] + fn frontier(&self) -> &Frontiers; + fn vv(&self) -> &VersionVector; + fn contains(&self, id: ID) -> bool; +} + +/// Whether the meet of two versions can serve as the replay base between them. +#[derive(Debug)] +pub(crate) enum MeetAsBase { + /// The meet is a valid replay base for the returned diff mode. That makes + /// it a critical version only in non-`Checkout` modes (spec S3). In + /// `Checkout` mode it is just the meet, and ops above it may be concurrent + /// with one of its heads; checkout consumers accept that (spec Q7). + Valid(Frontiers), + /// A concurrent branch crosses the meet, so replaying from it would + /// leave concurrency unadjudicated. The caller must retreat to a critical + /// version below it (see `docs/critical-version-spec.md`). + NeedsCriticalRetreat, +} + +pub(crate) trait DagUtils: Dag { + /// The replay base for diffing `a_id` into `b_id`: the meet when it is a + /// valid base for the diff mode, else the latest single-head critical + /// version. + /// + /// This is NOT always a critical version: in `DiffMode::Checkout` it may be + /// a meet with concurrent ops above it (see [`MeetAsBase::Valid`]). Callers + /// that need every other op to be before or after the result, such as the + /// shallow snapshot root, must use + /// [`Self::latest_single_head_critical_version`] (loro-dev/loro#1095). + /// + /// Only the DAG tests call it: the tree calculator used to, and now takes its + /// window from the two versions (`context/tree-checkout-window.md`). + #[cfg(test)] + fn find_replay_base(&self, a_id: &Frontiers, b_id: &Frontiers) -> (Frontiers, DiffMode); + /// Like `find_replay_base`, but leaves the conservative + /// fallback to the caller: on [`MeetAsBase::NeedsCriticalRetreat`] the + /// caller must retreat to a critical version (via + /// [`Self::latest_single_head_critical_version`], or a cheaper multi-head + /// one it can find itself). Finding the single-head cut walks the whole + /// DAG, so callers that usually have a better answer should not pay for + /// it up front. + #[cfg(test)] + fn find_meet_and_mode(&self, a_id: &Frontiers, b_id: &Frontiers) -> (MeetAsBase, DiffMode) { + self.try_find_meet_and_mode(a_id, b_id).unwrap() + } + fn try_find_meet_and_mode( + &self, + a_id: &Frontiers, + b_id: &Frontiers, + ) -> LoroResult<(MeetAsBase, DiffMode)>; + #[cfg(test)] + fn latest_single_head_critical_version(&self, a_id: &Frontiers, b_id: &Frontiers) -> Frontiers { + self.try_latest_single_head_critical_version(a_id, b_id) + .unwrap() + } + fn try_latest_single_head_critical_version( + &self, + a_id: &Frontiers, + b_id: &Frontiers, + ) -> LoroResult<Frontiers>; + /// Slow, should probably only use on dev + #[allow(unused)] + fn get_vv(&self, id: ID) -> VersionVector; + #[allow(unused)] + fn find_path(&self, from: &Frontiers, to: &Frontiers) -> VersionVectorDiff { + self.try_find_path(from, to).unwrap() + } + fn try_find_path(&self, from: &Frontiers, to: &Frontiers) -> LoroResult<VersionVectorDiff>; + #[cfg(test)] + fn iter_causal(&self, from: Frontiers, target: IdSpanVector) -> DagCausalIter<'_, Self> + where + Self: Sized; + #[allow(unused)] + fn iter(&self) -> DagIterator<'_, Self::Node> + where + Self: Sized; + #[allow(unused)] + fn iter_with_vv(&self) -> DagIteratorVV<'_, Self::Node> + where + Self: Sized; + #[allow(unused)] + fn mermaid(&self) -> String + where + Self: Sized; +} + +impl<T: Dag + ?Sized> DagUtils for T { + #[cfg(test)] + #[inline] + fn find_replay_base(&self, a_id: &Frontiers, b_id: &Frontiers) -> (Frontiers, DiffMode) { + // TODO: perf: make it also return the spans to reach the replay base + let (meet, mode) = self.find_meet_and_mode(a_id, b_id); + let base = match meet { + MeetAsBase::Valid(meet) => meet, + MeetAsBase::NeedsCriticalRetreat => { + self.latest_single_head_critical_version(a_id, b_id) + } + }; + (base, mode) + } + + #[inline] + fn try_find_meet_and_mode( + &self, + a_id: &Frontiers, + b_id: &Frontiers, + ) -> LoroResult<(MeetAsBase, DiffMode)> { + find_meet_and_mode(&|id| self.try_get(id), a_id, b_id) + } + + #[inline] + fn try_latest_single_head_critical_version( + &self, + a_id: &Frontiers, + b_id: &Frontiers, + ) -> LoroResult<Frontiers> { + latest_single_head_critical_version(&|id| self.try_get(id), a_id, b_id) + } + + #[inline] + fn get_vv(&self, id: ID) -> VersionVector { + get_version_vector(&|id| self.get(id), id) + } + + fn try_find_path(&self, from: &Frontiers, to: &Frontiers) -> LoroResult<VersionVectorDiff> { + let mut ans = VersionVectorDiff::default(); + if from == to { + return Ok(ans); + } + + if from.len() == 1 && to.len() == 1 { + let from = from.as_single().unwrap(); + let to = to.as_single().unwrap(); + if from.peer == to.peer { + let from_span = self + .try_get(from)? + .ok_or(LoroError::FrontiersNotFound(from))?; + let to_span = self.try_get(to)?.ok_or(LoroError::FrontiersNotFound(to))?; + if from_span.id_start() == to_span.id_start() { + if from.counter < to.counter { + ans.forward.insert( + from.peer, + CounterSpan::new(from.counter + 1, to.counter + 1), + ); + } else { + ans.retreat.insert( + from.peer, + CounterSpan::new(to.counter + 1, from.counter + 1), + ); + } + return Ok(ans); + } + + if from_span.deps().len() == 1 + && to_span.contains_id(from_span.deps().as_single().unwrap()) + { + ans.retreat.insert( + from.peer, + CounterSpan::new(to.counter + 1, from.counter + 1), + ); + return Ok(ans); + } + + if to_span.deps().len() == 1 + && from_span.contains_id(to_span.deps().as_single().unwrap()) + { + ans.forward.insert( + from.peer, + CounterSpan::new(from.counter + 1, to.counter + 1), + ); + return Ok(ans); + } + } + } + + _walk_to_meet( + &|v| self.try_get(v), + from, + to, + &mut |span, node_type| match node_type { + NodeType::A => ans.merge_left(span), + NodeType::B => ans.merge_right(span), + NodeType::Shared => { + ans.subtract_start_left(span); + ans.subtract_start_right(span); + } + }, + true, + )?; + + Ok(ans) + } + + #[inline(always)] + fn iter_with_vv(&self) -> DagIteratorVV<'_, Self::Node> + where + Self: Sized, + { + iter_dag_with_vv(self) + } + + #[inline(always)] + #[cfg(test)] + fn iter_causal(&self, from: Frontiers, target: IdSpanVector) -> DagCausalIter<'_, Self> + where + Self: Sized, + { + DagCausalIter::new(self, from, target) + } + + #[inline(always)] + fn iter(&self) -> DagIterator<'_, Self::Node> + where + Self: Sized, + { + iter_dag(self) + } + + /// You can visualize and generate img link at https://mermaid.live/ + #[inline] + fn mermaid(&self) -> String + where + Self: Sized, + { + dag_to_mermaid(self) + } +} + +#[allow(dead_code)] +fn get_version_vector<'a, Get, D>(get: &'a Get, id: ID) -> VersionVector +where + Get: Fn(ID) -> Option<D>, + D: DagNode + 'a, +{ + let mut vv = VersionVector::new(); + let mut visited: FxHashSet<ID> = FxHashSet::default(); + vv.insert(id.peer, id.counter + 1); + let node = get(id).unwrap(); + + if node.deps().is_empty() { + return vv; + } + + let mut stack = Vec::with_capacity(node.deps().len()); + for dep in node.deps().iter() { + stack.push(dep); + } + + while let Some(node_id) = stack.pop() { + let node = get(node_id).unwrap(); + let node_id_start = node.id_start(); + vv.try_update_last(node_id); + if !visited.contains(&node_id_start) { + for dep in node.deps().iter() { + if !visited.contains(&dep) { + stack.push(dep); + } + } + + visited.insert(node_id_start); + } + } + + vv +} + +#[derive(Debug, PartialEq, Eq)] +struct OrdIdSpan<'a> { + id: ID, + lamport: Lamport, + len: usize, + deps: Cow<'a, Frontiers>, +} + +impl HasLength for OrdIdSpan<'_> { + fn content_len(&self) -> usize { + self.len + } +} + +impl HasId for OrdIdSpan<'_> { + fn id_start(&self) -> ID { + self.id + } +} + +impl HasLamport for OrdIdSpan<'_> { + fn lamport(&self) -> Lamport { + self.lamport + } +} + +impl PartialOrd for OrdIdSpan<'_> { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for OrdIdSpan<'_> { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.lamport_last() + .cmp(&other.lamport_last()) + .then(self.id.peer.cmp(&other.id.peer)) + // If they have the same last id, we want the shorter one to be greater; + // Otherwise, find_replay_base won't work correctly. Because we may + // lazily load the dag node, so sometimes the longer one should be broken + // into smaller pieces but it's already pushed to the queue. + .then(other.len.cmp(&self.len)) + } +} + +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] +enum NodeType { + A, + B, + Shared, +} + +impl<'a> OrdIdSpan<'a> { + #[inline] + fn from_dag_node<D, F>(id: ID, get: &'a F) -> LoroResult<Option<OrdIdSpan<'a>>> + where + D: DagNode + 'a, + F: Fn(ID) -> LoroResult<Option<D>>, + { + let Some(span) = get(id)? else { + return Ok(None); + }; + let span_id = span.id_start(); + Ok(Some(OrdIdSpan { + id: span_id, + lamport: span.lamport(), + deps: Cow::Owned(span.deps().clone()), + len: (id.counter - span_id.counter) as usize + 1, + })) + } + + #[inline] + fn get_min(&self) -> OrdIdSpan<'a> { + OrdIdSpan { + id: self.id, + lamport: self.lamport, + deps: Cow::Owned(Default::default()), + len: 1, + } + } +} + +#[inline(always)] +fn find_meet_and_mode<'a, F, D>( + get: &'a F, + a_id: &Frontiers, + b_id: &Frontiers, +) -> LoroResult<(MeetAsBase, DiffMode)> +where + D: DagNode + 'a, + F: Fn(ID) -> LoroResult<Option<D>>, +{ + if b_id.is_empty() { + return Ok((MeetAsBase::Valid(Default::default()), DiffMode::Checkout)); + } + + _find_meet_and_mode(get, a_id, b_id) +} + +/// - deep whether keep searching until the min of non-shared node is found +fn _walk_to_meet<'a, F, D, G>( + get: &'a F, + a_ids: &Frontiers, + b_ids: &Frontiers, + notify: &mut G, + find_path: bool, +) -> LoroResult<FxHashMap<PeerID, Counter>> +where + D: DagNode + 'a, + F: Fn(ID) -> LoroResult<Option<D>>, + G: FnMut(IdSpan, NodeType), +{ + let mut ans: FxHashMap<PeerID, Counter> = Default::default(); + let mut queue: BinaryHeap<(OrdIdSpan, NodeType)> = BinaryHeap::new(); + for id in a_ids.iter() { + queue.push((OrdIdSpan::from_dag_node(id, get)?.unwrap(), NodeType::A)); + } + for id in b_ids.iter() { + queue.push((OrdIdSpan::from_dag_node(id, get)?.unwrap(), NodeType::B)); + } + let mut visited: HashMap<PeerID, (Counter, NodeType), _> = FxHashMap::default(); + // invariants in this method: + // + // - visited's (client, counters) are subset of max(version_vector_a, version_vector_b) + // - visited's node type reflecting whether we found the shared node of this client + // - ans's client id never repeat + // - nodes with the same id will only be visited once + // - we may visit nodes that are before the meet + + // type count in the queue. if both are zero, we can stop + let mut a_count = a_ids.len(); + let mut b_count = b_ids.len(); + let mut min = None; + while let Some((node, mut node_type)) = queue.pop() { + match node_type { + NodeType::A => a_count -= 1, + NodeType::B => b_count -= 1, + NodeType::Shared => {} + } + + if node_type != NodeType::Shared { + if let Some(min) = &mut min { + let node_start = node.get_min(); + if node_start < *min { + *min = node_start; + } + } else { + min = Some(node.get_min()) + } + } + + // pop the same node in the queue + while let Some((other_node, other_type)) = queue.peek() { + if node.id_span() == other_node.id_span() { + if node_type == *other_type { + match node_type { + NodeType::A => a_count -= 1, + NodeType::B => b_count -= 1, + NodeType::Shared => {} + } + } else { + if node_type != NodeType::Shared { + if visited.get(&node.id.peer).map(|(_, t)| *t) != Some(NodeType::Shared) { + ans.insert(node.id.peer, other_node.id_last().counter); + } + node_type = NodeType::Shared; + } + match other_type { + NodeType::A => a_count -= 1, + NodeType::B => b_count -= 1, + NodeType::Shared => {} + } + } + + queue.pop(); + } else { + break; + } + } + + // detect whether client is visited by other + if let Some((ctr, visited_type)) = visited.get_mut(&node.id.peer) { + debug_assert!(*ctr >= node.id_last().counter); + if *visited_type == NodeType::Shared { + node_type = NodeType::Shared; + } else if *visited_type != node_type { + // if node_type is shared, ans should already contains it or its descendance + if node_type != NodeType::Shared { + ans.insert(node.id.peer, node.id_last().counter); + } + *visited_type = NodeType::Shared; + node_type = NodeType::Shared; + } + } else { + visited.insert(node.id.peer, (node.id_last().counter, node_type)); + } + + // if this is not shared, the end of the span must be only reachable from A, or only reachable from B. + // but the begin of the span may be reachable from both A and B + notify(node.id_span(), node_type); + + match node_type { + NodeType::A => a_count += node.deps.len(), + NodeType::B => b_count += node.deps.len(), + NodeType::Shared => {} + } + + if a_count == 0 && b_count == 0 && (min.is_none() || &node <= min.as_ref().unwrap()) { + if node_type != NodeType::Shared { + ans.clear(); + } + + break; + } + + for dep_id in node.deps.as_ref().iter() { + queue.push((OrdIdSpan::from_dag_node(dep_id, get)?.unwrap(), node_type)); + } + + if node_type != NodeType::Shared { + if queue.is_empty() { + ans.clear(); + break; + } + if node.deps.is_empty() && !find_path { + if node.len == 1 { + ans.clear(); + break; + } + + match node_type { + NodeType::A => a_count += 1, + NodeType::B => b_count += 1, + NodeType::Shared => {} + } + + queue.push(( + OrdIdSpan { + deps: Cow::Owned(Default::default()), + id: node.id, + len: 1, + lamport: node.lamport, + }, + node_type, + )); + } + } + } + + Ok(ans) +} + +/// Resolves each frontier id to the span of its containing node, truncated at +/// that id. Returns `None` when an id is unavailable (trimmed history). +fn ids_to_ord_id_spans<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( + ids: &Frontiers, + get: &'a F, +) -> LoroResult<Option<Vec<OrdIdSpan<'a>>>> { + let mut ans = Vec::with_capacity(ids.len()); + for id in ids.iter() { + if let Some(node) = OrdIdSpan::from_dag_node(id, get)? { + ans.push(node); + } else { + return Ok(None); + } + } + + Ok(Some(ans)) +} + +/// The parent set of a span's first op: the node's explicit deps plus the +/// implicit same-peer predecessor when it is not already covered by one of them. +fn deps_to_ord_id_spans<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( + node: &OrdIdSpan<'a>, + get: &'a F, +) -> LoroResult<Option<Vec<OrdIdSpan<'a>>>> { + let Some(mut deps) = ids_to_ord_id_spans(node.deps.as_ref(), get)? else { + return Ok(None); + }; + if node.id.counter > 0 { + let prev = node.id.inc(-1); + if let Some(prev) = OrdIdSpan::from_dag_node(prev, get)? { + if !deps.iter().any(|dep| dep.contains_id(prev.id_last())) { + deps.push(prev); + } + } + } + + Ok(Some(deps)) +} + +/// The latest single-head critical version (Eg-walker §3.5/§3.6) of the +/// union graph `ancestry(left) ∪ ancestry(right)`: the newest event `v` +/// such that every other event in the union is an ancestor of `v` or +/// causally after `v`. Replaying from `{v}` is safe because no concurrency +/// crosses it, and it skips the fully-synced prefix of common history that +/// the old `∅` fallback would replay. +/// +/// Method: a one-colour descent from both frontiers using the same +/// coalesce/align machinery as the main walk. The pending heap is always a +/// cut of the unexplored region, so the first moment it narrows to a +/// single span, that span's `id_last` is the latest such `v`. If a chain +/// dies at a root or at trimmed history while other chains remain, its +/// endpoint is concurrent with everything below the current level, so no +/// later singleton can be valid — bail out to the empty version, which is +/// the old behaviour. +fn latest_single_head_critical_version<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( + get: &'a F, + left: &Frontiers, + right: &Frontiers, +) -> LoroResult<Frontiers> { + let mut queue: BinaryHeap<OrdIdSpan> = BinaryHeap::new(); + let Some(spans) = ids_to_ord_id_spans(left, get)? else { + return Ok(Default::default()); + }; + queue.extend(spans); + let Some(spans) = ids_to_ord_id_spans(right, get)? else { + return Ok(Default::default()); + }; + queue.extend(spans); + + while let Some(mut node) = queue.pop() { + while let Some(other) = queue.peek() { + if node == *other || node.id_last() == other.id_last() { + queue.pop(); + } else { + break; + } + } + + if queue.is_empty() { + return Ok(node.id_last().into()); + } + + if let Some(other) = queue.peek() { + if node.contains_id(other.id_last()) { + node.len = (other.id_last().counter - node.id.counter + 1) as usize; + queue.push(node); + continue; + } + + if node.len > 1 { + node.len = if other.lamport_last() >= node.lamport { + (other.lamport_last() - node.lamport + 1).min(node.len as u32 - 1) as usize + } else { + 1 + }; + queue.push(node); + continue; + } + } + + match deps_to_ord_id_spans(&node, get)? { + Some(deps) if !deps.is_empty() => { + for dep in deps { + queue.push(dep); + } + } + _ => return Ok(Default::default()), + } + } + + Ok(Default::default()) +} + +/// Finds the replay base and diff mode for the transition `left -> right`. +/// +/// Contract (see `docs/critical-version-spec.md` for definitions and proofs): +/// - S1: every id in the returned frontier is in the causal past of both sides; +/// - S2: the returned frontier is an antichain; +/// - S3: a non-`Checkout` mode additionally guarantees that the base equals +/// `left` and that EVERY newly imported event is causally after every head +/// of `left` (i.e. `left` is a critical version of the union graph in the +/// Eg-walker sense, arXiv:2409.14252 §3.5) — enforced for multi-head `left` +/// by `new_region_after_all_left_heads`; +/// - when a genuinely concurrent branch invalidates the candidate base, the +/// base retreats to the latest single-head critical version +/// (`latest_single_head_critical_version`), or to the empty version when no +/// such cut exists. +/// +/// Downstream consumers rely on these guarantees to skip CRDT adjudication +/// (tree/map fast paths) and to bound their replay windows (tree checkout); +/// see the comment in `diff_calc/tree.rs::checkout_diff`. +fn _find_meet_and_mode<'a, F, D>( + get: &'a F, + left: &Frontiers, + right: &Frontiers, +) -> LoroResult<(MeetAsBase, DiffMode)> +where + D: DagNode + 'a, + F: Fn(ID) -> LoroResult<Option<D>>, +{ + if right.is_empty() { + return Ok((MeetAsBase::Valid(Default::default()), DiffMode::Checkout)); + } + + if left.is_empty() { + if right.len() == 1 { + let mut node_id = right.as_single().unwrap(); + let mut node = get(node_id)?.unwrap(); + while node.deps().len() == 1 { + node_id = node.deps().as_single().unwrap(); + let Some(next) = get(node_id)? else { + return Ok(( + MeetAsBase::Valid(Default::default()), + DiffMode::ImportGreaterUpdates, + )); + }; + node = next; + } + + if node.deps().is_empty() { + return Ok((MeetAsBase::Valid(Default::default()), DiffMode::Linear)); + } + } + + return Ok(( + MeetAsBase::Valid(Default::default()), + DiffMode::ImportGreaterUpdates, + )); + } + + if left.len() == 1 && right.len() == 1 { + let left = left.as_single().unwrap(); + let right = right.as_single().unwrap(); + if left.peer == right.peer { + let left_span = get(left)?.unwrap(); + let right_span = get(right)?.unwrap(); + if left_span.id_start() == right_span.id_start() { + if left.counter < right.counter { + return Ok((MeetAsBase::Valid(left.into()), DiffMode::Linear)); + } else { + return Ok((MeetAsBase::Valid(right.into()), DiffMode::Checkout)); + } + } + + if left_span.deps().len() == 1 + && right_span.contains_id(left_span.deps().as_single().unwrap()) + { + return Ok((MeetAsBase::Valid(right.into()), DiffMode::Checkout)); + } + + if right_span.deps().len() == 1 + && left_span.contains_id(right_span.deps().as_single().unwrap()) + { + return Ok((MeetAsBase::Valid(left.into()), DiffMode::Linear)); + } + } + } + + let mut is_linear = left.len() <= 1 && right.len() == 1; + let mut is_right_greater = true; + let mut unmatched_branches = FxHashSet::default(); + let mut has_unresolved_unmatched_branch = false; + let mut ans: Frontiers = Default::default(); + + fn shrink_ancestor_frontiers<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( + ids: &Frontiers, + get: &'a F, + ) -> LoroResult<Frontiers> { + if ids.len() <= 1 { + return Ok(ids.clone()); + } + + let mut ids = ids_to_ord_id_spans(ids, get)?.expect("meet candidates should be in dag"); + ids.sort_unstable(); + let mut frontiers = Vec::with_capacity(ids.len()); + for id in ids.iter().rev() { + let mut should_insert = true; + for frontier in frontiers.iter().rev() { + if contains_in_ancestors(get, *frontier, id)? { + should_insert = false; + break; + } + } + + if should_insert { + frontiers.push(id.id_last()); + } + } + + Ok(frontiers.into_iter().collect()) + } + + fn has_trimmed_history_deps<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( + ids: &Frontiers, + get: &'a F, + ) -> LoroResult<bool> { + for id in ids.iter() { + let Some(node) = OrdIdSpan::from_dag_node(id, get)? else { + return Ok(true); + }; + if ids_to_ord_id_spans(node.deps.as_ref(), get)?.is_none() { + return Ok(true); + } + } + Ok(false) + } + + /// Whether every tip in `tips` is contained in the ancestors of `frontiers` + /// (the tip itself counts). One walk answers all tips: it starts from every + /// frontier with a shared visited set and prunes by the lowest lamport among + /// the still-unproven tips, so the ancestor region is traversed at most once + /// per call instead of once per (tip, frontier) pair. + fn all_tips_covered_by_ancestors<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( + get: &'a F, + frontiers: &Frontiers, + tips: &FxHashSet<ID>, + ) -> LoroResult<bool> { + let mut remaining = Vec::with_capacity(tips.len()); + for id in tips.iter() { + let Some(span) = OrdIdSpan::from_dag_node(*id, get)? else { + return Ok(false); + }; + remaining.push(span); + } + + if remaining.is_empty() { + return Ok(true); + } + + let mut min_lamport = remaining + .iter() + .map(|tip| tip.lamport_last()) + .min() + .unwrap(); + let mut visited = FxHashSet::default(); + let mut pending = Vec::new(); + for frontier in frontiers.iter() { + if let Some(node) = OrdIdSpan::from_dag_node(frontier, get)? { + pending.push(node); + } + } + + while let Some(node) = pending.pop() { + let len_before = remaining.len(); + remaining.retain(|tip| !node.contains_id(tip.id_last())); + if remaining.is_empty() { + return Ok(true); + } + + if remaining.len() != len_before { + min_lamport = remaining + .iter() + .map(|tip| tip.lamport_last()) + .min() + .unwrap(); + } + + // Ancestors of `node` all have lamport strictly below the node's + // start, so nothing below `min_lamport` can contain a remaining tip. + if node.lamport_last() < min_lamport { + continue; + } + + if !visited.insert(node.id_start()) { + continue; + } + + if let Some(deps) = deps_to_ord_id_spans(&node, get)? { + for dep in deps { + pending.push(dep); + } + } + } + + Ok(false) + } + + /// Verifies the `ImportGreaterUpdates` contract for a multi-head `left`: + /// every event in `Events(right) − Events(left)` must be causally after + /// every member of `left` (i.e. `left` must be a critical version of the + /// union graph). The main walk only proves version inclusion, which is + /// weaker: a new branch can enter old history through one left head while + /// staying concurrent with another, and the tree calculator's fast path + /// applies such updates without adjudication (see + /// `docs/critical-version-spec.md` §4.1). + /// + /// Method: descend from `right` over new changes only. A change whose + /// causal parents (explicit deps plus the implicit same-peer predecessor) + /// are all old is an entry point of the new region; its parents must + /// causally cover every left head. Non-entry changes inherit coverage + /// through their new parents. The common healthy shape — a change whose + /// deps equal the left frontier — passes with a set comparison and no + /// graph walk. Trimmed history fails conservatively. + fn new_region_after_all_left_heads<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( + get: &'a F, + left: &Frontiers, + right: &Frontiers, + ) -> LoroResult<bool> { + let left_ids: FxHashSet<ID> = left.iter().collect(); + let is_old = |id: ID| -> LoroResult<bool> { + if left_ids.contains(&id) { + return Ok(true); + } + let mut single = FxHashSet::default(); + single.insert(id); + all_tips_covered_by_ancestors(get, left, &single) + }; + + let mut visited: FxHashSet<ID> = FxHashSet::default(); + let mut stack: Vec<OrdIdSpan> = Vec::new(); + for id in right.iter() { + if is_old(id)? { + continue; + } + let Some(span) = OrdIdSpan::from_dag_node(id, get)? else { + return Ok(false); + }; + stack.push(span); + } + + while let Some(span) = stack.pop() { + if !visited.insert(span.id_start()) { + continue; + } + + let Some(parents) = deps_to_ord_id_spans(&span, get)? else { + return Ok(false); + }; + let mut entry_point = true; + let mut old_parents = Frontiers::default(); + for parent in parents { + let pid = parent.id_last(); + if is_old(pid)? { + old_parents.push(pid); + } else { + entry_point = false; + stack.push(parent); + } + } + + if entry_point { + if &old_parents == left { + continue; + } + + if !all_tips_covered_by_ancestors(get, &old_parents, &left_ids)? { + return Ok(false); + } + } + } + + Ok(true) + } + + fn contains_in_ancestors<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( + get: &'a F, + frontier: ID, + target: &OrdIdSpan<'_>, + ) -> LoroResult<bool> { + let mut visited = FxHashSet::default(); + let mut pending = Vec::new(); + let Some(node) = OrdIdSpan::from_dag_node(frontier, get)? else { + return Ok(false); + }; + pending.push(node); + while let Some(node) = pending.pop() { + if node.contains_id(target.id_last()) { + return Ok(true); + } + + if node.lamport_last() < target.lamport_last() { + continue; + } + + if !visited.insert(node.id_start()) { + continue; + } + + if let Some(deps) = deps_to_ord_id_spans(&node, get)? { + for dep in deps { + pending.push(dep); + } + } + } + + Ok(false) + } + + // The third tuple item carries the dependency tips at which this path first + // split from its sibling paths. If the path dies without meeting the other + // side, those tips tell us whether it was a real concurrent branch or merely + // a redundant route into an ancestor we already found. + let mut queue: BinaryHeap<(OrdIdSpan, NodeType, Vec<ID>)> = BinaryHeap::new(); + for span in ids_to_ord_id_spans(left, get)?.unwrap() { + let branch_tips = if left.len() > 1 { + vec![span.id_last()] + } else { + Vec::new() + }; + queue.push((span, NodeType::A, branch_tips)); + } + + for span in ids_to_ord_id_spans(right, get)?.unwrap() { + let branch_tips = if right.len() > 1 { + vec![span.id_last()] + } else { + Vec::new() + }; + queue.push((span, NodeType::B, branch_tips)); + } + + while let Some((mut node, mut node_type, mut branch_tips)) = queue.pop() { + while let Some((other_node, other_type, _)) = queue.peek() { + if node == *other_node || node.id_last() == other_node.id_last() { + if node_type != *other_type { + node_type = NodeType::Shared; + } + + let (_, _, other_branch_tips) = queue.pop().unwrap(); + // Union, not concatenation. On criss-cross histories the same + // tips arrive from both parents at every re-merge; concatenating + // doubles the vec per sync round, and the per-dep clone below + // then makes the walk O(2^rounds). Distinct tips stay few: they + // are only minted for multi-head initial frontiers and at each + // side's first split. + for tip in other_branch_tips { + if !branch_tips.contains(&tip) { + branch_tips.push(tip); + } + } + } else { + break; + } + } + + if node_type == NodeType::Shared { + ans.push(node.id_last()); + continue; + } + + if queue.is_empty() { + if branch_tips.is_empty() { + unmatched_branches.insert(node.id_last()); + } else { + unmatched_branches.extend(branch_tips); + } + break; + } + + // if node_type is A, then the left side is greater or parallel to the right side + if node_type == NodeType::A { + is_right_greater = false; + } + + if let Some(other) = queue.peek() { + if node.contains_id(other.0.id_last()) && node_type != other.1 { + node.len = (other.0.id_last().counter - node.id.counter + 1) as usize; + queue.push((node, node_type, branch_tips)); + continue; + } + + if node.len > 1 { + // The `min(..., len - 1)` cap guarantees strict progress when + // lamports tie: aligning to the other's lamport alone would + // re-push the span unchanged and loop forever. It is also what + // makes the termination measure decrease on this branch. + node.len = if other.0.lamport_last() >= node.lamport { + (other.0.lamport_last() - node.lamport + 1).min(node.len as u32 - 1) as usize + } else { + 1 + }; + queue.push((node, node_type, branch_tips)); + continue; + } + } + + if let Some(deps) = deps_to_ord_id_spans(&node, get)? { + if !deps.is_empty() { + let starts_new_branches = branch_tips.is_empty() && deps.len() > 1; + for dep in deps { + let child_branch_tips = if starts_new_branches { + vec![dep.id_last()] + } else { + branch_tips.clone() + }; + queue.push((dep, node_type, child_branch_tips)); + } + is_linear = false; + continue; + } + } else { + // The dependency is on trimmed shallow history. The exact ancestor is + // not representable in the current DAG, so fall back to a conservative + // checkout base. No tip needs recording: this flag short-circuits the + // coverage check entirely. + has_unresolved_unmatched_branch = true; + continue; + } + + { + // Some checkout calculators still require replaying from a base that + // includes every branch whose operation positions may affect the diff. + // In non-linear checkout mode, an earlier version in the causal past of + // both sides is a valid conservative base even when it is not the meet. + if branch_tips.is_empty() { + unmatched_branches.insert(node.id_last()); + } else { + unmatched_branches.extend(branch_tips); + } + continue; + } + } + + ans = shrink_ancestor_frontiers(&ans, get)?; + // A branch can look unmatched merely because a shared node was found first + // and was therefore not expanded. In that case another queued path may still + // walk into one of the shared node's ancestors. That path is redundant, not a + // concurrent branch. Only fall back when an unmatched tip is not causally + // covered by the meet candidates we found. + let has_uncovered_unmatched_branch = has_unresolved_unmatched_branch + || !all_tips_covered_by_ancestors(get, &ans, &unmatched_branches)?; + // A genuine concurrent branch invalidates the meet as a replay base. The + // caller has to retreat to a critical version; which one is its choice, so + // it can try a cheap multi-head cut before paying for the full-DAG + // single-head descent. + let mut needs_critical_retreat = + has_uncovered_unmatched_branch && !has_trimmed_history_deps(&ans, get)?; + + if has_uncovered_unmatched_branch { + is_right_greater = false; + } else if &ans == left { + // An A-only path may also have been a redundant path into `ans`. Once all + // such paths are proved covered, equality with `left` is the exact proof + // that `right` causally includes `left`. + is_right_greater = true; + } + + if is_right_greater && left.len() > 1 && !new_region_after_all_left_heads(get, left, right)? { + // Version inclusion holds, but part of the new region entered old + // history through a strict subset of the left heads and is therefore + // concurrent with the others. `ImportGreaterUpdates` promises "no + // update is concurrent to the current version", so claiming it here + // lets fast paths (notably the tree calculator's) apply the new ops + // without adjudicating against the concurrent existing branch, and the + // materialized state diverges from a full replay. Demote to the + // conservative mode and retreat the base to a safe cut so the + // competing branches are replayed together. + is_right_greater = false; + needs_critical_retreat = true; + } + + let mode = if is_right_greater { + if ans.len() <= 1 { + debug_assert_eq!(&ans, left); + } + + if is_linear { + debug_assert!(ans.len() <= 1); + DiffMode::Linear + } else { + DiffMode::ImportGreaterUpdates + } + } else { + DiffMode::Checkout + }; + + let meet = if needs_critical_retreat { + MeetAsBase::NeedsCriticalRetreat + } else { + MeetAsBase::Valid(ans) + }; + Ok((meet, mode)) +} + +pub fn remove_included_frontiers(frontiers: &mut VersionVector, new_change_deps: &[ID]) { + for dep in new_change_deps.iter() { + if let Some(last) = frontiers.get_last(dep.peer) { + if last <= dep.counter { + frontiers.remove(&dep.peer); + } + } + } +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use loro_common::{HasId, HasIdSpan}; + use rand::{rngs::StdRng, Rng, SeedableRng}; + + use super::*; + + #[derive(Clone, Debug)] + struct TestNode { + id: ID, + len: usize, + lamport: Lamport, + deps: Frontiers, + } + + impl DagNode for TestNode { + fn deps(&self) -> &Frontiers { + &self.deps + } + } + + impl HasId for TestNode { + fn id_start(&self) -> ID { + self.id + } + } + + impl HasLamport for TestNode { + fn lamport(&self) -> Lamport { + self.lamport + } + } + + impl HasLength for TestNode { + fn content_len(&self) -> usize { + self.len + } + } + + impl Sliceable for TestNode { + fn slice(&self, from: usize, to: usize) -> Self { + Self { + id: self.id.inc(from as i32), + len: to - from, + lamport: self.lamport + from as Lamport, + deps: if from == 0 { + self.deps.clone() + } else { + self.id.inc(from as i32 - 1).into() + }, + } + } + } + + #[derive(Debug)] + struct TestDag { + nodes: BTreeMap<ID, TestNode>, + vv: VersionVector, + frontier: Frontiers, + } + + impl TestDag { + fn new(nodes: impl IntoIterator<Item = TestNode>, frontier: Frontiers) -> Self { + let mut vv = VersionVector::default(); + let nodes = nodes + .into_iter() + .map(|node| { + vv.set_end(node.id_end()); + (node.id_start(), node) + }) + .collect(); + Self { + nodes, + vv, + frontier, + } + } + } + + impl Dag for TestDag { + type Node = TestNode; + + fn get(&self, id: ID) -> Option<Self::Node> { + self.nodes + .range(..=id) + .rev() + .find(|(_, node)| node.contains_id(id)) + .map(|(_, node)| node.clone()) + } + + fn frontier(&self) -> &Frontiers { + &self.frontier + } + + fn vv(&self) -> &VersionVector { + &self.vv + } + + fn contains(&self, id: ID) -> bool { + self.get(id).is_some() + } + } + + fn node( + peer: PeerID, + counter: Counter, + len: usize, + lamport: Lamport, + deps: Frontiers, + ) -> TestNode { + TestNode { + id: ID::new(peer, counter), + len, + lamport, + deps, + } + } + + fn ancestors_of_frontiers(dag: &TestDag, frontiers: &Frontiers) -> FxHashSet<ID> { + let mut ans = FxHashSet::default(); + for id in frontiers.iter() { + collect_ancestors(dag, id, &mut ans); + } + ans + } + + fn collect_ancestors(dag: &TestDag, id: ID, ans: &mut FxHashSet<ID>) { + let mut stack = vec![id]; + let mut visited_targets = FxHashSet::default(); + while let Some(id) = stack.pop() { + if !visited_targets.insert(id) { + continue; + } + + for node in dag.nodes.values() { + if node.id_start().peer != id.peer || node.id_start().counter > id.counter { + continue; + } + + let end = node.id_last().counter.min(id.counter); + for counter in node.id_start().counter..=end { + ans.insert(ID::new(node.id_start().peer, counter)); + } + + for dep in node.deps().iter() { + stack.push(dep); + } + } + } + } + + fn is_ancestor(dag: &TestDag, ancestor: ID, descendant: ID) -> bool { + let mut ancestors = FxHashSet::default(); + collect_ancestors(dag, descendant, &mut ancestors); + ancestors.contains(&ancestor) + } + + fn maximal_frontiers(dag: &TestDag, ids: impl IntoIterator<Item = ID>) -> Frontiers { + let mut ids = Vec::<ID>::from_iter(ids); + ids.sort_by_key(|id| dag.get(*id).unwrap().get_lamport_from_counter(id.counter)); + let mut frontiers = Vec::new(); + for id in ids.into_iter().rev() { + if frontiers + .iter() + .any(|frontier| is_ancestor(dag, id, *frontier)) + { + continue; + } + + frontiers.retain(|frontier| !is_ancestor(dag, *frontier, id)); + frontiers.push(id); + } + + frontiers.into_iter().collect() + } + + fn oracle_meet(dag: &TestDag, left: &Frontiers, right: &Frontiers) -> Frontiers { + let left_ancestors = ancestors_of_frontiers(dag, left); + let right_ancestors = ancestors_of_frontiers(dag, right); + maximal_frontiers( + dag, + left_ancestors + .into_iter() + .filter(|id| right_ancestors.contains(id)), + ) + } + + fn assert_replay_base_valid_against_oracle(dag: &TestDag, left: &Frontiers, right: &Frontiers) { + let (actual, mode) = dag.find_replay_base(left, right); + let expected = oracle_meet(dag, left, right); + let left_ancestors = ancestors_of_frontiers(dag, left); + let right_ancestors = ancestors_of_frontiers(dag, right); + for id in actual.iter() { + assert!( + left_ancestors.contains(&id) && right_ancestors.contains(&id), + "every replay-base id {id} must be common: left={left:?} right={right:?} actual={actual:?} expected={expected:?} mode={mode:?}\ndag={dag:?}", + ); + } + + for a in actual.iter() { + for b in actual.iter() { + if a != b { + assert!( + !is_ancestor(dag, a, b), + "the replay base must be a minimal frontier set: left={left:?} right={right:?} actual={actual:?} expected={expected:?} mode={mode:?}\ndag={dag:?}", + ); + } + } + } + + if !matches!(mode, DiffMode::Checkout) { + assert_eq!( + actual, expected, + "non-checkout mode should use the meet: left={left:?} right={right:?} mode={mode:?}\ndag={dag:?}", + ); + assert_eq!( + &actual, left, + "non-checkout mode must use left as the replay base: left={left:?} right={right:?} mode={mode:?}" + ); + for id in left.iter() { + assert!( + right_ancestors.contains(&id), + "non-checkout mode requires right to include left id {id}; left={left:?} right={right:?} mode={mode:?}", + ); + } + } + } + + fn all_ids(dag: &TestDag) -> Vec<ID> { + dag.nodes + .values() + .flat_map(|node| { + (0..node.content_len()).map(|offset| node.id_start().inc(offset as Counter)) + }) + .collect() + } + + fn random_frontiers(dag: &TestDag, ids: &[ID], rng: &mut impl Rng) -> Frontiers { + if ids.is_empty() || rng.gen_bool(0.1) { + return Frontiers::default(); + } + + let len = rng.gen_range(1..=ids.len().min(4)); + maximal_frontiers(dag, (0..len).map(|_| ids[rng.gen_range(0..ids.len())])) + } + + fn random_dag(seed: u64, node_count: usize) -> TestDag { + let mut rng = StdRng::seed_from_u64(seed); + let mut next_counter = [0 as Counter; 8]; + let mut nodes = Vec::new(); + let mut existing_ids = Vec::new(); + for i in 0..node_count { + let peer = rng.gen_range(1..next_counter.len() as PeerID); + let counter = next_counter[peer as usize]; + let len = rng.gen_range(1..=3); + next_counter[peer as usize] += len as Counter; + let dep_count = if existing_ids.is_empty() { + 0 + } else { + rng.gen_range(0..=existing_ids.len().min(3)) + }; + let deps = maximal_frontiers( + &TestDag::new(nodes.clone(), Frontiers::default()), + (0..dep_count).map(|_| existing_ids[rng.gen_range(0..existing_ids.len())]), + ); + let node = node(peer, counter, len, i as Lamport * 4, deps); + existing_ids.extend((0..len).map(|offset| node.id_start().inc(offset as Counter))); + nodes.push(node); + } + + let dag = TestDag::new(nodes, Frontiers::default()); + let frontier = maximal_frontiers(&dag, existing_ids); + TestDag::new(dag.nodes.into_values(), frontier) + } + + fn layered_merge_dag() -> TestDag { + let root = node(1, 0, 3, 0, Frontiers::default()); + let left = node(1, 3, 2, 4, ID::new(1, 2).into()); + let right = node(2, 0, 3, 5, ID::new(1, 1).into()); + let late_right = node(2, 3, 2, 9, ID::new(2, 2).into()); + let third = node(3, 0, 2, 6, ID::new(1, 2).into()); + let merge_left_right = node( + 4, + 0, + 1, + 12, + Frontiers::from([left.id_last(), right.id_last()]), + ); + let merge_all = node( + 5, + 0, + 2, + 16, + Frontiers::from([ + merge_left_right.id_last(), + late_right.id_last(), + third.id_last(), + ]), + ); + let independent = node(6, 0, 2, 20, Frontiers::default()); + let final_merge = node( + 7, + 0, + 1, + 25, + Frontiers::from([merge_all.id_last(), independent.id_last()]), + ); + + TestDag::new( + vec![ + root, + left, + right, + late_right, + third, + merge_left_right, + merge_all, + independent, + final_merge.clone(), + ], + final_merge.id_last().into(), + ) + } + + #[test] + fn replay_base_handles_empty_linear_same_span_and_parent_child_cases() { + let first = node(1, 0, 2, 0, Frontiers::default()); + let second = node(1, 2, 2, 2, ID::new(1, 1).into()); + let dag = TestDag::new(vec![first, second], ID::new(1, 3).into()); + + assert_eq!( + dag.find_replay_base(&Frontiers::default(), &ID::new(1, 3).into()), + (Frontiers::default(), DiffMode::Linear) + ); + assert_eq!( + dag.find_replay_base(&ID::new(1, 3).into(), &Frontiers::default()), + (Frontiers::default(), DiffMode::Checkout) + ); + assert_eq!( + dag.find_replay_base(&ID::new(1, 0).into(), &ID::new(1, 1).into()), + (ID::new(1, 0).into(), DiffMode::Linear) + ); + assert_eq!( + dag.find_replay_base(&ID::new(1, 1).into(), &ID::new(1, 0).into()), + (ID::new(1, 0).into(), DiffMode::Checkout) + ); + assert_eq!( + dag.find_replay_base(&ID::new(1, 1).into(), &ID::new(1, 3).into()), + (ID::new(1, 1).into(), DiffMode::Linear) + ); + } + + #[test] + fn replay_base_left_empty_stops_linear_scan_at_missing_shallow_dependency() { + let visible = node(1, 1, 1, 1, ID::new(1, 0).into()); + let dag = TestDag::new(vec![visible], ID::new(1, 1).into()); + + assert_eq!( + dag.find_replay_base(&Frontiers::default(), &ID::new(1, 1).into()), + (Frontiers::default(), DiffMode::ImportGreaterUpdates) + ); + } + + #[test] + fn replay_base_of_parallel_branches_is_shared_dependency() { + let root = node(1, 0, 1, 0, Frontiers::default()); + let left = node(2, 0, 1, 1, root.id.into()); + let right = node(3, 0, 1, 2, root.id.into()); + let merge = node(4, 0, 1, 3, Frontiers::from([left.id, right.id])); + let dag = TestDag::new( + vec![root.clone(), left.clone(), right.clone(), merge.clone()], + merge.id.into(), + ); + + let (ancestor, mode) = dag.find_replay_base(&left.id.into(), &right.id.into()); + assert_eq!(ancestor, root.id.into()); + assert_eq!(mode, DiffMode::Checkout); + + let (ancestor, _) = dag.find_replay_base(&root.id.into(), &merge.id.into()); + assert_eq!(ancestor, root.id.into()); + } + + #[test] + fn replay_base_falls_back_before_independent_branch() { + let left = node(1, 0, 1, 0, Frontiers::default()); + let independent = node(2, 0, 1, 1, Frontiers::default()); + let merge = node(3, 0, 1, 2, Frontiers::from([left.id, independent.id])); + let dag = TestDag::new( + vec![left.clone(), independent, merge.clone()], + merge.id.into(), + ); + + let (ancestor, mode) = dag.find_replay_base(&left.id.into(), &merge.id.into()); + assert_eq!(ancestor, Frontiers::default()); + assert_eq!(mode, DiffMode::Checkout); + } + + #[test] + fn replay_base_falls_back_before_unmatched_branch_with_multiple_left_frontiers() { + let left_a = node(1, 0, 1, 0, Frontiers::default()); + let left_b = node(2, 0, 1, 1, Frontiers::default()); + let independent = node(3, 0, 1, 2, Frontiers::default()); + let left_frontiers = Frontiers::from([left_a.id, left_b.id]); + let merge = node( + 4, + 0, + 1, + 3, + Frontiers::from([left_a.id, left_b.id, independent.id]), + ); + let dag = TestDag::new( + vec![left_a.clone(), left_b.clone(), independent, merge.clone()], + merge.id.into(), + ); + + let (ancestor, mode) = dag.find_replay_base(&left_frontiers, &merge.id.into()); + assert_eq!(ancestor, Frontiers::default()); + assert_eq!(mode, DiffMode::Checkout); + } + + #[test] + fn replay_base_marks_cross_peer_direct_dependency_as_greater_update() { + let left = node(1, 0, 1, 0, Frontiers::default()); + let right = node(2, 0, 1, 1, left.id.into()); + let dag = TestDag::new(vec![left.clone(), right.clone()], right.id.into()); + + let (ancestor, mode) = dag.find_replay_base(&left.id.into(), &right.id.into()); + assert_eq!(ancestor, left.id.into()); + assert_eq!(mode, DiffMode::ImportGreaterUpdates); + } + + #[test] + fn replay_base_ignores_implicit_predecessor_covered_by_explicit_dependency() { + let peer_one_previous = node(1, 0, 1, 0, Frontiers::default()); + let relay = node(2, 0, 1, 1, peer_one_previous.id.into()); + // This is peer 1's next change, so it implicitly depends on + // `peer_one_previous`. Its explicit dependency on `relay` already covers + // that predecessor, though, so the two paths are not concurrent. + let peer_one_next = node(1, 1, 1, 2, relay.id.into()); + let dag = TestDag::new( + vec![peer_one_previous, relay.clone(), peer_one_next.clone()], + peer_one_next.id.into(), + ); + + let (ancestor, mode) = dag.find_replay_base(&relay.id.into(), &peer_one_next.id.into()); + assert_eq!(ancestor, relay.id.into()); + assert_eq!(mode, DiffMode::ImportGreaterUpdates); + } + + #[test] + fn replay_base_ignores_implicit_predecessor_covered_transitively() { + let peer_one_previous = node(1, 0, 1, 0, Frontiers::default()); + let first_relay = node(2, 0, 1, 1, peer_one_previous.id.into()); + let current_frontier = node(3, 0, 1, 2, first_relay.id.into()); + let peer_one_next = node(1, 1, 1, 3, current_frontier.id.into()); + let dag = TestDag::new( + vec![ + peer_one_previous, + first_relay, + current_frontier.clone(), + peer_one_next.clone(), + ], + peer_one_next.id.into(), + ); + + let (ancestor, mode) = + dag.find_replay_base(¤t_frontier.id.into(), &peer_one_next.id.into()); + assert_eq!(ancestor, current_frontier.id.into()); + assert_eq!(mode, DiffMode::ImportGreaterUpdates); + } + + #[test] + fn replay_base_keeps_uncovered_implicit_predecessor_conservative() { + let peer_one_previous = node(1, 0, 1, 0, Frontiers::default()); + let concurrent = node(2, 0, 1, 1, Frontiers::default()); + let peer_one_next = node(1, 1, 1, 2, concurrent.id.into()); + let dag = TestDag::new( + vec![peer_one_previous, concurrent.clone(), peer_one_next.clone()], + peer_one_next.id.into(), + ); + + let (ancestor, mode) = + dag.find_replay_base(&concurrent.id.into(), &peer_one_next.id.into()); + assert_eq!(ancestor, Frontiers::default()); + assert_eq!(mode, DiffMode::Checkout); + } + + #[test] + fn replay_base_falls_back_when_right_adds_concurrent_branch_from_shared_root() { + let root = node(1, 0, 1, 0, Frontiers::default()); + let root_id = root.id; + let left = node(2, 0, 1, 1, root.id.into()); + let concurrent = node(3, 0, 1, 2, root.id.into()); + let merge = node(4, 0, 1, 3, Frontiers::from([left.id, concurrent.id])); + let dag = TestDag::new( + vec![root, left.clone(), concurrent, merge.clone()], + merge.id.into(), + ); + + let (ancestor, mode) = dag.find_replay_base(&left.id.into(), &merge.id.into()); + // The conservative base retreats to the latest single-head critical + // version below both sides — here the shared root — instead of the + // beginning of history. + assert_eq!(ancestor, root_id.into()); + assert_eq!(mode, DiffMode::Checkout); + } + + #[test] + fn replay_base_falls_back_when_right_frontiers_add_concurrent_branch() { + let root = node(1, 0, 1, 0, Frontiers::default()); + let left = node(2, 0, 1, 1, root.id.into()); + let concurrent = node(3, 0, 1, 2, root.id.into()); + let right = Frontiers::from([left.id, concurrent.id]); + let dag = TestDag::new(vec![root, left.clone(), concurrent], right.clone()); + + let (ancestor, mode) = dag.find_replay_base(&left.id.into(), &right); + // Conservative base = the shared root (latest single-head critical + // version), not the beginning of history. + assert_eq!(ancestor, ID::new(1, 0).into()); + assert_eq!(mode, DiffMode::Checkout); + } + + #[test] + fn replay_base_falls_back_when_left_frontiers_add_concurrent_branch() { + let root = node(1, 0, 1, 0, Frontiers::default()); + let shared = node(2, 0, 1, 1, root.id.into()); + let concurrent = node(3, 0, 1, 2, root.id.into()); + let left = Frontiers::from([shared.id, concurrent.id]); + let dag = TestDag::new(vec![root, shared.clone(), concurrent], left.clone()); + + // The concurrent left head walks below `shared` without ever meeting the + // right side. Only the tip seeded for the multi-element left frontier can + // prove it uncovered; the deep node it dies at is itself covered. + let (ancestor, mode) = dag.find_replay_base(&left, &shared.id.into()); + // Conservative base = the shared root (latest single-head critical + // version), not the beginning of history. + assert_eq!(ancestor, ID::new(1, 0).into()); + assert_eq!(mode, DiffMode::Checkout); + } + + #[test] + fn replay_base_falls_back_when_walk_reaches_trimmed_history() { + // Peer 9's changes are not present in the DAG, as after shallow trimming. + // Both sides die at the missing dependency inside the main walk, which + // must force the conservative empty base regardless of tip coverage. + let a = node(1, 0, 1, 5, ID::new(9, 5).into()); + let b = node(2, 0, 1, 6, ID::new(9, 7).into()); + let dag = TestDag::new(vec![a.clone(), b.clone()], Frontiers::from([a.id, b.id])); + + let (ancestor, mode) = dag.find_replay_base(&a.id.into(), &b.id.into()); + assert_eq!(ancestor, Frontiers::default()); + assert_eq!(mode, DiffMode::Checkout); + } + + #[test] + fn import_greater_updates_requires_new_ops_after_all_left_heads() { + // Movable-tree staleness issue shape: B3 → B4..B6 and B3 → A0 → A1..A3. + // from = {A0, B6}, to = {A3, B6}. Version inclusion holds + // (vv(to) ⊇ vv(from)), yet A1..A3 are concurrent with the left head B6, + // so ImportGreaterUpdates must not be claimed: the tree calculator's + // fast path would apply A1..A3 without adjudicating against B4..B6. + // The base must retreat to the latest critical version {B3}. + let b_creates = node(2, 0, 4, 0, Frontiers::default()); + let b_moves = node(2, 4, 3, 4, ID::new(2, 3).into()); + let a0 = node(1, 0, 1, 4, ID::new(2, 3).into()); + let a_moves = node(1, 1, 3, 5, ID::new(1, 0).into()); + let dag = TestDag::new( + vec![b_creates, b_moves, a0, a_moves], + Frontiers::from([ID::new(1, 3), ID::new(2, 6)]), + ); + + let left = Frontiers::from([ID::new(1, 0), ID::new(2, 6)]); + let right = Frontiers::from([ID::new(1, 3), ID::new(2, 6)]); + let (ancestor, mode) = dag.find_replay_base(&left, &right); + assert_eq!(ancestor, ID::new(2, 3).into()); + assert_eq!(mode, DiffMode::Checkout); + } + + #[test] + fn import_greater_updates_kept_when_new_ops_depend_on_all_left_heads() { + // Healthy multi-head import: the new change's deps equal the whole + // left frontier, so every new op is causally after all of it and the + // fast path must be preserved (entry check passes by set equality). + let root = node(1, 0, 1, 0, Frontiers::default()); + let x = node(2, 0, 1, 1, ID::new(1, 0).into()); + let y = node(3, 0, 1, 1, ID::new(1, 0).into()); + let merge = node(4, 0, 1, 2, Frontiers::from([ID::new(2, 0), ID::new(3, 0)])); + let dag = TestDag::new(vec![root, x, y, merge], ID::new(4, 0).into()); + + let left = Frontiers::from([ID::new(2, 0), ID::new(3, 0)]); + let (ancestor, mode) = dag.find_replay_base(&left, &ID::new(4, 0).into()); + assert_eq!(ancestor, left); + assert_eq!(mode, DiffMode::ImportGreaterUpdates); + } + + #[test] + fn replay_base_criss_cross_ladder_stays_linear() { + // Two peers that each merge both previous heads every round — the shape + // ordinary bidirectional sync produces. Branch tips re-merge at every + // rung; without deduplication in the tip union the walk is O(2^rounds) + // (~minutes at this depth), with it the walk is linear (~microseconds). + const ROUNDS: usize = 26; + let root = node(3, 0, 1, 0, Frontiers::default()); + let mut a_head = node(1, 0, 1, 1, root.id.into()); + let mut b_head = node(2, 0, 1, 1, root.id.into()); + let mut nodes = vec![root.clone(), a_head.clone(), b_head.clone()]; + for k in 1..=ROUNDS { + let deps = Frontiers::from([a_head.id_last(), b_head.id_last()]); + let lamport = (k as Lamport) * 2; + let next_a = node(1, k as Counter, 1, lamport, deps.clone()); + let next_b = node(2, k as Counter, 1, lamport, deps); + nodes.push(next_a.clone()); + nodes.push(next_b.clone()); + a_head = next_a; + b_head = next_b; + } + let frontier = Frontiers::from([a_head.id_last(), b_head.id_last()]); + let dag = TestDag::new(nodes, frontier.clone()); + + let start = std::time::Instant::now(); + let (ancestor, mode) = dag.find_replay_base(&root.id.into(), &frontier); + assert_eq!(ancestor, root.id.into()); + assert_eq!(mode, DiffMode::ImportGreaterUpdates); + // Generous 4-orders-of-magnitude margin over the fixed cost; the broken + // exponential path needs minutes here even in release mode. + assert!( + start.elapsed() < std::time::Duration::from_secs(10), + "criss-cross walk took {:?}; branch-tip growth is no longer linear", + start.elapsed() + ); + } + + #[test] + fn replay_base_keeps_target_when_checking_out_to_ancestor_with_extra_branch() { + let root = node(1, 0, 1, 0, Frontiers::default()); + let left = node(2, 0, 2, 1, root.id.into()); + let right = node(3, 0, 2, 3, root.id.into()); + let extra = node( + 4, + 0, + 1, + 5, + Frontiers::from([left.id_last(), right.id_last()]), + ); + let dag = TestDag::new( + vec![root, left.clone(), right.clone(), extra.clone()], + extra.id.into(), + ); + let target = Frontiers::from([ID::new(2, 0), ID::new(3, 0)]); + let current = Frontiers::from([extra.id, left.id_last(), right.id_last()]); + + let (ancestor, mode) = dag.find_replay_base(¤t, &target); + assert_eq!(ancestor, target); + assert_eq!(mode, DiffMode::Checkout); + } + + #[test] + fn replay_base_does_not_keep_ancestor_of_shared_descendant() { + let root = node(1, 0, 1, 0, Frontiers::default()); + let shared = node(2, 0, 1, 1, root.id.into()); + let left_only = node(3, 0, 1, 2, root.id.into()); + let right_only = node(4, 0, 1, 3, root.id.into()); + let dag = TestDag::new( + vec![root, shared.clone(), left_only.clone(), right_only.clone()], + Frontiers::from([shared.id, left_only.id, right_only.id]), + ); + + let (ancestor, mode) = dag.find_replay_base( + &Frontiers::from([shared.id, left_only.id]), + &Frontiers::from([shared.id, right_only.id]), + ); + assert_eq!(ancestor, shared.id.into()); + assert_eq!(mode, DiffMode::Checkout); + } + + #[test] + fn replay_base_valid_against_slow_oracle_on_random_dags() { + for seed in 0..128 { + let mut rng = StdRng::seed_from_u64(seed); + let dag = random_dag(seed, rng.gen_range(1..=18)); + let ids = all_ids(&dag); + for _ in 0..64 { + let left = random_frontiers(&dag, &ids, &mut rng); + let right = random_frontiers(&dag, &ids, &mut rng); + assert_replay_base_valid_against_oracle(&dag, &left, &right); + } + } + } + + #[test] + fn replay_base_valid_against_slow_oracle_on_all_pairs_in_small_random_dags() { + for seed in 1000..1020 { + let dag = random_dag(seed, 8); + let ids = all_ids(&dag); + let mut frontiers = vec![Frontiers::default()]; + frontiers.extend(ids.iter().copied().map(Frontiers::from)); + for chunk in ids.chunks(3) { + frontiers.push(maximal_frontiers(&dag, chunk.iter().copied())); + } + + for left in frontiers.iter() { + for right in frontiers.iter() { + assert_replay_base_valid_against_oracle(&dag, left, right); + } + } + } + } + + #[test] + fn replay_base_valid_against_slow_oracle_on_layered_merge_dag() { + let dag = layered_merge_dag(); + let ids = all_ids(&dag); + let mut frontiers = vec![Frontiers::default(), dag.frontier().clone()]; + frontiers.extend(ids.iter().copied().map(Frontiers::from)); + frontiers.extend([ + Frontiers::from([ID::new(1, 4), ID::new(2, 2)]), + Frontiers::from([ID::new(1, 4), ID::new(3, 1)]), + Frontiers::from([ID::new(4, 0), ID::new(2, 4), ID::new(3, 1)]), + Frontiers::from([ID::new(5, 1), ID::new(6, 1)]), + ]); + + for left in frontiers.iter() { + for right in frontiers.iter() { + assert_replay_base_valid_against_oracle(&dag, left, right); + } + } + } + + #[test] + fn replay_base_valid_against_slow_oracle_on_branchy_random_dags() { + for seed in 2000..2064 { + let mut rng = StdRng::seed_from_u64(seed); + let dag = random_dag(seed, rng.gen_range(20..=36)); + let ids = all_ids(&dag); + for _ in 0..96 { + let left = random_frontiers(&dag, &ids, &mut rng); + let right = random_frontiers(&dag, &ids, &mut rng); + assert_replay_base_valid_against_oracle(&dag, &left, &right); + } + } + } + + #[test] + fn find_path_reports_forward_and_retreat_spans_for_linear_and_branch_paths() { + let first = node(1, 0, 2, 0, Frontiers::default()); + let second = node(1, 2, 2, 2, ID::new(1, 1).into()); + let side = node(2, 0, 1, 1, ID::new(1, 1).into()); + let dag = TestDag::new( + vec![first, second, side], + Frontiers::from([ID::new(1, 3), ID::new(2, 0)]), + ); + + let forward = dag.find_path(&ID::new(1, 0).into(), &ID::new(1, 3).into()); + assert!(forward.retreat.is_empty()); + assert_eq!(forward.forward.get(&1), Some(&CounterSpan::new(1, 4))); + + let retreat = dag.find_path(&ID::new(1, 3).into(), &ID::new(1, 0).into()); + assert!(retreat.forward.is_empty()); + assert_eq!(retreat.retreat.get(&1), Some(&CounterSpan::new(1, 4))); + + let branch = dag.find_path(&ID::new(2, 0).into(), &ID::new(1, 3).into()); + assert_eq!(branch.retreat.get(&2), Some(&CounterSpan::new(0, 1))); + assert_eq!(branch.forward.get(&1), Some(&CounterSpan::new(2, 4))); + } + + #[test] + fn get_version_vector_walks_dependencies_once_and_tracks_dep_ids_inside_spans() { + let base = node(1, 0, 3, 0, Frontiers::default()); + let left = node(2, 0, 1, 4, ID::new(1, 1).into()); + let right = node(3, 0, 1, 5, ID::new(1, 2).into()); + let merge = node(4, 0, 1, 6, Frontiers::from([left.id, right.id])); + let dag = TestDag::new(vec![base, left, right, merge.clone()], merge.id.into()); + + let vv = dag.get_vv(merge.id); + assert_eq!(vv.get_last(1), Some(2)); + assert_eq!(vv.get_last(2), Some(0)); + assert_eq!(vv.get_last(3), Some(0)); + assert_eq!(vv.get_last(4), Some(0)); + } + + #[test] + fn remove_included_frontiers_drops_only_dependencies_at_or_after_recorded_frontiers() { + let mut vv = VersionVector::default(); + vv.set_last(ID::new(1, 3)); + vv.set_last(ID::new(2, 4)); + vv.set_last(ID::new(3, 1)); + + remove_included_frontiers(&mut vv, &[ID::new(1, 3), ID::new(2, 2), ID::new(4, 0)]); + + assert_eq!(vv.get_last(1), None); + assert_eq!(vv.get_last(2), Some(4)); + assert_eq!(vv.get_last(3), Some(1)); + } + + #[test] + fn ord_id_span_orders_by_last_lamport_peer_and_shorter_overlapping_span() { + let short = OrdIdSpan { + id: ID::new(1, 1), + lamport: 1, + len: 1, + deps: Cow::Owned(Frontiers::default()), + }; + let long = OrdIdSpan { + id: ID::new(1, 0), + lamport: 0, + len: 2, + deps: Cow::Owned(Frontiers::default()), + }; + let later_peer = OrdIdSpan { + id: ID::new(2, 0), + lamport: 1, + len: 1, + deps: Cow::Owned(Frontiers::default()), + }; + + assert!(short > long); + assert!(later_peer > short); + assert_eq!(long.get_min().len, 1); + } +} diff --git a/vendor/loro-internal/src/dag/iter.rs b/vendor/loro-internal/src/dag/iter.rs new file mode 100644 index 0000000..8427b1f --- /dev/null +++ b/vendor/loro-internal/src/dag/iter.rs @@ -0,0 +1,637 @@ +use crate::version::Frontiers; +use num::Zero; +use std::{collections::BTreeMap, ops::Range}; + +use super::*; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +struct IdHeapItem { + id: ID, + lamport: Lamport, +} + +impl PartialOrd for IdHeapItem { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for IdHeapItem { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.lamport.cmp(&other.lamport).reverse() + } +} + +#[allow(dead_code)] +pub(crate) fn iter_dag_with_vv<T, D: Dag<Node = T>>(dag: &D) -> DagIteratorVV<'_, T> { + DagIteratorVV { + dag, + vv_map: Default::default(), + heap: BinaryHeap::new(), + } +} + +#[allow(dead_code)] +pub(crate) fn iter_dag<T>(dag: &dyn Dag<Node = T>) -> DagIterator<'_, T> { + DagIterator { + dag, + visited: VersionVector::new(), + heap: BinaryHeap::new(), + } +} + +pub struct DagIterator<'a, T> { + dag: &'a dyn Dag<Node = T>, + /// Because all deps' lamports are smaller than current node's lamport. + /// We can use the lamport to sort the nodes so that each node's deps are processed before itself. + /// + /// The ids in this heap are start ids of nodes. It won't be a id pointing to the middle of a node. + heap: BinaryHeap<IdHeapItem>, + visited: VersionVector, +} + +/// Should only use it on debug, because it's slow and likely to use lots of mem +impl<T: DagNode> Iterator for DagIterator<'_, T> { + type Item = T; + + fn next(&mut self) -> Option<Self::Item> { + if self.visited.is_empty() { + if self.dag.vv().is_empty() { + return None; + } + + for (&client_id, _) in self.dag.vv().iter() { + if let Some(node) = self.dag.get(ID::new(client_id, 0)) { + self.heap.push(IdHeapItem { + id: ID::new(client_id, 0), + lamport: node.lamport(), + }); + } + + self.visited.insert(client_id, 0); + } + } + + if !self.heap.is_empty() { + let item = self.heap.pop().unwrap(); + let id = item.id; + let node = self.dag.get(id).unwrap(); + // push next node from the same client to the heap + let next_id = id.inc(node.content_len() as i32); + if self.dag.contains(next_id) { + let next_node = self.dag.get(next_id).unwrap(); + self.heap.push(IdHeapItem { + id: next_id, + lamport: next_node.lamport(), + }); + } + + return Some(node); + } + + None + } +} + +pub(crate) struct DagIteratorVV<'a, T> { + dag: &'a dyn Dag<Node = T>, + /// we should keep every nodes starting id inside this map + vv_map: FxHashMap<ID, VersionVector>, + /// Because all deps' lamports are smaller than current node's lamport. + /// We can use the lamport to sort the nodes so that each node's deps are processed before itself. + /// + /// The ids in this heap are start ids of nodes. It won't be a id pointing to the middle of a node. + heap: BinaryHeap<IdHeapItem>, +} + +/// Should only use it on debug, because it's slow and likely to use lots of mem +impl<T: DagNode> Iterator for DagIteratorVV<'_, T> { + type Item = (T, VersionVector); + + fn next(&mut self) -> Option<Self::Item> { + if self.vv_map.is_empty() { + if self.dag.vv().is_empty() { + return None; + } + + for (&client_id, _) in self.dag.vv().iter() { + let vv = VersionVector::new(); + if let Some(node) = self.dag.get(ID::new(client_id, 0)) { + if node.lamport() == 0 { + self.vv_map.insert(ID::new(client_id, 0), vv.clone()); + } + + self.heap.push(IdHeapItem { + id: ID::new(client_id, 0), + lamport: node.lamport(), + }); + } + } + } + + if !self.heap.is_empty() { + let item = self.heap.pop().unwrap(); + let id = item.id; + let node = self.dag.get(id).unwrap(); + debug_assert_eq!(id, node.id_start()); + let mut vv = { + // calculate vv + let mut vv: Option<VersionVector> = None; + for dep_id in node.deps().iter() { + let dep = self.dag.get(dep_id).unwrap(); + let dep_vv = self.vv_map.get(&dep.id_start()).unwrap(); + if let Some(vv) = vv.as_mut() { + vv.merge(dep_vv); + } else { + vv = Some(dep_vv.clone()); + } + + if dep.id_start() != dep_id { + vv.as_mut().unwrap().set_last(dep_id); + } + } + + vv.unwrap_or_default() + }; + + vv.try_update_last(id); + self.vv_map.insert(id, vv.clone()); + + // push next node from the same client to the heap + let next_id = id.inc(node.content_len() as i32); + if self.dag.contains(next_id) { + let next_node = self.dag.get(next_id).unwrap(); + self.heap.push(IdHeapItem { + id: next_id, + lamport: next_node.lamport(), + }); + } + + return Some((node, vv)); + } + + None + } +} + +/// Visit every span in the target IdSpanVector. +/// It's guaranteed that the spans are visited in causal order, and each span is visited only once. +/// When visiting a span, we will checkout to the version where the span was created +pub(crate) struct DagCausalIter<'a, Dag> { + dag: &'a Dag, + frontier: Frontiers, + target: IdSpanVector, + /// how many dependencies are inside target for each id + out_degrees: FxHashMap<ID, usize>, + succ: BTreeMap<ID, Vec<ID>>, + stack: Vec<ID>, +} + +#[derive(Debug)] +pub(crate) struct IterReturn<T> { + /// data is a reference, it need to be sliced by the counter_range to get the underlying data + pub data: T, + /// data[slice] is the data we want to return + #[allow(unused)] + pub slice: Range<i32>, +} + +impl<'a, T: DagNode, D: Dag<Node = T> + Debug> DagCausalIter<'a, D> { + #[cfg(test)] + pub fn new(dag: &'a D, from: Frontiers, target: IdSpanVector) -> Self { + Self::try_new(dag, from, target).unwrap() + } + + pub fn try_new(dag: &'a D, from: Frontiers, target: IdSpanVector) -> LoroResult<Self> { + let mut out_degrees: FxHashMap<ID, usize> = FxHashMap::default(); + let mut succ: BTreeMap<ID, Vec<ID>> = BTreeMap::default(); + let mut stack = Vec::new(); + let mut q = vec![]; + for id in target.iter() { + if id.1.content_len() > 0 { + let id = id.id_start(); + q.push(id); + } + } + + // traverse all nodes, calculate the out_degrees + // if out_degree is 0, then it can be iterated directly + while let Some(id) = q.pop() { + let client = id.peer; + let node = dag.try_get(id)?.ok_or(LoroError::FrontiersNotFound(id))?; + let deps = node.deps(); + out_degrees.insert( + id, + deps.iter() + .filter(|&dep| { + if let Some(span) = target.get(&dep.peer) { + let included_in_target = + dep.counter >= span.min() && dep.counter <= span.max(); + if included_in_target { + succ.entry(dep).or_default().push(id); + } + included_in_target + } else { + false + } + }) + .count(), + ); + let target_span = target.get(&client).unwrap(); + let last_counter = node.id_last().counter; + if target_span.max() > last_counter { + q.push(ID::new(client, last_counter + 1)) + } + } + + // Enforce per-peer counter order. Within a single peer, the iterator + // must visit tracked node-starts in ascending counter order even when + // the nodes are concurrent (i.e. don't declare each other as deps). + // Without this, two same-peer nodes can both have zero in-degree and + // end up on the stack at once; the LIFO pop order would then violate + // the iterator's invariant that each popped id equals the current + // target_span.min() for its peer. + let mut by_peer: FxHashMap<PeerID, Vec<Counter>> = FxHashMap::default(); + for id in out_degrees.keys() { + by_peer.entry(id.peer).or_default().push(id.counter); + } + for (peer, mut counters) in by_peer { + if counters.len() < 2 { + continue; + } + counters.sort_unstable(); + for pair in counters.windows(2) { + let prev = ID::new(peer, pair[0]); + let curr = ID::new(peer, pair[1]); + if let Some(deg) = out_degrees.get_mut(&curr) { + *deg += 1; + } + succ.entry(prev).or_default().push(curr); + } + } + + out_degrees.retain(|k, v| { + if v.is_zero() { + stack.push(*k); + return false; + } + true + }); + + Ok(Self { + dag, + frontier: from, + target, + out_degrees, + succ, + stack, + }) + } +} + +impl<T: DagNode, D: Dag<Node = T>> Iterator for DagCausalIter<'_, D> { + type Item = IterReturn<T>; + + fn next(&mut self) -> Option<Self::Item> { + loop { + if self.stack.is_empty() { + debug_assert_eq!( + 0, + self.target + .iter() + .map(|x| x.1.content_len() as i32) + .sum::<i32>() + ); + return None; + } + + let node_id = self.stack.pop().unwrap(); + let (node, slice_from, slice_end, next_same_peer) = { + let target_span = self.target.get_mut(&node_id.peer).unwrap(); + if node_id.counter != target_span.min() { + debug_assert!( + node_id.counter < target_span.min(), + "{} {:?}", + node_id, + target_span + ); + continue; + } + + // node_id may point into the middle of the node, we need to slice + // try_new has loaded every target node before iteration starts. + let node = self.dag.get(node_id).unwrap(); + // node start_id may be smaller than node_id + let counter = node.id_span().counter; + let slice_from = if counter.start < target_span.start { + target_span.start - counter.start + } else { + 0 + }; + let slice_end = if counter.end < target_span.end { + counter.end - counter.start + } else { + target_span.end - counter.start + }; + + if slice_end <= slice_from { + debug_assert_eq!(slice_end, slice_from, "{node_id} {:?}", target_span); + continue; + } + + let consumed_last_counter = counter.start + slice_end - 1; + target_span.set_start(consumed_last_counter + 1); + let next_same_peer = if target_span.content_len() > 0 { + Some(ID::new(node_id.peer, target_span.min())) + } else { + None + }; + + (node, slice_from, slice_end, next_same_peer) + }; + + if let Some(next_id) = next_same_peer { + if !self.out_degrees.contains_key(&next_id) && !self.stack.contains(&next_id) { + self.stack.push(next_id); + } + } + + // NOTE: we expect user to update the tracker, to apply node, after visiting the node + self.frontier = Frontiers::from_id(node.id_start().inc(slice_end - 1)); + + let current_peer = node_id.peer; + let mut keys = Vec::new(); + let mut heap = BinaryHeap::new(); + // The in-degree of the successor node minus 1, and if it becomes 0, it is added to the heap + for (key, succ) in self.succ.range(node.id_start()..node.id_end()) { + keys.push(*key); + for succ_id in succ.iter() { + self.out_degrees.entry(*succ_id).and_modify(|i| *i -= 1); + if let Some(in_degree) = self.out_degrees.get(succ_id) { + if in_degree.is_zero() { + heap.push((succ_id.peer != current_peer, *succ_id)); + self.out_degrees.remove(succ_id); + } + } + } + } + // Nodes that have been traversed are removed from the graph to avoid being covered by other node ranges again + keys.into_iter().for_each(|k| { + self.succ.remove(&k); + }); + while let Some(id) = heap.pop() { + self.stack.push(id.1) + } + + return Some(IterReturn { + data: node, + slice: slice_from..slice_end, + }); + } + } +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use super::*; + use crate::{ + change::Lamport, + id::ID, + span::{CounterSpan, HasId, HasLamport}, + version::VersionVector, + }; + use rle::{HasLength, Sliceable}; + + #[derive(Debug, Clone)] + struct DummyNode { + id: ID, + lamport: Lamport, + len: usize, + deps: Frontiers, + } + + impl DagNode for DummyNode { + fn deps(&self) -> &Frontiers { + &self.deps + } + } + + impl Sliceable for DummyNode { + fn slice(&self, from: usize, to: usize) -> Self { + Self { + id: self.id.inc(from as i32), + lamport: self.lamport + from as Lamport, + len: to - from, + deps: if from > 0 { + self.id.inc(from as i32 - 1).into() + } else { + self.deps.clone() + }, + } + } + } + + impl HasLamport for DummyNode { + fn lamport(&self) -> Lamport { + self.lamport + } + } + + impl HasId for DummyNode { + fn id_start(&self) -> ID { + self.id + } + } + + impl HasLength for DummyNode { + fn content_len(&self) -> usize { + self.len + } + } + + #[derive(Debug)] + struct DummyDag { + nodes: BTreeMap<ID, DummyNode>, + vv: VersionVector, + frontier: Frontiers, + } + + impl Dag for DummyDag { + type Node = DummyNode; + + fn get(&self, id: ID) -> Option<Self::Node> { + self.nodes + .range(..=id) + .next_back() + .filter(|(_, node)| node.contains_id(id)) + .map(|(_, node)| node.clone()) + } + + fn frontier(&self) -> &Frontiers { + &self.frontier + } + + fn vv(&self) -> &VersionVector { + &self.vv + } + + fn contains(&self, id: ID) -> bool { + self.nodes + .range(..=id) + .next_back() + .is_some_and(|(_, node)| node.contains_id(id)) + } + } + + #[test] + fn stale_iterator_state_repairs_missing_same_peer_continuation() { + let first = DummyNode { + id: ID::new(1, 0), + lamport: 0, + len: 5, + deps: Frontiers::default(), + }; + let second = DummyNode { + id: ID::new(1, 5), + lamport: 5, + len: 5, + deps: ID::new(1, 4).into(), + }; + let mut vv = VersionVector::default(); + vv.set_end(second.id_end()); + let dag = DummyDag { + frontier: second.id_last().into(), + nodes: [(first.id_start(), first), (second.id_start(), second)] + .into_iter() + .collect(), + vv, + }; + + let mut target = IdSpanVector::default(); + target.insert(1, CounterSpan::new(0, 7)); + let mut iter = DagCausalIter { + dag: &dag, + frontier: Frontiers::default(), + target, + out_degrees: Default::default(), + succ: BTreeMap::default(), + // This models the stale iterator state after `new()` saw one large + // node and queued only the first peer segment. + stack: vec![ID::new(1, 0)], + }; + + let first = iter.next().expect("first segment should be yielded"); + assert_eq!(first.data.id_start(), ID::new(1, 0)); + assert_eq!(first.slice, 0..5); + + let second = iter.next().expect("second segment should be re-queued"); + assert_eq!(second.data.id_start(), ID::new(1, 5)); + assert_eq!(second.slice, 0..2); + + assert!(iter.next().is_none()); + } + + /// Regression: before the fix, `DagCausalIter::new` would push both + /// `(peer=1, counter=0)` and `(peer=1, counter=5)` onto the initial + /// stack because neither node has any *in-target* dependency. The LIFO + /// pop would then surface `(peer=1, counter=5)` first while + /// `target_span.min()` is still `0`, tripping the causal-order + /// invariant (historically: "slice_end > slice_from" / "counter < + /// target_span.min()"). With the fix the iter synthesizes a per-peer + /// ordering edge so the second node is only released after the first is + /// consumed. + #[test] + fn two_concurrent_same_peer_nodes_visit_in_counter_order() { + let first = DummyNode { + id: ID::new(1, 0), + lamport: 10, + len: 5, + deps: Frontiers::default(), + }; + // `second` is concurrent with `first` from peer 1's perspective: + // its only dep lives outside the target span (peer 2), so the BFS + // records zero in-degree and would historically race to the stack + // alongside `first`. + let second = DummyNode { + id: ID::new(1, 5), + lamport: 20, + len: 5, + deps: ID::new(2, 0).into(), + }; + let side = DummyNode { + id: ID::new(2, 0), + lamport: 0, + len: 1, + deps: Frontiers::default(), + }; + + let mut vv = VersionVector::default(); + vv.set_end(first.id_end()); + vv.set_end(second.id_end()); + vv.set_end(side.id_end()); + + let dag = DummyDag { + frontier: second.id_last().into(), + nodes: [ + (first.id_start(), first), + (second.id_start(), second), + (side.id_start(), side), + ] + .into_iter() + .collect(), + vv, + }; + + // Target only peer 1. `second`'s dep on (peer 2, 0) is thus + // *outside* the target vector — the exact condition that made both + // same-peer nodes reach the stack concurrently before the fix. + let mut target = IdSpanVector::default(); + target.insert(1, CounterSpan::new(0, 10)); + + let mut iter = DagCausalIter::new(&dag, Frontiers::default(), target); + + let a = iter.next().expect("first peer-1 segment"); + assert_eq!(a.data.id_start(), ID::new(1, 0)); + assert_eq!(a.slice, 0..5); + + let b = iter.next().expect("second peer-1 segment"); + assert_eq!(b.data.id_start(), ID::new(1, 5)); + assert_eq!(b.slice, 0..5); + + assert!(iter.next().is_none()); + } + + #[test] + fn larger_node_only_advances_consumed_slice() { + let node = DummyNode { + id: ID::new(1, 0), + lamport: 0, + len: 10, + deps: Frontiers::default(), + }; + let mut vv = VersionVector::default(); + vv.set_end(node.id_end()); + let dag = DummyDag { + frontier: node.id_last().into(), + nodes: [(node.id_start(), node)].into_iter().collect(), + vv, + }; + + let mut target = IdSpanVector::default(); + target.insert(1, CounterSpan::new(0, 7)); + let mut iter = DagCausalIter { + dag: &dag, + frontier: Frontiers::default(), + target, + out_degrees: Default::default(), + succ: BTreeMap::default(), + stack: vec![ID::new(1, 0)], + }; + + let item = iter.next().expect("target slice should be yielded"); + assert_eq!(item.slice, 0..7); + assert_eq!(iter.target.get(&1).unwrap().content_len(), 0); + } +} diff --git a/vendor/loro-internal/src/dag/mermaid.rs b/vendor/loro-internal/src/dag/mermaid.rs new file mode 100644 index 0000000..f8d7f40 --- /dev/null +++ b/vendor/loro-internal/src/dag/mermaid.rs @@ -0,0 +1,320 @@ +use super::*; +#[allow(dead_code)] +struct BreakPoints { + break_points: FxHashMap<PeerID, FxHashSet<Counter>>, + /// start ID to ID. The target ID may be in the middle of an op. + /// + /// only includes links across different clients + links: FxHashMap<ID, Vec<ID>>, +} + +#[allow(dead_code)] +struct Output { + clients: FxHashMap<PeerID, Vec<IdSpan>>, + /// start ID to start ID. + /// + /// only includes links across different clients + links: FxHashMap<ID, Vec<ID>>, +} + +#[allow(dead_code)] +fn to_str(output: Output) -> String { + let mut s = String::new(); + let mut indent_level = 0; + macro_rules! new_line { + () => { + s += "\n"; + for _ in 0..indent_level { + s += " "; + } + }; + } + s += "flowchart RL"; + indent_level += 1; + new_line!(); + for (client_id, spans) in output.clients.iter() { + s += format!("subgraph peer{client_id}").as_str(); + new_line!(); + let mut is_first = true; + for id_span in spans.iter().rev() { + if !is_first { + s += " --> " + } + + is_first = false; + s += format!( + "{}-{}(\"c{}: [{}, {})\")", + id_span.peer, + id_span.counter.start, + id_span.peer, + id_span.counter.start, + id_span.counter.end, + ) + .as_str(); + } + + new_line!(); + s += "end"; + new_line!(); + new_line!(); + } + + for (id_from, id_tos) in output.links.iter() { + for id_to in id_tos.iter() { + s += format!( + "{}-{} --> {}-{}", + id_from.peer, id_from.counter, id_to.peer, id_to.counter + ) + .as_str(); + new_line!(); + } + } + + s +} + +#[allow(dead_code)] +fn break_points_to_output(input: BreakPoints) -> Output { + let mut output = Output { + clients: FxHashMap::default(), + links: FxHashMap::default(), + }; + let breaks: FxHashMap<PeerID, Vec<Counter>> = input + .break_points + .into_iter() + .map(|(client_id, set)| { + let mut vec: Vec<Counter> = set.iter().cloned().collect(); + vec.sort(); + (client_id, vec) + }) + .collect(); + for (client_id, break_points) in breaks.iter() { + let mut spans = Vec::with_capacity(break_points.len()); + for (from, to) in break_points.iter().zip(break_points.iter().skip(1)) { + spans.push(IdSpan::new(*client_id, *from, *to)); + } + output.clients.insert(*client_id, spans); + } + + for (id_from, id_tos) in input.links.iter() { + for id_to in id_tos { + let client_breaks = breaks.get(&id_to.peer).unwrap(); + match client_breaks.binary_search(&id_to.counter) { + Ok(_) => { + output.links.entry(*id_from).or_default().push(*id_to); + } + Err(index) => { + output + .links + .entry(*id_from) + .or_default() + .push(ID::new(id_to.peer, client_breaks[index - 1])); + } + } + } + } + output +} + +#[allow(dead_code)] +fn get_dag_break_points<T: DagNode>(dag: &impl Dag<Node = T>) -> BreakPoints { + let mut break_points = BreakPoints { + break_points: FxHashMap::default(), + links: FxHashMap::default(), + }; + + for node in dag.iter() { + let id = node.id_start(); + let set = break_points.break_points.entry(id.peer).or_default(); + set.insert(id.counter); + set.insert(id.counter + node.content_len() as Counter); + for dep in node.deps().iter() { + if dep.peer == id.peer { + continue; + } + + break_points + .break_points + .entry(dep.peer) + .or_default() + .insert(dep.counter); + break_points.links.entry(id).or_default().push(dep); + } + } + + break_points +} + +#[allow(dead_code)] +pub(crate) fn dag_to_mermaid<T: DagNode>(dag: &impl Dag<Node = T>) -> String { + to_str(break_points_to_output(get_dag_break_points(dag))) +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use loro_common::{HasId, HasIdSpan}; + use rle::{HasLength, Sliceable}; + + use super::*; + + #[derive(Clone, Debug)] + struct TestNode { + id: ID, + len: usize, + lamport: Lamport, + deps: Frontiers, + } + + impl DagNode for TestNode { + fn deps(&self) -> &Frontiers { + &self.deps + } + } + + impl HasId for TestNode { + fn id_start(&self) -> ID { + self.id + } + } + + impl HasLamport for TestNode { + fn lamport(&self) -> Lamport { + self.lamport + } + } + + impl HasLength for TestNode { + fn content_len(&self) -> usize { + self.len + } + } + + impl Sliceable for TestNode { + fn slice(&self, _from: usize, _to: usize) -> Self { + self.clone() + } + } + + #[derive(Debug)] + struct TestDag { + nodes: BTreeMap<ID, TestNode>, + vv: VersionVector, + frontier: Frontiers, + } + + impl TestDag { + fn new(nodes: impl IntoIterator<Item = TestNode>, frontier: Frontiers) -> Self { + let mut vv = VersionVector::default(); + let nodes = nodes + .into_iter() + .map(|node| { + vv.set_end(node.id_end()); + (node.id_start(), node) + }) + .collect(); + Self { + nodes, + vv, + frontier, + } + } + } + + impl Dag for TestDag { + type Node = TestNode; + + fn get(&self, id: ID) -> Option<Self::Node> { + self.nodes + .range(..=id) + .next_back() + .filter(|(_, node)| node.contains_id(id)) + .map(|(_, node)| node.clone()) + } + + fn frontier(&self) -> &Frontiers { + &self.frontier + } + + fn vv(&self) -> &VersionVector { + &self.vv + } + + fn contains(&self, id: ID) -> bool { + self.get(id).is_some() + } + } + + fn node( + peer: PeerID, + counter: Counter, + len: usize, + lamport: Lamport, + deps: Frontiers, + ) -> TestNode { + TestNode { + id: ID::new(peer, counter), + len, + lamport, + deps, + } + } + + #[test] + fn break_points_to_output_splits_spans_and_retargets_middle_links_to_span_starts() { + let mut break_points = FxHashMap::default(); + break_points.insert(1, FxHashSet::from_iter([0, 3])); + break_points.insert(2, FxHashSet::from_iter([0, 5, 10])); + let from = ID::new(1, 0); + let mut links = FxHashMap::default(); + links.insert(from, vec![ID::new(2, 7)]); + + let output = break_points_to_output(BreakPoints { + break_points, + links, + }); + + assert_eq!(output.clients.get(&1).unwrap(), &vec![IdSpan::new(1, 0, 3)]); + assert_eq!( + output.clients.get(&2).unwrap(), + &vec![IdSpan::new(2, 0, 5), IdSpan::new(2, 5, 10)] + ); + assert_eq!(output.links.get(&from).unwrap(), &vec![ID::new(2, 5)]); + } + + #[test] + fn dag_to_mermaid_includes_peer_subgraphs_split_spans_and_cross_peer_edges() { + let first = node(1, 0, 2, 0, Frontiers::default()); + let second = node(2, 0, 1, 3, ID::new(1, 1).into()); + let dag = TestDag::new(vec![first, second], ID::new(2, 0).into()); + + let graph = dag_to_mermaid(&dag); + + assert!(graph.starts_with("flowchart RL")); + assert!(graph.contains("subgraph peer1")); + assert!(graph.contains("subgraph peer2")); + assert!(graph.contains("1-0(\"c1: [0, 1)\")")); + assert!(graph.contains("1-1(\"c1: [1, 2)\")")); + assert!(graph.contains("2-0(\"c2: [0, 1)\")")); + assert!(graph.contains("2-0 --> 1-1")); + } + + #[test] + fn to_str_renders_all_links_without_requiring_hash_map_order() { + let output = Output { + clients: FxHashMap::from_iter([ + (1, vec![IdSpan::new(1, 0, 1), IdSpan::new(1, 1, 2)]), + (2, vec![IdSpan::new(2, 0, 1)]), + ]), + links: FxHashMap::from_iter([(ID::new(2, 0), vec![ID::new(1, 0), ID::new(1, 1)])]), + }; + + let graph = to_str(output); + + assert!(graph.contains("subgraph peer1")); + assert!(graph.contains("1-1(\"c1: [1, 2)\") --> 1-0(\"c1: [0, 1)\")")); + assert!(graph.contains("2-0 --> 1-0")); + assert!(graph.contains("2-0 --> 1-1")); + } +} diff --git a/vendor/loro-internal/src/dag/test.excalidraw b/vendor/loro-internal/src/dag/test.excalidraw new file mode 100644 index 0000000..bbb18b1 --- /dev/null +++ b/vendor/loro-internal/src/dag/test.excalidraw @@ -0,0 +1,4334 @@ +{ + "type": "excalidraw", + "version": 2, + "source": "https://marketplace.visualstudio.com/items?itemName=pomdtr.excalidraw-editor", + "elements": [ + { + "type": "text", + "version": 101, + "versionNonce": 883063978, + "isDeleted": false, + "id": "lhg64zlt-7Bh50s_bwPDh", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 263.48630115928825, + "y": -113.63915404458658, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 247, + "height": 25, + "seed": 127706155, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888070, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "Replay Base Tests", + "baseline": 18, + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "originalText": "Replay Base Tests" + }, + { + "type": "rectangle", + "version": 315, + "versionNonce": 978352886, + "isDeleted": false, + "id": "UFtnx7sfhV0uKBPc8bkjR", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 234.87301990928825, + "y": 593.3803772054134, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 56.71875, + "height": 53.90625, + "seed": 771228869, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "DvFA3B6P4HJIrrYLNfwWC", + "type": "arrow" + } + ], + "updated": 1666058888070, + "link": null, + "locked": false + }, + { + "type": "rectangle", + "version": 308, + "versionNonce": 759256938, + "isDeleted": false, + "id": "ndstLpUvl8l8gieSJBPWM", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 236.31442615928825, + "y": 492.0014709554134, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 51.8828125, + "height": 48.4921875, + "seed": 411378725, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "DvFA3B6P4HJIrrYLNfwWC", + "type": "arrow" + }, + { + "id": "lN2WY1kuFxjMAVkpFsGwW", + "type": "arrow" + }, + { + "id": "RU8Wyhtc02QcaaG6pQTMJ", + "type": "arrow" + } + ], + "updated": 1666058888070, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 532, + "versionNonce": 1135717430, + "isDeleted": false, + "id": "DvFA3B6P4HJIrrYLNfwWC", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 262.53317615928825, + "y": 547.0131897054134, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 1, + "height": 39.765625, + "seed": 653744005, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888070, + "link": null, + "locked": false, + "startBinding": { + "elementId": "ndstLpUvl8l8gieSJBPWM", + "focus": -0.03958466448687474, + "gap": 6.51953125 + }, + "endBinding": { + "elementId": "UFtnx7sfhV0uKBPc8bkjR", + "focus": -0.08757842935147449, + "gap": 6.6015625 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -1, + 39.765625 + ] + ] + }, + { + "type": "rectangle", + "version": 245, + "versionNonce": 1253497386, + "isDeleted": false, + "id": "URqECeM4WGZqAFI0abbR6", + "fillStyle": "cross-hatch", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 2, + "opacity": 100, + "angle": 0, + "x": 237.63473865928825, + "y": 382.3725647054134, + "strokeColor": "#e67700", + "backgroundColor": "transparent", + "width": 52.140625, + "height": 43.83203125, + "seed": 1133256421, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "lN2WY1kuFxjMAVkpFsGwW", + "type": "arrow" + }, + { + "id": "rsU49QVI8HgyJBtjILKZT", + "type": "arrow" + }, + { + "id": "4Xhxr95Fo3KM0W5_NblnS", + "type": "arrow" + } + ], + "updated": 1666058888070, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 551, + "versionNonce": 73053558, + "isDeleted": false, + "id": "lN2WY1kuFxjMAVkpFsGwW", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "angle": 0, + "x": 266.18161365928825, + "y": 434.3569397054134, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 3.11328125, + "height": 51.01953125, + "seed": 886110789, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888070, + "link": null, + "locked": false, + "startBinding": { + "elementId": "URqECeM4WGZqAFI0abbR6", + "focus": -0.15730547947414078, + "gap": 8.15234375 + }, + "endBinding": { + "elementId": "ndstLpUvl8l8gieSJBPWM", + "focus": -0.03906854855773698, + "gap": 6.625 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -3.11328125, + 51.01953125 + ] + ] + }, + { + "type": "rectangle", + "version": 229, + "versionNonce": 200148202, + "isDeleted": false, + "id": "WtyUQLscbyCgdCnYK_jNr", + "fillStyle": "cross-hatch", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 2, + "opacity": 100, + "angle": 0, + "x": 333.02536365928825, + "y": 382.2006897054134, + "strokeColor": "#e67700", + "backgroundColor": "transparent", + "width": 46.50390625, + "height": 47.48046875, + "seed": 329476517, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "RU8Wyhtc02QcaaG6pQTMJ", + "type": "arrow" + }, + { + "id": "ceD-EHtPmAHrld2ReqW1d", + "type": "arrow" + }, + { + "id": "gi633X0Z9XWBOZyYzVt0P", + "type": "arrow" + }, + { + "id": "aGZg71ALGFz6MuRal-TTz", + "type": "arrow" + }, + { + "id": "EE1SzT8racuV0SEacrH5H", + "type": "arrow" + } + ], + "updated": 1666058888070, + "link": null, + "locked": false + }, + { + "type": "rectangle", + "version": 214, + "versionNonce": 1972410038, + "isDeleted": false, + "id": "lSqDDXX9cdXC4LCluuQmS", + "fillStyle": "cross-hatch", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 2, + "opacity": 100, + "angle": 0, + "x": 419.02926990928825, + "y": 382.3374084554134, + "strokeColor": "#e67700", + "backgroundColor": "transparent", + "width": 50.58203125, + "height": 43.453125, + "seed": 19983621, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "KpyIcLVhnWpIY6J9Q8M3s", + "type": "arrow" + }, + { + "id": "Th-vLn9JQqbE80X8Pl1-U", + "type": "arrow" + }, + { + "id": "OzG5v9FzTWSKCdywOoGQL", + "type": "arrow" + } + ], + "updated": 1666058888070, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 456, + "versionNonce": 1517410218, + "isDeleted": false, + "id": "RU8Wyhtc02QcaaG6pQTMJ", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 325.62692615928825, + "y": 435.4702209554134, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 47.83203125, + "height": 47.4453125, + "seed": 485950565, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888070, + "link": null, + "locked": false, + "startBinding": { + "elementId": "WtyUQLscbyCgdCnYK_jNr", + "focus": 0.01865831404761865, + "gap": 7.3984375 + }, + "endBinding": { + "elementId": "ndstLpUvl8l8gieSJBPWM", + "focus": -0.358531455976611, + "gap": 9.0859375 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -47.83203125, + 47.4453125 + ] + ] + }, + { + "type": "arrow", + "version": 420, + "versionNonce": 536367094, + "isDeleted": false, + "id": "ceD-EHtPmAHrld2ReqW1d", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 345.79098865928825, + "y": 438.3452209554134, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 20.67578125, + "height": 99.421875, + "seed": 985870277, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888070, + "link": null, + "locked": false, + "startBinding": { + "elementId": "WtyUQLscbyCgdCnYK_jNr", + "focus": 0.6110590696052777, + "gap": 8.6640625 + }, + "endBinding": { + "elementId": "1Swh32YEcsSztjU6TVYMO", + "focus": 0.1403757111100622, + "gap": 6.3203125 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 20.67578125, + 99.421875 + ] + ] + }, + { + "type": "rectangle", + "version": 191, + "versionNonce": 913134186, + "isDeleted": false, + "id": "1Swh32YEcsSztjU6TVYMO", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 347.37692615928825, + "y": 544.0874084554134, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 43.8828125, + "height": 51.65625, + "seed": 1488121637, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "ceD-EHtPmAHrld2ReqW1d", + "type": "arrow" + } + ], + "updated": 1666058888070, + "link": null, + "locked": false + }, + { + "type": "rectangle", + "version": 181, + "versionNonce": 798417206, + "isDeleted": false, + "id": "7rpEPw0XEWSpd4zpGIL-i", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 456.69723865928825, + "y": 555.2280334554134, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 36.53125, + "height": 48.55078125, + "seed": 1429455493, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "gi633X0Z9XWBOZyYzVt0P", + "type": "arrow" + }, + { + "id": "KpyIcLVhnWpIY6J9Q8M3s", + "type": "arrow" + } + ], + "updated": 1666058888070, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 441, + "versionNonce": 1655403818, + "isDeleted": false, + "id": "gi633X0Z9XWBOZyYzVt0P", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 371.72848865928825, + "y": 442.6420959554134, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 115.453125, + "height": 106.890625, + "seed": 1694706149, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888070, + "link": null, + "locked": false, + "startBinding": { + "elementId": "WtyUQLscbyCgdCnYK_jNr", + "focus": 0.49474380369903664, + "gap": 12.9609375 + }, + "endBinding": { + "elementId": "7rpEPw0XEWSpd4zpGIL-i", + "focus": 1.0023527144670679, + "gap": 5.6953125 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 115.453125, + 106.890625 + ] + ] + }, + { + "type": "arrow", + "version": 435, + "versionNonce": 131156598, + "isDeleted": false, + "id": "KpyIcLVhnWpIY6J9Q8M3s", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 444.05661365928825, + "y": 433.2905334554134, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 36.18359375, + "height": 109.609375, + "seed": 1227793733, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888071, + "link": null, + "locked": false, + "startBinding": { + "elementId": "lSqDDXX9cdXC4LCluuQmS", + "focus": 0.30532272017379974, + "gap": 7.5 + }, + "endBinding": { + "elementId": "7rpEPw0XEWSpd4zpGIL-i", + "focus": 0.6606224867711618, + "gap": 12.328125 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 36.18359375, + 109.609375 + ] + ] + }, + { + "type": "rectangle", + "version": 442, + "versionNonce": 278347754, + "isDeleted": false, + "id": "CFSGkbwHAPWwmUPvyrNSU", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 246.38864490928825, + "y": 194.93506470541342, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 41.6796875, + "height": 41.82421874999999, + "seed": 1158919333, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "aGZg71ALGFz6MuRal-TTz", + "type": "arrow" + }, + { + "id": "WCsuKPIiyyv46Ci9BE954", + "type": "arrow" + } + ], + "updated": 1666058888071, + "link": null, + "locked": false + }, + { + "type": "rectangle", + "version": 201, + "versionNonce": 1466731446, + "isDeleted": false, + "id": "PX8R3GWFK-y4FAPfGXDWQ", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 241.00192615928825, + "y": -23.361810294586576, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 39, + "height": 43.90625, + "seed": 1415567365, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "vYg0q3zocHglNFtQ-Rzfb", + "type": "text" + }, + { + "id": "vYg0q3zocHglNFtQ-Rzfb", + "type": "text" + }, + { + "id": "g1I2bmNZBEIbE5bPbc9PO", + "type": "arrow" + }, + { + "type": "text", + "id": "vYg0q3zocHglNFtQ-Rzfb" + } + ], + "updated": 1666058888071, + "link": null, + "locked": false + }, + { + "type": "text", + "version": 56, + "versionNonce": 205238954, + "isDeleted": false, + "id": "vYg0q3zocHglNFtQ-Rzfb", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 246.00192615928825, + "y": -13.908685294586576, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 29, + "height": 23, + "seed": 554733413, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888071, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "A", + "baseline": 17, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "PX8R3GWFK-y4FAPfGXDWQ", + "originalText": "A" + }, + { + "type": "rectangle", + "version": 259, + "versionNonce": 747480310, + "isDeleted": false, + "id": "wkdtJfpB-XRjEMes0NHIG", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 338.02926990928825, + "y": -23.916497794586576, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 39, + "height": 43.90625, + "seed": 963861189, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "B0jO-HvbxLWHssI5X1XjY", + "type": "text" + }, + { + "id": "X8GhhoUwWv39DpajqYRWn", + "type": "arrow" + }, + { + "type": "text", + "id": "B0jO-HvbxLWHssI5X1XjY" + } + ], + "updated": 1666058888071, + "link": null, + "locked": false + }, + { + "type": "text", + "version": 117, + "versionNonce": 1749273962, + "isDeleted": false, + "id": "B0jO-HvbxLWHssI5X1XjY", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 343.02926990928825, + "y": -13.463372794586576, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 29, + "height": 23, + "seed": 103135781, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888071, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "B", + "baseline": 17, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "wkdtJfpB-XRjEMes0NHIG", + "originalText": "B" + }, + { + "type": "arrow", + "version": 305, + "versionNonce": 146380342, + "isDeleted": false, + "id": "aGZg71ALGFz6MuRal-TTz", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 267.8641585018744, + "y": 249.68115845541348, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 88.60298159582703, + "height": 125.39453124999994, + "seed": 1387909, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888071, + "link": null, + "locked": false, + "startBinding": { + "elementId": "CFSGkbwHAPWwmUPvyrNSU", + "focus": 0.6533881812518985, + "gap": 12.921875000000057 + }, + "endBinding": { + "elementId": "WtyUQLscbyCgdCnYK_jNr", + "focus": 0.5496088514101133, + "gap": 7.125 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 88.60298159582703, + 125.39453124999994 + ] + ] + }, + { + "type": "arrow", + "version": 364, + "versionNonce": 704286762, + "isDeleted": false, + "id": "Th-vLn9JQqbE80X8Pl1-U", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 285.62692615928825, + "y": 148.7884978967083, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 155.87566467544525, + "height": 226.02937930870513, + "seed": 645870821, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888071, + "link": null, + "locked": false, + "startBinding": { + "elementId": "hWhmUfN-whJHDhqK7HkDw", + "focus": -0.3630659075617793, + "gap": 5.17578125 + }, + "endBinding": { + "elementId": "lSqDDXX9cdXC4LCluuQmS", + "focus": 0.4308256364516943, + "gap": 7.51953125 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 155.87566467544525, + 226.02937930870513 + ] + ] + }, + { + "type": "rectangle", + "version": 231, + "versionNonce": 1960140662, + "isDeleted": false, + "id": "hWhmUfN-whJHDhqK7HkDw", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 240.19333240928825, + "y": 108.20459595541342, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 40.2578125, + "height": 45.4921875, + "seed": 888229957, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "WCsuKPIiyyv46Ci9BE954", + "type": "arrow" + }, + { + "id": "Th-vLn9JQqbE80X8Pl1-U", + "type": "arrow" + }, + { + "id": "g1I2bmNZBEIbE5bPbc9PO", + "type": "arrow" + }, + { + "id": "SJqqF6rk1YusFfgDKDZIX", + "type": "arrow" + } + ], + "updated": 1666058888071, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 452, + "versionNonce": 1967848170, + "isDeleted": false, + "id": "WCsuKPIiyyv46Ci9BE954", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 268.16418593279104, + "y": 159.16553345541342, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 0.11351614941020216, + "height": 32.2109375, + "seed": 424214437, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888071, + "link": null, + "locked": false, + "startBinding": { + "elementId": "hWhmUfN-whJHDhqK7HkDw", + "focus": -0.38312080421234723, + "gap": 5.46875 + }, + "endBinding": { + "elementId": "CFSGkbwHAPWwmUPvyrNSU", + "focus": 0.05429266252944664, + "gap": 3.55859375 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 0.11351614941020216, + 32.2109375 + ] + ] + }, + { + "type": "rectangle", + "version": 94, + "versionNonce": 354812086, + "isDeleted": false, + "id": "sHYBFDblul5QqJjxXun--", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 369.89255115928825, + "y": 81.69287720541342, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 40.76953125, + "height": 44.6484375, + "seed": 699646725, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "EE1SzT8racuV0SEacrH5H", + "type": "arrow" + }, + { + "id": "X8GhhoUwWv39DpajqYRWn", + "type": "arrow" + }, + { + "id": "T2wLMX7gk4q4Wlq65lvOL", + "type": "arrow" + } + ], + "updated": 1666058888071, + "link": null, + "locked": false + }, + { + "type": "rectangle", + "version": 71, + "versionNonce": 952110506, + "isDeleted": false, + "id": "MIEh2o7onmi2XVMBPNwtl", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 486.58786365928825, + "y": 145.29443970541342, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 50.74609375, + "height": 53.9140625, + "seed": 447683173, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "rsU49QVI8HgyJBtjILKZT", + "type": "arrow" + }, + { + "id": "T2wLMX7gk4q4Wlq65lvOL", + "type": "arrow" + }, + { + "id": "EtBC7WdsIkjxflHPwhLE3", + "type": "arrow" + } + ], + "updated": 1666058888071, + "link": null, + "locked": false + }, + { + "type": "rectangle", + "version": 87, + "versionNonce": 1028684278, + "isDeleted": false, + "id": "h7rDKyrC7qd8W2VaDHOVo", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 589.7050511592882, + "y": 230.97412720541342, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 60.6328125, + "height": 52.44140625, + "seed": 889750981, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "OzG5v9FzTWSKCdywOoGQL", + "type": "arrow" + }, + { + "id": "EtBC7WdsIkjxflHPwhLE3", + "type": "arrow" + } + ], + "updated": 1666058888071, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 170, + "versionNonce": 1501874282, + "isDeleted": false, + "id": "OzG5v9FzTWSKCdywOoGQL", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 601.5175511592882, + "y": 292.5288147054134, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 141.015625, + "height": 86.015625, + "seed": 1272808741, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888071, + "link": null, + "locked": false, + "startBinding": { + "elementId": "h7rDKyrC7qd8W2VaDHOVo", + "focus": -0.5378118988727681, + "gap": 9.11328125 + }, + "endBinding": { + "elementId": "lSqDDXX9cdXC4LCluuQmS", + "focus": -0.42120469532718297, + "gap": 3.79296875 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -141.015625, + 86.015625 + ] + ] + }, + { + "type": "arrow", + "version": 156, + "versionNonce": 72993590, + "isDeleted": false, + "id": "rsU49QVI8HgyJBtjILKZT", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 506.93161365928825, + "y": 207.66162720541342, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 236.51953125, + "height": 171.1328125, + "seed": 1922799749, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888071, + "link": null, + "locked": false, + "startBinding": { + "elementId": "MIEh2o7onmi2XVMBPNwtl", + "focus": -0.7011101066042149, + "gap": 8.453125 + }, + "endBinding": { + "elementId": "URqECeM4WGZqAFI0abbR6", + "focus": -0.5061734503271241, + "gap": 3.578125 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -236.51953125, + 171.1328125 + ] + ] + }, + { + "type": "arrow", + "version": 203, + "versionNonce": 1600400170, + "isDeleted": false, + "id": "EE1SzT8racuV0SEacrH5H", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 394.04880115928825, + "y": 132.08350220541342, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 29.9609375, + "height": 246.046875, + "seed": 1929396197, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888071, + "link": null, + "locked": false, + "startBinding": { + "elementId": "sHYBFDblul5QqJjxXun--", + "focus": -0.3111741555994148, + "gap": 5.7421875 + }, + "endBinding": { + "elementId": "WtyUQLscbyCgdCnYK_jNr", + "focus": 0.1692275109296219, + "gap": 4.0703125 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -29.9609375, + 246.046875 + ] + ] + }, + { + "type": "arrow", + "version": 152, + "versionNonce": 1487336566, + "isDeleted": false, + "id": "X8GhhoUwWv39DpajqYRWn", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 357.83786365928825, + "y": 26.669439705413424, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 28.1484375, + "height": 42.72265625, + "seed": 51968837, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888071, + "link": null, + "locked": false, + "startBinding": { + "elementId": "wkdtJfpB-XRjEMes0NHIG", + "focus": 0.5463571651085232, + "gap": 6.6796875 + }, + "endBinding": { + "elementId": "sHYBFDblul5QqJjxXun--", + "focus": 0.5277962544041825, + "gap": 12.30078125 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 28.1484375, + 42.72265625 + ] + ] + }, + { + "type": "arrow", + "version": 145, + "versionNonce": 550057450, + "isDeleted": false, + "id": "T2wLMX7gk4q4Wlq65lvOL", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 420.33786365928825, + "y": 109.02100220541342, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 88.5234375, + "height": 26.375, + "seed": 994265765, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888071, + "link": null, + "locked": false, + "startBinding": { + "elementId": "sHYBFDblul5QqJjxXun--", + "focus": -0.13918168745815823, + "gap": 9.67578125 + }, + "endBinding": { + "elementId": "MIEh2o7onmi2XVMBPNwtl", + "focus": 1.041000043955478, + "gap": 9.8984375 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 88.5234375, + 26.375 + ] + ] + }, + { + "type": "arrow", + "version": 170, + "versionNonce": 335345078, + "isDeleted": false, + "id": "EtBC7WdsIkjxflHPwhLE3", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 548.1972386592882, + "y": 171.43506470541342, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 72.3203125, + "height": 55.29296875, + "seed": 1277996549, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888071, + "link": null, + "locked": false, + "startBinding": { + "elementId": "MIEh2o7onmi2XVMBPNwtl", + "focus": -0.6152607989398555, + "gap": 10.86328125 + }, + "endBinding": { + "elementId": "h7rDKyrC7qd8W2VaDHOVo", + "focus": 0.6244234688285908, + "gap": 4.24609375 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 72.3203125, + 55.29296875 + ] + ] + }, + { + "type": "arrow", + "version": 342, + "versionNonce": 1858005162, + "isDeleted": false, + "id": "g1I2bmNZBEIbE5bPbc9PO", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 256.4971091669645, + "y": 29.618658455413424, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 4.3475249654532035, + "height": 65.71875, + "seed": 1959961957, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888071, + "link": null, + "locked": false, + "startBinding": { + "elementId": "PX8R3GWFK-y4FAPfGXDWQ", + "focus": 0.2891038770717789, + "gap": 9.07421875 + }, + "endBinding": { + "elementId": "hWhmUfN-whJHDhqK7HkDw", + "focus": 0.13304920019960997, + "gap": 12.8671875 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 4.3475249654532035, + 65.71875 + ] + ] + }, + { + "type": "rectangle", + "version": 144, + "versionNonce": 260099830, + "isDeleted": false, + "id": "anui-58DIlGAbjV4UqtEB", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 186.06833240928825, + "y": 259.5795959554134, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 35.375, + "height": 48.05859375, + "seed": 948089029, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "SJqqF6rk1YusFfgDKDZIX", + "type": "arrow" + }, + { + "id": "4Xhxr95Fo3KM0W5_NblnS", + "type": "arrow" + } + ], + "updated": 1666058888071, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 175, + "versionNonce": 1089487722, + "isDeleted": false, + "id": "SJqqF6rk1YusFfgDKDZIX", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 229.78317615928825, + "y": 140.61475220541342, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 26.859375, + "height": 109.1171875, + "seed": 1423593509, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888071, + "link": null, + "locked": false, + "startBinding": { + "elementId": "hWhmUfN-whJHDhqK7HkDw", + "focus": 1.0945410835846927, + "gap": 10.41015625 + }, + "endBinding": { + "elementId": "anui-58DIlGAbjV4UqtEB", + "focus": -0.38855870595300823, + "gap": 9.84765625 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -26.859375, + 109.1171875 + ] + ] + }, + { + "type": "arrow", + "version": 180, + "versionNonce": 934772790, + "isDeleted": false, + "id": "4Xhxr95Fo3KM0W5_NblnS", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 209.10348865928825, + "y": 316.2319397054134, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 36.80859375, + "height": 60.609375, + "seed": 2009531269, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888072, + "link": null, + "locked": false, + "startBinding": { + "elementId": "anui-58DIlGAbjV4UqtEB", + "focus": 0.4480882059017431, + "gap": 8.59375 + }, + "endBinding": { + "elementId": "URqECeM4WGZqAFI0abbR6", + "focus": -0.028542558229941315, + "gap": 5.53125 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 36.80859375, + 60.609375 + ] + ] + }, + { + "type": "text", + "version": 131, + "versionNonce": 1638417962, + "isDeleted": false, + "id": "YlP9Bsi-02bMH0FiCjimk", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1338.8156749765176, + "y": -115.61648283257028, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 95, + "height": 25, + "seed": 1642740997, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888072, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "Find Path", + "baseline": 18, + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "originalText": "Find Path" + }, + { + "type": "rectangle", + "version": 461, + "versionNonce": 545655158, + "isDeleted": false, + "id": "ar7IzDq-viaTUF4A87b_3", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 2, + "opacity": 100, + "angle": 0, + "x": 1350.2562583548645, + "y": 297.740958380131, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 37.91699739062982, + "height": 94.91248590244665, + "seed": 118309546, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "OLV3s1miKo9A3zrGxFock", + "type": "arrow" + }, + { + "id": "0vxegaqxPquMPgd_r72TA", + "type": "arrow" + }, + { + "id": "unCTd-_GGU2aGYrHtH0Xs", + "type": "arrow" + }, + { + "id": "XWSRH57gG_wU8RgnjMLPE", + "type": "arrow" + } + ], + "updated": 1666058888072, + "link": null, + "locked": false + }, + { + "type": "rectangle", + "version": 334, + "versionNonce": 433189098, + "isDeleted": false, + "id": "VjZnajfB7LKe5DMAoo0Do", + "fillStyle": "cross-hatch", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 2, + "opacity": 100, + "angle": 0, + "x": 1427.2168589704975, + "y": 345.30969428257765, + "strokeColor": "#e67700", + "backgroundColor": "transparent", + "width": 50.58203125, + "height": 43.453125, + "seed": 845372778, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "4EwKyIvTMtoyxqVHUbeGd", + "type": "arrow" + }, + { + "id": "E2mIJ2Sl4cVsW3XGconh3", + "type": "arrow" + }, + { + "id": "TggNAReZxluYM_0WrlwOr", + "type": "arrow" + } + ], + "updated": 1666058888072, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 1123, + "versionNonce": 422668982, + "isDeleted": false, + "id": "0vxegaqxPquMPgd_r72TA", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1364.6693370711946, + "y": 401.4742259036285, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 72.00486815355634, + "height": 146.2109087738151, + "seed": 698884138, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888072, + "link": null, + "locked": false, + "startBinding": { + "focus": -0.3965191378313845, + "gap": 8.159100701385455, + "elementId": "PDhm6OLJ3n51SVKIISduG" + }, + "endBinding": { + "focus": -0.13518700591321753, + "gap": 5.03237207597158, + "elementId": "MDw8O0rja4i4fRNIEVJ3V" + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -72.00486815355634, + 146.2109087738151 + ] + ] + }, + { + "type": "rectangle", + "version": 307, + "versionNonce": 1559774122, + "isDeleted": false, + "id": "MDw8O0rja4i4fRNIEVJ3V", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1260.210836693423, + "y": 552.7175067534151, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 43.8828125, + "height": 51.65625, + "seed": 1220971242, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "0vxegaqxPquMPgd_r72TA", + "type": "arrow" + } + ], + "updated": 1666058888072, + "link": null, + "locked": false + }, + { + "type": "rectangle", + "version": 222, + "versionNonce": 1079944182, + "isDeleted": false, + "id": "i1kjJhOQKEyXNdqTQ4aN7", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1497.8783853089833, + "y": 548.2801914995628, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 36.53125, + "height": 48.55078125, + "seed": 910794154, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "unCTd-_GGU2aGYrHtH0Xs", + "type": "arrow" + }, + { + "id": "4EwKyIvTMtoyxqVHUbeGd", + "type": "arrow" + } + ], + "updated": 1666058888072, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 944, + "versionNonce": 1967537770, + "isDeleted": false, + "id": "unCTd-_GGU2aGYrHtH0Xs", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1392.5188356116166, + "y": 402.286327945094, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 137.47301625611294, + "height": 141.3501859235961, + "seed": 257710186, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888072, + "link": null, + "locked": false, + "startBinding": { + "focus": 0.49474380369903687, + "gap": 10.567710822520771, + "elementId": "ar7IzDq-viaTUF4A87b_3" + }, + "endBinding": { + "focus": 1.0023527144670679, + "gap": 4.643677630872599, + "elementId": "i1kjJhOQKEyXNdqTQ4aN7" + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 137.47301625611294, + 141.3501859235961 + ] + ] + }, + { + "type": "arrow", + "version": 718, + "versionNonce": 403879222, + "isDeleted": false, + "id": "4EwKyIvTMtoyxqVHUbeGd", + "fillStyle": "cross-hatch", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1455.0832738563568, + "y": 396.26281928257765, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 63.74251748189454, + "height": 139.68924721698505, + "seed": 331987754, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888072, + "link": null, + "locked": false, + "startBinding": { + "focus": 0.3053227201737998, + "gap": 7.5, + "elementId": "VjZnajfB7LKe5DMAoo0Do" + }, + "endBinding": { + "focus": 0.6606224867711619, + "gap": 12.328125, + "elementId": "i1kjJhOQKEyXNdqTQ4aN7" + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 63.74251748189454, + 139.68924721698505 + ] + ] + }, + { + "type": "rectangle", + "version": 593, + "versionNonce": 797368618, + "isDeleted": false, + "id": "RTqCReH94hrfFOfKvX3Xb", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1237.3418614357154, + "y": 239.7958129496575, + "strokeColor": "#d9480f", + "backgroundColor": "transparent", + "width": 41.6796875, + "height": 41.82421874999999, + "seed": 1375520234, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "Gm1LhBSST9OO99UkA6y8X", + "type": "arrow" + }, + { + "id": "PIZ_GY_wTp8sNyDtJZcnP", + "type": "arrow" + } + ], + "updated": 1666058888072, + "link": null, + "locked": false + }, + { + "type": "rectangle", + "version": 242, + "versionNonce": 431136374, + "isDeleted": false, + "id": "v3ufybsWQdzjQGQnJYauJ", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1282.1830728089833, + "y": -30.30965225043724, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 39, + "height": 43.90625, + "seed": 1392539818, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "cVT4Yqnzt5w3srqK1yI08", + "type": "text" + }, + { + "id": "cVT4Yqnzt5w3srqK1yI08", + "type": "text" + }, + { + "id": "ScvEbRxtwuaacH97zK60u", + "type": "arrow" + }, + { + "type": "text", + "id": "cVT4Yqnzt5w3srqK1yI08" + } + ], + "updated": 1666058888072, + "link": null, + "locked": false + }, + { + "type": "text", + "version": 97, + "versionNonce": 119876586, + "isDeleted": false, + "id": "cVT4Yqnzt5w3srqK1yI08", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1287.1830728089833, + "y": -20.85652725043724, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 29, + "height": 23, + "seed": 1182782314, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888072, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "A", + "baseline": 17, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "v3ufybsWQdzjQGQnJYauJ", + "originalText": "A" + }, + { + "type": "rectangle", + "version": 300, + "versionNonce": 1241735094, + "isDeleted": false, + "id": "EliJKYDq1GH48V4c34Lk1", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1379.2104165589833, + "y": -30.86433975043724, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 39, + "height": 43.90625, + "seed": 784717354, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "HgWFwyAcCrdOtSBQ3AMZC", + "type": "text" + }, + { + "id": "Y38QXVN9QX9BPQY-2ARsJ", + "type": "arrow" + }, + { + "type": "text", + "id": "HgWFwyAcCrdOtSBQ3AMZC" + } + ], + "updated": 1666058888072, + "link": null, + "locked": false + }, + { + "type": "text", + "version": 158, + "versionNonce": 1378623146, + "isDeleted": false, + "id": "HgWFwyAcCrdOtSBQ3AMZC", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1384.2104165589833, + "y": -20.41121475043724, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 29, + "height": 23, + "seed": 213745898, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888072, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "B", + "baseline": 17, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "EliJKYDq1GH48V4c34Lk1", + "originalText": "B" + }, + { + "type": "arrow", + "version": 657, + "versionNonce": 1294596342, + "isDeleted": false, + "id": "E2mIJ2Sl4cVsW3XGconh3", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1326.6992629818317, + "y": 143.9103142656606, + "strokeColor": "#d9480f", + "backgroundColor": "transparent", + "width": 123.98105485129145, + "height": 193.77103893976562, + "seed": 200397738, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888072, + "link": null, + "locked": false, + "startBinding": { + "focus": -0.36231278326472255, + "gap": 5.17578125, + "elementId": "kKu5Ydyyyeh2KCFqMwJS4" + }, + "endBinding": { + "focus": 0.4326012077832137, + "gap": 7.628341077151447, + "elementId": "VjZnajfB7LKe5DMAoo0Do" + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 123.98105485129145, + 193.77103893976562 + ] + ] + }, + { + "type": "rectangle", + "version": 276, + "versionNonce": 1833351530, + "isDeleted": false, + "id": "kKu5Ydyyyeh2KCFqMwJS4", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1281.2656692318317, + "y": 101.25675399956276, + "strokeColor": "#d9480f", + "backgroundColor": "transparent", + "width": 40.2578125, + "height": 45.4921875, + "seed": 781045354, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "Gm1LhBSST9OO99UkA6y8X", + "type": "arrow" + }, + { + "id": "E2mIJ2Sl4cVsW3XGconh3", + "type": "arrow" + }, + { + "id": "ScvEbRxtwuaacH97zK60u", + "type": "arrow" + } + ], + "updated": 1666058888072, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 848, + "versionNonce": 2058054198, + "isDeleted": false, + "id": "Gm1LhBSST9OO99UkA6y8X", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1301.5745444918389, + "y": 152.10888167241131, + "strokeColor": "#d9480f", + "backgroundColor": "transparent", + "width": 33.471215097623144, + "height": 84.01952770009473, + "seed": 2036101418, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888072, + "link": null, + "locked": false, + "startBinding": { + "focus": -0.3812012413933706, + "gap": 5.359940172848553, + "elementId": "kKu5Ydyyyeh2KCFqMwJS4" + }, + "endBinding": { + "focus": 0.05283911803202242, + "gap": 3.667403577151447, + "elementId": "RTqCReH94hrfFOfKvX3Xb" + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -33.471215097623144, + 84.01952770009473 + ] + ] + }, + { + "type": "rectangle", + "version": 144, + "versionNonce": 1740635178, + "isDeleted": false, + "id": "61dxkeeBxIqh92cwqJ1lM", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1411.0736978089833, + "y": 74.74503524956276, + "strokeColor": "#1864ab", + "backgroundColor": "transparent", + "width": 40.76953125, + "height": 44.6484375, + "seed": 533249002, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "Y38QXVN9QX9BPQY-2ARsJ", + "type": "arrow" + }, + { + "id": "RPqJsAAGLOdXHUSB03TtV", + "type": "arrow" + }, + { + "id": "XWSRH57gG_wU8RgnjMLPE", + "type": "arrow" + } + ], + "updated": 1666058888072, + "link": null, + "locked": false + }, + { + "type": "rectangle", + "version": 116, + "versionNonce": 1902949238, + "isDeleted": false, + "id": "dLAlZSp2rgCOTpB7iMpyy", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1527.7690103089833, + "y": 138.34659774956276, + "strokeColor": "#1864ab", + "backgroundColor": "transparent", + "width": 50.74609375, + "height": 53.9140625, + "seed": 803057322, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "RPqJsAAGLOdXHUSB03TtV", + "type": "arrow" + }, + { + "id": "TggNAReZxluYM_0WrlwOr", + "type": "arrow" + } + ], + "updated": 1666058888072, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 517, + "versionNonce": 797107946, + "isDeleted": false, + "id": "TggNAReZxluYM_0WrlwOr", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1544.1200151918972, + "y": 204.47533658893383, + "strokeColor": "#364fc7", + "backgroundColor": "transparent", + "width": 69.09497933411285, + "height": 137.03534395324658, + "seed": 1044793706, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888072, + "link": null, + "locked": false, + "startBinding": { + "focus": -0.27534455299140825, + "gap": 12.214676339371067, + "elementId": "dLAlZSp2rgCOTpB7iMpyy" + }, + "endBinding": { + "focus": 0.26615030765156217, + "gap": 3.7990137403972426, + "elementId": "VjZnajfB7LKe5DMAoo0Do" + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -69.09497933411285, + 137.03534395324658 + ] + ] + }, + { + "type": "arrow", + "version": 889, + "versionNonce": 733140150, + "isDeleted": false, + "id": "XWSRH57gG_wU8RgnjMLPE", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1427.4290168688203, + "y": 128.0884665163548, + "strokeColor": "#364fc7", + "backgroundColor": "transparent", + "width": 36.397392064383894, + "height": 161.61331552909485, + "seed": 307072042, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888072, + "link": null, + "locked": false, + "startBinding": { + "focus": -0.12673028883550302, + "gap": 8.692142102217417, + "elementId": "61dxkeeBxIqh92cwqJ1lM" + }, + "endBinding": { + "focus": 0.31432596950919534, + "gap": 8.532211308753404, + "elementId": "ar7IzDq-viaTUF4A87b_3" + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -36.397392064383894, + 161.61331552909485 + ] + ] + }, + { + "type": "arrow", + "version": 302, + "versionNonce": 1025145258, + "isDeleted": false, + "id": "Y38QXVN9QX9BPQY-2ARsJ", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1398.6789464539738, + "y": 19.830407576714318, + "strokeColor": "#364fc7", + "backgroundColor": "transparent", + "width": 27.97996373105775, + "height": 42.725507914574635, + "seed": 1373533930, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888072, + "link": null, + "locked": false, + "startBinding": { + "focus": 0.5580789543163621, + "gap": 6.7884973271515605, + "elementId": "EliJKYDq1GH48V4c34Lk1" + }, + "endBinding": { + "focus": 0.5164516591849347, + "gap": 12.19197142284844, + "elementId": "61dxkeeBxIqh92cwqJ1lM" + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 27.97996373105775, + 42.725507914574635 + ] + ] + }, + { + "type": "arrow", + "version": 292, + "versionNonce": 321048054, + "isDeleted": false, + "id": "RPqJsAAGLOdXHUSB03TtV", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1461.0276308555176, + "y": 102.16607065982501, + "strokeColor": "#364fc7", + "backgroundColor": "transparent", + "width": 88.74199015486556, + "height": 26.39089941688931, + "seed": 763627946, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888072, + "link": null, + "locked": false, + "startBinding": { + "focus": -0.1330668246148966, + "gap": 9.458161595696765, + "elementId": "61dxkeeBxIqh92cwqJ1lM" + }, + "endBinding": { + "focus": 1.0359692074076057, + "gap": 9.78962767284844, + "elementId": "dLAlZSp2rgCOTpB7iMpyy" + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 88.74199015486556, + 26.39089941688931 + ] + ] + }, + { + "type": "arrow", + "version": 474, + "versionNonce": 1068610666, + "isDeleted": false, + "id": "ScvEbRxtwuaacH97zK60u", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1297.6782558166597, + "y": 22.562006672411314, + "strokeColor": "#d9480f", + "backgroundColor": "transparent", + "width": 4.274858880633019, + "height": 65.71875, + "seed": 208225386, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888072, + "link": null, + "locked": false, + "startBinding": { + "focus": 0.28876032726731193, + "gap": 8.965408922848553, + "elementId": "v3ufybsWQdzjQGQnJYauJ" + }, + "endBinding": { + "focus": 0.13338192970579654, + "gap": 12.975997327151447, + "elementId": "kKu5Ydyyyeh2KCFqMwJS4" + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 4.274858880633019, + 65.71875 + ] + ] + }, + { + "type": "rectangle", + "version": 172, + "versionNonce": 348233526, + "isDeleted": false, + "id": "PDhm6OLJ3n51SVKIISduG", + "fillStyle": "hachure", + "strokeWidth": 4, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1350.6704030660512, + "y": 344.5622776479856, + "strokeColor": "#e67700", + "backgroundColor": "transparent", + "width": 36.1762450326662, + "height": 48.752847554257414, + "seed": 945366826, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "PIZ_GY_wTp8sNyDtJZcnP", + "type": "arrow" + }, + { + "id": "0vxegaqxPquMPgd_r72TA", + "type": "arrow" + } + ], + "updated": 1666058888072, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 575, + "versionNonce": 1226020650, + "isDeleted": false, + "id": "PIZ_GY_wTp8sNyDtJZcnP", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1272.6633717593447, + "y": 291.80621417637605, + "strokeColor": "#d9480f", + "backgroundColor": "transparent", + "width": 70.51754950478039, + "height": 53.81745925866585, + "seed": 163492330, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888072, + "link": null, + "locked": false, + "startBinding": { + "focus": 0.5414720442395691, + "gap": 10.186182476718557, + "elementId": "RTqCReH94hrfFOfKvX3Xb" + }, + "endBinding": { + "focus": 0.09938892036401328, + "gap": 7.48948180192599, + "elementId": "PDhm6OLJ3n51SVKIISduG" + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 70.51754950478039, + 53.81745925866585 + ] + ] + }, + { + "type": "arrow", + "version": 278, + "versionNonce": 888424566, + "isDeleted": false, + "id": "p4uOM1CtA_v2Pgf6ijK9W", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 2, + "opacity": 100, + "angle": 0, + "x": 1816.8655741450823, + "y": 804.5549918935991, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 4.425399877032078, + "height": 863.6896840333961, + "seed": 639832037, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "startBinding": null, + "endBinding": null, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 4.425399877032078, + -863.6896840333961 + ] + ] + }, + { + "type": "text", + "version": 155, + "versionNonce": 2041258474, + "isDeleted": false, + "id": "j8MvrQTIbxG8XlEdrUsHO", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 2, + "opacity": 100, + "angle": 0, + "x": 1710.063519604042, + "y": -31.350809576339884, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 80, + "height": 25, + "seed": 786904971, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "Lamport", + "baseline": 18, + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "originalText": "Lamport" + }, + { + "type": "rectangle", + "version": 243, + "versionNonce": 595577270, + "isDeleted": false, + "id": "PNo3TYUfJ10IJi6267aAh", + "fillStyle": "hachure", + "strokeWidth": 4, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1350.7224316028319, + "y": 295.70182854499143, + "strokeColor": "#1864ab", + "backgroundColor": "transparent", + "width": 37.41238356134112, + "height": 46.67318451720979, + "seed": 329573546, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "Y38QXVN9QX9BPQY-2ARsJ", + "type": "arrow" + }, + { + "id": "RPqJsAAGLOdXHUSB03TtV", + "type": "arrow" + }, + { + "id": "XWSRH57gG_wU8RgnjMLPE", + "type": "arrow" + } + ], + "updated": 1666058888073, + "link": null, + "locked": false + }, + { + "type": "text", + "version": 163, + "versionNonce": 746804394, + "isDeleted": false, + "id": "2ZLvwZY7jTj3Y7A867PUw", + "fillStyle": "hachure", + "strokeWidth": 4, + "strokeStyle": "solid", + "roughness": 2, + "opacity": 100, + "angle": 0, + "x": 907.8436350772699, + "y": 2.945826594468457, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 200, + "height": 25, + "seed": 1748790533, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "Need to find all the", + "baseline": 18, + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "originalText": "Need to find all the" + }, + { + "type": "rectangle", + "version": 620, + "versionNonce": 1334387446, + "isDeleted": false, + "id": "awuQ8K6kOHnRv5HDrvJWm", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 926.507571138557, + "y": 50.93006817318019, + "strokeColor": "#d9480f", + "backgroundColor": "transparent", + "width": 41.6796875, + "height": 41.82421874999999, + "seed": 489627941, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "7o4qiZeXIC5XlAhjbYObN", + "type": "arrow" + }, + { + "id": "D7U5Ron34tY9c82vBqDaB", + "type": "arrow" + } + ], + "updated": 1666058888073, + "link": null, + "locked": false + }, + { + "type": "rectangle", + "version": 226, + "versionNonce": 591867754, + "isDeleted": false, + "id": "E3RI5q1yc3GeaorRS1w0w", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 1046.9959782392652, + "y": 46.34815941558787, + "strokeColor": "#1864ab", + "backgroundColor": "transparent", + "width": 40.76953125, + "height": 44.6484375, + "seed": 1561043499, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "strWHmShIdrbcdVwMei4L", + "type": "arrow" + }, + { + "id": "gouvuPNNZV_QH-D9GO0TA", + "type": "arrow" + }, + { + "id": "JZQIc_KcE8CBpiAjy1v9j", + "type": "arrow" + } + ], + "updated": 1666058888073, + "link": null, + "locked": false + }, + { + "type": "text", + "version": 39, + "versionNonce": 2073383990, + "isDeleted": false, + "id": "jhZwZVYHq9DVCoTsVfoNA", + "fillStyle": "hachure", + "strokeWidth": 4, + "strokeStyle": "solid", + "roughness": 2, + "opacity": 100, + "angle": 0, + "x": 920.1084297636246, + "y": 103.86982908128641, + "strokeColor": "#d9480f", + "backgroundColor": "transparent", + "width": 55, + "height": 20, + "seed": 1102244805, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "fontSize": 16, + "fontFamily": 1, + "text": "From A", + "baseline": 14, + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "originalText": "From A" + }, + { + "type": "text", + "version": 74, + "versionNonce": 843166250, + "isDeleted": false, + "id": "nwkFN4UJbc5Jg4yZ0eNgs", + "fillStyle": "hachure", + "strokeWidth": 4, + "strokeStyle": "solid", + "roughness": 2, + "opacity": 100, + "angle": 0, + "x": 1041.1473326329826, + "y": 101.57709076329934, + "strokeColor": "#1864ab", + "backgroundColor": "transparent", + "width": 56, + "height": 20, + "seed": 1781306661, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "fontSize": 16, + "fontFamily": 1, + "text": "From B", + "baseline": 14, + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "originalText": "From B" + }, + { + "type": "text", + "version": 81, + "versionNonce": 1367956854, + "isDeleted": false, + "id": "kIrTAwchInsTnq6LCV63N", + "fillStyle": "hachure", + "strokeWidth": 4, + "strokeStyle": "solid", + "roughness": 2, + "opacity": 100, + "angle": 0, + "x": 895.0964797797128, + "y": 397.1606789154389, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 214, + "height": 20, + "seed": 167668933, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "KLyXLrCImVTQP_jU2EX9O", + "type": "arrow" + } + ], + "updated": 1666058888073, + "link": null, + "locked": false, + "fontSize": 16, + "fontFamily": 1, + "text": "This case is a little tricky", + "baseline": 14, + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "originalText": "This case is a little tricky" + }, + { + "type": "arrow", + "version": 142, + "versionNonce": 1818090730, + "isDeleted": false, + "id": "KLyXLrCImVTQP_jU2EX9O", + "fillStyle": "hachure", + "strokeWidth": 4, + "strokeStyle": "dashed", + "roughness": 2, + "opacity": 100, + "angle": 0, + "x": 1119.079507605672, + "y": 405.26356192336186, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 205.11324147046594, + "height": 45.80272521494817, + "seed": 459973771, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "startBinding": { + "elementId": "kIrTAwchInsTnq6LCV63N", + "focus": 0.714758414751021, + "gap": 9.983027825959198 + }, + "endBinding": null, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 205.11324147046594, + -45.80272521494817 + ] + ] + }, + { + "type": "text", + "version": 188, + "versionNonce": 1990868662, + "isDeleted": false, + "id": "SztschmDzOAjFuvTM-OuV", + "fillStyle": "hachure", + "strokeWidth": 4, + "strokeStyle": "dashed", + "roughness": 2, + "opacity": 100, + "angle": 0, + "x": 893.4248140652206, + "y": 439.769275660658, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 276, + "height": 40, + "seed": 332043691, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "fontSize": 16, + "fontFamily": 1, + "text": "we need to slice it after we found\nthe meet", + "baseline": 34, + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "originalText": "we need to slice it after we found\nthe meet" + }, + { + "type": "rectangle", + "version": 108, + "versionNonce": 1327935402, + "isDeleted": false, + "id": "Y9vqkX1na6vJDz7l4PspG", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 207.46439441645236, + "y": 845.6472361162546, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 62.180771530968855, + "height": 64.0268369575906, + "seed": 1456447841, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "type": "text", + "id": "EJMwY_7pCh7jyDuzdJg6V" + }, + { + "id": "iBGHqUq7evqeBkhBGjpIY", + "type": "arrow" + }, + { + "id": "1FA4XZdv1alN1lHogHTl9", + "type": "arrow" + } + ], + "updated": 1666058888073, + "link": null, + "locked": false + }, + { + "type": "text", + "version": 144, + "versionNonce": 530380790, + "isDeleted": false, + "id": "t51UcEh3ESlAROMlQggkd", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 150.87847590478498, + "y": 750.1418377874459, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 609.5544837384108, + "height": 29.249255457697245, + "seed": 699369007, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "fontSize": 23.399404366157817, + "fontFamily": 1, + "text": "What is the meet in this case?", + "baseline": 21.249255457697245, + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "originalText": "What is the meet in this case?" + }, + { + "type": "rectangle", + "version": 178, + "versionNonce": 1858546282, + "isDeleted": false, + "id": "OcZsyOg63jPy2vGYoS8dH", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 197.62028593945422, + "y": 994.0831720435232, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 55, + "height": 67.44040550860723, + "seed": 1580756303, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "type": "text", + "id": "BW_IPp1nyObkgC7Vu3OYp" + }, + { + "id": "iBGHqUq7evqeBkhBGjpIY", + "type": "arrow" + }, + { + "id": "WLEzhxAeQRhzi52ESFg-q", + "type": "arrow" + } + ], + "updated": 1666058888073, + "link": null, + "locked": false + }, + { + "type": "text", + "version": 14, + "versionNonce": 610699574, + "isDeleted": false, + "id": "EJMwY_7pCh7jyDuzdJg6V", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 212.46439441645236, + "y": 865.1606545950499, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 52, + "height": 23, + "seed": 546698977, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "A", + "baseline": 17, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "Y9vqkX1na6vJDz7l4PspG", + "originalText": "A" + }, + { + "type": "text", + "version": 49, + "versionNonce": 571100458, + "isDeleted": false, + "id": "BW_IPp1nyObkgC7Vu3OYp", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 202.62028593945422, + "y": 1015.3033747978269, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 45, + "height": 23, + "seed": 1644625505, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "B", + "baseline": 17, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "OcZsyOg63jPy2vGYoS8dH", + "originalText": "B" + }, + { + "type": "rectangle", + "version": 136, + "versionNonce": 342618742, + "isDeleted": false, + "id": "gCZ4PjyxtYNIC3EGFAKxA", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 356.58493261190574, + "y": 974.517711358304, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 54, + "height": 58, + "seed": 1573171983, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "1FA4XZdv1alN1lHogHTl9", + "type": "arrow" + }, + { + "id": "fOuTMdWLfJmuB2ov11q7v", + "type": "arrow" + }, + { + "type": "text", + "id": "86HkQ09dZUZF0MFiJVz63" + } + ], + "updated": 1666058888073, + "link": null, + "locked": false + }, + { + "type": "rectangle", + "version": 185, + "versionNonce": 777721834, + "isDeleted": false, + "id": "hLRIE0OQJr_P647NEGYUb", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 339.35656242842015, + "y": 1187.155175856424, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 63.38000584903011, + "height": 74.49416956838468, + "seed": 1700659777, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "WLEzhxAeQRhzi52ESFg-q", + "type": "arrow" + }, + { + "id": "fOuTMdWLfJmuB2ov11q7v", + "type": "arrow" + }, + { + "type": "text", + "id": "uc0dpPTx3z-Oih__yVi7r" + } + ], + "updated": 1666058888073, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 52, + "versionNonce": 1248998326, + "isDeleted": false, + "id": "iBGHqUq7evqeBkhBGjpIY", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 238.39425275353517, + "y": 916.6475734194214, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 3.4230113409226988, + "height": 64.07877230207362, + "seed": 355303279, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "startBinding": { + "elementId": "Y9vqkX1na6vJDz7l4PspG", + "focus": -0.05859992602942486, + "gap": 6.973500345576213 + }, + "endBinding": { + "elementId": "OcZsyOg63jPy2vGYoS8dH", + "focus": 0.2503697342260085, + "gap": 13.356826322028098 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -3.4230113409226988, + 64.07877230207362 + ] + ] + }, + { + "type": "arrow", + "version": 221, + "versionNonce": 1942260394, + "isDeleted": false, + "id": "1FA4XZdv1alN1lHogHTl9", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 280.2730259866174, + "y": 874.3827042892433, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 108.9112565402437, + "height": 90.60251065896, + "seed": 958569537, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "startBinding": { + "elementId": "Y9vqkX1na6vJDz7l4PspG", + "gap": 10.627860039196209, + "focus": -0.6558398277536983 + }, + "endBinding": { + "elementId": "gCZ4PjyxtYNIC3EGFAKxA", + "gap": 9.53249641010075, + "focus": 0.8392853510122925 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 108.9112565402437, + 90.60251065896 + ] + ] + }, + { + "type": "arrow", + "version": 352, + "versionNonce": 10374390, + "isDeleted": false, + "id": "WLEzhxAeQRhzi52ESFg-q", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 225.846817638945, + "y": 1073.1712589011736, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 130.36469464909064, + "height": 104.34282846123074, + "seed": 974853505, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "startBinding": { + "elementId": "OcZsyOg63jPy2vGYoS8dH", + "focus": 0.8039769929584992, + "gap": 11.647681349043125 + }, + "endBinding": { + "elementId": "hLRIE0OQJr_P647NEGYUb", + "focus": 0.5592314137305141, + "gap": 9.641088494019641 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 130.36469464909064, + 104.34282846123074 + ] + ] + }, + { + "type": "arrow", + "version": 447, + "versionNonce": 418489706, + "isDeleted": false, + "id": "fOuTMdWLfJmuB2ov11q7v", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 383.2859330385243, + "y": 1039.3495698552904, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 0.8019442573741458, + "height": 139.71785644664988, + "seed": 1093453345, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "startBinding": { + "elementId": "gCZ4PjyxtYNIC3EGFAKxA", + "focus": 0.0034356344242915454, + "gap": 6.831858496986342 + }, + "endBinding": { + "elementId": "hLRIE0OQJr_P647NEGYUb", + "focus": 0.35034121969360427, + "gap": 8.087749554483707 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -0.8019442573741458, + 139.71785644664988 + ] + ] + }, + { + "type": "text", + "version": 86, + "versionNonce": 1685405238, + "isDeleted": false, + "id": "86HkQ09dZUZF0MFiJVz63", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 361.58493261190574, + "y": 992.017711358304, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 44, + "height": 23, + "seed": 1827546465, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "1", + "baseline": 17, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "gCZ4PjyxtYNIC3EGFAKxA", + "originalText": "1" + }, + { + "type": "text", + "version": 97, + "versionNonce": 925722666, + "isDeleted": false, + "id": "uc0dpPTx3z-Oih__yVi7r", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 344.35656242842015, + "y": 1211.9022606406163, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 53, + "height": 23, + "seed": 1503038895, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "2", + "baseline": 17, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "hLRIE0OQJr_P647NEGYUb", + "originalText": "2" + }, + { + "type": "text", + "version": 253, + "versionNonce": 719062902, + "isDeleted": false, + "id": "kI_tZyDto7LyRVi7fZo1b", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 458.5859491764503, + "y": 836.3733952089806, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 268, + "height": 25, + "seed": 381074991, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "Is it just B? Or B and 2?", + "baseline": 18, + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "originalText": "Is it just B? Or B and 2?" + }, + { + "type": "text", + "version": 172, + "versionNonce": 107139818, + "isDeleted": false, + "id": "Ucbb53X_Dwn5QAY3EB0D8", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 459.9740392926316, + "y": 901.9771780808721, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 254, + "height": 25, + "seed": 343812495, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "Should be both B and 2. ", + "baseline": 18, + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "originalText": "Should be both B and 2. " + }, + { + "type": "text", + "version": 59, + "versionNonce": 605530294, + "isDeleted": false, + "id": "cOQa-Eb9wSAJWzgq9aI7x", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 159.49974308895753, + "y": 1311.600682807928, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 424, + "height": 25, + "seed": 1981785473, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888073, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "How to tackle this case when finding path?", + "baseline": 18, + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "originalText": "How to tackle this case when finding path?" + }, + { + "type": "rectangle", + "version": 52, + "versionNonce": 152888746, + "isDeleted": false, + "id": "hwOHW2_5-VmaE0Y21RH6I", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 174.03219675428193, + "y": 1394.1222450159953, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 49.409398183112216, + "height": 51.5151403321488, + "seed": 578415457, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "type": "text", + "id": "o2Bs8-53MFFZjUFarRyRN" + }, + { + "id": "qCbjrqfXeEu-zEq2Ffb3T", + "type": "arrow" + }, + { + "id": "R6d9DcWsOcD8YWu9N7JxL", + "type": "arrow" + } + ], + "updated": 1666058888074, + "link": null, + "locked": false + }, + { + "type": "text", + "version": 14, + "versionNonce": 1338843638, + "isDeleted": false, + "id": "o2Bs8-53MFFZjUFarRyRN", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 179.03219675428193, + "y": 1407.3798151820697, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 39, + "height": 23, + "seed": 1451199681, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888074, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "A", + "baseline": 17, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "hwOHW2_5-VmaE0Y21RH6I", + "originalText": "A" + }, + { + "type": "rectangle", + "version": 48, + "versionNonce": 948346986, + "isDeleted": false, + "id": "D36mTqaq_mm5bD6sonefu", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 341.06570740140523, + "y": 1402.8757112588514, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 52, + "height": 54.08830058153217, + "seed": 1613404719, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "type": "text", + "id": "PnMoL-isuYyODBEw1k2wf" + }, + { + "id": "NyiyA39uyFO2fv9N82bF4", + "type": "arrow" + } + ], + "updated": 1666058888074, + "link": null, + "locked": false + }, + { + "type": "text", + "version": 14, + "versionNonce": 1895920438, + "isDeleted": false, + "id": "PnMoL-isuYyODBEw1k2wf", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 346.06570740140523, + "y": 1417.4198615496175, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 42, + "height": 23, + "seed": 467983471, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [], + "updated": 1666058888074, + "link": null, + "locked": false, + "fontSize": 20, + "fontFamily": 1, + "text": "B", + "baseline": 17, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "D36mTqaq_mm5bD6sonefu", + "originalText": "B" + }, + { + "type": "arrow", + "version": 83, + "versionNonce": 812319530, + "isDeleted": false, + "id": "qCbjrqfXeEu-zEq2Ffb3T", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 199.85822714717483, + "y": 1452.9508261303365, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 40.22628499953339, + "height": 184.9087119391695, + "seed": 105061935, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888074, + "link": null, + "locked": false, + "startBinding": { + "elementId": "hwOHW2_5-VmaE0Y21RH6I", + "focus": 0.20038022884771262, + "gap": 7.3134407821924015 + }, + "endBinding": null, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + 40.22628499953339, + 184.9087119391695 + ] + ] + }, + { + "type": "arrow", + "version": 50, + "versionNonce": 572103798, + "isDeleted": false, + "id": "NyiyA39uyFO2fv9N82bF4", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 370.7066249163197, + "y": 1466.4917868555315, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 113.29459329211295, + "height": 165.0694103466767, + "seed": 366695329, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888074, + "link": null, + "locked": false, + "startBinding": { + "elementId": "D36mTqaq_mm5bD6sonefu", + "focus": -0.6449918259980243, + "gap": 9.527775015147881 + }, + "endBinding": null, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -113.29459329211295, + 165.0694103466767 + ] + ] + }, + { + "type": "rectangle", + "version": 74, + "versionNonce": 1530203626, + "isDeleted": false, + "id": "s54CZ5KG2aYjaNsp6G4VZ", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 217.9317270272469, + "y": 1640.4751908734663, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 63.21475702567511, + "height": 68.62547564180954, + "seed": 638536961, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "aw37qj_R25zNHnnWOQGPF", + "type": "arrow" + } + ], + "updated": 1666058888074, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 59, + "versionNonce": 1759157686, + "isDeleted": false, + "id": "R6d9DcWsOcD8YWu9N7JxL", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 179.45235816032232, + "y": 1451.817691341617, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 111.97732410022672, + "height": 94.94253110981413, + "seed": 1780700449, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888074, + "link": null, + "locked": false, + "startBinding": { + "elementId": "hwOHW2_5-VmaE0Y21RH6I", + "focus": -0.3337409231098588, + "gap": 6.1803059934729845 + }, + "endBinding": { + "elementId": "Uu6icBmJsdOeGkGZzL7sU", + "focus": -0.6678530131421979, + "gap": 9.065078309754199 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -111.97732410022672, + 94.94253110981413 + ] + ] + }, + { + "type": "rectangle", + "version": 72, + "versionNonce": 502251690, + "isDeleted": false, + "id": "Uu6icBmJsdOeGkGZzL7sU", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 36.14857854696129, + "y": 1555.8253007611854, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 54.08830058153217, + "height": 59.489576407760524, + "seed": 1867485153, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "2-6tyGZ_ZmFG9B-mW7C21", + "type": "arrow" + }, + { + "id": "R6d9DcWsOcD8YWu9N7JxL", + "type": "arrow" + } + ], + "updated": 1666058888074, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 299, + "versionNonce": 1248425718, + "isDeleted": false, + "id": "2-6tyGZ_ZmFG9B-mW7C21", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 69.80268177192295, + "y": 1626.4762548378305, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 40.55206125129018, + "height": 95.98595939442657, + "seed": 803727777, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888074, + "link": null, + "locked": false, + "startBinding": { + "elementId": "Uu6icBmJsdOeGkGZzL7sU", + "focus": -0.6031691429467954, + "gap": 11.161377668884597 + }, + "endBinding": { + "elementId": "kMzfHdkQJvza3Y7oH-Stk", + "focus": -0.780062894083163, + "gap": 7.828072832068642 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -40.55206125129018, + 95.98595939442657 + ] + ] + }, + { + "type": "rectangle", + "version": 117, + "versionNonce": 71703402, + "isDeleted": false, + "id": "kMzfHdkQJvza3Y7oH-Stk", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 5.5633820414475395, + "y": 1730.2902870643259, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 49.86265209859994, + "height": 320.63937404792387, + "seed": 1045724623, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "2-6tyGZ_ZmFG9B-mW7C21", + "type": "arrow" + }, + { + "id": "StiyyzlA2m4GVtTLr2uzG", + "type": "arrow" + }, + { + "id": "3HbM7P7WEUHkMZ9blj5wa", + "type": "arrow" + } + ], + "updated": 1666058888074, + "link": null, + "locked": false + }, + { + "type": "rectangle", + "version": 125, + "versionNonce": 1598761014, + "isDeleted": false, + "id": "xG6Ryld1g4RsmlYfeyRyl", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 4.930715117745535, + "y": 1894.3540402860144, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 49.206378200133486, + "height": 156.04210319654658, + "seed": 441826383, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "29BHND6z19Wd0fVvFoxsH", + "type": "arrow" + } + ], + "updated": 1666058888074, + "link": null, + "locked": false + }, + { + "type": "rectangle", + "version": 40, + "versionNonce": 1820532266, + "isDeleted": false, + "id": "7avwsrGLRQ9zXDSv0w1np", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 166.8651192156325, + "y": 1781.2294172122108, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 24.806209083045587, + "height": 32.90812282238835, + "seed": 1685597185, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "aw37qj_R25zNHnnWOQGPF", + "type": "arrow" + }, + { + "id": "9h36VDCVJrRu8C1CMjJtB", + "type": "arrow" + } + ], + "updated": 1666058888074, + "link": null, + "locked": false + }, + { + "type": "rectangle", + "version": 52, + "versionNonce": 1734652278, + "isDeleted": false, + "id": "0uds6kbQkH4ArKucMh0Vg", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 115.45857096740258, + "y": 1831.7105720496534, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 33.93738692214151, + "height": 30.297191413380915, + "seed": 1820056143, + "groupIds": [], + "strokeSharpness": "sharp", + "boundElements": [ + { + "id": "9h36VDCVJrRu8C1CMjJtB", + "type": "arrow" + }, + { + "id": "29BHND6z19Wd0fVvFoxsH", + "type": "arrow" + } + ], + "updated": 1666058888074, + "link": null, + "locked": false + }, + { + "type": "arrow", + "version": 47, + "versionNonce": 865192170, + "isDeleted": false, + "id": "aw37qj_R25zNHnnWOQGPF", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 241.67090085091502, + "y": 1720.7483478643207, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 40.703145889786015, + "height": 49.39051260330052, + "seed": 1142455201, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888074, + "link": null, + "locked": false, + "startBinding": { + "elementId": "s54CZ5KG2aYjaNsp6G4VZ", + "focus": -0.5010982988927215, + "gap": 11.647681349044774 + }, + "endBinding": { + "elementId": "7avwsrGLRQ9zXDSv0w1np", + "focus": -0.03852497283277824, + "gap": 11.090556744589435 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -40.703145889786015, + 49.39051260330052 + ] + ] + }, + { + "type": "arrow", + "version": 36, + "versionNonce": 1576735414, + "isDeleted": false, + "id": "9h36VDCVJrRu8C1CMjJtB", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 164.44776499969817, + "y": 1807.2348606133176, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 17.138663679378624, + "height": 16.893151141822955, + "seed": 285622561, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888074, + "link": null, + "locked": false, + "startBinding": { + "elementId": "7avwsrGLRQ9zXDSv0w1np", + "focus": 0.17632017043480894, + "gap": 2.417354215934324 + }, + "endBinding": { + "elementId": "0uds6kbQkH4ArKucMh0Vg", + "focus": -0.2529475107653309, + "gap": 7.582560294512859 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -17.138663679378624, + 16.893151141822955 + ] + ] + }, + { + "type": "arrow", + "version": 53, + "versionNonce": 1627200426, + "isDeleted": false, + "id": "29BHND6z19Wd0fVvFoxsH", + "fillStyle": "hachure", + "strokeWidth": 1, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "angle": 0, + "x": 111.12433040055146, + "y": 1855.3930891338857, + "strokeColor": "#000000", + "backgroundColor": "transparent", + "width": 51.59068265139683, + "height": 34.503954316500995, + "seed": 668671791, + "groupIds": [], + "strokeSharpness": "round", + "boundElements": [], + "updated": 1666058888074, + "link": null, + "locked": false, + "startBinding": { + "elementId": "0uds6kbQkH4ArKucMh0Vg", + "focus": 0.2156267298677806, + "gap": 4.334240566851122 + }, + "endBinding": { + "elementId": "xG6Ryld1g4RsmlYfeyRyl", + "focus": -0.6606370592162203, + "gap": 5.396554431275604 + }, + "lastCommittedPoint": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "points": [ + [ + 0, + 0 + ], + [ + -51.59068265139683, + 34.503954316500995 + ] + ] + } + ], + "appState": { + "gridSize": null, + "viewBackgroundColor": "#ffffff" + }, + "files": {} +} \ No newline at end of file diff --git a/vendor/loro-internal/src/dag/test.rs b/vendor/loro-internal/src/dag/test.rs new file mode 100644 index 0000000..9519281 --- /dev/null +++ b/vendor/loro-internal/src/dag/test.rs @@ -0,0 +1,1467 @@ +#![allow(unused)] +use arbitrary::Arbitrary; +use im::HashSet; +use loro_common::HasCounter; +use std::{cmp::Ordering, sync::Arc}; + +use super::*; +use crate::{ + array_mut_ref, + change::Lamport, + id::{Counter, PeerID, ID}, + span::HasIdSpan, +}; + +#[derive(Debug, PartialEq, Eq, Clone)] +struct TestNode { + id: ID, + lamport: Lamport, + len: usize, + deps: Arc<Frontiers>, +} + +impl TestNode { + fn new(id: ID, lamport: Lamport, deps: Frontiers, len: usize) -> Self { + Self { + id, + lamport, + deps: Arc::new(deps), + len, + } + } +} + +impl DagNode for TestNode { + fn deps(&self) -> &Frontiers { + &self.deps + } +} + +impl Sliceable for TestNode { + fn slice(&self, from: usize, to: usize) -> Self { + Self { + id: self.id.inc(from as Counter), + lamport: self.lamport + from as Lamport, + len: to - from, + deps: if from > 0 { + Arc::new(self.id.inc(from as Counter - 1).into()) + } else { + self.deps.clone() + }, + } + } +} + +impl HasLamport for TestNode { + fn lamport(&self) -> Lamport { + self.lamport + } +} + +impl HasId for TestNode { + fn id_start(&self) -> ID { + self.id + } +} + +impl HasCounter for TestNode { + fn ctr_start(&self) -> Counter { + self.id.counter + } +} + +impl HasLength for TestNode { + fn content_len(&self) -> usize { + self.len + } +} + +#[derive(Debug, PartialEq, Eq)] +struct TestDag { + nodes: FxHashMap<PeerID, Vec<TestNode>>, + frontier: Frontiers, + version_vec: VersionVector, + next_lamport: Lamport, + client_id: PeerID, +} + +impl Dag for TestDag { + type Node = TestNode; + + fn get(&self, id: ID) -> Option<Self::Node> { + let arr = self.nodes.get(&id.peer)?; + arr.binary_search_by(|node| { + if node.id.counter > id.counter { + Ordering::Greater + } else if node.id.counter + node.len as i32 <= id.counter { + Ordering::Less + } else { + Ordering::Equal + } + }) + .map_or(None, |x| Some(arr[x].clone())) + } + + fn frontier(&self) -> &Frontiers { + &self.frontier + } + + fn vv(&self) -> &VersionVector { + &self.version_vec + } + + fn contains(&self, id: ID) -> bool { + self.version_vec.includes_id(id) + } +} + +impl TestDag { + pub fn new(client_id: PeerID) -> Self { + Self { + nodes: FxHashMap::default(), + frontier: Frontiers::new(), + version_vec: VersionVector::new(), + next_lamport: 0, + client_id, + } + } + + fn get_last_node(&mut self) -> &mut TestNode { + self.nodes + .get_mut(&self.client_id) + .unwrap() + .last_mut() + .unwrap() + } + + fn push(&mut self, len: usize) { + let client_id = self.client_id; + let counter = self.version_vec.entry(client_id).or_insert(0); + let id = ID::new(client_id, *counter); + *counter += len as Counter; + let deps = std::mem::replace(&mut self.frontier, id.inc(len as Counter - 1).into()); + self.nodes.entry(client_id).or_default().push(TestNode::new( + id, + self.next_lamport, + deps, + len, + )); + self.next_lamport += len as u32; + } + + fn merge(&mut self, other: &TestDag) { + let mut pending = Vec::new(); + for (_, nodes) in other.nodes.iter() { + for (i, node) in nodes.iter().enumerate() { + if self._try_push_node(node, &mut pending, i) { + break; + } + } + } + + let mut current = pending; + let mut pending = Vec::new(); + while !pending.is_empty() || !current.is_empty() { + if current.is_empty() { + std::mem::swap(&mut pending, &mut current); + } + + let (client_id, index) = current.pop().unwrap(); + let node_vec = other.nodes.get(&client_id).unwrap(); + #[allow(clippy::needless_range_loop)] + for i in index..node_vec.len() { + let node = &node_vec[i]; + if self._try_push_node(node, &mut pending, i) { + break; + } + } + } + } + + fn update_frontier(frontier: &mut Frontiers, new_node_id: ID, new_node_deps: &Frontiers) { + frontier.retain(|x| { + if x.peer == new_node_id.peer && x.counter <= new_node_id.counter { + return false; + } + + !new_node_deps + .iter() + .any(|y| y.peer == x.peer && y.counter >= x.counter) + }); + + // nodes from the same client with `counter < new_node_id.counter` + // are filtered out from frontier. + if frontier.iter().all(|x| x.peer != new_node_id.peer) { + frontier.push(new_node_id); + } + } + + fn _try_push_node( + &mut self, + node: &TestNode, + pending: &mut Vec<(PeerID, usize)>, + i: usize, + ) -> bool { + let client_id = node.id.peer; + if self.contains(node.id_last()) { + return false; + } + if node.deps.iter().any(|dep| !self.contains(dep)) { + pending.push((client_id, i)); + return true; + } + Self::update_frontier(&mut self.frontier, node.id_last(), &node.deps); + let contains_start = self.contains(node.id_start()); + let arr = self.nodes.entry(client_id).or_default(); + if contains_start { + arr.pop(); + arr.push(node.clone()); + } else { + arr.push(node.clone()); + } + self.version_vec.set_end(node.id_end()); + self.next_lamport = self.next_lamport.max(node.lamport + node.len as u32); + false + } +} + +/// ```mermaid /// flowchart RL +/// subgraph client0 +/// 0-1("c0: [1, 3)") --> 0-0("c0: [0, 1)") +/// end +/// +/// subgraph client1 +/// 1-0("c1: [0, 2)") +/// end +/// +/// 0-1 --> 1-0 +/// ``` +#[test] +fn test_dag() { + let mut a = TestDag::new(0); + let mut b = TestDag::new(1); + a.push(1); + assert_eq!(a.frontier().len(), 1); + assert_eq!(a.frontier().as_single().unwrap().counter, 0); + b.push(1); + a.merge(&b); + assert_eq!(a.frontier().len(), 2); + a.push(1); + assert_eq!(a.frontier().len(), 1); + // a: 0 --(merge)--- 1 + // ↑ + // | + // b: 0 ---- + assert_eq!( + a.frontier().iter().next().unwrap(), + ID { + peer: 0, + counter: 1 + } + ); + + // a: 0 --(merge)--- 1 --- 2 ------- + // ↑ | + // | ↓ + // b: 0 ------------1----------(merge) + a.push(1); + b.push(1); + b.merge(&a); + assert_eq!(b.next_lamport, 3); + assert_eq!(b.frontier().len(), 2); + // println!("{}", b.mermaid()); + assert_eq!( + b.find_replay_base(&[ID::new(0, 2)].into(), &[ID::new(1, 1)].into()) + .0 + .len(), + 0 + ); +} + +#[derive(Debug, Clone, Copy, Arbitrary)] +pub struct Interaction { + dag_idx: usize, + merge_with: Option<usize>, + len: usize, +} + +impl Interaction { + fn generate(rng: &mut impl rand::Rng, num: usize) -> Self { + if rng.gen_bool(0.5) { + let dag_idx = rng.gen_range(0..num); + let merge_with = (rng.gen_range(1..num - 1) + dag_idx) % num; + Self { + dag_idx, + merge_with: Some(merge_with), + len: rng.gen_range(1..10), + } + } else { + Self { + dag_idx: rng.gen_range(0..num), + merge_with: None, + len: rng.gen_range(1..10), + } + } + } + + fn apply(&self, dags: &mut [TestDag]) { + if let Some(merge_with) = self.merge_with { + if merge_with != self.dag_idx { + let (from, to) = array_mut_ref!(dags, [self.dag_idx, merge_with]); + from.merge(to); + } + } + + dags[self.dag_idx].push(self.len); + } +} + +// prop_compose! { +// fn gen_interaction(num: usize) ( +// dag_idx in 0..num, +// merge_with in 0..num, +// length in 1..10, +// should_merge in 0..2 +// ) -> Interaction { +// Interaction { +// dag_idx, +// merge_with: if should_merge == 1 && merge_with != dag_idx { Some(merge_with) } else { None }, +// len: length as usize, +// } +// } +// } + +fn preprocess(interactions: &mut [Interaction], num: i32) { + for interaction in interactions.iter_mut() { + interaction.dag_idx %= num as usize; + if let Some(ref mut merge_with) = interaction.merge_with { + *merge_with %= num as usize; + if *merge_with == interaction.dag_idx { + *merge_with = (*merge_with + 1) % num as usize; + } + } + + interaction.len = (interaction.len % 128).max(1); + } +} + +mod iter { + use super::*; + + #[test] + fn test() { + let mut a = TestDag::new(0); + let mut b = TestDag::new(1); + // 0-0 + a.push(1); + // 1-0 + b.push(1); + a.merge(&b); + // 0-1 + a.push(1); + b.merge(&a); + // 1-1 + b.push(1); + a.merge(&b); + // 0-2 + a.push(1); + + let mut count = 0; + for (node, vv) in a.iter_with_vv() { + count += 1; + if node.id == ID::new(0, 0) { + assert_eq!(vv, vec![ID::new(0, 0)].into()); + } else if node.id == ID::new(0, 2) { + assert_eq!(vv, vec![ID::new(0, 2), ID::new(1, 1)].into()); + } + } + + assert_eq!(count, 5); + } +} + +mod dfs { + #[allow(unused)] + #[allow(dead_code)] + use super::*; + use crate::{allocation::calc_critical_version_dfs, delta::DeltaValue}; + use rand::{rngs::StdRng, SeedableRng}; + + #[test] + fn test_dfs_small() { + let mut a = TestDag::new(0); + let mut b = TestDag::new(1); + let mut c = TestDag::new(2); + a.push(10); + b.merge(&a); + b.push(3); + c.merge(&b); + c.push(4); + a.push(3); + a.merge(&c); + a.push(2); + b.merge(&a); + assert_eq!( + calc_critical_version_dfs::<TestNode, TestDag>( + &b, + &[ID { + peer: 0, + counter: 13, + }] + .into(), + &[ID { + peer: 0, + counter: 9, + }] + .into(), + ) + .length(), + 0 + ); + } + + #[test] + fn test_dfs_big() { + let num = 5; + let mut rng = StdRng::seed_from_u64(100); + let mut dags = (0..num).map(TestDag::new).collect::<Vec<_>>(); + for _ in 0..100 { + Interaction::generate(&mut rng, num as usize).apply(&mut dags); + } + for i in 1..num { + let (a, other) = array_mut_ref!(&mut dags, [0, i as usize]); + a.merge(other); + } + let start = dags[0].frontier(); + let ends = [ + ID { + peer: 3, + counter: 7, + }, + ID { + peer: 4, + counter: 6, + }, + ] + .into(); + assert_eq!( + calc_critical_version_dfs(&dags[0], start, &ends).length(), + 0 + ); + } +} + +mod bfs { + use arref::array_mut_ref; + use loro_common::ID; + use rand::{rngs::StdRng, SeedableRng}; + + use crate::{ + allocation::calc_critical_version, + dag::{ + test::{TestDag, TestNode}, + Dag, Interaction, + }, + delta::DeltaValue as _, + }; + + #[test] + fn test_bfs_small() { + let mut a = TestDag::new(0); + let mut b = TestDag::new(1); + let mut c = TestDag::new(2); + a.push(10); + b.merge(&a); + b.push(3); + c.merge(&b); + c.push(4); + a.push(3); + a.merge(&c); + a.push(2); + b.merge(&a); + assert_eq!( + calc_critical_version::<TestNode, TestDag>( + &b, + &[ID { + peer: 0, + counter: 13, + }] + .into(), + ) + .length(), + 0 + ); + } + + #[test] + fn test_bfs_big() { + let num = 5; + let mut rng = StdRng::seed_from_u64(100); + let mut dags = (0..num).map(TestDag::new).collect::<Vec<_>>(); + for _ in 0..100 { + Interaction::generate(&mut rng, num as usize).apply(&mut dags); + } + for i in 1..num { + let (a, other) = array_mut_ref!(&mut dags, [0, i as usize]); + a.merge(other); + } + let start = dags[0].frontier(); + let ends = [ID { + peer: 3, + counter: 7, + }]; + assert_eq!(calc_critical_version(&dags[0], start).length(), 0); + } +} + +mod mermaid { + use super::*; + use rand::{rngs::StdRng, SeedableRng}; + + #[test] + fn simple() { + let mut a = TestDag::new(0); + let mut b = TestDag::new(1); + // 0-0 + a.push(1); + // 1-0 + b.push(1); + a.merge(&b); + // 0-1 + a.push(1); + b.merge(&a); + // 1-1 + b.push(1); + a.merge(&b); + // 0-2 + a.push(1); + + println!("{}", a.mermaid()); + } + + #[test] + fn three() { + let mut a = TestDag::new(0); + let mut b = TestDag::new(1); + let mut c = TestDag::new(2); + a.push(10); + b.merge(&a); + b.push(3); + c.merge(&b); + c.push(4); + a.push(3); + a.merge(&c); + a.push(2); + b.merge(&a); + println!("{}", a.mermaid()); + } + + #[test] + fn gen_graph() { + let num = 5; + let mut rng = StdRng::seed_from_u64(100); + let mut dags = (0..num).map(TestDag::new).collect::<Vec<_>>(); + for _ in 0..100 { + Interaction::generate(&mut rng, num as usize).apply(&mut dags); + } + for i in 1..num { + let (a, other) = array_mut_ref!(&mut dags, [0, i as usize]); + a.merge(other); + } + println!("{}", dags[0].mermaid()); + } +} + +mod get_version_vector { + #[allow(unused)] + #[allow(dead_code)] + use super::*; + + #[test] + fn vv() { + let mut a = TestDag::new(0); + let mut b = TestDag::new(1); + a.push(1); + b.push(1); + a.merge(&b); + a.push(1); + let actual = a.get_vv(ID::new(0, 0)); + assert_eq!(actual, vec![ID::new(0, 0)].into()); + let actual = a.get_vv(ID::new(0, 1)); + assert_eq!(actual, vec![ID::new(0, 1), ID::new(1, 0)].into()); + + let mut c = TestDag::new(2); + c.merge(&a); + b.push(1); + c.merge(&b); + c.push(1); + let actual = c.get_vv(ID::new(2, 0)); + assert_eq!( + actual, + vec![ID::new(0, 1), ID::new(1, 1), ID::new(2, 0)].into() + ); + } +} + +#[test] +fn test_alloc() { + use rand::thread_rng; + for _ in 1..10000 { + let num = 4; + let mut rng = thread_rng(); + let mut dags = (0..num).map(TestDag::new).collect::<Vec<_>>(); + for _ in 0..20 { + Interaction::generate(&mut rng, num as usize).apply(&mut dags); + } + for i in 1..num { + let (a, other) = array_mut_ref!(&mut dags, [0, i as usize]); + a.merge(other); + } + let a = &dags[0]; + let start = a.frontier(); + let end = crate::allocation::get_end_list(a, start); + let critical_version_actual: HashSet<ID> = + crate::allocation::calc_critical_version(a, start) + .into_iter() + .collect(); + let critical_version: HashSet<ID> = + crate::allocation::calc_critical_version_dfs(a, start, &end) + .into_iter() + .collect(); + assert!(critical_version_actual.eq(&critical_version)); + } +} + +pub fn fuzz_alloc_tree(num: usize, mut actions: Vec<Interaction>) { + preprocess(&mut actions, num as i32); + let mut dags = (0..num as u64).map(TestDag::new).collect::<Vec<_>>(); + for action in actions { + action.apply(&mut dags); + } + + for i in 1..num { + let (a, other) = array_mut_ref!(&mut dags, [0, i]); + a.merge(other); + } + + let a = &dags[0]; + let start = a.frontier(); + let end = crate::allocation::get_end_list(a, start); + let actual: HashSet<ID> = crate::allocation::calc_critical_version(a, start) + .into_iter() + .collect(); + let expected: HashSet<ID> = crate::allocation::calc_critical_version_dfs(a, start, &end) + .into_iter() + .collect(); + assert!(actual.eq(&expected)); +} + +#[test] +fn failed_fuzz() { + fuzz_alloc_tree( + 10, + vec![Interaction { + dag_idx: 14685055086129564619, + merge_with: Some(10), + len: 777939436809428736, + }], + ) +} + +// #[cfg(test)] +// mod find_path { +// use crate::{fx_map, span::CounterSpan}; + +// use super::*; + +// #[test] +// fn retreat_to_beginning() { +// let mut a = TestDag::new(0); +// let mut b = TestDag::new(1); +// a.push(1); +// b.push(1); +// a.merge(&b); +// let actual = a.find_path(&[ID::new(0, 0)], &[ID::new(1, 0)]); +// assert_eq!( +// actual, +// VersionVectorDiff { +// left: fx_map!(0 => CounterSpan { start: 0, end: 1 }), +// right: fx_map!(1 => CounterSpan { start: 0, end: 1 }) +// } +// ); +// } + +// #[test] +// fn one_path() { +// let mut a = TestDag::new(0); +// let mut b = TestDag::new(1); +// // 0 - 0 +// a.push(1); +// b.merge(&a); +// // 1 - 0 +// b.push(1); +// // 0 - 1 +// a.push(1); +// a.merge(&b); +// let actual = a.find_path(&[ID::new(0, 1)], &[ID::new(1, 0)]); +// assert_eq!( +// actual, +// VersionVectorDiff { +// left: fx_map!(0 => CounterSpan { start: 1, end: 2 }), +// right: fx_map!(1 => CounterSpan { start: 0, end: 1 }) +// } +// ); +// } + +// #[test] +// fn middle() { +// let mut a = TestDag::new(0); +// let mut b = TestDag::new(1); +// a.push(2); +// b.push(1); +// b.merge(&a); +// b.push(2); +// a.push(2); +// b.merge(&a); +// // println!("{}", b.mermaid()); +// let actual = b.find_path(&[ID::new(0, 3)], &[ID::new(1, 2)]); +// assert_eq!( +// actual, +// VersionVectorDiff { +// left: fx_map!(0 => CounterSpan { start: 2, end: 4 }), +// right: fx_map!(1 => CounterSpan { start: 0, end: 3 }) +// } +// ); +// let actual = b.find_path(&[ID::new(1, 1), ID::new(1, 2)], &[ID::new(0, 3)]); +// assert_eq!( +// actual, +// VersionVectorDiff { +// left: fx_map!(1 => CounterSpan { start: 0, end: 3 }), +// right: fx_map!(0 => CounterSpan { start: 2, end: 4 }) +// } +// ); +// } + +// fn test_find_path( +// dag_num: i32, +// mut interactions: Vec<Interaction>, +// ) -> Result<(), TestCaseError> { +// preprocess(&mut interactions, dag_num); +// let mut dags = Vec::new(); +// for i in 0..dag_num { +// dags.push(TestDag::new(i as PeerID)); +// } + +// for interaction in interactions.iter_mut() { +// interaction.apply(&mut dags); +// } + +// for i in 1..dag_num { +// let (a, b) = array_mut_ref!(&mut dags, [0, i as usize]); +// a.merge(b); +// } + +// let a = &dags[0]; +// let mut nodes = Vec::new(); +// for (node, vv) in a.iter_with_vv() { +// nodes.push((node, vv)); +// } + +// // println!("{}", a.mermaid()); +// let vec: Vec<_> = nodes.iter().enumerate().collect(); +// for &(i, (node, vv)) in vec.iter() { +// if i > 3 { +// break; +// } + +// for &(j, (other_node, other_vv)) in vec.iter() { +// if i >= j { +// continue; +// } + +// let actual = a.find_path(&[node.id], &[other_node.id]); +// let expected = vv.diff(other_vv); +// prop_assert_eq!( +// actual, +// expected, +// "\ni={} j={} node={} other={}", +// i, +// j, +// node.id, +// other_node.id +// ); + +// for iter in nodes[j + 1..].iter() { +// let mut vv = vv.clone(); +// vv.merge(other_vv); +// let actual = a.find_path(&[node.id, other_node.id], &[iter.0.id]); +// let expected = vv.diff(&iter.1); +// prop_assert_eq!(actual, expected); +// } +// } +// } + +// Ok(()) +// } + +// #[test] +// fn issue() { +// if let Err(err) = test_find_path( +// 5, +// vec![ +// Interaction { +// dag_idx: 1, +// merge_with: None, +// len: 3, +// }, +// Interaction { +// dag_idx: 1, +// merge_with: None, +// len: 3, +// }, +// Interaction { +// dag_idx: 4, +// merge_with: Some(1), +// len: 1, +// }, +// Interaction { +// dag_idx: 0, +// merge_with: None, +// len: 1, +// }, +// Interaction { +// dag_idx: 2, +// merge_with: Some(0), +// len: 1, +// }, +// Interaction { +// dag_idx: 0, +// merge_with: None, +// len: 1, +// }, +// Interaction { +// dag_idx: 2, +// merge_with: Some(0), +// len: 1, +// }, +// Interaction { +// dag_idx: 3, +// merge_with: Some(0), +// len: 1, +// }, +// ], +// ) { +// panic!("{}", err); +// } +// } + +// proptest! { +// #[test] +// fn proptest_path( +// interactions in prop::collection::vec(gen_interaction(5), 0..10 * PROPTEST_FACTOR_10), +// ) { +// test_find_path(5, interactions)?; +// } + +// #[test] +// fn proptest_path_large( +// interactions in prop::collection::vec(gen_interaction(10), 0..PROPTEST_FACTOR_10 * PROPTEST_FACTOR_10 + 10), +// ) { +// test_find_path(10, interactions)?; +// } +// } +// } + +// mod find_replay_base_tests { + +// use super::*; + +// #[test] +// fn siblings() { +// let mut a = TestDag::new(0); +// a.push(5); +// let actual = a +// .find_replay_base(&[ID::new(0, 2)], &[ID::new(0, 4)]) +// .0 +// .first() +// .copied(); +// assert_eq!(actual, Some(ID::new(0, 2))); +// assert_eq!( +// a.find_replay_base(&[ID::new(0, 2)], &[ID::new(0, 4)]).1, +// DiffMode::Linear +// ); +// } + +// #[test] +// fn empty_meet() { +// let mut a = TestDag::new(0); +// let mut b = TestDag::new(1); +// a.push(1); +// b.push(1); +// a.merge(&b); +// let actual = a +// .find_replay_base(&[ID::new(0, 0)], &[ID::new(1, 0)]) +// .0 +// .first() +// .copied(); +// assert_eq!(actual, None); + +// // interactions between b and c +// let mut c = TestDag::new(2); +// c.merge(&b); +// c.push(2); +// b.merge(&c); +// b.push(3); + +// // a and b should share no history, so their meet is empty +// let actual = a +// .find_replay_base(&[ID::new(0, 0)], &[ID::new(1, 0)]) +// .0 +// .first() +// .copied(); +// assert_eq!(actual, None); +// assert_eq!( +// a.find_replay_base(&[ID::new(0, 0)], &[ID::new(1, 0)]).1, +// DiffMode::Checkout +// ) +// } + +// #[test] +// fn empty_meet_when_there_is_an_redundant_node() { +// let mut a = TestDag::new(0); +// let mut b = TestDag::new(1); +// a.push(1); +// b.push(1); +// b.merge(&a); +// b.push(1); +// a.push(4); +// a.merge(&b); +// println!("{}", a.mermaid()); +// let actual = a +// .find_replay_base(&[ID::new(0, 4)], &[ID::new(0, 1), ID::new(1, 1)]) +// .0 +// .first() +// .copied(); +// assert_eq!(actual, None); +// let actual = a +// .find_replay_base(&[ID::new(0, 4)], &[ID::new(1, 1)]) +// .0 +// .first() +// .copied(); +// assert_eq!(actual, None); +// } + +// #[test] +// fn dep_in_middle() { +// let mut a = TestDag::new(0); +// let mut b = TestDag::new(1); +// a.push(3); +// b.merge(&a); +// b.push(9); +// a.push(2); +// b.merge(&a); +// println!("{}", b.mermaid()); +// assert_eq!( +// b.find_replay_base(&[ID::new(0, 3)], &[ID::new(1, 8)]) +// .0 +// .first() +// .copied(), +// Some(ID::new(0, 2)) +// ); +// } + +// /// ![](https://mermaid.ink/img/pako:eNqNkTFPwzAQhf_K6SYqOZJ9CYsHJroxwYgXY7skInEq1xFCVf87jg5XVQQSnk6fz_feO5_RzT6gxsM4f7repgzPTyZCOafl7T3ZYw9uHELMkqls2juDTmp4bQV0O4M7aJqHwqlyEtDecFW5EkA3XFYuBaiVs0CInotfXSimqunW16q87gTcX6cqdqe27hSrKVZr_6tGTImn0nYqcWbaZiZWI1ajP9WK2zqnClFd5jVn3SIKnEKa7ODLb53Xa4O5D1MwqEvpbfowaOKl9C1Hb3PY-yHPCfXBjqcg0C55fvmKDnVOS6hNj4Mtgaefrss3dp6HFg) +// #[test] +// fn large_lamport_with_longer_path() { +// let mut a0 = TestDag::new(0); +// let mut a1 = TestDag::new(1); +// let mut a2 = TestDag::new(2); + +// a0.push(3); +// a1.merge(&a0); +// a2.merge(&a0); +// a1.push(3); +// a2.push(2); +// a2.push(1); +// a1.merge(&a2); +// a2.push(1); +// a1.push(1); +// a1.merge(&a2); +// a1.push(1); +// a0.push(1); +// a1.merge(&a2); +// a1.merge(&a0); +// println!("{}", a1.mermaid()); +// assert_eq!( +// a1.find_replay_base(&[ID::new(0, 3)], &[ID::new(1, 4)]) +// .0 +// .first() +// .copied(), +// Some(ID::new(0, 2)) +// ); +// assert_eq!( +// a1.find_replay_base(&[ID::new(2, 3)], &[ID::new(1, 3)]) +// .0 +// .iter() +// .copied() +// .collect::<Vec<_>>(), +// vec![ID::new(0, 2)] +// ); +// } +// } + +// mod find_replay_base_proptest { + +// use crate::{ +// array_mut_ref, +// span::HasIdSpan, +// tests::{PROPTEST_FACTOR_1, PROPTEST_FACTOR_10}, +// }; + +// use super::*; + +// proptest! { +// #[test] +// fn test_2dags( +// before_merged_insertions in prop::collection::vec(gen_interaction(2), 0..100 * PROPTEST_FACTOR_10), +// after_merged_insertions in prop::collection::vec(gen_interaction(2), 0..100 * PROPTEST_FACTOR_10) +// ) { +// test_single_head_meet(2, before_merged_insertions, after_merged_insertions)?; +// } + +// #[test] +// fn test_4dags( +// before_merged_insertions in prop::collection::vec(gen_interaction(4), 0..50 * PROPTEST_FACTOR_10), +// after_merged_insertions in prop::collection::vec(gen_interaction(4), 0..50 * PROPTEST_FACTOR_10) +// ) { +// test_single_head_meet(4, before_merged_insertions, after_merged_insertions)?; +// } + +// #[test] +// fn test_10dags( +// before_merged_insertions in prop::collection::vec(gen_interaction(10), 0..10 * PROPTEST_FACTOR_10 * PROPTEST_FACTOR_10), +// after_merged_insertions in prop::collection::vec(gen_interaction(10), 0..10 * PROPTEST_FACTOR_10 * PROPTEST_FACTOR_10) +// ) { +// test_single_head_meet(10, before_merged_insertions, after_merged_insertions)?; +// } + +// #[test] +// fn test_mul_ancestors_5dags( +// before_merged_insertions in prop::collection::vec(gen_interaction(10), 0..30 + PROPTEST_FACTOR_1 * 500), +// after_merged_insertions in prop::collection::vec(gen_interaction(10), 0..30 + PROPTEST_FACTOR_1 * 500) +// ) { +// test_mul_ancestors::<2>(5, before_merged_insertions, after_merged_insertions)?; +// } + +// #[test] +// fn test_mul_ancestors_10dags( +// before_merged_insertions in prop::collection::vec(gen_interaction(10), 0..10 * PROPTEST_FACTOR_10 * PROPTEST_FACTOR_10), +// after_merged_insertions in prop::collection::vec(gen_interaction(10), 0..10 * PROPTEST_FACTOR_10 * PROPTEST_FACTOR_10) +// ) { +// test_mul_ancestors::<3>(10, before_merged_insertions, after_merged_insertions)?; +// } + +// #[test] +// fn test_mul_ancestors_15dags_2( +// before_merged_insertions in prop::collection::vec(gen_interaction(15), 0..10 * PROPTEST_FACTOR_10 * PROPTEST_FACTOR_10), +// after_merged_insertions in prop::collection::vec(gen_interaction(15), 0..10 * PROPTEST_FACTOR_10 * PROPTEST_FACTOR_10) +// ) { +// test_mul_ancestors::<5>(15, before_merged_insertions, after_merged_insertions)?; +// } +// } + +// #[test] +// fn issue_0() { +// if let Err(err) = test_mul_ancestors::<3>( +// 10, +// vec![ +// Interaction { +// dag_idx: 1, +// merge_with: None, +// len: 1, +// }, +// Interaction { +// dag_idx: 8, +// merge_with: None, +// len: 2, +// }, +// ], +// vec![Interaction { +// dag_idx: 1, +// merge_with: None, +// len: 1, +// }], +// ) { +// println!("{}", err); +// panic!(); +// } +// } + +// #[test] +// fn issue_1() { +// test_single_head_meet( +// 2, +// vec![], +// vec![ +// Interaction { +// dag_idx: 0, +// merge_with: None, +// len: 1, +// }, +// Interaction { +// dag_idx: 0, +// merge_with: None, +// len: 1, +// }, +// ], +// ) +// .unwrap(); +// } + +// fn test_single_head_meet( +// dag_num: i32, +// mut before_merge_insertion: Vec<Interaction>, +// mut after_merge_insertion: Vec<Interaction>, +// ) -> Result<(), TestCaseError> { +// preprocess(&mut before_merge_insertion, dag_num); +// preprocess(&mut after_merge_insertion, dag_num); +// let mut dags = Vec::new(); +// for i in 0..dag_num { +// dags.push(TestDag::new(i as PeerID)); +// } + +// for interaction in before_merge_insertion { +// apply(interaction, &mut dags); +// } + +// for dag_idx in 1..dags.len() { +// let (dag0, dag) = arref::array_mut_ref!(&mut dags, [0, dag_idx]); +// dag0.merge(dag); +// } + +// dags[0].push(1); +// let expected = dags[0].frontier()[0]; +// for dag_idx in 1..dags.len() { +// let (dag0, dag) = arref::array_mut_ref!(&mut dags, [0, dag_idx]); +// dag.merge(dag0); +// } +// for interaction in after_merge_insertion.iter_mut() { +// if let Some(merge) = interaction.merge_with { +// // odd dag merges with the odd +// // even dag merges with the even +// if merge % 2 != interaction.dag_idx % 2 { +// interaction.merge_with = None; +// } +// } + +// apply(*interaction, &mut dags); +// } + +// let (dag0, dag1) = array_mut_ref!(&mut dags, [0, 1]); +// dag1.push(1); +// dag0.merge(dag1); +// // println!("{}", dag0.mermaid()); +// let a = dags[0].nodes.get(&0).unwrap().last().unwrap().id_last(); +// let b = dags[1].nodes.get(&1).unwrap().last().unwrap().id_last(); +// let actual = dags[0].find_replay_base(&[a], &[b]); +// prop_assert_eq!(&**actual.0, &[expected]); +// Ok(()) +// } + +// fn apply(interaction: Interaction, dags: &mut [TestDag]) { +// let Interaction { +// dag_idx, +// len, +// merge_with, +// } = interaction; +// if let Some(merge_with) = merge_with { +// let (dag, merge_target): (&mut TestDag, &mut TestDag) = +// array_mut_ref!(dags, [dag_idx, merge_with]); +// dag.push(len); +// dag.merge(merge_target); +// } else { +// dags[dag_idx].push(len); +// } +// } + +// fn test_mul_ancestors<const N: usize>( +// dag_num: i32, +// mut before_merge_insertion: Vec<Interaction>, +// mut after_merge_insertion: Vec<Interaction>, +// ) -> Result<(), TestCaseError> { +// assert!(dag_num - 2 >= N as i32); +// preprocess(&mut before_merge_insertion, dag_num); +// preprocess(&mut after_merge_insertion, dag_num); +// let mut dags = Vec::new(); +// for i in 0..dag_num { +// dags.push(TestDag::new(i as PeerID)); +// } + +// for mut interaction in before_merge_insertion { +// if interaction.dag_idx < N { +// // cannot act on first N nodes +// interaction.dag_idx = interaction.dag_idx % (dags.len() - N) + N; +// } +// if let Some(merge) = interaction.merge_with { +// if interaction.dag_idx == merge { +// let next_merge = (merge + 1) % dags.len(); +// interaction.merge_with = Some(next_merge); +// } +// } + +// apply(interaction, &mut dags); +// } + +// for target in 0..N { +// for i in N..dags.len() { +// let (target, dag): (&mut TestDag, &mut TestDag) = +// arref::array_mut_ref!(&mut dags, [target, i]); +// target.merge(dag); +// } +// } + +// let mut expected = Vec::with_capacity(N); +// for dag in dags[0..N].iter_mut() { +// dag.push(1); +// expected.push(dag.frontier[0]); +// } + +// for target in 0..N { +// for i in N..dags.len() { +// let (target, dag): (&mut TestDag, &mut TestDag) = +// arref::array_mut_ref!(&mut dags, [target, i]); +// dag.merge(target); +// } +// } + +// let mut merged_to_even = [false; N]; +// let mut merged_to_odd = [false; N]; + +// for interaction in after_merge_insertion.iter_mut() { +// if interaction.dag_idx < N { +// // cannot act on first N nodes +// interaction.dag_idx = interaction.dag_idx % (dags.len() - N) + N; +// } +// if let Some(mut merge) = interaction.merge_with { +// if interaction.dag_idx == merge { +// let next_merge = (merge + 1) % dags.len(); +// interaction.merge_with = Some(next_merge); +// merge = next_merge; +// } + +// // odd dag merges with the odd +// // even dag merges with the even +// if merge >= N && merge % 2 != interaction.dag_idx % 2 { +// interaction.merge_with = None; +// } +// if merge < N { +// if interaction.dag_idx % 2 == 0 { +// merged_to_even[merge] = true; +// } else { +// merged_to_odd[merge] = true; +// } +// } +// } + +// if dags[interaction.dag_idx].is_first() { +// // need to merge to one of the shared-history dags first +// let target = interaction.dag_idx % N; +// let (dag, target) = arref::array_mut_ref!(&mut dags, [interaction.dag_idx, target]); +// dag.merge(target); +// } + +// apply(*interaction, &mut dags); +// } + +// // make the shared-history dags be merged to opposite side (even/odd) +// for i in 0..N { +// let (odd, even) = if N % 2 == 0 { (N + 1, N) } else { (N, N + 1) }; +// if !merged_to_even[i] && i % 2 != 0 { +// let (dag_a, dag_b) = array_mut_ref!(&mut dags, [even, i]); +// dag_a.merge(dag_b); +// dag_a.push(1); +// } +// if !merged_to_odd[i] && i % 2 == 0 { +// let (dag_a, dag_b) = array_mut_ref!(&mut dags, [odd, i]); +// dag_a.merge(dag_b); +// dag_a.push(1); +// } +// } + +// // merge with all odds or evens +// for i in dags.len() - 2..dags.len() { +// if i % 2 == 0 { +// for target in (0..dags.len() - 2).step_by(2) { +// let (dag_a, dag_b) = array_mut_ref!(&mut dags, [i, target]); +// dag_a.merge(dag_b); +// dag_a.push(1); +// } +// } else { +// for target in (1..dags.len() - 2).step_by(2) { +// let (dag_a, dag_b) = array_mut_ref!(&mut dags, [i, target]); +// dag_a.merge(dag_b); +// dag_a.push(1); +// } +// } +// } + +// let len = dags.len(); +// let (dag_a, dag_b) = array_mut_ref!(&mut dags, [len - 2, len - 1]); +// dag_a.push(1); +// dag_b.push(1); +// dag_a.merge(dag_b); +// let a = dag_a.get_last_node().id; +// let b = dag_b.get_last_node().id; +// let mut actual = dag_a.find_replay_base(&[a], &[b]).0; +// actual.sort(); +// let actual = actual.iter().copied().collect::<Vec<_>>(); +// if actual != expected { +// println!("{}", dag_a.mermaid()); +// } + +// prop_assert_eq!(actual, expected); +// Ok(()) +// } +// } + +// #[cfg(test)] +// mod dag_partial_iter { +// use loro_common::HasCounterSpan; + +// use crate::{dag::iter::IterReturn, tests::PROPTEST_FACTOR_10}; + +// use super::*; + +// fn test_partial_iter( +// dag_num: i32, +// mut interactions: Vec<Interaction>, +// ) -> Result<(), TestCaseError> { +// preprocess(&mut interactions, dag_num); +// let mut dags = Vec::new(); +// for i in 0..dag_num { +// dags.push(TestDag::new(i as PeerID)); +// } + +// for interaction in interactions.iter_mut() { +// interaction.apply(&mut dags); +// } + +// for i in 1..dag_num { +// let (a, b) = array_mut_ref!(&mut dags, [0, i as usize]); +// a.merge(b); +// } + +// let a = &dags[0]; +// let mut nodes = Vec::new(); +// for (node, vv) in a.iter_with_vv() { +// nodes.push((node, vv)); +// } + +// let mut map = FxHashMap::default(); +// for (node, vv) in nodes.iter() { +// map.insert(node.id, vv.clone()); +// } +// let vec: Vec<_> = nodes.iter().enumerate().collect(); +// { +// // println!("{}", a.mermaid()); +// } +// for &(i, (node, vv)) in vec.iter() { +// if i > 3 { +// break; +// } + +// for &(j, (_other_node, other_vv)) in vec.iter() { +// if i >= j { +// continue; +// } + +// let diff_spans = other_vv.diff(vv).left; +// { +// // println!("TARGET IS TO GO FROM {} TO {}", node.id, other_node.id); +// // dbg!(&other_vv, &vv, &diff_spans); +// } +// let mut target_vv = vv.clone(); +// target_vv.forward(&diff_spans); + +// for IterReturn { data, slice } in a.iter_causal(&[node.id], diff_spans.clone()) { +// let sliced = data.slice(slice.start as usize, slice.end as usize); +// { +// // println!("-----------------------------------"); +// // dbg!(&sliced, &forward, &retreat, slice); +// } +// assert!(diff_spans +// .get(&data.id.peer) +// .unwrap() +// .contains(sliced.id.counter)); +// let mut data_vv = map.get(&data.id).unwrap().clone(); +// data_vv.extend_to_include(IdSpan::new( +// sliced.id.peer, +// sliced.id.counter, +// sliced.id.counter + 1, +// )); +// data_vv.shrink_to_exclude(IdSpan::new( +// sliced.id.peer, +// sliced.id.counter, +// sliced.ctr_end(), +// )); +// } +// } +// } + +// Ok(()) +// } + +// #[test] +// #[ignore] +// fn issue() { +// if let Err(err) = test_partial_iter( +// 5, +// vec![ +// Interaction { +// dag_idx: 0, +// merge_with: None, +// len: 2, +// }, +// Interaction { +// dag_idx: 1, +// merge_with: Some(0), +// len: 1, +// }, +// Interaction { +// dag_idx: 0, +// merge_with: None, +// len: 1, +// }, +// Interaction { +// dag_idx: 0, +// merge_with: Some(1), +// len: 1, +// }, +// ], +// ) { +// panic!("{}", err); +// } +// } + +// proptest! { +// #[test] +// #[ignore] +// fn proptest_iter_2( +// interactions in prop::collection::vec(gen_interaction(2), 0..40 * PROPTEST_FACTOR_10), +// ) { +// test_partial_iter(2, interactions)?; +// } + +// fn proptest_iter_3( +// interactions in prop::collection::vec(gen_interaction(3), 0..40 * PROPTEST_FACTOR_10), +// ) { +// test_partial_iter(3, interactions)?; +// } + +// fn proptest_iter_5( +// interactions in prop::collection::vec(gen_interaction(5), 0..40 * PROPTEST_FACTOR_10), +// ) { +// test_partial_iter(5, interactions)?; +// } +// } +// } diff --git a/vendor/loro-internal/src/delta.rs b/vendor/loro-internal/src/delta.rs new file mode 100644 index 0000000..efc72a0 --- /dev/null +++ b/vendor/loro-internal/src/delta.rs @@ -0,0 +1,14 @@ +mod movable_list; +pub(crate) use movable_list::{ElementDelta, MovableListInnerDelta}; +mod seq; +pub use seq::{Delta, DeltaItem, DeltaType, DeltaValue, Meta}; +mod map; +pub use map::{MapDiff, ValuePair}; +mod map_delta; +pub use map_delta::{MapDelta, MapValue, ResolvedMapDelta, ResolvedMapValue}; +mod text; +pub use text::{StyleMeta, StyleMetaItem}; +mod tree; +pub use tree::{ + TreeDelta, TreeDeltaItem, TreeDiff, TreeDiffItem, TreeExternalDiff, TreeInternalDiff, +}; diff --git a/vendor/loro-internal/src/delta/map.rs b/vendor/loro-internal/src/delta/map.rs new file mode 100644 index 0000000..9b650f7 --- /dev/null +++ b/vendor/loro-internal/src/delta/map.rs @@ -0,0 +1,203 @@ +use rustc_hash::{FxHashMap, FxHashSet}; +use serde::Serialize; +use std::fmt::Debug; + +use crate::{InternalString, LoroValue}; + +#[derive(Clone, Debug, Serialize)] +pub struct ValuePair<T> { + pub old: T, + pub new: T, +} + +impl From<(LoroValue, LoroValue)> for ValuePair<LoroValue> { + fn from((old, new): (LoroValue, LoroValue)) -> Self { + ValuePair { old, new } + } +} + +#[derive(Clone, Debug, Serialize)] +pub struct MapDiff<T> { + pub added: FxHashMap<InternalString, T>, + pub updated: FxHashMap<InternalString, ValuePair<T>>, + pub deleted: FxHashMap<InternalString, T>, +} + +impl<T> MapDiff<T> { + pub fn new() -> Self { + Self::default() + } + + pub fn insert(mut self, key: InternalString, value: T) -> Self { + self.deleted.remove(&key); + self.added.insert(key, value); + self + } + + pub fn delete(mut self, key: &InternalString, value: T) -> Self { + self.added.remove(key); + self.deleted.insert(key.clone(), value); + self + } + + pub fn compose(mut self, other: Self) -> Self { + for (k, v) in other.added.into_iter() { + if let Some(dv) = self.deleted.remove(&k) { + self.updated.insert(k, ValuePair { old: dv, new: v }); + } else if let Some(ValuePair { old: _, new }) = self.updated.get_mut(&k) { + // should not happen in transaction + *new = v; + } else { + self.added.insert(k, v); + } + } + + for (k, v) in other.deleted.into_iter() { + if let Some(av) = self.added.remove(&k) { + self.deleted.insert(k, av); + } else if let Some(ValuePair { old, .. }) = self.updated.remove(&k) { + self.deleted.insert(k, old); + } else { + // delete old value + self.deleted.insert(k, v); + } + } + + for (k, ValuePair { old, new }) in other.updated.into_iter() { + if let Some(av) = self.added.get_mut(&k) { + *av = new; + } else if let Some(dv) = self.deleted.remove(&k) { + self.updated.insert(k, ValuePair { old: dv, new }); + } else if let Some(ValuePair { old: _, new: n }) = self.updated.get_mut(&k) { + *n = new + } else { + self.updated.insert(k, ValuePair { old, new }); + } + } + self + } +} + +#[derive(Clone, Debug, Serialize)] +#[allow(dead_code)] +pub struct MapDiffRaw<T> { + pub(crate) added: FxHashMap<InternalString, T>, + pub(crate) deleted: FxHashSet<InternalString>, +} + +impl<T> Default for MapDiff<T> { + fn default() -> Self { + Self { + added: Default::default(), + updated: Default::default(), + deleted: Default::default(), + } + } +} + +#[cfg(test)] +mod tests { + use super::{MapDiff, ValuePair}; + use crate::InternalString; + + fn key(value: &str) -> InternalString { + value.into() + } + + fn map_diff( + added: &[(&str, i32)], + updated: &[(&str, (i32, i32))], + deleted: &[(&str, i32)], + ) -> MapDiff<i32> { + let mut ans = MapDiff::new(); + for (k, v) in added { + ans.added.insert(key(k), *v); + } + for (k, (old, new)) in updated { + ans.updated.insert( + key(k), + ValuePair { + old: *old, + new: *new, + }, + ); + } + for (k, v) in deleted { + ans.deleted.insert(key(k), *v); + } + ans + } + + fn assert_map_diff_eq(actual: MapDiff<i32>, expected: MapDiff<i32>) { + assert_eq!(actual.added, expected.added); + assert_eq!(actual.deleted, expected.deleted); + + assert_eq!(actual.updated.len(), expected.updated.len()); + for (key, expected_pair) in expected.updated { + let actual_pair = actual.updated.get(&key).unwrap_or_else(|| { + panic!("missing updated entry for key {:?}", key); + }); + assert_eq!(actual_pair.old, expected_pair.old); + assert_eq!(actual_pair.new, expected_pair.new); + } + } + + #[test] + fn insert_replaces_previous_delete_marker() { + let diff = map_diff(&[], &[], &[("key", 1)]).insert(key("key"), 2); + assert_map_diff_eq(diff, map_diff(&[("key", 2)], &[], &[])); + } + + #[test] + fn delete_removes_pending_add_and_records_deleted_value() { + let diff = map_diff(&[("key", 1)], &[], &[]).delete(&key("key"), 1); + assert_map_diff_eq(diff, map_diff(&[], &[], &[("key", 1)])); + } + + #[test] + fn compose_add_then_update_keeps_latest_value_in_added() { + let lhs = map_diff(&[("key", 1)], &[], &[]); + let rhs = map_diff(&[], &[("key", (1, 2))], &[]); + + assert_map_diff_eq(lhs.compose(rhs), map_diff(&[("key", 2)], &[], &[])); + } + + #[test] + fn compose_delete_then_add_becomes_update_with_original_old_value() { + let lhs = map_diff(&[], &[], &[("key", 1)]); + let rhs = map_diff(&[("key", 2)], &[], &[]); + + assert_map_diff_eq(lhs.compose(rhs), map_diff(&[], &[("key", (1, 2))], &[])); + } + + #[test] + fn compose_update_then_delete_keeps_initial_old_value() { + let lhs = map_diff(&[], &[("key", (1, 2))], &[]); + let rhs = map_diff(&[], &[], &[("key", 2)]); + + assert_map_diff_eq(lhs.compose(rhs), map_diff(&[], &[], &[("key", 1)])); + } + + #[test] + fn compose_multiple_updates_preserves_first_old_and_latest_new() { + let lhs = map_diff(&[], &[("key", (1, 2))], &[]); + let rhs = map_diff(&[], &[("key", (2, 3))], &[]); + let third = map_diff(&[], &[("key", (3, 4))], &[]); + + assert_map_diff_eq( + lhs.compose(rhs).compose(third), + map_diff(&[], &[("key", (1, 4))], &[]), + ); + } + + #[test] + fn compose_is_key_local_and_preserves_other_entries() { + let lhs = map_diff(&[("added", 10)], &[("updated", (1, 2))], &[("deleted", 3)]); + let rhs = map_diff(&[("added", 11)], &[("updated", (2, 3))], &[("deleted", 4)]); + + assert_map_diff_eq( + lhs.compose(rhs), + map_diff(&[("added", 11)], &[("updated", (1, 3))], &[("deleted", 4)]), + ); + } +} diff --git a/vendor/loro-internal/src/delta/map_delta.rs b/vendor/loro-internal/src/delta/map_delta.rs new file mode 100644 index 0000000..966ebeb --- /dev/null +++ b/vendor/loro-internal/src/delta/map_delta.rs @@ -0,0 +1,315 @@ +use std::hash::Hash; + +use loro_common::IdLp; +use rustc_hash::FxHashMap; +use serde::{ser::SerializeStruct, Serialize}; + +use crate::{ + change::Lamport, handler::ValueOrHandler, id::PeerID, span::HasLamport, InternalString, + LoroValue, +}; + +#[derive(Default, Debug, Clone, Serialize)] +pub struct MapDelta { + /// If the value is none, it's a uncreate op that should remove the entry from the + /// map container. + pub updated: FxHashMap<InternalString, Option<MapValue>>, +} + +#[derive(Debug, Clone)] +pub struct MapValue { + pub value: Option<LoroValue>, + pub lamp: Lamport, + pub peer: PeerID, +} + +impl Ord for MapValue { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.lamp + .cmp(&other.lamp) + .then_with(|| self.peer.cmp(&other.peer)) + } +} + +impl PartialOrd for MapValue { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl PartialEq for MapValue { + fn eq(&self, other: &Self) -> bool { + self.lamp == other.lamp && self.peer == other.peer + } +} + +impl Eq for MapValue {} + +impl MapValue { + pub fn idlp(&self) -> IdLp { + IdLp::new(self.peer, self.lamp) + } +} + +#[derive(Default, Debug, Clone)] +pub struct ResolvedMapDelta { + pub updated: FxHashMap<InternalString, ResolvedMapValue>, +} + +#[derive(Debug, Clone)] +pub struct ResolvedMapValue { + pub value: Option<ValueOrHandler>, + pub idlp: IdLp, +} + +impl ResolvedMapValue { + /// This is used to indicate that the entry is unset. (caused by checkout to before the entry is created) + pub fn new_unset() -> Self { + ResolvedMapValue { + idlp: IdLp::new(PeerID::default(), Lamport::MAX), + value: None, + } + } +} + +impl MapDelta { + pub(crate) fn compose(mut self, x: MapDelta) -> MapDelta { + for (k, v) in x.updated.into_iter() { + if let Some(old) = self.updated.get_mut(&k) { + if &v > old { + *old = v; + } + } else { + self.updated.insert(k, v); + } + } + self + } + + #[inline] + pub fn new() -> Self { + MapDelta { + updated: FxHashMap::default(), + } + } + + #[inline] + pub fn with_entry(mut self, key: InternalString, map_value: MapValue) -> Self { + self.updated.insert(key, Some(map_value)); + self + } +} + +impl ResolvedMapDelta { + pub(crate) fn compose(mut self, x: ResolvedMapDelta) -> ResolvedMapDelta { + // Compose into `self` in place; cloning `self.updated` here made + // composing N fragments into one map event O(N^2). + for (k, v) in x.updated.into_iter() { + if let Some(old) = self.updated.get_mut(&k) { + if v.idlp > old.idlp { + *old = v; + } + } else { + self.updated.insert(k, v); + } + } + self + } + + #[inline] + pub fn new() -> Self { + ResolvedMapDelta { + updated: FxHashMap::default(), + } + } + + #[inline] + pub fn with_entry(mut self, key: InternalString, map_value: ResolvedMapValue) -> Self { + self.updated.insert(key, map_value); + self + } + + pub(crate) fn transform(&mut self, b: &ResolvedMapDelta, left_prior: bool) { + for (k, _) in b.updated.iter() { + if !left_prior { + self.updated.remove(k); + } + } + } +} + +impl Hash for MapValue { + fn hash<H: std::hash::Hasher>(&self, state: &mut H) { + // value is not being hashed + self.peer.hash(state); + self.lamp.hash(state); + } +} + +impl HasLamport for MapValue { + fn lamport(&self) -> Lamport { + self.lamp + } +} + +impl Serialize for MapValue { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + let mut s = serializer.serialize_struct("MapValue", 2)?; + s.serialize_field("value", &self.value)?; + s.serialize_field("lamport", &self.lamp)?; + s.serialize_field("id", &self.idlp())?; + s.end() + } +} + +#[cfg(test)] +mod tests { + use std::hash::{Hash, Hasher}; + + use rustc_hash::FxHasher; + + use crate::{handler::ValueOrHandler, LoroValue}; + + use super::*; + + fn key(value: &str) -> InternalString { + value.into() + } + + fn map_value(lamp: Lamport, peer: PeerID, value: i64) -> MapValue { + MapValue { + value: Some(LoroValue::I64(value)), + lamp, + peer, + } + } + + fn resolved_value(lamp: Lamport, peer: PeerID, value: i64) -> ResolvedMapValue { + ResolvedMapValue { + value: Some(ValueOrHandler::Value(LoroValue::I64(value))), + idlp: IdLp::new(peer, lamp), + } + } + + fn hash_map_value(value: &MapValue) -> u64 { + let mut hasher = FxHasher::default(); + value.hash(&mut hasher); + hasher.finish() + } + + #[test] + fn map_value_ordering_identity_and_hash_are_timestamp_based() { + let lower_lamport = map_value(1, 9, 10); + let higher_lamport = map_value(2, 1, 20); + let lower_peer = map_value(2, 1, 30); + let higher_peer = map_value(2, 2, 40); + + assert!(higher_lamport > lower_lamport); + assert!(higher_peer > lower_peer); + assert_eq!(higher_peer.idlp(), IdLp::new(2, 2)); + assert_eq!(higher_peer.lamport(), 2); + + let same_id_different_value = MapValue { + value: Some(LoroValue::I64(999)), + ..higher_peer.clone() + }; + assert_eq!(higher_peer, same_id_different_value); + assert_eq!( + hash_map_value(&higher_peer), + hash_map_value(&same_id_different_value) + ); + } + + #[test] + fn map_delta_compose_keeps_latest_timestamp_per_key() { + let initial = MapDelta::new() + .with_entry(key("same"), map_value(2, 1, 10)) + .with_entry(key("left-only"), map_value(1, 1, 11)); + + let mut incoming = MapDelta::new() + .with_entry(key("same"), map_value(2, 2, 20)) + .with_entry(key("right-only"), map_value(1, 1, 21)); + incoming.updated.insert(key("unset"), None); + + let composed = initial.compose(incoming); + assert_eq!( + composed + .updated + .get(&key("same")) + .and_then(|value| value.as_ref()) + .and_then(|value| value.value.as_ref()), + Some(&LoroValue::I64(20)) + ); + assert!(composed.updated.contains_key(&key("left-only"))); + assert!(composed.updated.contains_key(&key("right-only"))); + assert_eq!(composed.updated.get(&key("unset")), Some(&None)); + } + + #[test] + fn map_delta_compose_does_not_let_older_entries_overwrite_newer_ones() { + let initial = MapDelta::new().with_entry(key("same"), map_value(5, 1, 50)); + let incoming = MapDelta::new().with_entry(key("same"), map_value(4, 9, 40)); + + let composed = initial.compose(incoming); + let value = composed + .updated + .get(&key("same")) + .and_then(|value| value.as_ref()) + .and_then(|value| value.value.as_ref()); + assert_eq!(value, Some(&LoroValue::I64(50))); + } + + #[test] + fn resolved_map_delta_compose_and_transform_apply_the_same_conflict_contract() { + let left = ResolvedMapDelta::new() + .with_entry(key("same"), resolved_value(1, 1, 10)) + .with_entry(key("left-only"), resolved_value(1, 1, 11)); + let right = ResolvedMapDelta::new() + .with_entry(key("same"), resolved_value(1, 2, 20)) + .with_entry(key("right-only"), resolved_value(1, 1, 21)); + + let composed = left.compose(right.clone()); + let value = composed.updated.get(&key("same")).unwrap(); + assert_eq!(value.idlp, IdLp::new(2, 1)); + assert_eq!(value.value.as_ref().unwrap().to_value(), LoroValue::I64(20)); + assert!(composed.updated.contains_key(&key("left-only"))); + assert!(composed.updated.contains_key(&key("right-only"))); + + let mut left_prior = composed.clone(); + left_prior.transform(&right, true); + assert!(left_prior.updated.contains_key(&key("same"))); + + let mut right_prior = composed; + right_prior.transform(&right, false); + assert!(!right_prior.updated.contains_key(&key("same"))); + assert!(!right_prior.updated.contains_key(&key("right-only"))); + assert!(right_prior.updated.contains_key(&key("left-only"))); + } + + #[test] + fn resolved_unset_uses_max_lamport_to_win_against_material_values() { + let unset = ResolvedMapValue::new_unset(); + let value = resolved_value(Lamport::MAX - 1, PeerID::MAX, 1); + + let composed = ResolvedMapDelta::new() + .with_entry(key("field"), value) + .compose(ResolvedMapDelta::new().with_entry(key("field"), unset)); + let entry = composed.updated.get(&key("field")).unwrap(); + assert_eq!(entry.idlp, IdLp::new(PeerID::default(), Lamport::MAX)); + assert!(entry.value.is_none()); + } + + #[test] + fn map_value_serialization_exposes_value_lamport_and_id() { + let serialized = serde_json::to_value(map_value(7, 8, 42)).unwrap(); + assert_eq!(serialized["value"], serde_json::json!(42)); + assert_eq!(serialized["lamport"], serde_json::json!(7)); + assert_eq!( + serialized["id"], + serde_json::json!({ "peer": 8, "lamport": 7 }) + ); + } +} diff --git a/vendor/loro-internal/src/delta/movable_list.rs b/vendor/loro-internal/src/delta/movable_list.rs new file mode 100644 index 0000000..6c2a1e4 --- /dev/null +++ b/vendor/loro-internal/src/delta/movable_list.rs @@ -0,0 +1,56 @@ +use loro_common::{CompactIdLp, IdFull, IdLp, LoroValue}; +use rustc_hash::FxHashMap; +use smallvec::SmallVec; + +use super::{Delta, DeltaValue}; + +#[derive(Clone, Debug)] +pub(crate) struct MovableListInnerDelta { + pub list: Delta<SmallVec<[IdFull; 1]>, ()>, + pub elements: FxHashMap<CompactIdLp, ElementDelta>, +} + +impl DeltaValue for SmallVec<[IdFull; 1]> { + fn value_extend(&mut self, other: Self) -> Result<(), Self> { + for v in other { + self.push(v) + } + + Ok(()) + } + + fn take(&mut self, length: usize) -> Self { + self.drain(..length).collect() + } + + fn length(&self) -> usize { + self.len() + } +} + +impl MovableListInnerDelta { + pub(crate) fn is_empty(&self) -> bool { + self.list.is_empty() && self.elements.is_empty() + } +} + +#[derive(Clone, Debug)] +pub struct ElementDelta { + /// This must be Some if it's in checkout mode (not fast-forward mode) + pub pos: Option<IdLp>, + pub value: LoroValue, + pub value_updated: bool, + /// This must be Some if it's in checkout mode (not fast-forward mode) + pub value_id: Option<IdLp>, +} + +impl ElementDelta { + pub fn placeholder() -> Self { + Self { + pos: None, + value: LoroValue::Null, + value_updated: false, + value_id: None, + } + } +} diff --git a/vendor/loro-internal/src/delta/seq.rs b/vendor/loro-internal/src/delta/seq.rs new file mode 100644 index 0000000..eed69a5 --- /dev/null +++ b/vendor/loro-internal/src/delta/seq.rs @@ -0,0 +1,950 @@ +use enum_as_inner::EnumAsInner; +use serde::Serialize; +use std::fmt::Debug; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Delta<Value, Meta = ()> { + pub(crate) vec: Vec<DeltaItem<Value, Meta>>, +} + +impl<V: Serialize, M: Serialize> Serialize for Delta<V, M> { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + serializer.collect_seq(self.vec.iter()) + } +} + +#[derive(Debug, EnumAsInner, Clone, PartialEq, Eq, Serialize)] +pub enum DeltaItem<Value, Meta> { + Retain { retain: usize, attributes: Meta }, + Insert { insert: Value, attributes: Meta }, + Delete { delete: usize, attributes: Meta }, +} + +#[derive(PartialEq, Debug, Eq)] +pub enum DeltaType { + Retain, + Insert, + Delete, +} + +/// The metadata of a DeltaItem +/// If empty metadata is used to override the older one, we will remove the metadata into None +pub trait Meta: Debug + Clone + PartialEq + Default { + fn empty() -> Self { + Self::default() + } + fn is_empty(&self) -> bool; + + /// this is used when composing two [DeltaItem]s with the same length + fn compose(&mut self, other: &Self, type_pair: (DeltaType, DeltaType)); + #[allow(unused)] + fn take(&mut self, other: &Self) -> Self { + self.clone() + } + + fn is_mergeable(&self, other: &Self) -> bool; + /// This is used when we merge two [DeltaItem]s. + /// And it's guaranteed that [Meta::is_mergeable] is true + fn merge(&mut self, other: &Self); +} + +impl Meta for () { + fn empty() -> Self {} + fn is_empty(&self) -> bool { + true + } + + fn compose(&mut self, _other: &Self, _type_pair: (DeltaType, DeltaType)) {} + + fn is_mergeable(&self, _other: &Self) -> bool { + true + } + + fn merge(&mut self, _other: &Self) {} +} + +/// The value of [DeltaItem::Insert] +pub trait DeltaValue: Debug + Sized { + /// the other will be merged into self + fn value_extend(&mut self, other: Self) -> Result<(), Self>; + /// takes the first number of `length` elements + fn take(&mut self, length: usize) -> Self; + /// the length of the value + fn length(&self) -> usize; +} + +impl<V: DeltaValue, M: Debug> DeltaValue for DeltaItem<V, M> { + fn value_extend(&mut self, _other: Self) -> Result<(), Self> { + unreachable!() + } + + fn take(&mut self, _length: usize) -> Self { + unreachable!() + } + + fn length(&self) -> usize { + match self { + DeltaItem::Retain { + retain: len, + attributes: _, + } => *len, + DeltaItem::Insert { + insert: value, + attributes: _, + } => value.length(), + DeltaItem::Delete { + delete: len, + attributes: _, + } => *len, + } + } +} + +impl<Value: DeltaValue, M: Meta> DeltaItem<Value, M> { + pub fn meta(&self) -> &M { + match self { + DeltaItem::Insert { + attributes: meta, .. + } => meta, + DeltaItem::Retain { + attributes: meta, .. + } => meta, + DeltaItem::Delete { + delete: _, + attributes: meta, + } => meta, + } + } + + pub fn meta_mut(&mut self) -> &mut M { + match self { + DeltaItem::Insert { + attributes: meta, .. + } => meta, + DeltaItem::Retain { + attributes: meta, .. + } => meta, + DeltaItem::Delete { + delete: _, + attributes: meta, + } => meta, + } + } + + pub fn set_meta(&mut self, meta: M) { + match self { + DeltaItem::Insert { attributes: m, .. } => *m = meta, + DeltaItem::Retain { attributes: m, .. } => *m = meta, + DeltaItem::Delete { + delete: _, + attributes: m, + } => *m = meta, + } + } + + fn type_(&self) -> DeltaType { + match self { + DeltaItem::Insert { .. } => DeltaType::Insert, + DeltaItem::Retain { .. } => DeltaType::Retain, + DeltaItem::Delete { .. } => DeltaType::Delete, + } + } + + pub fn compose_meta(&mut self, other: &Self) { + let type_pair = (self.type_(), other.type_()); + let meta = self.meta_mut(); + let other_meta = other.meta(); + Meta::compose(meta, other_meta, type_pair); + } + + // change self-length to self.len()-length + // and return the taken one. + pub(crate) fn take(&mut self, length: usize) -> Self { + match self { + DeltaItem::Insert { + insert: value, + attributes: meta, + } => { + let v = value.take(length); + Self::Insert { + insert: v, + attributes: meta.clone(), + } + } + DeltaItem::Retain { + retain: len, + attributes: meta, + } => { + *len -= length; + Self::Retain { + retain: length, + attributes: meta.clone(), + } + } + DeltaItem::Delete { + delete: len, + attributes: _, + } => { + *len -= length; + Self::Delete { + delete: length, + // meta may store utf16 length, this take will invalidate it + attributes: M::empty(), + } + } + } + } + + pub(crate) fn take_with_meta_ref(&mut self, length: usize, other_meta: &Self) -> Self { + match self { + DeltaItem::Insert { + insert: value, + attributes: meta, + } => { + let v = value.take(length); + Self::Insert { + insert: v, + attributes: meta.take(other_meta.meta()), + } + } + DeltaItem::Retain { + retain: len, + attributes: meta, + } => { + *len -= length; + Self::Retain { + retain: length, + attributes: meta.take(other_meta.meta()), + } + } + DeltaItem::Delete { + delete: len, + attributes: meta, + } => { + *len -= length; + Self::Delete { + delete: length, + attributes: meta.take(other_meta.meta()), + } + } + } + } + + fn insert_inner(self) -> Value { + match self { + DeltaItem::Insert { insert: value, .. } => value, + _ => unreachable!(), + } + } +} + +#[derive(Debug)] +pub struct DeltaIterator<V, M: Meta> { + // The reversed Vec uses pop() to simulate getting the first element each time + ops: Vec<DeltaItem<V, M>>, +} + +impl<V: DeltaValue, M: Meta> DeltaIterator<V, M> { + fn new(ops: Vec<DeltaItem<V, M>>) -> Self { + Self { ops } + } + + #[inline(always)] + fn next<L: Into<Option<usize>>>(&mut self, len: L) -> DeltaItem<V, M> { + self.next_impl(len.into()) + } + + fn next_impl(&mut self, len: Option<usize>) -> DeltaItem<V, M> { + let length = len.unwrap_or(usize::MAX); + let next_op = self.peek_mut(); + if next_op.is_none() { + return DeltaItem::Retain { + retain: usize::MAX, + attributes: M::empty(), + }; + } + let op = next_op.unwrap(); + let op_length = op.length(); + if length < op_length { + // a part of the peek op + op.take(length) + } else { + self.take_peek().unwrap() + } + } + + fn next_with_ref(&mut self, len: usize, other: &DeltaItem<V, M>) -> DeltaItem<V, M> { + let next_op = self.peek_mut(); + if next_op.is_none() { + return DeltaItem::Retain { + retain: other.length(), + attributes: M::empty(), + }; + } + let op = next_op.unwrap(); + let op_length = op.length(); + if len < op_length { + // a part of the peek op + op.take_with_meta_ref(len, other) + } else { + self.take_peek().unwrap() + } + } + + fn next_pair(&mut self, other: &mut Self) -> (DeltaItem<V, M>, DeltaItem<V, M>) { + let self_len = self.peek_length(); + let other_len = other.peek_length(); + if self_len > other_len { + let length = other_len; + let other_op = other.next(None); + debug_assert_eq!(other_op.length(), length); + let this_op = self.next_with_ref(length, &other_op); + (this_op, other_op) + } else { + let length = self_len; + let this_op = self.next(None); + debug_assert_eq!(this_op.length(), length); + let other_op = other.next_with_ref(length, &this_op); + (this_op, other_op) + } + } + + fn peek_mut(&mut self) -> Option<&mut DeltaItem<V, M>> { + self.ops.last_mut() + } + + fn take_peek(&mut self) -> Option<DeltaItem<V, M>> { + self.ops.pop() + } + + fn rest(mut self) -> Vec<DeltaItem<V, M>> { + self.ops.reverse(); + self.ops + } + + fn has_next(&self) -> bool { + !self.ops.is_empty() + } + + fn peek(&self) -> Option<&DeltaItem<V, M>> { + self.ops.last() + } + + fn peek_length(&self) -> usize { + if let Some(op) = self.peek() { + op.length() + } else { + usize::MAX + } + } + + fn peek_is_insert(&self) -> bool { + if let Some(op) = self.peek() { + op.is_insert() + } else { + false + } + } + + fn peek_is_delete(&self) -> bool { + if let Some(op) = self.peek() { + op.is_delete() + } else { + false + } + } +} + +impl<Value: DeltaValue, M: Meta> Delta<Value, M> { + pub fn new() -> Self { + Self { vec: Vec::new() } + } + + pub fn items(&self) -> &[DeltaItem<Value, M>] { + &self.vec + } + + pub fn inner(self) -> Vec<DeltaItem<Value, M>> { + self.vec + } + + pub fn retain_with_meta(mut self, len: usize, meta: M) -> Self { + if len == 0 { + // currently no meta for retain if len == 0 + return self; + } + + self.push(DeltaItem::Retain { + retain: len, + attributes: meta, + }); + self + } + + pub fn insert_with_meta<V: Into<Value>>(mut self, value: V, meta: M) -> Self { + self.push(DeltaItem::Insert { + insert: value.into(), + attributes: meta, + }); + self + } + + pub fn delete_with_meta(mut self, len: usize, meta: M) -> Self { + self.push(DeltaItem::Delete { + delete: len, + attributes: meta, + }); + self + } + + pub fn delete(mut self, len: usize) -> Self { + if len == 0 { + return self; + } + self.push(DeltaItem::Delete { + delete: len, + attributes: M::empty(), + }); + self + } + + pub fn retain(mut self, len: usize) -> Self { + if len == 0 { + return self; + } + + self.push(DeltaItem::Retain { + retain: len, + attributes: M::empty(), + }); + self + } + + pub fn insert<V: Into<Value>>(mut self, value: V) -> Self { + self.push(DeltaItem::Insert { + insert: value.into(), + attributes: M::empty(), + }); + self + } + + // If the new_op is merged, return true + pub fn push(&mut self, new_op: DeltaItem<Value, M>) -> bool { + let mut index = self.vec.len(); + let last_op = self.vec.pop(); + if let Some(mut last_op) = last_op { + if new_op.is_delete() && last_op.is_delete() { + *last_op.as_delete_mut().unwrap().0 += new_op.length(); + self.vec.push(last_op); + return true; + } + // Since it does not matter if we insert before or after deleting at the same index, + // always prefer to insert first + if last_op.is_delete() && new_op.is_insert() { + index -= 1; + let _last_op = self.vec.pop(); + self.vec.push(last_op); + if let Some(_last_op_inner) = _last_op { + last_op = _last_op_inner; + } else { + self.vec.insert(0, new_op); + return true; + }; + } + if last_op.meta().is_mergeable(new_op.meta()) { + if new_op.is_insert() && last_op.is_insert() { + let value = last_op.as_insert_mut().unwrap().0; + let meta = new_op.meta().clone(); + match value.value_extend(new_op.insert_inner()) { + Ok(_) => { + last_op.meta_mut().merge(&meta); + self.vec.insert(index - 1, last_op); + return true; + } + Err(inner) => { + self.vec.insert(index - 1, last_op); + self.vec.insert( + index, + DeltaItem::Insert { + insert: inner, + attributes: meta, + }, + ); + return false; + } + } + } else if new_op.is_retain() && last_op.is_retain() { + *last_op.as_retain_mut().unwrap().0 += new_op.length(); + last_op.meta_mut().merge(new_op.meta()); + // self.vec.push(last_op); + self.vec.insert(index - 1, last_op); + return true; + } + } + + // self.vec.push(last_op); + self.vec.insert(index - 1, last_op); + } + if index == self.vec.len() { + self.vec.push(new_op); + false + } else { + self.vec.insert(index, new_op); + true + } + } + + pub fn iter(&self) -> impl Iterator<Item = &DeltaItem<Value, M>> { + self.vec.iter() + } + + pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut DeltaItem<Value, M>> { + self.vec.iter_mut() + } + + pub fn into_op_iter(self) -> DeltaIterator<Value, M> { + DeltaIterator::new(self.vec.into_iter().rev().collect()) + } + + pub fn len(&self) -> usize { + self.vec.len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Reference: [Quill Delta](https://github.com/quilljs/delta) + // TODO: PERF use &mut self and &other + pub fn compose(self, other: Delta<Value, M>) -> Delta<Value, M> { + let mut this_iter = self.into_op_iter(); + let mut other_iter = other.into_op_iter(); + let mut ops = vec![]; + let first_other = other_iter.peek(); + if let Some(first_other) = first_other { + // if other.delta starts with retain, we insert corresponding number of inserts from self.delta + if first_other.is_retain() && first_other.meta().is_empty() { + let mut first_left = first_other.length(); + let mut first_this = this_iter.peek(); + while let Some(first_this_inner) = first_this { + if first_this_inner.is_insert() && first_this_inner.length() <= first_left { + first_left -= first_this_inner.length(); + let mut op = this_iter.next(None); + op.compose_meta(first_other); + ops.push(op); + first_this = this_iter.peek(); + } else { + break; + } + } + if first_other.length() - first_left > 0 { + other_iter.next(first_other.length() - first_left); + } + } + } + let mut delta = Delta { vec: ops }; + while this_iter.has_next() || other_iter.has_next() { + if other_iter.peek_is_insert() { + // nothing to compose here + delta.push(other_iter.next(None)); + } else if this_iter.peek_is_delete() { + // nothing to compose here + delta.push(this_iter.next(None)); + } else { + // possible cases: + // 1. this: insert, other: retain + // 2. this: retain, other: retain + // 3. this: retain, other: delete + // 4. this: insert, other: delete + + let (mut this_op, mut other_op) = this_iter.next_pair(&mut other_iter); + if other_op.is_retain() { + // 1. this: insert, other: retain + // 2. this: retain, other: retain + this_op.compose_meta(&other_op); + let merged = delta.push(this_op); + let concat_rest = !other_iter.has_next() && !merged; + if concat_rest { + let vec = this_iter.rest(); + if vec.is_empty() { + break; + } + + let rest = Delta { vec }; + delta = delta.concat(rest); + break; + } + } else if other_op.is_delete() && this_op.is_retain() { + // 3. this: retain, other: delete + other_op.compose_meta(&this_op); + // other deletes the retained text + delta.push(other_op); + } else { + // 4. this: insert, other: delete + // nothing to do here, because insert and delete have the same length + } + } + } + + delta.chop() + } + + pub(crate) fn concat(mut self, mut other: Self) -> Self { + if !other.vec.is_empty() { + let other_first = other.vec.remove(0); + self.push(other_first); + self.vec.extend(other.vec); + } + self + } + + pub fn chop(mut self) -> Self { + loop { + match self.vec.last() { + Some(last_op) if last_op.is_retain() && last_op.meta().is_empty() => { + self.vec.pop(); + } + _ => break, + } + } + + self + } + + pub fn insert_len(&self) -> usize { + self.vec + .iter() + .map(|x| match x { + DeltaItem::Insert { insert, .. } => insert.length(), + _ => 0, + }) + .sum() + } +} + +impl<Value, M> IntoIterator for Delta<Value, M> { + type Item = DeltaItem<Value, M>; + + type IntoIter = std::vec::IntoIter<DeltaItem<Value, M>>; + fn into_iter(self) -> Self::IntoIter { + self.vec.into_iter() + } +} + +impl<Value: DeltaValue, M: Meta> Default for Delta<Value, M> { + fn default() -> Self { + Self::new() + } +} + +impl<T: Debug> DeltaValue for Vec<T> { + fn value_extend(&mut self, other: Self) -> Result<(), Self> { + self.extend(other); + Ok(()) + } + + fn take(&mut self, length: usize) -> Self { + let mut new = self.split_off(length); + std::mem::swap(self, &mut new); + new + } + + fn length(&self) -> usize { + self.len() + } +} + +impl DeltaValue for String { + fn value_extend(&mut self, other: Self) -> Result<(), Self> { + self.push_str(&other); + Ok(()) + } + + fn take(&mut self, length: usize) -> Self { + let mut new = self.split_off(length); + std::mem::swap(self, &mut new); + new + } + fn length(&self) -> usize { + self.len() + } +} + +#[cfg(test)] +mod test { + use super::{Delta, DeltaItem, DeltaType, Meta}; + + #[derive(Debug, PartialEq, Clone, Default)] + struct TestMeta { + bold: Option<Option<bool>>, + color: Option<Option<()>>, + } + + impl Meta for TestMeta { + fn empty() -> Self { + TestMeta { + bold: None, + color: None, + } + } + fn is_empty(&self) -> bool { + self.bold.is_none() && self.color.is_none() + } + + fn compose( + &mut self, + other: &Self, + (this_type, other_type): (super::DeltaType, super::DeltaType), + ) { + if this_type != DeltaType::Delete && other_type != DeltaType::Delete { + if let Some(other_bold) = other.bold { + self.bold = Some(other_bold); + } + if let Some(other_color) = other.color { + self.color = Some(other_color); + } + } + } + + fn is_mergeable(&self, other: &Self) -> bool { + self == other + } + + fn merge(&mut self, _other: &Self) {} + } + + type TestDelta = Delta<String, TestMeta>; + const BOLD_META: TestMeta = TestMeta { + bold: Some(Some(true)), + color: None, + }; + const COLOR_META: TestMeta = TestMeta { + bold: None, + color: Some(Some(())), + }; + const EMPTY_META: TestMeta = TestMeta { + bold: Some(None), + color: Some(None), + }; + const BOTH_META: TestMeta = TestMeta { + bold: Some(Some(true)), + color: Some(Some(())), + }; + + #[test] + fn delta_push() { + let mut a: Delta<String, ()> = Delta::new().insert("a".to_string()); + a.push(DeltaItem::Insert { + insert: "b".to_string(), + attributes: (), + }); + assert_eq!(a, Delta::new().insert("ab".to_string())); + } + + #[test] + fn delta_compose() { + let a: Delta<String, ()> = Delta::new().retain(3).insert("abcde".to_string()); + let b = Delta::new().retain(5).delete(6); + assert_eq!( + a.compose(b), + Delta::new().retain(3).insert("ab".to_string()).delete(3) + ); + + let a: Delta<String, ()> = Delta::new().insert("123".to_string()); + let b = Delta::new().retain(1).insert("123".to_string()); + assert_eq!(a.compose(b), Delta::new().insert("112323".to_string())); + } + + #[test] + fn delete_failed() { + let a: Delta<String, ()> = Delta::new() + .retain(2) + .insert("[31354]") + .retain(1) + .insert("[31354]") + .retain(12) + .insert("[31354]"); + let b: Delta<String, ()> = Delta::new().retain(27).delete(3); + assert_eq!( + a.compose(b), + Delta::new() + .retain(2) + .insert("[31354]") + .retain(1) + .insert("[31354]") + .retain(10) + .insert("31354]") + .delete(2) + ); + } + + #[test] + fn insert_insert() { + let a = TestDelta::new().insert("a"); + let b = TestDelta::new().insert("b"); + assert_eq!(a.compose(b), TestDelta::new().insert("b").insert("a")); + } + + #[test] + fn insert_retain() { + let a = TestDelta::new().insert("a"); + let b = TestDelta::new().retain_with_meta(1, BOLD_META); + assert_eq!( + a.compose(b), + TestDelta::new().insert_with_meta("a", BOLD_META) + ); + } + + #[test] + fn insert_delete() { + let a = TestDelta::new().insert("a"); + let b = TestDelta::new().delete(1); + assert_eq!(a.compose(b), TestDelta::new()); + } + + #[test] + fn delete_insert() { + let a = TestDelta::new().delete(1); + let b = TestDelta::new().insert("b"); + assert_eq!(a.compose(b), TestDelta::new().insert("b").delete(1)); + } + + #[test] + fn delete_retain() { + let a = TestDelta::new().delete(1); + let b = TestDelta::new().retain_with_meta(1, BOLD_META); + assert_eq!( + a.compose(b), + TestDelta::new().delete(1).retain_with_meta(1, BOLD_META) + ); + } + + #[test] + fn delete_delete() { + let a = TestDelta::new().delete(1); + let b = TestDelta::new().delete(1); + assert_eq!(a.compose(b), TestDelta::new().delete(2)); + } + + #[test] + fn retain_insert() { + let a = TestDelta::new().retain_with_meta(1, BOLD_META); + let b = TestDelta::new().insert("b"); + assert_eq!( + a.compose(b), + TestDelta::new().insert("b").retain_with_meta(1, BOLD_META) + ); + } + + #[test] + fn retain_retain() { + let a = TestDelta::new().retain_with_meta(1, BOLD_META); + let b = TestDelta::new().retain_with_meta(1, COLOR_META); + assert_eq!( + a.compose(b), + TestDelta::new().retain_with_meta(1, BOTH_META) + ); + } + + #[test] + fn retain_delete() { + let a = TestDelta::new().retain_with_meta(1, BOLD_META); + let b = TestDelta::new().delete(1); + assert_eq!(a.compose(b), TestDelta::new().delete(1)); + } + + #[test] + fn delete_entire() { + let a = TestDelta::new().retain(4).insert("abcde"); + let b = TestDelta::new().delete(9); + assert_eq!(a.compose(b), TestDelta::new().delete(4)); + } + + #[test] + fn retain_more() { + let a = TestDelta::new().insert("abcde"); + let b = TestDelta::new().retain(10); + assert_eq!(a.compose(b), TestDelta::new().insert("abcde")); + } + + #[test] + fn remove_meta() { + let a = TestDelta::new().insert_with_meta("a", BOLD_META); + let b = TestDelta::new().retain_with_meta(1, EMPTY_META); + assert_eq!( + a.compose(b), + TestDelta::new().insert_with_meta("a", EMPTY_META) + ); + } + + #[test] + fn retain_start_opt() { + let a = TestDelta::new() + .insert_with_meta("a", BOLD_META) + .insert("b") + .insert_with_meta("c", BOLD_META) + .delete(1); + let b = TestDelta::new().retain(3).insert("d"); + let expect = TestDelta::new() + .insert_with_meta("a", BOLD_META) + .insert("b") + .insert_with_meta("c", BOLD_META) + .insert("d") + .delete(1); + assert_eq!(a.compose(b), expect); + } + + #[test] + fn retain_start_opt_split() { + let a = TestDelta::new() + .insert_with_meta("a", BOLD_META) + .insert("b") + .insert_with_meta("c", BOLD_META) + .retain(5) + .delete(1); + let b = TestDelta::new().retain(4).insert("d"); + let expect = TestDelta::new() + .insert_with_meta("a", BOLD_META) + .insert("b") + .insert_with_meta("c", BOLD_META) + .retain(1) + .insert("d") + .retain(4) + .delete(1); + assert_eq!(a.compose(b), expect); + } + + #[test] + fn retain_end_opt() { + let a = TestDelta::new() + .insert_with_meta("a", BOLD_META) + .insert("b") + .insert_with_meta("c", BOLD_META); + let b = TestDelta::new().delete(1); + let expect = TestDelta::new() + .insert("b") + .insert_with_meta("c", BOLD_META); + assert_eq!(a.compose(b), expect); + } + + #[test] + fn retain_end_opt_join() { + let a = TestDelta::new() + .insert_with_meta("a", BOLD_META) + .insert("b") + .insert_with_meta("c", BOLD_META) + .insert("d") + .insert_with_meta("e", BOLD_META) + .insert("f"); + let b = TestDelta::new().retain(1).delete(1); + let expect = TestDelta::new() + .insert_with_meta("ac", BOLD_META) + .insert("d") + .insert_with_meta("e", BOLD_META) + .insert("f"); + assert_eq!(a.compose(b), expect); + } +} diff --git a/vendor/loro-internal/src/delta/text.rs b/vendor/loro-internal/src/delta/text.rs new file mode 100644 index 0000000..f973901 --- /dev/null +++ b/vendor/loro-internal/src/delta/text.rs @@ -0,0 +1,298 @@ +use loro_common::{InternalString, LoroValue, PeerID}; +use rustc_hash::FxHashMap; +use serde::{Deserialize, Serialize}; + +use crate::change::Lamport; +use crate::container::richtext::{Style, Styles}; +use crate::event::TextMeta; +use crate::ToJson; + +use super::Meta; + +#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StyleMeta { + map: FxHashMap<InternalString, StyleMetaItem>, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StyleMetaItem { + // We need lamport and peer to compose the event + pub lamport: Lamport, + pub peer: PeerID, + pub value: LoroValue, +} + +impl StyleMetaItem { + pub fn try_replace(&mut self, other: &StyleMetaItem) { + if (self.lamport, self.peer) < (other.lamport, other.peer) { + self.lamport = other.lamport; + self.peer = other.peer; + self.value = other.value.clone(); + } + } +} + +impl From<&Styles> for StyleMeta { + fn from(styles: &Styles) -> Self { + let mut map = FxHashMap::with_capacity_and_hasher(styles.len(), Default::default()); + for (key, value) in styles.iter() { + if let Some(value) = value.get() { + map.insert( + key.key().clone(), + StyleMetaItem { + value: value.to_value(), + lamport: value.lamport, + peer: value.peer, + }, + ); + } + } + Self { map } + } +} + +impl From<Styles> for StyleMeta { + fn from(styles: Styles) -> Self { + let temp = &styles; + temp.into() + } +} + +impl Meta for StyleMeta { + fn is_empty(&self) -> bool { + self.map.is_empty() + } + + fn compose(&mut self, other: &Self, _type_pair: (super::DeltaType, super::DeltaType)) { + for (key, value) in other.map.iter() { + match self.map.get_mut(key) { + Some(old_value) => { + old_value.try_replace(value); + } + None => { + self.map.insert(key.clone(), value.clone()); + } + } + } + } + + fn is_mergeable(&self, other: &Self) -> bool { + self.map == other.map + } + + fn merge(&mut self, _: &Self) {} +} + +impl Meta for TextMeta { + fn is_empty(&self) -> bool { + self.0.is_empty() + } + + fn compose(&mut self, other: &Self, _: (super::DeltaType, super::DeltaType)) { + for (key, value) in other.0.iter() { + self.0.insert(key.clone(), value.clone()); + } + } + + fn is_mergeable(&self, other: &Self) -> bool { + self.0 == other.0 + } + + fn merge(&mut self, _: &Self) {} +} + +impl StyleMeta { + pub(crate) fn iter(&self) -> impl Iterator<Item = (InternalString, Style)> + '_ { + self.map.iter().map(|(key, style)| { + ( + key.clone(), + Style { + key: key.clone(), + data: style.value.clone(), + }, + ) + }) + } + + pub(crate) fn insert(&mut self, key: InternalString, value: StyleMetaItem) { + self.map.insert(key, value); + } + + pub(crate) fn contains_key(&self, key: &InternalString) -> bool { + self.map.contains_key(key) + } + + pub(crate) fn to_value(&self) -> LoroValue { + LoroValue::Map(self.to_map_without_null_value().into()) + } + + fn to_map_without_null_value(&self) -> FxHashMap<String, LoroValue> { + self.map + .iter() + .filter_map(|(key, value)| { + if value.value.is_null() { + None + } else { + Some((key.to_string(), value.value.clone())) + } + }) + .collect() + } + + pub(crate) fn to_map(&self) -> FxHashMap<String, LoroValue> { + self.map + .iter() + .map(|(key, value)| (key.to_string(), value.value.clone())) + .collect() + } + + pub(crate) fn to_option_map(&self) -> Option<FxHashMap<String, LoroValue>> { + if self.is_empty() { + return None; + } + + Some(self.to_map()) + } + + pub(crate) fn to_option_map_without_null_value(&self) -> Option<FxHashMap<String, LoroValue>> { + let map = self.to_map_without_null_value(); + if map.is_empty() { + None + } else { + Some(map) + } + } +} + +impl ToJson for TextMeta { + fn to_json_value(&self) -> serde_json::Value { + let mut map = serde_json::Map::new(); + for (key, value) in self.0.iter() { + let value = serde_json::to_value(value).unwrap(); + map.insert(key.to_string(), value); + } + + serde_json::Value::Object(map) + } + + fn from_json(s: &str) -> Self { + let map: FxHashMap<String, LoroValue> = serde_json::from_str(s).unwrap(); + TextMeta(map) + } +} + +#[cfg(test)] +mod tests { + use rustc_hash::FxHashMap; + + use super::*; + use crate::delta::{DeltaType, Meta}; + + fn key(value: &str) -> InternalString { + value.into() + } + + fn style_item(lamport: Lamport, peer: PeerID, value: LoroValue) -> StyleMetaItem { + StyleMetaItem { + lamport, + peer, + value, + } + } + + #[test] + fn style_meta_item_replacement_is_ordered_by_lamport_then_peer() { + let mut item = style_item(1, 9, LoroValue::String("old".into())); + item.try_replace(&style_item(1, 8, LoroValue::String("ignored".into()))); + assert_eq!(item.value, LoroValue::String("old".into())); + + item.try_replace(&style_item(1, 10, LoroValue::String("peer-wins".into()))); + assert_eq!(item.value, LoroValue::String("peer-wins".into())); + + item.try_replace(&style_item(2, 0, LoroValue::String("lamport-wins".into()))); + assert_eq!(item.value, LoroValue::String("lamport-wins".into())); + } + + #[test] + fn style_meta_compose_keeps_latest_value_per_key_and_preserves_new_keys() { + let mut left = StyleMeta::default(); + left.insert(key("bold"), style_item(2, 1, LoroValue::Bool(true))); + left.insert( + key("color"), + style_item(1, 1, LoroValue::String("red".into())), + ); + + let mut right = StyleMeta::default(); + right.insert(key("bold"), style_item(1, 99, LoroValue::Bool(false))); + right.insert( + key("color"), + style_item(3, 0, LoroValue::String("blue".into())), + ); + right.insert( + key("link"), + style_item(1, 1, LoroValue::String("docs".into())), + ); + + left.compose(&right, (DeltaType::Retain, DeltaType::Retain)); + let values = left.to_map(); + assert_eq!(values.get("bold"), Some(&LoroValue::Bool(true))); + assert_eq!(values.get("color"), Some(&LoroValue::String("blue".into()))); + assert_eq!(values.get("link"), Some(&LoroValue::String("docs".into()))); + } + + #[test] + fn style_meta_value_views_distinguish_null_from_absent() { + let mut meta = StyleMeta::default(); + assert!(meta.is_empty()); + assert_eq!(meta.to_option_map(), None); + + meta.insert(key("bold"), style_item(1, 1, LoroValue::Bool(true))); + meta.insert(key("deleted"), style_item(1, 2, LoroValue::Null)); + + assert!(meta.contains_key(&key("deleted"))); + assert_eq!( + meta.to_map().get("deleted"), + Some(&LoroValue::Null), + "to_map keeps explicit null style values" + ); + assert_eq!( + meta.to_map_without_null_value().get("deleted"), + None, + "serialized style values omit null entries" + ); + assert_eq!( + meta.to_value(), + LoroValue::Map( + FxHashMap::from_iter([(String::from("bold"), LoroValue::Bool(true))]).into() + ) + ); + + let styles: FxHashMap<_, _> = meta.iter().map(|style| (style.0, style.1.data)).collect(); + assert_eq!(styles.get(&key("bold")), Some(&LoroValue::Bool(true))); + assert_eq!(styles.get(&key("deleted")), Some(&LoroValue::Null)); + } + + #[test] + fn text_meta_compose_and_json_roundtrip_are_map_like() { + let mut left = TextMeta(FxHashMap::from_iter([( + String::from("lang"), + LoroValue::String("en".into()), + )])); + let right = TextMeta(FxHashMap::from_iter([ + (String::from("lang"), LoroValue::String("fr".into())), + (String::from("author"), LoroValue::String("loro".into())), + ])); + + left.compose(&right, (DeltaType::Retain, DeltaType::Retain)); + assert_eq!(left.0.get("lang"), Some(&LoroValue::String("fr".into()))); + assert_eq!( + left.0.get("author"), + Some(&LoroValue::String("loro".into())) + ); + assert!(left.is_mergeable(&left.clone())); + + let json = left.to_json_value(); + let decoded = TextMeta::from_json(&json.to_string()); + assert_eq!(decoded.0, left.0); + } +} diff --git a/vendor/loro-internal/src/delta/tree.rs b/vendor/loro-internal/src/delta/tree.rs new file mode 100644 index 0000000..8f368e5 --- /dev/null +++ b/vendor/loro-internal/src/delta/tree.rs @@ -0,0 +1,209 @@ +use fractional_index::FractionalIndex; +use itertools::Itertools; +use loro_common::{IdFull, TreeID}; +use rustc_hash::{FxHashMap, FxHashSet}; +use std::fmt::Debug; +use std::ops::{Deref, DerefMut}; + +use crate::state::TreeParentId; + +#[derive(Debug, Clone, Default)] +pub struct TreeDiff { + pub diff: Vec<TreeDiffItem>, +} + +#[derive(Debug, Clone)] +pub struct TreeDiffItem { + pub target: TreeID, + pub action: TreeExternalDiff, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum TreeExternalDiff { + Create { + parent: TreeParentId, + index: usize, + position: FractionalIndex, + }, + Move { + parent: TreeParentId, + index: usize, + position: FractionalIndex, + old_parent: TreeParentId, + old_index: usize, + }, + Delete { + old_parent: TreeParentId, + old_index: usize, + }, +} + +impl TreeDiff { + pub(crate) fn compose(mut self, other: Self) -> Self { + self.diff.extend(other.diff); + // self = compose_tree_diff(&self); + self + } + + pub(crate) fn extend<I: IntoIterator<Item = TreeDiffItem>>(mut self, other: I) -> Self { + self.diff.extend(other); + self + } + + fn to_hash_map_mut(&mut self) -> FxHashMap<TreeID, usize> { + let mut ans = FxHashSet::default(); + for index in (0..self.diff.len()).rev() { + let target = self.diff[index].target; + if ans.contains(&target) { + self.diff.remove(index); + continue; + } + ans.insert(target); + } + self.iter() + .map(|x| x.target) + .enumerate() + .map(|(i, x)| (x, i)) + .collect() + } + + pub(crate) fn transform(&mut self, b: &TreeDiff, left_prior: bool) { + // println!("\ntransform prior {:?} {:?} \nb {:?}", left_prior, self, b); + if b.is_empty() || self.is_empty() { + return; + } + if !left_prior { + let mut self_update = self.to_hash_map_mut(); + for i in b + .iter() + .map(|x| x.target) + .filter_map(|x| self_update.remove(&x)) + .sorted() + .rev() + { + self.remove(i); + } + } + } +} + +/// Representation of differences in movable tree. It's an ordered list of [`TreeDiff`]. +#[derive(Clone, Default)] +pub struct TreeDelta { + pub(crate) diff: Vec<TreeDeltaItem>, +} + +impl Debug for TreeDelta { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("TreeDelta{ diff: [\n")?; + for item in self.diff.iter() { + f.write_fmt(format_args!("\t{:?}, \n", item))?; + } + f.write_str("]}") + } +} + +/// The semantic action in movable tree. +#[derive(Debug, Clone)] +pub struct TreeDeltaItem { + pub target: TreeID, + pub action: TreeInternalDiff, + pub last_effective_move_op_id: IdFull, +} + +/// The action of [`TreeDiff`]. It's the same as [`crate::container::tree::tree_op::TreeOp`], but semantic. +#[derive(Debug, Clone)] +pub enum TreeInternalDiff { + /// First create the node, have not seen it before + Create { + parent: TreeParentId, + position: FractionalIndex, + }, + /// For retreating, if the node is only created, not move it to `DELETED_ROOT` but delete it directly + UnCreate, + /// Move the node to the parent, the node exists + Move { + parent: TreeParentId, + position: FractionalIndex, + }, + /// move under a parent that is deleted + Delete { + parent: TreeParentId, + position: Option<FractionalIndex>, + }, + /// old parent is deleted, new parent is deleted too + MoveInDelete { + parent: TreeParentId, + position: Option<FractionalIndex>, + }, +} + +impl TreeDeltaItem { + /// * `is_new_parent_deleted` and `is_old_parent_deleted`: we need to infer whether it's a `creation`. + /// It's a creation if the old_parent is deleted but the new parent isn't. + /// If it is a creation, we need to emit the `Create` event so that downstream event handler can + /// handle the new containers easier. + pub(crate) fn new( + target: TreeID, + parent: TreeParentId, + old_parent: TreeParentId, + op_id: IdFull, + is_new_parent_deleted: bool, + is_old_parent_deleted: bool, + position: Option<FractionalIndex>, + ) -> Self { + let action = if matches!(parent, TreeParentId::Unexist) { + TreeInternalDiff::UnCreate + } else { + match ( + is_new_parent_deleted, + is_old_parent_deleted || old_parent == TreeParentId::Unexist, + ) { + (true, true) => TreeInternalDiff::MoveInDelete { parent, position }, + (true, false) => TreeInternalDiff::Delete { parent, position }, + (false, true) => TreeInternalDiff::Create { + parent, + position: position.unwrap(), + }, + (false, false) => TreeInternalDiff::Move { + parent, + position: position.unwrap(), + }, + } + }; + + TreeDeltaItem { + target, + action, + last_effective_move_op_id: op_id, + } + } +} + +impl Deref for TreeDelta { + type Target = Vec<TreeDeltaItem>; + fn deref(&self) -> &Self::Target { + &self.diff + } +} + +impl TreeDelta { + // TODO: cannot handle this for now + pub(crate) fn compose(mut self, x: TreeDelta) -> TreeDelta { + self.diff.extend(x.diff); + self + } +} + +impl Deref for TreeDiff { + type Target = Vec<TreeDiffItem>; + fn deref(&self) -> &Self::Target { + &self.diff + } +} + +impl DerefMut for TreeDiff { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.diff + } +} diff --git a/vendor/loro-internal/src/diff/LICENSE b/vendor/loro-internal/src/diff/LICENSE new file mode 100644 index 0000000..f49a4e1 --- /dev/null +++ b/vendor/loro-internal/src/diff/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/vendor/loro-internal/src/diff/diff_impl.rs b/vendor/loro-internal/src/diff/diff_impl.rs new file mode 100644 index 0000000..aef44cd --- /dev/null +++ b/vendor/loro-internal/src/diff/diff_impl.rs @@ -0,0 +1,857 @@ +//! This file was copied from the similar crate at +//! https://github.com/mitsuhiko/similar/blob/2b31f65445df9093ba007ca5a5ae6a71b899d491/src/algorithms/myers.rs +//! The original license is in the LICENSE file in the same directory as this file +//! +//! This file has been optimized for constant performance, removed some unnecessary cases +//! and simplified the use of DiffHandler. +//! Myers' diff algorithm. +//! +//! * time: `O((N+M)D)` +//! * space `O(N+M)` +//! +//! See [the original article by Eugene W. Myers](http://www.xmailserver.org/diff2.pdf) +//! describing it. +//! +//! The implementation of this algorithm is based on the implementation by +//! Brandon Williams. +use crate::change::get_sys_timestamp; +use rustc_hash::FxHashMap; +use std::cmp::Ordering; +use std::collections::BinaryHeap; +use std::iter::zip; +use std::ops::{Index, IndexMut}; + +/// Options for controlling the text update behavior. +/// +/// - `timeout_ms`: Optional timeout in milliseconds for the diff computation +/// - `use_refined_diff`: Whether to use a more refined but slower diff algorithm. Defaults to true. +#[derive(Clone, Debug)] +pub struct UpdateOptions { + pub timeout_ms: Option<f64>, + pub use_refined_diff: bool, +} + +impl Default for UpdateOptions { + fn default() -> Self { + Self { + timeout_ms: None, + use_refined_diff: true, + } + } +} + +#[derive(thiserror::Error, Debug, PartialEq)] +pub enum UpdateTimeoutError { + #[error("Timeout")] + Timeout, +} + +/// Utility function to check if a range is empty that works on older rust versions +#[inline(always)] +fn is_empty_range(start: usize, end: usize) -> bool { + start >= end +} + +#[inline(always)] +fn is_not_empty_range(start: usize, end: usize) -> bool { + start < end +} + +fn common_prefix(xs: &[u32], ys: &[u32]) -> usize { + let chunk_size = 4; + let off = zip(xs.chunks_exact(chunk_size), ys.chunks_exact(chunk_size)) + .take_while(|(xs_chunk, ys_chunk)| xs_chunk == ys_chunk) + .count() + * chunk_size; + off + zip(&xs[off..], &ys[off..]) + .take_while(|(x, y)| x == y) + .count() +} + +fn common_suffix_len(old: &[u32], new: &[u32]) -> usize { + let chunk_size = 4; + let old_len = old.len(); + let new_len = new.len(); + + let off = zip(old.rchunks_exact(chunk_size), new.rchunks_exact(chunk_size)) + .take_while(|(old_chunk, new_chunk)| old_chunk == new_chunk) + .count() + * chunk_size; + + off + zip( + old[..old_len - off].iter().rev(), + new[..new_len - off].iter().rev(), + ) + .take_while(|(o, n)| o == n) + .count() +} + +pub(crate) trait DiffHandler { + fn insert(&mut self, old_index: usize, new_index: usize, new_len: usize); + fn delete(&mut self, old_index: usize, old_len: usize); +} + +#[derive(Debug)] +pub(crate) struct OperateProxy<D: DiffHandler> { + handler: D, +} + +impl<D: DiffHandler> OperateProxy<D> { + pub fn new(handler: D) -> Self { + Self { handler } + } + + pub fn delete(&mut self, old_index: usize, old_len: usize) { + self.handler.delete(old_index, old_len); + } + + pub fn insert(&mut self, old_index: usize, new_index: usize, new_len: usize) { + self.handler.insert(old_index, new_index, new_len); + } + + #[allow(unused)] + fn unwrap(self) -> D { + self.handler + } +} + +pub(crate) fn diff<D: DiffHandler>( + proxy: &mut OperateProxy<D>, + options: UpdateOptions, + old: &[u32], + new: &[u32], +) -> Result<(), UpdateTimeoutError> { + let max_d = (old.len() + new.len()).div_ceil(2) + 1; + let mut vb = OffsetVec::new(max_d); + let mut vf = OffsetVec::new(max_d); + let start_time = if options.timeout_ms.is_some() { + get_sys_timestamp() + } else { + 0. + }; + + conquer( + proxy, + options.use_refined_diff, + options.timeout_ms, + start_time, + old, + 0, + old.len(), + new, + 0, + new.len(), + &mut vf, + &mut vb, + ) +} + +struct OffsetVec(isize, Vec<usize>); + +impl OffsetVec { + fn new(max_d: usize) -> Self { + Self(max_d as isize, vec![0; max_d << 1]) + } + + fn len(&self) -> usize { + self.1.len() + } +} + +impl Index<isize> for OffsetVec { + type Output = usize; + fn index(&self, index: isize) -> &Self::Output { + &self.1[(index + self.0) as usize] + } +} + +impl IndexMut<isize> for OffsetVec { + fn index_mut(&mut self, index: isize) -> &mut Self::Output { + &mut self.1[(index + self.0) as usize] + } +} + +struct MiddleSnakeResult { + #[allow(unused)] + d: usize, + x_start: usize, + y_start: usize, +} + +#[allow(clippy::too_many_arguments)] +fn find_middle_snake( + timeout_ms: Option<f64>, + start_time: f64, + old: &[u32], + old_start: usize, + old_end: usize, + new: &[u32], + new_start: usize, + new_end: usize, + vf: &mut OffsetVec, + vb: &mut OffsetVec, +) -> Result<Option<MiddleSnakeResult>, UpdateTimeoutError> { + let n = old_end - old_start; + let m = new_end - new_start; + let delta = n as isize - m as isize; + let odd = delta & 1 != 0; + vf[1] = 0; + vb[1] = 0; + let d_max = (n + m).div_ceil(2) + 1; + assert!(vf.len() >= d_max); + assert!(vb.len() >= d_max); + + for d in 0..d_max as isize { + for k in (-d..=d).rev().step_by(2) { + let mut x = if k == -d || (k != d && vf[k - 1] < vf[k + 1]) { + vf[k + 1] + } else { + vf[k - 1] + 1 + }; + let y = (x as isize - k) as usize; + let (x0, y0) = (x, y); + if x < n && y < m { + let advance = + common_prefix(&old[old_start + x..old_end], &new[new_start + y..new_end]); + x += advance; + } + vf[k] = x; + if odd && (k - delta).abs() <= (d - 1) && vf[k] + vb[delta - k] >= n { + return Ok(Some(MiddleSnakeResult { + d: d as usize, + x_start: x0 + old_start, + y_start: y0 + new_start, + })); + } + + if let Some(timeout_ms) = timeout_ms { + if get_sys_timestamp() - start_time > timeout_ms { + return Err(UpdateTimeoutError::Timeout); + } + } + } + + for k in (-d..=d).rev().step_by(2) { + let mut x = if k == -d || (k != d && vb[k - 1] < vb[k + 1]) { + vb[k + 1] + } else { + vb[k - 1] + 1 + }; + let mut y = (x as isize - k) as usize; + if x < n && y < m { + let advance = common_suffix_len( + &old[old_start..old_start + n - x], + &new[new_start..new_start + m - y], + ); + x += advance; + y += advance; + } + vb[k] = x; + if !odd && (k - delta).abs() <= d && vb[k] + vf[delta - k] >= n { + return Ok(Some(MiddleSnakeResult { + d: d as usize, + x_start: n - x + old_start, + y_start: m - y + new_start, + })); + } + + if let Some(timeout_ms) = timeout_ms { + if get_sys_timestamp() - start_time > timeout_ms { + return Err(UpdateTimeoutError::Timeout); + } + } + } + } + + Ok(None) +} + +#[allow(clippy::too_many_arguments)] +fn conquer<D: DiffHandler>( + proxy: &mut OperateProxy<D>, + should_use_dj: bool, + timeout_ms: Option<f64>, + start_time: f64, + old: &[u32], + mut old_start: usize, + mut old_end: usize, + new: &[u32], + mut new_start: usize, + mut new_end: usize, + vf: &mut OffsetVec, + vb: &mut OffsetVec, +) -> Result<(), UpdateTimeoutError> { + let common_prefix_len = common_prefix(&old[old_start..old_end], &new[new_start..new_end]); + if common_prefix_len > 0 { + old_start += common_prefix_len; + new_start += common_prefix_len; + } + + let common_suffix_len = common_suffix_len(&old[old_start..old_end], &new[new_start..new_end]); + old_end -= common_suffix_len; + new_end -= common_suffix_len; + + if is_not_empty_range(old_start, old_end) || is_not_empty_range(new_start, new_end) { + let len_old = old_end - old_start; + let len_new = new_end - new_start; + if should_use_dj && (len_old.max(1) * len_new.max(1) < 128 * 128) { + let ok = dj_diff( + proxy, + &old[old_start..old_end], + &new[new_start..new_end], + old_start, + new_start, + 10_000, + ); + if ok { + return Ok(()); + } + } + + if is_empty_range(new_start, new_end) { + proxy.delete(old_start, old_end - old_start); + } else if is_empty_range(old_start, old_end) { + proxy.insert(old_start, new_start, new_end - new_start); + } else if let Some(MiddleSnakeResult { + d: _, + x_start, + y_start, + }) = find_middle_snake( + timeout_ms, start_time, old, old_start, old_end, new, new_start, new_end, vf, vb, + )? { + conquer( + proxy, + should_use_dj, + timeout_ms, + start_time, + old, + old_start, + x_start, + new, + new_start, + y_start, + vf, + vb, + )?; + conquer( + proxy, + should_use_dj, + timeout_ms, + start_time, + old, + x_start, + old_end, + new, + y_start, + new_end, + vf, + vb, + )?; + } else { + proxy.delete(old_start, old_end - old_start); + proxy.insert(old_start, new_start, new_end - new_start); + } + } + + Ok(()) +} + +/// Return false if this method gives up early +#[must_use] +pub(crate) fn dj_diff<D: DiffHandler>( + proxy: &mut OperateProxy<D>, + old: &[u32], + new: &[u32], + old_offset: usize, + new_offset: usize, + max_try_count: usize, +) -> bool { + let common_prefix_len = common_prefix(old, new); + let common_suffix_len = common_suffix_len(&old[common_prefix_len..], &new[common_prefix_len..]); + let old = &old[common_prefix_len..old.len() - common_suffix_len]; + let new = &new[common_prefix_len..new.len() - common_suffix_len]; + if old.len() >= u16::MAX as usize || new.len() >= u16::MAX as usize { + return false; + } + + if old.is_empty() { + if new.is_empty() { + return true; + } + + proxy.insert( + old_offset + common_prefix_len, + new_offset + common_prefix_len, + new.len(), + ); + return true; + } + + if new.is_empty() { + proxy.delete(old_offset + common_prefix_len, old.len()); + return true; + } + + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + struct Point { + x: u16, + y: u16, + } + + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + enum Direction { + Up, + Left, + UpLeft, + } + + struct QueueItem { + point: Point, + cost: u32, + from: Direction, + } + + impl PartialEq for QueueItem { + fn eq(&self, other: &Self) -> bool { + self.cost == other.cost + } + } + + impl PartialOrd for QueueItem { + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { + Some(self.cmp(other)) + } + } + + impl Ord for QueueItem { + fn cmp(&self, other: &Self) -> Ordering { + other.cost.cmp(&self.cost) + } + } + + impl Eq for QueueItem {} + + let mut visited: FxHashMap<Point, Direction> = FxHashMap::default(); + let mut q: BinaryHeap<QueueItem> = BinaryHeap::new(); + q.push(QueueItem { + point: Point { x: 0, y: 0 }, + cost: 0, + from: Direction::UpLeft, + }); + + while let Some(QueueItem { point, cost, from }) = q.pop() { + if visited.contains_key(&point) { + continue; + } + + visited.insert(point, from); + if point.x == old.len() as u16 && point.y == new.len() as u16 { + break; + } + + if visited.len() + q.len() > max_try_count { + // println!("give up on: visited len: {}", visited.len()); + // println!("queue len: {}", q.len()); + return false; + } + + if point.x < old.len() as u16 { + let next_point = Point { + x: point.x + 1, + y: point.y, + }; + + if !visited.contains_key(&next_point) { + let mut next_cost = cost + 1; + if from != Direction::Left { + next_cost += 8; + } + + q.push(QueueItem { + point: next_point, + cost: next_cost, + from: Direction::Left, + }); + } + } + + if point.y < new.len() as u16 { + let next_point = Point { + x: point.x, + y: point.y + 1, + }; + + if !visited.contains_key(&next_point) { + let direction = Direction::Up; + let mut next_cost = cost + 1; + if from != direction { + next_cost += 8; + } + + q.push(QueueItem { + point: next_point, + cost: next_cost, + from: Direction::Up, + }); + } + } + + if point.x < old.len() as u16 + && point.y < new.len() as u16 + && old[point.x as usize] == new[point.y as usize] + { + let next_point = Point { + x: point.x + 1, + y: point.y + 1, + }; + + if !visited.contains_key(&next_point) { + let next_cost = if from == Direction::UpLeft { + cost + } else { + cost + 1 + }; + + q.push(QueueItem { + point: next_point, + cost: next_cost, + from: Direction::UpLeft, + }); + } + } + } + + // println!("visited len: {}", visited.len()); + // println!("queue len: {}", q.len()); + + // Backtrack from end point to construct diff operations + let mut current = Point { + x: old.len() as u16, + y: new.len() as u16, + }; + + let mut path: Vec<(Direction, usize)> = Vec::new(); + while current.x > 0 || current.y > 0 { + let direction = visited.get(¤t).unwrap(); + if let Some((last_dir, count)) = path.last_mut() { + if last_dir == direction { + *count += 1; + } else { + path.push((*direction, 1)); + } + } else { + path.push((*direction, 1)); + } + match direction { + Direction::Left => { + current.x -= 1; + } + Direction::Up => { + current.y -= 1; + } + Direction::UpLeft => { + current.x -= 1; + current.y -= 1; + } + } + } + + path.reverse(); + + let mut old_index = common_prefix_len; + let mut new_index = common_prefix_len; + + for (direction, count) in path { + match direction { + Direction::Left => { + proxy.delete(old_offset + old_index, count); + old_index += count; + } + Direction::Up => { + proxy.insert(old_offset + old_index, new_index + new_offset, count); + new_index += count; + } + Direction::UpLeft => { + old_index += count; + new_index += count; + } + } + } + + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Debug, Default)] + struct RecordingDiffHandler { + ops: Vec<DiffOperation>, + } + + #[derive(Debug, PartialEq)] + enum DiffOperation { + Insert { + old_index: usize, + new_index: usize, + length: usize, + }, + Delete { + old_index: usize, + length: usize, + }, + } + + impl DiffHandler for RecordingDiffHandler { + fn insert(&mut self, pos: usize, start: usize, len: usize) { + self.ops.push(DiffOperation::Insert { + old_index: pos, + new_index: start, + length: len, + }); + } + + fn delete(&mut self, pos: usize, len: usize) { + self.ops.push(DiffOperation::Delete { + old_index: pos, + length: len, + }); + } + } + + #[test] + fn test_recording_diff_handler() { + let handler = RecordingDiffHandler::default(); + let mut proxy = OperateProxy::new(handler); + let old = vec![1, 2, 3]; + let new = vec![1, 4, 3]; + + let _ = dj_diff(&mut proxy, &old, &new, 0, 0, 100_000); + let handler = proxy.unwrap(); + assert_eq!( + handler.ops, + vec![ + DiffOperation::Delete { + old_index: 1, + length: 1 + }, + DiffOperation::Insert { + old_index: 2, + new_index: 1, + length: 1 + }, + ] + ); + } + + #[test] + fn test_dj_diff_same() { + let handler = RecordingDiffHandler::default(); + let mut proxy = OperateProxy::new(handler); + let old = vec![1, 2, 3]; + let new = vec![1, 2, 3]; + let _ = dj_diff(&mut proxy, &old, &new, 0, 0, 100_000); + let handler = proxy.unwrap(); + assert_eq!(handler.ops, vec![]); + } + + #[test] + fn test_dj_diff_1() { + let handler = RecordingDiffHandler::default(); + let mut proxy = OperateProxy::new(handler); + let old = vec![1]; + let new = vec![0, 1, 2]; + let _ = dj_diff(&mut proxy, &old, &new, 0, 0, 100_000); + let handler = proxy.unwrap(); + assert_eq!( + handler.ops, + vec![ + DiffOperation::Insert { + old_index: 0, + new_index: 0, + length: 1 + }, + DiffOperation::Insert { + old_index: 1, + new_index: 2, + length: 1 + }, + ] + ); + } + + #[test] + fn test_diff_may_scatter() { + let handler = RecordingDiffHandler::default(); + let mut proxy = OperateProxy::new(handler); + let old = vec![1, 2, 3, 4, 5]; + let new = vec![99, 1, 2, 3, 4, 5, 98, 97, 96, 3, 95, 4, 93, 92, 5, 91]; + diff(&mut proxy, UpdateOptions::default(), &old, &new).unwrap(); + let handler = proxy.unwrap(); + assert_eq!( + handler.ops, + vec![ + DiffOperation::Insert { + old_index: 0, + new_index: 0, + length: 1 + }, + DiffOperation::Insert { + old_index: 5, + new_index: 6, + length: 10 + }, + ] + ); + } + + #[test] + fn test_diff_may_scatter_1() { + let handler = RecordingDiffHandler::default(); + let mut proxy = OperateProxy::new(handler); + let old = vec![1, 2, 3, 4, 5]; + let new = vec![99, 1, 2, 98, 97, 96, 3, 95, 4, 93, 92, 5, 1, 2, 3, 4, 5, 91]; + diff(&mut proxy, UpdateOptions::default(), &old, &new).unwrap(); + let handler = proxy.unwrap(); + assert_eq!( + handler.ops, + vec![ + DiffOperation::Insert { + old_index: 0, + new_index: 0, + length: 12 + }, + DiffOperation::Insert { + old_index: 5, + new_index: 17, + length: 1 + }, + ] + ); + } + + #[test] + fn test_dj_diff_may_scatter() { + let handler = RecordingDiffHandler::default(); + let mut proxy = OperateProxy::new(handler); + let old = vec![1, 2, 3, 4, 5]; + let new = vec![99, 1, 2, 3, 4, 5, 98, 97, 96, 3, 95, 4, 93, 92, 5, 91]; + let _ = dj_diff(&mut proxy, &old, &new, 0, 0, 100_000); + let handler = proxy.unwrap(); + assert_eq!( + handler.ops, + vec![ + DiffOperation::Insert { + old_index: 0, + new_index: 0, + length: 1 + }, + DiffOperation::Insert { + old_index: 5, + new_index: 6, + length: 10 + }, + ] + ); + } + + #[test] + fn test_dj_diff_may_scatter_1() { + let handler = RecordingDiffHandler::default(); + let mut proxy = OperateProxy::new(handler); + let old = vec![1, 2, 3, 4, 5]; + let new = vec![99, 1, 2, 98, 97, 96, 3, 95, 4, 93, 92, 5, 1, 2, 3, 4, 5, 91]; + let _ = dj_diff(&mut proxy, &old, &new, 0, 0, 100_000); + let handler = proxy.unwrap(); + assert_eq!( + handler.ops, + vec![ + DiffOperation::Insert { + old_index: 0, + new_index: 0, + length: 12 + }, + DiffOperation::Insert { + old_index: 5, + new_index: 17, + length: 1 + }, + ] + ); + } + + #[test] + fn test_dj_diff_100_differences() { + let handler = RecordingDiffHandler::default(); + let mut proxy = OperateProxy::new(handler); + let old = vec![1; 100]; + let new = vec![2; 100]; + let _ = dj_diff(&mut proxy, &old, &new, 0, 0, 100_000); + let handler = proxy.unwrap(); + assert_eq!( + handler.ops, + vec![ + DiffOperation::Delete { + old_index: 0, + length: 100 + }, + DiffOperation::Insert { + old_index: 100, + new_index: 0, + length: 100 + }, + ] + ); + } + + #[test] + fn test_dj_diff_insert() { + let handler = RecordingDiffHandler::default(); + let mut proxy = OperateProxy::new(handler); + let old = vec![1; 100]; + let mut new = old.clone(); + new.splice(50..50, [1, 2, 3, 4, 1, 2, 3, 4]); + new.splice(0..0, [0, 1, 2, 3, 4, 5, 6, 7]); + let _ = dj_diff(&mut proxy, &old, &new, 0, 0, 100_000); + let handler = proxy.unwrap(); + assert_eq!( + handler.ops, + vec![ + DiffOperation::Insert { + old_index: 0, + new_index: 0, + length: 9 + }, + DiffOperation::Insert { + old_index: 50, + new_index: 59, + length: 7 + } + ] + ); + } + + #[test] + fn test_diff() { + let handler = RecordingDiffHandler::default(); + let mut proxy = OperateProxy::new(handler); + let old = vec![1; 100]; + let new = vec![2; 100]; + diff(&mut proxy, Default::default(), &old, &new).unwrap(); + } + + #[test] + fn test_timeout() { + let handler = RecordingDiffHandler::default(); + let mut proxy = OperateProxy::new(handler); + let old = vec![1; 10000]; + let new = vec![2; 10000]; + let options = UpdateOptions { + timeout_ms: Some(0.1), + ..Default::default() + }; + let result = diff(&mut proxy, options, &old, &new); + assert!(result.is_err()); + } +} diff --git a/vendor/loro-internal/src/diff/mod.rs b/vendor/loro-internal/src/diff/mod.rs new file mode 100644 index 0000000..5d9d5cb --- /dev/null +++ b/vendor/loro-internal/src/diff/mod.rs @@ -0,0 +1,4 @@ +pub mod diff_impl; +pub(crate) use diff_impl::diff; +pub(crate) use diff_impl::DiffHandler; +pub(crate) use diff_impl::OperateProxy; diff --git a/vendor/loro-internal/src/diff_calc.rs b/vendor/loro-internal/src/diff_calc.rs new file mode 100644 index 0000000..dbc2f1e --- /dev/null +++ b/vendor/loro-internal/src/diff_calc.rs @@ -0,0 +1,2635 @@ +use std::{num::NonZeroU16, sync::Arc}; + +#[cfg(feature = "counter")] +mod counter; +#[cfg(feature = "counter")] +pub(crate) use counter::CounterDiffCalculator; +mod tracker_texts; +mod tracker_values; +pub(super) mod tree; +mod unknown; +use either::Either; +use generic_btree::rle::{HasLength as _, Sliceable as _}; +use itertools::Itertools; +use tracker_texts::TrackerTexts; +use tracker_values::TrackerValues; + +use enum_dispatch::enum_dispatch; +use loro_common::{ + CompactIdLp, ContainerID, Counter, HasCounterSpan, IdFull, IdLp, IdSpan, LoroValue, PeerID, ID, +}; +use loro_delta::DeltaRope; +use rustc_hash::{FxHashMap, FxHashSet}; +use smallvec::SmallVec; +use tracing::{info_span, instrument}; + +use crate::{ + change::Lamport, + container::{ + idx::ContainerIdx, + list::list_op::InnerListOp, + richtext::{ + richtext_state::{RichtextStateChunk, TextChunk}, + AnchorType, CrdtRopeDelta, RichtextChunk, RichtextChunkValue, RichtextTracker, StyleOp, + }, + }, + cursor::AbsolutePosition, + delta::{ + Delta, DeltaItem, DeltaValue, ElementDelta, MapDelta, MapValue, MovableListInnerDelta, + }, + event::{DiffVariant, InternalDiff}, + op::{InnerContent, RichOp, SliceWithId}, + span::{HasId, HasLamport}, + version::Frontiers, + InternalString, VersionVector, +}; + +use self::tree::TreeDiffCalculator; + +use self::unknown::UnknownDiffCalculator; + +use super::{ + event::InternalContainerDiff, + oplog::{OpLog, ReplayBase}, +}; + +/// Calculate the diff between two versions. given [OpLog][super::oplog::OpLog] +/// and [AppState][super::state::AppState]. +/// +/// TODO: persist diffCalculator and skip processed version +#[derive(Debug)] +pub struct DiffCalculator { + /// ContainerIdx -> (depth, calculator) + /// + /// if depth is None, we need to calculate it again + calculators: FxHashMap<ContainerIdx, (Option<NonZeroU16>, ContainerDiffCalculator)>, + retain_mode: DiffCalculatorRetainMode, +} + +#[derive(Debug)] +enum DiffCalculatorRetainMode { + /// The diff calculator can only be used once. + Once { used: bool }, + /// The diff calculator will be persisted and can be reused after the diff calc is done. + Persist, +} + +/// This mode defines how the diff is calculated and how it should be applied on the state. +#[derive(Debug, Clone, PartialEq, Eq, Copy)] +pub(crate) enum DiffMode { + /// This is the most general mode of diff calculation. + /// + /// When applying `Checkout` diff, we already know the current state of the affected registers. + /// So there is no need to compare the lamport values. + /// + /// It can be used whenever a user want to switch to a different version. + /// But it is also the slowest mode. It relies on the `ContainerHistoryCache`, which is expensive to build and maintain in memory. + Checkout, + /// This mode is used when the user imports new updates. + /// + /// When applying `Import` diff, we may need to know the the current state. + /// For example, we may need to compare the current register's lamport with the update's lamport to decide + /// what's the new value. + /// + /// It has stricter requirements than `Checkout`: + /// + /// - The target version vector must be greater than the current version vector. + Import, + /// This mode is used when the user imports new updates and all the updates are guaranteed to greater than the current version. + /// + /// It has stricter requirements than `Import`. + /// - All the updates are greater than the current version. No update is concurrent to the current version. + /// - So the replay base is always the `from` version + ImportGreaterUpdates, + /// This mode is used when we don't need to build CRDTs to calculate the difference. It is the fastest mode. + /// + /// It has stricter requirements than `ImportGreaterUpdates`. + /// - In `ImportGreaterUpdates`, all the updates are guaranteed to be greater than the current version. + /// - In `Linear`, all the updates are ordered, no concurrent update exists. + Linear, +} + +#[derive(Debug, Clone, Copy)] +pub(crate) struct DiffCalcVersionInfo<'a> { + from_vv: &'a VersionVector, + to_vv: &'a VersionVector, + from_frontiers: &'a Frontiers, + to_frontiers: &'a Frontiers, + replay_base_vv: &'a VersionVector, + /// The replay base is a critical version of `ancestry(from) ∪ ancestry(to)`: + /// nothing above it is concurrent with anything below it. See + /// `OpLog::iter_from_replay_base_causally`. + replay_base_is_critical: bool, +} + +fn changed_containers_between( + oplog: &OpLog, + before: &VersionVector, + after: &VersionVector, +) -> loro_common::LoroResult<FxHashSet<ContainerIdx>> { + let (retreat, forward) = before.diff_iter(after); + oplog.try_containers_in_spans(retreat.chain(forward)) +} + +impl DiffCalculator { + /// Create a new diff calculator. + /// + /// If `persist` is true, the diff calculator will be persisted after the diff calc is done. + /// This is useful when we need to cache the diff calculator for future use. But it is slower + /// for importing updates and requires more memory. + pub fn new(persist: bool) -> Self { + Self { + calculators: Default::default(), + retain_mode: if persist { + DiffCalculatorRetainMode::Persist + } else { + DiffCalculatorRetainMode::Once { used: false } + }, + } + } + + /// The containers touched by the ranges this calculator has computed diffs for. + pub(crate) fn touched_containers(&self) -> impl Iterator<Item = ContainerIdx> + '_ { + self.calculators.keys().copied() + } + + #[allow(unused)] + pub(crate) fn get_calc(&self, container: ContainerIdx) -> Option<&ContainerDiffCalculator> { + self.calculators.get(&container).map(|(_, c)| c) + } + + /// Calculate the diff between two versions. + /// + /// Return the diff and the origin diff mode (it's not the diff mode used by the diff calculator. + /// It's the expected diff mode inferred from the two version, which can reflect the direction of the + /// change). + pub(crate) fn calc_diff_internal( + &mut self, + oplog: &OpLog, + before: &VersionVector, + before_frontiers: &Frontiers, + after: &VersionVector, + after_frontiers: &Frontiers, + container_filter: Option<&dyn Fn(ContainerIdx) -> bool>, + ) -> (Vec<InternalContainerDiff>, DiffMode) { + self.try_calc_diff_internal( + oplog, + before, + before_frontiers, + after, + after_frontiers, + container_filter, + ) + .unwrap() + } + + pub(crate) fn try_calc_diff_internal( + &mut self, + oplog: &super::oplog::OpLog, + before: &crate::VersionVector, + before_frontiers: &Frontiers, + after: &crate::VersionVector, + after_frontiers: &Frontiers, + container_filter: Option<&dyn Fn(ContainerIdx) -> bool>, + ) -> loro_common::LoroResult<(Vec<InternalContainerDiff>, DiffMode)> { + if before == after { + return Ok((Vec::new(), DiffMode::Linear)); + } + + let s = tracing::span!(tracing::Level::INFO, "DiffCalc", ?before, ?after,); + let _e = s.enter(); + + let mut merged = before.clone(); + merged.merge(after); + let ( + ReplayBase { + vv: replay_base, + diff_mode: origin_diff_mode, + is_critical: replay_base_is_critical, + concurrent_containers, + }, + iter, + ) = oplog.try_iter_from_replay_base_causally( + before, + before_frontiers, + after, + after_frontiers, + )?; + // A conservative replay base may be much older than `before`. The causal replay + // still needs that common history as position context, but containers + // whose ops are present on both sides cannot contribute to the diff. + // Without this filter, every such List/Text/MovableList can trigger its + // own full-history safety rebuild below. + let changed_containers = (&replay_base != before) + .then(|| changed_containers_between(oplog, before, after)) + .transpose()?; + // Two distinct mode values live in this function — do not conflate them: + // - `origin_diff_mode` describes the DIRECTION of the transition + // (Checkout can go backwards; the other modes imply `after ⊇ before`). + // It is what this function returns, and its consumer + // (`DocState::apply_diff`) uses it only for direction-sensitive + // policies such as the dead-containers cache. + // - `calc_mode` is the mode the calculators actually COMPUTE with. A + // persistent calculator always computes in Checkout mode, and each + // calculator reports its own effective mode in the per-container + // `InternalContainerDiff::diff_mode`, which is what the state layer's + // per-container logic (`need_check` / `need_compare`) consumes. + let mut calc_mode = origin_diff_mode; + match &mut self.retain_mode { + DiffCalculatorRetainMode::Once { used } => { + if *used { + panic!("DiffCalculator with retain_mode Once can only be used once"); + } + } + DiffCalculatorRetainMode::Persist => { + calc_mode = DiffMode::Checkout; + } + } + + let affected_set = { + loro_common::debug!("replay_base: {:?} mode={:?}", &replay_base, calc_mode); + let mut started_set = FxHashSet::default(); + for item in iter { + let (change, (start_counter, end_counter), vv) = item?; + let iter_start = change + .ops + .binary_search_by(|op| op.ctr_last().cmp(&start_counter)) + .unwrap_or_else(|e| e); + let mut visited = FxHashSet::default(); + for mut op in &change.ops.vec()[iter_start..] { + if op.counter >= end_counter { + break; + } + + let idx = op.container; + if changed_containers + .as_ref() + .is_some_and(|containers| !containers.contains(&idx)) + { + continue; + } + + if let Some(filter) = container_filter { + if !filter(idx) { + continue; + } + } + + // slice the op if needed + // PERF: we can skip the slice by using the RichOp::new_slice + let stack_sliced_op; + if op.ctr_last() < start_counter { + continue; + } + + if op.counter < start_counter || op.ctr_end() > end_counter { + stack_sliced_op = Some(op.slice( + (start_counter as usize).saturating_sub(op.counter as usize), + op.atom_len().min((end_counter - op.counter) as usize), + )); + op = stack_sliced_op.as_ref().unwrap(); + } + + let vv = &mut vv.borrow_mut(); + vv.extend_to_include_end_id(ID::new(change.peer(), op.counter)); + let container = op.container; + let depth = oplog.arena.get_depth(container); + let (old_depth, calculator) = self.get_or_create_calc(container, depth); + // checkout use the same diff_calculator, the depth of calculator is not updated + // That may cause the container to be considered deleted + if *old_depth != depth { + *old_depth = depth; + } + + if !started_set.contains(&op.container) { + started_set.insert(container); + // A container that also has ops in the concurrent old + // history (a register, or the oplog would not have let + // us replay from `before`) must resolve its values from + // history instead of trusting the state's metadata. + let container_mode = if concurrent_containers + .as_ref() + .is_some_and(|set| set.contains(&container)) + { + DiffMode::Import + } else { + calc_mode + }; + calculator.start_tracking(oplog, &replay_base, container_mode); + } + + // A change whose version misses part of `before` is being + // applied against a source state it never saw. When the + // oplog proved which containers that missing history + // touches, only those calculators lose their op context; + // the others see exactly the state their ops were made in. + if !vv.includes_vv(before) + && concurrent_containers + .as_ref() + .is_none_or(|set| set.contains(&container)) + { + calculator.mark_source_not_in_op_context(); + } + + // A replayed op concurrent with the replay base would + // contradict the base's claimed criticality. + debug_assert!( + !replay_base_is_critical || vv.includes_vv(&replay_base), + "op {}@{} is concurrent with a replay base claimed critical", + op.counter, + change.peer(), + ); + + if calculator.ignores_ops_shared_by_both_versions() { + let op_id = ID::new(change.peer(), op.ctr_last()); + if before.includes_id(op_id) && after.includes_id(op_id) { + continue; + } + } + + if visited.contains(&op.container) { + // don't checkout if we have already checked out this container in this round + calculator.apply_change(oplog, RichOp::new_by_change(&change, op), None); + } else { + calculator.apply_change( + oplog, + RichOp::new_by_change(&change, op), + Some(vv), + ); + visited.insert(container); + } + } + } + + Some(started_set) + }; + + // Because we need to get correct `bring_back` value that indicates container is created during this round of diff calc, + // we need to iterate from parents to children. i.e. from smaller depth to larger depth. + let mut new_containers = FxHashSet::default(); + let mut container_id_to_depth = FxHashMap::default(); + let mut all: Vec<(Option<NonZeroU16>, ContainerIdx)> = if let Some(set) = affected_set { + // only visit the affected containers + set.into_iter() + .map(|x| { + let (depth, _) = self.calculators.get_mut(&x).unwrap(); + (*depth, x) + }) + .collect() + } else { + self.calculators + .iter_mut() + .map(|(x, (depth, _))| (*depth, *x)) + .collect() + }; + let mut ans = FxHashMap::default(); + let info = DiffCalcVersionInfo { + from_vv: before, + to_vv: after, + from_frontiers: before_frontiers, + to_frontiers: after_frontiers, + replay_base_vv: &replay_base, + replay_base_is_critical, + }; + while !all.is_empty() { + // sort by depth and lamport, ensure we iterate from top to bottom + all.sort_by_key(|x| x.0); + for (_, container_idx) in std::mem::take(&mut all) { + if ans.contains_key(&container_idx) { + continue; + } + let (depth, calc) = self.calculators.get_mut(&container_idx).unwrap(); + if depth.is_none() { + let d = oplog.arena.get_depth(container_idx); + if d != *depth { + *depth = d; + all.push((*depth, container_idx)); + continue; + } + } + let id = oplog.arena.idx_to_id(container_idx).unwrap(); + let bring_back = new_containers.remove(&id); + + info_span!("CalcDiff", ?id).in_scope(|| { + let (diff, diff_mode) = calc.calculate_diff(container_idx, oplog, info, |c| { + new_containers.insert(c.clone()); + container_id_to_depth + .insert(c.clone(), depth.and_then(|d| d.checked_add(1))); + oplog.arena.register_container(c); + }); + calc.finish_this_round(); + if !diff.is_empty() || bring_back { + ans.insert( + container_idx, + ( + *depth, + InternalContainerDiff { + idx: container_idx, + bring_back, + diff: diff.into(), + diff_mode, + kept: None, + }, + ), + ); + } + }); + } + } + + while !new_containers.is_empty() { + for id in std::mem::take(&mut new_containers) { + // Registration can be lazy; ensure it is registered so we can proceed + let idx = oplog.arena.register_container(&id); + if ans.contains_key(&idx) { + continue; + } + let depth = container_id_to_depth.remove(&id).unwrap(); + ans.insert( + idx, + ( + depth, + InternalContainerDiff { + idx, + bring_back: true, + diff: DiffVariant::None, + diff_mode: DiffMode::Checkout, + kept: None, + }, + ), + ); + } + } + + Ok(( + ans.into_values().map(|x| x.1).collect_vec(), + origin_diff_mode, + )) + } + + // TODO: we may remove depth info + pub(crate) fn get_or_create_calc( + &mut self, + idx: ContainerIdx, + depth: Option<NonZeroU16>, + ) -> &mut (Option<NonZeroU16>, ContainerDiffCalculator) { + self.calculators + .entry(idx) + .or_insert_with(|| match idx.get_type() { + crate::ContainerType::Text => ( + depth, + ContainerDiffCalculator::Richtext(RichtextDiffCalculator::new()), + ), + crate::ContainerType::Map => ( + depth, + ContainerDiffCalculator::Map(MapDiffCalculator::new(idx)), + ), + crate::ContainerType::List => ( + depth, + ContainerDiffCalculator::List(ListDiffCalculator::default()), + ), + crate::ContainerType::Tree => ( + depth, + ContainerDiffCalculator::Tree(TreeDiffCalculator::new(idx)), + ), + crate::ContainerType::Unknown(_) => ( + depth, + ContainerDiffCalculator::Unknown(unknown::UnknownDiffCalculator), + ), + crate::ContainerType::MovableList => ( + depth, + ContainerDiffCalculator::MovableList(MovableListDiffCalculator::new(idx)), + ), + #[cfg(feature = "counter")] + crate::ContainerType::Counter => ( + depth, + ContainerDiffCalculator::Counter(CounterDiffCalculator::new(idx)), + ), + }) + } +} + +/// DiffCalculator should track the history first before it can calculate the difference. +/// +/// So we need it to first apply all the ops between the two versions. +/// +/// NOTE: not every op between two versions are included in a certain container. +/// So there may be some ops that cannot be seen by the container. +/// +#[enum_dispatch] +pub(crate) trait DiffCalculatorTrait { + fn start_tracking(&mut self, oplog: &OpLog, vv: &crate::VersionVector, mode: DiffMode); + fn apply_change( + &mut self, + oplog: &OpLog, + op: crate::op::RichOp, + vv: Option<&crate::VersionVector>, + ); + fn calculate_diff( + &mut self, + idx: ContainerIdx, + oplog: &OpLog, + info: DiffCalcVersionInfo, + on_new_container: impl FnMut(&ContainerID), + ) -> (InternalDiff, DiffMode); + /// This round of diff calc is finished, we can clear the cache + fn finish_this_round(&mut self); +} + +#[cfg(test)] +thread_local! { + /// Counts full-history CRDT tracker rebuilds so tests can assert the + /// incremental path actually short-circuits them. Test observability + /// only; thread-local so concurrently running tests cannot disturb each + /// other's counts (diff calc runs on the importing thread). + pub(crate) static FULL_TRACKER_REBUILD_COUNT: std::cell::Cell<u64> = + const { std::cell::Cell::new(0) }; +} + +#[enum_dispatch(DiffCalculatorTrait)] +#[derive(Debug)] +pub(crate) enum ContainerDiffCalculator { + Map(MapDiffCalculator), + List(ListDiffCalculator), + Richtext(RichtextDiffCalculator), + Tree(TreeDiffCalculator), + MovableList(MovableListDiffCalculator), + #[cfg(feature = "counter")] + Counter(counter::CounterDiffCalculator), + Unknown(UnknownDiffCalculator), +} + +impl ContainerDiffCalculator { + /// Whether ops that both versions already contain can be skipped. + /// + /// A conservative replay base can be far below `before`, so most replayed + /// ops are shared by both versions. Trackers still need them as position + /// context, but a register (map) resolves per key from the history cache, + /// so a shared op can never change the diff: it only makes the calculator + /// look up a key that must resolve to the same value on both sides. + fn ignores_ops_shared_by_both_versions(&self) -> bool { + matches!(self, Self::Map(_)) + } + + fn mark_source_not_in_op_context(&mut self) { + match self { + Self::Richtext(calc) => calc.mark_source_not_in_op_context(), + Self::List(calc) => calc.mark_source_not_in_op_context(), + Self::MovableList(calc) => calc.mark_source_not_in_op_context(), + _ => {} + } + } +} + +trait RebuildOpVisitor { + fn visit(&mut self, vv: &VersionVector, op: RichOp<'_>); +} + +#[cold] +#[inline(never)] +fn replay_container_ops_from_empty( + idx: ContainerIdx, + oplog: &OpLog, + vv: &VersionVector, + visitor: &mut dyn RebuildOpVisitor, +) { + let empty_vv = VersionVector::default(); + let empty_frontiers = Frontiers::default(); + let target_frontiers = oplog.dag.vv_to_frontiers(vv); + let (_, iter) = + oplog.iter_from_replay_base_causally(&empty_vv, &empty_frontiers, vv, &target_frontiers); + + for (change, (start_counter, end_counter), vv) in iter { + let iter_start = change + .ops + .binary_search_by(|op| op.ctr_last().cmp(&start_counter)) + .unwrap_or_else(|e| e); + for mut op in &change.ops.vec()[iter_start..] { + if op.counter >= end_counter { + break; + } + + if op.container != idx || op.ctr_last() < start_counter { + continue; + } + + let stack_sliced_op; + if op.counter < start_counter || op.ctr_end() > end_counter { + stack_sliced_op = Some(op.slice( + (start_counter as usize).saturating_sub(op.counter as usize), + op.atom_len().min((end_counter - op.counter) as usize), + )); + op = stack_sliced_op.as_ref().unwrap(); + } + + let vv = &mut vv.borrow_mut(); + vv.extend_to_include_end_id(ID::new(change.peer(), op.counter)); + visitor.visit(vv, RichOp::new_by_change(&change, op)); + } + } +} + +#[derive(Debug)] +pub(crate) struct MapDiffCalculator { + container_idx: ContainerIdx, + /// In `ImportGreaterUpdates`/`Linear` this holds the resolved new value per key. + /// + /// In `Checkout`/`Import` the values come from the history cache instead, so + /// only the key set matters (values stay `None`): a key that no op in the + /// replayed span writes has the same ops on both sides and therefore the + /// same winner, so it cannot appear in the diff. Restricting the history + /// cache lookup to these keys keeps map diffing proportional to the update + /// instead of to the size of the map. + changed: FxHashMap<InternalString, Option<MapValue>>, + current_mode: DiffMode, +} + +impl MapDiffCalculator { + pub(crate) fn new(container_idx: ContainerIdx) -> Self { + Self { + container_idx, + changed: Default::default(), + current_mode: DiffMode::Checkout, + } + } +} + +impl DiffCalculatorTrait for MapDiffCalculator { + fn start_tracking( + &mut self, + _oplog: &crate::OpLog, + _vv: &crate::VersionVector, + mode: DiffMode, + ) { + self.changed.clear(); + self.current_mode = mode; + } + + fn apply_change( + &mut self, + _oplog: &crate::OpLog, + op: crate::op::RichOp, + _vv: Option<&crate::VersionVector>, + ) { + let map = op.raw_op().content.as_map().unwrap(); + if matches!(self.current_mode, DiffMode::Checkout | DiffMode::Import) { + // The value is resolved from the history cache; only record which + // keys this span could have changed. + if !self.changed.contains_key(&map.key) { + self.changed.insert(map.key.clone(), None); + } + return; + } + + let new_value = MapValue { + value: map.value.clone(), + peer: op.peer, + lamp: op.lamport(), + }; + match self.changed.get(&map.key) { + Some(Some(old_value)) if old_value > &new_value => {} + _ => { + self.changed.insert(map.key.clone(), Some(new_value)); + } + } + } + + fn finish_this_round(&mut self) { + self.changed.clear(); + self.current_mode = DiffMode::Checkout; + } + + fn calculate_diff( + &mut self, + _idx: ContainerIdx, + oplog: &super::oplog::OpLog, + DiffCalcVersionInfo { from_vv, to_vv, .. }: DiffCalcVersionInfo, + mut on_new_container: impl FnMut(&ContainerID), + ) -> (InternalDiff, DiffMode) { + match self.current_mode { + DiffMode::Checkout | DiffMode::Import => oplog.with_history_cache(|h| { + h.ensure_shallow_map_seeded(self.container_idx); + let checkout_index = &h.get_checkout_index().map; + let keys = std::mem::take(&mut self.changed); + // Every key whose winning op differs is emitted, even when both + // winners carry the same value: the state keeps the winner's + // lamport/peer, and a shallow root state encoded from stale + // metadata collides with a retained op in this index and loses + // the root entry. The state is at `from` and already holds the + // `from` value, so `MapState` tells value changes from + // metadata-only updates in the same write, and the `from` value + // is never fetched here. + let changed = checkout_index.changed_winners_for_keys( + self.container_idx, + from_vv, + to_vv, + keys.into_keys(), + oplog, + ); + + let mut updated = + FxHashMap::with_capacity_and_hasher(changed.len(), Default::default()); + for (key, value) in changed { + let value = value.map(|v| { + // A normal container id is minted by one op, so a new + // winner holding a container always changes the value. + if let Some(LoroValue::Container(c)) = &v.value { + on_new_container(c); + } + + MapValue { + value: v.value, + lamp: v.lamport, + peer: v.peer, + } + }); + + updated.insert(key, value); + } + + (InternalDiff::Map(MapDelta { updated }), DiffMode::Checkout) + }), + DiffMode::ImportGreaterUpdates | DiffMode::Linear => { + let changed = std::mem::take(&mut self.changed); + let mode = self.current_mode; + // Reset this field to avoid we use `has_all` to cache the diff calc and use it next round + // (In the next round we need to use the checkout mode) + self.current_mode = DiffMode::Checkout; + (InternalDiff::Map(MapDelta { updated: changed }), mode) + } + } + } +} + +use rle::{HasLength as _, Sliceable}; + +#[derive(Default)] +pub(crate) struct ListDiffCalculator { + start_vv: VersionVector, + tracker: Box<ListTracker>, + source_not_in_op_context: bool, +} + +/// A list tracker and the values its chunks point into, replaced together. +#[derive(Default)] +struct ListTracker { + tracker: RichtextTracker, + values: TrackerValues, +} + +impl ListTracker { + /// Reseeds the tracker; the value table keeps its capacity. + fn reset(&mut self) { + self.tracker = RichtextTracker::new_with_unknown(); + self.values.clear(); + } + + #[inline(never)] + fn apply_op(&mut self, op: &crate::op::RichOp<'_>) { + match &op.op().content { + crate::op::InnerContent::List(l) => match l { + InnerListOp::Insert { slice, pos } => { + // Record only what the tracker has not applied yet: a + // checkout can replay ops the tracker already has. + let values = &mut self.values; + self.tracker + .insert_with(op.id_full(), *pos, slice.len(), |skip| { + RichtextChunk::new_text(values.push(slice.slice(skip, slice.len()))) + }); + } + InnerListOp::Delete(del) => { + self.tracker.delete( + op.id_start(), + del.id_start, + del.start() as usize, + del.atom_len(), + del.is_reversed(), + ); + } + _ => unreachable!(), + }, + _ => unreachable!(), + } + } +} + +impl std::ops::Deref for ListTracker { + type Target = RichtextTracker; + + fn deref(&self) -> &Self::Target { + &self.tracker + } +} + +impl std::ops::DerefMut for ListTracker { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.tracker + } +} + +impl ListDiffCalculator { + /// Test-only: how many values the value table holds, to pin that + /// re-replayed inserts do not grow it. + #[cfg(test)] + pub(crate) fn tracked_values_len(&self) -> usize { + self.tracker.values.len() + } + + pub(crate) fn get_id_latest_pos(&self, id: ID) -> Option<crate::cursor::AbsolutePosition> { + self.tracker.get_target_id_latest_index_at_new_version(id) + } + + fn mark_source_not_in_op_context(&mut self) { + self.source_not_in_op_context = true; + } + + #[cold] + #[inline(never)] + fn build_full_tracker(idx: ContainerIdx, oplog: &OpLog, vv: &VersionVector) -> ListTracker { + struct ListRebuildVisitor<'a> { + tracker: &'a mut ListTracker, + } + + impl RebuildOpVisitor for ListRebuildVisitor<'_> { + fn visit(&mut self, vv: &VersionVector, op: RichOp<'_>) { + self.tracker.checkout(vv); + self.tracker.apply_op(&op); + } + } + + let mut tracker = ListTracker::default(); + let mut visitor = ListRebuildVisitor { + tracker: &mut tracker, + }; + replay_container_ops_from_empty(idx, oplog, vv, &mut visitor); + + tracker + } +} + +impl MovableListDiffCalculator { + #[cfg(test)] + pub(crate) fn tracked_values_len(&self) -> usize { + self.list.tracked_values_len() + } + + pub(crate) fn get_id_latest_pos(&self, id: ID) -> Option<crate::cursor::AbsolutePosition> { + self.list + .tracker + .get_target_id_latest_index_at_new_version(id) + } + + fn mark_source_not_in_op_context(&mut self) { + self.list.mark_source_not_in_op_context(); + } +} + +impl std::fmt::Debug for ListDiffCalculator { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ListDiffCalculator") + // .field("tracker", &self.tracker) + .finish() + } +} + +impl DiffCalculatorTrait for ListDiffCalculator { + fn start_tracking(&mut self, _oplog: &OpLog, vv: &crate::VersionVector, _mode: DiffMode) { + self.source_not_in_op_context = false; + if !vv.includes_vv(&self.start_vv) || !self.tracker.all_vv().includes_vv(vv) { + self.tracker.reset(); + self.start_vv = vv.clone(); + } + + self.tracker.checkout(vv); + } + + fn apply_change( + &mut self, + _oplog: &OpLog, + op: crate::op::RichOp, + vv: Option<&crate::VersionVector>, + ) { + if let Some(vv) = vv { + self.tracker.checkout(vv); + } + + self.tracker.apply_op(&op); + } + + fn finish_this_round(&mut self) {} + + fn calculate_diff( + &mut self, + idx: ContainerIdx, + oplog: &OpLog, + info: DiffCalcVersionInfo, + mut on_new_container: impl FnMut(&ContainerID), + ) -> (InternalDiff, DiffMode) { + let mut delta = Delta::new(); + let (mut retreat, _) = info.from_vv.diff_iter(info.to_vv); + let has_retreat = retreat.next().is_some(); + let should_rebuild = matches!(idx.get_type(), crate::ContainerType::List) && { + // A certified-critical replay base can be trusted for the same + // reason as in richtext (see the soundness comment in + // `RichtextDiffCalculator::calculate_diff`) — with less + // machinery, as list trackers have no style anchors. The critical + // arm additionally requires a non-shallow doc, which preserves + // the old behavior exactly: list trackers have no shallow-root + // seeding, and the pre-existing `base == from` arm never had a + // shallow term. `has_retreat` stays load-bearing: a retreat is + // the only way a diff could emit the opaque below-base span. + let base_is_trustworthy = (info.replay_base_is_critical + && oplog.shallow_since_vv().is_empty()) + || (info.replay_base_vv == info.from_vv && !self.source_not_in_op_context); + has_retreat || !base_is_trustworthy + }; + let diff_items = if should_rebuild { + #[cfg(test)] + FULL_TRACKER_REBUILD_COUNT.with(|c| c.set(c.get() + 1)); + let mut merged = info.from_vv.clone(); + merged.merge(info.to_vv); + let mut full_tracker = Self::build_full_tracker(idx, oplog, &merged); + let diff_items = full_tracker.diff(info.from_vv, info.to_vv).collect_vec(); + *self.tracker = full_tracker; + diff_items + } else { + self.tracker.diff(info.from_vv, info.to_vv).collect_vec() + }; + + for item in diff_items { + match item { + CrdtRopeDelta::Retain(len) => { + delta = delta.retain(len); + } + CrdtRopeDelta::Insert { + chunk: value, + id, + lamport, + } => match value.value() { + RichtextChunkValue::Text(range) => { + let lamport = lamport.unwrap(); + self.tracker.values.for_each_slice(range, |offset, values| { + for v in values.as_slice() { + if let LoroValue::Container(c) = v { + on_new_container(c); + } + } + delta = std::mem::take(&mut delta).insert(SliceWithId { + values: Either::Left(values), + id: IdFull::new( + id.peer, + id.counter + offset as Counter, + lamport + offset as Lamport, + ), + elem_id: None, + }); + }); + } + RichtextChunkValue::StyleAnchor { .. } => unreachable!(), + RichtextChunkValue::Unknown(len) => { + delta = handle_unknown(idx, id, oplog, len, &mut on_new_container, delta); + } + RichtextChunkValue::MoveAnchor => { + delta = handle_unknown(idx, id, oplog, 1, &mut on_new_container, delta); + } + }, + CrdtRopeDelta::Delete(len) => { + delta = delta.delete(len); + } + } + } + + /// Handle span with unknown content when calculating diff + /// + /// We can lookup the content of the span by the id in the oplog + fn handle_unknown( + idx: ContainerIdx, + mut id: ID, + oplog: &OpLog, + len: u32, + on_new_container: &mut dyn FnMut(&ContainerID), + mut delta: Delta<SliceWithId>, + ) -> Delta<SliceWithId> { + // assert not unknown id + assert_ne!(id.peer, PeerID::MAX); + let mut acc_len = 0; + let end = id.counter + len as Counter; + let shallow_root = oplog.shallow_since_vv().get(&id.peer).copied().unwrap_or(0); + if id.counter < shallow_root { + // need to find the content between id.counter ~ target_end in gc state + let target_end = shallow_root.min(end); + delta = oplog.with_history_cache(|h| { + let chunks = + h.find_list_chunks_in(idx, IdSpan::new(id.peer, id.counter, target_end)); + for c in chunks { + acc_len += c.length(); + match &c.values { + Either::Left(_) => unreachable!(), + Either::Right(r) => { + if let LoroValue::Container(c) = r { + on_new_container(c) + } + } + } + delta = delta.insert(c); + } + + delta + }); + id.counter = shallow_root; + } + + if id.counter < end { + for rich_op in oplog.iter_ops(IdSpan::new(id.peer, id.counter, end)) { + acc_len += rich_op.content_len(); + let op = rich_op.op(); + let lamport = rich_op.lamport(); + + if let InnerListOp::Insert { slice, pos: _ } = op.content.as_list().unwrap() { + for v in slice.as_slice() { + if let LoroValue::Container(c) = v { + (on_new_container)(c); + } + } + + delta = delta.insert(SliceWithId { + values: Either::Left(slice.clone()), + id: IdFull::new(id.peer, op.counter, lamport), + elem_id: None, + }); + } else if let InnerListOp::Move { elem_id, .. } = op.content.as_list().unwrap() + { + delta = delta.insert(SliceWithId { + // We do NOT need an actual value range, + // movable list container will only use the id info + values: Either::Right(LoroValue::Null), + id: IdFull::new(id.peer, op.counter, lamport), + elem_id: Some(elem_id.compact()), + }); + } + } + } + + debug_assert_eq!(acc_len, len as usize); + delta + } + + (InternalDiff::ListRaw(delta), DiffMode::Checkout) + } +} + +#[derive(Debug)] +pub(crate) struct RichtextDiffCalculator { + mode: Box<RichtextCalcMode>, +} + +#[derive(Debug)] +enum RichtextCalcMode { + Crdt { + tracker: Box<RichtextTracker>, + /// (op, end_pos) + styles: Vec<(StyleOp, usize)>, + /// The text the tracker's text chunks point into. + texts: TrackerTexts, + start_vv: VersionVector, + source_not_in_op_context: bool, + shallow_root_seeded: bool, + }, + Linear { + diff: DeltaRope<RichtextStateChunk, ()>, + last_style_start: Option<(Arc<StyleOp>, u32)>, + }, +} + +impl RichtextDiffCalculator { + pub fn new() -> Self { + Self { + mode: Box::new(RichtextCalcMode::Crdt { + tracker: Box::new(RichtextTracker::new_with_unknown()), + styles: Vec::new(), + texts: TrackerTexts::default(), + start_vv: VersionVector::new(), + source_not_in_op_context: false, + shallow_root_seeded: false, + }), + } + } + + fn mark_source_not_in_op_context(&mut self) { + if let RichtextCalcMode::Crdt { + source_not_in_op_context, + .. + } = &mut *self.mode + { + *source_not_in_op_context = true; + } + } + + /// Test-only: how many chars the text table holds, to pin that + /// re-replayed inserts do not grow it. + #[cfg(test)] + pub(crate) fn tracked_text_len(&self) -> usize { + match &*self.mode { + RichtextCalcMode::Crdt { texts, .. } => texts.len(), + RichtextCalcMode::Linear { .. } => unreachable!(), + } + } + + /// Test-only: the ids of the style table's entries, to pin that + /// re-replayed style ops do not grow the table. + #[cfg(test)] + pub(crate) fn tracked_style_ids(&self) -> Vec<ID> { + match &*self.mode { + RichtextCalcMode::Crdt { styles, .. } => { + styles.iter().map(|(s, _)| ID::new(s.peer, s.cnt)).collect() + } + RichtextCalcMode::Linear { .. } => unreachable!(), + } + } + + fn style_for_end_anchor(oplog: &OpLog, op: &RichOp) -> Option<(StyleOp, usize)> { + let style_start_id = op.id().inc(-1); + if let Some(start_op) = oplog.get_op_that_includes(style_start_id) { + let InnerListOp::StyleStart { + start: _, + end, + key, + value, + info, + } = start_op.content.as_list().unwrap() + else { + unreachable!() + }; + + Some(( + StyleOp { + lamport: start_op.lamport(), + peer: style_start_id.peer, + cnt: style_start_id.counter, + key: key.clone(), + value: value.clone(), + info: *info, + }, + *end as usize, + )) + } else { + oplog.with_history_cache(|history_cache| { + history_cache + .find_text_style_end_in_shallow_root(op.raw_op().container, style_start_id) + }) + } + } + + fn shallow_delete_range_matches_tracker( + tracker: &RichtextTracker, + target_start: ID, + pos: usize, + len: usize, + ) -> bool { + let mut remaining = len; + let mut pos = pos; + let mut expected = target_start; + while remaining > 0 { + let Some((real_id, available)) = tracker.active_real_span_at(pos) else { + return false; + }; + + if real_id.peer != expected.peer || real_id.counter != expected.counter { + return false; + } + + let take = remaining.min(available); + expected = expected.inc(take as Counter); + pos += take; + remaining -= take; + } + + true + } + + fn shallow_clamped_tracker_pos(oplog: &OpLog, tracker: &RichtextTracker, pos: usize) -> usize { + if oplog.shallow_since_vv().is_empty() { + pos + } else { + pos.min(tracker.len()) + } + } + + /// This should be called after calc_diff + /// + /// TODO: Refactor, this can be simplified + pub fn get_id_latest_pos(&self, id: ID) -> Option<AbsolutePosition> { + match &*self.mode { + RichtextCalcMode::Crdt { tracker, .. } => { + tracker.get_target_id_latest_index_at_new_version(id) + } + RichtextCalcMode::Linear { .. } => unreachable!(), + } + } + + fn apply_crdt_op_to_tracker( + oplog: &OpLog, + tracker: &mut RichtextTracker, + styles: &mut Vec<(StyleOp, usize)>, + texts: &mut TrackerTexts, + op: RichOp, + ) { + match &op.raw_op().content { + crate::op::InnerContent::List(l) => match l { + InnerListOp::Insert { .. } | InnerListOp::Move { .. } | InnerListOp::Set { .. } => { + unreachable!() + } + InnerListOp::InsertText { + slice, + unicode_len: len, + pos, + } => { + let pos = Self::shallow_clamped_tracker_pos(oplog, tracker, *pos as usize); + // Record only what the tracker has not applied yet: a + // checkout can replay ops the tracker already has. + tracker.insert_with(op.id_full(), pos, *len as usize, |skip| { + RichtextChunk::new_text(texts.push_from(slice, *len, skip)) + }); + } + InnerListOp::Delete(del) => { + let is_shallow = !oplog.shallow_since_vv().is_empty(); + let pos = del.start() as usize; + if is_shallow + && !Self::shallow_delete_range_matches_tracker( + tracker, + del.id_start, + pos, + del.atom_len(), + ) + { + let atom_len = del.atom_len(); + let mut segments = + tracker.active_segments_of_real_id_span(del.id_start, atom_len); + if segments.is_empty() { + return; + } + + segments.sort_unstable_by_key(|(_, pos, _)| *pos); + if del.is_reversed() { + for (target_id, pos, len) in segments.into_iter().rev() { + let target_offset = + (target_id.counter - del.id_start.counter) as usize; + debug_assert!(target_offset + len <= atom_len); + let op_offset = atom_len - target_offset - len; + tracker.delete( + op.id_start().inc(op_offset as Counter), + target_id, + pos, + len, + true, + ); + } + } else { + let mut deleted_before = 0; + for (target_id, pos, len) in segments { + let target_offset = + (target_id.counter - del.id_start.counter) as usize; + debug_assert!(pos >= deleted_before); + tracker.delete( + op.id_start().inc(target_offset as Counter), + target_id, + pos.saturating_sub(deleted_before), + len, + false, + ); + deleted_before += len; + } + } + + return; + } + + tracker.delete( + op.id_start(), + del.id_start, + pos, + del.atom_len(), + del.is_reversed(), + ); + } + InnerListOp::StyleStart { + start, + end, + key, + info, + value, + } => { + debug_assert!(start < end, "start: {}, end: {}", start, end); + // A persisted tracker replays ops it has already + // applied whenever the replay base sits below the + // version the tracker reached on an earlier round. The + // tracker itself skips those inserts (`skip_applied`), + // so pushing again would only grow the table with an + // unreferenced duplicate; reuse the entry pushed the + // first time instead. All entries for one op id are + // content-equal: seeded entries (whose position slot is + // not the op's `end` field) only cover ops below the + // shallow root, which are trimmed from the oplog and + // never replayed here. StyleStart is a single atom, so + // applied-vv membership is exact. + let id = op.id_start(); + let existing_style_id = if tracker.all_vv().includes_id(id) { + styles + .iter() + .rev() + .position(|(s, _)| s.peer == id.peer && s.cnt == id.counter) + .map(|pos| styles.len() - pos - 1) + } else { + None + }; + let style_id = match existing_style_id { + Some(style_id) => style_id, + None => { + styles.push(( + StyleOp { + lamport: op.lamport(), + peer: id.peer, + cnt: id.counter, + key: key.clone(), + value: value.clone(), + info: *info, + }, + *end as usize, + )); + styles.len() - 1 + } + }; + let start = Self::shallow_clamped_tracker_pos(oplog, tracker, *start as usize); + tracker.insert( + op.id_full(), + start, + RichtextChunk::new_style_anchor(style_id as u32, AnchorType::Start), + ); + } + InnerListOp::StyleEnd => { + let id = op.id(); + if let Some(pos) = styles + .iter() + .rev() + .position(|(op, _pos)| op.peer == id.peer && op.cnt == id.counter - 1) + { + let style_id = styles.len() - pos - 1; + let (_start_op, end_pos) = &styles[style_id]; + tracker.insert( + op.id_full(), + // need to shift 1 because we insert the start style anchor before this pos + (*end_pos + 1).min(tracker.len()), + RichtextChunk::new_style_anchor(style_id as u32, AnchorType::End), + ); + } else { + let Some((style, end)) = Self::style_for_end_anchor(oplog, &op) else { + panic!("Unhandled checkout case") + }; + styles.push((style, end)); + let style_id = styles.len() - 1; + tracker.insert( + op.id_full(), + // need to shift 1 because we insert the start style anchor before this pos + (end + 1).min(tracker.len()), + RichtextChunk::new_style_anchor(style_id as u32, AnchorType::End), + ); + } + } + }, + _ => unreachable!(), + } + } + + #[cold] + #[inline(never)] + fn seed_tracker_from_shallow_root( + idx: ContainerIdx, + oplog: &OpLog, + tracker: &mut RichtextTracker, + styles: &mut Vec<(StyleOp, usize)>, + vv: &VersionVector, + ) { + if oplog.shallow_since_vv().is_empty() { + return; + } + + *tracker = RichtextTracker::new_empty(); + styles.clear(); + let shallow_root_vv = oplog + .dag + .frontiers_to_vv(oplog.shallow_since_frontiers()) + .unwrap_or_else(|| oplog.shallow_since_vv().to_vv()); + let seed_vv = if vv.includes_vv(&shallow_root_vv) { + &shallow_root_vv + } else { + vv + }; + + #[derive(Debug, Clone, Copy)] + struct SeedItem { + order: usize, + id: IdFull, + content: RichtextChunk, + } + + struct Fenwick { + tree: Vec<usize>, + } + + impl Fenwick { + fn new(len: usize) -> Self { + Self { + tree: vec![0; len + 1], + } + } + + fn add(&mut self, mut index: usize, value: usize) { + index += 1; + while index < self.tree.len() { + self.tree[index] += value; + index += index & index.wrapping_neg(); + } + } + + fn prefix_sum(&self, mut end: usize) -> usize { + let mut sum = 0; + while end > 0 { + sum += self.tree[end]; + end -= end & end.wrapping_neg(); + } + + sum + } + } + + let chunks = oplog.with_history_cache(|h| h.find_text_chunks_in_shallow_root_order(idx)); + let mut pos = 0; + let mut seed_items = Vec::new(); + let mut style_id_to_index = FxHashMap::default(); + for chunk in chunks { + match chunk { + RichtextStateChunk::Text(text) => { + let id = text.id_full(); + let vv_end = seed_vv.get(&id.peer).copied().unwrap_or(0); + if vv_end <= id.counter { + continue; + } + + let end = vv_end.min(id.counter + text.unicode_len() as Counter); + let len = (end - id.counter) as usize; + if len == 0 { + continue; + } + + seed_items.push(SeedItem { + order: seed_items.len(), + id, + content: RichtextChunk::new_unknown(len as u32), + }); + pos += len; + } + RichtextStateChunk::Style { style, anchor_type } => { + let id = match anchor_type { + AnchorType::Start => style.id(), + AnchorType::End => style.id().inc(1), + }; + if !seed_vv.includes_id(id) { + continue; + } + + let style_id = if let Some(id) = style_id_to_index.get(&style.id()) { + *id + } else { + let id = styles.len(); + styles.push((style.as_ref().clone(), pos)); + style_id_to_index.insert(style.id(), id); + id + }; + + if anchor_type == AnchorType::End { + styles[style_id].1 = pos.saturating_sub(1); + } + + seed_items.push(SeedItem { + order: seed_items.len(), + id: IdFull::new( + id.peer, + id.counter, + style.lamport + (id.counter - style.cnt) as u32, + ), + content: RichtextChunk::new_style_anchor(style_id as u32, anchor_type), + }); + pos += 1; + } + } + } + + seed_items.sort_unstable_by_key(|item| (item.id.peer, item.id.counter)); + let mut seen_end_by_peer: FxHashMap<PeerID, Counter> = FxHashMap::default(); + let mut normalized_items = Vec::with_capacity(seed_items.len()); + for mut item in seed_items { + let end = item.id.counter + item.content.len() as Counter; + let seen_end = seen_end_by_peer.entry(item.id.peer).or_default(); + if end <= *seen_end { + continue; + } + + if item.id.counter < *seen_end { + let skip = (*seen_end - item.id.counter) as usize; + item.id = item.id.inc(skip as Counter); + item.content = item.content.slice(skip..item.content.len()); + } + + *seen_end = end; + normalized_items.push(item); + } + + let seed_items = normalized_items; + let fenwick_len = seed_items + .iter() + .map(|item| item.order) + .max() + .map_or(0, |order| order + 1); + let mut inserted = Fenwick::new(fenwick_len); + for item in seed_items { + let pos = inserted.prefix_sum(item.order); + tracker.insert_seeded(pos, item.content, item.id); + inserted.add(item.order, item.content.len()); + } + + tracker.mark_shallow_root_applied(seed_vv); + } + + #[cold] + #[inline(never)] + fn build_full_crdt_tracker( + idx: ContainerIdx, + oplog: &OpLog, + vv: &VersionVector, + ) -> (RichtextTracker, Vec<(StyleOp, usize)>, TrackerTexts) { + struct RichtextRebuildVisitor<'a> { + oplog: &'a OpLog, + tracker: &'a mut RichtextTracker, + styles: &'a mut Vec<(StyleOp, usize)>, + texts: &'a mut TrackerTexts, + } + + impl RebuildOpVisitor for RichtextRebuildVisitor<'_> { + fn visit(&mut self, vv: &VersionVector, op: RichOp<'_>) { + self.tracker.checkout(vv); + RichtextDiffCalculator::apply_crdt_op_to_tracker( + self.oplog, + self.tracker, + self.styles, + self.texts, + op, + ); + } + } + + let mut tracker = RichtextTracker::new_with_unknown(); + let mut styles = Vec::new(); + let mut texts = TrackerTexts::default(); + if !oplog.shallow_since_vv().is_empty() { + Self::seed_tracker_from_shallow_root(idx, oplog, &mut tracker, &mut styles, vv); + } + + let mut visitor = RichtextRebuildVisitor { + oplog, + tracker: &mut tracker, + styles: &mut styles, + texts: &mut texts, + }; + replay_container_ops_from_empty(idx, oplog, vv, &mut visitor); + + (tracker, styles, texts) + } +} + +impl DiffCalculatorTrait for RichtextDiffCalculator { + fn start_tracking( + &mut self, + _oplog: &super::oplog::OpLog, + vv: &crate::VersionVector, + mode: DiffMode, + ) { + match mode { + DiffMode::Linear => { + *self.mode = RichtextCalcMode::Linear { + diff: DeltaRope::new(), + last_style_start: None, + }; + } + _ => { + if !matches!(&*self.mode, RichtextCalcMode::Crdt { .. }) { + unreachable!(); + } + } + } + + match &mut *self.mode { + RichtextCalcMode::Crdt { + tracker, + styles, + texts, + start_vv, + source_not_in_op_context, + shallow_root_seeded, + } => { + *source_not_in_op_context = false; + if !vv.includes_vv(start_vv) || !tracker.all_vv().includes_vv(vv) { + **tracker = RichtextTracker::new_with_unknown(); + styles.clear(); + texts.clear(); + *start_vv = vv.clone(); + *shallow_root_seeded = false; + } + + tracker.checkout(vv); + } + RichtextCalcMode::Linear { .. } => {} + } + } + + fn apply_change( + &mut self, + oplog: &super::oplog::OpLog, + op: crate::op::RichOp, + vv: Option<&crate::VersionVector>, + ) { + match &mut *self.mode { + RichtextCalcMode::Linear { + diff, + last_style_start, + } => match &op.raw_op().content { + crate::op::InnerContent::List(l) => match l { + InnerListOp::Insert { .. } + | InnerListOp::Move { .. } + | InnerListOp::Set { .. } => { + unreachable!() + } + InnerListOp::InsertText { slice, pos, .. } => { + diff.insert_value( + *pos as usize, + RichtextStateChunk::new_text(slice.clone(), op.id_full()), + (), + ); + } + InnerListOp::Delete(del) => { + diff.delete(del.start() as usize, del.atom_len()); + } + InnerListOp::StyleStart { + start, + end, + key, + info, + value, + } => { + debug_assert!(start < end, "start: {}, end: {}", start, end); + let style_op = Arc::new(StyleOp { + lamport: op.lamport(), + peer: op.peer, + cnt: op.id_start().counter, + key: key.clone(), + value: value.clone(), + info: *info, + }); + + *last_style_start = Some((style_op.clone(), *end)); + diff.insert_value( + *start as usize, + RichtextStateChunk::new_style(style_op, AnchorType::Start), + (), + ); + } + InnerListOp::StyleEnd => { + let (style_op, pos) = match last_style_start.take() { + Some((style_op, pos)) => (style_op, pos), + None => { + let Some((style_op, pos)) = Self::style_for_end_anchor(oplog, &op) + else { + panic!("Unhandled checkout case") + }; + + (Arc::new(style_op), pos as u32) + } + }; + assert_eq!(style_op.peer, op.peer); + assert_eq!(style_op.cnt, op.id_start().counter - 1); + diff.insert_value( + pos as usize + 1, + RichtextStateChunk::new_style(style_op, AnchorType::End), + (), + ); + } + }, + _ => unreachable!(), + }, + RichtextCalcMode::Crdt { + tracker, + styles, + texts, + start_vv, + source_not_in_op_context: _, + shallow_root_seeded, + } => { + if !*shallow_root_seeded && !oplog.shallow_since_vv().is_empty() { + Self::seed_tracker_from_shallow_root( + op.raw_op().container, + oplog, + tracker, + styles, + start_vv, + ); + // The seeded tracker replaced the old one and holds no text chunks. + texts.clear(); + *shallow_root_seeded = true; + } + + if let Some(vv) = vv { + tracker.checkout(vv); + } + Self::apply_crdt_op_to_tracker(oplog, tracker, styles, texts, op); + } + } + } + + fn calculate_diff( + &mut self, + idx: ContainerIdx, + oplog: &OpLog, + info: DiffCalcVersionInfo, + _: impl FnMut(&ContainerID), + ) -> (InternalDiff, DiffMode) { + #[allow(clippy::too_many_arguments)] + fn push_tracker_chunk( + delta: &mut DeltaRope<RichtextStateChunk, ()>, + idx: ContainerIdx, + oplog: &OpLog, + styles: &[(StyleOp, usize)], + texts: &TrackerTexts, + value: RichtextChunk, + id: ID, + lamport: Option<Lamport>, + ) { + match value.value() { + RichtextChunkValue::Text(text) => { + let lamport = lamport.unwrap(); + texts.for_each_slice(text, |offset, bytes| { + delta.push_insert( + RichtextStateChunk::Text(TextChunk::new( + bytes, + IdFull::new( + id.peer, + id.counter + offset as Counter, + lamport + offset as Lamport, + ), + )), + (), + ); + }); + } + RichtextChunkValue::StyleAnchor { id, anchor_type } => { + delta.push_insert( + RichtextStateChunk::Style { + style: Arc::new(styles[id as usize].0.clone()), + anchor_type, + }, + (), + ); + } + RichtextChunkValue::Unknown(len) => { + // assert not unknown id + assert_ne!(id.peer, PeerID::MAX); + let mut id = id; + let mut acc_len = 0; + let end = id.counter + len as Counter; + let shallow_root = oplog.shallow_since_vv().get(&id.peer).copied().unwrap_or(0); + if id.counter < shallow_root { + // need to find the content between id.counter ~ target_end in gc state + let target_end = shallow_root.min(end); + oplog.with_history_cache(|h| { + let chunks = h.find_text_chunks_in( + idx, + IdSpan::new(id.peer, id.counter, target_end), + ); + for c in chunks { + acc_len += c.rle_len(); + delta.push_insert(c, ()); + } + }); + id.counter = shallow_root; + } + + if id.counter < end { + for rich_op in oplog.iter_ops(IdSpan::new(id.peer, id.counter, end)) { + acc_len += rich_op.content_len(); + let op = rich_op.op(); + let lamport = rich_op.lamport(); + let content = op.content.as_list().unwrap(); + match content { + InnerListOp::InsertText { slice, .. } => { + delta.push_insert( + RichtextStateChunk::Text(TextChunk::new( + slice.clone(), + IdFull::new(id.peer, op.counter, lamport), + )), + (), + ); + } + _ => unreachable!("{:?}", content), + } + } + } + + debug_assert_eq!(acc_len, len as usize); + } + RichtextChunkValue::MoveAnchor => unreachable!(), + } + } + + fn push_tracker_delta_item( + delta: &mut DeltaRope<RichtextStateChunk, ()>, + idx: ContainerIdx, + oplog: &OpLog, + styles: &[(StyleOp, usize)], + texts: &TrackerTexts, + item: CrdtRopeDelta, + ) { + match item { + CrdtRopeDelta::Retain(len) => { + delta.push_retain(len, ()); + } + CrdtRopeDelta::Insert { + chunk: value, + id, + lamport, + } => push_tracker_chunk(delta, idx, oplog, styles, texts, value, id, lamport), + CrdtRopeDelta::Delete(len) => { + delta.push_delete(len); + } + } + } + + match &mut *self.mode { + RichtextCalcMode::Linear { diff, .. } => ( + InternalDiff::RichtextRaw(std::mem::take(diff)), + DiffMode::Linear, + ), + RichtextCalcMode::Crdt { + tracker, + styles, + texts, + source_not_in_op_context, + .. + } => { + let (mut retreat, _) = info.from_vv.diff_iter(info.to_vv); + let has_retreat = retreat.next().is_some(); + // The tracker models everything below its seed version as one + // opaque "unknown" span: it can never be retreated and its + // interior has no ids. Trusting it is sound exactly when no + // replayed op is concurrent with anything below the replay + // base — the definition of a critical base (spec D8b). Every + // concurrent pair the Fugue adjudication has to order is then + // inside the replayed region, and the alive-set of below-base + // content is identical at every checkout the replay performs, + // so the opaque span is a faithful, length-stable model of + // the base state. A reused tracker may be seeded even lower + // (`start_vv` ⊆ base); criticality transfers down, because an + // op concurrent with an event in `Events(start_vv)` would be + // concurrent with that same event in `Events(base)`. + // A base only known to lie in the causal past of both sides + // gives no such promise (`source_not_in_op_context` then + // reports replayed ops whose causal context misses the source + // state), so fall back to reconstructing the target state from + // CRDT ids. + let base_is_trustworthy = info.replay_base_is_critical + || (info.replay_base_vv == info.from_vv && !*source_not_in_op_context); + let should_rebuild = + has_retreat || !base_is_trustworthy || !oplog.shallow_since_vv().is_empty(); + if should_rebuild { + // Richtext diffs can start from a tracker that only knows the replay-base + // state as unknown spans. Expressing a rollback or an import from a base + // older than `from` as local + // edits can target the wrong visible text when the source state contains + // concurrent inserts or sliced ops. The same risk exists when an op is replayed + // from a dependency version that does not include the visible source state. + // Preserve correctness by replacing the visible source state with the target + // state reconstructed from CRDT ids. Shallow docs seed this tracker from the + // shallow-root state and replay only the retained suffix of history. + #[cfg(test)] + FULL_TRACKER_REBUILD_COUNT.with(|c| c.set(c.get() + 1)); + let mut merged = info.from_vv.clone(); + merged.merge(info.to_vv); + let (mut full_tracker, full_styles, full_texts) = + Self::build_full_crdt_tracker(idx, oplog, &merged); + + let mut delta = DeltaRope::new(); + for item in full_tracker.diff(info.from_vv, info.to_vv) { + push_tracker_delta_item( + &mut delta, + idx, + oplog, + &full_styles, + &full_texts, + item, + ); + } + **tracker = full_tracker; + *styles = full_styles; + *texts = full_texts; + // `start_vv` is deliberately left as-is: the rebuild's + // real seed is even lower (the empty version, or the + // shallow root), so the reseed test in `start_tracking` + // only becomes more conservative. + + return (InternalDiff::RichtextRaw(delta), DiffMode::Checkout); + } + + let mut delta = DeltaRope::new(); + for item in tracker.diff(info.from_vv, info.to_vv) { + // `has_retreat` in `should_rebuild` is load-bearing for + // this loop: a retreat is the only way to un-delete + // below-base content, so a forward-only diff can never + // emit the opaque span as an insert (which would abort in + // `push_tracker_chunk`). + #[cfg(debug_assertions)] + if let CrdtRopeDelta::Insert { chunk, .. } = &item { + debug_assert!( + !matches!(chunk.value(), RichtextChunkValue::Unknown(_)), + "the opaque below-base span leaked into a richtext diff" + ); + } + push_tracker_delta_item(&mut delta, idx, oplog, styles, texts, item); + } + + (InternalDiff::RichtextRaw(delta), DiffMode::Checkout) + } + } + } + + fn finish_this_round(&mut self) { + match &mut *self.mode { + RichtextCalcMode::Crdt { .. } => {} + RichtextCalcMode::Linear { + diff, + last_style_start, + } => { + *diff = DeltaRope::new(); + last_style_start.take(); + } + } + } +} + +#[derive(Debug)] +pub(crate) struct MovableListDiffCalculator { + list: Box<ListDiffCalculator>, + inner: Box<MovableListInner>, +} + +#[derive(Debug)] +struct MovableListInner { + changed_elements: FxHashMap<CompactIdLp, ElementDelta>, + move_id_to_elem_id: FxHashMap<ID, IdLp>, + current_mode: DiffMode, +} + +impl DiffCalculatorTrait for MovableListDiffCalculator { + fn start_tracking(&mut self, _oplog: &OpLog, vv: &crate::VersionVector, mode: DiffMode) { + self.list.source_not_in_op_context = false; + if !vv.includes_vv(&self.list.start_vv) || !self.list.tracker.all_vv().includes_vv(vv) { + self.list.tracker.reset(); + self.list.start_vv = vv.clone(); + } + + self.list.tracker.checkout(vv); + self.inner.current_mode = mode; + } + + fn apply_change( + &mut self, + oplog: &OpLog, + op: crate::op::RichOp, + vv: Option<&crate::VersionVector>, + ) { + let InnerContent::List(l) = &op.raw_op().content else { + unreachable!() + }; + + // collect the elements that are moved, updated, or inserted + + // If it's checkout mode, we don't need to track the changes + // we only need the element ids + match l { + InnerListOp::Insert { slice, pos: _ } => { + let op_id = op.id_full().idlp(); + for (i, value) in slice.as_slice().iter().enumerate() { + let id = op_id.inc(i as Counter); + + self.inner.changed_elements.insert( + id.compact(), + ElementDelta { + pos: Some(id), + value: value.clone(), + value_updated: true, + value_id: Some(id), + }, + ); + } + } + InnerListOp::Delete(_) => {} + InnerListOp::Move { elem_id, .. } => { + let idlp = IdLp::new(op.peer, op.lamport()); + match self.inner.changed_elements.get_mut(&elem_id.compact()) { + Some(change) => { + if change.pos.is_some() && change.pos.as_ref().unwrap() > &idlp { + } else { + change.pos = Some(idlp); + } + } + None => { + self.inner.changed_elements.insert( + elem_id.compact(), + ElementDelta { + pos: Some(idlp), + value: LoroValue::Null, + value_updated: false, + value_id: None, + }, + ); + } + } + } + InnerListOp::Set { elem_id, value } => { + let idlp = IdLp::new(op.peer, op.lamport()); + match self.inner.changed_elements.get_mut(&elem_id.compact()) { + Some(change) => { + if change.value_id.is_some() && change.value_id.as_ref().unwrap() > &idlp { + } else { + change.value_id = Some(idlp); + change.value = value.clone(); + } + } + None => { + self.inner.changed_elements.insert( + elem_id.compact(), + ElementDelta { + pos: None, + value: value.clone(), + value_updated: true, + value_id: Some(idlp), + }, + ); + } + } + } + + InnerListOp::StyleStart { .. } => unreachable!(), + InnerListOp::StyleEnd => unreachable!(), + InnerListOp::InsertText { .. } => unreachable!(), + } + + let is_checkout = matches!(self.inner.current_mode, DiffMode::Checkout); + + { + // Apply change on the list items + if let Some(vv) = vv { + self.list.tracker.checkout(vv); + } + Self::apply_op_to_tracker( + &mut self.list.tracker, + &mut self.inner.move_id_to_elem_id, + oplog, + &op, + is_checkout, + ); + }; + } + + fn finish_this_round(&mut self) { + self.list.finish_this_round(); + } + + #[instrument(skip(self, oplog, on_new_container))] + fn calculate_diff( + &mut self, + idx: ContainerIdx, + oplog: &OpLog, + info: DiffCalcVersionInfo, + mut on_new_container: impl FnMut(&ContainerID), + ) -> (InternalDiff, DiffMode) { + let (mut retreat, _) = info.from_vv.diff_iter(info.to_vv); + let has_retreat = retreat.next().is_some(); + // Deliberately NOT relaxed for a certified-critical replay base: the + // movable-list element phase reads positions from a tracker this + // rebuild has just refreshed, and trusting an unknown-span tracker + // here needs its own argument about element/position state. See the + // soundness comment in `RichtextDiffCalculator::calculate_diff`. + if has_retreat || info.replay_base_vv != info.from_vv || self.list.source_not_in_op_context + { + let mut merged = info.from_vv.clone(); + merged.merge(info.to_vv); + self.rebuild_full_tracker(idx, oplog, &merged); + } + + let (InternalDiff::ListRaw(list_diff), diff_mode) = + self.list.calculate_diff(idx, oplog, info, |_| {}) + else { + unreachable!() + }; + + assert_eq!(diff_mode, DiffMode::Checkout); + let is_checkout = matches!( + self.inner.current_mode, + DiffMode::Checkout | DiffMode::Import + ); + let mut element_changes: FxHashMap<CompactIdLp, ElementDelta> = if is_checkout { + FxHashMap::default() + } else { + std::mem::take(&mut self.inner.changed_elements) + }; + + if is_checkout { + for id in self.inner.changed_elements.keys() { + element_changes.insert(*id, ElementDelta::placeholder()); + } + } + + let list_diff: Delta<SmallVec<[IdFull; 1]>, ()> = Delta { + vec: list_diff + .iter() + .map(|x| match x { + &DeltaItem::Retain { retain, .. } => DeltaItem::Retain { + retain, + attributes: (), + }, + DeltaItem::Insert { insert, .. } => { + let len = insert.length(); + let id = insert.id; + let mut new_insert = SmallVec::with_capacity(len); + for i in 0..len { + let id = id.inc(i as i32); + let elem_id = + if let Some(e) = self.inner.move_id_to_elem_id.get(&id.id()) { + e.compact() + } else { + insert.elem_id.unwrap_or_else(|| id.idlp().compact()) + }; + if is_checkout { + // add the related element id + element_changes.insert(elem_id, ElementDelta::placeholder()); + } + new_insert.push(id); + } + + DeltaItem::Insert { + insert: new_insert, + attributes: (), + } + } + &DeltaItem::Delete { delete, .. } => DeltaItem::Delete { + delete, + attributes: (), + }, + }) + .collect(), + }; + + if is_checkout { + oplog.with_history_cache(|history_cache| { + let checkout_index = &history_cache.get_checkout_index().movable_list; + element_changes.retain(|id, change| { + let id = id.to_id(); + // It can be None if the target does not exist before the `to` version + // But we don't need to calc from, because the deletion is handled by the diff from list items + + // TODO: PERF: Provide the lamport of to version + let Some(pos) = checkout_index.last_pos(id, info.to_vv, Lamport::MAX, oplog) + else { + return false; + }; + // TODO: PERF: Provide the lamport of to version + let value = checkout_index + .last_value(id, info.to_vv, Lamport::MAX, oplog) + .unwrap(); + // TODO: PERF: Provide the lamport of to version + let old_pos = checkout_index.last_pos(id, info.from_vv, Lamport::MAX, oplog); + // TODO: PERF: Provide the lamport of to version + let old_value = + checkout_index.last_value(id, info.from_vv, Lamport::MAX, oplog); + if old_pos.is_none() && old_value.is_none() { + if let LoroValue::Container(c) = &value.value { + on_new_container(c); + } + *change = ElementDelta { + pos: Some(pos.idlp()), + value: value.value.clone(), + value_id: Some(IdLp::new(value.peer, value.lamport)), + value_updated: true, + }; + } else { + // TODO: PERF: can be filtered based on the list_diff and whether the pos/value are updated + *change = ElementDelta { + pos: Some(pos.idlp()), + value: value.value.clone(), + value_updated: old_value.unwrap().value != value.value, + value_id: Some(IdLp::new(value.peer, value.lamport)), + }; + } + + true + }); + }); + } + + let diff = MovableListInnerDelta { + list: list_diff, + elements: element_changes, + }; + + (InternalDiff::MovableList(diff), self.inner.current_mode) + } +} + +impl MovableListDiffCalculator { + fn new(_container: ContainerIdx) -> MovableListDiffCalculator { + MovableListDiffCalculator { + list: Default::default(), + inner: Box::new(MovableListInner { + changed_elements: Default::default(), + current_mode: DiffMode::Checkout, + move_id_to_elem_id: Default::default(), + }), + } + } + + fn apply_op_to_tracker( + tracker: &mut ListTracker, + move_id_to_elem_id: &mut FxHashMap<ID, IdLp>, + oplog: &OpLog, + op: &RichOp<'_>, + is_checkout: bool, + ) { + let real_op = op.op(); + match &real_op.content { + InnerContent::List(l) => match l { + InnerListOp::Insert { .. } | InnerListOp::Delete(_) => tracker.apply_op(op), + InnerListOp::Move { from, elem_id, to } => { + move_id_to_elem_id.insert(op.id(), *elem_id); + if !tracker.current_vv().includes_id(op.id()) { + let last_pos = if is_checkout { + oplog.with_history_cache(|h| { + let list = &h.get_checkout_index().movable_list; + list.last_pos(*elem_id, tracker.current_vv(), Lamport::MAX, oplog) + .expect("moved element should have a visible source position") + .id() + }) + } else { + // In import/linear mode this id is only needed if the tracker is later + // checked out before the source version, which those modes do not do. + ID::new(PeerID::MAX - 2, 0) + }; + tracker.move_item(op.id_full(), last_pos, *from as usize, *to as usize); + } + } + InnerListOp::Set { .. } => {} + InnerListOp::InsertText { .. } + | InnerListOp::StyleStart { .. } + | InnerListOp::StyleEnd => unreachable!(), + }, + _ => unreachable!(), + } + } + + #[cold] + #[inline(never)] + fn rebuild_full_tracker(&mut self, idx: ContainerIdx, oplog: &OpLog, vv: &VersionVector) { + struct MovableListRebuildVisitor<'a> { + oplog: &'a OpLog, + tracker: &'a mut ListTracker, + move_id_to_elem_id: &'a mut FxHashMap<ID, IdLp>, + } + + impl RebuildOpVisitor for MovableListRebuildVisitor<'_> { + fn visit(&mut self, vv: &VersionVector, op: RichOp<'_>) { + self.tracker.checkout(vv); + MovableListDiffCalculator::apply_op_to_tracker( + self.tracker, + self.move_id_to_elem_id, + self.oplog, + &op, + true, + ); + } + } + + let mut tracker = ListTracker::default(); + let mut move_id_to_elem_id = FxHashMap::default(); + let mut visitor = MovableListRebuildVisitor { + oplog, + tracker: &mut tracker, + move_id_to_elem_id: &mut move_id_to_elem_id, + }; + replay_container_ops_from_empty(idx, oplog, vv, &mut visitor); + + *self.list.tracker = tracker; + self.inner.move_id_to_elem_id = move_id_to_elem_id; + } +} + +#[test] +fn test_size() { + let text = RichtextDiffCalculator::new(); + let size = std::mem::size_of_val(&text); + assert!(size < 50, "RichtextDiffCalculator size: {}", size); + let list = MovableListDiffCalculator::new(ContainerIdx::from_index_and_type( + 0, + loro_common::ContainerType::MovableList, + )); + let size = std::mem::size_of_val(&list); + assert!(size < 50, "MovableListDiffCalculator size: {}", size); + let calc = ContainerDiffCalculator::Richtext(text); + let size = std::mem::size_of_val(&calc); + assert!(size < 50, "ContainerDiffCalculator size: {}", size); +} + +/// A doc with a movable list "items" holding a nested map (`value: 0`) plus +/// unrelated list/text containers, committed as peer 1. +#[cfg(test)] +fn movable_list_fixture() -> crate::LoroDoc { + use crate::{LoroDoc, MapHandler}; + + let base = LoroDoc::new_auto_commit(); + base.set_peer_id(1).unwrap(); + let nested = base + .get_movable_list("items") + .push_container(MapHandler::new_detached()) + .unwrap(); + nested.insert("value", 0).unwrap(); + base.get_list("unrelated-list").push("a").unwrap(); + base.get_text("unrelated-text") + .insert(0, "a", crate::cursor::PosType::Unicode) + .unwrap(); + base.commit_then_renew(); + base +} + +#[cfg(test)] +fn nested_map(doc: &crate::LoroDoc) -> crate::MapHandler { + use crate::handler::ValueOrHandler; + + match doc.get_movable_list("items").get_(0).unwrap() { + ValueOrHandler::Handler(handler) => handler.into_map().unwrap(), + ValueOrHandler::Value(value) => panic!("expected nested map, got {value:?}"), + } +} + +/// Asserts the diff round produced exactly one internal map diff, for +/// `expected_idx`, whose `key` entry resolves to `expected`. +#[cfg(test)] +fn assert_single_map_value_diff( + diffs: &[InternalContainerDiff], + expected_idx: ContainerIdx, + key: &str, + expected: LoroValue, +) { + assert_eq!(diffs.len(), 1); + let diff = &diffs[0]; + assert_eq!(diff.idx, expected_idx); + let DiffVariant::Internal(InternalDiff::Map(map_diff)) = &diff.diff else { + panic!("expected an internal map diff, got {:?}", diff.diff); + }; + let value = map_diff + .updated + .get(&InternalString::from(key)) + .unwrap_or_else(|| panic!("map diff has no entry for {key:?}: {map_diff:?}")) + .as_ref() + .and_then(|map_value| map_value.value.clone()); + assert_eq!(value, Some(expected)); +} + +#[test] +fn causal_existing_peer_import_uses_current_version_as_replay_base() { + use crate::{handler::HandlerTrait, loro::ExportMode}; + + let base = movable_list_fixture(); + let target = base.fork(); + let source = base.fork(); + let relay = base.fork(); + // Continue an existing peer after another peer has become the current + // frontier. This gives the new change both an explicit dependency on the + // relay and an implicit dependency on its own previous counter. + source.set_peer_id(1).unwrap(); + relay.set_peer_id(2).unwrap(); + relay.get_map("relay").insert("ready", true).unwrap(); + relay.commit_then_renew(); + let relay_updates = relay.export(ExportMode::updates(&base.oplog_vv())).unwrap(); + target.import(&relay_updates).unwrap(); + source.import(&relay_updates).unwrap(); + + let before = target.oplog_vv(); + let before_frontiers = target.oplog_frontiers(); + nested_map(&source).insert("value", 1).unwrap(); + source.commit_then_renew(); + let nested_update = source.export(ExportMode::updates(&before)).unwrap(); + + // Import only into the oplog so this test can inspect the exact diff round. + target.detach(); + target.import(&nested_update).unwrap(); + let after = target.oplog_vv(); + let after_frontiers = target.oplog_frontiers(); + let expected_idx = nested_map(&target).idx(); + + let oplog = target.oplog().lock(); + let (base, _) = + oplog.iter_from_replay_base_causally(&before, &before_frontiers, &after, &after_frontiers); + assert_eq!(base.vv, before); + assert_eq!(base.diff_mode, DiffMode::ImportGreaterUpdates); + assert_eq!( + changed_containers_between(&oplog, &before, &after).unwrap(), + [expected_idx].into_iter().collect() + ); + + let mut calculator = DiffCalculator::new(false); + let (diffs, _) = calculator.calc_diff_internal( + &oplog, + &before, + &before_frontiers, + &after, + &after_frontiers, + None, + ); + assert_eq!(calculator.calculators.len(), 1); + assert!(calculator.get_calc(expected_idx).is_some()); + assert_single_map_value_diff(&diffs, expected_idx, "value", 1.into()); +} + +#[test] +fn conservative_replay_only_builds_calculators_for_changed_containers() { + use crate::{handler::HandlerTrait, loro::ExportMode}; + + let base = movable_list_fixture(); + let target = base.fork(); + target.set_peer_id(2).unwrap(); + target.get_map("relay").insert("ready", true).unwrap(); + // Concurrent edits on the same list are what force the conservative + // replay; register-only concurrency would be replayed from `before`. + target.get_list("unrelated-list").push("b").unwrap(); + target.commit_then_renew(); + + let source = base.fork(); + source.set_peer_id(3).unwrap(); + nested_map(&source).insert("value", 1).unwrap(); + source.get_list("unrelated-list").push("c").unwrap(); + source.commit_then_renew(); + + let before = target.oplog_vv(); + let before_frontiers = target.oplog_frontiers(); + let nested_update = source.export(ExportMode::updates(&before)).unwrap(); + + // Import only into the oplog so this test can inspect the exact diff round. + target.detach(); + target.import(&nested_update).unwrap(); + let after = target.oplog_vv(); + let after_frontiers = target.oplog_frontiers(); + let expected_idx = nested_map(&target).idx(); + let list_idx = target.get_list("unrelated-list").idx(); + + let oplog = target.oplog().lock(); + let (base, _) = + oplog.iter_from_replay_base_causally(&before, &before_frontiers, &after, &after_frontiers); + assert_ne!( + base.vv, before, + "the fixture must exercise conservative replay" + ); + assert_eq!(base.diff_mode, DiffMode::Import); + assert_eq!( + changed_containers_between(&oplog, &before, &after).unwrap(), + [expected_idx, list_idx].into_iter().collect() + ); + + let mut calculator = DiffCalculator::new(false); + let (diffs, _) = calculator.calc_diff_internal( + &oplog, + &before, + &before_frontiers, + &after, + &after_frontiers, + None, + ); + assert_eq!(calculator.calculators.len(), 2); + assert!(calculator.get_calc(expected_idx).is_some()); + assert!(calculator.get_calc(list_idx).is_some()); + let map_diffs: Vec<_> = diffs + .iter() + .filter(|d| d.idx == expected_idx) + .cloned() + .collect(); + assert_single_map_value_diff(&map_diffs, expected_idx, "value", 1.into()); +} + +#[test] +fn conservative_checkout_replay_filters_to_retreat_changed_containers() { + use crate::{handler::HandlerTrait, loro::ExportMode}; + + let base = movable_list_fixture(); + let target = base.fork(); + target.set_peer_id(2).unwrap(); + target.get_map("relay").insert("ready", true).unwrap(); + target.commit_then_renew(); + + let source = base.fork(); + source.set_peer_id(3).unwrap(); + nested_map(&source).insert("value", 1).unwrap(); + source.commit_then_renew(); + + // `after` is the older version; the concurrent nested-map edit exists only + // on the `before` side, so the changed set comes from the retreat spans. + let after = target.oplog_vv(); + let after_frontiers = target.oplog_frontiers(); + let nested_update = source + .export(ExportMode::updates(&base.oplog_vv())) + .unwrap(); + + // Import only into the oplog so this test can inspect the exact diff round. + target.detach(); + target.import(&nested_update).unwrap(); + let before = target.oplog_vv(); + let before_frontiers = target.oplog_frontiers(); + let expected_idx = nested_map(&target).idx(); + + let oplog = target.oplog().lock(); + let (base, _) = + oplog.iter_from_replay_base_causally(&before, &before_frontiers, &after, &after_frontiers); + assert_ne!( + base.vv, before, + "the fixture must exercise conservative replay" + ); + assert_eq!(base.diff_mode, DiffMode::Checkout); + assert_eq!( + changed_containers_between(&oplog, &before, &after).unwrap(), + [expected_idx].into_iter().collect() + ); + + let mut calculator = DiffCalculator::new(false); + let (diffs, _) = calculator.calc_diff_internal( + &oplog, + &before, + &before_frontiers, + &after, + &after_frontiers, + None, + ); + assert_eq!(calculator.calculators.len(), 1); + assert!(calculator.get_calc(expected_idx).is_some()); + // Checking out backward removes the concurrent edit again. + assert_single_map_value_diff(&diffs, expected_idx, "value", 0.into()); +} + +/// A persisted calculator (the shape `LoroDoc::checkout` drives) replays +/// ops its tracker has already applied whenever the tracker was rebuilt +/// past `from`: here a retreat rebuilds it over the whole history, and the +/// forward walk that follows re-replays every op. The tracker skips those +/// inserts, but the style table must not grow a duplicate entry per +/// re-replayed StyleStart. +#[test] +fn persisted_walk_does_not_duplicate_style_entries() { + use crate::{cursor::PosType, handler::HandlerTrait, LoroDoc}; + + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + a.get_text("t") + .insert(0, "seed text", PosType::Unicode) + .unwrap(); + a.commit_then_renew(); + let marks = 5; + let mut stops = vec![a.oplog_frontiers()]; + for round in 0..marks { + let t = a.get_text("t"); + t.insert(0, "x", PosType::Unicode).unwrap(); + t.mark(0, 4, "bold", (round % 2 == 0).into(), PosType::Unicode) + .unwrap(); + a.commit_then_renew(); + stops.push(a.oplog_frontiers()); + } + + let oplog = a.oplog().lock(); + let idx = a.get_text("t").idx(); + let vv = |f: &Frontiers| oplog.dag.frontiers_to_vv(f).unwrap(); + let mut calc = DiffCalculator::new(true); + let first = &stops[0]; + let last = stops.last().unwrap(); + calc.calc_diff_internal(&oplog, &vv(first), first, &vv(last), last, None); + calc.calc_diff_internal(&oplog, &vv(last), last, &vv(first), first, None); + for w in stops.windows(2) { + calc.calc_diff_internal(&oplog, &vv(&w[0]), &w[0], &vv(&w[1]), &w[1], None); + } + + let (_, c) = calc.get_or_create_calc(idx, oplog.arena.get_depth(idx)); + let ContainerDiffCalculator::Richtext(text) = c else { + panic!("expected a richtext calculator"); + }; + let ids = text.tracked_style_ids(); + assert_eq!(ids.len(), marks, "duplicate style entries: {ids:?}"); +} diff --git a/vendor/loro-internal/src/diff_calc/counter.rs b/vendor/loro-internal/src/diff_calc/counter.rs new file mode 100644 index 0000000..bf0663b --- /dev/null +++ b/vendor/loro-internal/src/diff_calc/counter.rs @@ -0,0 +1,63 @@ +use std::collections::BTreeMap; + +use loro_common::{ContainerID, ID}; + +use crate::{container::idx::ContainerIdx, event::InternalDiff, OpLog}; + +use super::{DiffCalcVersionInfo, DiffCalculatorTrait, DiffMode}; + +#[derive(Debug)] +pub(crate) struct CounterDiffCalculator { + ops: BTreeMap<ID, f64>, +} + +impl CounterDiffCalculator { + pub(crate) fn new(_idx: ContainerIdx) -> Self { + Self { + ops: BTreeMap::new(), + } + } +} + +impl DiffCalculatorTrait for CounterDiffCalculator { + fn start_tracking(&mut self, _oplog: &OpLog, _vv: &crate::VersionVector, _mode: DiffMode) {} + + fn apply_change( + &mut self, + _oplog: &OpLog, + op: crate::op::RichOp, + _vv: Option<&crate::VersionVector>, + ) { + let id = op.id(); + self.ops.insert( + id, + *op.op().content.as_future().unwrap().as_counter().unwrap(), + ); + } + + fn finish_this_round(&mut self) {} + + fn calculate_diff( + &mut self, + _idx: ContainerIdx, + _oplog: &OpLog, + info: DiffCalcVersionInfo, + _on_new_container: impl FnMut(&ContainerID), + ) -> (InternalDiff, DiffMode) { + let mut diff = 0.; + let (b, a) = info.from_vv.diff_iter(info.to_vv); + + for sub in b { + for (_, c) in self.ops.range(sub.norm_id_start()..sub.norm_id_end()) { + diff -= c; + } + } + for sub in a { + for (_, c) in self.ops.range(sub.norm_id_start()..sub.norm_id_end()) { + diff += c; + } + } + + (InternalDiff::Counter(diff), DiffMode::Linear) + } +} diff --git a/vendor/loro-internal/src/diff_calc/tracker_texts.rs b/vendor/loro-internal/src/diff_calc/tracker_texts.rs new file mode 100644 index 0000000..5aaec63 --- /dev/null +++ b/vendor/loro-internal/src/diff_calc/tracker_texts.rs @@ -0,0 +1,195 @@ +use std::ops::Range; + +use append_only_bytes::BytesSlice; + +use crate::{ + container::richtext::{richtext_state::unicode_to_utf8_index, RichtextChunk}, + utils::string_slice::unicode_range_to_byte_range, +}; + +/// Non-ASCII op text is cut into pieces of at most this many bytes, so that +/// finding a unicode offset inside a piece scans at most this many bytes. +const MAX_PIECE_BYTES: usize = 256; + +/// The text of the ops applied to a rich-text tracker. +/// +/// The tracker's text chunks are unicode ranges in this table, which holds the +/// ops' own [`BytesSlice`]s. Ops decoded from a change block keep their text in +/// a buffer owned by that decode, not in the doc's string arena, so the tracker +/// cannot address them by arena position. The table is reset with its tracker. +/// See `context/text-arena-growth.md`. +#[derive(Debug, Default)] +pub(super) struct TrackerTexts { + /// `(unicode start, text)`, sorted by start. A piece ends where the next + /// one starts, the last one at `len`. + pieces: Vec<(u32, BytesSlice)>, + len: u32, +} + +impl TrackerTexts { + pub fn clear(&mut self) { + self.pieces.clear(); + self.len = 0; + } + + #[cfg(test)] + pub fn len(&self) -> usize { + self.len as usize + } + + /// Records the chars of `text` (`unicode_len` of them) after the first + /// `skip`, and returns their range. + pub fn push_from(&mut self, text: &BytesSlice, unicode_len: u32, skip: usize) -> Range<u32> { + if skip == 0 { + return self.push(text, unicode_len); + } + + let byte = if text.len() == unicode_len as usize { + skip + } else { + unicode_to_utf8_index(as_str(text), skip).expect("skip is within the op text") + }; + self.push(&text.slice_clone(byte..), unicode_len - skip as u32) + } + + /// Records the `unicode_len` chars of `text` and returns their range. + pub fn push(&mut self, text: &BytesSlice, unicode_len: u32) -> Range<u32> { + let start = self.len; + let end = start + .checked_add(unicode_len) + .filter(|&end| end < RichtextChunk::MOVE_ANCHOR) + .expect("rich-text tracker text exceeds the u32 index space"); + if unicode_len == 0 { + return start..end; + } + + if text.len() == unicode_len as usize || text.len() <= MAX_PIECE_BYTES { + self.pieces.push((start, text.clone())); + } else { + let s = as_str(text); + let mut piece_byte = 0; + let mut piece_unicode = start; + let mut unicode = start; + for (byte, _) in s.char_indices() { + if byte - piece_byte >= MAX_PIECE_BYTES { + self.pieces + .push((piece_unicode, text.slice_clone(piece_byte..byte))); + piece_byte = byte; + piece_unicode = unicode; + } + unicode += 1; + } + assert_eq!(unicode, end, "op unicode_len does not match its text"); + self.pieces + .push((piece_unicode, text.slice_clone(piece_byte..))); + } + + self.len = end; + start..end + } + + /// Calls `f(offset, text)` for the text in `range`, in order. `offset` is + /// the unicode offset of `text` from `range.start`. Neighboring pieces of + /// one buffer are passed as one slice. + pub fn for_each_slice(&self, range: Range<u32>, mut f: impl FnMut(usize, BytesSlice)) { + assert!(range.end <= self.len, "{range:?} is out of {}", self.len); + if range.start >= range.end { + return; + } + + let mut i = self + .pieces + .partition_point(|(start, _)| *start <= range.start) + - 1; + let mut pending: Option<(usize, BytesSlice)> = None; + let mut cur = range.start; + while cur < range.end { + let (piece_start, piece) = &self.pieces[i]; + let piece_end = self.pieces.get(i + 1).map_or(self.len, |(start, _)| *start); + let piece_len = (piece_end - piece_start) as usize; + let from = (cur - piece_start) as usize; + let to = (range.end.min(piece_end) - piece_start) as usize; + let slice = if from == 0 && to == piece_len { + piece.clone() + } else if piece.len() == piece_len { + piece.slice_clone(from..to) + } else { + let (from, to) = unicode_range_to_byte_range(as_str(piece), from, to); + piece.slice_clone(from..to) + }; + + let offset = (cur - range.start) as usize; + match &mut pending { + Some((_, prev)) if prev.can_merge(&slice) => prev.try_merge(&slice).unwrap(), + _ => { + if let Some((offset, prev)) = pending.replace((offset, slice)) { + f(offset, prev); + } + } + } + + cur = piece_start + to as u32; + i += 1; + } + + if let Some((offset, prev)) = pending { + f(offset, prev); + } + } +} + +fn as_str(text: &BytesSlice) -> &str { + // SAFETY: text op content is valid UTF-8; it was decoded or created as `str` + unsafe { std::str::from_utf8_unchecked(text) } +} + +#[cfg(test)] +mod test { + use super::*; + + fn collect(texts: &TrackerTexts, range: Range<u32>) -> Vec<(usize, String)> { + let mut ans = Vec::new(); + texts.for_each_slice(range, |offset, s| { + ans.push((offset, as_str(&s).to_string())); + }); + ans + } + + #[test] + fn slices_across_ops_and_pieces() { + let mut texts = TrackerTexts::default(); + let a = BytesSlice::from_bytes("hello".as_bytes()); + let long = "文字".repeat(300); + let b = BytesSlice::from_bytes(long.as_bytes()); + assert_eq!(texts.push(&a, 5), 0..5); + assert_eq!(texts.push(&b, 600), 5..605); + assert!(texts.pieces.len() > 2); + + let all = collect(&texts, 0..605); + assert_eq!(all.len(), 2, "pieces of one buffer are passed merged"); + assert_eq!(all[0], (0, "hello".to_string())); + assert_eq!(all[1], (5, long.clone())); + + let expected: String = long.chars().skip(95).take(300).collect(); + assert_eq!(collect(&texts, 100..400), vec![(0, expected)]); + assert_eq!( + collect(&texts, 3..7), + vec![(0, "lo".to_string()), (2, "文字".to_string())] + ); + assert!(collect(&texts, 4..4).is_empty()); + } + + #[test] + fn push_from_records_only_the_suffix() { + let mut texts = TrackerTexts::default(); + let ascii = BytesSlice::from_bytes("abcd".as_bytes()); + assert_eq!(texts.push_from(&ascii, 4, 1), 0..3); + let wide = BytesSlice::from_bytes("文字😀x".as_bytes()); + assert_eq!(texts.push_from(&wide, 4, 2), 3..5); + assert_eq!( + collect(&texts, 0..5), + vec![(0, "bcd".to_string()), (3, "😀x".to_string())] + ); + assert_eq!(texts.push_from(&ascii, 4, 0), 5..9); + } +} diff --git a/vendor/loro-internal/src/diff_calc/tracker_values.rs b/vendor/loro-internal/src/diff_calc/tracker_values.rs new file mode 100644 index 0000000..5a895ad --- /dev/null +++ b/vendor/loro-internal/src/diff_calc/tracker_values.rs @@ -0,0 +1,128 @@ +use std::{cell::Cell, ops::Range}; + +use rle::Sliceable; + +use crate::{container::richtext::RichtextChunk, op::ValueSlice}; + +/// The values of the insert ops applied to a list tracker. +/// +/// The tracker's chunks are ranges in this table, which holds the ops' own +/// [`ValueSlice`]s, the way [`super::tracker_texts::TrackerTexts`] holds text. +/// The table is reset with its tracker. See `context/text-arena-growth.md`. +#[derive(Debug, Default)] +pub(super) struct TrackerValues { + /// Where each entry of `slices` starts, sorted. An entry ends where the + /// next one starts, the last one at `len`. Kept apart from `slices` so the + /// binary search reads a dense array. + starts: Vec<u32>, + slices: Vec<ValueSlice>, + len: u32, + /// The entry the last lookup ended in; a diff often reads nearby entries. + hint: Cell<usize>, +} + +impl TrackerValues { + pub fn clear(&mut self) { + self.starts.clear(); + self.slices.clear(); + self.len = 0; + self.hint.set(0); + } + + /// Records `values` and returns their range. + pub fn push(&mut self, values: ValueSlice) -> Range<u32> { + let start = self.len; + let end = u32::try_from(values.len()) + .ok() + .and_then(|len| start.checked_add(len)) + .filter(|&end| end < RichtextChunk::MOVE_ANCHOR) + .expect("list tracker values exceed the u32 index space"); + if start < end { + if !self + .slices + .last_mut() + .is_some_and(|last| last.extend_if_adjacent(&values)) + { + self.starts.push(start); + self.slices.push(values); + } + self.len = end; + } + start..end + } + + #[cfg(test)] + pub fn len(&self) -> usize { + self.len as usize + } + + fn entry_end(&self, i: usize) -> u32 { + self.starts.get(i + 1).copied().unwrap_or(self.len) + } + + /// The entry that holds `pos`. + fn find(&self, pos: u32) -> usize { + let hint = self.hint.get(); + for i in [hint, hint + 1] { + if i < self.starts.len() && self.starts[i] <= pos && pos < self.entry_end(i) { + return i; + } + } + self.starts.partition_point(|start| *start <= pos) - 1 + } + + /// Calls `f(offset, values)` for the values in `range`, in order. `offset` + /// is the offset of `values` from `range.start`. + pub fn for_each_slice(&self, range: Range<u32>, mut f: impl FnMut(usize, ValueSlice)) { + assert!(range.end <= self.len, "{range:?} is out of {}", self.len); + if range.start >= range.end { + return; + } + + let mut i = self.find(range.start); + let mut cur = range.start; + loop { + let start = self.starts[i]; + let values = &self.slices[i]; + let from = (cur - start) as usize; + let to = (range.end.min(self.entry_end(i)) - start) as usize; + let slice = if from == 0 && to == values.len() { + values.clone() + } else { + values.slice(from, to) + }; + f((cur - range.start) as usize, slice); + cur = start + to as u32; + if cur >= range.end { + break; + } + i += 1; + } + self.hint.set(i); + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::LoroValue; + + #[test] + fn slices_across_ops() { + let mut values = TrackerValues::default(); + let a = ValueSlice::new(vec![LoroValue::I64(1), LoroValue::I64(2)]); + let b = ValueSlice::new((3..8).map(LoroValue::I64).collect()); + assert_eq!(values.push(a), 0..2); + assert_eq!(values.push(b), 2..7); + + let mut got = Vec::new(); + values.for_each_slice(1..5, |offset, s| got.push((offset, s.as_slice().to_vec()))); + assert_eq!( + got, + vec![ + (0, vec![LoroValue::I64(2)]), + (1, (3..6).map(LoroValue::I64).collect()) + ] + ); + } +} diff --git a/vendor/loro-internal/src/diff_calc/tree.rs b/vendor/loro-internal/src/diff_calc/tree.rs new file mode 100644 index 0000000..7543e5b --- /dev/null +++ b/vendor/loro-internal/src/diff_calc/tree.rs @@ -0,0 +1,725 @@ +use std::{collections::BTreeSet, ops::RangeInclusive, sync::Arc}; + +use fractional_index::FractionalIndex; +use loro_common::{ContainerID, IdFull, IdLp, Lamport, PeerID, TreeID, ID}; +use rustc_hash::FxHashMap; + +use crate::{ + container::{idx::ContainerIdx, tree::tree_op::TreeOp}, + delta::{TreeDelta, TreeDeltaItem, TreeInternalDiff}, + event::InternalDiff, + state::TreeParentId, + version::Frontiers, + OpLog, VersionVector, +}; + +use super::{DiffCalcVersionInfo, DiffCalculatorTrait, DiffMode}; + +#[derive(Debug)] +pub(crate) struct TreeDiffCalculator { + container: ContainerIdx, + mode: TreeDiffCalculatorMode, +} + +#[derive(Debug)] +enum TreeDiffCalculatorMode { + Crdt, + Linear(TreeDelta), + ImportGreaterUpdates(TreeDelta), +} + +impl DiffCalculatorTrait for TreeDiffCalculator { + fn start_tracking(&mut self, _oplog: &OpLog, _vv: &crate::VersionVector, mode: DiffMode) { + match mode { + DiffMode::Checkout => { + self.mode = TreeDiffCalculatorMode::Crdt; + } + DiffMode::Import => { + self.mode = TreeDiffCalculatorMode::Crdt; + } + DiffMode::ImportGreaterUpdates => { + self.mode = TreeDiffCalculatorMode::ImportGreaterUpdates(TreeDelta::default()); + } + DiffMode::Linear => { + self.mode = TreeDiffCalculatorMode::Linear(TreeDelta::default()); + } + } + } + + fn apply_change( + &mut self, + _oplog: &OpLog, + op: crate::op::RichOp, + _vv: Option<&crate::VersionVector>, + ) { + match &mut self.mode { + TreeDiffCalculatorMode::Crdt => {} + TreeDiffCalculatorMode::Linear(ref mut delta) + | TreeDiffCalculatorMode::ImportGreaterUpdates(ref mut delta) => { + let id_full = op.id_full(); + let op = op.op(); + let content = op.content.as_tree().unwrap(); + + let item: TreeDeltaItem = match &**content { + crate::container::tree::tree_op::TreeOp::Create { + target, + parent, + position, + } => TreeDeltaItem { + target: *target, + action: TreeInternalDiff::Create { + parent: (*parent).into(), + position: position.clone(), + }, + last_effective_move_op_id: id_full, + }, + crate::container::tree::tree_op::TreeOp::Move { + target, + parent, + position, + } => TreeDeltaItem { + target: *target, + action: TreeInternalDiff::Move { + parent: (*parent).into(), + position: position.clone(), + }, + last_effective_move_op_id: id_full, + }, + crate::container::tree::tree_op::TreeOp::Delete { target } => TreeDeltaItem { + target: *target, + action: TreeInternalDiff::Delete { + parent: TreeParentId::Deleted, + position: None, + }, + last_effective_move_op_id: id_full, + }, + }; + + delta.diff.push(item); + } + } + } + + fn finish_this_round(&mut self) { + self.mode = TreeDiffCalculatorMode::Crdt; + } + + fn calculate_diff( + &mut self, + _idx: ContainerIdx, + oplog: &OpLog, + info: DiffCalcVersionInfo, + mut on_new_container: impl FnMut(&ContainerID), + ) -> (InternalDiff, DiffMode) { + match &mut self.mode { + TreeDiffCalculatorMode::Crdt => { + let diff = self.diff(oplog, info); + diff.diff.iter().for_each(|d| { + // the metadata could be modified before, so (re)create a node need emit the map container diffs + // `Create` here is because maybe in a diff calc uncreate and then create back + if matches!(d.action, TreeInternalDiff::Create { .. }) { + on_new_container(&d.target.associated_meta_container()) + } + }); + + (InternalDiff::Tree(diff), DiffMode::Checkout) + } + TreeDiffCalculatorMode::Linear(ans) => { + (InternalDiff::Tree(std::mem::take(ans)), DiffMode::Linear) + } + TreeDiffCalculatorMode::ImportGreaterUpdates(ans) => { + let mut ans = std::mem::take(ans); + ans.diff.sort_unstable_by(|a, b| { + a.last_effective_move_op_id + .lamport + .cmp(&b.last_effective_move_op_id.lamport) + .then_with(|| { + a.last_effective_move_op_id + .peer + .cmp(&b.last_effective_move_op_id.peer) + }) + }); + (InternalDiff::Tree(ans), DiffMode::ImportGreaterUpdates) + } + } + } +} + +impl TreeDiffCalculator { + pub(crate) fn new(container: ContainerIdx) -> Self { + Self { + container, + mode: TreeDiffCalculatorMode::Crdt, + } + } + + fn diff(&mut self, oplog: &OpLog, info: DiffCalcVersionInfo) -> TreeDelta { + self.checkout(info.from_vv, info.from_frontiers, oplog); + self.checkout_diff(info, oplog) + } + + /// Moves the diff cache to `to` without recording diffs. + fn checkout(&mut self, to: &VersionVector, to_frontiers: &Frontiers, oplog: &OpLog) { + oplog.with_history_cache(|h| { + let mark = h.ensure_importing_caches_exist(); + let tree_ops = h.get_tree(&self.container, mark).unwrap(); + let mut tree_cache = tree_ops.tree().lock(); + tree_cache.init_current_vv(oplog); + let s = format!("checkout current {:?} to {:?}", &tree_cache.current_vv, &to); + let s = tracing::span!(tracing::Level::INFO, "checkout", s = s); + let _e = s.enter(); + if to == &tree_cache.current_vv { + return; + } + let Some(min_lamport) = min_lamport_of_version_diff(&tree_cache.current_vv, to, oplog) + else { + tree_cache.current_vv = to.clone(); + return; + }; + + let ops = tree_ops.ops(); + let retreat = tree_cache.retreat_range(min_lamport); + for (idlp, op) in retreat.map(|r| ops.range(r)).into_iter().flatten() { + tree_cache.take(IdFull::new(idlp.peer, op.counter, idlp.lamport), &op.value); + } + tree_cache.retreated_from(min_lamport); + + let max_lamport = self + .get_max_lamport_by_frontiers(to_frontiers, oplog) + .max(min_lamport); + for (idlp, op) in + ops.range(IdLp::new(0, min_lamport)..=IdLp::new(PeerID::MAX, max_lamport)) + { + if to.includes_id(ID::new(idlp.peer, op.counter)) { + tree_cache.apply(MoveLamportAndID { + id: IdFull::new(idlp.peer, op.counter, idlp.lamport), + op: op.value.clone(), + effected: false, + }); + } + } + tree_cache.current_vv = to.clone(); + }); + } + + fn checkout_diff(&mut self, info: DiffCalcVersionInfo, oplog: &OpLog) -> TreeDelta { + oplog.with_history_cache(|h| { + let mark = h.ensure_importing_caches_exist(); + let tree_ops = h.get_tree(&self.container, mark).unwrap(); + let mut tree_cache = tree_ops.tree().lock(); + debug_assert_eq!(&tree_cache.current_vv, info.from_vv); + let mut parent_to_children_cache = + TreeParentToChildrenCache::init_from_tree_cache(&tree_cache); + let s = tracing::span!(tracing::Level::INFO, "checkout_diff"); + let _e = s.enter(); + // CORRECTNESS: `effected` (the cycle check) of each cached op + // depends on every op ordered before it, so the cache must always + // hold ops applied in (lamport, peer) order. Ops below + // `min_lamport` are the same in `from` and `to`; everything at or + // above it is retreated from `from` and replayed for `to` in that + // order. The window is taken from the versions themselves, not + // from a replay base: in `Checkout` mode `find_replay_base` may + // return a meet that is not a critical version, and ops concurrent + // with that meet can have lower lamports than it. See + // `context/tree-checkout-window.md`. + let Some(min_lamport) = min_lamport_of_version_diff(info.from_vv, info.to_vv, oplog) + else { + tree_cache.current_vv = info.to_vv.clone(); + return TreeDelta::default(); + }; + // `max` keeps the forward range well-formed when `to` only drops ops. + let to_max_lamport = self + .get_max_lamport_by_frontiers(info.to_frontiers, oplog) + .max(min_lamport); + let ops = tree_ops.ops(); + + let mut diffs = vec![]; + // retreat, newest first + let retreat = tree_cache.retreat_range(min_lamport); + for (idlp, op) in retreat.map(|r| ops.range(r)).into_iter().flatten().rev() { + let Some(op) = + tree_cache.take(IdFull::new(idlp.peer, op.counter, idlp.lamport), &op.value) + else { + continue; + }; + if !op.effected { + continue; + } + let (old_parent, position, last_effective_move_op_id) = + tree_cache.get_parent_with_id(op.op.target()); + // we need to know whether old_parent is deleted + let is_parent_deleted = tree_cache.is_parent_deleted(op.op.parent_id()); + let is_old_parent_deleted = tree_cache.is_parent_deleted(old_parent); + if op.op.target().id() == op.id.id() { + assert_eq!( + old_parent, + TreeParentId::Unexist, + "old_parent = {:?} instead", + &old_parent + ); + } + parent_to_children_cache.record_change( + op.op.target(), + op.op.parent_id(), + old_parent, + ); + let this_diff = TreeDeltaItem::new( + op.op.target(), + old_parent, + op.op.parent_id(), + last_effective_move_op_id, + is_old_parent_deleted, + is_parent_deleted, + position, + ); + let is_create = matches!(this_diff.action, TreeInternalDiff::Create { .. }); + diffs.push(this_diff); + if is_create { + tree_cache.push_children_creation( + op.op.target(), + &parent_to_children_cache, + &mut diffs, + ); + } + } + + tree_cache.retreated_from(min_lamport); + + // forward, oldest first + for (idlp, op) in + ops.range(IdLp::new(0, min_lamport)..=IdLp::new(PeerID::MAX, to_max_lamport)) + { + let id = ID::new(idlp.peer, op.counter); + if !info.to_vv.includes_id(id) { + continue; + } + let op = MoveLamportAndID { + id: IdFull { + peer: id.peer, + lamport: idlp.lamport, + counter: id.counter, + }, + op: op.value.clone(), + effected: false, + }; + let (old_parent, _position, _id) = tree_cache.get_parent_with_id(op.op.target()); + let is_parent_deleted = tree_cache.is_parent_deleted(op.op.parent_id()); + let is_old_parent_deleted = tree_cache.is_parent_deleted(old_parent); + let effected = tree_cache.apply(op.clone()); + if effected { + let this_diff = TreeDeltaItem::new( + op.op.target(), + op.op.parent_id(), + old_parent, + op.id_full(), + is_parent_deleted, + is_old_parent_deleted, + op.op.fractional_index(), + ); + parent_to_children_cache.record_change( + op.op.target(), + old_parent, + op.op.parent_id(), + ); + let is_create = matches!(this_diff.action, TreeInternalDiff::Create { .. }); + diffs.push(this_diff); + if is_create { + tree_cache.push_children_creation( + op.op.target(), + &parent_to_children_cache, + &mut diffs, + ); + } + } + } + + tree_cache.current_vv = info.to_vv.clone(); + TreeDelta { diff: diffs } + }) + } + + fn get_max_lamport_by_frontiers(&self, frontiers: &Frontiers, oplog: &OpLog) -> Lamport { + frontiers + .iter() + .map(|id| oplog.get_max_lamport_at(id)) + .max() + .unwrap_or(Lamport::MAX) + } +} + +/// The smallest lamport among the ops that are in exactly one of `a` and `b`, +/// or `None` when both contain the same ops. +/// +/// Every tree op below it is in both versions, so moving the diff cache +/// between them only has to retreat and replay the ops at or above it. +fn min_lamport_of_version_diff( + a: &VersionVector, + b: &VersionVector, + oplog: &OpLog, +) -> Option<Lamport> { + a.sub_iter(b) + .chain(b.sub_iter(a)) + .map(|span| { + let id = ID::new(span.peer, span.counter.start); + oplog + .dag + .get_lamport(&id) + .unwrap_or_else(|| panic!("op {id} of a tree diff version is not in the DAG")) + }) + .min() +} + +/// All information of an operation for diff calculating of movable tree. +#[derive(Debug, Clone)] +pub struct MoveLamportAndID { + pub(crate) id: IdFull, + pub(crate) op: Arc<TreeOp>, + /// Whether this action is applied in the current version. + /// If this action will cause a circular reference, then this action will not be applied. + pub(crate) effected: bool, +} + +impl MoveLamportAndID { + fn id_full(&self) -> IdFull { + self.id + } +} + +impl PartialEq for MoveLamportAndID { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + } +} + +impl Eq for MoveLamportAndID {} + +impl PartialOrd for MoveLamportAndID { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for MoveLamportAndID { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.id + .lamport + .cmp(&other.id.lamport) + .then_with(|| self.id.peer.cmp(&other.id.peer)) + } +} + +#[derive(Clone, Default)] +pub(crate) struct TreeCacheForDiff { + tree: FxHashMap<TreeID, BTreeSet<MoveLamportAndID>>, + current_vv: VersionVector, + /// `false` until the first transition. In a shallow doc the cache starts + /// at the shallow root (seeded with its state, or empty when the tree had + /// no nodes there), which `current_vv` does not express yet. + current_vv_initialized: bool, + /// No cached op has a greater lamport. Bounds the retreat so it does not + /// walk the ops above the cached version, which can be most of the + /// history when checking out between two old versions. + max_lamport: Lamport, +} + +impl std::fmt::Debug for TreeCacheForDiff { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + writeln!(f, "TreeCacheForDiff {{ tree: ")?; + for (id, ops) in self.tree.iter() { + writeln!(f, " {} -> {:?}", id, ops)?; + } + writeln!(f, " current_vv: {:?}", self.current_vv)?; + Ok(()) + } +} + +impl TreeCacheForDiff { + /// Removes the op from the cache if it is there, returning it with its + /// `effected` flag. + fn take(&mut self, id: IdFull, op: &Arc<TreeOp>) -> Option<MoveLamportAndID> { + self.tree.get_mut(&op.target())?.take(&MoveLamportAndID { + id, + op: op.clone(), + effected: false, + }) + } + + /// The `IdLp` range holding every cached op whose lamport is at least + /// `min_lamport`, or `None` when there is none. + fn retreat_range(&self, min_lamport: Lamport) -> Option<RangeInclusive<IdLp>> { + (self.max_lamport >= min_lamport) + .then(|| IdLp::new(0, min_lamport)..=IdLp::new(PeerID::MAX, self.max_lamport)) + } + + /// Records that every cached op whose lamport is at least `min_lamport` + /// has been retreated. + fn retreated_from(&mut self, min_lamport: Lamport) { + self.max_lamport = self.max_lamport.min(min_lamport.saturating_sub(1)); + } + + fn init_current_vv(&mut self, oplog: &OpLog) { + if self.current_vv_initialized { + return; + } + + self.current_vv_initialized = true; + if oplog.is_shallow() { + self.current_vv = oplog + .dag + .frontiers_to_vv(oplog.dag.shallow_since_frontiers()) + .expect("the shallow root version must be in the DAG"); + } + } + + /// After `target` is (re)created, pushes a `Create` for each node of its + /// current subtree. + fn push_children_creation( + &self, + target: TreeID, + cache: &TreeParentToChildrenCache, + diffs: &mut Vec<TreeDeltaItem>, + ) { + let mut s = vec![target]; + while let Some(t) = s.pop() { + let children = self.get_children_with_id(TreeParentId::Node(t), cache); + diffs.extend(children.iter().map(|c| TreeDeltaItem { + target: c.0, + action: TreeInternalDiff::Create { + parent: TreeParentId::Node(t), + position: c.1.clone().unwrap(), + }, + last_effective_move_op_id: c.2, + })); + s.extend(children.iter().map(|c| c.0)); + } + } + + fn is_ancestor_of(&self, maybe_ancestor: &TreeID, node_id: &TreeParentId) -> bool { + if !self.tree.contains_key(maybe_ancestor) { + return false; + } + if let TreeParentId::Node(id) = node_id { + if id == maybe_ancestor { + return true; + } + } + match node_id { + TreeParentId::Node(id) => { + let (parent, _, _) = &self.get_parent_with_id(*id); + if parent == node_id { + panic!("is_ancestor_of loop") + } + self.is_ancestor_of(maybe_ancestor, parent) + } + TreeParentId::Deleted | TreeParentId::Root => false, + TreeParentId::Unexist => false, + } + } + + fn apply(&mut self, mut node: MoveLamportAndID) -> bool { + let mut effected = true; + if self.is_ancestor_of(&node.op.target(), &node.op.parent_id()) { + effected = false; + } + node.effected = effected; + self.max_lamport = self.max_lamport.max(node.id.lamport); + self.current_vv.set_last(node.id.id()); + self.tree.entry(node.op.target()).or_default().insert(node); + effected + } + + pub(crate) fn init_tree_with_shallow_root_version(&mut self, nodes: Vec<MoveLamportAndID>) { + if nodes.is_empty() { + return; + } + + debug_assert!(self.tree.is_empty()); + for node in nodes.into_iter() { + self.max_lamport = self.max_lamport.max(node.id.lamport); + self.current_vv.extend_to_include_last_id(node.id.id()); + self.current_vv + .extend_to_include_last_id(node.op.target().id()); + self.tree.entry(node.op.target()).or_default().insert(node); + } + } + + fn is_parent_deleted(&self, parent: TreeParentId) -> bool { + match parent { + TreeParentId::Deleted => true, + TreeParentId::Node(id) => self.is_parent_deleted(self.get_parent_with_id(id).0), + TreeParentId::Root => false, + TreeParentId::Unexist => false, + } + } + + /// get the parent of the first effected op and its id + fn get_parent_with_id( + &self, + tree_id: TreeID, + ) -> (TreeParentId, Option<FractionalIndex>, IdFull) { + let mut ans = (TreeParentId::Unexist, None, IdFull::NONE_ID); + if let Some(cache) = self.tree.get(&tree_id) { + for op in cache.iter().rev() { + if op.effected { + ans = ( + op.op.parent_id(), + op.op.fractional_index().clone(), + op.id_full(), + ); + break; + } + } + } + ans + } + + /// get the parent of the last effected op + fn get_last_effective_move(&self, tree_id: TreeID) -> Option<&MoveLamportAndID> { + if TreeID::is_deleted_root(&tree_id) { + return None; + } + + let mut ans = None; + if let Some(set) = self.tree.get(&tree_id) { + for op in set.iter().rev() { + if op.effected { + ans = Some(op); + break; + } + } + } + + ans + } + + fn get_children_with_id( + &self, + parent: TreeParentId, + cache: &TreeParentToChildrenCache, + ) -> Vec<(TreeID, Option<FractionalIndex>, IdFull)> { + let Some(children_ids) = cache.get_children(parent) else { + return vec![]; + }; + let mut ans = Vec::with_capacity(children_ids.len()); + for child in children_ids.iter() { + let Some(op) = self.get_last_effective_move(*child) else { + panic!("child {:?} has no last effective move", child); + }; + + assert_eq!(op.op.parent_id(), parent); + ans.push((*child, op.op.fractional_index().clone(), op.id_full())); + } + // The children should be sorted by the position. + // If the fractional index is the same, then sort by the lamport and peer. + ans.sort_by(|a, b| { + a.1.cmp(&b.1) + .then(a.2.lamport.cmp(&b.2.lamport).then(a.2.peer.cmp(&b.2.peer))) + }); + ans + } +} + +#[derive(Debug)] +struct TreeParentToChildrenCache { + cache: FxHashMap<TreeParentId, BTreeSet<TreeID>>, +} + +impl TreeParentToChildrenCache { + fn get_children(&self, parent: TreeParentId) -> Option<&BTreeSet<TreeID>> { + self.cache.get(&parent) + } + + fn init_from_tree_cache(tree_cache: &TreeCacheForDiff) -> Self { + let mut cache = Self { + cache: FxHashMap::default(), + }; + for (tree_id, _) in tree_cache.tree.iter() { + let Some(op) = tree_cache.get_last_effective_move(*tree_id) else { + continue; + }; + + cache + .cache + .entry(op.op.parent_id()) + .or_default() + .insert(op.op.target()); + } + cache + } + + fn record_change( + &mut self, + target: TreeID, + old_parent: TreeParentId, + new_parent: TreeParentId, + ) { + if !old_parent.is_unexist() { + let removed = if let Some(children) = self.cache.get_mut(&old_parent) { + children.remove(&target) + } else { + false + }; + + if !removed { + let removed = self + .cache + .values_mut() + .any(|children| children.remove(&target)); + assert!( + removed, + "target {target:?} should be present in TreeParentToChildrenCache before moving from {old_parent:?} to {new_parent:?}", + ); + } + } + self.cache.entry(new_parent).or_default().insert(target); + } +} + +#[cfg(test)] +mod test { + use loro_common::{TreeID, ID}; + + use crate::{state::TreeParentId, version::Frontiers, HandlerTrait, LoroDoc}; + + /// Checking out between two old versions must retreat only what the cache + /// holds: `max_lamport` bounds every cached op, and stays at the cached + /// version instead of the end of the history. + #[test] + fn retreat_bound_follows_the_cached_version() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let tree = doc.get_tree("tree"); + let nodes: Vec<TreeID> = (0..20) + .map(|_| tree.create(TreeParentId::Root).unwrap()) + .collect(); + doc.commit_then_renew(); + let mut versions = vec![]; + for i in 0..400 { + let _ = tree.mov(nodes[i % 20], TreeParentId::Node(nodes[(i * 7 + 3) % 20])); + doc.commit_then_renew(); + versions.push(doc.oplog_frontiers()); + } + + let (v1, v2) = (&versions[10], &versions[20]); + let lamport_of = |f: &Frontiers| { + let id: ID = f.as_single().unwrap(); + doc.oplog().lock().dag.get_lamport(&id).unwrap() + }; + for v in [v1, v2, v1, v2] { + doc.checkout(v).unwrap(); + let (cached_max, bound) = doc.oplog().lock().with_history_cache(|h| { + let mark = h.ensure_importing_caches_exist(); + let cache = h.get_tree(&tree.idx(), mark).unwrap().tree().lock(); + let cached_max = cache + .tree + .values() + .flat_map(|ops| ops.iter().map(|op| op.id.lamport)) + .max() + .unwrap(); + (cached_max, cache.max_lamport) + }); + assert!(cached_max <= bound); + assert!(bound <= lamport_of(v)); + } + } +} diff --git a/vendor/loro-internal/src/diff_calc/unknown.rs b/vendor/loro-internal/src/diff_calc/unknown.rs new file mode 100644 index 0000000..25a6fbf --- /dev/null +++ b/vendor/loro-internal/src/diff_calc/unknown.rs @@ -0,0 +1,32 @@ +use loro_common::ContainerID; + +use crate::{container::idx::ContainerIdx, event::InternalDiff, OpLog}; + +use super::{DiffCalcVersionInfo, DiffCalculatorTrait, DiffMode}; + +#[derive(Debug, Default)] +pub struct UnknownDiffCalculator; + +impl DiffCalculatorTrait for UnknownDiffCalculator { + fn start_tracking(&mut self, _oplog: &OpLog, _vv: &crate::VersionVector, _mode: DiffMode) {} + + fn apply_change( + &mut self, + _oplog: &OpLog, + _op: crate::op::RichOp, + _vv: Option<&crate::VersionVector>, + ) { + } + + fn finish_this_round(&mut self) {} + + fn calculate_diff( + &mut self, + _idx: ContainerIdx, + _oplog: &OpLog, + _info: DiffCalcVersionInfo, + _on_new_container: impl FnMut(&ContainerID), + ) -> (InternalDiff, DiffMode) { + (InternalDiff::Unknown, DiffMode::Checkout) + } +} diff --git a/vendor/loro-internal/src/encoding.rs b/vendor/loro-internal/src/encoding.rs new file mode 100644 index 0000000..9495e3d --- /dev/null +++ b/vendor/loro-internal/src/encoding.rs @@ -0,0 +1,658 @@ +pub(crate) mod arena; +pub(crate) mod fast_snapshot; +pub(crate) mod json_schema; +mod outdated_encode_reordered; +mod shallow_snapshot; +pub(crate) mod value; +pub(crate) mod value_register; +pub(crate) use outdated_encode_reordered::{ + decode_op, encode_op, get_op_prop, DecodedBlockBuffers, EncodedDeleteStartId, + IterableEncodedDeleteStartId, +}; +use outdated_encode_reordered::{import_changes_to_oplog, ImportChangesResult}; +pub(crate) use value::OwnedValue; + +use crate::change::Change; +use crate::oplog::ImportedValues; +use crate::version::{Frontiers, VersionRange}; +use crate::LoroDoc; +use crate::{oplog::OpLog, LoroError, VersionVector}; +use loro_common::{IdSpan, InternalString, LoroEncodeError, LoroResult, ID}; +use num_traits::{FromPrimitive, ToPrimitive}; +use std::borrow::Cow; + +/// The mode of the export. +/// +/// Loro CRDT internally consists of two parts: document history and current document state. +/// The export modes offer various options to meet different requirements. +/// These modes do not include remote changes waiting for missing dependencies. +/// Persist those separately with [`LoroDoc::export_pending_updates`]. +/// +/// - CRDT property: Documents maintain consistent states when they receive the same set of updates. +/// - In real-time collaboration, peers typically only need to synchronize updates +/// (operations/history) to achieve consistency. +/// +/// ## Update Export +/// +/// - Exports only the history part, containing multiple operations. +/// - Suitable for real-time collaboration scenarios where peers only need to synchronize updates. +/// +/// ## Snapshot Export +/// +/// ### Default Snapshot +/// +/// - Includes complete history and current full state. +/// +/// ### Shallow Snapshot +/// +/// - Contains the complete current state. +/// - Retains partial history starting from a specified version. +/// +/// ### State-only Snapshot +/// +/// - Exports the state of the target version. +/// - Includes a minimal set of operation history. +#[non_exhaustive] +#[derive(Debug, Clone)] +pub enum ExportMode<'a> { + /// It contains the full history and the current state of the document. + Snapshot, + /// It contains the history since the `from` version vector. + Updates { from: Cow<'a, VersionVector> }, + /// This mode exports the history in the specified range. + UpdatesInRange { spans: Cow<'a, [IdSpan]> }, + /// The shallow snapshot only contains the history since the target frontiers + ShallowSnapshot(Cow<'a, Frontiers>), + /// The state only snapshot exports the state of the target version + /// with a minimal set of history (a few ops). + /// + /// It's a shallow snapshot with depth=1 at the target version. + /// If the target version is None, it will use the latest version as the target version. + StateOnly(Option<Cow<'a, Frontiers>>), + /// The snapshot at the specified frontiers. It contains the full history + /// till the target frontiers and the state at the target frontiers. + SnapshotAt { version: Cow<'a, Frontiers> }, +} + +impl<'a> ExportMode<'a> { + /// It contains the full history and the current state of the document. + pub fn snapshot() -> Self { + ExportMode::Snapshot + } + + /// It contains the history since the `from` version vector. + pub fn updates(from: &'a VersionVector) -> Self { + ExportMode::Updates { + from: Cow::Borrowed(from), + } + } + + /// It contains the history since the `from` version vector. + pub fn updates_owned(from: VersionVector) -> Self { + ExportMode::Updates { + from: Cow::Owned(from), + } + } + + /// It contains all the history of the document. + pub fn all_updates() -> Self { + ExportMode::Updates { + from: Cow::Owned(Default::default()), + } + } + + /// This mode exports the history in the specified range. + pub fn updates_in_range(spans: impl Into<Cow<'a, [IdSpan]>>) -> Self { + ExportMode::UpdatesInRange { + spans: spans.into(), + } + } + + /// The shallow snapshot only contains the history since the target frontiers. + pub fn shallow_snapshot(frontiers: &'a Frontiers) -> Self { + ExportMode::ShallowSnapshot(Cow::Borrowed(frontiers)) + } + + /// The shallow snapshot only contains the history since the target frontiers. + pub fn shallow_snapshot_owned(frontiers: Frontiers) -> Self { + ExportMode::ShallowSnapshot(Cow::Owned(frontiers)) + } + + /// The shallow snapshot only contains the history since the target frontiers. + pub fn shallow_snapshot_since(id: ID) -> Self { + let frontiers = Frontiers::from_id(id); + ExportMode::ShallowSnapshot(Cow::Owned(frontiers)) + } + + /// The state only snapshot exports the state of the target version + /// with a minimal set of history (a few ops). + /// + /// It's a shallow snapshot with depth=1 at the target version. + /// If the target version is None, it will use the latest version as the target version. + pub fn state_only(frontiers: Option<&'a Frontiers>) -> Self { + ExportMode::StateOnly(frontiers.map(Cow::Borrowed)) + } + + /// The snapshot at the specified frontiers. It contains the full history + /// till the target frontiers and the state at the target frontiers. + pub fn snapshot_at(frontiers: &'a Frontiers) -> Self { + ExportMode::SnapshotAt { + version: Cow::Borrowed(frontiers), + } + } + + /// This mode exports the history within the specified version vector. + pub fn updates_till(vv: &VersionVector) -> ExportMode<'static> { + let mut spans = Vec::with_capacity(vv.len()); + for (peer, counter) in vv.iter() { + if *counter > 0 { + spans.push(IdSpan::new(*peer, 0, *counter)); + } + } + + ExportMode::UpdatesInRange { + spans: Cow::Owned(spans), + } + } +} + +const MAGIC_BYTES: [u8; 4] = *b"loro"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum EncodeMode { + // This is a config option, it won't be used in encoding. + Auto = 255, + OutdatedRle = 1, + OutdatedSnapshot = 2, + FastSnapshot = 3, + FastUpdates = 4, +} + +impl num_traits::FromPrimitive for EncodeMode { + #[allow(trivial_numeric_casts)] + #[inline] + fn from_i64(n: i64) -> Option<Self> { + match n { + n if n == EncodeMode::Auto as i64 => Some(EncodeMode::Auto), + n if n == EncodeMode::OutdatedRle as i64 => Some(EncodeMode::OutdatedRle), + n if n == EncodeMode::OutdatedSnapshot as i64 => Some(EncodeMode::OutdatedSnapshot), + n if n == EncodeMode::FastSnapshot as i64 => Some(EncodeMode::FastSnapshot), + n if n == EncodeMode::FastUpdates as i64 => Some(EncodeMode::FastUpdates), + _ => None, + } + } + #[inline] + fn from_u64(n: u64) -> Option<Self> { + Self::from_i64(n as i64) + } +} + +impl num_traits::ToPrimitive for EncodeMode { + #[inline] + #[allow(trivial_numeric_casts)] + fn to_i64(&self) -> Option<i64> { + Some(match *self { + EncodeMode::Auto => EncodeMode::Auto as i64, + EncodeMode::OutdatedRle => EncodeMode::OutdatedRle as i64, + EncodeMode::OutdatedSnapshot => EncodeMode::OutdatedSnapshot as i64, + EncodeMode::FastSnapshot => EncodeMode::FastSnapshot as i64, + EncodeMode::FastUpdates => EncodeMode::FastUpdates as i64, + }) + } + #[inline] + fn to_u64(&self) -> Option<u64> { + self.to_i64().map(|x| x as u64) + } +} + +impl EncodeMode { + pub fn to_bytes(self) -> [u8; 2] { + let value = self.to_u16().unwrap(); + value.to_be_bytes() + } + + pub fn is_snapshot(self) -> bool { + matches!( + self, + EncodeMode::OutdatedSnapshot | EncodeMode::FastSnapshot + ) + } +} + +impl TryFrom<[u8; 2]> for EncodeMode { + type Error = LoroError; + + fn try_from(value: [u8; 2]) -> Result<Self, Self::Error> { + let value = u16::from_be_bytes(value); + Self::from_u16(value).ok_or(LoroError::IncompatibleFutureEncodingError(value as usize)) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ImportStatus { + pub success: VersionRange, + pub pending: Option<VersionRange>, +} + +pub(crate) fn decode_oplog( + oplog: &mut OpLog, + parsed: ParsedHeaderAndBody, + values: ImportedValues, +) -> Result<ImportStatus, LoroError> { + let changes = decode_oplog_changes(oplog, parsed, values)?; + // Outdated decoders do not go through `import_changes_and_apply`. Compare + // here so a restored outdated import still honors the caller's mode. + let changes = oplog.check_and_trim_known_part_of_changes(changes, values)?; + let result = apply_decoded_changes_to_oplog(oplog, changes)?; + if result.has_deps_before_shallow_root { + return Err(LoroError::ImportUpdatesThatDependsOnOutdatedVersion); + } + + Ok(result.status) +} + +pub(crate) fn decode_oplog_changes( + oplog: &mut OpLog, + parsed: ParsedHeaderAndBody, + values: ImportedValues, +) -> Result<Vec<Change>, LoroError> { + let ParsedHeaderAndBody { mode, body, .. } = parsed; + match mode { + EncodeMode::OutdatedRle | EncodeMode::OutdatedSnapshot => { + Err(LoroError::ImportUnsupportedEncodingMode) + } + EncodeMode::FastSnapshot => fast_snapshot::decode_oplog(oplog, body, values), + EncodeMode::FastUpdates => fast_snapshot::decode_updates(oplog, body.to_vec().into()), + EncodeMode::Auto => unreachable!(), + } +} + +pub(crate) struct ApplyDecodedChangesResult { + pub status: ImportStatus, + pub has_deps_before_shallow_root: bool, +} + +pub(crate) fn apply_decoded_changes_to_oplog( + oplog: &mut OpLog, + changes: Vec<Change>, +) -> LoroResult<ApplyDecodedChangesResult> { + let ImportChangesResult { + mut imported, + latest_ids, + pending_changes, + changes_that_have_deps_before_shallow_root, + } = import_changes_to_oplog(changes, oplog)?; + + // TODO: PERF: should we use hashmap to filter latest_ids with the same peer first? + oplog.try_apply_pending(latest_ids, Some(&mut imported)); + // Applying previously parked pending ops can unlock deps of `pending_changes`. + // Those are applied here (and counted in `imported`); only still-blocked ones + // remain in the returned pending range. + let pending = + oplog.import_unknown_lamport_pending_changes(pending_changes, Some(&mut imported)); + Ok(ApplyDecodedChangesResult { + status: ImportStatus { + success: imported, + pending: (!pending.is_empty()).then_some(pending), + }, + has_deps_before_shallow_root: !changes_that_have_deps_before_shallow_root.is_empty(), + }) +} + +pub(crate) struct ParsedHeaderAndBody<'a> { + pub checksum: [u8; 16], + pub checksum_body: &'a [u8], + pub mode: EncodeMode, + pub body: &'a [u8], +} + +const XXH_SEED: u32 = u32::from_le_bytes(*b"LORO"); +impl ParsedHeaderAndBody<'_> { + /// Return if the checksum is correct. + fn check_checksum(&self) -> LoroResult<()> { + match self.mode { + EncodeMode::OutdatedRle | EncodeMode::OutdatedSnapshot => { + if md5::compute(self.checksum_body).0 != self.checksum { + return Err(LoroError::DecodeChecksumMismatchError); + } + } + EncodeMode::FastSnapshot | EncodeMode::FastUpdates => { + let mut expected_bytes = [0; 4]; + expected_bytes.copy_from_slice(&self.checksum[12..16]); + let expected = u32::from_le_bytes(expected_bytes); + if xxhash_rust::xxh32::xxh32(self.checksum_body, XXH_SEED) != expected { + return Err(LoroError::DecodeChecksumMismatchError); + } + } + EncodeMode::Auto => { + return Err(LoroError::DecodeError( + "Invalid import mode `Auto` in encoded blob" + .to_string() + .into_boxed_str(), + )); + } + } + + Ok(()) + } +} + +const MIN_HEADER_SIZE: usize = 22; +pub(crate) fn parse_header_and_body( + bytes: &[u8], + check_checksum: bool, +) -> Result<ParsedHeaderAndBody<'_>, LoroError> { + let reader = &bytes; + if bytes.len() < MIN_HEADER_SIZE { + return Err(LoroError::DecodeError("Invalid import data".into())); + } + + let (magic_bytes, reader) = reader.split_at(4); + if magic_bytes != MAGIC_BYTES { + return Err(LoroError::DecodeError("Invalid magic bytes".into())); + } + + let (checksum, reader) = reader.split_at(16); + let checksum_body = reader; + let (mode_bytes, reader) = reader.split_at(2); + let mode: EncodeMode = [mode_bytes[0], mode_bytes[1]].try_into()?; + if mode == EncodeMode::Auto { + return Err(LoroError::DecodeError( + "Invalid import mode `Auto` in encoded blob" + .to_string() + .into_boxed_str(), + )); + } + let mut checksum_arr = [0; 16]; + checksum_arr.copy_from_slice(checksum); + + let ans = ParsedHeaderAndBody { + mode, + checksum_body, + checksum: checksum_arr, + body: reader, + }; + + if check_checksum { + ans.check_checksum()?; + } + Ok(ans) +} + +pub(crate) fn export_fast_snapshot(doc: &LoroDoc) -> Result<Vec<u8>, LoroEncodeError> { + let snapshot = fast_snapshot::encode_snapshot_inner(doc)?; + let expected_len = snapshot + .encoded_len() + .and_then(|len| MIN_HEADER_SIZE.checked_add(len)) + .ok_or_else(|| LoroEncodeError::internal("snapshot length overflow"))?; + let encoded = encode_with_capacity(EncodeMode::FastSnapshot, expected_len, &mut |ans| { + fast_snapshot::_encode_snapshot(&snapshot, ans); + Ok(()) + })?; + debug_assert_eq!(encoded.len(), expected_len); + Ok(encoded) +} + +pub(crate) fn export_snapshot_at( + doc: &LoroDoc, + frontiers: &Frontiers, +) -> Result<Vec<u8>, LoroEncodeError> { + check_target_version_reachable(doc, frontiers)?; + encode_with(EncodeMode::FastSnapshot, &mut |ans| { + shallow_snapshot::encode_snapshot_at(doc, frontiers, ans) + }) +} + +pub(crate) fn export_fast_updates(doc: &LoroDoc, vv: &VersionVector) -> Vec<u8> { + encode_with(EncodeMode::FastUpdates, &mut |ans| { + fast_snapshot::encode_updates(doc, vv, ans); + Ok(()) + }) + .unwrap() +} + +pub(crate) fn export_pending_updates(oplog: &OpLog) -> Result<Option<Vec<u8>>, LoroEncodeError> { + let changes = oplog.pending_changes.export_changes(oplog.vv())?; + if changes.is_empty() { + return Ok(None); + } + + encode_with(EncodeMode::FastUpdates, &mut |ans| { + // A singleton block needs neither continuous history nor a DAG-resolved + // Lamport. Never insert these incomplete changes into a ChangeStore. + for change in &changes { + let bytes = + crate::oplog::encode_change_block(std::slice::from_ref(change), &oplog.arena); + leb128::write::unsigned(ans, bytes.len() as u64).unwrap(); + ans.extend_from_slice(&bytes); + } + Ok(()) + }) + .map(Some) +} + +pub(crate) fn export_fast_updates_in_range(oplog: &OpLog, spans: &[IdSpan]) -> Vec<u8> { + encode_with(EncodeMode::FastUpdates, &mut |ans| { + fast_snapshot::encode_updates_in_range(oplog, spans, ans); + Ok(()) + }) + .unwrap() +} + +pub(crate) fn export_shallow_snapshot( + doc: &LoroDoc, + f: &Frontiers, +) -> Result<Vec<u8>, LoroEncodeError> { + check_target_version_reachable(doc, f)?; + encode_with(EncodeMode::FastSnapshot, &mut |ans| { + shallow_snapshot::export_shallow_snapshot(doc, f, ans)?; + Ok(()) + }) +} + +fn check_target_version_reachable(doc: &LoroDoc, f: &Frontiers) -> Result<(), LoroEncodeError> { + let oplog = doc.oplog.lock(); + if !oplog.dag.can_export_shallow_snapshot_on(f) { + return Err(LoroEncodeError::FrontiersNotFound(format!("{f:?}"))); + } + + Ok(()) +} + +pub(crate) fn export_state_only_snapshot( + doc: &LoroDoc, + f: &Frontiers, +) -> Result<Vec<u8>, LoroEncodeError> { + check_target_version_reachable(doc, f)?; + encode_with(EncodeMode::FastSnapshot, &mut |ans| { + shallow_snapshot::export_state_only_snapshot(doc, f, ans)?; + Ok(()) + }) +} + +pub(crate) fn encode_with( + mode: EncodeMode, + f: &mut dyn FnMut(&mut Vec<u8>) -> Result<(), LoroEncodeError>, +) -> Result<Vec<u8>, LoroEncodeError> { + encode_with_capacity(mode, MIN_HEADER_SIZE, f) +} + +fn encode_with_capacity( + mode: EncodeMode, + capacity: usize, + f: &mut dyn FnMut(&mut Vec<u8>) -> Result<(), LoroEncodeError>, +) -> Result<Vec<u8>, LoroEncodeError> { + // HEADER + let mut ans = Vec::with_capacity(capacity); + ans.extend(MAGIC_BYTES); + let checksum = [0; 16]; + ans.extend(checksum); + ans.extend(mode.to_bytes()); + + // BODY + f(&mut ans)?; + + // CHECKSUM in HEADER + let checksum_body = &ans[20..]; + let checksum = xxhash_rust::xxh32::xxh32(checksum_body, XXH_SEED); + ans[16..20].copy_from_slice(&checksum.to_le_bytes()); + Ok(ans) +} + +pub(crate) fn decode_snapshot( + doc: &LoroDoc, + mode: EncodeMode, + body: &[u8], + origin: InternalString, +) -> Result<ImportStatus, LoroError> { + match mode { + EncodeMode::OutdatedSnapshot => { + return Err(LoroError::ImportUnsupportedEncodingMode); + } + EncodeMode::FastSnapshot => { + fast_snapshot::decode_snapshot(doc, body.to_vec().into(), origin)? + } + _ => { + return Err(LoroError::DecodeError( + format!("Invalid snapshot encoding mode: {mode:?}").into_boxed_str(), + )); + } + }; + Ok(ImportStatus { + success: VersionRange::from_vv(&doc.oplog_vv()), + pending: None, + }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum EncodedBlobMode { + Snapshot, + OutdatedSnapshot, + ShallowSnapshot, + OutdatedRle, + Updates, +} + +impl std::fmt::Display for EncodedBlobMode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + EncodedBlobMode::OutdatedRle => "outdated-update", + EncodedBlobMode::OutdatedSnapshot => "outdated-snapshot", + EncodedBlobMode::Snapshot => "snapshot", + EncodedBlobMode::ShallowSnapshot => "shallow-snapshot", + EncodedBlobMode::Updates => "update", + }) + } +} + +impl EncodedBlobMode { + pub fn is_snapshot(&self) -> bool { + matches!( + self, + EncodedBlobMode::Snapshot + | EncodedBlobMode::ShallowSnapshot + | EncodedBlobMode::OutdatedSnapshot + ) + } +} + +#[derive(Debug, Clone)] +pub struct ImportBlobMetadata { + /// The partial start version vector. + /// + /// Import blob includes all the ops from `partial_start_vv` to `partial_end_vv`. + /// However, it does not constitute a complete version vector, as it only contains counters + /// from peers included within the import blob. + pub partial_start_vv: VersionVector, + /// The partial end version vector. + /// + /// Import blob includes all the ops from `partial_start_vv` to `partial_end_vv`. + /// However, it does not constitute a complete version vector, as it only contains counters + /// from peers included within the import blob. + pub partial_end_vv: VersionVector, + pub start_timestamp: i64, + pub start_frontiers: Frontiers, + pub end_timestamp: i64, + pub change_num: u32, + pub mode: EncodedBlobMode, +} + +impl LoroDoc { + /// Decodes the metadata for an imported blob from the provided bytes. + pub fn decode_import_blob_meta( + blob: &[u8], + check_checksum: bool, + ) -> LoroResult<ImportBlobMetadata> { + let parsed = parse_header_and_body(blob, check_checksum)?; + match parsed.mode { + EncodeMode::Auto => unreachable!(), + EncodeMode::OutdatedRle | EncodeMode::OutdatedSnapshot => { + Err(LoroError::ImportUnsupportedEncodingMode) + } + EncodeMode::FastSnapshot => fast_snapshot::decode_snapshot_blob_meta(parsed), + EncodeMode::FastUpdates => fast_snapshot::decode_updates_blob_meta(parsed), + } + } +} + +#[cfg(test)] +mod test { + use super::*; + use loro_common::{loro_value, ContainerID, ContainerType, LoroValue, ID}; + + #[test] + fn fast_snapshot_envelope_has_exact_length_and_valid_checksum() { + let doc = LoroDoc::new_auto_commit(); + doc.get_map("root").insert("key", "value").unwrap(); + let encoded = doc.export(ExportMode::Snapshot).unwrap(); + assert_eq!(&encoded[..4], &MAGIC_BYTES); + assert_eq!(&encoded[20..22], &EncodeMode::FastSnapshot.to_bytes()); + let parsed = parse_header_and_body(&encoded, true).unwrap(); + assert_eq!(parsed.mode, EncodeMode::FastSnapshot); + assert_eq!(encoded.len(), MIN_HEADER_SIZE + parsed.body.len()); + + let mut corrupted = encoded; + *corrupted.last_mut().unwrap() ^= 1; + assert!(matches!( + parse_header_and_body(&corrupted, true), + Err(LoroError::DecodeChecksumMismatchError) + )); + } + + #[test] + fn test_value_encode_size() { + fn assert_size(value: LoroValue, max_size: usize) { + let size = postcard::to_allocvec(&value).unwrap().len(); + assert!( + size <= max_size, + "value: {:?}, size: {}, max_size: {}", + value, + size, + max_size + ); + } + + assert_size(LoroValue::Null, 1); + assert_size(LoroValue::I64(1), 2); + assert_size(LoroValue::Double(1.), 9); + assert_size(LoroValue::Bool(true), 2); + assert_size(LoroValue::String("123".to_string().into()), 5); + assert_size(LoroValue::Binary(vec![1, 2, 3].into()), 5); + assert_size( + loro_value!({ + "a": 1, + "b": 2, + }), + 10, + ); + assert_size(loro_value!([1, 2, 3]), 8); + assert_size( + LoroValue::Container(ContainerID::new_normal(ID::new(1, 1), ContainerType::Map)), + 5, + ); + assert_size( + LoroValue::Container(ContainerID::new_root("a", ContainerType::Map)), + 5, + ); + } +} diff --git a/vendor/loro-internal/src/encoding/AGENTS.md b/vendor/loro-internal/src/encoding/AGENTS.md new file mode 100644 index 0000000..ec0025e --- /dev/null +++ b/vendor/loro-internal/src/encoding/AGENTS.md @@ -0,0 +1,42 @@ +# Encoding Guidelines + +This module owns Loro import/export formats. Read +[../../../../context/internal-encoding.md](../../../../context/internal-encoding.md) +for the verified map of supported modes, outdated modes, shallow snapshots, JSON +schema, and validation entry points. + +## Local Entry Points + +- `../encoding.rs`: `ExportMode`, `EncodeMode`, 22-byte `loro` header, checksum + validation, top-level dispatch, and `decode_import_blob_meta`. +- `fast_snapshot.rs`: current `FastSnapshot` and `FastUpdates` body layouts. +- `shallow_snapshot.rs`: `ShallowSnapshot`, `StateOnly`, and `SnapshotAt`. + Shallow exports null dead rich-text style values before the state KV is + exported; read + [../../../../context/shallow-snapshot-style-redaction.md](../../../../context/shallow-snapshot-style-redaction.md) + before changing that pass or the surrounding branch structure. +- `json_schema.rs`: JSON updates, peer compression, validation, import/export, + and redaction. +- `outdated_encode_reordered.rs`: legacy-named op/value columnar helpers still + used by current fast paths; do not confuse this with unsupported top-level + outdated blob modes. +- `value.rs`, `value_register.rs`, `arena.rs`: op/value encoding support. + +## Rules + +- Current binary modes are `FastSnapshot = 3` and `FastUpdates = 4`. +- Top-level `OutdatedRle = 1` and `OutdatedSnapshot = 2` are compatibility + detections, not formats to extend. +- Malformed bytes or JSON schema should return `Err`, not partially import. +- Snapshot import/export must preserve rollback and attached/detached state + invariants. +- Unknown container types must block shallow/state snapshot export rather than + producing a blob that cannot be decoded correctly. + +## Validation + +- `cargo test -p loro-internal import_atomicity` +- `cargo test -p loro-internal decode_updates_rejects_truncated_block` +- `cargo test -p loro-internal --test mergeable_container` when snapshot changes + can affect mergeable child retention. +- Root `pnpm test` for shared import/export semantic changes. diff --git a/vendor/loro-internal/src/encoding/CLAUDE.md b/vendor/loro-internal/src/encoding/CLAUDE.md new file mode 100644 index 0000000..ec0025e --- /dev/null +++ b/vendor/loro-internal/src/encoding/CLAUDE.md @@ -0,0 +1,42 @@ +# Encoding Guidelines + +This module owns Loro import/export formats. Read +[../../../../context/internal-encoding.md](../../../../context/internal-encoding.md) +for the verified map of supported modes, outdated modes, shallow snapshots, JSON +schema, and validation entry points. + +## Local Entry Points + +- `../encoding.rs`: `ExportMode`, `EncodeMode`, 22-byte `loro` header, checksum + validation, top-level dispatch, and `decode_import_blob_meta`. +- `fast_snapshot.rs`: current `FastSnapshot` and `FastUpdates` body layouts. +- `shallow_snapshot.rs`: `ShallowSnapshot`, `StateOnly`, and `SnapshotAt`. + Shallow exports null dead rich-text style values before the state KV is + exported; read + [../../../../context/shallow-snapshot-style-redaction.md](../../../../context/shallow-snapshot-style-redaction.md) + before changing that pass or the surrounding branch structure. +- `json_schema.rs`: JSON updates, peer compression, validation, import/export, + and redaction. +- `outdated_encode_reordered.rs`: legacy-named op/value columnar helpers still + used by current fast paths; do not confuse this with unsupported top-level + outdated blob modes. +- `value.rs`, `value_register.rs`, `arena.rs`: op/value encoding support. + +## Rules + +- Current binary modes are `FastSnapshot = 3` and `FastUpdates = 4`. +- Top-level `OutdatedRle = 1` and `OutdatedSnapshot = 2` are compatibility + detections, not formats to extend. +- Malformed bytes or JSON schema should return `Err`, not partially import. +- Snapshot import/export must preserve rollback and attached/detached state + invariants. +- Unknown container types must block shallow/state snapshot export rather than + producing a blob that cannot be decoded correctly. + +## Validation + +- `cargo test -p loro-internal import_atomicity` +- `cargo test -p loro-internal decode_updates_rejects_truncated_block` +- `cargo test -p loro-internal --test mergeable_container` when snapshot changes + can affect mergeable child retention. +- Root `pnpm test` for shared import/export semantic changes. diff --git a/vendor/loro-internal/src/encoding/arena.rs b/vendor/loro-internal/src/encoding/arena.rs new file mode 100644 index 0000000..5ede1b7 --- /dev/null +++ b/vendor/loro-internal/src/encoding/arena.rs @@ -0,0 +1,277 @@ +use std::{borrow::Cow, ops::Deref}; + +use crate::InternalString; +use loro_common::{ContainerID, ContainerType, Counter, LoroError, LoroResult, PeerID}; +use rustc_hash::FxHashSet; +use serde_columnar::columnar; + +use super::{ + outdated_encode_reordered::PeerIdx, + value::{Value, ValueDecodedArenasTrait, ValueEncodeRegister}, + value_register::ValueRegister, +}; + +#[derive(Debug)] +pub struct EncodedRegisters<'a> { + pub(super) peer: ValueRegister<PeerID>, + pub(super) key: ValueRegister<InternalString>, + pub(super) tree_id: ValueRegister<EncodedTreeID>, + pub(super) position: either::Either<FxHashSet<&'a [u8]>, ValueRegister<&'a [u8]>>, +} + +impl ValueEncodeRegister for EncodedRegisters<'_> { + fn key_mut(&mut self) -> &mut ValueRegister<InternalString> { + &mut self.key + } + + fn peer_mut(&mut self) -> &mut ValueRegister<PeerID> { + &mut self.peer + } + + fn encode_tree_op( + &mut self, + op: &crate::container::tree::tree_op::TreeOp, + ) -> super::value::Value<'static> { + Value::TreeMove(super::value::EncodedTreeMove::from_tree_op(op, self)) + } +} + +#[columnar(vec, ser, de, iterable)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub(crate) struct EncodedContainer { + #[columnar(strategy = "BoolRle")] + is_root: bool, + #[columnar(strategy = "Rle")] + kind: u8, + #[columnar(strategy = "Rle")] + peer_idx: usize, + #[columnar(strategy = "DeltaRle")] + key_idx_or_counter: i32, +} + +impl EncodedContainer { + pub fn as_container_id(&self, arenas: &dyn ValueDecodedArenasTrait) -> LoroResult<ContainerID> { + if self.is_root { + Ok(ContainerID::Root { + container_type: ContainerType::try_from_u8(self.kind) + .unwrap_or(ContainerType::Unknown(self.kind)), + name: arenas + .keys() + .get(self.key_idx_or_counter as usize) + .ok_or(LoroError::DecodeDataCorruptionError)? + .clone(), + }) + } else { + Ok(ContainerID::Normal { + container_type: ContainerType::try_from_u8(self.kind) + .unwrap_or(ContainerType::Unknown(self.kind)), + peer: *(arenas + .peers() + .get(self.peer_idx) + .ok_or(LoroError::DecodeDataCorruptionError)?), + counter: self.key_idx_or_counter, + }) + } + } +} + +#[columnar(ser, de)] +#[derive(Default)] +pub(crate) struct ContainerArena { + #[columnar(class = "vec", iter = "EncodedContainer")] + pub(super) containers: Vec<EncodedContainer>, +} + +impl Deref for ContainerArena { + type Target = [EncodedContainer]; + + fn deref(&self) -> &Self::Target { + &self.containers + } +} + +impl ContainerArena { + pub fn encode(&self) -> Vec<u8> { + serde_columnar::to_vec(&self.containers).unwrap() + } + + pub fn decode(bytes: &[u8]) -> LoroResult<Self> { + Ok(ContainerArena { + containers: serde_columnar::from_bytes(bytes)?, + }) + } + + pub fn from_containers( + cids: Vec<ContainerID>, + peer_register: &mut ValueRegister<PeerID>, + key_reg: &mut ValueRegister<InternalString>, + ) -> Self { + let mut ans = Self { + containers: Vec::with_capacity(cids.len()), + }; + for cid in cids { + ans.push(cid, peer_register, key_reg); + } + + ans + } + + pub fn push( + &mut self, + id: ContainerID, + peer_register: &mut ValueRegister<PeerID>, + register_key: &mut ValueRegister<InternalString>, + ) { + let (is_root, kind, peer_idx, key_idx_or_counter) = match id { + ContainerID::Root { + container_type, + name, + } => (true, container_type, 0, register_key.register(&name) as i32), + ContainerID::Normal { + container_type, + peer, + counter, + } => ( + false, + container_type, + peer_register.register(&peer), + counter, + ), + }; + self.containers.push(EncodedContainer { + is_root, + kind: kind.to_u8(), + peer_idx, + key_idx_or_counter, + }); + } +} + +#[derive(Clone, Hash, PartialEq, Eq, Debug)] +#[columnar(vec, ser, de, iterable)] +pub struct EncodedTreeID { + #[columnar(strategy = "Rle")] + pub peer_idx: PeerIdx, + #[columnar(strategy = "DeltaRle")] + pub counter: Counter, +} + +#[derive(Clone)] +#[columnar(vec, ser, de, iterable)] +pub(super) struct PositionDelta<'a> { + #[columnar(strategy = "Rle")] + common_prefix_length: usize, + #[columnar(borrow)] + rest: Cow<'a, [u8]>, +} + +#[derive(Default)] +#[columnar(ser, de)] +pub(crate) struct PositionArena<'a> { + #[columnar(class = "vec", iter = "PositionDelta<'a>")] + pub(super) positions: Vec<PositionDelta<'a>>, +} + +impl<'a> PositionArena<'a> { + pub fn from_positions(positions: impl IntoIterator<Item = &'a [u8]>) -> Self { + let iter = positions.into_iter(); + let mut ans = Vec::with_capacity(iter.size_hint().0); + let mut last_bytes: &[u8] = &[]; + for p in iter { + let common = longest_common_prefix_length(last_bytes, p); + let rest = &p[common..]; + last_bytes = p; + ans.push(PositionDelta { + common_prefix_length: common, + rest: Cow::Borrowed(rest), + }) + } + Self { positions: ans } + } + + pub fn try_parse_to_positions(self) -> LoroResult<Vec<Vec<u8>>> { + let mut ans: Vec<Vec<u8>> = Vec::with_capacity(self.positions.len()); + for PositionDelta { + common_prefix_length, + rest, + } in self.positions + { + if let Some(last_bytes) = ans.last() { + if common_prefix_length > last_bytes.len() { + return Err(LoroError::DecodeError( + "Decode position arena failed: common prefix out of range".into(), + )); + } + } else if common_prefix_length != 0 { + return Err(LoroError::DecodeError( + "Decode position arena failed: first common prefix is nonzero".into(), + )); + } + + // +1 for Fractional Index + let capacity = rest + .len() + .checked_add(common_prefix_length) + .and_then(|len| len.checked_add(1)) + .ok_or_else(|| { + LoroError::DecodeError( + "Decode position arena failed: position length overflow".into(), + ) + })?; + let mut p = Vec::with_capacity(capacity); + if let Some(last_bytes) = ans.last() { + p.extend_from_slice(&last_bytes[0..common_prefix_length]); + } + p.extend_from_slice(rest.as_ref()); + ans.push(p); + } + Ok(ans) + } + + pub fn encode(&self) -> Vec<u8> { + serde_columnar::to_vec(&self).unwrap() + } + + pub fn decode<'de: 'a>(bytes: &'de [u8]) -> LoroResult<Self> { + Ok(serde_columnar::from_bytes(bytes)?) + } + + pub fn encode_v2(&self) -> Vec<u8> { + if self.positions.is_empty() { + return Vec::new(); + } + + serde_columnar::to_vec(&self).unwrap() + } + + pub fn decode_v2<'de: 'a>(bytes: &'de [u8]) -> LoroResult<Self> { + if bytes.is_empty() { + return Ok(Self::default()); + } + + Ok(serde_columnar::from_bytes(bytes)?) + } +} + +fn longest_common_prefix_length(a: &[u8], b: &[u8]) -> usize { + a.iter().zip(b.iter()).take_while(|(x, y)| x == y).count() +} + +#[cfg(test)] +mod tests { + use std::borrow::Cow; + + use super::{PositionArena, PositionDelta}; + + #[test] + fn position_arena_rejects_invalid_common_prefix() { + let arena = PositionArena { + positions: vec![PositionDelta { + common_prefix_length: 1, + rest: Cow::Borrowed(&[]), + }], + }; + + assert!(arena.try_parse_to_positions().is_err()); + } +} diff --git a/vendor/loro-internal/src/encoding/fast_snapshot.rs b/vendor/loro-internal/src/encoding/fast_snapshot.rs new file mode 100644 index 0000000..53fa01c --- /dev/null +++ b/vendor/loro-internal/src/encoding/fast_snapshot.rs @@ -0,0 +1,629 @@ +//! Fast snapshot encoding and decoding. +//! +//! # Layout +//! +//! - u32 in little endian for len of bytes for oplog +//! - oplog bytes +//! - u32 in little endian for len of bytes for state +//! - state bytes +//! - u32 in little endian for len of bytes for gc +//! - gc bytes +//! +//! All of `oplog bytes`, `state bytes` and `gc bytes` are encoded KV store bytes. +//! +//! +//! +use std::io::{Read, Write}; + +use crate::{ + change::Change, encoding::shallow_snapshot, oplog::ChangeStore, version::Frontiers, LoroDoc, + OpLog, VersionVector, +}; +use bytes::{Buf, Bytes}; +use loro_common::{HasCounterSpan, IdSpan, InternalString, LoroEncodeError, LoroError, LoroResult}; + +use super::{EncodedBlobMode, ImportBlobMetadata, ParsedHeaderAndBody}; +pub(crate) const EMPTY_MARK: &[u8] = b"E"; +pub(crate) struct Snapshot { + pub oplog_bytes: Bytes, + pub state_bytes: Option<Bytes>, + pub shallow_root_state_bytes: Bytes, +} + +impl Snapshot { + pub(super) fn encoded_len(&self) -> Option<usize> { + let state_len = self + .state_bytes + .as_ref() + .map_or(EMPTY_MARK.len(), Bytes::len); + u32::try_from(self.oplog_bytes.len()).ok()?; + u32::try_from(state_len).ok()?; + u32::try_from(self.shallow_root_state_bytes.len()).ok()?; + (3 * std::mem::size_of::<u32>()) + .checked_add(self.oplog_bytes.len())? + .checked_add(state_len)? + .checked_add(self.shallow_root_state_bytes.len()) + } +} + +pub(super) fn _encode_snapshot<W: Write>(s: &Snapshot, w: &mut W) { + w.write_all(&(s.oplog_bytes.len() as u32).to_le_bytes()) + .unwrap(); + w.write_all(&s.oplog_bytes).unwrap(); + let state_bytes = s.state_bytes.as_deref().unwrap_or(EMPTY_MARK); + w.write_all(&(state_bytes.len() as u32).to_le_bytes()) + .unwrap(); + w.write_all(state_bytes).unwrap(); + w.write_all(&(s.shallow_root_state_bytes.len() as u32).to_le_bytes()) + .unwrap(); + w.write_all(&s.shallow_root_state_bytes).unwrap(); +} + +pub(super) fn _decode_snapshot_bytes(bytes: Bytes) -> LoroResult<Snapshot> { + let mut r = bytes.reader(); + let oplog_bytes_len = read_u32_le(&mut r)? as usize; + if r.get_ref().len() < oplog_bytes_len { + return Err(LoroError::DecodeError( + "decode_snapshot: invalid oplog bytes length" + .to_string() + .into_boxed_str(), + )); + } + let oplog_bytes = r.get_mut().copy_to_bytes(oplog_bytes_len); + let state_bytes_len = read_u32_le(&mut r)? as usize; + if r.get_ref().len() < state_bytes_len { + return Err(LoroError::DecodeError( + "decode_snapshot: invalid state bytes length" + .to_string() + .into_boxed_str(), + )); + } + let state_bytes = r.get_mut().copy_to_bytes(state_bytes_len); + let state_bytes = if state_bytes == EMPTY_MARK { + None + } else { + Some(state_bytes) + }; + let shallow_bytes_len = read_u32_le(&mut r)? as usize; + if r.get_ref().len() < shallow_bytes_len { + return Err(LoroError::DecodeError( + "decode_snapshot: invalid shallow root bytes length" + .to_string() + .into_boxed_str(), + )); + } + let shallow_root_state_bytes = r.get_mut().copy_to_bytes(shallow_bytes_len); + if r.get_ref().has_remaining() { + return Err(LoroError::DecodeError( + "decode_snapshot: trailing bytes after snapshot" + .to_string() + .into_boxed_str(), + )); + } + + Ok(Snapshot { + oplog_bytes, + state_bytes, + shallow_root_state_bytes, + }) +} + +pub(super) fn _decode_snapshot_meta_partial(bytes: &[u8]) -> LoroResult<(&[u8], bool)> { + let mut r = bytes; + let oplog_bytes_len = read_u32_le_slice(&mut r)? as usize; + if r.len() < oplog_bytes_len { + return Err(LoroError::DecodeDataCorruptionError); + } + let oplog_bytes = &r[..oplog_bytes_len]; + r = &r[oplog_bytes_len..]; + let state_bytes_len = read_u32_le_slice(&mut r)? as usize; + if r.len() < state_bytes_len { + return Err(LoroError::DecodeDataCorruptionError); + } + r = &r[state_bytes_len..]; + let shallow_bytes_len = read_u32_le_slice(&mut r)? as usize; + if r.len() < shallow_bytes_len { + return Err(LoroError::DecodeDataCorruptionError); + } + r = &r[shallow_bytes_len..]; + if !r.is_empty() { + return Err(LoroError::DecodeDataCorruptionError); + } + + Ok((oplog_bytes, shallow_bytes_len > 0)) +} + +fn read_u32_le_slice(r: &mut &[u8]) -> LoroResult<u32> { + let mut buf = [0; 4]; + r.read_exact(&mut buf) + .map_err(|_| LoroError::DecodeDataCorruptionError)?; + Ok(u32::from_le_bytes(buf)) +} + +fn read_u32_le(r: &mut bytes::buf::Reader<Bytes>) -> LoroResult<u32> { + let mut buf = [0; 4]; + r.read_exact(&mut buf).map_err(|_| { + LoroError::DecodeError( + "decode_snapshot: unexpected end of snapshot bytes" + .to_string() + .into_boxed_str(), + ) + })?; + Ok(u32::from_le_bytes(buf)) +} + +pub(crate) fn decode_snapshot( + doc: &LoroDoc, + bytes: Bytes, + origin: InternalString, +) -> LoroResult<()> { + let snapshot = _decode_snapshot_bytes(bytes)?; + decode_snapshot_inner(snapshot, doc, origin) +} + +pub(crate) fn decode_snapshot_inner( + snapshot: Snapshot, + doc: &LoroDoc, + origin: InternalString, +) -> Result<(), LoroError> { + let Snapshot { + oplog_bytes, + state_bytes, + shallow_root_state_bytes, + } = snapshot; + ensure_cov::notify_cov("loro_internal::import::fast_snapshot::decode_snapshot"); + let mut oplog = doc.oplog().lock(); + if !oplog.is_empty() { + return Err(LoroError::DecodeError( + "decode_snapshot: cannot import snapshot into a non-empty doc" + .to_string() + .into_boxed_str(), + )); + } + + let mut state = doc.app_state().lock(); + + state.check_before_decode_snapshot()?; + + if !state.frontiers.is_empty() { + return Err(LoroError::DecodeError( + "decode_snapshot: app state frontiers must be empty before import" + .to_string() + .into_boxed_str(), + )); + } + + if !oplog.frontiers().is_empty() { + return Err(LoroError::DecodeError( + "decode_snapshot: oplog frontiers must be empty before import" + .to_string() + .into_boxed_str(), + )); + } + let need_calc = state_bytes.is_none(); + let checkout_origin = origin.clone(); + + let arena_checkpoint = oplog.arena.checkpoint_for_rollback(); + let decode_result = (|| -> LoroResult<()> { + oplog.decode_change_store(oplog_bytes)?; + let state_frontiers; + if shallow_root_state_bytes.is_empty() { + ensure_cov::notify_cov("loro_internal::import::snapshot::normal"); + if let Some(bytes) = state_bytes { + state.store.decode(bytes)?; + } + state_frontiers = oplog.frontiers().clone(); + } else { + ensure_cov::notify_cov("loro_internal::import::snapshot::gc"); + let shallow_root_state_frontiers = state.store.decode_gc( + shallow_root_state_bytes.clone(), + oplog.dag().shallow_since_frontiers().clone(), + doc.config.clone(), + )?; + state.store.decode_state_by_two_bytes( + shallow_root_state_bytes, + state_bytes.unwrap_or_default(), + )?; + + let shallow_root_store = state.shallow_root_store().cloned(); + oplog.with_history_cache(|h| { + h.set_shallow_root_store(shallow_root_store); + }); + + if need_calc { + ensure_cov::notify_cov("shallow_snapshot::need_calc"); + state_frontiers = shallow_root_state_frontiers.ok_or_else(|| { + LoroError::DecodeError( + "decode_snapshot: shallow root frontiers are missing" + .to_string() + .into_boxed_str(), + ) + })?; + } else { + ensure_cov::notify_cov("shallow_snapshot::dont_need_calc"); + state_frontiers = oplog.frontiers().clone(); + } + } + + state.init_with_states_and_version(state_frontiers, &oplog, vec![], false, origin)?; + Ok(()) + })(); + + if let Err(e) = decode_result { + state.reset_to_empty_for_failed_snapshot_import(); + oplog.reset_to_empty_for_failed_snapshot_import(arena_checkpoint, &mut state); + return Err(e); + } + drop(state); + drop(oplog); + if need_calc { + doc.set_detached(true); + if let Err(e) = doc._checkout_to_latest_without_commit_as_import(false, checkout_origin) { + doc.set_detached(false); + let mut oplog = doc.oplog().lock(); + let mut state = doc.app_state().lock(); + state.reset_to_empty_for_failed_snapshot_import(); + oplog.reset_to_empty_for_failed_snapshot_import(arena_checkpoint, &mut state); + return Err(e); + } + debug_assert_eq!(doc.state_frontiers(), doc.oplog_frontiers()); + } + + Ok(()) +} + +impl OpLog { + pub(super) fn decode_change_store(&mut self, bytes: bytes::Bytes) -> LoroResult<()> { + let v = self.change_store().import_all(bytes)?; + self.dag.set_version_by_fast_snapshot_import(v)?; + self.refresh_visible_op_count(); + Ok(()) + } +} + +pub(crate) fn encode_snapshot_inner(doc: &LoroDoc) -> Result<Snapshot, LoroEncodeError> { + encode_snapshot_inner_with(doc, shallow_snapshot::CachedShallowRoot::Prune) +} + +/// Snapshot for `LoroDoc::fork`: a shallow doc's cached root is copied +/// verbatim instead of being filtered. +pub(crate) fn encode_snapshot_inner_for_fork(doc: &LoroDoc) -> Result<Snapshot, LoroEncodeError> { + encode_snapshot_inner_with(doc, shallow_snapshot::CachedShallowRoot::Verbatim) +} + +fn encode_snapshot_inner_with( + doc: &LoroDoc, + cached_root: shallow_snapshot::CachedShallowRoot, +) -> Result<Snapshot, LoroEncodeError> { + assert!(doc.drop_pending_events().is_empty()); + let old_state_frontiers = doc.state_frontiers(); + let was_detached = doc.is_detached(); + let oplog = doc.oplog().lock(); + let mut state = doc.app_state().lock(); + let is_gc = state.store.shallow_root_store().is_some(); + if is_gc { + // TODO: PERF: this can be optimized by reusing the bytes of gc store + let f = oplog.shallow_since_frontiers().clone(); + drop(state); + drop(oplog); + let (snapshot, _) = shallow_snapshot::export_shallow_snapshot_inner(doc, &f, cached_root)?; + return Ok(snapshot); + } + + assert!(!state.is_in_txn()); + let oplog_bytes = oplog.encode_change_store(); + if oplog.is_shallow() { + assert_eq!( + oplog.shallow_since_frontiers(), + state.store.shallow_root_frontiers().unwrap() + ); + } + if was_detached { + let latest = oplog.frontiers().clone(); + drop(state); + drop(oplog); + doc._checkout_without_emitting(&latest, false, true) + .unwrap(); + state = doc.app_state().lock(); + } + // Every container referenced by applied ops/diffs already has a store entry + // (`ensure_containers_created_by_op` / `ensure_containers_created_by_internal_diff`), so a + // full snapshot does not need to walk the alive-container graph: flushing the store and + // exporting the kv bytes is sufficient, and it keeps snapshot-backed state lazy. Only + // shallow snapshot export still derives the alive set (to filter retained keys). + let snapshot: Result<Snapshot, LoroEncodeError> = Ok(Snapshot { + oplog_bytes, + state_bytes: Some(state.store.encode()), + shallow_root_state_bytes: Bytes::new(), + }); + if was_detached { + drop(state); + doc._checkout_without_emitting(&old_state_frontiers, false, true) + .unwrap(); + doc.drop_pending_events(); + } + + snapshot +} + +pub(crate) fn decode_oplog( + oplog: &mut OpLog, + bytes: &[u8], + values: crate::oplog::ImportedValues, +) -> Result<Vec<Change>, LoroError> { + let oplog_len = bytes + .get(0..4) + .ok_or_else(|| LoroError::DecodeError("decode_oplog: missing length prefix".into()))?; + let oplog_len = u32::from_le_bytes( + oplog_len + .try_into() + .expect("slice length checked to be exactly 4"), + ) as usize; + let oplog_bytes = bytes + .get(4..4 + oplog_len) + .ok_or_else(|| LoroError::DecodeError("decode_oplog: invalid oplog length".into()))?; + let mut changes = + ChangeStore::decode_snapshot_for_updates(oplog_bytes.to_vec().into(), oplog, values)?; + changes.sort_unstable_by_key(|x| x.lamport); + Ok(changes) +} + +pub(crate) fn encode_updates<W: std::io::Write>(doc: &LoroDoc, vv: &VersionVector, w: &mut W) { + let oplog = doc.oplog().lock(); + oplog.export_blocks_from(vv, w); +} + +pub(crate) fn encode_updates_in_range<W: std::io::Write>( + oplog: &OpLog, + spans: &[IdSpan], + w: &mut W, +) { + oplog.export_blocks_in_range(spans, w); +} + +pub(crate) fn decode_updates(oplog: &mut OpLog, body: Bytes) -> Result<Vec<Change>, LoroError> { + let mut reader: &[u8] = body.as_ref(); + let mut index = 0; + let mut changes = Vec::new(); + while !reader.is_empty() { + let old_reader_len = reader.len(); + let len = leb128::read::unsigned(&mut reader) + .map_err(|_| LoroError::DecodeError("decode_updates: invalid block length".into()))? + as usize; + index += old_reader_len - reader.len(); + let end = index.checked_add(len).ok_or_else(|| { + LoroError::DecodeError("decode_updates: block length overflow".into()) + })?; + if end > body.len() { + return Err(LoroError::DecodeError( + "decode_updates: truncated block payload".into(), + )); + } + let block_bytes = body.slice(index..end); + changes.extend( + oplog + .change_store() + .decode_update_block(block_bytes, oplog.vv())?, + ); + index = end; + reader = &reader[len..]; + } + + changes.sort_unstable_by_key(|x| x.lamport); + Ok(changes) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + encoding::ExportMode, handler::HandlerTrait, utils::kv_wrapper::KvWrapper, MapHandler, + }; + + fn snapshot_sections(doc: &LoroDoc) -> Snapshot { + let encoded = doc.export(ExportMode::Snapshot).unwrap(); + let parsed = crate::encoding::parse_header_and_body(&encoded, true).unwrap(); + _decode_snapshot_bytes(Bytes::copy_from_slice(parsed.body)).unwrap() + } + + #[test] + fn snapshot_encoded_len_matches_written_len() { + for snapshot in [ + Snapshot { + oplog_bytes: Bytes::from_static(b"oplog"), + state_bytes: Some(Bytes::from_static(b"state")), + shallow_root_state_bytes: Bytes::new(), + }, + Snapshot { + oplog_bytes: Bytes::new(), + state_bytes: None, + shallow_root_state_bytes: Bytes::from_static(b"shallow"), + }, + ] { + let expected_len = snapshot.encoded_len().unwrap(); + let mut encoded = Vec::new(); + _encode_snapshot(&snapshot, &mut encoded); + assert_eq!(encoded.len(), expected_len); + } + } + + #[test] + fn decode_updates_rejects_truncated_block() { + let doc = LoroDoc::new(); + let mut oplog = doc.oplog.lock(); + let err = decode_updates(&mut oplog, Bytes::from_static(&[0x02, 0x01])) + .expect_err("truncated update block should be rejected"); + assert!(matches!(err, LoroError::DecodeError(_))); + } + + #[test] + fn full_export_round_trips_lazy_child_parent_conflict_but_shallow_rejects() { + fn doc_with_child(root: &str) -> (LoroDoc, loro_common::ContainerID) { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(42).unwrap(); + let child = doc + .get_map(root) + .insert_container("child", MapHandler::new_detached()) + .unwrap(); + child.insert("value", root).unwrap(); + let child_id = child.id(); + (doc, child_id) + } + + let (parent_a, child_a) = doc_with_child("parent-a"); + let (parent_b, child_b) = doc_with_child("parent-b"); + assert_eq!(child_a, child_b, "test setup needs the same child id"); + + let mut sections_a = snapshot_sections(&parent_a); + let sections_b = snapshot_sections(&parent_b); + let state_a = KvWrapper::new_mem(); + state_a + .import(sections_a.state_bytes.take().unwrap()) + .unwrap(); + let state_b = KvWrapper::new_mem(); + state_b.import(sections_b.state_bytes.unwrap()).unwrap(); + let child_key = child_a.to_bytes(); + state_a.insert(&child_key, state_b.get(&child_key).unwrap()); + + let target = LoroDoc::new(); + decode_snapshot_inner( + Snapshot { + oplog_bytes: sections_a.oplog_bytes, + state_bytes: Some(state_a.export()), + shallow_root_state_bytes: sections_a.shallow_root_state_bytes, + }, + &target, + Default::default(), + ) + .unwrap(); + + // Full snapshot export is a byte-faithful round-trip of the imported kv and does not + // re-derive the container graph, so it must succeed even with conflicting lazy parent + // metadata. The alive-container walk (and its validation) now only runs for shallow + // exports, which must still reject the conflict. + let reexported = target + .export(ExportMode::Snapshot) + .expect("full export round-trips lazy state without walking it"); + let reimported = LoroDoc::new(); + reimported.import(&reexported).unwrap(); + + let err = target + .export(ExportMode::StateOnly(None)) + .expect_err("shallow export walks the graph and must reject the conflict"); + assert!(err.to_string().contains("snapshot state encodes parent")); + } + + #[test] + fn full_export_round_trips_malformed_lazy_wrapper_but_shallow_rejects() { + let source = LoroDoc::new_auto_commit(); + source.get_map("root").insert("value", 1).unwrap(); + let mut sections = snapshot_sections(&source); + let state = KvWrapper::new_mem(); + state.import(sections.state_bytes.take().unwrap()).unwrap(); + let root = loro_common::ContainerID::new_root("root", crate::ContainerType::Map); + state.insert( + &root.to_bytes(), + Bytes::from(vec![crate::ContainerType::Map.to_u8()]), + ); + + let target = LoroDoc::new(); + decode_snapshot_inner( + Snapshot { + oplog_bytes: sections.oplog_bytes, + state_bytes: Some(state.export()), + shallow_root_state_bytes: sections.shallow_root_state_bytes, + }, + &target, + Default::default(), + ) + .unwrap(); + + // Full snapshot export no longer decodes lazy wrappers, so the malformed entry is + // round-tripped as-is; the error surfaces where the wrapper is actually read, e.g. the + // shallow-export walk. + target + .export(ExportMode::Snapshot) + .expect("full export round-trips lazy state without decoding it"); + + let err = target + .export(ExportMode::StateOnly(None)) + .expect_err("shallow export decodes the wrapper and must return an error"); + assert!(err.to_string().contains("Decode container state failed")); + } +} + +pub(crate) fn decode_snapshot_blob_meta( + parsed: ParsedHeaderAndBody, +) -> LoroResult<ImportBlobMetadata> { + let (oplog_bytes, is_shallow) = _decode_snapshot_meta_partial(parsed.body)?; + let mode = if is_shallow { + EncodedBlobMode::ShallowSnapshot + } else { + EncodedBlobMode::Snapshot + }; + + let doc = LoroDoc::new(); + let mut oplog = doc.oplog.lock(); + oplog.decode_change_store(oplog_bytes.to_vec().into())?; + let timestamp = oplog.get_greatest_timestamp(oplog.dag.frontiers()); + let f = oplog.dag.shallow_since_frontiers().clone(); + let start_timestamp = oplog.get_timestamp_of_version(&f); + let change_num = oplog.change_store().change_num() as u32; + + Ok(ImportBlobMetadata { + mode, + partial_start_vv: oplog.dag.shallow_since_vv().to_vv(), + partial_end_vv: oplog.vv().clone(), + start_timestamp, + start_frontiers: f, + end_timestamp: timestamp, + change_num, + }) +} + +pub(crate) fn decode_updates_blob_meta( + parsed: ParsedHeaderAndBody, +) -> LoroResult<ImportBlobMetadata> { + let doc = LoroDoc::new(); + let mut oplog = doc.oplog.lock(); + let changes = decode_updates(&mut oplog, parsed.body.to_vec().into())?; + let mut start_vv = VersionVector::new(); + let mut end_vv = VersionVector::new(); + for c in changes.iter() { + match start_vv.get(&c.id.peer).copied() { + Some(start) if start <= c.id.counter => {} + _ => { + start_vv.insert(c.id.peer, c.id.counter); + } + } + match end_vv.get(&c.id.peer).copied() { + Some(end) if end >= c.ctr_end() => {} + _ => { + end_vv.insert(c.id.peer, c.ctr_end()); + } + } + } + + let mut start_frontiers = Frontiers::new(); + for c in changes.iter() { + for dep in c.deps().iter() { + if let Some(start_counter) = start_vv.get(&dep.peer) { + if *start_counter > dep.counter { + start_frontiers.push(dep); + } + } else if end_vv.get(&dep.peer).is_none() { + start_frontiers.push(dep); + } + } + } + + Ok(ImportBlobMetadata { + mode: EncodedBlobMode::Updates, + partial_start_vv: start_vv, + partial_end_vv: end_vv, + start_timestamp: changes.first().map(|x| x.timestamp).unwrap_or(0), + start_frontiers, + end_timestamp: changes.last().map(|x| x.timestamp).unwrap_or(0), + change_num: changes.len() as u32, + }) +} diff --git a/vendor/loro-internal/src/encoding/json_schema.rs b/vendor/loro-internal/src/encoding/json_schema.rs new file mode 100644 index 0000000..ba79ac6 --- /dev/null +++ b/vendor/loro-internal/src/encoding/json_schema.rs @@ -0,0 +1,1911 @@ +use super::outdated_encode_reordered::ValueRegister; +use crate::{ + arena::SharedArena, + change::{Change, ChangeRef}, + container::{ + list::list_op::{DeleteSpan, DeleteSpanWithId, InnerListOp}, + map::MapSet, + richtext::TextStyleInfoFlag, + tree::tree_op::TreeOp, + }, + op::{FutureInnerContent, InnerContent, Op, ValueSlice}, + oplog::BlockChangeRef, + version::Frontiers, + OpLog, VersionVector, +}; +use either::Either; +use itertools::Itertools; +use json::{JsonChange, JsonOpContent, JsonSchema}; +use loro_common::{ + ContainerID, ContainerType, Counter, HasCounterSpan, HasId, IdLp, IdSpan, LoroError, + LoroResult, LoroValue, PeerID, TreeID, ID, +}; +use rle::{HasLength, RleVec, Sliceable}; +use std::sync::Arc; + +const SCHEMA_VERSION: u8 = 1; + +fn refine_vv(vv: &VersionVector, oplog: &OpLog) -> VersionVector { + let mut refined = VersionVector::new(); + for (&peer, &counter) in vv.iter() { + if counter <= 0 { + continue; + } + let end = oplog.vv().get(&peer).copied().unwrap_or(0); + if end <= counter { + refined.insert(peer, end); + } else { + refined.insert(peer, counter); + } + } + refined +} + +pub(crate) fn try_export_json<'a, 'c: 'a>( + oplog: &'c OpLog, + start_vv: &VersionVector, + end_vv: &VersionVector, + with_peer_compression: bool, +) -> LoroResult<JsonSchema> { + let actual_start_vv = refine_vv(start_vv, oplog); + let actual_end_vv = refine_vv(end_vv, oplog); + + let frontiers = oplog.dag.try_vv_to_frontiers(&actual_start_vv)?; + + let diff_changes = init_encode(oplog, &actual_start_vv, &actual_end_vv); + // Legacy iteration records a bad block and skips it. Do not return that gap. + oplog.check_history_parsable()?; + if with_peer_compression { + let mut peer_register = ValueRegister::<PeerID>::new(); + let changes = encode_changes(&diff_changes, &oplog.arena, Some(&mut peer_register)); + Ok(JsonSchema { + changes, + schema_version: SCHEMA_VERSION, + peers: Some(peer_register.unwrap_vec()), + start_version: frontiers, + }) + } else { + let changes = encode_changes(&diff_changes, &oplog.arena, None); + Ok(JsonSchema { + changes, + schema_version: SCHEMA_VERSION, + peers: None, + start_version: frontiers, + }) + } +} + +pub(crate) fn export_json_in_id_span(oplog: &OpLog, mut id_span: IdSpan) -> Vec<json::JsonChange> { + id_span.normalize_(); + if id_span.counter.end <= 0 { + return vec![]; + } + id_span.counter.start = id_span.counter.start.max(0); + id_span.counter.end = id_span.counter.end.max(0); + + let end = oplog.vv().get(&id_span.peer).copied().unwrap_or(0); + if id_span.counter.start >= end { + return vec![]; + } + + id_span.counter.end = id_span.counter.end.min(end); + let mut diff_changes: Vec<Either<BlockChangeRef, Change>> = Vec::new(); + while id_span.counter.start < id_span.counter.end { + let Some(change) = oplog.get_change_at(id_span.id_start()) else { + break; + }; + let ctr_end = change.ctr_end(); + if change.id.counter >= id_span.counter.start && change.ctr_end() <= id_span.counter.end { + diff_changes.push(Either::Left(change)); + } else { + let start = if change.id.counter < id_span.counter.start { + (id_span.counter.start - change.id.counter) as usize + } else { + 0 + }; + + let end = if change.ctr_end() > id_span.counter.end { + (id_span.counter.end - change.id.counter) as usize + } else { + change.atom_len() + }; + + diff_changes.push(Either::Right(change.slice(start, end))); + } + + id_span.counter.start = ctr_end; + } + + encode_changes(&diff_changes, &oplog.arena, None) +} + +pub(crate) fn decode_json_changes( + json: JsonSchema, + arena: &SharedArena, +) -> LoroResult<Vec<Change>> { + decode_changes(json, arena) +} + +fn init_encode<'s, 'a: 's>( + oplog: &'a OpLog, + start_vv: &VersionVector, + end_vv: &VersionVector, +) -> Vec<Either<BlockChangeRef, Change>> { + let mut diff_changes: Vec<Either<BlockChangeRef, Change>> = Vec::new(); + for change in oplog.iter_changes_peer_by_peer(start_vv, end_vv) { + let start_cnt = start_vv.get(&change.id.peer).copied().unwrap_or(0); + let end_cnt = end_vv.get(&change.id.peer).copied().unwrap_or(0); + if change.id.counter < start_cnt { + if change.ctr_end() <= start_cnt { + continue; + } + + let offset = start_cnt - change.id.counter; + let to = change + .atom_len() + .min((end_cnt - change.id.counter) as usize); + diff_changes.push(Either::Right(change.slice(offset as usize, to))); + } else if change.id.counter + change.atom_len() as i32 > end_cnt { + let len = end_cnt - change.id.counter; + diff_changes.push(Either::Right(change.slice(0, len as usize))); + } else { + diff_changes.push(Either::Left(change)); + } + } + diff_changes.sort_by_key(|x| match x { + Either::Left(c) => c.lamport, + Either::Right(c) => c.lamport, + }); + diff_changes +} + +fn register_id(id: &ID, peer_register: Option<&mut ValueRegister<PeerID>>) -> ID { + let peer = match peer_register { + Some(peer_register) => peer_register.register(&id.peer) as PeerID, + None => id.peer, + }; + ID::new(peer as PeerID, id.counter) +} + +fn register_idlp(idlp: &IdLp, peer_register: Option<&mut ValueRegister<PeerID>>) -> IdLp { + let peer = match peer_register { + Some(peer_register) => peer_register.register(&idlp.peer) as PeerID, + None => idlp.peer, + }; + IdLp { + peer, + lamport: idlp.lamport, + } +} + +fn register_tree_id(tree: &TreeID, peer_register: Option<&mut ValueRegister<PeerID>>) -> TreeID { + TreeID { + peer: match peer_register { + Some(peer_register) => peer_register.register(&tree.peer) as PeerID, + None => tree.peer, + }, + counter: tree.counter, + } +} + +fn register_container_id( + container: ContainerID, + peer_register: Option<&mut ValueRegister<PeerID>>, +) -> ContainerID { + match container { + ContainerID::Normal { + peer, + counter, + container_type, + } => ContainerID::Normal { + peer: match peer_register { + Some(peer_register) => peer_register.register(&peer) as PeerID, + None => peer, + }, + counter, + container_type, + }, + r => r, + } +} + +fn convert_container_id( + container: ContainerID, + peers: &Option<Vec<PeerID>>, +) -> LoroResult<ContainerID> { + match container { + ContainerID::Normal { + peer, + counter, + container_type, + } => Ok(ContainerID::Normal { + peer: get_peer_from_peers(peers, peer)?, + counter, + container_type, + }), + r => Ok(r), + } +} + +pub(crate) fn get_peer_from_peers(peers: &Option<Vec<PeerID>>, peer: PeerID) -> LoroResult<PeerID> { + match peers { + Some(peers) => peers.get(peer as usize).copied().ok_or_else(|| { + LoroError::DecodeError("peer index out of range in compressed peer table".into()) + }), + None => Ok(peer), + } +} + +fn convert_id(id: &ID, peers: &Option<Vec<PeerID>>) -> LoroResult<ID> { + Ok(ID { + peer: get_peer_from_peers(peers, id.peer)?, + counter: id.counter, + }) +} + +fn convert_idlp(idlp: &IdLp, peers: &Option<Vec<PeerID>>) -> LoroResult<IdLp> { + Ok(IdLp { + lamport: idlp.lamport, + peer: get_peer_from_peers(peers, idlp.peer)?, + }) +} + +fn convert_tree_id(tree: &TreeID, peers: &Option<Vec<PeerID>>) -> LoroResult<TreeID> { + Ok(TreeID { + peer: get_peer_from_peers(peers, tree.peer)?, + counter: tree.counter, + }) +} +pub(crate) fn encode_change_to_json(change: ChangeRef<'_>, arena: &SharedArena) -> JsonSchema { + let f = change.deps.clone(); + let changes = vec![encode_change(change, arena, None)]; + JsonSchema { + changes, + schema_version: SCHEMA_VERSION, + peers: None, + start_version: f, + } +} + +fn encode_changes( + diff_changes: &[Either<BlockChangeRef, Change>], + arena: &SharedArena, + mut peer_register: Option<&mut ValueRegister<PeerID>>, +) -> Vec<json::JsonChange> { + let mut changes = Vec::with_capacity(diff_changes.len()); + for change in diff_changes.iter() { + let change: &Change = match change { + Either::Left(c) => c, + Either::Right(c) => c, + }; + let c = encode_change( + ChangeRef::from_change(change), + arena, + peer_register.as_deref_mut(), + ); + changes.push(c); + } + changes +} + +pub(crate) fn encode_change( + change: ChangeRef<'_, Op>, + arena: &SharedArena, + mut peer_register: Option<&mut ValueRegister<PeerID>>, +) -> JsonChange { + let mut ops = Vec::with_capacity(change.ops.len()); + for Op { + counter, + container, + content, + } in change.ops.iter() + { + let mut container = arena.get_container_id(*container).unwrap(); + if container.is_normal() { + container = register_container_id(container, peer_register.as_deref_mut()); + } + let op = match container.container_type() { + ContainerType::List => match content { + InnerContent::List(list) => JsonOpContent::List(match list { + InnerListOp::Insert { slice, pos } => { + let mut values = slice.as_slice().to_vec(); + values.iter_mut().for_each(|x| { + if let LoroValue::Container(id) = x { + if id.is_normal() { + *id = register_container_id( + id.clone(), + peer_register.as_deref_mut(), + ); + } + } + }); + json::ListOp::Insert { + pos: *pos as u32, + value: values, + } + } + InnerListOp::Delete(DeleteSpanWithId { + id_start, + span: DeleteSpan { pos, signed_len }, + }) => json::ListOp::Delete { + pos: *pos as i32, + len: *signed_len as i32, + start_id: register_id(id_start, peer_register.as_deref_mut()), + }, + _ => unreachable!(), + }), + _ => unreachable!(), + }, + ContainerType::MovableList => match content { + InnerContent::List(list) => JsonOpContent::MovableList(match list { + InnerListOp::Insert { slice, pos } => { + let mut values = slice.as_slice().to_vec(); + values.iter_mut().for_each(|x| { + if let LoroValue::Container(id) = x { + if id.is_normal() { + *id = register_container_id( + id.clone(), + peer_register.as_deref_mut(), + ); + } + } + }); + json::MovableListOp::Insert { + pos: *pos as u32, + value: values, + } + } + InnerListOp::Delete(DeleteSpanWithId { + id_start, + span: DeleteSpan { pos, signed_len }, + }) => json::MovableListOp::Delete { + pos: *pos as i32, + len: *signed_len as i32, + start_id: register_id(id_start, peer_register.as_deref_mut()), + }, + InnerListOp::Move { + from, + elem_id: from_id, + to, + } => json::MovableListOp::Move { + from: *from, + to: *to, + elem_id: register_idlp(from_id, peer_register.as_deref_mut()), + }, + InnerListOp::Set { elem_id, value } => { + let value = if let LoroValue::Container(id) = value { + if id.is_normal() { + LoroValue::Container(register_container_id( + id.clone(), + peer_register.as_deref_mut(), + )) + } else { + value.clone() + } + } else { + value.clone() + }; + json::MovableListOp::Set { + elem_id: register_idlp(elem_id, peer_register.as_deref_mut()), + value, + } + } + _ => unreachable!(), + }), + _ => unreachable!(), + }, + ContainerType::Text => match content { + InnerContent::List(list) => JsonOpContent::Text(match list { + InnerListOp::InsertText { + slice, + unicode_len: _, + pos, + } => { + let text = String::from_utf8(slice.as_bytes().to_vec()).unwrap(); + json::TextOp::Insert { pos: *pos, text } + } + InnerListOp::Delete(DeleteSpanWithId { + id_start, + span: DeleteSpan { pos, signed_len }, + }) => json::TextOp::Delete { + pos: *pos as i32, + len: *signed_len as i32, + start_id: register_id(id_start, peer_register.as_deref_mut()), + }, + InnerListOp::StyleStart { + start, + end, + key, + value, + info, + } => json::TextOp::Mark { + start: *start, + end: *end, + style_key: key.to_string(), + style_value: value.clone(), + info: info.to_byte(), + }, + InnerListOp::StyleEnd => json::TextOp::MarkEnd, + _ => unreachable!(), + }), + _ => unreachable!(), + }, + ContainerType::Map => match content { + InnerContent::Map(MapSet { key, value }) => { + JsonOpContent::Map(if let Some(v) = value { + let value = if let LoroValue::Container(id) = v { + if id.is_normal() { + LoroValue::Container(register_container_id( + id.clone(), + peer_register.as_deref_mut(), + )) + } else { + v.clone() + } + } else { + v.clone() + }; + json::MapOp::Insert { + key: key.to_string(), + value, + } + } else { + json::MapOp::Delete { + key: key.to_string(), + } + }) + } + + _ => unreachable!(), + }, + + ContainerType::Tree => match content { + InnerContent::Tree(op) => JsonOpContent::Tree(match &**op { + TreeOp::Create { + target, + parent, + position, + } => json::TreeOp::Create { + target: register_tree_id(target, peer_register.as_deref_mut()), + parent: parent.map(|p| register_tree_id(&p, peer_register.as_deref_mut())), + fractional_index: position.clone(), + }, + TreeOp::Move { + target, + parent, + position, + } => json::TreeOp::Move { + target: register_tree_id(target, peer_register.as_deref_mut()), + parent: parent.map(|p| register_tree_id(&p, peer_register.as_deref_mut())), + fractional_index: position.clone(), + }, + TreeOp::Delete { target } => json::TreeOp::Delete { + target: register_tree_id(target, peer_register.as_deref_mut()), + }, + }), + _ => unreachable!(), + }, + ContainerType::Unknown(_) => { + let InnerContent::Future(FutureInnerContent::Unknown { prop, value }) = content + else { + unreachable!(); + }; + JsonOpContent::Future(json::FutureOpWrapper { + prop: *prop, + value: json::FutureOp::Unknown((**value).clone()), + }) + } + #[cfg(feature = "counter")] + ContainerType::Counter => { + let InnerContent::Future(f) = content else { + unreachable!() + }; + match f { + FutureInnerContent::Counter(x) => { + JsonOpContent::Future(json::FutureOpWrapper { + prop: 0, + value: json::FutureOp::Counter(super::OwnedValue::F64(*x)), + }) + } + _ => unreachable!(), + } + } + }; + ops.push(json::JsonOp { + counter: *counter, + container, + content: op, + }); + } + let c = json::JsonChange { + id: register_id(change.id, peer_register.as_deref_mut()), + ops, + deps: change + .deps + .iter() + // Make sure the order is deterministic + .sorted() + .map(|id| register_id(&id, peer_register.as_deref_mut())) + .collect(), + lamport: *change.lamport, + timestamp: *change.timestamp, + msg: change.commit_msg.as_deref().map(|x| x.to_string()), + }; + c +} + +fn decode_changes(json: JsonSchema, arena: &SharedArena) -> LoroResult<Vec<Change>> { + let JsonSchema { + schema_version, + start_version, + peers, + changes, + } = json; + if schema_version != SCHEMA_VERSION { + return Err(LoroError::DecodeError( + format!( + "unsupported json schema version: expected {SCHEMA_VERSION}, got {schema_version}" + ) + .into_boxed_str(), + )); + } + validate_json_frontiers(&start_version)?; + + let mut ans = Vec::with_capacity(changes.len()); + for json::JsonChange { + id, + timestamp, + deps, + lamport, + msg, + ops: json_ops, + } in changes + { + let id = convert_id(&id, &peers)?; + validate_json_id_counter(id, "change id")?; + let mut ops: RleVec<[Op; 1]> = RleVec::new(); + let mut expected_counter = id.counter; + if json_ops.is_empty() { + return Err(LoroError::DecodeError( + "invalid json change: change must contain at least one op".into(), + )); + } + + for op in json_ops { + let next_counter = validate_json_op_counter(expected_counter, &op)?; + let op = decode_op(op, arena, &peers)?; + validate_json_op_created_container_ids(id.peer, &op)?; + ops.push(op); + expected_counter = next_counter; + } + + let deps = deps + .into_iter() + .map(|id| convert_id(&id, &peers)) + .collect::<LoroResult<Vec<_>>>()?; + for dep in &deps { + validate_json_id_counter(*dep, "dependency id")?; + } + + let change = Change { + id, + timestamp, + deps: Frontiers::from_iter(deps), + lamport, + ops, + commit_msg: msg.map(|x| x.into()), + }; + ans.push(change); + } + Ok(ans) +} + +fn validate_json_frontiers(frontiers: &Frontiers) -> LoroResult<()> { + for id in frontiers.iter() { + validate_json_id_counter(id, "start version id")?; + } + + Ok(()) +} + +fn validate_json_id_counter(id: ID, name: &str) -> LoroResult<()> { + if id.counter < 0 { + return Err(LoroError::DecodeError( + format!("invalid json counter: {name} counter must be non-negative").into_boxed_str(), + )); + } + + Ok(()) +} + +fn validate_json_tree_id_counter(id: &TreeID, name: &str) -> LoroResult<()> { + if id.counter < 0 { + return Err(LoroError::DecodeError( + format!("invalid json counter: {name} counter must be non-negative").into_boxed_str(), + )); + } + + Ok(()) +} + +fn validate_json_container_id_counter(id: &ContainerID, name: &str) -> LoroResult<()> { + if let ContainerID::Normal { counter, .. } = id { + if *counter < 0 { + return Err(LoroError::DecodeError( + format!("invalid json counter: {name} counter must be non-negative") + .into_boxed_str(), + )); + } + } + + Ok(()) +} + +fn validate_json_op_counter(expected_counter: Counter, op: &json::JsonOp) -> LoroResult<Counter> { + let op_len = op.content.op_len(); + if op_len == 0 { + return Err(LoroError::DecodeError( + "invalid json op counter: op length must be greater than zero".into(), + )); + } + + if expected_counter < 0 || op.counter < 0 { + return Err(LoroError::DecodeError( + "invalid json op counter: op counters must be non-negative".into(), + )); + } + + let op_len = Counter::try_from(op_len).map_err(|_| { + LoroError::DecodeError("invalid json op counter: op length is too large".into()) + })?; + if op.counter != expected_counter { + return Err(LoroError::DecodeError( + "invalid json op counter: op counters must be contiguous with the change id".into(), + )); + } + + expected_counter + .checked_add(op_len) + .ok_or_else(|| LoroError::DecodeError("invalid json op counter: counter overflow".into())) +} + +fn validate_json_op_created_container_ids(peer: PeerID, op: &Op) -> LoroResult<()> { + match &op.content { + InnerContent::List(list) => match list { + InnerListOp::Insert { slice, .. } => { + for (offset, value) in slice.as_slice().iter().enumerate() { + let LoroValue::Container(id) = value else { + validate_json_value_has_no_container_refs(value)?; + continue; + }; + let offset = Counter::try_from(offset).map_err(|_| { + LoroError::DecodeError( + "invalid json container id: list offset is too large".into(), + ) + })?; + let counter = op.counter.checked_add(offset).ok_or_else(|| { + LoroError::DecodeError("invalid json container id: counter overflow".into()) + })?; + validate_json_created_container_id(id, ID::new(peer, counter))?; + } + } + InnerListOp::Set { value, .. } => { + if let LoroValue::Container(id) = value { + validate_json_created_container_id(id, ID::new(peer, op.counter))?; + } else { + validate_json_value_has_no_container_refs(value)?; + } + } + InnerListOp::Move { .. } + | InnerListOp::InsertText { .. } + | InnerListOp::Delete(_) + | InnerListOp::StyleEnd => {} + InnerListOp::StyleStart { value, .. } => { + validate_json_value_has_no_container_refs(value)?; + } + }, + InnerContent::Map(map) => { + if let Some(value) = &map.value { + if let LoroValue::Container(id) = value { + validate_json_created_container_id(id, ID::new(peer, op.counter))?; + } else { + validate_json_value_has_no_container_refs(value)?; + } + } + } + InnerContent::Tree(tree) => { + if let TreeOp::Create { target, .. } = tree.as_ref() { + validate_json_tree_create_target(target, ID::new(peer, op.counter))?; + } + } + InnerContent::Future(_) => {} + } + + Ok(()) +} + +fn validate_json_value_has_no_container_refs(value: &LoroValue) -> LoroResult<()> { + let mut stack = vec![value]; + while let Some(value) = stack.pop() { + match value { + LoroValue::Container(_) => { + return Err(LoroError::DecodeError( + "invalid json container id: container values must not be nested".into(), + )); + } + LoroValue::List(list) => { + stack.extend(list.iter()); + } + LoroValue::Map(map) => { + stack.extend(map.values()); + } + LoroValue::Null + | LoroValue::Bool(_) + | LoroValue::Double(_) + | LoroValue::I64(_) + | LoroValue::Binary(_) + | LoroValue::String(_) => {} + } + } + + Ok(()) +} + +fn validate_json_created_container_id(id: &ContainerID, expected_id: ID) -> LoroResult<()> { + let ContainerID::Normal { peer, counter, .. } = id else { + return Err(LoroError::DecodeError( + "invalid json container id: created child containers must be normal".into(), + )); + }; + + if *peer != expected_id.peer || *counter != expected_id.counter { + return Err(LoroError::DecodeError( + "invalid json container id: created child container id must match the op id".into(), + )); + } + + Ok(()) +} + +fn validate_json_tree_create_target(target: &TreeID, expected_id: ID) -> LoroResult<()> { + if target.peer != expected_id.peer || target.counter != expected_id.counter { + return Err(LoroError::DecodeError( + "invalid json tree target: tree create target must match the op id".into(), + )); + } + + Ok(()) +} + +fn decode_op(op: json::JsonOp, arena: &SharedArena, peers: &Option<Vec<PeerID>>) -> LoroResult<Op> { + let json::JsonOp { + counter, + container, + content, + } = op; + let container = convert_container_id(container, peers)?; + validate_json_container_id_counter(&container, "op container")?; + let idx = arena.register_container(&container); + let content = match container.container_type() { + ContainerType::Text => match content { + JsonOpContent::Text(text) => match text { + json::TextOp::Insert { pos, text } => { + let (slice, result) = arena.alloc_str_with_slice(&text); + InnerContent::List(InnerListOp::InsertText { + slice, + unicode_len: (result.end - result.start) as u32, + pos, + }) + } + json::TextOp::Delete { + pos, + len, + start_id: id_start, + } => { + let id_start = convert_id(&id_start, peers)?; + validate_json_id_counter(id_start, "text delete start id")?; + InnerContent::List(InnerListOp::Delete(DeleteSpanWithId { + id_start, + span: DeleteSpan { + pos: pos as isize, + signed_len: len as isize, + }, + })) + } + json::TextOp::Mark { + start, + end, + style_key, + style_value, + info, + } => InnerContent::List(InnerListOp::StyleStart { + start, + end, + key: style_key.into(), + value: style_value, + info: TextStyleInfoFlag::from_byte(info), + }), + json::TextOp::MarkEnd => InnerContent::List(InnerListOp::StyleEnd), + }, + _ => { + return Err(LoroError::DecodeError( + "invalid op content for text container".into(), + )) + } + }, + ContainerType::List => match content { + JsonOpContent::List(list) => match list { + json::ListOp::Insert { + pos, + value: mut values, + } => { + for v in values.iter_mut() { + if let LoroValue::Container(id) = v { + if id.is_normal() { + *id = convert_container_id(id.clone(), peers)?; + } + } + } + InnerContent::List(InnerListOp::Insert { + slice: ValueSlice::new(values), + pos: pos as usize, + }) + } + json::ListOp::Delete { pos, len, start_id } => { + let start_id = convert_id(&start_id, peers)?; + validate_json_id_counter(start_id, "list delete start id")?; + InnerContent::List(InnerListOp::Delete(DeleteSpanWithId { + id_start: start_id, + span: DeleteSpan { + pos: pos as isize, + signed_len: len as isize, + }, + })) + } + }, + _ => { + return Err(LoroError::DecodeError( + "invalid op content for list container".into(), + )) + } + }, + ContainerType::MovableList => match content { + JsonOpContent::MovableList(list) => match list { + json::MovableListOp::Insert { + pos, + value: mut values, + } => { + for v in values.iter_mut() { + if let LoroValue::Container(id) = v { + if id.is_normal() { + *id = convert_container_id(id.clone(), peers)?; + } + } + } + InnerContent::List(InnerListOp::Insert { + slice: ValueSlice::new(values), + pos: pos as usize, + }) + } + json::MovableListOp::Delete { pos, len, start_id } => { + let start_id = convert_id(&start_id, peers)?; + validate_json_id_counter(start_id, "movable list delete start id")?; + InnerContent::List(InnerListOp::Delete(DeleteSpanWithId { + id_start: start_id, + span: DeleteSpan { + pos: pos as isize, + signed_len: len as isize, + }, + })) + } + json::MovableListOp::Move { + from, + elem_id: from_id, + to, + } => { + let from_id = convert_idlp(&from_id, peers)?; + InnerContent::List(InnerListOp::Move { + from, + elem_id: from_id, + to, + }) + } + json::MovableListOp::Set { elem_id, mut value } => { + let elem_id = convert_idlp(&elem_id, peers)?; + if let LoroValue::Container(id) = &mut value { + *id = convert_container_id(id.clone(), peers)?; + } + InnerContent::List(InnerListOp::Set { elem_id, value }) + } + }, + _ => { + return Err(LoroError::DecodeError( + "invalid op content for movable list container".into(), + )) + } + }, + ContainerType::Map => match content { + JsonOpContent::Map(map) => match map { + json::MapOp::Insert { key, mut value } => { + if let LoroValue::Container(id) = &mut value { + *id = convert_container_id(id.clone(), peers)?; + } + InnerContent::Map(MapSet { + key: key.into(), + value: Some(value), + }) + } + json::MapOp::Delete { key } => InnerContent::Map(MapSet { + key: key.into(), + value: None, + }), + }, + _ => { + return Err(LoroError::DecodeError( + "invalid op content for map container".into(), + )) + } + }, + ContainerType::Tree => match content { + JsonOpContent::Tree(tree) => match tree { + json::TreeOp::Create { + target, + parent, + fractional_index, + } => { + let target = convert_tree_id(&target, peers)?; + validate_json_tree_id_counter(&target, "tree create target")?; + let parent = match parent { + Some(p) => { + let parent = convert_tree_id(&p, peers)?; + validate_json_tree_id_counter(&parent, "tree create parent")?; + Some(parent) + } + None => None, + }; + InnerContent::Tree(Arc::new(TreeOp::Create { + target, + parent, + position: fractional_index, + })) + } + json::TreeOp::Move { + target, + parent, + fractional_index, + } => { + let target = convert_tree_id(&target, peers)?; + validate_json_tree_id_counter(&target, "tree move target")?; + let parent = match parent { + Some(p) => { + let parent = convert_tree_id(&p, peers)?; + validate_json_tree_id_counter(&parent, "tree move parent")?; + Some(parent) + } + None => None, + }; + InnerContent::Tree(Arc::new(TreeOp::Move { + target, + parent, + position: fractional_index, + })) + } + json::TreeOp::Delete { target } => { + let target = convert_tree_id(&target, peers)?; + validate_json_tree_id_counter(&target, "tree delete target")?; + InnerContent::Tree(Arc::new(TreeOp::Delete { target })) + } + }, + _ => { + return Err(LoroError::DecodeError( + "invalid op content for tree container".into(), + )) + } + }, + ContainerType::Unknown(_) => match content { + JsonOpContent::Future(json::FutureOpWrapper { + prop, + value: json::FutureOp::Unknown(value), + }) => InnerContent::Future(FutureInnerContent::Unknown { + prop, + value: Box::new(value), + }), + _ => { + return Err(LoroError::DecodeError( + "invalid op content for unknown container".into(), + )) + } + }, + #[cfg(feature = "counter")] + ContainerType::Counter => { + let JsonOpContent::Future(json::FutureOpWrapper { prop: _, value }) = content else { + return Err(LoroError::DecodeError( + "invalid op content for counter container".into(), + )); + }; + use crate::encoding::OwnedValue; + match value { + json::FutureOp::Counter(OwnedValue::F64(c)) + | json::FutureOp::Unknown(OwnedValue::F64(c)) => { + InnerContent::Future(FutureInnerContent::Counter(c)) + } + json::FutureOp::Counter(OwnedValue::I64(c)) + | json::FutureOp::Unknown(OwnedValue::I64(c)) => { + InnerContent::Future(FutureInnerContent::Counter(c as f64)) + } + _ => { + return Err(LoroError::DecodeError( + "invalid counter op value type".into(), + )) + } + } + } // Note: The Future Type need try to parse Op from the unknown content + }; + if let InnerContent::List(list_op) = &content { + list_op.check_positions()?; + } + Ok(Op { + counter, + container: idx, + content, + }) +} + +impl TryFrom<&str> for JsonSchema { + type Error = serde_json::Error; + + fn try_from(value: &str) -> Result<Self, Self::Error> { + serde_json::from_str(value) + } +} + +impl TryFrom<&String> for JsonSchema { + type Error = serde_json::Error; + + fn try_from(value: &String) -> Result<Self, Self::Error> { + serde_json::from_str(value) + } +} + +impl TryFrom<String> for JsonSchema { + type Error = serde_json::Error; + + fn try_from(value: String) -> Result<Self, Self::Error> { + serde_json::from_str(&value) + } +} + +pub mod json { + use crate::{ + encoding::OwnedValue, + version::{Frontiers, VersionRange}, + }; + use fractional_index::FractionalIndex; + use loro_common::{ContainerID, Counter, IdLp, Lamport, LoroValue, PeerID, TreeID, ID}; + use serde::{Deserialize, Serialize}; + use std::ops::Range; + + use super::{get_peer_from_peers, redact_value}; + + #[derive(Debug, Clone, Serialize, Deserialize)] + pub struct JsonSchema { + pub schema_version: u8, + #[serde(with = "self::serde_impl::frontiers")] + pub start_version: Frontiers, + #[serde(with = "self::serde_impl::peer_id")] + pub peers: Option<Vec<PeerID>>, + pub changes: Vec<JsonChange>, + } + + #[derive(Debug, Clone, Serialize, Deserialize)] + pub struct JsonChange { + #[serde(with = "self::serde_impl::id")] + pub id: ID, + pub timestamp: i64, + #[serde(with = "self::serde_impl::deps")] + pub deps: Vec<ID>, + pub lamport: Lamport, + pub msg: Option<String>, + pub ops: Vec<JsonOp>, + } + + impl JsonChange { + pub fn checked_op_len(&self) -> Option<usize> { + let Some(last_op) = self.ops.last() else { + return Some(0); + }; + if last_op.counter < self.id.counter { + return None; + } + + let counter_delta = last_op.counter.checked_sub(self.id.counter)?; + let counter_delta = usize::try_from(counter_delta).ok()?; + counter_delta.checked_add(last_op.content.op_len()) + } + + pub fn op_len(&self) -> usize { + self.checked_op_len().unwrap_or(0) + } + } + + #[derive(Debug, Clone)] + pub struct JsonOp { + pub content: JsonOpContent, + pub container: ContainerID, + pub counter: i32, + } + + #[derive(Debug, Clone, Serialize, Deserialize)] + #[serde(untagged)] + pub enum JsonOpContent { + List(ListOp), + MovableList(MovableListOp), + Map(MapOp), + Text(TextOp), + Tree(TreeOp), + // #[serde(with = "self::serde_impl::future_op")] + Future(FutureOpWrapper), + } + + impl JsonOpContent { + pub fn op_len(&self) -> usize { + match self { + JsonOpContent::List(list_op) => list_op.op_len(), + JsonOpContent::MovableList(movable_list_op) => movable_list_op.op_len(), + JsonOpContent::Map(..) => 1, + JsonOpContent::Text(text_op) => text_op.op_len(), + JsonOpContent::Tree(..) => 1, + JsonOpContent::Future(..) => 1, + } + } + } + + #[derive(Debug, Clone, Serialize, Deserialize)] + pub struct FutureOpWrapper { + #[serde(flatten)] + pub value: FutureOp, + pub prop: i32, + } + + #[derive(Debug, Clone, Serialize, Deserialize)] + #[serde(tag = "type", rename_all = "snake_case")] + pub enum ListOp { + Insert { + pos: u32, + value: Vec<LoroValue>, + }, + Delete { + pos: i32, + len: i32, + #[serde(with = "self::serde_impl::id")] + start_id: ID, + }, + } + + impl ListOp { + fn op_len(&self) -> usize { + match self { + ListOp::Insert { value: values, .. } => values.len(), + ListOp::Delete { len, .. } => (*len).unsigned_abs() as usize, + } + } + } + + #[derive(Debug, Clone, Serialize, Deserialize)] + #[serde(tag = "type", rename_all = "snake_case")] + pub enum MovableListOp { + Insert { + pos: u32, + value: Vec<LoroValue>, + }, + Delete { + pos: i32, + len: i32, + #[serde(with = "self::serde_impl::id")] + start_id: ID, + }, + Move { + from: u32, + to: u32, + #[serde(with = "self::serde_impl::idlp")] + elem_id: IdLp, + }, + Set { + #[serde(with = "self::serde_impl::idlp")] + elem_id: IdLp, + value: LoroValue, + }, + } + + impl MovableListOp { + fn op_len(&self) -> usize { + match self { + MovableListOp::Insert { value: values, .. } => values.len(), + MovableListOp::Delete { len, .. } => (*len).unsigned_abs() as usize, + MovableListOp::Move { .. } => 1, + MovableListOp::Set { .. } => 1, + } + } + } + + #[derive(Debug, Clone, Serialize, Deserialize)] + #[serde(tag = "type", rename_all = "snake_case")] + pub enum MapOp { + Insert { key: String, value: LoroValue }, + Delete { key: String }, + } + + #[derive(Debug, Clone, Serialize, Deserialize)] + #[serde(tag = "type", rename_all = "snake_case")] + pub enum TextOp { + Insert { + pos: u32, + text: String, + }, + Delete { + pos: i32, + len: i32, + #[serde(with = "self::serde_impl::id")] + start_id: ID, + }, + Mark { + start: u32, + end: u32, + style_key: String, + style_value: LoroValue, + info: u8, + }, + MarkEnd, + } + + impl TextOp { + fn op_len(&self) -> usize { + match self { + TextOp::Insert { text, .. } => text.chars().count(), + TextOp::Delete { len, .. } => len.unsigned_abs() as usize, + TextOp::Mark { .. } => 1, + TextOp::MarkEnd => 1, + } + } + } + + #[derive(Debug, Clone, Serialize, Deserialize)] + #[serde(tag = "type", rename_all = "snake_case")] + pub enum TreeOp { + Create { + #[serde(with = "self::serde_impl::tree_id")] + target: TreeID, + #[serde(with = "self::serde_impl::option_tree_id")] + parent: Option<TreeID>, + #[serde(default, with = "self::serde_impl::fractional_index")] + fractional_index: FractionalIndex, + }, + Move { + #[serde(with = "self::serde_impl::tree_id")] + target: TreeID, + #[serde(with = "self::serde_impl::option_tree_id")] + parent: Option<TreeID>, + #[serde(default, with = "self::serde_impl::fractional_index")] + fractional_index: FractionalIndex, + }, + Delete { + #[serde(with = "self::serde_impl::tree_id")] + target: TreeID, + }, + } + + #[derive(Debug, Clone, Serialize, Deserialize)] + #[serde(tag = "type", rename_all = "snake_case")] + pub enum FutureOp { + #[cfg(feature = "counter")] + Counter(OwnedValue), + Unknown(OwnedValue), + } + + mod serde_impl { + + use loro_common::{ContainerID, ContainerType}; + use serde::{ + de::{Error, IgnoredAny, MapAccess, Visitor}, + ser::SerializeStruct, + Deserialize, Deserializer, Serialize, Serializer, + }; + + #[allow(unused_imports)] + use crate::encoding::OwnedValue; + + impl Serialize for super::JsonOp { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + let mut s = serializer.serialize_struct("Op", 3)?; + s.serialize_field("container", &self.container.to_string())?; + s.serialize_field("content", &self.content)?; + s.serialize_field("counter", &self.counter)?; + s.end() + } + } + + impl<'de> Deserialize<'de> for super::JsonOp { + fn deserialize<D>(deserializer: D) -> Result<super::JsonOp, D::Error> + where + D: Deserializer<'de>, + { + struct __Visitor; + + impl<'de> Visitor<'de> for __Visitor { + type Value = super::JsonOp; + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("struct Op") + } + + fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> + where + A: MapAccess<'de>, + { + let mut container = None; + let mut content = None; + let mut counter = None; + + while let Some(key) = map.next_key::<String>()? { + match key.as_str() { + "container" => { + if container.is_some() { + return Err(A::Error::duplicate_field("container")); + } + let value = map.next_value::<String>()?; + container = + Some(ContainerID::try_from(value.as_str()).map_err( + |_| A::Error::custom("invalid container id"), + )?); + } + "content" => { + if content.is_some() { + return Err(A::Error::duplicate_field("content")); + } + content = Some(map.next_value::<serde_json::Value>()?); + } + "counter" => { + if counter.is_some() { + return Err(A::Error::duplicate_field("counter")); + } + counter = Some(map.next_value::<i32>()?); + } + _ => { + let _ = map.next_value::<IgnoredAny>()?; + } + } + } + + let container = + container.ok_or_else(|| A::Error::missing_field("container"))?; + let content = content.ok_or_else(|| A::Error::missing_field("content"))?; + let op = json_op_content_from_value(&container, content)?; + let counter = counter.ok_or_else(|| A::Error::missing_field("counter"))?; + Ok(super::JsonOp { + container, + content: op, + counter, + }) + } + } + const FIELDS: &[&str] = &["container", "content", "counter"]; + deserializer.deserialize_struct("JsonOp", FIELDS, __Visitor) + } + } + + fn json_op_content_from_value<E: Error>( + container: &ContainerID, + value: serde_json::Value, + ) -> Result<super::JsonOpContent, E> { + match container.container_type() { + ContainerType::List => serde_json::from_value(value) + .map(super::JsonOpContent::List) + .map_err(E::custom), + ContainerType::MovableList => serde_json::from_value(value) + .map(super::JsonOpContent::MovableList) + .map_err(E::custom), + ContainerType::Map => serde_json::from_value(value) + .map(super::JsonOpContent::Map) + .map_err(E::custom), + ContainerType::Text => serde_json::from_value(value) + .map(super::JsonOpContent::Text) + .map_err(E::custom), + ContainerType::Tree => serde_json::from_value(value) + .map(super::JsonOpContent::Tree) + .map_err(E::custom), + ContainerType::Unknown(_) => serde_json::from_value(value) + .map(super::JsonOpContent::Future) + .map_err(E::custom), + #[cfg(feature = "counter")] + ContainerType::Counter => { + match serde_json::from_value::<super::FutureOpWrapper>(value.clone()) { + Ok(op) => Ok(super::JsonOpContent::Future(op)), + Err(_) => { + let value = + serde_json::from_value::<OwnedValue>(value).map_err(E::custom)?; + Ok(super::JsonOpContent::Future(super::FutureOpWrapper { + prop: 0, + value: super::FutureOp::Counter(value), + })) + } + } + } + } + } + + pub mod id { + use loro_common::ID; + use serde::{Deserialize, Deserializer, Serializer}; + + pub fn serialize<S>(id: &ID, s: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + s.serialize_str(&id.to_string()) + } + + pub fn deserialize<'de, 'a, D>(d: D) -> Result<ID, D::Error> + where + D: Deserializer<'de>, + { + // NOTE: https://github.com/serde-rs/serde/issues/2467 we use String here + let str: String = Deserialize::deserialize(d)?; + let id: ID = ID::try_from(str.as_str()) + .map_err(|_| serde::de::Error::custom("invalid ID format"))?; + Ok(id) + } + } + + pub mod frontiers { + use itertools::Itertools; + use loro_common::ID; + use serde::{ser::SerializeMap, Deserializer, Serializer}; + + use crate::version::Frontiers; + + pub fn serialize<S>(f: &Frontiers, s: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + let mut map = s.serialize_map(Some(f.len()))?; + for id in f + .iter() + // Make sure the order is deterministic + .sorted() + { + map.serialize_entry(&id.peer.to_string(), &id.counter)?; + } + map.end() + } + + pub fn deserialize<'de, 'a, D>(d: D) -> Result<Frontiers, D::Error> + where + D: Deserializer<'de>, + { + struct __Visitor; + impl<'de> serde::de::Visitor<'de> for __Visitor { + type Value = Frontiers; + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("a Frontiers") + } + + fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> + where + A: serde::de::MapAccess<'de>, + { + let mut f = Frontiers::default(); + while let Some((k, v)) = map.next_entry::<String, i32>()? { + f.push(ID::new( + k.parse().map_err(|_| { + serde::de::Error::custom("invalid peer id in frontiers") + })?, + v, + )) + } + Ok(f) + } + } + d.deserialize_map(__Visitor) + } + } + + pub mod deps { + use loro_common::ID; + use serde::{Deserialize, Deserializer, Serializer}; + + pub fn serialize<S>(deps: &[ID], s: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + s.collect_seq(deps.iter().map(|x| x.to_string())) + } + + pub fn deserialize<'de, 'a, D>(d: D) -> Result<Vec<ID>, D::Error> + where + D: Deserializer<'de>, + { + let deps: Vec<String> = Deserialize::deserialize(d)?; + deps.into_iter() + .map(|x| { + ID::try_from(x.as_str()) + .map_err(|_| serde::de::Error::custom("invalid ID in deps")) + }) + .collect::<Result<Vec<_>, _>>() + } + } + + pub mod peer_id { + use loro_common::PeerID; + use serde::{Deserialize, Deserializer, Serializer}; + + pub fn serialize<S>(peers: &Option<Vec<PeerID>>, s: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + match peers { + Some(peers) => s.collect_seq(peers.iter().map(|x| x.to_string())), + None => s.serialize_none(), + } + } + + pub fn deserialize<'de, 'a, D>(d: D) -> Result<Option<Vec<PeerID>>, D::Error> + where + D: Deserializer<'de>, + { + let peers: Option<Vec<String>> = Deserialize::deserialize(d)?; + peers + .map(|x| { + x.into_iter() + .map(|x| { + x.parse() + .map_err(|_| serde::de::Error::custom("invalid peer id")) + }) + .collect::<Result<Vec<_>, _>>() + }) + .transpose() + } + } + + pub mod idlp { + use loro_common::IdLp; + use serde::{Deserialize, Deserializer, Serializer}; + + pub fn serialize<S>(idlp: &IdLp, s: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + s.serialize_str(&idlp.to_string()) + } + + pub fn deserialize<'de, 'a, D>(d: D) -> Result<IdLp, D::Error> + where + D: Deserializer<'de>, + { + let str: String = Deserialize::deserialize(d)?; + let id: IdLp = IdLp::try_from(str.as_str()) + .map_err(|_| serde::de::Error::custom("invalid IdLp format"))?; + Ok(id) + } + } + + pub mod tree_id { + use loro_common::TreeID; + use serde::{Deserialize, Deserializer, Serializer}; + + pub fn serialize<S>(id: &TreeID, s: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + s.serialize_str(&id.to_string()) + } + + pub fn deserialize<'de, 'a, D>(d: D) -> Result<TreeID, D::Error> + where + D: Deserializer<'de>, + { + let str: String = Deserialize::deserialize(d)?; + let id: TreeID = TreeID::try_from(str.as_str()) + .map_err(|_| serde::de::Error::custom("invalid TreeID format"))?; + Ok(id) + } + } + + pub mod option_tree_id { + use loro_common::TreeID; + use serde::{Deserialize, Deserializer, Serializer}; + + pub fn serialize<S>(id: &Option<TreeID>, s: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + match id { + Some(id) => s.serialize_str(&id.to_string()), + None => s.serialize_none(), + } + } + + pub fn deserialize<'de, 'a, D>(d: D) -> Result<Option<TreeID>, D::Error> + where + D: Deserializer<'de>, + { + let str: Option<String> = Deserialize::deserialize(d)?; + match str { + Some(str) => { + let id: TreeID = TreeID::try_from(str.as_str()) + .map_err(|_| serde::de::Error::custom("invalid TreeID format"))?; + Ok(Some(id)) + } + None => Ok(None), + } + } + } + + pub mod fractional_index { + use fractional_index::FractionalIndex; + use serde::{Deserialize, Deserializer, Serializer}; + + pub fn serialize<S>(fi: &FractionalIndex, s: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + s.serialize_str(&fi.to_string()) + } + + pub fn deserialize<'de, 'a, D>(d: D) -> Result<FractionalIndex, D::Error> + where + D: Deserializer<'de>, + { + let str: String = Deserialize::deserialize(d)?; + if !str.len().is_multiple_of(2) { + return Err(serde::de::Error::custom( + "invalid fractional index hex length", + )); + } + + let mut bytes = Vec::with_capacity(str.len() / 2); + for i in 0..str.len() / 2 { + let byte = u8::from_str_radix(&str[i * 2..i * 2 + 2], 16).map_err(|e| { + serde::de::Error::custom(format!("invalid fractional index hex: {e}")) + })?; + bytes.push(byte); + } + + Ok(FractionalIndex::from_bytes(bytes)) + } + } + } + + #[derive(thiserror::Error, Debug, PartialEq, Eq)] + pub enum RedactError { + #[error("unknown operation type")] + UnknownOperationType, + #[error("invalid schema: {0}")] + InvalidSchema(String), + } + + fn invalid_schema(message: impl Into<String>) -> RedactError { + RedactError::InvalidSchema(message.into()) + } + + fn checked_redact_op_len(op: &JsonOp) -> Result<Counter, RedactError> { + let len = op.content.op_len(); + if len == 0 { + return Err(invalid_schema("op length must be greater than zero")); + } + + Counter::try_from(len).map_err(|_| invalid_schema("op length is too large")) + } + + fn validate_redactable_change(change: &JsonChange) -> Result<usize, RedactError> { + if change.id.counter < 0 { + return Err(invalid_schema("change id counter must be non-negative")); + } + + let mut expected_counter = change.id.counter; + for op in &change.ops { + if op.counter < 0 { + return Err(invalid_schema("op counter must be non-negative")); + } + if op.counter != expected_counter { + return Err(invalid_schema( + "op counters must be contiguous with the change id", + )); + } + + let len = checked_redact_op_len(op)?; + expected_counter = expected_counter + .checked_add(len) + .ok_or_else(|| invalid_schema("op counter overflow"))?; + } + + let len = expected_counter + .checked_sub(change.id.counter) + .ok_or_else(|| invalid_schema("change counter overflow"))?; + usize::try_from(len).map_err(|_| invalid_schema("change length is too large")) + } + + /// Redacts sensitive content within the specified range by replacing it with default values. + /// + /// This method applies the following redaction rules: + /// + /// - Preserves delete and move operations without changes + /// - Replaces text insertion content with the Unicode replacement character (U+FFFD) + /// - Substitutes list and map insert values with `LoroValue::Null` + /// - Maintains child container creation operations + /// - Replaces text mark values with `LoroValue::Null` + /// - Preserves map insertion and text annotation keys + /// - Resets counter operations to zero + /// - Leaves unknown operation types (from future Loro versions) unchanged + /// + /// This approach ensures sensitive data removal while preserving the document's overall + /// structure. Redacted documents maintain seamless collaboration capabilities with both + /// redacted and non-redacted versions. + pub fn redact(json: &mut JsonSchema, range: VersionRange) -> Result<(), RedactError> { + let peers = json.peers.clone(); + let mut errors = Vec::new(); + for change in json.changes.iter_mut() { + let real_peer = get_peer_from_peers(&peers, change.id.peer) + .map_err(|_| RedactError::InvalidSchema("peer index out of range".to_string()))?; + let real_id = ID::new(real_peer, change.id.counter); + let change_len = validate_redactable_change(change)?; + if !range.has_overlap_with(real_id.to_span(change_len)) { + continue; + } + + let redact_range = range.get(&real_peer).copied().unwrap(); + for op in change.ops.iter_mut() { + if op.counter >= redact_range.1 { + break; + } + + let len = checked_redact_op_len(op)?; + let op_end = op + .counter + .checked_add(len) + .ok_or_else(|| invalid_schema("op counter overflow"))?; + if op_end <= redact_range.0 { + continue; + } + + let result = redact_op( + &mut op.content, + redact_range.0.saturating_sub(op.counter).max(0).min(len) + ..redact_range.1.saturating_sub(op.counter).max(0).min(len), + ); + match result { + Ok(()) => {} + Err(e) => errors.push(e), + } + } + } + + if errors.is_empty() { + Ok(()) + } else { + Err(errors.pop().unwrap()) + } + } + + fn redact_op(op: &mut JsonOpContent, range: Range<Counter>) -> Result<(), RedactError> { + match op { + JsonOpContent::List(list_op) => { + match list_op { + ListOp::Insert { value: values, .. } => { + for i in range { + redact_value(&mut values[i as usize]); + } + } + ListOp::Delete { .. } => { + // Delete op won't be changed + } + } + } + JsonOpContent::MovableList(movable_list_op) => { + match movable_list_op { + MovableListOp::Insert { value: values, .. } => { + for i in range { + redact_value(&mut values[i as usize]); + } + } + MovableListOp::Delete { .. } | MovableListOp::Move { .. } => { + // Delete and move ops won't be changed + } + MovableListOp::Set { value, .. } => { + assert!(range.start == 0 && range.len() == 1); + redact_value(value); + } + } + } + JsonOpContent::Map(map_op) => { + match map_op { + MapOp::Insert { value, .. } => { + assert!(range.start == 0 && range.len() == 1); + redact_value(value); + } + MapOp::Delete { .. } => { + // Delete op won't be changed + } + } + } + JsonOpContent::Text(text_op) => { + match text_op { + TextOp::Insert { text, .. } => { + let mut chars = vec![]; + for (i, c) in text.chars().enumerate() { + if i < range.start as usize || i >= range.end as usize { + chars.push(c); + } else { + chars.push("� ".chars().next().unwrap()); + } + } + *text = chars.into_iter().collect(); + } + TextOp::Delete { .. } => { + // Delete op won't be changed + } + TextOp::Mark { style_value, .. } => { + assert!(range.start == 0 && range.len() == 1); + *style_value = LoroValue::Null; + } + TextOp::MarkEnd => { + // MarkEnd won't be changed + } + } + } + JsonOpContent::Tree(..) => { + // Creation of child container won't be changed + } + JsonOpContent::Future(future_op_wrapper) => match &mut future_op_wrapper.value { + #[cfg(feature = "counter")] + FutureOp::Counter(owned_value) => { + *owned_value = OwnedValue::I64(0); + } + FutureOp::Unknown(..) => { + return Err(RedactError::UnknownOperationType); + } + }, + } + + Ok(()) + } +} + +fn redact_value(v: &mut LoroValue) { + match v { + LoroValue::Container(_) => {} + _ => *v = LoroValue::Null, + } +} + +#[cfg(test)] +mod tests { + use crate::{LoroDoc, VersionVector}; + + #[test] + fn json_range_version() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(0).unwrap(); + let list = doc.get_list("list"); + list.insert(0, "a").unwrap(); + list.insert(0, "b").unwrap(); + list.insert(0, "c").unwrap(); + let json = doc + .export_json_updates( + &VersionVector::from_iter(vec![(0, 1)]), + &VersionVector::from_iter(vec![(0, 2)]), + true, + ) + .unwrap(); + assert_eq!(json.changes[0].ops.len(), 1); + let json = doc + .export_json_updates( + &VersionVector::from_iter(vec![(0, 0)]), + &VersionVector::from_iter(vec![(0, 2)]), + true, + ) + .unwrap(); + assert_eq!(json.changes[0].ops.len(), 2); + } +} diff --git a/vendor/loro-internal/src/encoding/outdated_encode_reordered.rs b/vendor/loro-internal/src/encoding/outdated_encode_reordered.rs new file mode 100644 index 0000000..de2b133 --- /dev/null +++ b/vendor/loro-internal/src/encoding/outdated_encode_reordered.rs @@ -0,0 +1,649 @@ +use append_only_bytes::{AppendOnlyBytes, BytesSlice}; +pub(crate) use encode::{encode_op, get_op_prop}; +use fractional_index::FractionalIndex; +use loro_common::{ + ContainerID, ContainerType, Counter, HasCounterSpan, HasIdSpan, IdLp, LoroError, LoroListValue, + LoroResult, LoroValue, TreeID, ID, +}; +use serde_columnar::{columnar, ColumnarError}; +use std::sync::Arc; + +use crate::version::VersionRange; +use crate::{ + change::{Change, Lamport}, + container::{ + list::list_op::DeleteSpanWithId, richtext::TextStyleInfoFlag, tree::tree_op::TreeOp, + }, + op::{FutureInnerContent, ValueSlice}, + OpLog, +}; + +use super::value::{Value, ValueDecodedArenasTrait}; + +pub(crate) use crate::encoding::value_register::ValueRegister; + +#[allow(unused_imports)] +use super::value::FutureValue; + +/// If any collection in the document is longer than this, we will not decode it. +/// It will return an data corruption error instead. +pub(super) const MAX_COLLECTION_SIZE: usize = 1 << 28; + +pub(crate) struct ImportChangesResult { + pub latest_ids: Vec<ID>, + pub pending_changes: Vec<Change>, + pub changes_that_have_deps_before_shallow_root: Vec<Change>, + pub imported: VersionRange, +} + +/// NOTE: This method expects that the remote_changes are already sorted by lamport value +pub(crate) fn import_changes_to_oplog( + changes: Vec<Change>, + oplog: &mut OpLog, +) -> LoroResult<ImportChangesResult> { + let mut pending_changes = Vec::new(); + let mut latest_ids = Vec::new(); + let mut changes_before_shallow_root = Vec::new(); + let mut imported = VersionRange::default(); + for mut change in changes { + if change.ctr_end() <= oplog.vv().get(&change.id.peer).copied().unwrap_or(0) { + // skip included changes + continue; + } + + if oplog + .dag + .try_import_deps_before_shallow_root(&change.deps)? + { + changes_before_shallow_root.push(change); + continue; + } + + latest_ids.push(change.id_last()); + // calc lamport or pending if its deps are not satisfied + match oplog.dag.try_get_change_lamport_from_deps(&change.deps)? { + Some(lamport) => change.lamport = lamport, + None => { + pending_changes.push(change); + continue; + } + } + + let Some(change) = oplog.trim_the_known_part_of_change(change) else { + continue; + }; + + imported.extends_to_include_id_span(change.id_span()); + oplog.insert_new_change(change, false); + } + + Ok(ImportChangesResult { + latest_ids, + pending_changes, + changes_that_have_deps_before_shallow_root: changes_before_shallow_root, + imported, + }) +} + +mod encode { + use loro_common::ContainerType; + + use crate::{ + encoding::value::{MarkStart, Value, ValueEncodeRegister, ValueKind, ValueWriter}, + op::{FutureInnerContent, Op}, + }; + + use super::EncodedDeleteStartId; + + fn get_future_op_prop(op: &FutureInnerContent) -> i32 { + match op { + #[cfg(feature = "counter")] + FutureInnerContent::Counter(_) => 0, + FutureInnerContent::Unknown { prop, .. } => *prop, + } + } + + pub(crate) fn get_op_prop(op: &Op, registers: &mut dyn ValueEncodeRegister) -> i32 { + match &op.content { + crate::op::InnerContent::List(list) => match list { + crate::container::list::list_op::InnerListOp::Move { to, .. } => *to as i32, + crate::container::list::list_op::InnerListOp::Set { .. } => 0, + crate::container::list::list_op::InnerListOp::Insert { pos, .. } => *pos as i32, + crate::container::list::list_op::InnerListOp::InsertText { pos, .. } => *pos as i32, + crate::container::list::list_op::InnerListOp::Delete(span) => span.span.pos as i32, + crate::container::list::list_op::InnerListOp::StyleStart { start, .. } => { + *start as i32 + } + crate::container::list::list_op::InnerListOp::StyleEnd => 0, + }, + crate::op::InnerContent::Map(map) => { + let key = registers.key_mut().register(&map.key); + key as i32 + } + crate::op::InnerContent::Tree(_) => 0, + crate::op::InnerContent::Future(f) => get_future_op_prop(f), + } + } + + #[inline] + pub(crate) fn encode_op<'p, 'a: 'p>( + op: &'a Op, + delete_start: &mut Vec<EncodedDeleteStartId>, + value_writer: &mut ValueWriter, + registers: &mut dyn ValueEncodeRegister, + ) -> ValueKind { + let value = match &op.content { + crate::op::InnerContent::List(list) => match list { + crate::container::list::list_op::InnerListOp::Insert { slice, .. } => { + assert!(matches!( + op.container.get_type(), + ContainerType::List | ContainerType::MovableList + )); + Value::LoroValue(slice.as_slice().to_vec().into()) + } + crate::container::list::list_op::InnerListOp::InsertText { slice, .. } => { + Value::Str(std::str::from_utf8(slice.as_bytes()).unwrap()) + } + crate::container::list::list_op::InnerListOp::Delete(span) => { + delete_start.push(EncodedDeleteStartId { + peer_idx: registers.peer_mut().register(&span.id_start.peer), + counter: span.id_start.counter, + len: span.span.signed_len, + }); + Value::DeleteSeq + } + crate::container::list::list_op::InnerListOp::StyleStart { + start, + end, + key, + value, + info, + } => Value::MarkStart(MarkStart { + len: *end - *start, + key: key.clone(), + value: value.clone(), + info: info.to_byte(), + }), + crate::container::list::list_op::InnerListOp::Set { elem_id, value } => { + Value::ListSet { + peer_idx: registers.peer_mut().register(&elem_id.peer), + lamport: elem_id.lamport, + value: value.clone(), + } + } + crate::container::list::list_op::InnerListOp::StyleEnd => Value::Null, + crate::container::list::list_op::InnerListOp::Move { + from, + elem_id: from_id, + to: _, + } => Value::ListMove { + from: *from as usize, + from_idx: registers.peer_mut().register(&from_id.peer), + lamport: from_id.lamport as usize, + }, + }, + crate::op::InnerContent::Map(map) => { + assert_eq!(op.container.get_type(), ContainerType::Map); + match &map.value { + Some(v) => Value::LoroValue(v.clone()), + None => Value::DeleteOnce, + } + } + crate::op::InnerContent::Tree(t) => { + assert_eq!(op.container.get_type(), ContainerType::Tree); + registers.encode_tree_op(t) + } + crate::op::InnerContent::Future(f) => match f { + #[cfg(feature = "counter")] + FutureInnerContent::Counter(c) => { + let c_abs = c.abs(); + if c_abs.fract() == 0.0 && (c_abs as i64) < (2 << 26) { + Value::I64(*c as i64) + } else { + Value::F64(*c) + } + } + FutureInnerContent::Unknown { value, .. } => Value::from_owned(value), + }, + }; + let (k, _) = value.encode(value_writer, registers); + k + } +} + +/// The text and list values of the ops decoded from one change block. +/// +/// They are dropped with those ops. Decoding into the doc's arenas instead, +/// which are never freed, made them grow by a block's whole content every time +/// the block was parsed again after an export (`context/text-arena-growth.md`). +/// Each kind goes into one buffer, so a block's values are read together and +/// adjacent slices merge without copying. +pub(crate) struct DecodedBlockBuffers { + text: Option<AppendOnlyBytes>, + text_capacity: usize, + values: Vec<LoroValue>, + /// What list slices point into until [`Self::finish`] gives them `values`. + /// Created with the first list value, so most blocks allocate nothing here. + pending_values: Option<Arc<Vec<LoroValue>>>, +} + +impl DecodedBlockBuffers { + /// `text_capacity` should bound the decoded text, so that all of its + /// slices share one buffer. + pub fn new(text_capacity: usize) -> Self { + Self { + text: None, + text_capacity, + values: Vec::new(), + pending_values: None, + } + } + + fn push_text(&mut self, s: &str) -> BytesSlice { + let bytes = self + .text + .get_or_insert_with(|| AppendOnlyBytes::with_capacity(self.text_capacity.max(s.len()))); + let start = bytes.len(); + bytes.push_str(s); + bytes.slice(start..) + } + + /// A multi-value slice can be neither read nor merged before [`Self::finish`]. + fn push_values(&mut self, list: LoroListValue) -> ValueSlice { + let list = list.into_arc(); + if list.len() == 1 { + // Stored inline. A sync that imports one small change from each of + // many peers decodes many blocks with one value each, and a shared + // buffer would cost each block a few allocations. + let value = + Arc::try_unwrap(list).map_or_else(|list| list[0].clone(), |mut v| v.pop().unwrap()); + return ValueSlice::one(value); + } + + let start = self.values.len(); + match Arc::try_unwrap(list) { + Ok(mut list) => self.values.append(&mut list), + Err(list) => self.values.extend_from_slice(&list), + } + let pending = self.pending_values.get_or_insert_with(Default::default); + ValueSlice::pending(pending, start..self.values.len()) + } + + /// Points the slices that [`Self::push_values`] returned at the values. + pub fn finish<'a>(self, slices: impl Iterator<Item = &'a mut ValueSlice>) { + let Some(pending) = self.pending_values else { + return; + }; + let mut values = self.values; + // The values live as long as any op slice of the block. + values.shrink_to_fit(); + let values = Arc::new(values); + for slice in slices { + slice.replace_buffer(&pending, &values); + } + } +} + +#[allow(clippy::too_many_arguments)] +pub(crate) fn decode_op( + cid: &ContainerID, + value: Value<'_>, + del_iter: &mut impl Iterator<Item = Result<EncodedDeleteStartId, ColumnarError>>, + buffers: &mut DecodedBlockBuffers, + arenas: &dyn ValueDecodedArenasTrait, + positions: &[Vec<u8>], + prop: i32, + op_id: ID, +) -> LoroResult<crate::op::InnerContent> { + let content = match cid.container_type() { + ContainerType::Text => match value { + Value::Str(s) => { + let unicode_len = s.chars().count(); + crate::op::InnerContent::List( + crate::container::list::list_op::InnerListOp::InsertText { + slice: buffers.push_text(s), + unicode_len: unicode_len as u32, + pos: prop as u32, + }, + ) + } + Value::DeleteSeq => { + let del_start = del_iter + .next() + .ok_or(LoroError::DecodeDataCorruptionError)??; + let peer_idx = del_start.peer_idx; + let cnt = del_start.counter; + let len = del_start.len; + crate::op::InnerContent::List(crate::container::list::list_op::InnerListOp::Delete( + DeleteSpanWithId::new( + ID::new( + *arenas + .peers() + .get(peer_idx) + .ok_or(LoroError::DecodeDataCorruptionError)?, + cnt as Counter, + ), + prop as isize, + len, + ), + )) + } + Value::MarkStart(mark) => crate::op::InnerContent::List( + crate::container::list::list_op::InnerListOp::StyleStart { + start: prop as u32, + end: prop as u32 + mark.len, + key: mark.key, + value: mark.value, + info: TextStyleInfoFlag::from_byte(mark.info), + }, + ), + Value::Null => crate::op::InnerContent::List( + crate::container::list::list_op::InnerListOp::StyleEnd, + ), + _ => return Err(LoroError::DecodeDataCorruptionError), + }, + ContainerType::Map => { + let key = arenas + .keys() + .get(prop as usize) + .ok_or(LoroError::DecodeDataCorruptionError)? + .clone(); + match value { + Value::DeleteOnce => { + crate::op::InnerContent::Map(crate::container::map::MapSet { key, value: None }) + } + Value::LoroValue(v) => { + crate::op::InnerContent::Map(crate::container::map::MapSet { + key, + value: Some(v.clone()), + }) + } + _ => return Err(LoroError::DecodeDataCorruptionError), + } + } + ContainerType::List => { + let pos = prop as usize; + match value { + Value::LoroValue(arr) => { + let list = arr + .into_list() + .map_err(|_| LoroError::DecodeDataCorruptionError)?; + crate::op::InnerContent::List( + crate::container::list::list_op::InnerListOp::Insert { + slice: buffers.push_values(list), + pos, + }, + ) + } + Value::DeleteSeq => { + let del_start = del_iter + .next() + .ok_or(LoroError::DecodeDataCorruptionError)??; + let peer_idx = del_start.peer_idx; + let cnt = del_start.counter; + let len = del_start.len; + crate::op::InnerContent::List( + crate::container::list::list_op::InnerListOp::Delete( + DeleteSpanWithId::new( + ID::new( + *arenas + .peers() + .get(peer_idx) + .ok_or(LoroError::DecodeDataCorruptionError)?, + cnt as Counter, + ), + pos as isize, + len, + ), + ), + ) + } + _ => return Err(LoroError::DecodeDataCorruptionError), + } + } + ContainerType::Tree => match value { + Value::TreeMove(op) => crate::op::InnerContent::Tree(Arc::new( + arenas.decode_tree_op(positions, op, op_id)?, + )), + Value::RawTreeMove(op) => { + let subject = TreeID::new( + *arenas + .peers() + .get(op.subject_peer_idx) + .ok_or(LoroError::DecodeDataCorruptionError)?, + op.subject_cnt as Counter, + ); + let parent = if op.is_parent_null { + None + } else { + let parent_id = TreeID::new( + *arenas + .peers() + .get(op.parent_peer_idx) + .ok_or(LoroError::DecodeDataCorruptionError)?, + op.parent_cnt as Counter, + ); + if parent_id.is_deleted_root() { + return Ok(crate::op::InnerContent::Tree(Arc::new(TreeOp::Delete { + target: subject, + }))); + } + + Some(parent_id) + }; + + let fi = FractionalIndex::from_bytes( + positions + .get(op.position_idx) + .ok_or(LoroError::DecodeDataCorruptionError)? + .clone(), + ); + let is_create = subject.id() == op_id; + let ans = if is_create { + TreeOp::Create { + target: subject, + parent, + position: fi, + } + } else { + TreeOp::Move { + target: subject, + parent, + position: fi, + } + }; + crate::op::InnerContent::Tree(Arc::new(ans)) + } + _ => return Err(LoroError::DecodeDataCorruptionError), + }, + ContainerType::MovableList => { + let pos = prop as usize; + match value { + Value::LoroValue(arr) => { + let list = arr + .into_list() + .map_err(|_| LoroError::DecodeDataCorruptionError)?; + crate::op::InnerContent::List( + crate::container::list::list_op::InnerListOp::Insert { + slice: buffers.push_values(list), + pos, + }, + ) + } + Value::DeleteSeq => { + let del_start = del_iter + .next() + .ok_or(LoroError::DecodeDataCorruptionError)??; + let peer_idx = del_start.peer_idx; + let cnt = del_start.counter; + let len = del_start.len; + crate::op::InnerContent::List( + crate::container::list::list_op::InnerListOp::Delete( + DeleteSpanWithId::new( + ID::new( + *arenas + .peers() + .get(peer_idx) + .ok_or(LoroError::DecodeDataCorruptionError)?, + cnt as Counter, + ), + pos as isize, + len, + ), + ), + ) + } + Value::ListMove { + from, + from_idx, + lamport, + } => crate::op::InnerContent::List( + crate::container::list::list_op::InnerListOp::Move { + from: from as u32, + elem_id: IdLp::new( + *arenas + .peers() + .get(from_idx) + .ok_or(LoroError::DecodeDataCorruptionError)?, + lamport as Lamport, + ), + to: prop as u32, + }, + ), + Value::ListSet { + peer_idx, + lamport, + value, + } => crate::op::InnerContent::List( + crate::container::list::list_op::InnerListOp::Set { + elem_id: IdLp::new( + *arenas + .peers() + .get(peer_idx) + .ok_or(LoroError::DecodeDataCorruptionError)?, + lamport as Lamport, + ), + value, + }, + ), + _ => return Err(LoroError::DecodeDataCorruptionError), + } + } + #[cfg(feature = "counter")] + ContainerType::Counter => match value { + Value::F64(c) => crate::op::InnerContent::Future(FutureInnerContent::Counter(c)), + Value::I64(c) => crate::op::InnerContent::Future(FutureInnerContent::Counter(c as f64)), + _ => return Err(LoroError::DecodeDataCorruptionError), + }, + // NOTE: The future container type need also try to parse the unknown type + ContainerType::Unknown(_) => crate::op::InnerContent::Future(FutureInnerContent::Unknown { + prop, + value: Box::new(value.into_owned()), + }), + }; + + if let crate::op::InnerContent::List(list_op) = &content { + list_op.check_positions()?; + } + + Ok(content) +} + +pub type PeerIdx = usize; + +#[columnar(vec, ser, de, iterable)] +#[derive(Debug, Clone)] +pub(crate) struct EncodedDeleteStartId { + #[columnar(strategy = "DeltaRle")] + peer_idx: usize, + #[columnar(strategy = "DeltaRle")] + counter: i32, + #[columnar(strategy = "DeltaRle")] + len: isize, +} + +#[cfg(test)] +mod test { + + use loro_common::LoroValue; + use rustc_hash::FxHashSet; + + use crate::{ + encoding::{ + arena::EncodedRegisters, + value::{ValueReader, ValueWriter}, + value_register::ValueRegister, + }, + fx_map, + }; + + use super::*; + + fn test_loro_value_read_write(v: impl Into<LoroValue>, container_id: Option<ContainerID>) { + let v = v.into(); + let id = match &container_id { + Some(ContainerID::Root { .. }) => ID::new(u64::MAX, 0), + Some(ContainerID::Normal { peer, counter, .. }) => ID::new(*peer, *counter), + None => ID::new(u64::MAX, 0), + }; + + let mut registers = EncodedRegisters { + key: ValueRegister::new(), + peer: ValueRegister::new(), + tree_id: ValueRegister::new(), + position: either::Either::Left(FxHashSet::default()), + }; + + let mut writer = ValueWriter::new(); + let (kind, _) = writer.write_value_content(&v, &mut registers); + + let binding = writer.finish(); + let mut reader = ValueReader::new(binding.as_slice()); + + let ans = reader + .read_value_content(kind, ®isters.key.unwrap_vec(), id) + .unwrap(); + assert_eq!(v, ans) + } + + #[test] + fn test_value_read_write() { + test_loro_value_read_write(true, None); + test_loro_value_read_write(false, None); + test_loro_value_read_write(123, None); + test_loro_value_read_write(1.23, None); + test_loro_value_read_write(LoroValue::Null, None); + test_loro_value_read_write( + LoroValue::Binary((vec![123, 223, 255, 0, 1, 2, 3]).into()), + None, + ); + test_loro_value_read_write("sldk;ajfas;dlkfas测试", None); + // we won't encode root container by `value content` + // test_loro_value_read_write( + // LoroValue::Container(ContainerID::new_root("name", ContainerType::Text)), + // Some(ContainerID::new_root("name", ContainerType::Text)), + // ); + test_loro_value_read_write( + LoroValue::Container(ContainerID::new_normal( + ID::new(u64::MAX, 123), + ContainerType::Tree, + )), + Some(ContainerID::new_normal( + ID::new(u64::MAX, 123), + ContainerType::Tree, + )), + ); + test_loro_value_read_write(vec![1i32, 2, 3], None); + test_loro_value_read_write( + LoroValue::Map( + (fx_map![ + "1".into() => 123.into(), + "2".into() => "123".into(), + "3".into() => vec![true].into() + ]) + .into(), + ), + None, + ); + } +} diff --git a/vendor/loro-internal/src/encoding/shallow_snapshot.rs b/vendor/loro-internal/src/encoding/shallow_snapshot.rs new file mode 100644 index 0000000..360f6ac --- /dev/null +++ b/vendor/loro-internal/src/encoding/shallow_snapshot.rs @@ -0,0 +1,1979 @@ +use bytes::Bytes; +use rle::HasLength; +use rustc_hash::FxHashSet; +use std::collections::BTreeSet; + +use loro_common::{ContainerID, ContainerType, IdSpan, LoroEncodeError, LoroError, ID}; + +use crate::{ + container::{idx::ContainerIdx, list::list_op::InnerListOp}, + dag::DagUtils, + encoding::export_fast_updates_in_range, + encoding::fast_snapshot::{_encode_snapshot, Snapshot}, + state::{ + container_store::{ContainerWrapper, PrunedRootState, FRONTIERS_KEY}, + redact_dead_style_values, DocState, + }, + utils::kv_wrapper::KvWrapper, + version::{Frontiers, VersionVector}, + LoroDoc, +}; + +#[cfg(test)] +const MAX_OPS_NUM_TO_ENCODE_WITHOUT_LATEST_STATE: usize = 16; +#[cfg(not(test))] +const MAX_OPS_NUM_TO_ENCODE_WITHOUT_LATEST_STATE: usize = 256; + +/// Minimum number of retained ops (root..latest) for the forward-replay fast +/// path to be worth it. Below this, the old checkout path is used: at F == +/// latest it is trivial (no history to walk back), and on the 66k-container / +/// 720k-op fixture the paths tie at ~8k retained ops while the checkout path +/// peaks at ~4x less memory; forward replay only wins decisively past ~64k +/// (1.25-3.6x at 79k, 10-14x at 393k). Note this fixture has tiny +/// per-container histories; docs with long text histories penalize the +/// checkout path more, shifting the real crossover lower. +#[cfg(test)] +const MIN_RETAINED_OPS_FOR_FORWARD_ROOT_STATE: usize = 16; +#[cfg(not(test))] +const MIN_RETAINED_OPS_FOR_FORWARD_ROOT_STATE: usize = 65536; + +/// The fast path re-encodes and replays ALL pre-root history into a temporary +/// doc, so its cost scales with the prefix, not the tail. Cap the prefix/tail +/// ratio: on the fixture the fast path wins at ratio 9 and loses at ratio 19, +/// and an unrelated huge prefix (e.g. millions of same-key Map overwrites +/// before the root) must not be replayed just because the tail is large. +const MAX_PRE_ROOT_TO_RETAINED_OPS_RATIO: usize = 16; + +/// Absolute cap on pre-root ops for the forward-replay path. Replaying ~1M ops +/// costs roughly 0.5-1s and several hundred MiB of peak memory; beyond that +/// the checkout path is safer (its work is bounded by the tail), especially +/// on wasm32. +const MAX_PRE_ROOT_OPS_FOR_FORWARD_REPLAY: usize = 1_000_000; + +/// Cap on the pre-root prefix's decoded byte size, estimated by walking op +/// payloads by reference BEFORE any value is copied (see +/// `estimate_ops_content_bytes`). Op counts miss value sizes: a Map write is +/// one atom regardless of how large its Binary/String value is, so a +/// byte-heavy but low-op prefix would bypass the op-count gates. Checking only +/// the encoded blob afterwards would be too late — +/// `export_fast_updates_in_range` slice-copies values into a fresh store while +/// building it, which is exactly the allocation this cap exists to prevent. +#[cfg(test)] +const MAX_PRE_ROOT_BYTES_FOR_FORWARD_REPLAY: usize = 1 << 20; +#[cfg(not(test))] +const MAX_PRE_ROOT_BYTES_FOR_FORWARD_REPLAY: usize = 32 << 20; + +/// Estimate the decoded byte size of everything in `spans` — op payloads +/// (recursing into nested `LoroValue::List`/`Map`), style values, and commit +/// messages — following arena slices by reference and never copying values. +/// The walk is cap-aware: every counting step takes a remaining budget and +/// bails as soon as it is exceeded, so a rejected prefix costs one bounded +/// walk instead of a full copy. +fn estimate_ops_content_bytes(oplog: &crate::OpLog, spans: &[IdSpan], cap: usize) -> usize { + let mut total = 0usize; + 'outer: for span in spans { + let mut span = *span; + span.normalize_(); + if span.counter.end <= 0 { + continue; + } + + span.counter.start = span.counter.start.max(0); + span.counter.end = span.counter.end.max(0); + if span.counter.start >= span.counter.end { + continue; + } + + for change in oplog.iter_changes(span) { + let start = + ((span.counter.start - change.id.counter).max(0) as usize).min(change.atom_len()); + let end = + ((span.counter.end - change.id.counter).max(0) as usize).min(change.atom_len()); + if start == end { + continue; + } + + if let Some(msg) = change.commit_msg.as_ref() { + total = total.saturating_add(msg.len()); + if total > cap { + break 'outer; + } + } + + for op in crate::op::RichOp::new_iter_by_cnt_range(change, span.counter) { + total = total.saturating_add(rich_op_content_bytes(oplog, &op, cap - total)); + if total > cap { + break 'outer; + } + } + } + } + total +} + +/// Byte size of an op's variable-length fields plus a small flat per-op +/// overhead: everything the block encoder copies (payload values, map and +/// style keys, fractional indexes, root container names, unknown-future +/// bytes). Arena slices are measured by reference; nothing is copied. +/// `remaining` is the budget left before the cap; the count may stop early +/// once it is exceeded. +fn rich_op_content_bytes(oplog: &crate::OpLog, op: &crate::op::RichOp, remaining: usize) -> usize { + const PER_OP_OVERHEAD: usize = 16; + if remaining < PER_OP_OVERHEAD { + return remaining + 1; + } + + // Root container names are variable-length and copied into the encoded + // block's container arena. + let container_name_len = match oplog.arena.get_container_id(op.raw_op().container) { + Some(ContainerID::Root { name, .. }) => name.len(), + _ => 0, + }; + let after_fixed = remaining.saturating_sub(PER_OP_OVERHEAD + container_name_len); + + PER_OP_OVERHEAD + + container_name_len + + match &op.raw_op().content { + crate::op::InnerContent::Map(map) => { + let mut used = map.key.len(); + if let Some(value) = map.value.as_ref() { + used = used.saturating_add(value_bytes_capped( + value, + after_fixed.saturating_sub(used), + )); + } + used + } + crate::op::InnerContent::List(list) => match list { + InnerListOp::Insert { slice, .. } => { + let mut used = 0usize; + for value in slice.as_slice() { + used = used.saturating_add(value_bytes_capped( + value, + after_fixed.saturating_sub(used), + )); + if used > after_fixed { + break; + } + } + used + } + InnerListOp::InsertText { slice, .. } => slice.len(), + InnerListOp::Set { value, .. } => value_bytes_capped(value, after_fixed), + InnerListOp::StyleStart { key, value, .. } => { + let mut used = key.len(); + used = used.saturating_add(value_bytes_capped( + value, + after_fixed.saturating_sub(used), + )); + used + } + _ => 0, + }, + // Fractional indexes are variable-length and copied by the encoder. + crate::op::InnerContent::Tree(tree_op) => match tree_op.as_ref() { + crate::container::tree::tree_op::TreeOp::Create { position, .. } + | crate::container::tree::tree_op::TreeOp::Move { position, .. } => { + position.as_bytes().len() + } + crate::container::tree::tree_op::TreeOp::Delete { .. } => 0, + }, + crate::op::InnerContent::Future(future) => match future { + crate::op::FutureInnerContent::Unknown { value, .. } => { + owned_value_bytes_capped(value, after_fixed) + } + #[cfg(feature = "counter")] + crate::op::FutureInnerContent::Counter(_) => 0, + }, + } +} + +/// Byte size of an owned future/unknown value, recursing where the payload is +/// a `LoroValue`. `remaining` is the budget left before the cap. +fn owned_value_bytes_capped(value: &crate::encoding::value::OwnedValue, remaining: usize) -> usize { + use crate::encoding::value::OwnedValue; + const OVERHEAD: usize = 16; + if remaining < OVERHEAD { + return remaining + 1; + } + + match value { + OwnedValue::Str(s) => OVERHEAD.saturating_add(s.len()), + OwnedValue::Binary(b) => OVERHEAD.saturating_add(b.len()), + OwnedValue::LoroValue(v) => OVERHEAD.saturating_add(value_bytes_capped(v, remaining)), + // The encoder writes the mark key into the block's key register and + // recurses into the value; both are variable-length. + OwnedValue::MarkStart(mark) => { + let mut used = OVERHEAD.saturating_add(mark.key.len()); + used = used.saturating_add(value_bytes_capped( + &mark.value, + remaining.saturating_sub(used), + )); + used + } + // The encoder recurses into the set value. + OwnedValue::ListSet { value, .. } => { + OVERHEAD.saturating_add(value_bytes_capped(value, remaining)) + } + OwnedValue::Future(owned) => match owned { + crate::encoding::value::OwnedFutureValue::Unknown { data, .. } => { + OVERHEAD.saturating_add(data.len()) + } + }, + // TreeMove/RawTreeMove/ListMove carry only fixed-size indices; the + // fractional-index payloads they point at are small by construction. + _ => OVERHEAD, + } +} + +/// Byte size of a value, recursing into nested lists and maps (the encoder +/// writes them recursively, so the estimate must too). `remaining` is the +/// budget left before the cap; the count may stop early once it is exceeded. +fn value_bytes_capped(value: &loro_common::LoroValue, remaining: usize) -> usize { + const OVERHEAD: usize = 16; + if remaining < OVERHEAD { + return remaining + 1; + } + + let mut used = OVERHEAD; + match value { + loro_common::LoroValue::String(s) => used = used.saturating_add(s.len()), + loro_common::LoroValue::Binary(b) => used = used.saturating_add(b.len()), + loro_common::LoroValue::List(list) => { + for item in list.iter() { + used = + used.saturating_add(value_bytes_capped(item, remaining.saturating_sub(used))); + if used > remaining { + break; + } + } + } + loro_common::LoroValue::Map(map) => { + for (key, item) in map.iter() { + used = used.saturating_add(key.len()); + if used > remaining { + break; + } + used = + used.saturating_add(value_bytes_capped(item, remaining.saturating_sub(used))); + if used > remaining { + break; + } + } + } + _ => {} + } + used +} + +/// Whether the forward-replay path may be used for the given prefix/tail +/// shape. The caller still has to require a non-shallow doc whose state is at +/// the latest version. Extracted as a pure predicate so the gate can be +/// tested directly. +fn forward_replay_gate(ops_num: usize, pre_root_ops: usize, pre_root_bytes: usize) -> bool { + ops_num >= MIN_RETAINED_OPS_FOR_FORWARD_ROOT_STATE + && pre_root_ops <= MAX_PRE_ROOT_OPS_FOR_FORWARD_REPLAY + && pre_root_ops <= MAX_PRE_ROOT_TO_RETAINED_OPS_RATIO * ops_num + && pre_root_bytes <= MAX_PRE_ROOT_BYTES_FOR_FORWARD_REPLAY +} + +#[tracing::instrument(skip_all)] +pub(crate) fn export_shallow_snapshot<W: std::io::Write>( + doc: &LoroDoc, + start_from: &Frontiers, + w: &mut W, +) -> Result<Frontiers, LoroEncodeError> { + let (snapshot, start_from) = + export_shallow_snapshot_inner(doc, start_from, CachedShallowRoot::Prune)?; + _encode_snapshot(&snapshot, w); + Ok(start_from) +} + +/// How a shallow export at a doc's own shallow root treats the cached root state. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CachedShallowRoot { + /// Drop containers the retention walk does not reach (every export). + Prune, + /// Reuse the cached root as-is (`LoroDoc::fork`). + Verbatim, +} + +pub(crate) fn export_shallow_snapshot_inner( + doc: &LoroDoc, + start_from: &Frontiers, + cached_root: CachedShallowRoot, +) -> Result<(Snapshot, Frontiers), LoroEncodeError> { + let oplog = doc.oplog().lock(); + let start_from = calc_shallow_doc_start(&oplog, start_from, oplog.frontiers())?; + // `root_vv` is the version of the state at the shallow root; `start_vv` + // additionally excludes the frontier ops themselves because the retained + // history must include them. + let root_vv = frontiers_to_vv_for_export(&oplog, &start_from, "export_shallow_snapshot")?; + let mut start_vv = root_vv.clone(); + for id in start_from.iter() { + // we need to include the ops in start_from, this can make things easier + start_vv.insert(id.peer, id.counter); + } + + #[cfg(debug_assertions)] + { + use crate::dag::Dag; + if !start_from.is_empty() { + assert!(start_from.len() == 1); + let id = start_from.as_single().unwrap(); + let node = oplog.dag.try_get(id)?.unwrap(); + if id.counter == node.cnt { + let vv = oplog.dag().try_frontiers_to_vv(&node.deps)?.unwrap(); + assert_eq!(vv, start_vv); + } else { + let vv = oplog + .dag() + .try_frontiers_to_vv(&Frontiers::from(id.inc(-1)))? + .unwrap(); + assert_eq!(vv, start_vv); + } + } + } + + loro_common::debug!( + "start version vv={:?} frontiers={:?}", + &start_vv, + &start_from, + ); + + let latest_frontiers = oplog.frontiers().clone(); + let state_frontiers = doc.state_frontiers(); + let is_attached = !doc.is_detached(); + let oplog_bytes = oplog.export_change_store_from(&start_vv, &start_from); + let latest_vv = oplog.vv(); + let ops_num: usize = latest_vv.sub_iter(&start_vv).map(|x| x.atom_len()).sum(); + // Pre-encode the pre-root history for the forward-replay path below while + // the oplog lock is held. Calling `LoroDoc::export` there instead would + // re-enter `with_barrier` and violate the txn lock order. Shallow docs are + // excluded: their pre-root history is trimmed, so forward replay from + // empty cannot reconstruct the root state. Small retained ranges are + // excluded too: the checkout path is then cheap and peaks at far less + // memory (see MIN_RETAINED_OPS_FOR_FORWARD_ROOT_STATE). The prefix itself + // is bounded absolutely and relative to the tail, because this path pays + // for replaying all of it while the checkout path only walks the tail. + let pre_root_ops: usize = root_vv + .values() + .map(|counter| (*counter).max(0) as usize) + .sum(); + // Cheap op-count legs first (even the estimate walks the prefix's ops, so + // it must not run for the small-tail cases the checkout path handles + // best). The byte leg runs BEFORE encoding: the estimate follows arena + // slices by reference, while export_fast_updates_in_range would + // slice-copy every value into a fresh store — the very allocation the cap + // exists to prevent. + let pre_root_updates = (state_frontiers == latest_frontiers + && oplog.shallow_since_vv().is_empty() + && forward_replay_gate(ops_num, pre_root_ops, 0)) + .then(|| { + let spans: Vec<IdSpan> = root_vv + .iter() + .filter(|(_, counter)| **counter > 0) + .map(|(peer, counter)| IdSpan::new(*peer, 0, *counter)) + .collect(); + if estimate_ops_content_bytes(&oplog, &spans, MAX_PRE_ROOT_BYTES_FOR_FORWARD_REPLAY) + > MAX_PRE_ROOT_BYTES_FOR_FORWARD_REPLAY + { + return None; + } + + Some(export_fast_updates_in_range(&oplog, &spans)) + }) + .flatten(); + if &start_from == oplog.shallow_since_frontiers() && state_frontiers == latest_frontiers { + let mut state = doc.app_state().lock(); + if let Some(shallow_root) = state.store.shallow_root_store().cloned() { + let (mut shallow_root_state_bytes, shallow_root_kv) = + state.store.shallow_root_state_for_export().unwrap(); + // The cached root may come from an older exporter that kept + // containers deleted before the root, so filter it with the same + // retention rule the other paths use instead of trusting its key + // set. The root never changes, so the result is computed once. + // A root the walk cannot judge (an inconsistent parent header, or + // a state that does not decode) is kept verbatim, as exporters + // before #1123 did: nothing referenced is dropped, and the export + // still succeeds. A fork always copies the root verbatim: it + // publishes nothing. + if cached_root == CachedShallowRoot::Prune { + let pruned = shallow_root.pruned_root.get_or_init(|| { + match prune_cached_root( + &shallow_root_state_bytes, + &shallow_root_kv, + &shallow_root.shallow_root_frontiers, + &root_vv, + ) { + Ok(pruned) => pruned, + Err(err) => { + tracing::warn!( + ?err, + "cached shallow root cannot be checked; exporting it verbatim" + ); + None + } + } + }); + if let Some(pruned) = pruned { + for key in &pruned.removed { + shallow_root_kv.remove(key); + } + shallow_root_state_bytes = pruned.state_bytes.clone(); + } + } + + // Ops since the root are few enough to replay on import; otherwise + // also ship the encoded latest state as an overlay. + let overlay_kv = if ops_num > MAX_OPS_NUM_TO_ENCODE_WITHOUT_LATEST_STATE { + let mut alive_c_bytes = shallow_root_kv.keys(); + if has_unknown_container_key(alive_c_bytes.iter()) { + return Err(LoroEncodeError::UnknownContainer); + } + + state.ensure_all_alive_containers()?; + state.store.flush(); + + retain_created_after_root(&mut state, &root_vv, &mut alive_c_bytes); + + let new_kv = state.store.get_kv_clone(); + new_kv.remove_same(&shallow_root_kv); + new_kv.retain_keys(&alive_c_bytes); + Some(new_kv) + } else { + None + }; + + // The stored shallow-root bytes may predate dead-style redaction + // (e.g. imported from an older export), so re-run it before reuse. + let shallow_root_state_bytes = + if redact_export_states(&shallow_root_kv, overlay_kv.as_ref())? { + // The cloned root kv has no FRONTIERS_KEY (InnerStore::decode + // strips it on import); restore it before export. + shallow_root_kv.insert(FRONTIERS_KEY, start_from.encode().into()); + shallow_root_kv.export() + } else { + shallow_root_state_bytes + }; + + return Ok(( + Snapshot { + oplog_bytes, + state_bytes: overlay_kv.map(|kv| kv.export()), + shallow_root_state_bytes, + }, + start_from, + )); + } + } + drop(oplog); + let result = (|| -> Result<Snapshot, LoroEncodeError> { + if let Some(pre_root_updates) = pre_root_updates { + // The live state is already at the latest version: build the root + // state by replaying pre-root history forward into a temporary doc + // instead of checking the live doc out backwards. A reverse + // checkout (latest -> root) makes the diff calculators rebuild a + // full CRDT tracker from empty for every list-like container + // touched in the range (the `should_rebuild` path in + // `RichtextDiffCalculator::calculate_diff`), which costs orders of + // magnitude more than forward replay when the doc has many small + // containers. Forward replay also leaves the live doc untouched, + // so no state restore is needed. + let root_doc = LoroDoc::new(); + root_doc + .import(&pre_root_updates) + .map_err(LoroEncodeError::from)?; + let mut root_state = root_doc.app_state().lock(); + // The replay doc does not share the live doc's deleted-root set; + // without it a root container deleted before the root would be + // re-encoded as an empty entry instead of being dropped at flush. + // (`InnerStore::flush` only drops the entry when the value is + // still empty, so roots deleted *after* the root keep their + // at-root content even with the set mirrored.) + *root_state.config.deleted_root_containers.lock() = + doc.config().deleted_root_containers.lock().clone(); + // Root containers exist on the live doc once they are accessed, + // even when they have no ops; the replay doc cannot know about + // those. Mirror the live store's root entries so the exported root + // state ships the same empty root containers the checkout path + // would. `existing_retention_roots` is a root-only key scan — a + // full `load_all` here would defeat lazily imported docs. + { + let mut live_state = doc.app_state().lock(); + for idx in live_state.existing_retention_roots() { + let cid = live_state.arena.get_container_id(idx).unwrap(); + root_state.store.ensure_container(&cid); + } + } + let alive_containers = root_state.ensure_all_alive_containers()?; + if has_unknown_container(alive_containers.iter().copied()) { + return Err(LoroEncodeError::UnknownContainer); + } + let mut alive_c_bytes = alive_indices_to_bytes(&root_state, &alive_containers); + root_state.store.flush(); + let shallow_root_state_kv = root_state.store.get_kv_clone(); + drop(root_state); + + let latest_state_kv = { + let mut state = doc.app_state().lock(); + latest_state_overlay_kv( + &mut state, + ops_num, + &root_vv, + &shallow_root_state_kv, + &mut alive_c_bytes, + )? + }; + return encode_shallow_sections( + oplog_bytes, + &start_from, + shallow_root_state_kv, + latest_state_kv, + alive_c_bytes, + ); + } + + doc._checkout_without_emitting(&start_from, false, false) + .map_err(LoroEncodeError::from)?; + let mut state = doc.app_state().lock(); + let alive_containers = state.ensure_all_alive_containers()?; + if has_unknown_container(alive_containers.iter().copied()) { + return Err(LoroEncodeError::UnknownContainer); + } + let mut alive_c_bytes = alive_indices_to_bytes(&state, &alive_containers); + state.store.flush(); + let shallow_root_state_kv = state.store.get_kv_clone(); + drop(state); + doc._checkout_without_emitting(&latest_frontiers, false, false) + .map_err(LoroEncodeError::from)?; + let latest_state_kv = { + let mut state = doc.app_state().lock(); + latest_state_overlay_kv( + &mut state, + ops_num, + &root_vv, + &shallow_root_state_kv, + &mut alive_c_bytes, + )? + }; + encode_shallow_sections( + oplog_bytes, + &start_from, + shallow_root_state_kv, + latest_state_kv, + alive_c_bytes, + ) + })(); + + restore_export_doc_state(doc, &state_frontiers, is_attached)?; + doc.drop_pending_events(); + Ok((result?, start_from)) +} + +/// Compute the encoded latest-state overlay shipped alongside the shallow root +/// when the retained history is too large to replay on import. Containers +/// created after the root are added to `alive_c_bytes` so both the root +/// state and the overlay keep them. +fn latest_state_overlay_kv( + state: &mut DocState, + ops_num: usize, + root_vv: &VersionVector, + shallow_root_state_kv: &KvWrapper, + alive_c_bytes: &mut BTreeSet<Vec<u8>>, +) -> Result<Option<KvWrapper>, LoroEncodeError> { + if ops_num <= MAX_OPS_NUM_TO_ENCODE_WITHOUT_LATEST_STATE { + return Ok(None); + } + + state.ensure_all_alive_containers()?; + state.store.encode(); + retain_created_after_root(state, root_vv, alive_c_bytes); + + let new_kv = state.store.get_kv_clone(); + new_kv.remove_same(shallow_root_state_kv); + new_kv.retain_keys(alive_c_bytes); + Ok(Some(new_kv)) +} + +/// Adds every stored container created after the root (plus every non-normal +/// container) to `alive_c_bytes`. +/// +/// `alive_c_bytes` starts as the root state's retention set +/// (`DocState::ensure_all_alive_containers`), so a container created at or +/// before the root survives only if that walk reached it. Map/list children +/// deleted before the root are dropped: a retained op cannot re-attach them. +/// Tree node metas are not dropped even when the node is deleted, because a +/// retained op can revive the node; the retention walk includes them. +fn retain_created_after_root( + state: &mut DocState, + root_vv: &VersionVector, + alive_c_bytes: &mut BTreeSet<Vec<u8>>, +) { + for cid in state.store.iter_all_container_ids() { + if let ContainerID::Normal { peer, counter, .. } = cid { + if !root_vv.includes_id(ID::new(peer, counter)) { + alive_c_bytes.insert(cid.to_bytes()); + } + } else { + alive_c_bytes.insert(cid.to_bytes()); + } + } +} + +/// Filters a cached shallow root state with the retention walk, returning the +/// pruned state, or `None` when nothing has to be removed. +/// +/// Runs on a scratch doc so the live doc's arena and store are untouched. The +/// cheap `DocState::unreached_stored_containers` filter settles the common +/// case: every stored container is reached, counting placeholders for +/// containers created after the root as reached. Otherwise the full walk +/// (`ensure_all_alive_containers`) also runs; its `Err` on an inconsistent root +/// is returned rather than dropping containers that are still referenced (the +/// caller then exports the root verbatim), and only keys that both leave +/// unreached are removed. +fn prune_cached_root( + root_state_bytes: &Bytes, + root_kv: &KvWrapper, + root_frontiers: &Frontiers, + root_vv: &VersionVector, +) -> Result<Option<PrunedRootState>, LoroEncodeError> { + let root_doc = LoroDoc::new(); + let mut root_state = root_doc.app_state().lock(); + root_state + .store + .decode(root_state_bytes.clone()) + .map_err(LoroEncodeError::from)?; + let candidates = root_state.unreached_stored_containers(root_vv)?; + if candidates.is_empty() { + #[cfg(debug_assertions)] + debug_check_nothing_to_prune(root_state_bytes, root_kv, root_vv); + return Ok(None); + } + + // Remove only what both the filter and the full walk leave unreached: the + // walk rejects forged headers the filter cannot judge, and the filter + // protects entries the walk cannot see (post-root placeholders, children of + // unknown-type containers). + let alive = root_state.ensure_all_alive_containers()?; + let retained = alive_indices_to_bytes(&root_state, &alive); + let removed: Vec<Bytes> = candidates + .into_iter() + .filter(|key| !retained.contains(&key[..])) + .collect(); + if removed.is_empty() { + return Ok(None); + } + + for key in &removed { + root_kv.remove(key); + } + root_kv.insert(FRONTIERS_KEY, root_frontiers.encode().into()); + let state_bytes = root_kv.export(); + root_kv.remove(FRONTIERS_KEY); + Ok(Some(PrunedRootState { + state_bytes, + removed, + })) +} + +/// When the filter finds no candidate, the full walk must not drop anything +/// either, except post-root placeholders. Only checked when no unknown-type +/// container is stored: the filter keeps their subtrees, which the walk cannot +/// see. +#[cfg(debug_assertions)] +fn debug_check_nothing_to_prune( + root_state_bytes: &Bytes, + root_kv: &KvWrapper, + root_vv: &VersionVector, +) { + let keys = root_kv.scan_all_keys(); + if keys + .iter() + .any(|key| ContainerID::from_bytes(key).is_unknown()) + { + return; + } + let check_doc = LoroDoc::new(); + let mut check_state = check_doc.app_state().lock(); + check_state.store.decode(root_state_bytes.clone()).unwrap(); + let Ok(alive) = check_state.ensure_all_alive_containers() else { + return; + }; + let retained = alive_indices_to_bytes(&check_state, &alive); + for key in keys { + if retained.contains(&key[..]) { + continue; + } + let ContainerID::Normal { peer, counter, .. } = ContainerID::from_bytes(&key) else { + continue; + }; + assert!( + !root_vv.includes_id(ID::new(peer, counter)), + "cached-root retention filter missed an unretained container" + ); + } +} + +fn encode_shallow_sections( + oplog_bytes: Bytes, + start_from: &Frontiers, + shallow_root_state_kv: KvWrapper, + latest_state_kv: Option<KvWrapper>, + alive_c_bytes: BTreeSet<Vec<u8>>, +) -> Result<Snapshot, LoroEncodeError> { + shallow_root_state_kv.retain_keys(&alive_c_bytes); + redact_export_states(&shallow_root_state_kv, latest_state_kv.as_ref())?; + let state_bytes = latest_state_kv.map(|kv| kv.export()); + shallow_root_state_kv.insert(FRONTIERS_KEY, start_from.encode().into()); + let shallow_root_state_bytes = shallow_root_state_kv.export(); + + Ok(Snapshot { + oplog_bytes, + state_bytes, + shallow_root_state_bytes, + }) +} + +fn has_unknown_container(mut idxs: impl Iterator<Item = ContainerIdx>) -> bool { + idxs.any(|idx| matches!(idx.get_type(), ContainerType::Unknown(_))) +} + +fn has_unknown_container_key<'a>(mut keys: impl Iterator<Item = &'a Vec<u8>>) -> bool { + keys.any(|key| ContainerID::from_bytes(key).is_unknown()) +} + +/// Nulls the values of rich-text style pairs that are dead in this state (no +/// text between the anchors). In a document whose history is trimmed at this +/// state such a pair can never style anything again, but its value would +/// otherwise ship in the export even though no read API can reach it. See +/// `context/shallow-snapshot-style-redaction.md`. +/// +/// Containers are keyed by `ContainerID` bytes whose first byte is the +/// container type, so the scan stays within the two Text key ranges and blocks +/// holding other containers are passed through in their compressed form. +/// +/// Returns the ids of the redacted `StyleStart` ops, or `None` when the KV was +/// left untouched. +/// Applies dead-style redaction to the states being exported. +/// +/// The root state is fully redacted; the optional overlay (the encoded +/// latest/target state shipped alongside it) only redacts the pairs the root +/// redacted. Pairs that die *after* the root must keep their values so +/// checkouts into the retained range still render them — this function is the +/// single place that protocol lives. +/// +/// Returns whether the root KV changed. Call before the KVs are exported and +/// after `remove_same`, so byte-identical entries still dedup (a deduped entry +/// resolves to the redacted root version on import). +fn redact_export_states( + root: &KvWrapper, + overlay: Option<&KvWrapper>, +) -> Result<bool, LoroEncodeError> { + match redact_dead_text_styles(root, None)? { + None => Ok(false), + Some(redacted) => { + if let Some(overlay) = overlay { + redact_dead_text_styles(overlay, Some(&redacted))?; + } + Ok(true) + } + } +} + +fn redact_dead_text_styles( + kv: &KvWrapper, + only_pairs: Option<&FxHashSet<ID>>, +) -> Result<Option<FxHashSet<ID>>, LoroEncodeError> { + const ROOT_MARK: u8 = 0b1000_0000; + let text_kind = ContainerType::Text.to_u8(); + debug_assert_eq!(text_kind & ROOT_MARK, 0); + let mut redacted: FxHashSet<ID> = FxHashSet::default(); + let mut changed = false; + for first_key_byte in [text_kind, text_kind | ROOT_MARK] { + for (key, value) in kv.scan_range_entries(&[first_key_byte], &[first_key_byte + 1]) { + if value.is_empty() { + continue; + } + let offset = ContainerWrapper::payload_offset(&value).map_err(LoroEncodeError::from)?; + if let Some((payload, ids)) = redact_dead_style_values(&value[offset..], only_pairs) + .map_err(LoroEncodeError::from)? + { + let mut new_value = Vec::with_capacity(offset + payload.len()); + new_value.extend_from_slice(&value[..offset]); + new_value.extend_from_slice(&payload); + kv.insert(&key, new_value.into()); + redacted.extend(ids); + changed = true; + } + } + } + Ok(changed.then_some(redacted)) +} + +pub(crate) fn export_state_only_snapshot<W: std::io::Write>( + doc: &LoroDoc, + target_frontiers: &Frontiers, + w: &mut W, +) -> Result<Frontiers, LoroEncodeError> { + let oplog = doc.oplog().lock(); + let start_from = calc_shallow_doc_start(&oplog, target_frontiers, target_frontiers)?; + let root_vv = frontiers_to_vv_for_export(&oplog, &start_from, "export_state_only_snapshot")?; + let mut start_vv = root_vv.clone(); + for id in start_from.iter() { + // we need to include the ops in start_from, this can make things easier + start_vv.insert(id.peer, id.counter); + } + + loro_common::debug!( + "start version vv={:?} frontiers={:?}", + &start_vv, + &start_from, + ); + + let to_vv = frontiers_to_vv_for_export(&oplog, target_frontiers, "export_state_only_snapshot")?; + let oplog_bytes = + oplog.export_change_store_in_range(&start_vv, &start_from, &to_vv, target_frontiers); + let state_frontiers = doc.state_frontiers(); + let is_attached = !doc.is_detached(); + drop(oplog); + let result = (|| -> Result<(), LoroEncodeError> { + doc._checkout_without_emitting(&start_from, false, false) + .map_err(LoroEncodeError::from)?; + let mut state = doc.app_state().lock(); + let alive_containers = state.ensure_all_alive_containers()?; + if has_unknown_container(alive_containers.iter().copied()) { + return Err(LoroEncodeError::UnknownContainer); + } + let mut alive_c_bytes = alive_indices_to_bytes(&state, &alive_containers); + state.store.flush(); + let shallow_state_kv = state.store.get_kv_clone(); + drop(state); + + doc._checkout_without_emitting(target_frontiers, false, false) + .map_err(LoroEncodeError::from)?; + let mut state = doc.app_state().lock(); + state.ensure_all_alive_containers()?; + state.store.encode(); + retain_created_after_root(&mut state, &root_vv, &mut alive_c_bytes); + + let target_state_kv = state.store.get_kv_clone(); + drop(state); + target_state_kv.remove_same(&shallow_state_kv); + target_state_kv.retain_keys(&alive_c_bytes); + + shallow_state_kv.retain_keys(&alive_c_bytes); + redact_export_states(&shallow_state_kv, Some(&target_state_kv))?; + shallow_state_kv.insert(FRONTIERS_KEY, start_from.encode().into()); + let shallow_state_bytes = shallow_state_kv.export(); + let snapshot = Snapshot { + oplog_bytes, + state_bytes: Some(target_state_kv.export()), + shallow_root_state_bytes: shallow_state_bytes, + }; + _encode_snapshot(&snapshot, w); + Ok(()) + })(); + + restore_export_doc_state(doc, &state_frontiers, is_attached)?; + doc.drop_pending_events(); + result?; + Ok(start_from) +} + +fn alive_indices_to_bytes( + state: &DocState, + alive_containers: &rustc_hash::FxHashSet<ContainerIdx>, +) -> BTreeSet<Vec<u8>> { + alive_containers + .iter() + .map(|idx| state.arena.get_container_id(*idx).unwrap().to_bytes()) + .collect() +} + +fn frontiers_to_vv_for_export( + oplog: &crate::OpLog, + frontiers: &Frontiers, + context: &str, +) -> Result<VersionVector, LoroEncodeError> { + oplog.dag().try_frontiers_to_vv(frontiers)?.ok_or_else(|| { + LoroEncodeError::FrontiersNotFound(format!( + "{context}: unreachable frontiers {frontiers:?}" + )) + }) +} + +fn restore_export_doc_state( + doc: &LoroDoc, + state_frontiers: &Frontiers, + was_attached: bool, +) -> Result<(), LoroEncodeError> { + if &doc.state_frontiers() != state_frontiers { + doc._checkout_without_emitting(state_frontiers, false, false) + .map_err(LoroEncodeError::from)?; + } + + if was_attached { + doc.set_detached(false); + } + + Ok(()) +} + +/// Picks the shallow root for an export at `frontiers`. +/// +/// The root must be a *critical version* of every op the export retains: each +/// one is causally before the root or causally after it, never concurrent. +/// The shallow format stores the state at the root plus every op above it, so +/// an op concurrent with the root belongs to neither side and the snapshot +/// cannot be imported (loro-dev/loro#1095). The meet of the heads is not +/// enough. +/// +/// `retained_to` is where the retained history ends: the latest version for a +/// shallow snapshot, `frontiers` itself for a state-only snapshot. It matters +/// because a branch merged after `frontiers` that forked below it is +/// concurrent with `frontiers`, so a single-head past version is not a valid +/// root on its own. See `docs/critical-version-spec.md`. +fn calc_shallow_doc_start( + oplog: &crate::OpLog, + frontiers: &Frontiers, + retained_to: &Frontiers, +) -> Result<Frontiers, LoroEncodeError> { + if frontiers.is_empty() { + return clamp_to_shallow_root(oplog, Frontiers::default()); + } + + // Single-head or empty: the empty version is the answer when no critical + // version exists, e.g. for independent heads with no common history. + let root = oplog + .dag() + .try_latest_single_head_critical_version(frontiers, retained_to)?; + + let mut ans = Frontiers::new(); + for id in root.iter() { + let mut processed = false; + if let Some(op) = oplog.get_op_that_includes(id) { + if let crate::op::InnerContent::List(InnerListOp::StyleStart { .. }) = &op.content { + // StyleStart and StyleEnd operations are kept together in the GC snapshot + // when both exist, so we advance the frontier by one step to include both + // operations. (Id.counter + 1 is guaranteed to be the StyleEnd Op.) + // + // When this doc's history ends at the StyleStart, the end op does not + // exist here; the root keeps the lone start anchor, which the state + // encoding supports (loro-dev/loro#1165). + if oplog.vv().includes_id(id.inc(1)) { + ans.push(id.inc(1)); + processed = true; + } + } + } + + if !processed { + ans.push(id); + } + } + + clamp_to_shallow_root(oplog, ans) +} + +fn clamp_to_shallow_root( + oplog: &crate::OpLog, + frontiers: Frontiers, +) -> Result<Frontiers, LoroEncodeError> { + if oplog.shallow_since_vv().is_empty() { + return Ok(frontiers); + } + + let Some(vv) = oplog.dag().try_frontiers_to_vv(&frontiers)? else { + return Ok(oplog.shallow_since_frontiers().clone()); + }; + + if vv.includes_vv(&oplog.shallow_since_vv().to_vv()) { + Ok(frontiers) + } else { + Ok(oplog.shallow_since_frontiers().clone()) + } +} + +/// Retains container state required by the exported version. +/// +/// The supplied keys retain alive containers and roots. History also needs +/// deleted normal containers whose creating operations belong to `version`. +/// The scan reads encoded keys without decoding container state. Validation +/// completes before the KV store is filtered. +/// +/// # Errors +/// +/// Returns an encoding error for malformed keys or unknown normal containers +/// retained by history. +fn retain_containers_at_version( + state_kv: &KvWrapper, + mut retained_containers: BTreeSet<Vec<u8>>, + version: &VersionVector, +) -> Result<(), LoroEncodeError> { + for key in state_kv.keys() { + let container = ContainerID::try_from_bytes(&key)?; + if let ContainerID::Normal { peer, counter, .. } = container { + if version.includes_id(ID::new(peer, counter)) { + if container.is_unknown() { + return Err(LoroEncodeError::UnknownContainer); + } + retained_containers.insert(key); + } + } + } + state_kv.retain_keys(&retained_containers); + Ok(()) +} + +/// Builds the container-state copy required by a full-history snapshot. +/// +/// `state` MUST already represent `version`. +/// The returned copy retains alive containers and deleted normal containers +/// required by the retained history. +/// +/// # Errors +/// +/// Returns an encoding error for invalid container state, malformed keys, +/// or unsupported retained containers. +fn prepare_snapshot_container_state( + state: &mut DocState, + version: &VersionVector, +) -> Result<KvWrapper, LoroEncodeError> { + let alive_containers = state.ensure_all_alive_containers()?; + if has_unknown_container(alive_containers.iter().copied()) { + return Err(LoroEncodeError::UnknownContainer); + } + + let alive_container_keys = alive_indices_to_bytes(state, &alive_containers); + state.store.flush(); + let state_kv = state.store.get_kv_clone(); + retain_containers_at_version(&state_kv, alive_container_keys, version)?; + Ok(state_kv) +} + +pub(crate) fn encode_snapshot_at<W: std::io::Write>( + doc: &LoroDoc, + frontiers: &Frontiers, + w: &mut W, +) -> Result<(), LoroEncodeError> { + let was_detached = doc.is_detached(); + let version_before_start = doc.state_frontiers().clone(); + doc._checkout_without_emitting(frontiers, true, false) + .map_err(LoroEncodeError::from)?; + let result = 'block: { + let oplog = doc.oplog().lock(); + let mut state = doc.app_state().lock(); + let is_shallow = state.store.shallow_root_store().is_some(); + if is_shallow { + break 'block Err(LoroEncodeError::from(LoroError::NotImplemented( + "fork_at on shallow docs", + ))); + } + + if state.is_in_txn() { + break 'block Err(LoroEncodeError::internal( + "encode_snapshot_at: state is unexpectedly still in a transaction", + )); + } + let oplog_bytes = match oplog.fork_changes_up_to(frontiers) { + Ok(bytes) => bytes, + Err(err) => break 'block Err(err.into()), + }; + let Some(oplog_bytes) = oplog_bytes else { + break 'block Err(LoroEncodeError::FrontiersNotFound(format!( + "frontiers: {:?} when export in SnapshotAt mode", + frontiers + ))); + }; + + if oplog.is_shallow() { + let Some(shallow_root_frontiers) = state.store.shallow_root_frontiers() else { + break 'block Err(LoroEncodeError::internal( + "encode_snapshot_at: shallow oplog is missing shallow root frontiers", + )); + }; + if oplog.shallow_since_frontiers() != shallow_root_frontiers { + break 'block Err(LoroEncodeError::internal( + "encode_snapshot_at: shallow root frontiers are inconsistent", + )); + } + } + + let version = match oplog.dag.try_frontiers_to_vv(frontiers) { + Ok(version) => version, + Err(err) => break 'block Err(err.into()), + }; + let Some(version) = version else { + break 'block Err(LoroEncodeError::FrontiersNotFound(format!( + "frontiers: {:?} when export in SnapshotAt mode", + frontiers + ))); + }; + let state_kv = match prepare_snapshot_container_state(&mut state, &version) { + Ok(state_kv) => state_kv, + Err(error) => break 'block Err(error), + }; + let bytes = state_kv.export(); + _encode_snapshot( + &Snapshot { + oplog_bytes, + state_bytes: Some(bytes), + shallow_root_state_bytes: Bytes::new(), + }, + w, + ); + + Ok(()) + }; + let restore_result = doc + ._checkout_without_emitting(&version_before_start, false, false) + .map_err(LoroEncodeError::from); + doc.set_detached(was_detached); + doc.app_state().lock().take_events(); + + match result { + Err(err) => Err(err), + Ok(()) => restore_result, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::configure::Configure; + use crate::container::idx::ContainerIdx; + use crate::container::richtext::richtext_state::{PosType, RichtextStateChunk}; + use crate::container::richtext::AnchorType; + use crate::encoding::fast_snapshot::_decode_snapshot_bytes; + use crate::encoding::EncodeMode; + use crate::encoding::ExportMode; + use crate::handler::MapHandler; + use crate::handler::TextHandler; + use crate::state::{ContainerCreationContext, FastStateSnapshot, RichtextState}; + use crate::HandlerTrait; + use crate::LoroDoc; + use loro_common::LoroValue; + + fn shallow_sections(blob: &[u8]) -> Snapshot { + let parsed = crate::encoding::parse_header_and_body(blob, true).unwrap(); + _decode_snapshot_bytes(Bytes::copy_from_slice(parsed.body)).unwrap() + } + + /// Reassemble decomposed sections into a complete importable blob + /// (magic + checksum + mode header, matching `encode_with`). + fn assemble_snapshot_blob(sections: &Snapshot) -> Vec<u8> { + let mut blob = Vec::new(); + blob.extend(crate::encoding::MAGIC_BYTES); + blob.extend([0u8; 16]); + blob.extend(EncodeMode::FastSnapshot.to_bytes()); + _encode_snapshot(sections, &mut blob); + let checksum = xxhash_rust::xxh32::xxh32(&blob[20..], crate::encoding::XXH_SEED); + blob[16..20].copy_from_slice(&checksum.to_le_bytes()); + blob + } + + #[test] + fn snapshot_at_alive_walk_error_restores_source() { + let document = LoroDoc::new_auto_commit(); + document.set_peer_id(42).unwrap(); + let child = document + .get_map("parent-a") + .insert_container("child", MapHandler::new_detached()) + .unwrap(); + child.insert("value", 1).unwrap(); + document.commit_then_renew(); + let target = document.oplog_frontiers(); + document.get_map("unrelated").insert("later", 2).unwrap(); + document.commit_then_renew(); + let head = document.oplog_frontiers(); + let mut sections = shallow_sections(&document.export(ExportMode::Snapshot).unwrap()); + let state = crate::utils::kv_wrapper::KvWrapper::new_mem(); + state.import(sections.state_bytes.take().unwrap()).unwrap(); + + let other = LoroDoc::new_auto_commit(); + other.set_peer_id(42).unwrap(); + let other_child = other + .get_map("parent-b") + .insert_container("child", MapHandler::new_detached()) + .unwrap(); + other_child.insert("value", 1).unwrap(); + assert_eq!(child.id(), other_child.id()); + let other_sections = shallow_sections(&other.export(ExportMode::Snapshot).unwrap()); + let other_state = crate::utils::kv_wrapper::KvWrapper::new_mem(); + other_state + .import(other_sections.state_bytes.unwrap()) + .unwrap(); + let child_key = child.id().to_bytes(); + state.insert(&child_key, other_state.get(&child_key).unwrap()); + sections.state_bytes = Some(state.export()); + let snapshot = assemble_snapshot_blob(§ions); + + for detached in [false, true] { + let imported = LoroDoc::new_auto_commit(); + imported.import(&snapshot).unwrap(); + if detached { + imported.detach(); + } + let unaffected = imported.get_map("unrelated").get_value(); + let error = imported + .export(ExportMode::SnapshotAt { + version: std::borrow::Cow::Borrowed(&target), + }) + .unwrap_err(); + assert!(error.to_string().contains("snapshot state encodes parent")); + assert_eq!(imported.state_frontiers(), head); + assert_eq!(imported.is_detached(), detached); + assert_eq!(imported.get_map("unrelated").get_value(), unaffected); + } + } + + /// Decode the style values of a text container straight out of exported + /// state KV bytes, so assertions don't depend on whether the secret is + /// visible through LZ4 compression. + fn text_style_values(kv_bytes: &Bytes, cid: &ContainerID) -> Vec<(ID, LoroValue)> { + let kv = KvWrapper::new_mem(); + kv.import(kv_bytes.clone()).unwrap(); + let value = kv + .get(&cid.to_bytes()) + .expect("text container should be present in the exported state"); + let offset = ContainerWrapper::payload_offset(&value).unwrap(); + let (text, rest) = RichtextState::decode_value(&value[offset..]).unwrap(); + let idx = ContainerIdx::from_index_and_type(0, ContainerType::Text); + let configure = Configure::default(); + let ctx = ContainerCreationContext { + configure: &configure, + peer: 0, + }; + let state = RichtextState::decode_snapshot_fast(idx, (text, rest), ctx).unwrap(); + let mut styles = Vec::new(); + state.iter_raw(&mut |chunk| { + if let RichtextStateChunk::Style { + style, + anchor_type: AnchorType::Start, + } = chunk + { + styles.push((ID::new(style.peer, style.cnt), style.value.clone())); + } + }); + styles + } + + fn root_text_cid() -> ContainerID { + ContainerID::new_root("text", ContainerType::Text) + } + + #[test] + fn shallow_export_nulls_dead_style_values_for_root_and_nested_text() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let root_text = doc.get_text("text"); + root_text.insert(0, "abc", PosType::Unicode).unwrap(); + root_text + .mark(0, 3, "comment", "root-secret".into(), PosType::Unicode) + .unwrap(); + let nested_text = doc + .get_map("meta") + .insert_container("note", TextHandler::new_detached()) + .unwrap(); + nested_text.insert(0, "xyz", PosType::Unicode).unwrap(); + nested_text + .mark(0, 3, "comment", "nested-secret".into(), PosType::Unicode) + .unwrap(); + doc.commit_then_renew(); + root_text.delete(0, 3, PosType::Unicode).unwrap(); + nested_text.delete(0, 3, PosType::Unicode).unwrap(); + doc.commit_then_renew(); + + let blob = doc + .export(ExportMode::shallow_snapshot(&doc.oplog_frontiers())) + .unwrap(); + let sections = shallow_sections(&blob); + + for cid in [root_text_cid(), nested_text.id()] { + let styles = text_style_values(§ions.shallow_root_state_bytes, &cid); + assert_eq!(styles.len(), 1, "container {cid}"); + assert_eq!(styles[0].1, LoroValue::Null, "container {cid}"); + } + } + + #[test] + fn overlay_keeps_style_values_that_die_after_the_root() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let text = doc.get_text("text"); + text.insert(0, "hello", PosType::Unicode).unwrap(); + text.mark(0, 5, "comment", "keep-me".into(), PosType::Unicode) + .unwrap(); + doc.commit_then_renew(); + let start = doc.oplog_frontiers(); + + // The style dies after the shallow root... + text.delete(0, 5, PosType::Unicode).unwrap(); + // ...and enough tail ops force the export to carry the latest state. + let filler = doc.get_map("filler"); + for i in 0..(MAX_OPS_NUM_TO_ENCODE_WITHOUT_LATEST_STATE + 1) { + filler.insert(&i.to_string(), i as i64).unwrap(); + } + doc.commit_then_renew(); + + let blob = doc.export(ExportMode::shallow_snapshot(&start)).unwrap(); + let sections = shallow_sections(&blob); + let state_bytes = sections + .state_bytes + .expect("overlay state should be encoded"); + + let cid = root_text_cid(); + let keep = LoroValue::String("keep-me".into()); + assert_eq!( + text_style_values(§ions.shallow_root_state_bytes, &cid)[0].1, + keep, + "style alive at the root must keep its value" + ); + // The pair is dead in the latest state but was alive at the root, so a + // checkout back into the retained range must still render it. + assert_eq!(text_style_values(&state_bytes, &cid)[0].1, keep); + } + + #[test] + fn overlay_redacts_pairs_dead_at_the_root() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let text = doc.get_text("text"); + text.insert(0, "abc", PosType::Unicode).unwrap(); + text.mark(0, 3, "comment", "dead-secret".into(), PosType::Unicode) + .unwrap(); + doc.commit_then_renew(); + text.delete(0, 3, PosType::Unicode).unwrap(); + doc.commit_then_renew(); + let start = doc.oplog_frontiers(); + + // Make the latest text entry differ from the root entry so it survives + // `remove_same` and must be redacted via the root's pair whitelist. + text.insert(0, "later", PosType::Unicode).unwrap(); + let filler = doc.get_map("filler"); + for i in 0..(MAX_OPS_NUM_TO_ENCODE_WITHOUT_LATEST_STATE + 1) { + filler.insert(&i.to_string(), i as i64).unwrap(); + } + doc.commit_then_renew(); + + let blob = doc.export(ExportMode::shallow_snapshot(&start)).unwrap(); + let sections = shallow_sections(&blob); + let cid = root_text_cid(); + assert_eq!( + text_style_values(§ions.shallow_root_state_bytes, &cid)[0].1, + LoroValue::Null + ); + let state_bytes = sections + .state_bytes + .expect("overlay state should be encoded"); + assert_eq!(text_style_values(&state_bytes, &cid)[0].1, LoroValue::Null); + } + + #[test] + fn legacy_unredacted_shallow_blob_is_cleaned_on_reexport() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let text = doc.get_text("text"); + text.insert(0, "abc", PosType::Unicode).unwrap(); + text.mark(0, 3, "comment", "legacy-secret".into(), PosType::Unicode) + .unwrap(); + doc.commit_then_renew(); + text.delete(0, 3, PosType::Unicode).unwrap(); + doc.commit_then_renew(); + + let blob = doc + .export(ExportMode::shallow_snapshot(&doc.oplog_frontiers())) + .unwrap(); + let mut sections = shallow_sections(&blob); + + // Rebuild the root state the way pre-redaction exports encoded it: the + // doc's own state at the tip still holds the secret value. + let unredacted_root = { + let mut state = doc.app_state().lock(); + state.store.flush(); + let kv = state.store.get_kv_clone(); + drop(state); + kv.insert(FRONTIERS_KEY, doc.oplog_frontiers().encode().into()); + kv.export() + }; + let cid = root_text_cid(); + assert_eq!( + text_style_values(&unredacted_root, &cid)[0].1, + LoroValue::String("legacy-secret".into()), + "test setup must produce an unredacted legacy root" + ); + sections.shallow_root_state_bytes = unredacted_root; + + // Import the legacy-shaped blob; re-exporting must clean the stored + // root bytes on the reuse branch. + let legacy_doc = LoroDoc::new(); + legacy_doc + .import(&assemble_snapshot_blob(§ions)) + .unwrap(); + let reexported = legacy_doc + .export(ExportMode::shallow_snapshot(&legacy_doc.oplog_frontiers())) + .unwrap(); + let resections = shallow_sections(&reexported); + assert_eq!( + text_style_values(&resections.shallow_root_state_bytes, &cid)[0].1, + LoroValue::Null + ); + } + + /// Regression test for the P1 found in review of the bounded container + /// value cache (loro-dev/loro#1092): after a shallow-snapshot import the + /// store is `AllLoaded`, and a container walk evicts most decoded values. + /// Re-exporting the same shallow root must still enumerate every container + /// created after the root — otherwise the latest-state overlay silently + /// drops the evicted ones and the next import loses them. + #[test] + fn reexport_same_shallow_root_after_walk_eviction_keeps_overlay_containers() { + // Doc A: base content behind the shallow root. + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + a.get_text("text") + .insert(0, "base", PosType::Unicode) + .unwrap(); + a.commit_then_renew(); + let start = a.oplog_frontiers(); + + // Doc B: import the shallow snapshot, then create containers that live + // only in the latest-state overlay (they are not in the root KV). + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(2).unwrap(); + b.import(&a.export(ExportMode::shallow_snapshot(&start)).unwrap()) + .unwrap(); + let n = 64; + let list = b.get_list("list"); + for i in 0..n { + let map = list + .insert_container(i, MapHandler::new_detached()) + .unwrap(); + map.insert("key", i as i64).unwrap(); + } + b.commit_then_renew(); + // 2 ops per container > MAX_OPS_NUM_TO_ENCODE_WITHOUT_LATEST_STATE + // (16 in test builds), so this export ships the latest-state overlay. + let blob = b.export(ExportMode::shallow_snapshot(&start)).unwrap(); + + // Doc C imports the blob (store is AllLoaded with lazy wrappers) and + // walks every overlay container, evicting most of them from the + // bounded value cache. + let c = LoroDoc::new_auto_commit(); + c.import(&blob).unwrap(); + let list = c.get_list("list"); + for i in 0..n { + let child_id = list.get(i).unwrap().as_container().unwrap().clone(); + assert_eq!(c.get_map(child_id).get("key"), Some((i as i64).into())); + } + + // Re-exporting the same shallow root reuses the stored root bytes and + // rebuilds the overlay by enumerating all containers. With the broken + // `load_all` short-circuit this dropped every evicted container. + let reexported = c.export(ExportMode::shallow_snapshot(&start)).unwrap(); + assert!( + shallow_sections(&reexported).state_bytes.is_some(), + "test setup must take the overlay export path" + ); + + let d = LoroDoc::new_auto_commit(); + d.import(&reexported).unwrap(); + let list = d.get_list("list"); + assert_eq!(list.len(), n); + for i in 0..n { + let child_id = list + .get(i) + .unwrap_or_else(|| panic!("container {i} lost after shallow re-export")) + .as_container() + .unwrap() + .clone(); + assert_eq!(d.get_map(child_id).get("key"), Some((i as i64).into())); + } + } + + #[test] + fn forward_replay_gate_bounds_prefix_by_ops_ratio_and_bytes() { + let min = MIN_RETAINED_OPS_FOR_FORWARD_ROOT_STATE; + let max_ops = MAX_PRE_ROOT_OPS_FOR_FORWARD_REPLAY; + let max_bytes = MAX_PRE_ROOT_BYTES_FOR_FORWARD_REPLAY; + + // Tail below the minimum: never. + assert!(!forward_replay_gate(min - 1, 0, 0)); + // Balanced prefix/tail: allowed. + assert!(forward_replay_gate(min, min, 1)); + // Prefix larger than 16x the tail: blocked even though both op counts + // are small. + assert!(!forward_replay_gate(min, 17 * min, 1)); + // Prefix above the absolute op cap: blocked. + assert!(!forward_replay_gate(max_ops, max_ops + 1, 1)); + // A byte-heavy but low-op prefix (a Map write is one atom regardless + // of value size): blocked only by the byte leg. + assert!(!forward_replay_gate(min, 1, max_bytes + 1)); + assert!(forward_replay_gate(min, 1, max_bytes)); + } + + /// A byte-heavy, low-op prefix (a huge payload nested inside a Map value, + /// later overwritten) must not be replayed into a temporary doc just + /// because the tail clears the retained-ops threshold. The export must + /// still be correct. + #[test] + fn byte_heavy_low_op_prefix_exports_correctly() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let map = doc.get_map("m"); + let big = "v".repeat(MAX_PRE_ROOT_BYTES_FOR_FORWARD_REPLAY + 1024); + // Nested one level down: the estimator must recurse into it. + let mut payload = crate::FxHashMap::default(); + payload.insert("payload".to_string(), LoroValue::String(big.into())); + map.insert("k", LoroValue::Map(payload.into())).unwrap(); + map.insert("k", "small").unwrap(); + doc.commit_then_renew(); + let f = doc.oplog_frontiers(); + // Tail just past the (test-scale) retained-ops threshold. + let text = doc.get_text("t"); + text.insert( + 0, + &"x".repeat(MIN_RETAINED_OPS_FOR_FORWARD_ROOT_STATE + 1), + PosType::Unicode, + ) + .unwrap(); + doc.commit_then_renew(); + + let blob = doc.export(ExportMode::shallow_snapshot(&f)).unwrap(); + let imported = LoroDoc::new(); + imported.import(&blob).unwrap(); + assert_eq!(imported.get_deep_value(), doc.get_deep_value()); + assert_eq!(imported.shallow_since_frontiers(), f); + } + + #[test] + fn prefix_content_bytes_estimate_counts_value_bytes() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + // One atom carrying 2 MiB of payload. + let big = "v".repeat(2 << 20); + doc.get_map("m").insert("k", big.as_str()).unwrap(); + doc.get_text("t") + .insert(0, "abc", PosType::Unicode) + .unwrap(); + doc.commit_then_renew(); + + let oplog = doc.oplog().lock(); + let spans = vec![IdSpan::new(1, 0, 4)]; + let est = estimate_ops_content_bytes(&oplog, &spans, usize::MAX); + assert!( + est >= (2 << 20) + 3, + "estimate must include the value bytes, got {est}" + ); + // Early exit: a smaller cap stops the walk as soon as it is exceeded. + let capped = estimate_ops_content_bytes(&oplog, &spans, 1024); + assert!(capped > 1024 && capped <= 1024 + (2 << 20) + 64); + } + + #[test] + fn prefix_content_bytes_estimate_counts_nested_style_and_commit_msg_bytes() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let big = "v".repeat(1 << 20); + + // One atom whose payload is a nested map/list holding the big string. + let mut inner = crate::FxHashMap::default(); + inner.insert("payload".to_string(), LoroValue::String(big.clone().into())); + let nested = LoroValue::List(vec![LoroValue::Map(inner.into())].into()); + doc.get_map("m").insert("k", nested).unwrap(); + + // A style mark value. + let text = doc.get_text("t"); + text.insert(0, "ab", PosType::Unicode).unwrap(); + text.mark( + 0, + 1, + "comment", + LoroValue::String(big.clone().into()), + PosType::Unicode, + ) + .unwrap(); + + // A commit message. + doc.set_next_commit_message(&big); + doc.commit_then_renew(); + + let oplog = doc.oplog().lock(); + let end = *oplog.vv().get(&1).unwrap(); + let spans = vec![IdSpan::new(1, 0, end)]; + let est = estimate_ops_content_bytes(&oplog, &spans, usize::MAX); + assert!( + est >= 3 * big.len(), + "estimate must count nested values, style values and the commit message, got {est}" + ); + } + + #[test] + fn prefix_content_bytes_estimate_counts_style_keys_and_root_names() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let big = "k".repeat(1 << 20); + + // A huge style key: the block encoder copies keys into the block's + // key register. + let mut styles = crate::container::richtext::config::StyleConfigMap::new(); + styles.insert( + big.as_str().into(), + crate::container::richtext::config::StyleConfig { + expand: crate::container::richtext::ExpandType::After, + }, + ); + doc.config_text_style(styles); + let text = doc.get_text("t"); + text.insert(0, "ab", PosType::Unicode).unwrap(); + text.mark(0, 1, big.as_str(), LoroValue::Bool(true), PosType::Unicode) + .unwrap(); + + // A huge root container name: copied into the block's container arena. + doc.get_text(big.as_str()) + .insert(0, "x", PosType::Unicode) + .unwrap(); + doc.commit_then_renew(); + + let oplog = doc.oplog().lock(); + let end = *oplog.vv().get(&1).unwrap(); + let spans = vec![IdSpan::new(1, 0, end)]; + let est = estimate_ops_content_bytes(&oplog, &spans, usize::MAX); + assert!( + est >= 2 * big.len(), + "estimate must count style keys and root container names, got {est}" + ); + } + + /// Unknown-container ops can carry OwnedValue::MarkStart / ListSet with + /// variable-length key/value payloads (the decoder accepts any Value for + /// unknown containers and owns it); the prefix estimator must count them. + #[test] + fn prefix_content_bytes_estimate_counts_unknown_owned_values() { + use crate::change::Change; + use crate::encoding::value::{MarkStart, OwnedValue}; + use crate::op::{FutureInnerContent, InnerContent, Op}; + use rle::RleVec; + + let big = "v".repeat(1 << 20); + let doc = LoroDoc::new(); + let mut oplog = doc.oplog().lock(); + let idx = oplog + .arena + .register_container(&ContainerID::new_root("u", ContainerType::Unknown(7))); + + let mut ops: RleVec<[Op; 1]> = RleVec::new(); + ops.push(Op::new( + ID::new(1, 0), + InnerContent::Future(FutureInnerContent::Unknown { + prop: 0, + value: Box::new(OwnedValue::MarkStart(MarkStart { + len: 1, + key: big.as_str().into(), + value: LoroValue::Null, + info: 0, + })), + }), + idx, + )); + ops.push(Op::new( + ID::new(1, 1), + InnerContent::Future(FutureInnerContent::Unknown { + prop: 0, + value: Box::new(OwnedValue::ListSet { + peer_idx: 0, + lamport: 0, + value: LoroValue::String(big.clone().into()), + }), + }), + idx, + )); + oplog.insert_new_change( + Change::new(ops, Frontiers::default(), ID::new(1, 0), 0, 0), + false, + ); + + let est = estimate_ops_content_bytes(&oplog, &[IdSpan::new(1, 0, 2)], usize::MAX); + assert!( + est >= 2 * big.len(), + "estimate must count MarkStart keys and ListSet values on unknown ops, got {est}" + ); + } + + /// Rewrites the parent id in the header of `target`'s entry in the shallow + /// root state of a replay-only (`E`) shallow blob, keeping its payload. + fn forge_root_state(blob: &[u8], edit: impl FnOnce(&KvWrapper)) -> Vec<u8> { + let mut sections = shallow_sections(blob); + assert!( + sections.state_bytes.is_none(), + "fixture must use the replay path" + ); + let kv = KvWrapper::new_mem(); + kv.import(sections.shallow_root_state_bytes.clone()) + .unwrap(); + edit(&kv); + sections.shallow_root_state_bytes = kv.export(); + assemble_snapshot_blob(§ions) + } + + fn with_header_parent(value: &[u8], parent: Option<ContainerID>) -> Bytes { + let offset = ContainerWrapper::payload_offset(value).unwrap(); + let mut reader = &value[1..]; + let depth = leb128::read::unsigned(&mut reader).unwrap(); + let mut out = vec![value[0]]; + leb128::write::unsigned(&mut out, depth).unwrap(); + postcard::to_io(&parent, &mut out).unwrap(); + out.extend_from_slice(&value[offset..]); + out.into() + } + + fn set_header_parent(kv: &KvWrapper, target: &ContainerID, parent: Option<ContainerID>) { + let key = target.to_bytes(); + let value = kv.get(&key).expect("target container is stored"); + kv.insert(&key, with_header_parent(&value, parent)); + } + + fn root_state_keys(blob: &[u8]) -> BTreeSet<Vec<u8>> { + let kv = KvWrapper::new_mem(); + kv.import(shallow_sections(blob).shallow_root_state_bytes) + .unwrap(); + kv.keys() + } + + /// Every export of a doc whose cached root has a forged header must succeed + /// and keep the doc's content: the root is exported verbatim, and no + /// referenced data is dropped. + fn assert_exports_keep_content(doc: &LoroDoc, expected: &LoroValue, case: &str) { + for mode in [ + ExportMode::shallow_snapshot(&doc.shallow_since_frontiers()), + ExportMode::Snapshot, + ] { + let bytes = doc + .export(mode) + .unwrap_or_else(|e| panic!("{case}: export failed: {e}")); + let again = LoroDoc::new(); + again.import(&bytes).unwrap(); + assert_eq!( + &again.get_deep_value(), + expected, + "{case}: export lost data" + ); + } + // A fork copies the cached root verbatim and must not panic. + assert_eq!(&doc.fork().get_deep_value(), expected, "{case}: fork"); + } + + #[test] + fn cached_root_with_forged_parent_header_never_drops_referenced_containers() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + doc.get_map("decoy").insert("k", 1).unwrap(); + let fill = |map: &MapHandler| -> ContainerID { + map.insert("secret", "KEEP-ME").unwrap(); + let body = map + .insert_container("body", TextHandler::new_detached()) + .unwrap(); + body.insert(0, "inner", PosType::Unicode).unwrap(); + body.id() + }; + let row = doc + .get_map("rows") + .insert_container("row", MapHandler::new_detached()) + .unwrap(); + let row_body = fill(&row); + let item = doc + .get_list("list") + .insert_container(0, MapHandler::new_detached()) + .unwrap(); + let item_body = fill(&item); + let moved = doc + .get_movable_list("movable") + .insert_container(0, MapHandler::new_detached()) + .unwrap(); + let moved_body = fill(&moved); + let tree = doc.get_tree("tree"); + let node = tree.create(crate::TreeParentId::Root).unwrap(); + let meta = tree.get_meta(node).unwrap(); + let meta_body = fill(&meta); + doc.commit_then_renew(); + let root = doc.oplog_frontiers(); + doc.get_map("other").insert("after", 1).unwrap(); + doc.commit_then_renew(); + let expected = doc.get_deep_value(); + let blob = doc.export(ExportMode::shallow_snapshot(&root)).unwrap(); + + let decoy = ContainerID::new_root("decoy", ContainerType::Map); + let missing = ContainerID::new_normal(ID::new(99, 7), ContainerType::Map); + let targets = [ + ("map row", row.id(), Some(row_body.clone())), + ("list element", item.id(), Some(item_body)), + ("movable list element", moved.id(), Some(moved_body)), + ("tree meta", meta.id(), Some(meta_body)), + ("inner text", row_body, None), + ]; + let mut cases = 0; + for (name, target, child) in targets { + let mut parents = vec![ + ("decoy root", Some(decoy.clone())), + ("missing id", Some(missing.clone())), + ("itself", Some(target.clone())), + ("none", None), + ]; + if let Some(child) = child { + parents.push(("own child (cycle)", Some(child))); + } + for (how, parent) in parents { + let case = format!("{name} claims parent {how}"); + let forged = + forge_root_state(&blob, |kv| set_header_parent(kv, &target, parent.clone())); + let shallow = LoroDoc::new(); + shallow.import(&forged).unwrap(); + assert_eq!(shallow.get_deep_value(), expected, "{case}: import"); + assert_exports_keep_content(&shallow, &expected, &case); + cases += 1; + } + } + assert_eq!(cases, 24); + } + + #[test] + fn cached_root_keeps_children_of_unknown_containers() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let tmp = ContainerID::new_root("tmp", ContainerType::Map); + let row = doc + .get_map("tmp") + .insert_container("row", MapHandler::new_detached()) + .unwrap(); + row.insert("secret", "KEEP-ME").unwrap(); + doc.commit_then_renew(); + let root = doc.oplog_frontiers(); + doc.get_map("other").insert("after", 1).unwrap(); + doc.commit_then_renew(); + let blob = doc.export(ExportMode::shallow_snapshot(&root)).unwrap(); + + // Re-home `row` under a root of a container type this version does not + // know: its child references cannot be read, so the child must stay. + let unknown = ContainerID::new_root("future", ContainerType::Unknown(9)); + let forged = forge_root_state(&blob, |kv| { + let tmp_value = kv.remove(&tmp.to_bytes()).unwrap(); + let offset = ContainerWrapper::payload_offset(&tmp_value).unwrap(); + let mut header = with_header_parent(&tmp_value, None)[..offset].to_vec(); + header[0] = ContainerType::Unknown(9).to_u8(); + kv.insert(&unknown.to_bytes(), header.into()); + set_header_parent(kv, &row.id(), Some(unknown.clone())); + }); + let shallow = LoroDoc::new(); + shallow.import(&forged).unwrap(); + assert!(root_state_keys(&forged).contains(&row.id().to_bytes())); + for mode in [ + ExportMode::shallow_snapshot(&shallow.shallow_since_frontiers()), + ExportMode::Snapshot, + ] { + let bytes = shallow.export(mode).unwrap(); + assert!( + root_state_keys(&bytes).contains(&row.id().to_bytes()), + "child of an unknown container was dropped" + ); + LoroDoc::new().import(&bytes).unwrap(); + } + } + + /// An encoded wrapper of an unknown container type with an empty payload. + fn unknown_entry(kind: u8, parent: Option<ContainerID>) -> Bytes { + let mut out = vec![kind]; + leb128::write::unsigned(&mut out, 1).unwrap(); + postcard::to_io(&parent, &mut out).unwrap(); + out.into() + } + + #[test] + fn unknown_types_do_not_shield_unrelated_dead_containers() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + // Op 0@1 is a scalar write, so no real container has id 0@1. + doc.get_map("decoy").insert("k", 1).unwrap(); + let row = doc + .get_map("rows") + .insert_container("row", MapHandler::new_detached()) + .unwrap(); + row.insert("secret", "KEEP-ME").unwrap(); + doc.commit_then_renew(); + let root = doc.oplog_frontiers(); + doc.get_map("other").insert("after", 1).unwrap(); + doc.commit_then_renew(); + let expected = doc.get_deep_value(); + let blob = doc.export(ExportMode::shallow_snapshot(&root)).unwrap(); + + let rows = ContainerID::new_root("rows", ContainerType::Map); + // A pre-root map nothing references, carrying a copy of `row`'s content. + let dead = ContainerID::new_normal(ID::new(1, 0), ContainerType::Map); + let unknown = ContainerType::Unknown(9); + let cases: [(&str, Option<ContainerID>, Option<(ContainerID, Bytes)>); 4] = [ + ( + "dead entry claims a missing unknown root parent", + Some(ContainerID::new_root("ghost", unknown)), + None, + ), + ( + "dead entry claims a missing unknown normal parent", + Some(ContainerID::new_normal(ID::new(5, 5), unknown)), + None, + ), + ( + "unreferenced unknown root is stored", + Some(rows.clone()), + Some(( + ContainerID::new_root("future", unknown), + unknown_entry(9, None), + )), + ), + ( + "unreferenced unknown normal entry is stored", + Some(rows.clone()), + Some(( + ContainerID::new_normal(ID::new(1, 0), unknown), + unknown_entry(9, Some(rows.clone())), + )), + ), + ]; + for (case, dead_parent, extra) in cases { + let forged = forge_root_state(&blob, |kv| { + let value = kv.get(&row.id().to_bytes()).unwrap(); + kv.insert(&dead.to_bytes(), with_header_parent(&value, dead_parent)); + if let Some((id, value)) = &extra { + kv.insert(&id.to_bytes(), value.clone()); + } + }); + assert!(root_state_keys(&forged).contains(&dead.to_bytes())); + let shallow = LoroDoc::new(); + shallow.import(&forged).unwrap(); + // An unknown root shows up as `Null`; everything else is unchanged. + let imported = shallow.get_deep_value(); + for key in ["decoy", "rows", "other"] { + assert_eq!( + imported.as_map().unwrap().get(key), + expected.as_map().unwrap().get(key), + "{case}: import" + ); + } + for mode in [ + ExportMode::shallow_snapshot(&shallow.shallow_since_frontiers()), + ExportMode::Snapshot, + ] { + let bytes = shallow.export(mode).unwrap(); + let keys = root_state_keys(&bytes); + assert!(!keys.contains(&dead.to_bytes()), "{case}: dead entry kept"); + assert!(keys.contains(&row.id().to_bytes()), "{case}: live row lost"); + if let Some((id, _)) = &extra { + // Roots are always retained; an unreferenced normal entry is not. + assert_eq!(keys.contains(&id.to_bytes()), id.is_root(), "{case}"); + } + let again = LoroDoc::new(); + again.import(&bytes).unwrap(); + assert_eq!(again.get_deep_value(), imported, "{case}"); + } + } + } +} diff --git a/vendor/loro-internal/src/encoding/value.rs b/vendor/loro-internal/src/encoding/value.rs new file mode 100644 index 0000000..c0711e0 --- /dev/null +++ b/vendor/loro-internal/src/encoding/value.rs @@ -0,0 +1,1535 @@ +use enum_as_inner::EnumAsInner; +use fractional_index::FractionalIndex; +use loro_common::{ + ContainerID, ContainerType, Counter, InternalString, LoroError, LoroResult, LoroValue, PeerID, + TreeID, ID, +}; +use rustc_hash::FxHashMap; +use serde::{Deserialize, Serialize}; +use std::sync::Arc; + +use crate::{ + change::Lamport, container::tree::tree_op::TreeOp, + encoding::outdated_encode_reordered::MAX_COLLECTION_SIZE, +}; + +use super::{ + arena::{EncodedRegisters, EncodedTreeID}, + value_register::ValueRegister, +}; + +pub trait ValueDecodedArenasTrait { + fn keys(&self) -> &[InternalString]; + fn peers(&self) -> &[PeerID]; + fn decode_tree_op( + &self, + positions: &[Vec<u8>], + op: super::value::EncodedTreeMove, + id: ID, + ) -> LoroResult<crate::container::tree::tree_op::TreeOp>; +} + +pub trait ValueEncodeRegister { + fn key_mut(&mut self) -> &mut ValueRegister<InternalString>; + fn peer_mut(&mut self) -> &mut ValueRegister<PeerID>; + fn encode_tree_op(&mut self, op: &TreeOp) -> Value<'static>; +} + +#[derive(Debug)] +pub enum ValueKind { + Null, // 0 + True, // 1 + False, // 2 + I64, // 3 + F64, // 4 + Str, // 5 + Binary, // 6 + ContainerType, // 7 + DeleteOnce, // 8 + DeleteSeq, // 9 + DeltaInt, // 10 + LoroValue, // 11 + MarkStart, // 12 + TreeMove, // 13 + ListMove, // 14 + ListSet, // 15 + Future(FutureValueKind), + // 16 Counter + RawTreeMove, // 17 +} + +#[derive(Debug)] +pub enum LoroValueKind { + Null, + True, + False, + I64, + F64, + Binary, + Str, + List, + Map, + ContainerType, +} +impl LoroValueKind { + fn from_u8(kind: u8) -> Option<Self> { + match kind { + 0 => Some(LoroValueKind::Null), + 1 => Some(LoroValueKind::True), + 2 => Some(LoroValueKind::False), + 3 => Some(LoroValueKind::I64), + 4 => Some(LoroValueKind::F64), + 5 => Some(LoroValueKind::Str), + 6 => Some(LoroValueKind::Binary), + 7 => Some(LoroValueKind::List), + 8 => Some(LoroValueKind::Map), + 9 => Some(LoroValueKind::ContainerType), + _ => None, + } + } + + fn to_u8(&self) -> u8 { + match self { + LoroValueKind::Null => 0, + LoroValueKind::True => 1, + LoroValueKind::False => 2, + LoroValueKind::I64 => 3, + LoroValueKind::F64 => 4, + LoroValueKind::Str => 5, + LoroValueKind::Binary => 6, + LoroValueKind::List => 7, + LoroValueKind::Map => 8, + LoroValueKind::ContainerType => 9, + } + } +} + +#[derive(Debug)] +pub enum FutureValueKind { + Unknown(u8), +} + +impl ValueKind { + pub(crate) fn to_u8(&self) -> u8 { + match self { + ValueKind::Null => 0, + ValueKind::True => 1, + ValueKind::False => 2, + ValueKind::I64 => 3, + ValueKind::F64 => 4, + ValueKind::Str => 5, + ValueKind::Binary => 6, + ValueKind::ContainerType => 7, + ValueKind::DeleteOnce => 8, + ValueKind::DeleteSeq => 9, + ValueKind::DeltaInt => 10, + ValueKind::LoroValue => 11, + ValueKind::MarkStart => 12, + ValueKind::TreeMove => 13, + ValueKind::ListMove => 14, + ValueKind::ListSet => 15, + ValueKind::Future(future_value_kind) => match future_value_kind { + FutureValueKind::Unknown(u8) => *u8 | 0x80, + }, + ValueKind::RawTreeMove => 16, + } + } + + pub(crate) fn from_u8(mut kind: u8) -> Self { + kind &= 0x7F; + match kind { + 0 => ValueKind::Null, + 1 => ValueKind::True, + 2 => ValueKind::False, + 3 => ValueKind::I64, + 4 => ValueKind::F64, + 5 => ValueKind::Str, + 6 => ValueKind::Binary, + 7 => ValueKind::ContainerType, + 8 => ValueKind::DeleteOnce, + 9 => ValueKind::DeleteSeq, + 10 => ValueKind::DeltaInt, + 11 => ValueKind::LoroValue, + 12 => ValueKind::MarkStart, + 13 => ValueKind::TreeMove, + 14 => ValueKind::ListMove, + 15 => ValueKind::ListSet, + 16 => ValueKind::RawTreeMove, + _ => ValueKind::Future(FutureValueKind::Unknown(kind)), + } + } +} + +#[derive(Debug, EnumAsInner)] +pub enum Value<'a> { + Null, + True, + False, + I64(i64), + F64(f64), + Str(&'a str), + Binary(&'a [u8]), + ContainerIdx(usize), + DeleteOnce, + DeleteSeq, + DeltaInt(i32), + #[allow(clippy::enum_variant_names)] + LoroValue(LoroValue), + MarkStart(MarkStart), + TreeMove(EncodedTreeMove), + RawTreeMove(RawTreeMove), + ListMove { + from: usize, + from_idx: usize, + lamport: usize, + }, + ListSet { + peer_idx: usize, + lamport: Lamport, + value: LoroValue, + }, + Future(FutureValue<'a>), +} + +#[derive(Debug)] +pub enum FutureValue<'a> { + // The future value cannot depend on the arena for encoding. + Unknown { kind: u8, data: &'a [u8] }, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "value_type", content = "value", rename_all = "snake_case")] +pub enum OwnedValue { + Null, + True, + False, + I64(i64), + F64(f64), + Str(Arc<String>), + Binary(Arc<Vec<u8>>), + ContainerIdx(usize), + DeleteOnce, + DeleteSeq, + DeltaInt(i32), + LoroValue(LoroValue), + MarkStart(MarkStart), + TreeMove(EncodedTreeMove), + RawTreeMove(RawTreeMove), + ListMove { + from: usize, + from_idx: usize, + lamport: usize, + }, + ListSet { + peer_idx: usize, + lamport: Lamport, + value: LoroValue, + }, + #[serde(untagged)] + Future(OwnedFutureValue), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "value_type", content = "value")] +pub enum OwnedFutureValue { + // The future value cannot depend on the arena for encoding. + Unknown { kind: u8, data: Arc<Vec<u8>> }, +} + +impl<'a> Value<'a> { + pub fn from_owned(owned_value: &'a OwnedValue) -> Self { + match owned_value { + OwnedValue::Null => Value::Null, + OwnedValue::True => Value::True, + OwnedValue::False => Value::False, + OwnedValue::DeleteOnce => Value::DeleteOnce, + OwnedValue::I64(x) => Value::I64(*x), + OwnedValue::ContainerIdx(x) => Value::ContainerIdx(*x), + OwnedValue::F64(x) => Value::F64(*x), + OwnedValue::Str(x) => Value::Str(x.as_str()), + OwnedValue::DeleteSeq => Value::DeleteSeq, + OwnedValue::DeltaInt(x) => Value::DeltaInt(*x), + OwnedValue::LoroValue(x) => Value::LoroValue(x.clone()), + OwnedValue::MarkStart(x) => Value::MarkStart(x.clone()), + OwnedValue::Binary(x) => Value::Binary(x.as_slice()), + OwnedValue::TreeMove(x) => Value::TreeMove(x.clone()), + OwnedValue::ListMove { + from, + from_idx, + lamport, + } => Value::ListMove { + from: *from, + from_idx: *from_idx, + lamport: *lamport, + }, + OwnedValue::ListSet { + peer_idx, + lamport, + value, + } => Value::ListSet { + peer_idx: *peer_idx, + lamport: *lamport, + value: value.clone(), + }, + OwnedValue::Future(value) => match value { + OwnedFutureValue::Unknown { kind, data } => Value::Future(FutureValue::Unknown { + kind: *kind, + data: data.as_slice(), + }), + }, + OwnedValue::RawTreeMove(t) => Value::RawTreeMove(t.clone()), + } + } + + pub fn into_owned(self) -> OwnedValue { + match self { + Value::Null => OwnedValue::Null, + Value::True => OwnedValue::True, + Value::False => OwnedValue::False, + Value::DeleteOnce => OwnedValue::DeleteOnce, + Value::I64(x) => OwnedValue::I64(x), + Value::ContainerIdx(x) => OwnedValue::ContainerIdx(x), + Value::F64(x) => OwnedValue::F64(x), + Value::Str(x) => OwnedValue::Str(Arc::new(x.to_owned())), + Value::DeleteSeq => OwnedValue::DeleteSeq, + Value::DeltaInt(x) => OwnedValue::DeltaInt(x), + Value::LoroValue(x) => OwnedValue::LoroValue(x), + Value::MarkStart(x) => OwnedValue::MarkStart(x), + Value::Binary(x) => OwnedValue::Binary(Arc::new(x.to_owned())), + Value::TreeMove(x) => OwnedValue::TreeMove(x), + Value::ListMove { + from, + from_idx, + lamport, + } => OwnedValue::ListMove { + from, + from_idx, + lamport, + }, + Value::ListSet { + peer_idx, + lamport, + value, + } => OwnedValue::ListSet { + peer_idx, + lamport, + value, + }, + Value::Future(value) => match value { + FutureValue::Unknown { kind, data } => { + OwnedValue::Future(OwnedFutureValue::Unknown { + kind, + data: Arc::new(data.to_owned()), + }) + } + }, + Value::RawTreeMove(t) => OwnedValue::RawTreeMove(t), + } + } + + fn decode_without_arena<'r: 'a>( + future_kind: FutureValueKind, + value_reader: &'r mut ValueReader, + ) -> LoroResult<Self> { + let bytes = value_reader.read_binary()?; + let value = match future_kind { + FutureValueKind::Unknown(kind) => { + Value::Future(FutureValue::Unknown { kind, data: bytes }) + } + }; + Ok(value) + } + + pub(crate) fn decode<'r: 'a>( + kind: ValueKind, + value_reader: &'r mut ValueReader, + arenas: &'a dyn ValueDecodedArenasTrait, + id: ID, + ) -> LoroResult<Self> { + Ok(match kind { + ValueKind::Null => Value::Null, + ValueKind::True => Value::True, + ValueKind::False => Value::False, + ValueKind::I64 => Value::I64(value_reader.read_i64()?), + ValueKind::F64 => Value::F64(value_reader.read_f64()?), + ValueKind::Str => Value::Str(value_reader.read_str()?), + ValueKind::Binary => Value::Binary(value_reader.read_binary()?), + ValueKind::ContainerType => Value::ContainerIdx(value_reader.read_usize()?), + ValueKind::DeleteOnce => Value::DeleteOnce, + ValueKind::DeleteSeq => Value::DeleteSeq, + ValueKind::DeltaInt => Value::DeltaInt(value_reader.read_i32()?), + ValueKind::LoroValue => { + Value::LoroValue(value_reader.read_value_type_and_content(arenas.keys(), id)?) + } + ValueKind::MarkStart => Value::MarkStart(value_reader.read_mark(arenas.keys(), id)?), + ValueKind::TreeMove => Value::TreeMove(value_reader.read_tree_move()?), + ValueKind::RawTreeMove => Value::RawTreeMove(value_reader.read_raw_tree_move()?), + ValueKind::ListMove => { + let from = value_reader.read_usize()?; + let from_idx = value_reader.read_usize()?; + let lamport = value_reader.read_usize()?; + Value::ListMove { + from, + from_idx, + lamport, + } + } + ValueKind::ListSet => { + let peer_idx = value_reader.read_usize()?; + let lamport = value_reader.read_usize()? as u32; + let value = value_reader.read_value_type_and_content(arenas.keys(), id)?; + Value::ListSet { + peer_idx, + lamport, + value, + } + } + ValueKind::Future(future_kind) => { + Self::decode_without_arena(future_kind, value_reader)? + } + }) + } + + fn encode_without_registers( + value: FutureValue, + value_writer: &mut ValueWriter, + ) -> (FutureValueKind, usize) { + // Note: we should encode FutureValue as binary data. + // [binary data length, binary data] + // when decoding, we will use reader.read_binary() to read the binary data. + // So such as FutureValue::Counter, we should write 0 as the length of binary data first. + match value { + FutureValue::Unknown { kind, data } => ( + FutureValueKind::Unknown(kind), + value_writer.write_binary(data), + ), + } + } + + pub(super) fn encode( + self, + value_writer: &mut ValueWriter, + registers: &mut dyn ValueEncodeRegister, + ) -> (ValueKind, usize) { + match self { + Value::Null => (ValueKind::Null, 0), + Value::True => (ValueKind::True, 0), + Value::False => (ValueKind::False, 0), + Value::I64(x) => (ValueKind::I64, value_writer.write_i64(x)), + Value::F64(x) => (ValueKind::F64, value_writer.write_f64(x)), + Value::Str(x) => (ValueKind::Str, value_writer.write_str(x)), + Value::Binary(x) => (ValueKind::Binary, value_writer.write_binary(x)), + Value::ContainerIdx(x) => (ValueKind::ContainerType, value_writer.write_usize(x)), + Value::DeleteOnce => (ValueKind::DeleteOnce, 0), + Value::DeleteSeq => (ValueKind::DeleteSeq, 0), + Value::DeltaInt(x) => (ValueKind::DeltaInt, value_writer.write_i32(x)), + Value::LoroValue(x) => ( + ValueKind::LoroValue, + value_writer.write_value_type_and_content(&x, registers), + ), + Value::MarkStart(x) => (ValueKind::MarkStart, value_writer.write_mark(x, registers)), + Value::TreeMove(tree) => (ValueKind::TreeMove, value_writer.write_tree_move(&tree)), + Value::ListMove { + from, + from_idx, + lamport, + } => ( + ValueKind::ListMove, + value_writer.write_usize(from) + + value_writer.write_usize(from_idx) + + value_writer.write_usize(lamport), + ), + Value::ListSet { + peer_idx, + lamport, + value, + } => ( + ValueKind::ListSet, + value_writer.write_usize(peer_idx) + + value_writer.write_usize(lamport as usize) + + value_writer.write_value_type_and_content(&value, registers), + ), + Value::Future(value) => { + let (k, i) = Self::encode_without_registers(value, value_writer); + (ValueKind::Future(k), i) + } + Value::RawTreeMove(x) => (ValueKind::RawTreeMove, value_writer.write_raw_tree_move(x)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct MarkStart { + pub len: u32, + pub key: InternalString, + pub value: LoroValue, + pub info: u8, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct RawTreeMove { + pub subject_peer_idx: usize, + pub subject_cnt: Counter, + pub is_parent_null: bool, + pub parent_peer_idx: usize, + pub parent_cnt: Counter, + pub position_idx: usize, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct EncodedTreeMove { + pub target_idx: usize, + pub is_parent_null: bool, + pub parent_idx: usize, + pub position: usize, +} + +impl EncodedTreeMove { + pub fn as_tree_op( + &self, + peer_ids: &[u64], + positions: &[Vec<u8>], + tree_ids: &[EncodedTreeID], + op_id: ID, + ) -> LoroResult<TreeOp> { + let parent = if self.is_parent_null { + None + } else { + let EncodedTreeID { peer_idx, counter } = tree_ids[self.parent_idx]; + Some(TreeID::new( + *(peer_ids + .get(peer_idx) + .ok_or(LoroError::DecodeDataCorruptionError)?), + counter as Counter, + )) + }; + let is_delete = parent.is_some_and(|p| TreeID::is_deleted_root(&p)); + let position = if is_delete { + None + } else { + let bytes = &positions[self.position]; + Some(FractionalIndex::from_bytes(bytes.clone())) + }; + let EncodedTreeID { peer_idx, counter } = tree_ids[self.target_idx]; + let target = TreeID::new( + *(peer_ids + .get(peer_idx) + .ok_or(LoroError::DecodeDataCorruptionError)?), + counter as Counter, + ); + + let is_create = target.id() == op_id; + let op = if is_delete { + TreeOp::Delete { target } + } else if is_create { + TreeOp::Create { + target, + parent, + position: position.unwrap(), + } + } else { + TreeOp::Move { + target, + parent, + position: position.unwrap(), + } + }; + Ok(op) + } + + pub fn from_tree_op<'p, 'a: 'p>(op: &'a TreeOp, registers: &mut EncodedRegisters) -> Self { + match op { + TreeOp::Create { + target, + parent, + position, + } + | TreeOp::Move { + target, + parent, + position, + } => { + let bytes = position.as_bytes(); + let either::Right(position_register) = &mut registers.position else { + unreachable!() + }; + let position = position_register.get(&bytes).unwrap(); + let target_idx = registers.tree_id.register(&EncodedTreeID { + peer_idx: registers.peer.register(&target.peer), + counter: target.counter, + }); + + let parent_idx = parent.map(|x| { + registers.tree_id.register(&EncodedTreeID { + peer_idx: registers.peer.register(&x.peer), + counter: x.counter, + }) + }); + EncodedTreeMove { + target_idx, + is_parent_null: parent.is_none(), + parent_idx: parent_idx.unwrap_or(0), + position, + } + } + TreeOp::Delete { target } => { + let target_idx = registers.tree_id.register(&EncodedTreeID { + peer_idx: registers.peer.register(&target.peer), + counter: target.counter, + }); + let parent_idx = registers.tree_id.register(&EncodedTreeID { + peer_idx: registers.peer.register(&TreeID::delete_root().peer), + counter: TreeID::delete_root().counter, + }); + EncodedTreeMove { + target_idx, + is_parent_null: false, + parent_idx, + position: 0, + } + } + } + } +} + +pub struct ValueWriter { + buffer: Vec<u8>, +} + +pub struct ValueReader<'a> { + raw: &'a [u8], +} + +impl<'a> ValueReader<'a> { + pub fn new(raw: &'a [u8]) -> Self { + ValueReader { raw } + } + + pub fn read_value_type_and_content( + &mut self, + keys: &[InternalString], + id: ID, + ) -> LoroResult<LoroValue> { + let kind = self.read_u8()?; + let kind = LoroValueKind::from_u8(kind).ok_or(LoroError::DecodeDataCorruptionError)?; + self.read_value_content(kind, keys, id) + } + + pub fn read_value_content( + &mut self, + kind: LoroValueKind, + keys: &[InternalString], + id: ID, + ) -> LoroResult<LoroValue> { + Ok(match kind { + LoroValueKind::Null => LoroValue::Null, + LoroValueKind::True => LoroValue::Bool(true), + LoroValueKind::False => LoroValue::Bool(false), + LoroValueKind::I64 => LoroValue::I64(self.read_i64()?), + LoroValueKind::F64 => LoroValue::Double(self.read_f64()?), + LoroValueKind::Str => LoroValue::String((self.read_str()?.to_owned()).into()), + LoroValueKind::List => { + let len = self.read_usize()?; + if len > MAX_COLLECTION_SIZE { + return Err(LoroError::DecodeDataCorruptionError); + } + let mut ans = Vec::with_capacity(len); + for i in 0..len { + ans.push(self.recursive_read_value_type_and_content(keys, id.inc(i as i32))?); + } + ans.into() + } + LoroValueKind::Map => { + let len = self.read_usize()?; + if len > MAX_COLLECTION_SIZE { + return Err(LoroError::DecodeDataCorruptionError); + } + let mut ans = FxHashMap::with_capacity_and_hasher(len, Default::default()); + for _ in 0..len { + let key_idx = self.read_usize()?; + let key = keys + .get(key_idx) + .ok_or(LoroError::DecodeDataCorruptionError)? + .to_string(); + let value = self.recursive_read_value_type_and_content(keys, id)?; + ans.insert(key, value); + } + ans.into() + } + LoroValueKind::Binary => LoroValue::Binary(self.read_binary()?.to_owned().into()), + LoroValueKind::ContainerType => { + let u8 = self.read_u8()?; + let container_id = ContainerID::new_normal( + id, + ContainerType::try_from_u8(u8).unwrap_or(ContainerType::Unknown(u8)), + ); + + LoroValue::Container(container_id) + } + }) + } + + /// Read a value that may be very deep efficiently. + /// + /// This method avoids using recursive calls to read deeply nested values. + /// Otherwise, it may cause stack overflow. + fn recursive_read_value_type_and_content( + &mut self, + keys: &[InternalString], + id: ID, + ) -> LoroResult<LoroValue> { + #[derive(Debug)] + enum Task { + Init, + ReadList { + left: usize, + vec: Vec<LoroValue>, + key_idx_in_parent: usize, + }, + ReadMap { + left: usize, + map: FxHashMap<String, LoroValue>, + key_idx_in_parent: usize, + }, + } + impl Task { + fn should_read(&self) -> bool { + !matches!( + self, + Self::ReadList { left: 0, .. } | Self::ReadMap { left: 0, .. } + ) + } + + fn key_idx(&self) -> usize { + match self { + Self::ReadList { + key_idx_in_parent, .. + } => *key_idx_in_parent, + Self::ReadMap { + key_idx_in_parent, .. + } => *key_idx_in_parent, + _ => unreachable!(), + } + } + + fn into_value(self) -> LoroValue { + match self { + Self::ReadList { vec, .. } => vec.into(), + Self::ReadMap { map, .. } => map.into(), + _ => unreachable!(), + } + } + } + let mut stack = vec![Task::Init]; + while let Some(mut task) = stack.pop() { + if task.should_read() { + let key_idx = if matches!(task, Task::ReadMap { .. }) { + self.read_usize()? + } else { + 0 + }; + let kind = self.read_u8()?; + let kind = + LoroValueKind::from_u8(kind).ok_or(LoroError::DecodeDataCorruptionError)?; + let value = match kind { + LoroValueKind::Null => LoroValue::Null, + LoroValueKind::True => LoroValue::Bool(true), + LoroValueKind::False => LoroValue::Bool(false), + LoroValueKind::I64 => LoroValue::I64(self.read_i64()?), + LoroValueKind::F64 => LoroValue::Double(self.read_f64()?), + LoroValueKind::Str => LoroValue::String((self.read_str()?.to_owned()).into()), + LoroValueKind::List => { + let len = self.read_usize()?; + if len > MAX_COLLECTION_SIZE { + return Err(LoroError::DecodeDataCorruptionError); + } + let ans = Vec::with_capacity(len); + stack.push(task); + stack.push(Task::ReadList { + left: len, + vec: ans, + key_idx_in_parent: key_idx, + }); + continue; + } + LoroValueKind::Map => { + let len = self.read_usize()?; + if len > MAX_COLLECTION_SIZE { + return Err(LoroError::DecodeDataCorruptionError); + } + + let ans = FxHashMap::with_capacity_and_hasher(len, Default::default()); + stack.push(task); + stack.push(Task::ReadMap { + left: len, + map: ans, + key_idx_in_parent: key_idx, + }); + continue; + } + LoroValueKind::Binary => { + LoroValue::Binary(self.read_binary()?.to_owned().into()) + } + LoroValueKind::ContainerType => { + let u8 = self.read_u8()?; + let container_id = ContainerID::new_normal( + id, + ContainerType::try_from_u8(u8).unwrap_or(ContainerType::Unknown(u8)), + ); + + LoroValue::Container(container_id) + } + }; + + task = match task { + Task::Init => { + return Ok(value); + } + Task::ReadList { + mut left, + mut vec, + key_idx_in_parent, + } => { + left -= 1; + vec.push(value); + let task = Task::ReadList { + left, + vec, + key_idx_in_parent, + }; + if left != 0 { + stack.push(task); + continue; + } + + task + } + Task::ReadMap { + mut left, + mut map, + key_idx_in_parent, + } => { + left -= 1; + let key = keys + .get(key_idx) + .ok_or(LoroError::DecodeDataCorruptionError)? + .to_string(); + map.insert(key, value); + let task = Task::ReadMap { + left, + map, + key_idx_in_parent, + }; + if left != 0 { + stack.push(task); + continue; + } + task + } + }; + } + + let key_index = task.key_idx(); + let value = task.into_value(); + if let Some(last) = stack.last_mut() { + match last { + Task::Init => { + return Ok(value); + } + Task::ReadList { left, vec, .. } => { + *left -= 1; + vec.push(value); + } + Task::ReadMap { left, map, .. } => { + *left -= 1; + let key = keys + .get(key_index) + .ok_or(LoroError::DecodeDataCorruptionError)? + .to_string(); + map.insert(key, value); + } + } + } else { + return Ok(value); + } + } + + unreachable!(); + } + + pub fn read_i64(&mut self) -> LoroResult<i64> { + leb128::read::signed(&mut self.raw).map_err(|_| LoroError::DecodeDataCorruptionError) + } + + #[allow(unused)] + pub fn read_u64(&mut self) -> LoroResult<u64> { + leb128::read::unsigned(&mut self.raw).map_err(|_| LoroError::DecodeDataCorruptionError) + } + + #[allow(unused)] + pub fn read_i32(&mut self) -> LoroResult<i32> { + leb128::read::signed(&mut self.raw) + .map(|x| x as i32) + .map_err(|_| LoroError::DecodeDataCorruptionError) + } + + pub fn read_f64(&mut self) -> LoroResult<f64> { + if self.raw.len() < 8 { + return Err(LoroError::DecodeDataCorruptionError); + } + + let mut bytes = [0; 8]; + bytes.copy_from_slice(&self.raw[..8]); + self.raw = &self.raw[8..]; + Ok(f64::from_be_bytes(bytes)) + } + + pub fn read_usize(&mut self) -> LoroResult<usize> { + Ok(leb128::read::unsigned(&mut self.raw) + .map_err(|_| LoroError::DecodeDataCorruptionError)? as usize) + } + + pub fn read_str(&mut self) -> LoroResult<&'a str> { + let len = self.read_usize()?; + if self.raw.len() < len { + return Err(LoroError::DecodeDataCorruptionError); + } + + let ans = std::str::from_utf8(&self.raw[..len]) + .map_err(|_| LoroError::DecodeDataCorruptionError)?; + self.raw = &self.raw[len..]; + Ok(ans) + } + + #[allow(unused)] + fn read_binary_vec(&mut self) -> LoroResult<Vec<u8>> { + let len = self.read_usize()?; + if self.raw.len() < len { + return Err(LoroError::DecodeDataCorruptionError); + } + let ans = &self.raw[..len]; + self.raw = &self.raw[len..]; + Ok(ans.to_vec()) + } + + fn read_u8(&mut self) -> LoroResult<u8> { + if self.raw.is_empty() { + return Err(LoroError::DecodeDataCorruptionError); + } + + let ans = self.raw[0]; + self.raw = &self.raw[1..]; + Ok(ans) + } + + pub fn read_binary(&mut self) -> LoroResult<&'a [u8]> { + let len = self.read_usize()?; + if self.raw.len() < len { + return Err(LoroError::DecodeDataCorruptionError); + } + + let ans = &self.raw[..len]; + self.raw = &self.raw[len..]; + Ok(ans) + } + + pub fn read_mark<'s: 'm, 'm>( + &mut self, + keys: &'s [InternalString], + id: ID, + ) -> LoroResult<MarkStart> { + let info = self.read_u8()?; + let len = self.read_usize()?; + let key_idx = self.read_usize()?; + let value = self.read_value_type_and_content(keys, id)?; + Ok(MarkStart { + len: len as u32, + key: keys + .get(key_idx) + .ok_or(LoroError::DecodeDataCorruptionError)? + .clone(), + value, + info, + }) + } + + pub fn read_tree_move(&mut self) -> LoroResult<EncodedTreeMove> { + let subject_idx = self.read_usize()?; + let is_parent_null = self.read_u8()? != 0; + let position = self.read_usize()?; + let mut parent_idx = 0; + if !is_parent_null { + parent_idx = self.read_usize()?; + } + Ok(EncodedTreeMove { + target_idx: subject_idx, + is_parent_null, + parent_idx, + position, + }) + } + + fn read_raw_tree_move(&mut self) -> LoroResult<RawTreeMove> { + let subject_peer_idx = self.read_usize()?; + let subject_cnt = self.read_usize()?; + let position_idx = self.read_usize()?; + let is_parent_null = self.read_u8()? != 0; + let mut parent_peer_idx = 0; + let mut parent_cnt = 0; + if !is_parent_null { + parent_peer_idx = self.read_usize()?; + parent_cnt = self.read_usize()?; + } + + Ok(RawTreeMove { + subject_peer_idx, + subject_cnt: subject_cnt as i32, + position_idx, + is_parent_null, + parent_peer_idx, + parent_cnt: parent_cnt as i32, + }) + } +} + +impl ValueWriter { + pub fn new() -> Self { + ValueWriter { buffer: Vec::new() } + } + + pub fn write_value_type_and_content( + &mut self, + value: &LoroValue, + registers: &mut dyn ValueEncodeRegister, + ) -> usize { + let len = self.write_u8(get_loro_value_kind(value).to_u8()); + let (_, l) = self.write_value_content(value, registers); + len + l + } + + pub fn write_value_content( + &mut self, + value: &LoroValue, + registers: &mut dyn ValueEncodeRegister, + ) -> (LoroValueKind, usize) { + enum Task<'a> { + Value(&'a LoroValue, bool), + Key(&'a str), + } + let start = self.buffer.len(); + let mut pending = vec![Task::Value(value, false)]; + while let Some(task) = pending.pop() { + let (value, with_kind) = match task { + Task::Value(value, with_kind) => (value, with_kind), + Task::Key(key) => { + let key_idx = registers.key_mut().register(&key.into()); + self.write_usize(key_idx); + continue; + } + }; + if with_kind { + self.write_u8(get_loro_value_kind(value).to_u8()); + } + match value { + LoroValue::Null | LoroValue::Bool(_) => {} + LoroValue::I64(v) => { + self.write_i64(*v); + } + LoroValue::Double(v) => { + self.write_f64(*v); + } + LoroValue::String(v) => { + self.write_str(v); + } + LoroValue::Binary(v) => { + self.write_binary(v); + } + LoroValue::Container(c) => { + self.write_u8(c.container_type().to_u8()); + } + LoroValue::List(list) => { + self.write_usize(list.len()); + pending.extend(list.iter().rev().map(|value| Task::Value(value, true))); + } + LoroValue::Map(map) => { + self.write_usize(map.len()); + let start = pending.len(); + for (key, value) in map.iter() { + pending.push(Task::Key(key)); + pending.push(Task::Value(value, true)); + } + pending[start..].reverse(); + } + } + } + (get_loro_value_kind(value), self.buffer.len() - start) + } + + pub fn write_i64(&mut self, value: i64) -> usize { + let len = self.buffer.len(); + leb128::write::signed(&mut self.buffer, value).unwrap(); + self.buffer.len() - len + } + + fn write_i32(&mut self, value: i32) -> usize { + let len = self.buffer.len(); + leb128::write::signed(&mut self.buffer, value as i64).unwrap(); + self.buffer.len() - len + } + + #[allow(unused)] + fn write_u64(&mut self, value: u64) -> usize { + let len = self.buffer.len(); + leb128::write::unsigned(&mut self.buffer, value).unwrap(); + self.buffer.len() - len + } + + fn write_usize(&mut self, value: usize) -> usize { + let len = self.buffer.len(); + leb128::write::unsigned(&mut self.buffer, value as u64).unwrap(); + self.buffer.len() - len + } + + fn write_f64(&mut self, value: f64) -> usize { + let len = self.buffer.len(); + self.buffer.extend_from_slice(&value.to_be_bytes()); + self.buffer.len() - len + } + + fn write_str(&mut self, value: &str) -> usize { + let len = self.buffer.len(); + self.write_usize(value.len()); + self.buffer.extend_from_slice(value.as_bytes()); + self.buffer.len() - len + } + + fn write_u8(&mut self, value: u8) -> usize { + let len = self.buffer.len(); + self.buffer.push(value); + self.buffer.len() - len + } + + fn write_binary(&mut self, value: &[u8]) -> usize { + let len = self.buffer.len(); + self.write_usize(value.len()); + self.buffer.extend_from_slice(value); + self.buffer.len() - len + } + + fn write_mark(&mut self, mark: MarkStart, registers: &mut dyn ValueEncodeRegister) -> usize { + let key_idx = registers.key_mut().register(&mark.key); + let len = self.buffer.len(); + self.write_u8(mark.info); + self.write_usize(mark.len as usize); + self.write_usize(key_idx); + self.write_value_type_and_content(&mark.value, registers); + self.buffer.len() - len + } + + fn write_tree_move(&mut self, op: &EncodedTreeMove) -> usize { + let len = self.buffer.len(); + self.write_usize(op.target_idx); + self.write_u8(op.is_parent_null as u8); + self.write_usize(op.position); + if op.is_parent_null { + return self.buffer.len() - len; + } + self.write_usize(op.parent_idx); + self.buffer.len() - len + } + + pub(crate) fn finish(self) -> Vec<u8> { + self.buffer + } + + fn write_raw_tree_move(&mut self, op: RawTreeMove) -> usize { + let len = self.buffer.len(); + self.write_usize(op.subject_peer_idx); + self.write_usize(op.subject_cnt as usize); + self.write_usize(op.position_idx); + self.write_u8(op.is_parent_null as u8); + if op.is_parent_null { + return self.buffer.len() - len; + } + self.write_usize(op.parent_peer_idx); + self.write_usize(op.parent_cnt as usize); + self.buffer.len() - len + } +} + +fn get_loro_value_kind(value: &LoroValue) -> LoroValueKind { + match value { + LoroValue::Null => LoroValueKind::Null, + LoroValue::Bool(true) => LoroValueKind::True, + LoroValue::Bool(false) => LoroValueKind::False, + LoroValue::I64(_) => LoroValueKind::I64, + LoroValue::Double(_) => LoroValueKind::F64, + LoroValue::String(_) => LoroValueKind::Str, + LoroValue::List(_) => LoroValueKind::List, + LoroValue::Map(_) => LoroValueKind::Map, + LoroValue::Binary(_) => LoroValueKind::Binary, + LoroValue::Container(_) => LoroValueKind::ContainerType, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{container::tree::tree_op::TreeOp, fx_map}; + + #[derive(Default)] + struct TestRegisters { + key: ValueRegister<InternalString>, + peer: ValueRegister<PeerID>, + } + + impl ValueEncodeRegister for TestRegisters { + fn key_mut(&mut self) -> &mut ValueRegister<InternalString> { + &mut self.key + } + + fn peer_mut(&mut self) -> &mut ValueRegister<PeerID> { + &mut self.peer + } + + fn encode_tree_op(&mut self, op: &TreeOp) -> Value<'static> { + let target = match op { + TreeOp::Create { target, .. } + | TreeOp::Move { target, .. } + | TreeOp::Delete { target } => *target, + }; + + Value::TreeMove(EncodedTreeMove { + target_idx: self.peer.register(&target.peer), + is_parent_null: true, + parent_idx: 0, + position: 0, + }) + } + } + + struct TestArenas { + keys: Vec<InternalString>, + peers: Vec<PeerID>, + } + + impl ValueDecodedArenasTrait for TestArenas { + fn keys(&self) -> &[InternalString] { + &self.keys + } + + fn peers(&self) -> &[PeerID] { + &self.peers + } + + fn decode_tree_op( + &self, + positions: &[Vec<u8>], + op: EncodedTreeMove, + id: ID, + ) -> LoroResult<TreeOp> { + op.as_tree_op(&self.peers, positions, &[], id) + } + } + + fn encode_then_decode_owned(value: Value<'_>) -> OwnedValue { + let mut writer = ValueWriter::new(); + let mut registers = TestRegisters::default(); + let (kind, _) = value.encode(&mut writer, &mut registers); + let bytes = writer.finish(); + let arenas = TestArenas { + keys: registers.key.unwrap_vec(), + peers: registers.peer.unwrap_vec(), + }; + let mut reader = ValueReader::new(&bytes); + Value::decode(kind, &mut reader, &arenas, ID::new(9, 1)) + .unwrap() + .into_owned() + } + + #[test] + fn value_kind_tags_roundtrip_including_future_kinds() { + let kinds = [ + ValueKind::Null, + ValueKind::True, + ValueKind::False, + ValueKind::I64, + ValueKind::F64, + ValueKind::Str, + ValueKind::Binary, + ValueKind::ContainerType, + ValueKind::DeleteOnce, + ValueKind::DeleteSeq, + ValueKind::DeltaInt, + ValueKind::LoroValue, + ValueKind::MarkStart, + ValueKind::TreeMove, + ValueKind::ListMove, + ValueKind::ListSet, + ValueKind::RawTreeMove, + ]; + + for kind in kinds { + let tag = kind.to_u8(); + assert_eq!(ValueKind::from_u8(tag).to_u8(), tag); + } + + let future = ValueKind::Future(FutureValueKind::Unknown(42)); + assert_eq!(future.to_u8(), 42 | 0x80); + match ValueKind::from_u8(future.to_u8()) { + ValueKind::Future(FutureValueKind::Unknown(kind)) => assert_eq!(kind, 42), + other => panic!("expected future kind, got {other:?}"), + } + + let loro_kinds = [ + LoroValueKind::Null, + LoroValueKind::True, + LoroValueKind::False, + LoroValueKind::I64, + LoroValueKind::F64, + LoroValueKind::Str, + LoroValueKind::Binary, + LoroValueKind::List, + LoroValueKind::Map, + LoroValueKind::ContainerType, + ]; + for kind in loro_kinds { + assert_eq!( + LoroValueKind::from_u8(kind.to_u8()) + .expect("known value kind tag should decode") + .to_u8(), + kind.to_u8() + ); + } + } + + #[test] + fn owned_value_conversion_is_lossless_for_all_current_variants() { + let mark = MarkStart { + len: 3, + key: "bold".into(), + value: true.into(), + info: 7, + }; + let tree_move = EncodedTreeMove { + target_idx: 2, + is_parent_null: false, + parent_idx: 1, + position: 4, + }; + let raw_tree_move = RawTreeMove { + subject_peer_idx: 3, + subject_cnt: 9, + is_parent_null: false, + parent_peer_idx: 4, + parent_cnt: 8, + position_idx: 6, + }; + let values = vec![ + OwnedValue::Null, + OwnedValue::True, + OwnedValue::False, + OwnedValue::I64(-123), + OwnedValue::F64(1.25), + OwnedValue::Str(Arc::new("hello".to_string())), + OwnedValue::Binary(Arc::new(vec![1, 2, 3])), + OwnedValue::ContainerIdx(42), + OwnedValue::DeleteOnce, + OwnedValue::DeleteSeq, + OwnedValue::DeltaInt(-9), + OwnedValue::LoroValue( + fx_map!( + "k".to_string() => + LoroValue::from(vec![LoroValue::from(1_i64), LoroValue::from("v")]) + ) + .into(), + ), + OwnedValue::MarkStart(mark), + OwnedValue::TreeMove(tree_move), + OwnedValue::RawTreeMove(raw_tree_move), + OwnedValue::ListMove { + from: 1, + from_idx: 2, + lamport: 3, + }, + OwnedValue::ListSet { + peer_idx: 4, + lamport: 5, + value: "set".into(), + }, + OwnedValue::Future(OwnedFutureValue::Unknown { + kind: 99, + data: Arc::new(vec![4, 5, 6]), + }), + ]; + + for owned in values { + assert_eq!(Value::from_owned(&owned).into_owned(), owned); + } + } + + #[test] + fn value_encode_decode_roundtrips_non_loro_value_variants() { + let cases = vec![ + (Value::Null, OwnedValue::Null), + (Value::True, OwnedValue::True), + (Value::False, OwnedValue::False), + (Value::I64(-42), OwnedValue::I64(-42)), + (Value::F64(3.5), OwnedValue::F64(3.5)), + ( + Value::Str("encoded"), + OwnedValue::Str(Arc::new("encoded".to_string())), + ), + ( + Value::Binary(&[9, 8, 7]), + OwnedValue::Binary(Arc::new(vec![9, 8, 7])), + ), + (Value::ContainerIdx(17), OwnedValue::ContainerIdx(17)), + (Value::DeleteOnce, OwnedValue::DeleteOnce), + (Value::DeleteSeq, OwnedValue::DeleteSeq), + (Value::DeltaInt(-17), OwnedValue::DeltaInt(-17)), + ( + Value::LoroValue(fx_map!("nested".to_string() => LoroValue::from(1_i64)).into()), + OwnedValue::LoroValue( + fx_map!("nested".to_string() => LoroValue::from(1_i64)).into(), + ), + ), + ( + Value::MarkStart(MarkStart { + len: 2, + key: "italic".into(), + value: "yes".into(), + info: 3, + }), + OwnedValue::MarkStart(MarkStart { + len: 2, + key: "italic".into(), + value: "yes".into(), + info: 3, + }), + ), + ( + Value::TreeMove(EncodedTreeMove { + target_idx: 5, + is_parent_null: true, + parent_idx: 0, + position: 7, + }), + OwnedValue::TreeMove(EncodedTreeMove { + target_idx: 5, + is_parent_null: true, + parent_idx: 0, + position: 7, + }), + ), + ( + Value::RawTreeMove(RawTreeMove { + subject_peer_idx: 1, + subject_cnt: 2, + is_parent_null: true, + parent_peer_idx: 0, + parent_cnt: 0, + position_idx: 3, + }), + OwnedValue::RawTreeMove(RawTreeMove { + subject_peer_idx: 1, + subject_cnt: 2, + is_parent_null: true, + parent_peer_idx: 0, + parent_cnt: 0, + position_idx: 3, + }), + ), + ( + Value::ListMove { + from: 3, + from_idx: 4, + lamport: 5, + }, + OwnedValue::ListMove { + from: 3, + from_idx: 4, + lamport: 5, + }, + ), + ( + Value::ListSet { + peer_idx: 1, + lamport: 2, + value: vec![LoroValue::from(1_i64), LoroValue::from(2_i64)].into(), + }, + OwnedValue::ListSet { + peer_idx: 1, + lamport: 2, + value: vec![LoroValue::from(1_i64), LoroValue::from(2_i64)].into(), + }, + ), + ( + Value::Future(FutureValue::Unknown { + kind: 100, + data: &[1, 3, 5], + }), + OwnedValue::Future(OwnedFutureValue::Unknown { + kind: 100, + data: Arc::new(vec![1, 3, 5]), + }), + ), + ]; + + for (value, expected) in cases { + assert_eq!(encode_then_decode_owned(value), expected); + } + } + + #[test] + fn loro_value_writer_reader_roundtrips_nested_scalars_collections_and_containers() { + let container = ContainerID::new_normal(ID::new(7, 2), ContainerType::Tree); + let value: LoroValue = fx_map!( + "null".to_string() => LoroValue::Null, + "true".to_string() => true.into(), + "false".to_string() => false.into(), + "int".to_string() => (-9_i64).into(), + "float".to_string() => 2.25.into(), + "string".to_string() => "text".into(), + "binary".to_string() => vec![1_u8, 2, 3].into(), + "container".to_string() => container.into(), + "list".to_string() => vec![ + LoroValue::Null, + true.into(), + fx_map!("child".to_string() => "value".into()).into(), + ].into() + ) + .into(); + + let mut writer = ValueWriter::new(); + let mut registers = TestRegisters::default(); + writer.write_value_type_and_content(&value, &mut registers); + let keys = registers.key.unwrap_vec(); + assert!(keys.iter().any(|key| key.as_ref() == "child")); + + let bytes = writer.finish(); + let mut reader = ValueReader::new(&bytes); + let decoded = reader + .read_value_type_and_content(&keys, ID::new(7, 2)) + .unwrap(); + assert_eq!(decoded, value); + } + + #[test] + fn reader_reports_corruption_for_truncated_or_invalid_value_payloads() { + assert!(ValueReader::new(&[]).read_i64().is_err()); + assert!(ValueReader::new(&[1, 2, 3]).read_f64().is_err()); + assert!(ValueReader::new(&[5, b'a']).read_str().is_err()); + assert!(ValueReader::new(&[5, 1, 2]).read_binary().is_err()); + + let mut writer = ValueWriter::new(); + writer.write_usize(1); + writer.write_usize(9); + writer.write_value_type_and_content(&"value".into(), &mut TestRegisters::default()); + let bytes = writer.finish(); + let mut reader = ValueReader::new(&bytes); + assert!(reader + .read_value_content(LoroValueKind::Map, &[], ID::new(1, 0)) + .is_err()); + } +} diff --git a/vendor/loro-internal/src/encoding/value_register.rs b/vendor/loro-internal/src/encoding/value_register.rs new file mode 100644 index 0000000..a2bc97d --- /dev/null +++ b/vendor/loro-internal/src/encoding/value_register.rs @@ -0,0 +1,52 @@ +use rustc_hash::FxHashMap; + +#[derive(Debug)] +pub struct ValueRegister<T> { + map_value_to_index: FxHashMap<T, usize>, + vec: Vec<T>, +} + +impl<T: std::hash::Hash + Clone + PartialEq + Eq> Default for ValueRegister<T> { + fn default() -> Self { + Self::new() + } +} + +impl<T: std::hash::Hash + Clone + PartialEq + Eq> ValueRegister<T> { + pub fn new() -> Self { + Self { + map_value_to_index: FxHashMap::default(), + vec: Vec::new(), + } + } + + /// Return the index of the given value. If it does not exist, + /// insert it and return the new index. + pub fn register(&mut self, key: &T) -> usize { + if let Some(index) = self.map_value_to_index.get(key) { + *index + } else { + let idx = self.vec.len(); + self.vec.push(key.clone()); + self.map_value_to_index.insert(key.clone(), idx); + idx + } + } + + pub fn get(&self, key: &T) -> Option<usize> { + self.map_value_to_index.get(key).copied() + } + + pub fn unwrap_vec(self) -> Vec<T> { + self.vec + } + + #[allow(unused)] + pub fn get_value(&self, index: usize) -> Option<&T> { + self.vec.get(index) + } + + pub fn vec(&self) -> &Vec<T> { + &self.vec + } +} diff --git a/vendor/loro-internal/src/error.rs b/vendor/loro-internal/src/error.rs new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/vendor/loro-internal/src/error.rs @@ -0,0 +1 @@ + diff --git a/vendor/loro-internal/src/estimated_size.rs b/vendor/loro-internal/src/estimated_size.rs new file mode 100644 index 0000000..64718f5 --- /dev/null +++ b/vendor/loro-internal/src/estimated_size.rs @@ -0,0 +1,27 @@ +use loro_common::LoroValue; + +pub trait EstimatedSize { + /// Estimate the storage size of the object in bytes + fn estimate_storage_size(&self) -> usize; +} + +impl EstimatedSize for LoroValue { + fn estimate_storage_size(&self) -> usize { + match self { + LoroValue::Null => 1, + LoroValue::Bool(_) => 1, + LoroValue::Double(_) => 8, + LoroValue::I64(i) => 1 + (64 - i.leading_zeros()) as usize / 7, + LoroValue::Binary(b) => b.len() + 1, + LoroValue::String(s) => s.len() + 1, + LoroValue::List(l) => 3 + l.iter().map(|x| x.estimate_storage_size()).sum::<usize>(), + LoroValue::Map(m) => { + 3 + m + .iter() + .map(|(k, v)| k.len() + 3 + v.estimate_storage_size()) + .sum::<usize>() + } + LoroValue::Container(_) => 6, + } + } +} diff --git a/vendor/loro-internal/src/event.rs b/vendor/loro-internal/src/event.rs new file mode 100644 index 0000000..9bb5f10 --- /dev/null +++ b/vendor/loro-internal/src/event.rs @@ -0,0 +1,573 @@ +use enum_as_inner::EnumAsInner; +use itertools::Itertools; +use loro_delta::{array_vec::ArrayVec, delta_trait::DeltaAttr, DeltaItem, DeltaRope}; +use rustc_hash::FxHashMap; +use serde::{Deserialize, Serialize}; +use smallvec::SmallVec; + +use crate::{ + container::richtext::richtext_state::RichtextStateChunk, + delta::{Delta, MapDelta, Meta, MovableListInnerDelta, ResolvedMapDelta, TreeDelta, TreeDiff}, + diff_calc::DiffMode, + handler::ValueOrHandler, + op::SliceWithId, + utils::string_slice::StringSlice, + InternalString, +}; + +use std::{borrow::Cow, hash::Hash}; + +use loro_common::{ContainerID, LoroValue, TreeID}; + +use crate::{container::idx::ContainerIdx, version::Frontiers}; + +#[derive(Debug, Clone)] +pub struct ContainerDiff { + pub id: ContainerID, + pub path: Vec<(ContainerID, Index)>, + pub(crate) idx: ContainerIdx, + pub is_unknown: bool, + pub diff: Diff, + /// Set when `diff` is a full-state revival of a container that kept its id and state. + pub(crate) kept: Option<KeptChange>, +} + +impl ContainerDiff { + /// The container's actual change in this event, which differs from `diff` when `diff` is + /// a full-state revival of a container that kept its state. `None` means unchanged. + pub(crate) fn change(&self) -> Option<&Diff> { + match &self.kept { + None => Some(&self.diff), + Some(KeptChange::Unchanged) => None, + Some(KeptChange::Changed(d)) => Some(d), + } + } +} + +/// Events and [`crate::undo::DiffBatch`]es describe a container that becomes visible with its +/// full state, which is what a consumer that never saw it needs. A re-activated mergeable child +/// (and every container it holds) keeps its id and its hidden state, so its actual change is +/// recorded next to the full state. Undo, revert and the undo manager's transforms use it. +/// See context/mergeable-containers.md. +#[derive(Debug, Clone)] +pub(crate) enum KeptChange { + Unchanged, + Changed(Diff), +} + +impl KeptChange { + pub(crate) fn from_diff(diff: Diff) -> Self { + if diff.is_empty() { + KeptChange::Unchanged + } else { + KeptChange::Changed(diff) + } + } + + /// `self` followed by `next`. + pub(crate) fn then(self, next: KeptChange) -> Self { + match (self, next) { + (KeptChange::Unchanged, x) | (x, KeptChange::Unchanged) => x, + (KeptChange::Changed(a), KeptChange::Changed(b)) => { + KeptChange::Changed(a.compose(b).unwrap()) + } + } + } +} + +/// The kind of the event trigger. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum EventTriggerKind { + /// The event is triggered by a local transaction. + Local, + /// The event is triggered by importing + Import, + /// The event is triggered by checkout + Checkout, +} + +impl std::fmt::Display for EventTriggerKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + EventTriggerKind::Local => write!(f, "local"), + EventTriggerKind::Import => write!(f, "import"), + EventTriggerKind::Checkout => write!(f, "checkout"), + } + } +} + +impl EventTriggerKind { + #[inline] + pub fn is_local(&self) -> bool { + matches!(self, EventTriggerKind::Local) + } + + #[inline] + pub fn is_import(&self) -> bool { + matches!(self, EventTriggerKind::Import) + } + + #[inline] + pub fn is_checkout(&self) -> bool { + matches!(self, EventTriggerKind::Checkout) + } +} + +#[derive(Debug, Clone)] +pub struct DiffEvent<'a> { + /// The receiver of the event. + pub current_target: Option<ContainerID>, + /// A list of events that should be received by the current target. + pub events: &'a [&'a ContainerDiff], + pub event_meta: &'a DocDiff, +} + +/// It's the exposed event type. +/// It's exposed to the user. The user can use this to apply the diff to their local state. +/// +/// [DocDiff] may include the diff that calculated from several transactions and imports. +/// They all should have the same origin and local flag. +#[derive(Debug, Clone)] +pub struct DocDiff { + pub from: Frontiers, + pub to: Frontiers, + pub origin: InternalString, + pub by: EventTriggerKind, + pub diff: Vec<ContainerDiff>, +} + +#[derive(Debug, Clone)] +pub(crate) struct InternalContainerDiff { + pub(crate) idx: ContainerIdx, + /// Indicates whether this event was generated by a container that has been resurrected during a checkout operation. + pub(crate) bring_back: bool, + pub(crate) diff: DiffVariant, + /// This mode decides how should we apply the diff. + pub(crate) diff_mode: DiffMode, + /// See [`ContainerDiff::kept`]. + pub(crate) kept: Option<KeptChange>, +} + +#[derive(Default, Debug, Clone, EnumAsInner)] +pub(crate) enum DiffVariant { + #[default] + None, + Internal(InternalDiff), + External(Diff), +} + +/// It's used for transmitting and recording the diff internally. +/// +/// It can be convert into a [DocDiff]. +// Internally, we need to batch the diff then calculate the event. Because +// we need to sort the diff by containers' created time, to make sure the +// the path to each container is up-to-date. +#[derive(Debug, Clone)] +pub(crate) struct InternalDocDiff<'a> { + pub(crate) origin: InternalString, + pub(crate) by: EventTriggerKind, + /// The values inside this array is in random order + pub(crate) diff: Cow<'a, [InternalContainerDiff]>, + pub(crate) new_version: Cow<'a, Frontiers>, +} + +impl InternalDocDiff<'_> { + pub fn into_owned(self) -> InternalDocDiff<'static> { + InternalDocDiff { + origin: self.origin, + by: self.by, + diff: Cow::Owned((*self.diff).to_owned()), + new_version: Cow::Owned((*self.new_version).to_owned()), + } + } + + pub fn can_merge(&self, other: &Self) -> bool { + self.by == other.by + } +} + +pub type Path = SmallVec<[Index; 4]>; + +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, enum_as_inner::EnumAsInner)] +pub enum Index { + Key(InternalString), + Seq(usize), + Node(TreeID), +} + +impl std::fmt::Debug for Index { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Key(arg0) => write!(f, "Index::Key(\"{}\")", arg0), + Self::Seq(arg0) => write!(f, "Index::Seq({})", arg0), + Self::Node(arg0) => write!(f, "Index::Node({})", arg0), + } + } +} + +impl std::fmt::Display for Index { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Index::Key(key) => write!(f, "{}", key), + Index::Seq(s) => write!(f, "{}", s), + Index::Node(id) => write!(f, "{}@{}", id.peer, id.counter), + } + } +} + +impl From<usize> for Index { + fn from(s: usize) -> Self { + Index::Seq(s) + } +} + +impl TryFrom<&str> for Index { + type Error = &'static str; + fn try_from(s: &str) -> Result<Self, &'static str> { + if s.is_empty() { + return Ok(Index::Key(InternalString::default())); + } + + let c = s.chars().next().unwrap(); + if c.is_ascii_digit() { + if let Ok(seq) = s.parse::<usize>() { + Ok(Index::Seq(seq)) + } else if let Ok(id) = s.try_into() { + Ok(Index::Node(id)) + } else { + Ok(Index::Key(InternalString::from(s))) + } + } else { + Ok(Index::Key(InternalString::from(s))) + } + } +} + +impl DiffVariant { + pub fn compose(self, other: Self) -> Result<Self, Self> { + match (self, other) { + (DiffVariant::Internal(a), DiffVariant::Internal(b)) => { + Ok(DiffVariant::Internal(a.compose(b)?)) + } + (DiffVariant::External(a), DiffVariant::External(b)) => { + Ok(DiffVariant::External(a.compose(b)?)) + } + (a, _) => Err(a), + } + } + + pub fn is_empty(&self) -> bool { + match self { + DiffVariant::Internal(diff) => diff.is_empty(), + DiffVariant::External(diff) => diff.is_empty(), + DiffVariant::None => true, + } + } +} + +#[non_exhaustive] +#[derive(Clone, Debug, EnumAsInner)] +pub(crate) enum InternalDiff { + ListRaw(Delta<SliceWithId>), + /// This always uses entity indexes. + RichtextRaw(DeltaRope<RichtextStateChunk, ()>), + Map(MapDelta), + Tree(TreeDelta), + MovableList(MovableListInnerDelta), + #[cfg(feature = "counter")] + Counter(f64), + Unknown, +} + +impl From<InternalDiff> for DiffVariant { + fn from(diff: InternalDiff) -> Self { + DiffVariant::Internal(diff) + } +} + +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct ListDeltaMeta { + /// Whether the content of the insert is moved from + /// a deletion in the same delta and **the value is not changed**. + /// + /// If true, this op must be a move op under the hood. + /// But an insert created by a move op doesn't necessarily + /// have this flag, because the insert content may not + /// be moved from a deletion in the same delta. + pub from_move: bool, +} + +impl Meta for ListDeltaMeta { + fn is_empty(&self) -> bool { + !self.from_move + } + + fn compose( + &mut self, + other: &Self, + type_pair: (crate::delta::DeltaType, crate::delta::DeltaType), + ) { + // We can't have two Some because we don't have `move_from` for Retain. + // And this function is only called when composing a insert/retain with a retain. + if let (crate::delta::DeltaType::Insert, crate::delta::DeltaType::Insert) = type_pair { + unreachable!() + } + + self.from_move = self.from_move || other.from_move; + } + + fn is_mergeable(&self, other: &Self) -> bool { + self.from_move == other.from_move + } + + fn merge(&mut self, _other: &Self) {} +} + +impl DeltaAttr for ListDeltaMeta { + fn compose(&mut self, other: &Self) { + self.from_move = self.from_move || other.from_move; + } + + fn attr_is_empty(&self) -> bool { + !self.from_move + } +} + +pub type ListDiffInsertItem = ArrayVec<ValueOrHandler, 8>; +pub type ListDiffItem = DeltaItem<ListDiffInsertItem, ListDeltaMeta>; +pub type ListDiff = DeltaRope<ListDiffInsertItem, ListDeltaMeta>; + +#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct TextMeta(pub FxHashMap<String, LoroValue>); + +impl From<TextMeta> for FxHashMap<String, LoroValue> { + fn from(value: TextMeta) -> Self { + value.0 + } +} + +impl From<FxHashMap<String, LoroValue>> for TextMeta { + fn from(value: FxHashMap<String, LoroValue>) -> Self { + TextMeta(value) + } +} + +pub type TextDiffItem = DeltaItem<StringSlice, TextMeta>; +pub type TextDiff = DeltaRope<StringSlice, TextMeta>; + +impl DeltaAttr for TextMeta { + fn compose(&mut self, other: &Self) { + for (key, value) in other.0.iter() { + self.0.insert(key.clone(), value.clone()); + } + } + + fn attr_is_empty(&self) -> bool { + self.0.is_empty() + } +} + +/// Diff is the diff between two versions of a container. +/// It's used to describe the change of a container and the events. +/// +/// # Internal +/// +/// Text index variants: +/// +/// - When `wasm` is enabled, it should use utf16 indexes. +/// - When `wasm` is disabled, it should use unicode indexes. +#[non_exhaustive] +#[derive(Clone, Debug, EnumAsInner)] +pub enum Diff { + List(ListDiff), + /// - When feature `wasm` is enabled, it should use utf16 indexes. + /// - When feature `wasm` is disabled, it should use unicode indexes. + Text(TextDiff), + Map(ResolvedMapDelta), + Tree(TreeDiff), + #[cfg(feature = "counter")] + Counter(f64), + Unknown, +} + +impl From<Diff> for DiffVariant { + fn from(diff: Diff) -> Self { + DiffVariant::External(diff) + } +} + +impl InternalDiff { + pub(crate) fn is_empty(&self) -> bool { + match self { + InternalDiff::ListRaw(s) => s.is_empty(), + InternalDiff::RichtextRaw(t) => t.is_empty(), + InternalDiff::Map(m) => m.updated.is_empty(), + InternalDiff::Tree(t) => t.is_empty(), + InternalDiff::MovableList(t) => t.is_empty(), + // 0 is empty. A smaller nonzero delta such as 1e-17 is a real increment. + #[cfg(feature = "counter")] + InternalDiff::Counter(c) => *c == 0.0, + InternalDiff::Unknown => true, + } + } + + pub(crate) fn compose(self, diff: InternalDiff) -> Result<Self, Self> { + // PERF: avoid clone + match (self, diff) { + (InternalDiff::ListRaw(a), InternalDiff::ListRaw(b)) => { + Ok(InternalDiff::ListRaw(a.compose(b))) + } + (InternalDiff::RichtextRaw(mut a), InternalDiff::RichtextRaw(b)) => { + a.compose(&b); + Ok(InternalDiff::RichtextRaw(a)) + } + (InternalDiff::Map(a), InternalDiff::Map(b)) => Ok(InternalDiff::Map(a.compose(b))), + (InternalDiff::Tree(a), InternalDiff::Tree(b)) => Ok(InternalDiff::Tree(a.compose(b))), + (a, _) => Err(a), + } + } +} + +impl Diff { + pub fn compose_ref(&mut self, diff: &Diff) { + match (self, diff) { + (Diff::List(a), Diff::List(b)) => { + a.compose(b); + } + (Diff::Text(a), Diff::Text(b)) => { + a.compose(b); + } + (Diff::Map(a), Diff::Map(b)) => { + // Move the accumulator out instead of cloning it, so composing + // a long run of fragments stays linear rather than O(n^2). + *a = std::mem::take(a).compose(b.clone()); + } + (Diff::Tree(a), Diff::Tree(b)) => { + *a = std::mem::take(a).compose(b.clone()); + } + #[cfg(feature = "counter")] + (Diff::Counter(a), Diff::Counter(b)) => *a += b, + // Unknown containers have no diff content + (Diff::Unknown, Diff::Unknown) => {} + (_, _) => unreachable!(), + } + } + + pub fn compose(self, diff: Diff) -> Result<Self, Self> { + // PERF: avoid clone + match (self, diff) { + (Diff::List(mut a), Diff::List(b)) => { + a.compose(&b); + Ok(Diff::List(a)) + } + (Diff::Text(mut a), Diff::Text(b)) => { + a.compose(&b); + Ok(Diff::Text(a)) + } + (Diff::Map(a), Diff::Map(b)) => Ok(Diff::Map(a.compose(b))), + + (Diff::Tree(a), Diff::Tree(b)) => Ok(Diff::Tree(a.compose(b))), + #[cfg(feature = "counter")] + (Diff::Counter(a), Diff::Counter(b)) => Ok(Diff::Counter(a + b)), + (a, _) => Err(a), + } + } + + // Transform this diff based on the other diff + pub fn transform(&mut self, other: &Self, left_prior: bool) { + match (self, other) { + (Diff::List(a), Diff::List(b)) => a.transform_(b, left_prior), + (Diff::Text(a), Diff::Text(b)) => a.transform_(b, left_prior), + (Diff::Map(a), Diff::Map(b)) => a.transform(b, left_prior), + (Diff::Tree(a), Diff::Tree(b)) => a.transform(b, left_prior), + #[cfg(feature = "counter")] + (Diff::Counter(_a), Diff::Counter(_b)) => { + // Counter operations commute; no transformation is needed. + } + _ => {} + } + } + + pub fn is_empty(&self) -> bool { + match self { + Diff::List(s) => s.is_empty(), + Diff::Text(t) => t.is_empty(), + Diff::Map(m) => m.updated.is_empty(), + Diff::Tree(t) => t.diff.is_empty(), + // Same rule as `InternalDiff`: only an exact 0 is an empty counter diff. + #[cfg(feature = "counter")] + Diff::Counter(c) => *c == 0.0, + Diff::Unknown => true, + } + } + + #[allow(unused)] + pub(crate) fn concat(self, diff: Diff) -> Diff { + match (self, diff) { + (Diff::List(mut a), Diff::List(b)) => { + a.compose(&b); + Diff::List(a) + } + (Diff::Text(mut a), Diff::Text(b)) => { + a.compose(&b); + Diff::Text(a) + } + (Diff::Map(a), Diff::Map(b)) => { + let mut a = a; + for (k, v) in b.updated { + a = a.with_entry(k, v); + } + Diff::Map(a) + } + + (Diff::Tree(a), Diff::Tree(b)) => Diff::Tree(a.extend(b.diff)), + #[cfg(feature = "counter")] + (Diff::Counter(a), Diff::Counter(b)) => Diff::Counter(a + b), + _ => unreachable!(), + } + } + + /// Transform the cursor based on this diff + pub(crate) fn transform_cursor(&self, pos: usize, left_prior: bool) -> usize { + match self { + Diff::List(list) => list.transform_pos(pos, left_prior), + Diff::Text(text) => text.transform_pos(pos, left_prior), + _ => pos, + } + } +} + +pub fn str_to_path(s: &str) -> Option<Vec<Index>> { + s.split('/').map(|x| x.try_into()).try_collect().ok() +} + +pub fn path_to_str(path: &[Index]) -> String { + path.iter().map(|x| x.to_string()).join("/") +} + +#[cfg(test)] +mod test { + use std::sync::Arc; + + use itertools::Itertools; + use loro_common::LoroValue; + + use crate::{cursor::PosType, ApplyDiff, LoroDoc}; + + #[test] + fn test_text_event() { + let loro = LoroDoc::new(); + let _g = loro.subscribe_root(Arc::new(|event| { + let mut value = LoroValue::String(Default::default()); + value.apply_diff(&event.events.iter().map(|x| x.diff.clone()).collect_vec()); + assert_eq!(value, "h223ello".into()); + })); + let mut txn = loro.txn().unwrap(); + let text = loro.get_text("id"); + text.insert_with_txn(&mut txn, 0, "hello", PosType::Unicode) + .unwrap(); + text.insert_with_txn(&mut txn, 1, "223", PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + } +} diff --git a/vendor/loro-internal/src/fork.rs b/vendor/loro-internal/src/fork.rs new file mode 100644 index 0000000..9404a03 --- /dev/null +++ b/vendor/loro-internal/src/fork.rs @@ -0,0 +1,64 @@ +//! The fork module provides functionality to create a new LoroDoc instance at a specified version +//! (Frontiers) with minimal overhead. +//! +//! # Implementation Overview +//! +//! The `fork_at` function in this module allows for the creation of a new document that reflects +//! the state of the original document at a given version. The function achieves this by: +//! +//! ## Exporting Necessary Data: +//! +//! - **Change Store Data**: Collects all changes up to the specified version from the change +//! store's key-value (kv) data store. It includes the version vector and frontiers for accurate +//! identification of the version. +//! +//! - **Container Store Data**: Exports the container store's kv data representing the document's +//! state at the specified version. This involves checking out to the desired version, exporting +//! the state, and efficiently checking back to the latest version. +//! +//! - **GC Store Data**: If applicable, exports the gc store's kv data, ensuring that version +//! identifiers are included. +//! +//! ## Reconstructing the New Document: +//! +//! Imports the exported data into a new LoroDoc instance using optimized import mechanisms +//! similar to those used in fast snapshot imports. +//! +//! By focusing on exporting only the necessary data and optimizing state transitions during +//! version checkout, the `fork_at` function minimizes overhead and efficiently creates new +//! document instances representing past versions. +//! +use std::borrow::Cow; + +use crate::{version::Frontiers, LoroDoc}; +use loro_common::{LoroError, LoroResult}; + +impl LoroDoc { + /// Creates a new LoroDoc at a specified version (Frontiers) + pub fn fork_at(&self, frontiers: &Frontiers) -> LoroResult<Self> { + self.fork_at_inner(frontiers, true) + } + + /// See [`LoroDoc::export_inner`] for `reject_partial_history`. + pub(crate) fn fork_at_inner( + &self, + frontiers: &Frontiers, + reject_partial_history: bool, + ) -> LoroResult<Self> { + let bytes = self + .export_inner( + crate::loro::ExportMode::SnapshotAt { + version: Cow::Borrowed(frontiers), + }, + reject_partial_history, + ) + .map_err(LoroError::from)?; + let doc = LoroDoc::new(); + doc.set_config(&self.config); + if self.auto_commit.load(std::sync::atomic::Ordering::Relaxed) { + doc.start_auto_commit(); + } + doc.import(&bytes)?; + Ok(doc) + } +} diff --git a/vendor/loro-internal/src/fuzz.rs b/vendor/loro-internal/src/fuzz.rs new file mode 100644 index 0000000..6c22cdd --- /dev/null +++ b/vendor/loro-internal/src/fuzz.rs @@ -0,0 +1,89 @@ +use std::{fmt::Debug, time::Instant}; + +pub fn minify_error<T, F, N>(site_num: u8, actions: Vec<T>, f: F, normalize: N) +where + F: Fn(u8, &mut [T]), + N: Fn(u8, &mut [T]) -> Vec<T>, + T: Clone + Debug, +{ + std::panic::set_hook(Box::new(|_info| { + // ignore panic output + // println!("{:?}", _info); + })); + + let f_ref: *const _ = &f; + let f_ref: usize = f_ref as usize; + #[allow(clippy::redundant_clone)] + let mut actions_clone = actions.clone(); + let action_ref: usize = (&mut actions_clone) as *mut _ as usize; + #[allow(clippy::blocks_in_conditions)] + if std::panic::catch_unwind(|| { + // SAFETY: test + let f = unsafe { &*(f_ref as *const F) }; + // SAFETY: test + let actions_ref = unsafe { &mut *(action_ref as *mut Vec<T>) }; + f(site_num, actions_ref); + }) + .is_ok() + { + println!("No Error Found"); + return; + } + + let mut minified = actions.clone(); + let mut candidates = Vec::new(); + for i in 0..actions.len() { + let mut new = actions.clone(); + new.remove(i); + candidates.push(new); + } + + println!("Minifying..."); + let start = Instant::now(); + while let Some(candidate) = candidates.pop() { + let f_ref: *const _ = &f; + let f_ref: usize = f_ref as usize; + let mut actions_clone = candidate.clone(); + let action_ref: usize = (&mut actions_clone) as *mut _ as usize; + #[allow(clippy::blocks_in_conditions)] + if std::panic::catch_unwind(|| { + // SAFETY: test + let f = unsafe { &*(f_ref as *const F) }; + // SAFETY: test + let actions_ref = unsafe { &mut *(action_ref as *mut Vec<T>) }; + f(site_num, actions_ref); + }) + .is_err() + { + for i in 0..candidate.len() { + let mut new = candidate.clone(); + new.remove(i); + candidates.push(new); + } + if candidate.len() < minified.len() { + minified = candidate; + println!("New min len={}", minified.len()); + } + if candidates.len() > 40 { + candidates.drain(0..30); + } + } + if start.elapsed().as_secs() > 10 && minified.len() <= 4 { + break; + } + if start.elapsed().as_secs() > 60 { + break; + } + } + + let minified = normalize(site_num, &mut minified); + println!( + "Old Length {}, New Length {}", + actions.len(), + minified.len() + ); + dbg!(&minified); + if actions.len() > minified.len() { + minify_error(site_num, minified, f, normalize); + } +} diff --git a/vendor/loro-internal/src/handler.rs b/vendor/loro-internal/src/handler.rs new file mode 100644 index 0000000..4a194d1 --- /dev/null +++ b/vendor/loro-internal/src/handler.rs @@ -0,0 +1,6099 @@ +use super::{state::DocState, txn::Transaction}; +use crate::sync::Mutex; +use crate::{ + container::{ + idx::ContainerIdx, + list::list_op::{DeleteSpan, DeleteSpanWithId, ListOp}, + richtext::{richtext_state::PosType, RichtextState, StyleKey, StyleOp, TextStyleInfoFlag}, + }, + cursor::{Cursor, Side}, + delta::{DeltaItem, Meta, StyleMeta, TreeExternalDiff}, + diff::{diff, diff_impl::UpdateTimeoutError, OperateProxy}, + event::{Diff, TextDiff, TextDiffItem, TextMeta}, + op::ListSlice, + state::{IndexType, State, TreeParentId}, + txn::EventHint, + utils::{string_slice::StringSlice, utf16::count_utf16_len}, + LoroDoc, LoroDocInner, +}; +use append_only_bytes::BytesSlice; +use enum_as_inner::EnumAsInner; +use generic_btree::rle::HasLength; +use loro_common::{ + ContainerID, ContainerType, IdFull, InternalString, LoroError, LoroResult, LoroValue, PeerID, + TreeID, ID, +}; +use rustc_hash::{FxHashMap, FxHashSet}; +use serde::{Deserialize, Serialize}; +use std::{borrow::Cow, fmt::Debug, ops::Deref, sync::Arc}; +use tracing::{error, instrument}; + +pub use crate::diff::diff_impl::UpdateOptions; +pub use tree::TreeHandler; +mod full_state; +mod movable_list_apply_delta; +pub(crate) use full_state::align_full_state; +mod tree; + +const REGULAR_CONTAINER_VALUE_ARG_ERROR: &str = + "Cannot use a LoroValue::Container as a regular value. To create a child container, use insert_container/set_container, or ensure_mergeable_* on maps for mergeable children"; + +mod text_update; + +fn ensure_no_regular_container_value(value: &LoroValue) -> LoroResult<()> { + // Fast path: scalar values can never transitively hold a container, so we + // skip the heap allocation + traversal below. This is the common case on + // the per-op insert hot path (inserting numbers/strings/bools), where the + // previous unconditional `vec![value]` allocation showed up as a measurable + // regression. + if !matches!( + value, + LoroValue::Container(_) | LoroValue::List(_) | LoroValue::Map(_) + ) { + return Ok(()); + } + + let mut stack = vec![value]; + while let Some(value) = stack.pop() { + match value { + LoroValue::Container(_) => { + return Err(LoroError::ArgErr( + REGULAR_CONTAINER_VALUE_ARG_ERROR + .to_string() + .into_boxed_str(), + )); + } + LoroValue::List(list) => { + stack.extend(list.iter()); + } + LoroValue::Map(map) => { + stack.extend(map.values()); + } + LoroValue::Null + | LoroValue::Bool(_) + | LoroValue::Double(_) + | LoroValue::I64(_) + | LoroValue::Binary(_) + | LoroValue::String(_) => {} + } + } + + Ok(()) +} + +fn checked_range_end( + pos: usize, + len: usize, + container_len: usize, + // Lazily built: this is on the per-op edit hot path, so the position-context + // string must only be allocated when a bound check actually fails. + info: impl Fn() -> Box<str>, +) -> LoroResult<usize> { + let end = pos.checked_add(len).ok_or_else(|| LoroError::OutOfBound { + pos: usize::MAX, + len: container_len, + info: info(), + })?; + if end > container_len { + return Err(LoroError::OutOfBound { + pos: end, + len: container_len, + info: info(), + }); + } + + Ok(end) +} + +fn checked_delta_index_end(pos: usize, len: usize, container_len: usize) -> LoroResult<usize> { + pos.checked_add(len).ok_or_else(|| LoroError::OutOfBound { + pos: usize::MAX, + len: container_len, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }) +} + +pub trait HandlerTrait: Clone + Sized { + fn is_attached(&self) -> bool; + fn attached_handler(&self) -> Option<&BasicHandler>; + fn get_value(&self) -> LoroValue; + fn get_deep_value(&self) -> LoroValue; + fn kind(&self) -> ContainerType; + fn to_handler(&self) -> Handler; + fn from_handler(h: Handler) -> Option<Self>; + fn doc(&self) -> Option<LoroDoc>; + /// This method returns an attached handler. + fn attach( + &self, + txn: &mut Transaction, + parent: &BasicHandler, + self_id: ContainerID, + ) -> LoroResult<Self>; + /// If a detached container is attached, this method will return its corresponding attached handler. + fn get_attached(&self) -> Option<Self>; + + fn parent(&self) -> Option<Handler> { + self.attached_handler().and_then(|x| x.parent()) + } + + fn idx(&self) -> ContainerIdx { + self.attached_handler() + .map(|x| x.container_idx) + .unwrap_or_else(|| { + ContainerIdx::from_index_and_type(ContainerIdx::INDEX_MASK, self.kind()) + }) + } + + fn id(&self) -> ContainerID { + self.attached_handler() + .map(|x| x.id.clone()) + .unwrap_or_else(|| ContainerID::new_normal(ID::NONE_ID, self.kind())) + } + + fn with_state<R>(&self, f: impl FnOnce(&mut State) -> LoroResult<R>) -> LoroResult<R> { + let inner = self + .attached_handler() + .ok_or(LoroError::MisuseDetachedContainer { + method: "with_state", + })?; + let state = inner.doc.state.clone(); + let mut guard = state.lock(); + guard.with_state_mut(inner.container_idx, f) + } +} + +fn create_handler(inner: &BasicHandler, id: ContainerID) -> Handler { + Handler::new_attached(id, inner.doc.clone()) +} + +fn value_to_value_or_handler(inner: &BasicHandler, value: LoroValue) -> ValueOrHandler { + match value { + LoroValue::Container(container_id) => { + ValueOrHandler::Handler(create_handler(inner, container_id)) + } + value => ValueOrHandler::Value(value), + } +} + +/// Reject inserting a container that is attached to another doc, either directly +/// or nested inside a detached container, or a copy that would need to create an +/// unknown container. +/// +/// Attaching copies an attached container through its own doc, so a foreign +/// child would mix the source doc's arena with the target doc's transaction. +/// Callers must run this before applying any op so the target doc is untouched. +fn ensure_not_attached_to_other_doc<H: HandlerTrait>(child: &H, doc: &LoroDoc) -> LoroResult<()> { + ensure_handler_not_attached_to_other_doc(&child.to_handler(), doc) +} + +fn ensure_handler_not_attached_to_other_doc(handler: &Handler, doc: &LoroDoc) -> LoroResult<()> { + if let Some(a) = handler.attached_handler() { + if Arc::ptr_eq(&a.doc.inner, &doc.inner) { + // Attaching a container of the same doc copies it + return ensure_no_unknown_container_in_attached(handler); + } + + return Err(LoroError::ArgErr( + "Cannot insert a container attached to another LoroDoc".into(), + )); + } + + let check_values = |values: &mut dyn Iterator<Item = &ValueOrHandler>| { + for v in values { + if let ValueOrHandler::Handler(h) = v { + ensure_handler_not_attached_to_other_doc(h, doc)?; + } + } + Ok(()) + }; + + match handler { + Handler::Map(m) => match &m.inner { + MaybeDetached::Detached(d) => check_values(&mut d.lock().value.values()), + MaybeDetached::Attached(_) => Ok(()), + }, + Handler::List(l) => match &l.inner { + MaybeDetached::Detached(d) => check_values(&mut d.lock().value.iter()), + MaybeDetached::Attached(_) => Ok(()), + }, + Handler::MovableList(l) => match &l.inner { + MaybeDetached::Detached(d) => check_values(&mut d.lock().value.iter()), + MaybeDetached::Attached(_) => Ok(()), + }, + Handler::Tree(t) => { + for meta in t.detached_meta_maps() { + ensure_handler_not_attached_to_other_doc(&Handler::Map(meta), doc)?; + } + Ok(()) + } + Handler::Text(_) | Handler::Unknown(_) => Ok(()), + #[cfg(feature = "counter")] + Handler::Counter(_) => Ok(()), + } +} + +const UNKNOWN_CONTAINER_CREATION_ERR_SUFFIX: &str = ": the type is unknown to this version of Loro"; + +/// The error for operations that would create a container of a type this +/// version doesn't know ([ContainerType::Unknown], written by a newer Loro). +pub(crate) fn unknown_container_creation_err(kind: ContainerType) -> LoroError { + LoroError::ArgErr( + format!("Cannot create a container of type {kind}{UNKNOWN_CONTAINER_CREATION_ERR_SUFFIX}") + .into_boxed_str(), + ) +} + +/// Whether `e` is [`unknown_container_creation_err`]. +pub(crate) fn is_unknown_container_creation_err(e: &LoroError) -> bool { + matches!(e, LoroError::ArgErr(msg) if msg.ends_with(UNKNOWN_CONTAINER_CREATION_ERR_SUFFIX)) +} + +/// Attaching an attached container copies its content, which is impossible for +/// a container whose type this version doesn't know (created by a newer Loro). +fn ensure_no_unknown_container_in_attached(handler: &Handler) -> LoroResult<()> { + let check_children = |value: LoroValue| -> LoroResult<()> { + let children: Vec<ContainerID> = match value { + LoroValue::Map(m) => m + .values() + .filter_map(|v| v.as_container().cloned()) + .collect(), + LoroValue::List(l) => l.iter().filter_map(|v| v.as_container().cloned()).collect(), + _ => Vec::new(), + }; + let Some(doc) = handler.attached_handler().map(|a| a.doc()) else { + return Ok(()); + }; + for id in children { + ensure_no_unknown_container_in_attached(&Handler::new_attached(id, doc.clone()))?; + } + Ok(()) + }; + + match handler { + Handler::Unknown(u) => Err(unknown_container_creation_err(u.kind())), + Handler::Map(m) => check_children(m.get_value()), + Handler::List(l) => check_children(l.get_value()), + Handler::MovableList(l) => check_children(l.get_value()), + Handler::Tree(t) => { + let mut pending = t.get_all_hierarchy_nodes_under(TreeParentId::Root); + pending.reverse(); + while let Some(mut node) = pending.pop() { + ensure_no_unknown_container_in_attached(&Handler::Map(t.get_meta(node.id)?))?; + pending.extend(std::mem::take(&mut node.children).into_iter().rev()); + } + Ok(()) + } + Handler::Text(_) => Ok(()), + #[cfg(feature = "counter")] + Handler::Counter(_) => Ok(()), + } +} + +/// Flatten attributes that allow overlap +#[derive(Clone, Debug)] +pub struct BasicHandler { + id: ContainerID, + container_idx: ContainerIdx, + doc: LoroDoc, +} + +struct DetachedInner<T> { + value: T, + /// If the handler attached later, this field will be filled. + attached: Option<BasicHandler>, +} + +impl<T> DetachedInner<T> { + fn new(v: T) -> Self { + Self { + value: v, + attached: None, + } + } +} + +enum MaybeDetached<T> { + Detached(Arc<Mutex<DetachedInner<T>>>), + Attached(BasicHandler), +} + +impl<T> Clone for MaybeDetached<T> { + fn clone(&self) -> Self { + match self { + MaybeDetached::Detached(a) => MaybeDetached::Detached(Arc::clone(a)), + MaybeDetached::Attached(a) => MaybeDetached::Attached(a.clone()), + } + } +} + +impl<T> MaybeDetached<T> { + fn new_detached(v: T) -> Self { + MaybeDetached::Detached(Arc::new(Mutex::new(DetachedInner::new(v)))) + } + + fn is_attached(&self) -> bool { + match self { + MaybeDetached::Detached(_) => false, + MaybeDetached::Attached(_) => true, + } + } + + fn attached_handler(&self) -> Option<&BasicHandler> { + match self { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => Some(a), + } + } + + fn try_attached_state(&self) -> LoroResult<&BasicHandler> { + match self { + MaybeDetached::Detached(_) => Err(LoroError::MisuseDetachedContainer { + method: "inner_state", + }), + MaybeDetached::Attached(a) => Ok(a), + } + } +} + +impl<T> From<BasicHandler> for MaybeDetached<T> { + fn from(a: BasicHandler) -> Self { + MaybeDetached::Attached(a) + } +} + +impl BasicHandler { + pub(crate) fn doc(&self) -> LoroDoc { + self.doc.clone() + } + + #[inline] + fn with_doc_state<R>(&self, f: impl FnOnce(&mut DocState) -> R) -> R { + let state = self.doc.state.clone(); + let mut guard = state.lock(); + f(&mut guard) + } + + fn with_txn<R>( + &self, + f: impl FnOnce(&mut Transaction) -> Result<R, LoroError>, + ) -> Result<R, LoroError> { + with_txn(&self.doc, f) + } + + fn get_parent(&self) -> Option<Handler> { + let parent_idx = self.doc.arena.get_parent(self.container_idx)?; + let parent_id = self.doc.arena.get_container_id(parent_idx).unwrap(); + { + let kind = parent_id.container_type(); + let handler = BasicHandler { + container_idx: parent_idx, + id: parent_id, + doc: self.doc.clone(), + }; + + Some(match kind { + ContainerType::Map => Handler::Map(MapHandler { + inner: handler.into(), + }), + ContainerType::List => Handler::List(ListHandler { + inner: handler.into(), + }), + ContainerType::Tree => Handler::Tree(TreeHandler { + inner: handler.into(), + }), + ContainerType::Text => Handler::Text(TextHandler { + inner: handler.into(), + }), + ContainerType::MovableList => Handler::MovableList(MovableListHandler { + inner: handler.into(), + }), + #[cfg(feature = "counter")] + ContainerType::Counter => Handler::Counter(counter::CounterHandler { + inner: handler.into(), + }), + // Snapshots from a newer Loro may store children of an unknown container + ContainerType::Unknown(_) => Handler::Unknown(UnknownHandler { inner: handler }), + }) + } + } + + pub fn get_value(&self) -> LoroValue { + self.doc.state.lock().get_value_by_idx(self.container_idx) + } + + pub fn get_deep_value(&self) -> LoroValue { + self.doc + .state + .lock() + .get_container_deep_value(self.container_idx) + } + + fn with_state<R>(&self, f: impl FnOnce(&mut State) -> R) -> R { + let mut guard = self.doc.state.lock(); + guard.with_state_mut(self.container_idx, f) + } + + pub fn parent(&self) -> Option<Handler> { + self.get_parent() + } + + fn is_deleted(&self) -> bool { + self.doc.state.lock().is_deleted(self.container_idx) + } + + fn has_decoded_state(&self) -> bool { + self.with_doc_state(|state| state.has_decoded_container_state(self.container_idx)) + } +} + +/// Flatten attributes that allow overlap +#[derive(Clone)] +pub struct TextHandler { + inner: MaybeDetached<RichtextState>, +} + +impl HandlerTrait for TextHandler { + fn to_handler(&self) -> Handler { + Handler::Text(self.clone()) + } + + fn attach( + &self, + txn: &mut Transaction, + parent: &BasicHandler, + self_id: ContainerID, + ) -> LoroResult<Self> { + match &self.inner { + MaybeDetached::Detached(t) => { + let mut t = t.lock(); + let inner = create_handler(parent, self_id); + let text = inner.into_text().unwrap(); + let mut delta: Vec<TextDelta> = Vec::new(); + for span in t.value.iter() { + delta.push(TextDelta::Insert { + insert: span.text.to_string(), + attributes: span.attributes.to_option_map(), + }); + } + + text.apply_delta_with_txn(txn, &delta)?; + t.attached = text.attached_handler().cloned(); + Ok(text) + } + MaybeDetached::Attached(a) => { + let new_inner = create_handler(a, self_id); + let ans = new_inner.into_text().unwrap(); + + let delta = self.get_delta(); + ans.apply_delta_with_txn(txn, &delta)?; + Ok(ans) + } + } + } + + fn attached_handler(&self) -> Option<&BasicHandler> { + self.inner.attached_handler() + } + + fn get_value(&self) -> LoroValue { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + LoroValue::String((t.value.to_string()).into()) + } + MaybeDetached::Attached(a) => a.get_value(), + } + } + + fn get_deep_value(&self) -> LoroValue { + self.get_value() + } + + fn is_attached(&self) -> bool { + matches!(&self.inner, MaybeDetached::Attached(..)) + } + + fn kind(&self) -> ContainerType { + ContainerType::Text + } + + fn get_attached(&self) -> Option<Self> { + match &self.inner { + MaybeDetached::Detached(d) => d.lock().attached.clone().map(|x| Self { + inner: MaybeDetached::Attached(x), + }), + MaybeDetached::Attached(_a) => Some(self.clone()), + } + } + + fn from_handler(h: Handler) -> Option<Self> { + match h { + Handler::Text(x) => Some(x), + _ => None, + } + } + + fn doc(&self) -> Option<LoroDoc> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => Some(a.doc()), + } + } +} + +impl std::fmt::Debug for TextHandler { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.inner { + MaybeDetached::Detached(_) => { + write!(f, "TextHandler(Unattached)") + } + MaybeDetached::Attached(a) => { + write!(f, "TextHandler({:?})", &a.id) + } + } + } +} + +#[derive(Debug, Clone, EnumAsInner, Deserialize, Serialize, PartialEq)] +#[serde(untagged)] +pub enum TextDelta { + Retain { + retain: usize, + attributes: Option<FxHashMap<String, LoroValue>>, + }, + Insert { + insert: String, + attributes: Option<FxHashMap<String, LoroValue>>, + }, + Delete { + delete: usize, + }, +} + +impl TextDelta { + pub fn from_text_diff<'a>(diff: impl Iterator<Item = &'a TextDiffItem>) -> Vec<TextDelta> { + let mut ans = Vec::with_capacity(diff.size_hint().0); + for iter in diff { + match iter { + loro_delta::DeltaItem::Retain { len, attr } => { + ans.push(TextDelta::Retain { + retain: *len, + attributes: if attr.0.is_empty() { + None + } else { + Some(attr.0.clone()) + }, + }); + } + loro_delta::DeltaItem::Replace { + value, + attr, + delete, + } => { + if value.rle_len() > 0 { + ans.push(TextDelta::Insert { + insert: value.to_string(), + attributes: if attr.0.is_empty() { + None + } else { + Some(attr.0.clone()) + }, + }); + } + if *delete > 0 { + ans.push(TextDelta::Delete { delete: *delete }); + } + } + } + } + + ans + } + + pub fn into_text_diff(vec: impl Iterator<Item = Self>) -> TextDiff { + let mut delta = TextDiff::new(); + for item in vec { + match item { + TextDelta::Retain { retain, attributes } => { + delta.push_retain(retain, TextMeta(attributes.unwrap_or_default().clone())); + } + TextDelta::Insert { insert, attributes } => { + delta.push_insert( + StringSlice::from(insert.as_str()), + TextMeta(attributes.unwrap_or_default()), + ); + } + TextDelta::Delete { delete } => { + delta.push_delete(delete); + } + } + } + + delta + } +} + +impl From<&DeltaItem<StringSlice, StyleMeta>> for TextDelta { + fn from(value: &DeltaItem<StringSlice, StyleMeta>) -> Self { + match value { + crate::delta::DeltaItem::Retain { retain, attributes } => TextDelta::Retain { + retain: *retain, + attributes: attributes.to_option_map(), + }, + crate::delta::DeltaItem::Insert { insert, attributes } => TextDelta::Insert { + insert: insert.to_string(), + attributes: attributes.to_option_map(), + }, + crate::delta::DeltaItem::Delete { + delete, + attributes: _, + } => TextDelta::Delete { delete: *delete }, + } + } +} + +#[derive(Clone)] +pub struct MapHandler { + inner: MaybeDetached<FxHashMap<String, ValueOrHandler>>, +} + +impl HandlerTrait for MapHandler { + fn is_attached(&self) -> bool { + matches!(&self.inner, MaybeDetached::Attached(..)) + } + + fn attached_handler(&self) -> Option<&BasicHandler> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => Some(a), + } + } + + fn get_value(&self) -> LoroValue { + match &self.inner { + MaybeDetached::Detached(m) => { + let m = m.lock(); + let mut map = FxHashMap::default(); + for (k, v) in m.value.iter() { + map.insert(k.to_string(), v.to_value()); + } + LoroValue::Map(map.into()) + } + MaybeDetached::Attached(a) => a.get_value(), + } + } + + fn get_deep_value(&self) -> LoroValue { + match &self.inner { + MaybeDetached::Detached(m) => { + let m = m.lock(); + let mut map = FxHashMap::default(); + for (k, v) in m.value.iter() { + map.insert(k.to_string(), v.to_deep_value()); + } + LoroValue::Map(map.into()) + } + MaybeDetached::Attached(a) => a.get_deep_value(), + } + } + + fn kind(&self) -> ContainerType { + ContainerType::Map + } + + fn to_handler(&self) -> Handler { + Handler::Map(self.clone()) + } + + fn attach( + &self, + txn: &mut Transaction, + parent: &BasicHandler, + self_id: ContainerID, + ) -> LoroResult<Self> { + match &self.inner { + MaybeDetached::Detached(m) => { + let mut m = m.lock(); + let inner = create_handler(parent, self_id); + let map = inner.into_map().unwrap(); + for (k, v) in m.value.iter() { + match v { + ValueOrHandler::Value(v) => { + map.insert_with_txn(txn, k, v.clone())?; + } + ValueOrHandler::Handler(h) => { + map.insert_container_with_txn(txn, k, h.clone())?; + } + } + } + m.attached = map.attached_handler().cloned(); + Ok(map) + } + MaybeDetached::Attached(a) => { + let new_inner = create_handler(a, self_id); + let ans = new_inner.into_map().unwrap(); + + for (k, v) in self.get_value().into_map().unwrap().iter() { + if let LoroValue::Container(id) = v { + ans.insert_container_with_txn(txn, k, create_handler(a, id.clone()))?; + } else { + ans.insert_with_txn(txn, k, v.clone())?; + } + } + + Ok(ans) + } + } + } + + fn get_attached(&self) -> Option<Self> { + match &self.inner { + MaybeDetached::Detached(d) => d.lock().attached.clone().map(|x| Self { + inner: MaybeDetached::Attached(x), + }), + MaybeDetached::Attached(_a) => Some(self.clone()), + } + } + + fn from_handler(h: Handler) -> Option<Self> { + match h { + Handler::Map(x) => Some(x), + _ => None, + } + } + + fn doc(&self) -> Option<LoroDoc> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => Some(a.doc()), + } + } +} + +impl std::fmt::Debug for MapHandler { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.inner { + MaybeDetached::Detached(_) => write!(f, "MapHandler Detached"), + MaybeDetached::Attached(a) => write!(f, "MapHandler {}", a.id), + } + } +} + +#[derive(Clone)] +pub struct ListHandler { + inner: MaybeDetached<Vec<ValueOrHandler>>, +} + +#[derive(Clone)] +pub struct MovableListHandler { + inner: MaybeDetached<Vec<ValueOrHandler>>, +} + +impl HandlerTrait for MovableListHandler { + fn is_attached(&self) -> bool { + matches!(&self.inner, MaybeDetached::Attached(..)) + } + + fn attached_handler(&self) -> Option<&BasicHandler> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => Some(a), + } + } + + fn get_value(&self) -> LoroValue { + match &self.inner { + MaybeDetached::Detached(a) => { + let a = a.lock(); + LoroValue::List(a.value.iter().map(|v| v.to_value()).collect()) + } + MaybeDetached::Attached(a) => a.get_value(), + } + } + + fn get_deep_value(&self) -> LoroValue { + match &self.inner { + MaybeDetached::Detached(a) => { + let a = a.lock(); + LoroValue::List(a.value.iter().map(|v| v.to_deep_value()).collect()) + } + MaybeDetached::Attached(a) => a.get_deep_value(), + } + } + + fn kind(&self) -> ContainerType { + ContainerType::MovableList + } + + fn to_handler(&self) -> Handler { + Handler::MovableList(self.clone()) + } + + fn from_handler(h: Handler) -> Option<Self> { + match h { + Handler::MovableList(x) => Some(x), + _ => None, + } + } + + fn attach( + &self, + txn: &mut Transaction, + parent: &BasicHandler, + self_id: ContainerID, + ) -> LoroResult<Self> { + match &self.inner { + MaybeDetached::Detached(l) => { + let mut l = l.lock(); + let inner = create_handler(parent, self_id); + let list = inner.into_movable_list().unwrap(); + for (index, v) in l.value.iter().enumerate() { + match v { + ValueOrHandler::Value(v) => { + list.insert_with_txn(txn, index, v.clone())?; + } + ValueOrHandler::Handler(h) => { + list.insert_container_with_txn(txn, index, h.clone())?; + } + } + } + l.attached = list.attached_handler().cloned(); + Ok(list) + } + MaybeDetached::Attached(a) => { + let new_inner = create_handler(a, self_id); + let ans = new_inner.into_movable_list().unwrap(); + + for (i, v) in self.get_value().into_list().unwrap().iter().enumerate() { + if let LoroValue::Container(id) = v { + ans.insert_container_with_txn(txn, i, create_handler(a, id.clone()))?; + } else { + ans.insert_with_txn(txn, i, v.clone())?; + } + } + + Ok(ans) + } + } + } + + fn get_attached(&self) -> Option<Self> { + match &self.inner { + MaybeDetached::Detached(d) => d.lock().attached.clone().map(|x| Self { + inner: MaybeDetached::Attached(x), + }), + MaybeDetached::Attached(_a) => Some(self.clone()), + } + } + + fn doc(&self) -> Option<LoroDoc> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => Some(a.doc()), + } + } +} + +impl std::fmt::Debug for MovableListHandler { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "MovableListHandler {}", self.id()) + } +} + +impl std::fmt::Debug for ListHandler { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.inner { + MaybeDetached::Detached(_) => write!(f, "ListHandler Detached"), + MaybeDetached::Attached(a) => write!(f, "ListHandler {}", a.id), + } + } +} + +impl HandlerTrait for ListHandler { + fn is_attached(&self) -> bool { + self.inner.is_attached() + } + + fn attached_handler(&self) -> Option<&BasicHandler> { + self.inner.attached_handler() + } + + fn get_value(&self) -> LoroValue { + match &self.inner { + MaybeDetached::Detached(a) => { + let a = a.lock(); + LoroValue::List(a.value.iter().map(|v| v.to_value()).collect()) + } + MaybeDetached::Attached(a) => a.get_value(), + } + } + + fn get_deep_value(&self) -> LoroValue { + match &self.inner { + MaybeDetached::Detached(a) => { + let a = a.lock(); + LoroValue::List(a.value.iter().map(|v| v.to_deep_value()).collect()) + } + MaybeDetached::Attached(a) => a.get_deep_value(), + } + } + + fn kind(&self) -> ContainerType { + ContainerType::List + } + + fn to_handler(&self) -> Handler { + Handler::List(self.clone()) + } + + fn attach( + &self, + txn: &mut Transaction, + parent: &BasicHandler, + self_id: ContainerID, + ) -> LoroResult<Self> { + match &self.inner { + MaybeDetached::Detached(l) => { + let mut l = l.lock(); + let inner = create_handler(parent, self_id); + let list = inner.into_list().unwrap(); + for (index, v) in l.value.iter().enumerate() { + match v { + ValueOrHandler::Value(v) => { + list.insert_with_txn(txn, index, v.clone())?; + } + ValueOrHandler::Handler(h) => { + list.insert_container_with_txn(txn, index, h.clone())?; + } + } + } + l.attached = list.attached_handler().cloned(); + Ok(list) + } + MaybeDetached::Attached(a) => { + let new_inner = create_handler(a, self_id); + let ans = new_inner.into_list().unwrap(); + + for (i, v) in self.get_value().into_list().unwrap().iter().enumerate() { + if let LoroValue::Container(id) = v { + ans.insert_container_with_txn(txn, i, create_handler(a, id.clone()))?; + } else { + ans.insert_with_txn(txn, i, v.clone())?; + } + } + + Ok(ans) + } + } + } + + fn get_attached(&self) -> Option<Self> { + match &self.inner { + MaybeDetached::Detached(d) => d.lock().attached.clone().map(|x| Self { + inner: MaybeDetached::Attached(x), + }), + MaybeDetached::Attached(_a) => Some(self.clone()), + } + } + + fn from_handler(h: Handler) -> Option<Self> { + match h { + Handler::List(x) => Some(x), + _ => None, + } + } + + fn doc(&self) -> Option<LoroDoc> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => Some(a.doc()), + } + } +} + +#[derive(Clone)] +pub struct UnknownHandler { + inner: BasicHandler, +} + +impl Debug for UnknownHandler { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "UnknownHandler") + } +} + +impl UnknownHandler { + pub fn is_deleted(&self) -> bool { + self.inner.is_deleted() + } +} + +impl HandlerTrait for UnknownHandler { + fn is_attached(&self) -> bool { + true + } + + fn attached_handler(&self) -> Option<&BasicHandler> { + Some(&self.inner) + } + + fn get_value(&self) -> LoroValue { + // The payload of an unknown container is opaque to this version of + // Loro; expose it as `Null`, matching the public API convention in + // `ValueOrContainer::get_deep_value` (crates/loro/src/lib.rs). + LoroValue::Null + } + + fn get_deep_value(&self) -> LoroValue { + LoroValue::Null + } + + fn kind(&self) -> ContainerType { + self.inner.id.container_type() + } + + fn to_handler(&self) -> Handler { + Handler::Unknown(self.clone()) + } + + fn from_handler(h: Handler) -> Option<Self> { + match h { + Handler::Unknown(x) => Some(x), + _ => None, + } + } + + fn attach( + &self, + _txn: &mut Transaction, + _parent: &BasicHandler, + self_id: ContainerID, + ) -> LoroResult<Self> { + let new_inner = create_handler(&self.inner, self_id); + let ans = new_inner.into_unknown().unwrap(); + Ok(ans) + } + + fn get_attached(&self) -> Option<Self> { + Some(self.clone()) + } + + fn doc(&self) -> Option<LoroDoc> { + Some(self.inner.doc()) + } +} + +#[derive(Clone, EnumAsInner, Debug)] +pub enum Handler { + Text(TextHandler), + Map(MapHandler), + List(ListHandler), + MovableList(MovableListHandler), + Tree(TreeHandler), + #[cfg(feature = "counter")] + Counter(counter::CounterHandler), + Unknown(UnknownHandler), +} + +impl HandlerTrait for Handler { + fn is_attached(&self) -> bool { + match self { + Self::Text(x) => x.is_attached(), + Self::Map(x) => x.is_attached(), + Self::List(x) => x.is_attached(), + Self::Tree(x) => x.is_attached(), + Self::MovableList(x) => x.is_attached(), + #[cfg(feature = "counter")] + Self::Counter(x) => x.is_attached(), + Self::Unknown(x) => x.is_attached(), + } + } + + fn attached_handler(&self) -> Option<&BasicHandler> { + match self { + Self::Text(x) => x.attached_handler(), + Self::Map(x) => x.attached_handler(), + Self::List(x) => x.attached_handler(), + Self::MovableList(x) => x.attached_handler(), + Self::Tree(x) => x.attached_handler(), + #[cfg(feature = "counter")] + Self::Counter(x) => x.attached_handler(), + Self::Unknown(x) => x.attached_handler(), + } + } + + fn get_value(&self) -> LoroValue { + match self { + Self::Text(x) => x.get_value(), + Self::Map(x) => x.get_value(), + Self::List(x) => x.get_value(), + Self::MovableList(x) => x.get_value(), + Self::Tree(x) => x.get_value(), + #[cfg(feature = "counter")] + Self::Counter(x) => x.get_value(), + Self::Unknown(x) => x.get_value(), + } + } + + fn get_deep_value(&self) -> LoroValue { + match self { + Self::Text(x) => x.get_deep_value(), + Self::Map(x) => x.get_deep_value(), + Self::List(x) => x.get_deep_value(), + Self::MovableList(x) => x.get_deep_value(), + Self::Tree(x) => x.get_deep_value(), + #[cfg(feature = "counter")] + Self::Counter(x) => x.get_deep_value(), + Self::Unknown(x) => x.get_deep_value(), + } + } + + fn kind(&self) -> ContainerType { + match self { + Self::Text(x) => x.kind(), + Self::Map(x) => x.kind(), + Self::List(x) => x.kind(), + Self::MovableList(x) => x.kind(), + Self::Tree(x) => x.kind(), + #[cfg(feature = "counter")] + Self::Counter(x) => x.kind(), + Self::Unknown(x) => x.kind(), + } + } + + fn to_handler(&self) -> Handler { + match self { + Self::Text(x) => x.to_handler(), + Self::Map(x) => x.to_handler(), + Self::List(x) => x.to_handler(), + Self::MovableList(x) => x.to_handler(), + Self::Tree(x) => x.to_handler(), + #[cfg(feature = "counter")] + Self::Counter(x) => x.to_handler(), + Self::Unknown(x) => x.to_handler(), + } + } + + fn attach( + &self, + txn: &mut Transaction, + parent: &BasicHandler, + self_id: ContainerID, + ) -> LoroResult<Self> { + match self { + Self::Text(x) => Ok(Handler::Text(x.attach(txn, parent, self_id)?)), + Self::Map(x) => Ok(Handler::Map(x.attach(txn, parent, self_id)?)), + Self::List(x) => Ok(Handler::List(x.attach(txn, parent, self_id)?)), + Self::MovableList(x) => Ok(Handler::MovableList(x.attach(txn, parent, self_id)?)), + Self::Tree(x) => Ok(Handler::Tree(x.attach(txn, parent, self_id)?)), + #[cfg(feature = "counter")] + Self::Counter(x) => Ok(Handler::Counter(x.attach(txn, parent, self_id)?)), + Self::Unknown(x) => Ok(Handler::Unknown(x.attach(txn, parent, self_id)?)), + } + } + + fn get_attached(&self) -> Option<Self> { + match self { + Self::Text(x) => x.get_attached().map(Handler::Text), + Self::Map(x) => x.get_attached().map(Handler::Map), + Self::List(x) => x.get_attached().map(Handler::List), + Self::MovableList(x) => x.get_attached().map(Handler::MovableList), + Self::Tree(x) => x.get_attached().map(Handler::Tree), + #[cfg(feature = "counter")] + Self::Counter(x) => x.get_attached().map(Handler::Counter), + Self::Unknown(x) => x.get_attached().map(Handler::Unknown), + } + } + + fn from_handler(h: Handler) -> Option<Self> { + Some(h) + } + + fn doc(&self) -> Option<LoroDoc> { + match self { + Self::Text(x) => x.doc(), + Self::Map(x) => x.doc(), + Self::List(x) => x.doc(), + Self::MovableList(x) => x.doc(), + Self::Tree(x) => x.doc(), + #[cfg(feature = "counter")] + Self::Counter(x) => x.doc(), + Self::Unknown(x) => x.doc(), + } + } +} + +impl Handler { + fn apply_map_container_diff_value( + map: &MapHandler, + key: &str, + old_id: ContainerID, + on_container_remap: &mut dyn FnMut(ContainerID, ContainerID), + full_state_targets: &mut FxHashSet<ContainerID>, + ) -> LoroResult<()> { + if old_id.is_mergeable() { + let parent_id = map.id(); + let kind = old_id.container_type(); + let new_id = ContainerID::new_mergeable(&parent_id, key, kind); + let marker = loro_common::mergeable_marker(&parent_id, key, kind); + map.insert_without_skipping(key, marker)?; + // The deterministic cid may still hold hidden state, while the child's diff in + // this batch is its full target state. Reconcile instead of appending. + full_state_targets.insert(new_id.clone()); + on_container_remap(old_id, new_id); + return Ok(()); + } + + let new_h = map.insert_container(key, Handler::new_unattached(old_id.container_type())?)?; + let new_id = new_h.id(); + on_container_remap(old_id, new_id); + Ok(()) + } + + pub(crate) fn new_attached(id: ContainerID, doc: LoroDoc) -> Self { + let kind = id.container_type(); + let handler = BasicHandler { + container_idx: doc.arena.register_container(&id), + id, + doc, + }; + + match kind { + ContainerType::Map => Self::Map(MapHandler { + inner: handler.into(), + }), + ContainerType::List => Self::List(ListHandler { + inner: handler.into(), + }), + ContainerType::Tree => Self::Tree(TreeHandler { + inner: handler.into(), + }), + ContainerType::Text => Self::Text(TextHandler { + inner: handler.into(), + }), + ContainerType::MovableList => Self::MovableList(MovableListHandler { + inner: handler.into(), + }), + #[cfg(feature = "counter")] + ContainerType::Counter => Self::Counter(counter::CounterHandler { + inner: handler.into(), + }), + ContainerType::Unknown(_) => Self::Unknown(UnknownHandler { inner: handler }), + } + } + + /// Errors on [ContainerType::Unknown]: this version cannot create a + /// container of a type it doesn't know. + pub(crate) fn new_unattached(kind: ContainerType) -> LoroResult<Self> { + Ok(match kind { + ContainerType::Text => Self::Text(TextHandler::new_detached()), + ContainerType::Map => Self::Map(MapHandler::new_detached()), + ContainerType::List => Self::List(ListHandler::new_detached()), + ContainerType::Tree => Self::Tree(TreeHandler::new_detached()), + ContainerType::MovableList => Self::MovableList(MovableListHandler::new_detached()), + #[cfg(feature = "counter")] + ContainerType::Counter => Self::Counter(counter::CounterHandler::new_detached()), + ContainerType::Unknown(_) => return Err(unknown_container_creation_err(kind)), + }) + } + + pub fn id(&self) -> ContainerID { + match self { + Self::Map(x) => x.id(), + Self::List(x) => x.id(), + Self::Text(x) => x.id(), + Self::Tree(x) => x.id(), + Self::MovableList(x) => x.id(), + #[cfg(feature = "counter")] + Self::Counter(x) => x.id(), + Self::Unknown(x) => x.id(), + } + } + + pub(crate) fn container_idx(&self) -> ContainerIdx { + match self { + Self::Map(x) => x.idx(), + Self::List(x) => x.idx(), + Self::Text(x) => x.idx(), + Self::Tree(x) => x.idx(), + Self::MovableList(x) => x.idx(), + #[cfg(feature = "counter")] + Self::Counter(x) => x.idx(), + Self::Unknown(x) => x.idx(), + } + } + + pub fn c_type(&self) -> ContainerType { + match self { + Self::Map(_) => ContainerType::Map, + Self::List(_) => ContainerType::List, + Self::Text(_) => ContainerType::Text, + Self::Tree(_) => ContainerType::Tree, + Self::MovableList(_) => ContainerType::MovableList, + #[cfg(feature = "counter")] + Self::Counter(_) => ContainerType::Counter, + Self::Unknown(x) => x.id().container_type(), + } + } + + fn get_deep_value(&self) -> LoroValue { + match self { + Self::Map(x) => x.get_deep_value(), + Self::List(x) => x.get_deep_value(), + Self::MovableList(x) => x.get_deep_value(), + Self::Text(x) => x.get_deep_value(), + Self::Tree(x) => x.get_deep_value(), + #[cfg(feature = "counter")] + Self::Counter(x) => x.get_deep_value(), + Self::Unknown(x) => x.get_deep_value(), + } + } + + pub(crate) fn apply_diff( + &self, + diff: Diff, + container_remap: &mut FxHashMap<ContainerID, ContainerID>, + full_state_targets: &mut FxHashSet<ContainerID>, + ) -> LoroResult<()> { + // In this method we will not clone the values of the containers if + // they are remapped. It's the caller's duty to do so + let on_container_remap = &mut |old_id, new_id| { + if old_id != new_id { + container_remap.insert(old_id, new_id); + } + }; + match self { + Self::Map(x) => { + let diff = match diff { + crate::event::Diff::Map(d) => d, + _ => { + return Err(LoroError::DecodeError( + "Invalid diff type for map container".into(), + )); + } + }; + for (key, value) in diff.updated.into_iter() { + match value.value { + Some(ValueOrHandler::Handler(h)) => { + Self::apply_map_container_diff_value( + x, + &key, + h.id(), + on_container_remap, + full_state_targets, + )?; + } + Some(ValueOrHandler::Value(LoroValue::Container(old_id))) => { + Self::apply_map_container_diff_value( + x, + &key, + old_id, + on_container_remap, + full_state_targets, + )?; + } + Some(ValueOrHandler::Value(v)) => { + x.insert_without_skipping(&key, v)?; + } + None => { + x.delete(&key)?; + } + } + } + } + Self::Text(x) => { + let delta = match diff { + crate::event::Diff::Text(d) => d, + _ => { + return Err(LoroError::DecodeError( + "Invalid diff type for text container".into(), + )); + } + }; + x.apply_delta(&TextDelta::from_text_diff(delta.iter()))?; + } + Self::List(x) => { + let delta = match diff { + crate::event::Diff::List(d) => d, + _ => { + return Err(LoroError::DecodeError( + "Invalid diff type for list container".into(), + )); + } + }; + x.apply_delta(delta, on_container_remap)?; + } + Self::MovableList(x) => { + let delta = match diff { + crate::event::Diff::List(d) => d, + _ => { + return Err(LoroError::DecodeError( + "Invalid diff type for movable list container".into(), + )); + } + }; + x.apply_delta(delta, container_remap)?; + } + Self::Tree(x) => { + fn remap_tree_id( + id: &mut TreeID, + container_remap: &FxHashMap<ContainerID, ContainerID>, + ) { + let mut remapped = false; + let mut map_id = id.associated_meta_container(); + while let Some(rid) = container_remap.get(&map_id) { + remapped = true; + map_id = rid.clone(); + } + if remapped { + *id = TreeID::new( + *map_id.as_normal().unwrap().0, + *map_id.as_normal().unwrap().1, + ) + } + } + let tree_diff = match diff { + crate::event::Diff::Tree(d) => d, + _ => { + return Err(LoroError::DecodeError( + "Invalid diff type for tree container".into(), + )); + } + }; + for diff in tree_diff.diff { + let mut target = diff.target; + match diff.action { + TreeExternalDiff::Create { + mut parent, + index: _, + position, + } => { + if let TreeParentId::Node(p) = &mut parent { + remap_tree_id(p, container_remap) + } + remap_tree_id(&mut target, container_remap); + if !x.is_node_unexist(&target) && !x.is_node_deleted(&target)? { + // 1@0 is the parent of 2@1 + // ┌────┐ ┌───────────────┐ + // │xxxx│◀───│Move 2@1 to 0@0◀┐ + // └────┘ └───────────────┘│ + // ┌───────┐ │ ┌────────┐ + // │Del 1@0│◀─────────────────┴─│Meta 2@1│ ◀─── undo 2 ops redo 2 ops + // └───────┘ └────────┘ + // + // When we undo the delete operation, we should not create a new tree node and its child. + // However, the concurrent operation has moved the child to another parent. It's still alive. + // So when we redo the delete operation, we should check if the target is still alive. + // If it's alive, we should move it back instead of creating new one. + x.move_at_with_target_for_apply_diff(parent, position, target)?; + } else { + let new_target = x.__internal__next_tree_id(); + if x.create_at_with_target_for_apply_diff( + parent, position, new_target, + )? { + container_remap.insert( + target.associated_meta_container(), + new_target.associated_meta_container(), + ); + } + } + } + TreeExternalDiff::Move { + mut parent, + index: _, + position, + old_parent: _, + old_index: _, + } => { + if let TreeParentId::Node(p) = &mut parent { + remap_tree_id(p, container_remap) + } + remap_tree_id(&mut target, container_remap); + // determine if the target is deleted + if x.is_node_unexist(&target) || x.is_node_deleted(&target)? { + // create the target node, we should use the new target id + let new_target = x.__internal__next_tree_id(); + if x.create_at_with_target_for_apply_diff( + parent, position, new_target, + )? { + container_remap.insert( + target.associated_meta_container(), + new_target.associated_meta_container(), + ); + } + } else { + x.move_at_with_target_for_apply_diff(parent, position, target)?; + } + } + TreeExternalDiff::Delete { .. } => { + remap_tree_id(&mut target, container_remap); + if !x.is_node_deleted(&target)? { + x.delete(target)?; + } + } + } + } + } + #[cfg(feature = "counter")] + Self::Counter(x) => { + let delta = match diff { + crate::event::Diff::Counter(d) => d, + _ => { + return Err(LoroError::DecodeError( + "Invalid diff type for counter container".into(), + )); + } + }; + x.increment(delta)?; + } + Self::Unknown(_) => { + // do nothing + } + } + + Ok(()) + } + + pub fn clear(&self) -> LoroResult<()> { + match self { + Handler::Text(text_handler) => text_handler.clear(), + Handler::Map(map_handler) => map_handler.clear(), + Handler::List(list_handler) => list_handler.clear(), + Handler::MovableList(movable_list_handler) => movable_list_handler.clear(), + Handler::Tree(tree_handler) => tree_handler.clear(), + #[cfg(feature = "counter")] + Handler::Counter(counter_handler) => counter_handler.clear(), + Handler::Unknown(_unknown_handler) => Ok(()), + } + } +} + +#[derive(Clone, EnumAsInner, Debug)] +pub enum ValueOrHandler { + Value(LoroValue), + Handler(Handler), +} + +impl ValueOrHandler { + pub(crate) fn from_value(value: LoroValue, doc: &Arc<LoroDocInner>) -> Self { + if let LoroValue::Container(c) = value { + ValueOrHandler::Handler(Handler::new_attached(c, LoroDoc::from_inner(doc.clone()))) + } else { + ValueOrHandler::Value(value) + } + } + + pub(crate) fn to_value(&self) -> LoroValue { + match self { + Self::Value(v) => v.clone(), + Self::Handler(h) => LoroValue::Container(h.id().clone()), + } + } + + pub(crate) fn to_deep_value(&self) -> LoroValue { + match self { + Self::Value(v) => v.clone(), + Self::Handler(h) => h.get_deep_value(), + } + } +} + +impl From<LoroValue> for ValueOrHandler { + fn from(value: LoroValue) -> Self { + ValueOrHandler::Value(value) + } +} + +impl TextHandler { + /// Create a new container that is detached from the document. + /// + /// The edits on a detached container will not be persisted. + /// To attach the container to the document, please insert it into an attached container. + pub fn new_detached() -> Self { + Self { + inner: MaybeDetached::new_detached(RichtextState::default()), + } + } + + /// Get the version id of the richtext + /// + /// This can be used to detect whether the richtext is changed + pub fn version_id(&self) -> Option<usize> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => { + Some(a.with_state(|state| state.as_richtext_state_mut().unwrap().get_version_id())) + } + } + } + + pub fn get_richtext_value(&self) -> LoroValue { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.get_richtext_value() + } + MaybeDetached::Attached(a) => { + a.with_state(|state| state.as_richtext_state_mut().unwrap().get_richtext_value()) + } + } + } + + pub fn is_empty(&self) -> bool { + match &self.inner { + MaybeDetached::Detached(t) => t.lock().value.is_empty(), + MaybeDetached::Attached(a) if a.has_decoded_state() => { + a.with_state(|state| state.as_richtext_state_mut().unwrap().is_empty()) + } + MaybeDetached::Attached(a) => a.get_value().as_string().unwrap().is_empty(), + } + } + + pub fn len_utf8(&self) -> usize { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.len_utf8() + } + MaybeDetached::Attached(a) => { + a.with_doc_state(|state| state.get_text_len(a.container_idx, PosType::Bytes)) + } + } + } + + pub fn len_utf16(&self) -> usize { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.len_utf16() + } + MaybeDetached::Attached(a) => { + a.with_doc_state(|state| state.get_text_len(a.container_idx, PosType::Utf16)) + } + } + } + + pub fn len_unicode(&self) -> usize { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.len_unicode() + } + MaybeDetached::Attached(a) => { + a.with_doc_state(|state| state.get_text_len(a.container_idx, PosType::Unicode)) + } + } + } + + /// if `wasm` feature is enabled, it is a UTF-16 length + /// otherwise, it is a Unicode length + pub fn len_event(&self) -> usize { + if cfg!(feature = "wasm") { + self.len_utf16() + } else { + self.len_unicode() + } + } + + fn len(&self, pos_type: PosType) -> usize { + match &self.inner { + MaybeDetached::Detached(t) => t.lock().value.len(pos_type), + MaybeDetached::Attached(a) => { + a.with_doc_state(|state| state.get_text_len(a.container_idx, pos_type)) + } + } + } + + fn validate_text_boundary(&self, pos: usize, pos_type: PosType) -> LoroResult<()> { + let err = match pos_type { + PosType::Bytes => Some(LoroError::UTF8InUnicodeCodePoint { pos }), + PosType::Utf16 => Some(LoroError::UTF16InUnicodeCodePoint { pos }), + PosType::Event if cfg!(feature = "wasm") => { + Some(LoroError::UTF16InUnicodeCodePoint { pos }) + } + _ => None, + }; + + let Some(err) = err else { + return Ok(()); + }; + + let len = self.len(pos_type); + if pos > len { + return Ok(()); + } + + if self.all_text_positions_are_boundaries(pos_type, len) { + return Ok(()); + } + + let Some(unicode_pos) = self.convert_pos(pos, pos_type, PosType::Unicode) else { + return Err(err); + }; + if self.convert_pos(unicode_pos, PosType::Unicode, pos_type) != Some(pos) { + return Err(err); + } + + Ok(()) + } + + fn all_text_positions_are_boundaries(&self, pos_type: PosType, len: usize) -> bool { + match pos_type { + PosType::Bytes => len == self.len_unicode(), + PosType::Utf16 => len == self.len_unicode(), + PosType::Event if cfg!(feature = "wasm") => len == self.len_unicode(), + _ => false, + } + } + + pub fn diagnose(&self) { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.diagnose(); + } + MaybeDetached::Attached(a) => { + a.with_state(|state| state.as_richtext_state_mut().unwrap().diagnose()); + } + } + } + + pub fn iter(&self, mut callback: impl FnMut(&str) -> bool) { + // Do not call user callbacks while holding the state lock; callbacks may re-enter Loro. + let spans: Vec<String> = match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value + .iter() + .map(|span| span.text.as_str().to_owned()) + .collect() + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let mut spans = Vec::new(); + state.as_richtext_state_mut().unwrap().iter(|span| { + spans.push(span.to_owned()); + true + }); + spans + }), + }; + + for span in spans { + if !callback(span.as_str()) { + return; + } + } + } + + /// Get a character at `pos` in the coordinate system specified by `pos_type`. + pub fn char_at(&self, pos: usize, pos_type: PosType) -> LoroResult<char> { + let len = self.len(pos_type); + if pos >= len { + return Err(LoroError::OutOfBound { + pos, + len, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }); + } + if let Ok(c) = match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + let event_pos = match pos_type { + PosType::Event => pos, + _ => t.value.index_to_event_index(pos, pos_type), + }; + t.value.get_char_by_event_index(event_pos) + } + MaybeDetached::Attached(a) if a.has_decoded_state() || pos_type == PosType::Entity => a + .with_state(|state| { + let state = state.as_richtext_state_mut().unwrap(); + let event_pos = match pos_type { + PosType::Event => pos, + _ => state.index_to_event_index(pos, pos_type), + }; + state.get_char_by_event_index(event_pos) + }), + MaybeDetached::Attached(a) => { + return text_char_at(a.get_value().as_string().unwrap(), pos, pos_type); + } + } { + Ok(c) + } else { + Err(LoroError::OutOfBound { + pos, + len, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }) + } + } + + /// `start_index` and `end_index` are Event Index: + /// + /// - if feature="wasm", pos is a UTF-16 index + /// - if feature!="wasm", pos is a Unicode index + /// + pub fn slice( + &self, + start_index: usize, + end_index: usize, + pos_type: PosType, + ) -> LoroResult<String> { + self.slice_with_pos_type(start_index, end_index, pos_type) + } + + pub fn slice_utf16(&self, start_index: usize, end_index: usize) -> LoroResult<String> { + self.slice(start_index, end_index, PosType::Utf16) + } + + fn slice_with_pos_type( + &self, + start_index: usize, + end_index: usize, + pos_type: PosType, + ) -> LoroResult<String> { + if end_index < start_index { + return Err(LoroError::EndIndexLessThanStartIndex { + start: start_index, + end: end_index, + }); + } + if start_index == end_index { + return Ok(String::new()); + } + + let info = || format!("Position: {}:{}", file!(), line!()).into_boxed_str(); + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + let len = t.value.len(pos_type); + if end_index > len { + return Err(LoroError::OutOfBound { + pos: end_index, + len, + info: info(), + }); + } + let (start, end) = match pos_type { + PosType::Event => (start_index, end_index), + _ => ( + t.value.index_to_event_index(start_index, pos_type), + t.value.index_to_event_index(end_index, pos_type), + ), + }; + t.value.get_text_slice_by_event_index(start, end - start) + } + MaybeDetached::Attached(a) if a.has_decoded_state() || pos_type == PosType::Entity => a + .with_state(|state| { + let state = state.as_richtext_state_mut().unwrap(); + let len = state.len(pos_type); + if end_index > len { + return Err(LoroError::OutOfBound { + pos: end_index, + len, + info: info(), + }); + } + let (start, end) = match pos_type { + PosType::Event => (start_index, end_index), + _ => ( + state.index_to_event_index(start_index, pos_type), + state.index_to_event_index(end_index, pos_type), + ), + }; + state.get_text_slice_by_event_index(start, end - start) + }), + MaybeDetached::Attached(a) => text_slice( + a.get_value().as_string().unwrap(), + start_index, + end_index, + pos_type, + ) + .map_err(|err| match err { + LoroError::OutOfBound { pos, len, .. } => LoroError::OutOfBound { + pos, + len, + info: info(), + }, + err => err, + }), + } + } + + pub fn slice_delta( + &self, + start_index: usize, + end_index: usize, + pos_type: PosType, + ) -> LoroResult<Vec<TextDelta>> { + if end_index < start_index { + return Err(LoroError::EndIndexLessThanStartIndex { + start: start_index, + end: end_index, + }); + } + if start_index == end_index { + return Ok(Vec::new()); + } + + let len = self.len(pos_type); + if end_index > len { + return Err(LoroError::OutOfBound { + pos: end_index, + len, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }); + } + self.validate_text_boundary(start_index, pos_type)?; + self.validate_text_boundary(end_index, pos_type)?; + + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + let ans = t.value.slice_delta(start_index, end_index, pos_type)?; + Ok(ans + .into_iter() + .map(|(s, a)| TextDelta::Insert { + insert: s, + attributes: a.to_option_map_without_null_value(), + }) + .collect()) + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let ans = state.as_richtext_state_mut().unwrap().slice_delta( + start_index, + end_index, + pos_type, + )?; + Ok(ans + .into_iter() + .map(|(s, a)| TextDelta::Insert { + insert: s, + attributes: a.to_option_map_without_null_value(), + }) + .collect()) + }), + } + } + + /// `pos` is a Event Index: + /// + /// - if feature="wasm", pos is a UTF-16 index + /// - if feature!="wasm", pos is a Unicode index + /// + /// This method requires auto_commit to be enabled. + pub fn splice(&self, pos: usize, len: usize, s: &str, pos_type: PosType) -> LoroResult<String> { + let end = checked_range_end(pos, len, self.len(pos_type), || { + format!("Position: {}:{}", file!(), line!()).into_boxed_str() + })?; + let x = self.slice(pos, end, pos_type)?; + self.delete(pos, len, pos_type)?; + self.insert(pos, s, pos_type)?; + Ok(x) + } + + pub fn splice_utf8(&self, pos: usize, len: usize, s: &str) -> LoroResult<()> { + // let x = self.slice(pos, pos + len)?; + self.delete_utf8(pos, len)?; + self.insert_utf8(pos, s)?; + Ok(()) + } + + pub fn splice_utf16(&self, pos: usize, len: usize, s: &str) -> LoroResult<()> { + self.delete(pos, len, PosType::Utf16)?; + self.insert(pos, s, PosType::Utf16)?; + Ok(()) + } + + /// Insert text at `pos` using the given `pos_type` coordinate system. + /// + /// This method requires auto_commit to be enabled. + pub fn insert(&self, pos: usize, s: &str, pos_type: PosType) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(t) => { + let len = self.len(pos_type); + if pos > len { + return Err(LoroError::OutOfBound { + pos, + len, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }); + } + self.validate_text_boundary(pos, pos_type)?; + + let mut t = t.lock(); + let (index, _) = t + .value + .get_entity_index_for_text_insert(pos, pos_type) + .unwrap(); + t.value.insert_at_entity_index( + index, + BytesSlice::from_bytes(s.as_bytes()), + IdFull::NONE_ID, + ); + Ok(()) + } + MaybeDetached::Attached(a) => { + if s.is_empty() { + let len = self.len(pos_type); + if pos > len { + return Err(LoroError::OutOfBound { + pos, + len, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }); + } + self.validate_text_boundary(pos, pos_type)?; + return Ok(()); + } + + a.with_txn(|txn| self.insert_with_txn(txn, pos, s, pos_type)) + } + } + } + + pub fn insert_utf8(&self, pos: usize, s: &str) -> LoroResult<()> { + self.insert(pos, s, PosType::Bytes) + } + + pub fn insert_utf16(&self, pos: usize, s: &str) -> LoroResult<()> { + self.insert(pos, s, PosType::Utf16) + } + + pub fn insert_unicode(&self, pos: usize, s: &str) -> LoroResult<()> { + self.insert(pos, s, PosType::Unicode) + } + + /// Insert text within an existing transaction using the provided `pos_type`. + pub fn insert_with_txn( + &self, + txn: &mut Transaction, + pos: usize, + s: &str, + pos_type: PosType, + ) -> LoroResult<()> { + self.insert_with_txn_and_attr(txn, pos, s, None, pos_type)?; + Ok(()) + } + + pub fn insert_with_txn_utf8( + &self, + txn: &mut Transaction, + pos: usize, + s: &str, + ) -> LoroResult<()> { + self.insert_with_txn(txn, pos, s, PosType::Bytes) + } + + /// Delete a span using the coordinate system described by `pos_type`. + /// + /// This method requires auto_commit to be enabled. + pub fn delete(&self, pos: usize, len: usize, pos_type: PosType) -> LoroResult<()> { + if len == 0 { + return Ok(()); + } + + let text_len = self.len(pos_type); + let end = checked_range_end(pos, len, text_len, || { + format!("Position: {}:{}", file!(), line!()).into_boxed_str() + })?; + self.validate_text_boundary(pos, pos_type)?; + self.validate_text_boundary(end, pos_type)?; + + match &self.inner { + MaybeDetached::Detached(t) => { + let mut t = t.lock(); + let ranges = t.value.get_text_entity_ranges(pos, len, pos_type)?; + for range in ranges.iter().rev() { + t.value + .drain_by_entity_index(range.entity_start, range.entity_len(), None); + } + Ok(()) + } + MaybeDetached::Attached(a) => { + a.with_txn(|txn| self.delete_with_txn(txn, pos, len, pos_type)) + } + } + } + + pub fn delete_utf8(&self, pos: usize, len: usize) -> LoroResult<()> { + self.delete(pos, len, PosType::Bytes) + } + + pub fn delete_utf16(&self, pos: usize, len: usize) -> LoroResult<()> { + self.delete(pos, len, PosType::Utf16) + } + + pub fn delete_unicode(&self, pos: usize, len: usize) -> LoroResult<()> { + self.delete(pos, len, PosType::Unicode) + } + + /// If attr is specified, it will be used as the attribute of the inserted text. + /// It will override the existing attribute of the text. + fn insert_with_txn_and_attr( + &self, + txn: &mut Transaction, + pos: usize, + s: &str, + attr: Option<&FxHashMap<String, LoroValue>>, + pos_type: PosType, + ) -> Result<Vec<(InternalString, LoroValue)>, LoroError> { + if s.is_empty() { + return Ok(Vec::new()); + } + + // Fast path: plain-text insert into a style-free document (non-wasm). + // With no style anchors, entity_index == unicode pos and the event index + // equals the unicode index, so bounds + no-styles are checked in a single + // state access and the entire read phase (cursor location + two + // visit_previous_caches walks + styles lookup) is skipped; apply_local_op + // then locates the cursor exactly once. + #[cfg(not(feature = "wasm"))] + if attr.is_none() && pos_type == PosType::Unicode { + let inner = self.inner.try_attached_state()?; + let fast = inner.with_state(|state| { + let rt = state.as_richtext_state_mut().unwrap(); + if rt.has_styles() { + return Ok(false); + } + let len = rt.len_unicode(); + if pos > len { + return Err(LoroError::OutOfBound { + pos, + len, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }); + } + Ok(true) + })?; + if fast { + let unicode_len = s.chars().count(); + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::List( + crate::container::list::list_op::ListOp::Insert { + slice: ListSlice::RawStr { + str: Cow::Borrowed(s), + unicode_len, + }, + // entity_index == unicode pos (no style anchors) + pos, + }, + ), + EventHint::InsertText { + // event index == unicode index (non-wasm) + pos: pos as u32, + styles: StyleMeta::empty(), + unicode_len: unicode_len as u32, + event_len: unicode_len as u32, + }, + &inner.doc, + )?; + return Ok(Vec::new()); + } + } + + match pos_type { + PosType::Event => { + if pos > self.len_event() { + return Err(LoroError::OutOfBound { + pos, + len: self.len_event(), + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }); + } + } + PosType::Bytes => { + if pos > self.len_utf8() { + return Err(LoroError::OutOfBound { + pos, + len: self.len_utf8(), + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }); + } + } + PosType::Unicode => { + if pos > self.len_unicode() { + return Err(LoroError::OutOfBound { + pos, + len: self.len_unicode(), + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }); + } + } + PosType::Entity => {} + PosType::Utf16 => { + if pos > self.len_utf16() { + return Err(LoroError::OutOfBound { + pos, + len: self.len_utf16(), + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }); + } + } + } + self.validate_text_boundary(pos, pos_type)?; + + let inner = self.inner.try_attached_state()?; + let (entity_index, event_index, styles) = inner.with_state(|state| { + let richtext_state = state.as_richtext_state_mut().unwrap(); + let ret = richtext_state.get_entity_index_for_text_insert(pos, pos_type); + let (entity_index, cursor) = match ret { + Err(_) => match pos_type { + PosType::Bytes => { + return ( + Err(LoroError::UTF8InUnicodeCodePoint { pos }), + 0, + StyleMeta::empty(), + ); + } + PosType::Utf16 | PosType::Event => { + return ( + Err(LoroError::UTF16InUnicodeCodePoint { pos }), + 0, + StyleMeta::empty(), + ); + } + _ => unreachable!(), + }, + Ok(x) => x, + }; + let event_index = if let Some(cursor) = cursor { + if pos_type == PosType::Event { + debug_assert_eq!( + richtext_state.get_event_index_by_cursor(cursor), + pos, + "pos={} cursor={:?} state={:#?}", + pos, + cursor, + &richtext_state + ); + pos + } else { + richtext_state.get_event_index_by_cursor(cursor) + } + } else { + assert_eq!(entity_index, 0); + 0 + }; + let styles = richtext_state.get_styles_at_entity_index(entity_index); + (Ok(entity_index), event_index, styles) + }); + + let entity_index = match entity_index { + Err(x) => return Err(x), + _ => entity_index.unwrap(), + }; + + let mut override_styles = Vec::new(); + if let Some(attr) = attr { + // current styles + let map: FxHashMap<_, _> = styles.iter().map(|x| (x.0.clone(), x.1.data)).collect(); + for (key, style) in map.iter() { + match attr.get(key.deref()) { + Some(v) if v == style => {} + new_style_value => { + // need to override + let new_style_value = new_style_value.cloned().unwrap_or(LoroValue::Null); + override_styles.push((key.clone(), new_style_value)); + } + } + } + + for (key, style) in attr.iter() { + let key = key.as_str().into(); + if !map.contains_key(&key) { + override_styles.push((key, style.clone())); + } + } + } + + let unicode_len = s.chars().count(); + let event_len = if cfg!(feature = "wasm") { + count_utf16_len(s.as_bytes()) + } else { + unicode_len + }; + + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Insert { + slice: ListSlice::RawStr { + str: Cow::Borrowed(s), + unicode_len, + }, + pos: entity_index, + }), + EventHint::InsertText { + pos: event_index as u32, + styles, + unicode_len: unicode_len as u32, + event_len: event_len as u32, + }, + &inner.doc, + )?; + + Ok(override_styles) + } + + /// Delete text within a transaction using the specified `pos_type`. + pub fn delete_with_txn( + &self, + txn: &mut Transaction, + pos: usize, + len: usize, + pos_type: PosType, + ) -> LoroResult<()> { + self.delete_with_txn_inline(txn, pos, len, pos_type) + } + + fn delete_with_txn_inline( + &self, + txn: &mut Transaction, + pos: usize, + len: usize, + pos_type: PosType, + ) -> LoroResult<()> { + if len == 0 { + return Ok(()); + } + + let text_len = self.len(pos_type); + let end = checked_range_end(pos, len, text_len, || { + format!("Position: {}:{}", file!(), line!()).into_boxed_str() + }) + .inspect_err(|_| error!("pos={} len={} len={}", pos, len, text_len))?; + self.validate_text_boundary(pos, pos_type)?; + self.validate_text_boundary(end, pos_type)?; + + let inner = self.inner.try_attached_state()?; + let s = tracing::span!(tracing::Level::INFO, "delete", "pos={} len={}", pos, len); + let _e = s.enter(); + let mut event_pos = 0; + let mut event_len = 0; + let ranges = inner.with_state(|state| { + let richtext_state = state.as_richtext_state_mut().unwrap(); + // Fast path: with no style anchors (non-wasm), the event index equals + // the unicode index, so the two index_to_event_index walks collapse to + // identity. + let fast = cfg!(not(feature = "wasm")) + && pos_type == PosType::Unicode + && !richtext_state.has_styles(); + if fast { + event_pos = pos; + event_len = len; + } else { + event_pos = richtext_state.index_to_event_index(pos, pos_type); + let event_end = richtext_state.index_to_event_index(end, pos_type); + event_len = event_end - event_pos; + } + + richtext_state.get_text_entity_ranges_in_event_index_range(event_pos, event_len) + })?; + + //debug_assert_eq!(ranges.iter().map(|x| x.event_len).sum::<usize>(), len); + let pos = event_pos as isize; + let len = event_len as isize; + let mut event_end = pos + len; + for range in ranges.iter().rev() { + let event_start = event_end - range.event_len as isize; + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::List(ListOp::Delete(DeleteSpanWithId::new( + range.id_start, + range.entity_start as isize, + range.entity_len() as isize, + ))), + EventHint::DeleteText { + span: DeleteSpan { + pos: event_start, + signed_len: range.event_len as isize, + }, + unicode_len: range.entity_len(), + }, + &inner.doc, + )?; + event_end = event_start; + } + + Ok(()) + } + + /// `start` and `end` are interpreted using `pos_type`. + /// + /// This method requires auto_commit to be enabled. + pub fn mark( + &self, + start: usize, + end: usize, + key: impl Into<InternalString>, + value: LoroValue, + pos_type: PosType, + ) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(t) => { + let mut g = t.lock(); + self.mark_for_detached(&mut g.value, key, &value, start, end, pos_type) + } + MaybeDetached::Attached(a) => { + a.with_txn(|txn| self.mark_with_txn(txn, start, end, key, value, pos_type)) + } + } + } + + fn mark_for_detached( + &self, + state: &mut RichtextState, + key: impl Into<InternalString>, + value: &LoroValue, + start: usize, + end: usize, + pos_type: PosType, + ) -> Result<(), LoroError> { + let key: InternalString = key.into(); + let is_delete = matches!(value, &LoroValue::Null); + if start >= end { + return Err(loro_common::LoroError::ArgErr( + "Start must be less than end".to_string().into_boxed_str(), + )); + } + ensure_no_regular_container_value(value)?; + + let len = state.len(pos_type); + if end > len { + return Err(LoroError::OutOfBound { + pos: end, + len, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }); + } + let (entity_range, styles) = + state.get_entity_range_and_text_styles_at_range(start..end, pos_type); + // `styles` is None when the range spans multiple style ranges; fall + // back to scanning them so redundant marks are still skipped instead + // of accumulating style anchors. + let already_applied = styles.map(|styles| styles.has_key_value(&key, value)); + let already_applied = match already_applied { + Some(applied) => applied, + None => state.range_has_style_key_value(entity_range.clone(), &key, value), + }; + if already_applied { + return Ok(()); + } + + let has_target_style = + state.range_has_style_key(entity_range.clone(), &StyleKey::Key(key.clone())); + let missing_style_key = is_delete && !has_target_style; + + if missing_style_key { + return Ok(()); + } + + let style_op = Arc::new(StyleOp { + lamport: 0, + peer: 0, + cnt: 0, + key, + value: value.clone(), + // TODO: describe this behavior in the document + info: if is_delete { + TextStyleInfoFlag::BOLD.to_delete() + } else { + TextStyleInfoFlag::BOLD + }, + }); + state.mark_with_entity_index(entity_range, style_op); + Ok(()) + } + + /// `start` and `end` are interpreted using `pos_type`. + pub fn unmark( + &self, + start: usize, + end: usize, + key: impl Into<InternalString>, + pos_type: PosType, + ) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(t) => self.mark_for_detached( + &mut t.lock().value, + key, + &LoroValue::Null, + start, + end, + pos_type, + ), + MaybeDetached::Attached(a) => a.with_txn(|txn| { + self.mark_with_txn(txn, start, end, key, LoroValue::Null, pos_type) + }), + } + } + + /// `start` and `end` are interpreted using `pos_type`. + pub fn mark_with_txn( + &self, + txn: &mut Transaction, + start: usize, + end: usize, + key: impl Into<InternalString>, + value: LoroValue, + pos_type: PosType, + ) -> LoroResult<()> { + if start >= end { + return Err(loro_common::LoroError::ArgErr( + "Start must be less than end".to_string().into_boxed_str(), + )); + } + ensure_no_regular_container_value(&value)?; + + let inner = self.inner.try_attached_state()?; + let key: InternalString = key.into(); + let is_delete = matches!(&value, &LoroValue::Null); + + let mut doc_state = inner.doc.state.lock(); + let len = doc_state.with_state_mut(inner.container_idx, |state| { + state.as_richtext_state_mut().unwrap().len(pos_type) + }); + + if end > len { + return Err(LoroError::OutOfBound { + pos: end, + len, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }); + } + + let (entity_range, skip, missing_style_key, event_start, event_end) = doc_state + .with_state_mut(inner.container_idx, |state| { + let state = state.as_richtext_state_mut().unwrap(); + let event_start = state.index_to_event_index(start, pos_type); + let event_end = state.index_to_event_index(end, pos_type); + let (entity_range, styles) = + state.get_entity_range_and_styles_at_range(start..end, pos_type); + + // `styles` is None when the range spans multiple style + // ranges; fall back to scanning them so redundant marks are + // still skipped instead of accumulating style anchors. + let skip = match styles + .as_ref() + .map(|styles| styles.has_key_value(&key, &value)) + { + Some(skip) => skip, + None => state.has_style_key_value_in_entity_range( + entity_range.clone(), + &key, + &value, + ), + }; + let has_target_style = state.has_style_key_in_entity_range( + entity_range.clone(), + &StyleKey::Key(key.clone()), + ); + let missing_style_key = is_delete && !has_target_style; + + ( + entity_range, + skip, + missing_style_key, + event_start, + event_end, + ) + }); + + if skip || missing_style_key { + return Ok(()); + } + + let entity_start = entity_range.start; + let entity_end = entity_range.end; + let style_config = doc_state.config.text_style_config.read(); + let flag = if is_delete { + style_config + .get_style_flag_for_unmark(&key) + .ok_or_else(|| LoroError::StyleConfigMissing(key.clone()))? + } else { + style_config + .get_style_flag(&key) + .ok_or_else(|| LoroError::StyleConfigMissing(key.clone()))? + }; + + drop(style_config); + drop(doc_state); + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::List(ListOp::StyleStart { + start: entity_start as u32, + end: entity_end as u32, + key: key.clone(), + value: value.clone(), + info: flag, + }), + EventHint::Mark { + start: event_start as u32, + end: event_end as u32, + style: crate::container::richtext::Style { key, data: value }, + }, + &inner.doc, + )?; + + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::List(ListOp::StyleEnd), + EventHint::MarkEnd, + &inner.doc, + )?; + + Ok(()) + } + + pub fn check(&self) { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.check_consistency_between_content_and_style_ranges(); + } + MaybeDetached::Attached(a) => a.with_state(|state| { + state + .as_richtext_state_mut() + .unwrap() + .check_consistency_between_content_and_style_ranges(); + }), + } + } + + pub fn apply_delta(&self, delta: &[TextDelta]) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(t) => { + let _t = t.lock(); + // TODO: implement + Err(LoroError::NotImplemented( + "`apply_delta` on a detached text container", + )) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| self.apply_delta_with_txn(txn, delta)), + } + } + + pub fn apply_delta_with_txn( + &self, + txn: &mut Transaction, + delta: &[TextDelta], + ) -> LoroResult<()> { + let mut index = 0; + struct PendingMark { + start: usize, + end: usize, + attributes: FxHashMap<InternalString, LoroValue>, + } + let mut marks: Vec<PendingMark> = Vec::new(); + for d in delta { + match d { + TextDelta::Insert { insert, attributes } => { + let insert_len = event_len(insert.as_str()); + if insert_len == 0 { + continue; + } + + let mut empty_attr = None; + let attr_ref = attributes.as_ref().unwrap_or_else(|| { + empty_attr = Some(FxHashMap::default()); + empty_attr.as_ref().unwrap() + }); + + let end = checked_delta_index_end(index, insert_len, self.len_event())?; + let override_styles = self.insert_with_txn_and_attr( + txn, + index, + insert.as_str(), + Some(attr_ref), + PosType::Event, + )?; + + let mut pending_mark = PendingMark { + start: index, + end, + attributes: FxHashMap::default(), + }; + for (key, value) in override_styles { + pending_mark.attributes.insert(key, value); + } + marks.push(pending_mark); + index = end; + } + TextDelta::Delete { delete } => { + self.delete_with_txn(txn, index, *delete, PosType::Event)?; + } + TextDelta::Retain { attributes, retain } => { + let end = checked_delta_index_end(index, *retain, self.len_event())?; + match attributes { + Some(attr) if !attr.is_empty() => { + let mut pending_mark = PendingMark { + start: index, + end, + attributes: FxHashMap::default(), + }; + for (key, value) in attr { + pending_mark + .attributes + .insert(key.deref().into(), value.clone()); + } + marks.push(pending_mark); + } + _ => {} + } + index = end; + } + } + } + + let mut len = match &self.inner { + MaybeDetached::Detached(_) => self.len_event(), + MaybeDetached::Attached(a) => { + a.with_state(|state| state.as_richtext_state_mut().unwrap().len(PosType::Event)) + } + }; + for pending_mark in marks { + if pending_mark.start >= len { + self.insert_with_txn( + txn, + len, + &"\n".repeat(pending_mark.start - len + 1), + PosType::Event, + )?; + len = pending_mark.start; + } + + for (key, value) in pending_mark.attributes { + self.mark_with_txn( + txn, + pending_mark.start, + pending_mark.end, + key.deref(), + value, + PosType::Event, + )?; + } + } + + Ok(()) + } + + pub fn update(&self, text: &str, options: UpdateOptions) -> Result<(), UpdateTimeoutError> { + let old_str = self.to_string(); + let new = text.chars().map(|x| x as u32).collect::<Vec<u32>>(); + let old = old_str.chars().map(|x| x as u32).collect::<Vec<u32>>(); + diff( + &mut OperateProxy::new(text_update::DiffHook::new(self, &new)), + options, + &old, + &new, + )?; + Ok(()) + } + + pub fn update_by_line( + &self, + text: &str, + options: UpdateOptions, + ) -> Result<(), UpdateTimeoutError> { + let hook = text_update::DiffHookForLine::new(self, text); + let old_lines = hook.get_old_arr().to_vec(); + let new_lines = hook.get_new_arr().to_vec(); + diff( + &mut OperateProxy::new(hook), + options, + &old_lines, + &new_lines, + ) + } + + #[allow(clippy::inherent_to_string)] + pub fn to_string(&self) -> String { + match &self.inner { + MaybeDetached::Detached(t) => t.lock().value.to_string(), + MaybeDetached::Attached(a) => a.get_value().into_string().unwrap().unwrap(), + } + } + + /// Get the deep value of the text with its container id, as a + /// `{ cid, value }` map where `value` is the text content. + pub fn get_deep_value_with_id(&self) -> LoroResult<LoroValue> { + let inner = self.inner.try_attached_state()?; + Ok(inner.with_doc_state(|state| { + state.get_container_deep_value_with_id(inner.container_idx, None) + })) + } + + pub fn get_cursor(&self, event_index: usize, side: Side) -> Option<Cursor> { + self.get_cursor_internal(event_index, side, true) + } + + /// Get the stable position representation for the target pos + pub(crate) fn get_cursor_internal( + &self, + index: usize, + side: Side, + get_by_event_index: bool, + ) -> Option<Cursor> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => { + let (id, len, origin_pos) = a.with_state(|s| { + let s = s.as_richtext_state_mut().unwrap(); + ( + s.get_stable_position(index, get_by_event_index), + if get_by_event_index { + s.len_event() + } else { + s.len_unicode() + }, + if get_by_event_index { + s.event_index_to_unicode_index(index) + } else { + index + }, + ) + }); + + if len == 0 { + return Some(Cursor { + id: None, + container: self.id(), + side: if side == Side::Middle { + Side::Left + } else { + side + }, + origin_pos: 0, + }); + } + + if len <= index { + return Some(Cursor { + id: None, + container: self.id(), + side: Side::Right, + origin_pos: len, + }); + } + + let id = id?; + Some(Cursor { + id: Some(id), + container: self.id(), + side, + origin_pos, + }) + } + } + } + + pub(crate) fn convert_entity_index_to_event_index(&self, entity_index: usize) -> usize { + match &self.inner { + MaybeDetached::Detached(s) => s.lock().value.entity_index_to_event_index(entity_index), + MaybeDetached::Attached(a) => { + let mut pos = 0; + a.with_state(|s| { + let s = s.as_richtext_state_mut().unwrap(); + pos = s.entity_index_to_event_index(entity_index); + }); + pos + } + } + } + + pub fn get_delta(&self) -> Vec<TextDelta> { + match &self.inner { + MaybeDetached::Detached(s) => { + let mut delta = Vec::new(); + for span in s.lock().value.iter() { + if span.text.as_str().is_empty() { + continue; + } + + let next_attr = span.attributes.to_option_map(); + match delta.last_mut() { + Some(TextDelta::Insert { insert, attributes }) + if &next_attr == attributes => + { + insert.push_str(span.text.as_str()); + continue; + } + _ => {} + } + + delta.push(TextDelta::Insert { + insert: span.text.as_str().to_string(), + attributes: next_attr, + }) + } + delta + } + MaybeDetached::Attached(_a) => self + .with_state(|state| { + let state = state.as_richtext_state_mut().unwrap(); + Ok(state.get_delta()) + }) + .unwrap(), + } + } + + pub fn is_deleted(&self) -> bool { + match &self.inner { + MaybeDetached::Detached(_) => false, + MaybeDetached::Attached(a) => a.is_deleted(), + } + } + + pub fn push_str(&self, s: &str) -> LoroResult<()> { + self.insert_utf8(self.len_utf8(), s) + } + + pub fn clear(&self) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(mutex) => { + let mut t = mutex.lock(); + let len = t.value.len_unicode(); + let ranges = t.value.get_text_entity_ranges(0, len, PosType::Unicode)?; + for range in ranges.iter().rev() { + t.value + .drain_by_entity_index(range.entity_start, range.entity_len(), None); + } + Ok(()) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| { + let len = a.with_state(|s| s.as_richtext_state_mut().unwrap().len_unicode()); + self.delete_with_txn_inline(txn, 0, len, PosType::Unicode) + }), + } + } + + /// Convert a position `index` from one coordinate system to another. + /// + /// Supported `PosType` conversions: `Event`, `Unicode`, `Utf16`, and `Bytes`. + /// Returns `None` if the index is out of bounds or the conversion is unsupported. + pub fn convert_pos(&self, index: usize, from: PosType, to: PosType) -> Option<usize> { + if from == to { + return Some(index); + } + + if matches!(from, PosType::Entity) || matches!(to, PosType::Entity) { + return None; + } + + // Normalize to event + unicode indices for the given position. + let (event_index, unicode_index) = match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + if index > t.value.len(from) { + return None; + } + let event_index = if from == PosType::Event { + index + } else { + t.value.index_to_event_index(index, from) + }; + let unicode_index = if from == PosType::Unicode { + index + } else { + t.value.event_index_to_unicode_index(event_index) + }; + (event_index, unicode_index) + } + MaybeDetached::Attached(a) if a.has_decoded_state() => { + let res: Option<(usize, usize)> = a.with_state(|state| { + let state = state.as_richtext_state_mut().unwrap(); + if index > state.len(from) { + return None; + } + + let event_index = if from == PosType::Event { + index + } else { + state.index_to_event_index(index, from) + }; + let unicode_index = if from == PosType::Unicode { + index + } else { + state.event_index_to_unicode_index(event_index) + }; + Some((event_index, unicode_index)) + }); + + res? + } + MaybeDetached::Attached(a) => { + let value = a.get_value(); + let s = value.as_string().unwrap(); + let unicode_index = text_pos_to_unicode(s, index, from)?; + let event_index = unicode_to_text_pos(s, unicode_index, PosType::Event)?; + (event_index, unicode_index) + } + }; + + let result = match to { + PosType::Unicode => Some(unicode_index), + PosType::Event => Some(event_index), + PosType::Bytes | PosType::Utf16 => { + // Map the event-index position onto the target coordinate via the + // rope's prefix caches. This is O(log n); materializing the prefix + // string would be O(n) and makes repeated edits O(n^2). + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + if event_index > t.value.len_event() { + return None; + } + Some(t.value.event_index_to_index(event_index, to)) + } + MaybeDetached::Attached(a) if a.has_decoded_state() => a.with_state(|state| { + let state = state.as_richtext_state_mut().unwrap(); + if event_index > state.len_event() { + return None; + } + Some(state.event_index_to_index(event_index, to)) + }), + MaybeDetached::Attached(a) => { + let value = a.get_value(); + let s = value.as_string().unwrap(); + unicode_to_text_pos(s, unicode_index, to) + } + } + } + PosType::Entity => None, + }; + result + } +} + +fn event_len(s: &str) -> usize { + if cfg!(feature = "wasm") { + count_utf16_len(s.as_bytes()) + } else { + s.chars().count() + } +} + +fn text_len(s: &str, pos_type: PosType) -> Option<usize> { + Some(match pos_type { + PosType::Bytes => s.len(), + PosType::Unicode => s.chars().count(), + PosType::Utf16 => count_utf16_len(s.as_bytes()), + PosType::Event => event_len(s), + PosType::Entity => return None, + }) +} + +fn text_pos_to_unicode(s: &str, index: usize, pos_type: PosType) -> Option<usize> { + match pos_type { + PosType::Unicode => (index <= s.chars().count()).then_some(index), + PosType::Bytes => { + if index > s.len() { + None + } else { + Some( + s.char_indices() + .take_while(|(pos, c)| *pos + c.len_utf8() <= index) + .count(), + ) + } + } + PosType::Utf16 => utf16_to_unicode_pos(s, index), + PosType::Event if cfg!(feature = "wasm") => utf16_to_unicode_pos(s, index), + PosType::Event => (index <= s.chars().count()).then_some(index), + PosType::Entity => None, + } +} + +fn unicode_to_text_pos(s: &str, index: usize, pos_type: PosType) -> Option<usize> { + match pos_type { + PosType::Unicode => (index <= s.chars().count()).then_some(index), + PosType::Bytes => unicode_to_byte_pos(s, index), + PosType::Utf16 => unicode_to_utf16_pos(s, index), + PosType::Event if cfg!(feature = "wasm") => unicode_to_utf16_pos(s, index), + PosType::Event => (index <= s.chars().count()).then_some(index), + PosType::Entity => None, + } +} + +fn unicode_to_byte_pos(s: &str, index: usize) -> Option<usize> { + if index == 0 { + return Some(0); + } + + let mut unicode_pos = 0; + for (byte_pos, _) in s.char_indices() { + if unicode_pos == index { + return Some(byte_pos); + } + unicode_pos += 1; + } + + (unicode_pos == index).then_some(s.len()) +} + +fn unicode_to_utf16_pos(s: &str, index: usize) -> Option<usize> { + let mut unicode_pos = 0; + let mut utf16_pos = 0; + if index == 0 { + return Some(0); + } + + for c in s.chars() { + unicode_pos += 1; + utf16_pos += c.len_utf16(); + if unicode_pos == index { + return Some(utf16_pos); + } + } + + (unicode_pos == index).then_some(utf16_pos) +} + +fn utf16_to_unicode_pos(s: &str, index: usize) -> Option<usize> { + let mut unicode_pos = 0; + let mut utf16_pos = 0; + if index == 0 { + return Some(0); + } + + for c in s.chars() { + let next_utf16_pos = utf16_pos + c.len_utf16(); + if index < next_utf16_pos { + return Some(unicode_pos); + } + if index == next_utf16_pos { + return Some(unicode_pos + 1); + } + utf16_pos = next_utf16_pos; + unicode_pos += 1; + } + + (index == utf16_pos).then_some(unicode_pos) +} + +fn text_boundary_error(pos: usize, pos_type: PosType) -> LoroError { + match pos_type { + PosType::Bytes => LoroError::UTF8InUnicodeCodePoint { pos }, + PosType::Utf16 => LoroError::UTF16InUnicodeCodePoint { pos }, + PosType::Event if cfg!(feature = "wasm") => LoroError::UTF16InUnicodeCodePoint { pos }, + _ => LoroError::OutOfBound { + pos, + len: 0, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }, + } +} + +fn text_char_at(s: &str, pos: usize, pos_type: PosType) -> LoroResult<char> { + let len = text_len(s, pos_type).unwrap_or(0); + if pos >= len { + return Err(LoroError::OutOfBound { + pos, + len, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }); + } + + let unicode_pos = + text_pos_to_unicode(s, pos, pos_type).ok_or_else(|| text_boundary_error(pos, pos_type))?; + s.chars().nth(unicode_pos).ok_or(LoroError::OutOfBound { + pos, + len, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }) +} + +fn text_slice(s: &str, start: usize, end: usize, pos_type: PosType) -> LoroResult<String> { + if end < start { + return Err(LoroError::EndIndexLessThanStartIndex { start, end }); + } + if start == end { + return Ok(String::new()); + } + + let len = text_len(s, pos_type).unwrap_or(0); + if end > len { + return Err(LoroError::OutOfBound { + pos: end, + len, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + }); + } + + let start = text_pos_to_unicode(s, start, pos_type) + .ok_or_else(|| text_boundary_error(start, pos_type))?; + let end = + text_pos_to_unicode(s, end, pos_type).ok_or_else(|| text_boundary_error(end, pos_type))?; + let start = unicode_to_byte_pos(s, start).expect("unicode index must map to a byte boundary"); + let end = unicode_to_byte_pos(s, end).expect("unicode index must map to a byte boundary"); + Ok(s[start..end].to_string()) +} + +impl ListHandler { + /// Create a new container that is detached from the document. + /// The edits on a detached container will not be persisted. + /// To attach the container to the document, please insert it into an attached container. + pub fn new_detached() -> Self { + Self { + inner: MaybeDetached::new_detached(Vec::new()), + } + } + + pub fn insert(&self, pos: usize, v: impl Into<LoroValue>) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(l) => { + let mut list = l.lock(); + let len = list.value.len(); + if pos > len { + return Err(LoroError::OutOfBound { + pos, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len, + }); + } + let value = v.into(); + ensure_no_regular_container_value(&value)?; + list.value.insert(pos, ValueOrHandler::Value(value)); + Ok(()) + } + MaybeDetached::Attached(a) => { + a.with_txn(|txn| self.insert_with_txn(txn, pos, v.into())) + } + } + } + + pub fn insert_with_txn( + &self, + txn: &mut Transaction, + pos: usize, + v: LoroValue, + ) -> LoroResult<()> { + if pos > self.len() { + return Err(LoroError::OutOfBound { + pos, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: self.len(), + }); + } + + let inner = self.inner.try_attached_state()?; + ensure_no_regular_container_value(&v)?; + + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Insert { + slice: ListSlice::RawData(Cow::Owned(vec![v.clone()])), + pos, + }), + EventHint::InsertList { len: 1, pos }, + &inner.doc, + ) + } + + pub fn push(&self, v: impl Into<LoroValue>) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(l) => { + let mut list = l.lock(); + let value = v.into(); + ensure_no_regular_container_value(&value)?; + list.value.push(ValueOrHandler::Value(value)); + Ok(()) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| self.push_with_txn(txn, v.into())), + } + } + + pub fn push_with_txn(&self, txn: &mut Transaction, v: LoroValue) -> LoroResult<()> { + let pos = self.len(); + self.insert_with_txn(txn, pos, v) + } + + pub fn pop(&self) -> LoroResult<Option<LoroValue>> { + match &self.inner { + MaybeDetached::Detached(l) => { + let mut list = l.lock(); + Ok(list.value.pop().map(|v| v.to_value())) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| self.pop_with_txn(txn)), + } + } + + pub fn pop_with_txn(&self, txn: &mut Transaction) -> LoroResult<Option<LoroValue>> { + let len = self.len(); + if len == 0 { + return Ok(None); + } + + let v = self.get(len - 1); + self.delete_with_txn(txn, len - 1, 1)?; + Ok(v) + } + + pub fn insert_container<H: HandlerTrait>(&self, pos: usize, child: H) -> LoroResult<H> { + match &self.inner { + MaybeDetached::Detached(l) => { + let mut list = l.lock(); + if pos > list.value.len() { + return Err(LoroError::OutOfBound { + pos, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: list.value.len(), + }); + } + list.value + .insert(pos, ValueOrHandler::Handler(child.to_handler())); + Ok(child) + } + MaybeDetached::Attached(a) => { + a.with_txn(|txn| self.insert_container_with_txn(txn, pos, child)) + } + } + } + + pub fn push_container<H: HandlerTrait>(&self, child: H) -> LoroResult<H> { + self.insert_container(self.len(), child) + } + + pub fn insert_container_with_txn<H: HandlerTrait>( + &self, + txn: &mut Transaction, + pos: usize, + child: H, + ) -> LoroResult<H> { + if pos > self.len() { + return Err(LoroError::OutOfBound { + pos, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: self.len(), + }); + } + + let inner = self.inner.try_attached_state()?; + ensure_not_attached_to_other_doc(&child, &inner.doc)?; + let id = txn.next_id(); + let container_id = ContainerID::new_normal(id, child.kind()); + let v = LoroValue::Container(container_id.clone()); + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Insert { + slice: ListSlice::RawData(Cow::Owned(vec![v.clone()])), + pos, + }), + EventHint::InsertList { len: 1, pos }, + &inner.doc, + )?; + let ans = child.attach(txn, inner, container_id)?; + Ok(ans) + } + + pub fn delete(&self, pos: usize, len: usize) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(l) => { + let mut list = l.lock(); + let end = checked_range_end(pos, len, list.value.len(), || { + format!("Position: {}:{}", file!(), line!()).into_boxed_str() + })?; + list.value.drain(pos..end); + Ok(()) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| self.delete_with_txn(txn, pos, len)), + } + } + + pub fn delete_with_txn(&self, txn: &mut Transaction, pos: usize, len: usize) -> LoroResult<()> { + if len == 0 { + return Ok(()); + } + + let list_len = self.len(); + let end = checked_range_end(pos, len, list_len, || { + format!("Position: {}:{}", file!(), line!()).into_boxed_str() + })?; + + let inner = self.inner.try_attached_state()?; + let ids: Vec<_> = inner.with_state(|state| { + let list = state.as_list_state().unwrap(); + (pos..end).map(|i| list.get_id_at(i).unwrap()).collect() + }); + + for id in ids.into_iter() { + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::List(ListOp::Delete(DeleteSpanWithId::new( + id.id(), + pos as isize, + 1, + ))), + EventHint::DeleteList(DeleteSpan::new(pos as isize, 1)), + &inner.doc, + )?; + } + + Ok(()) + } + + pub fn get_child_handler(&self, index: usize) -> LoroResult<Handler> { + match &self.inner { + MaybeDetached::Detached(l) => { + let list = l.lock(); + let value = list.value.get(index).ok_or(LoroError::OutOfBound { + pos: index, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: list.value.len(), + })?; + match value { + ValueOrHandler::Handler(h) => Ok(h.clone()), + _ => Err(LoroError::ArgErr( + format!( + "Expected container at index {}, but found {:?}", + index, value + ) + .into_boxed_str(), + )), + } + } + MaybeDetached::Attached(_) => { + let Some(value) = self.get_(index) else { + return Err(LoroError::OutOfBound { + pos: index, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: self.len(), + }); + }; + match value { + ValueOrHandler::Handler(handler) => Ok(handler), + ValueOrHandler::Value(value) => Err(LoroError::ArgErr( + format!( + "Expected container at index {}, but found {:?}", + index, value + ) + .into_boxed_str(), + )), + } + } + } + } + + pub fn len(&self) -> usize { + match &self.inner { + MaybeDetached::Detached(l) => l.lock().value.len(), + MaybeDetached::Attached(a) => { + a.with_doc_state(|state| state.get_list_len(a.container_idx)) + } + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub fn get_deep_value_with_id(&self) -> LoroResult<LoroValue> { + let inner = self.inner.try_attached_state()?; + Ok(inner.with_doc_state(|state| { + state.get_container_deep_value_with_id(inner.container_idx, None) + })) + } + + /// Get the deep value of the elements in the range `[start, end)`. + /// + /// Child containers in the range are recursively resolved to `{ cid, value }` + /// nodes. Out-of-range bounds are clamped to the list length; an empty or + /// inverted range returns an empty list. + pub fn get_slice_deep_value_with_id(&self, start: usize, end: usize) -> LoroResult<LoroValue> { + let inner = self.inner.try_attached_state()?; + Ok(inner.with_doc_state(|state| { + state.get_list_range_deep_value(inner.container_idx, start, end, true) + })) + } + + /// Get the deep value of the elements in the range `[start, end)`. + /// + /// Child containers in the range are recursively resolved to their deep value. + /// Out-of-range bounds are clamped to the list length; an empty or inverted + /// range returns an empty list. + pub fn get_slice_deep_value(&self, start: usize, end: usize) -> LoroResult<LoroValue> { + let inner = self.inner.try_attached_state()?; + Ok(inner.with_doc_state(|state| { + state.get_list_range_deep_value(inner.container_idx, start, end, false) + })) + } + + pub fn get(&self, index: usize) -> Option<LoroValue> { + match &self.inner { + MaybeDetached::Detached(l) => l.lock().value.get(index).map(|x| x.to_value()), + MaybeDetached::Attached(a) => { + a.with_doc_state(|state| state.get_list_value_at(a.container_idx, index)) + } + } + } + + /// Get value at given index, if it's a container, return a handler to the container + pub fn get_(&self, index: usize) -> Option<ValueOrHandler> { + match &self.inner { + MaybeDetached::Detached(l) => { + let l = l.lock(); + l.value.get(index).cloned() + } + MaybeDetached::Attached(inner) => { + let value = inner + .with_doc_state(|state| state.get_list_value_at(inner.container_idx, index)); + value.map(|value| value_to_value_or_handler(inner, value)) + } + } + } + + pub fn for_each<I>(&self, mut f: I) + where + I: FnMut(ValueOrHandler), + { + match &self.inner { + MaybeDetached::Detached(l) => { + let l = l.lock(); + for v in l.value.iter() { + f(v.clone()) + } + } + MaybeDetached::Attached(inner) => { + let temp = inner.with_doc_state(|state| { + state + .get_list_values(inner.container_idx) + .into_iter() + .map(|value| value_to_value_or_handler(inner, value)) + .collect::<Vec<_>>() + }); + for v in temp.into_iter() { + f(v); + } + } + } + } + + pub fn get_cursor(&self, pos: usize, side: Side) -> Option<Cursor> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => { + let (id, len) = a.with_state(|s| { + let l = s.as_list_state().unwrap(); + (l.get_id_at(pos), l.len()) + }); + + if len == 0 { + return Some(Cursor { + id: None, + container: self.id(), + side: if side == Side::Middle { + Side::Left + } else { + side + }, + origin_pos: 0, + }); + } + + if len <= pos { + return Some(Cursor { + id: None, + container: self.id(), + side: Side::Right, + origin_pos: len, + }); + } + + let id = id?; + Some(Cursor { + id: Some(id.id()), + container: self.id(), + side, + origin_pos: pos, + }) + } + } + } + + fn apply_delta( + &self, + delta: loro_delta::DeltaRope< + loro_delta::array_vec::ArrayVec<ValueOrHandler, 8>, + crate::event::ListDeltaMeta, + >, + on_container_remap: &mut dyn FnMut(ContainerID, ContainerID), + ) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(_) => unimplemented!(), + MaybeDetached::Attached(_) => { + let mut index = 0; + for item in delta.iter() { + match item { + loro_delta::DeltaItem::Retain { len, .. } => { + index += len; + } + loro_delta::DeltaItem::Replace { value, delete, .. } => { + if *delete > 0 { + self.delete(index, *delete)?; + } + + for v in value.iter() { + match v { + ValueOrHandler::Value(LoroValue::Container(old_id)) => { + let new_h = self.insert_container( + index, + Handler::new_unattached(old_id.container_type())?, + )?; + let new_id = new_h.id(); + on_container_remap(old_id.clone(), new_id); + } + ValueOrHandler::Handler(h) => { + let old_id = h.id(); + let new_h = self.insert_container( + index, + Handler::new_unattached(old_id.container_type())?, + )?; + let new_id = new_h.id(); + on_container_remap(old_id, new_id); + } + ValueOrHandler::Value(v) => { + self.insert(index, v.clone())?; + } + } + + index += 1; + } + } + } + } + } + } + + Ok(()) + } + + pub fn is_deleted(&self) -> bool { + match &self.inner { + MaybeDetached::Detached(_) => false, + MaybeDetached::Attached(a) => a.is_deleted(), + } + } + + pub fn clear(&self) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(l) => { + let mut l = l.lock(); + l.value.clear(); + Ok(()) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| self.clear_with_txn(txn)), + } + } + + pub fn clear_with_txn(&self, txn: &mut Transaction) -> LoroResult<()> { + self.delete_with_txn(txn, 0, self.len()) + } + + pub fn get_id_at(&self, pos: usize) -> Option<ID> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => a.with_state(|state| { + state + .as_list_state() + .unwrap() + .get_id_at(pos) + .map(|x| x.id()) + }), + } + } +} + +impl MovableListHandler { + pub fn insert(&self, pos: usize, v: impl Into<LoroValue>) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(d) => { + let mut d = d.lock(); + if pos > d.value.len() { + return Err(LoroError::OutOfBound { + pos, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: d.value.len(), + }); + } + let value = v.into(); + ensure_no_regular_container_value(&value)?; + d.value.insert(pos, ValueOrHandler::Value(value)); + Ok(()) + } + MaybeDetached::Attached(a) => { + a.with_txn(|txn| self.insert_with_txn(txn, pos, v.into())) + } + } + } + + #[instrument(skip_all)] + pub fn insert_with_txn( + &self, + txn: &mut Transaction, + pos: usize, + v: LoroValue, + ) -> LoroResult<()> { + if pos > self.len() { + return Err(LoroError::OutOfBound { + pos, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: self.len(), + }); + } + + ensure_no_regular_container_value(&v)?; + + let op_index = self.with_state(|state| { + let list = state.as_movable_list_state().unwrap(); + Ok(list + .convert_index(pos, IndexType::ForUser, IndexType::ForOp) + .unwrap()) + })?; + + let inner = self.inner.try_attached_state()?; + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Insert { + slice: ListSlice::RawData(Cow::Owned(vec![v.clone()])), + pos: op_index, + }), + EventHint::InsertList { len: 1, pos }, + &inner.doc, + ) + } + + #[inline] + pub fn mov(&self, from: usize, to: usize) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(d) => { + let mut d = d.lock(); + if from >= d.value.len() { + return Err(LoroError::OutOfBound { + pos: from, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: d.value.len(), + }); + } + if to >= d.value.len() { + return Err(LoroError::OutOfBound { + pos: to, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: d.value.len(), + }); + } + let v = d.value.remove(from); + d.value.insert(to, v); + Ok(()) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| self.move_with_txn(txn, from, to)), + } + } + + /// Move element from `from` to `to`. After this op, elem will be at pos `to`. + #[instrument(skip_all)] + pub fn move_with_txn(&self, txn: &mut Transaction, from: usize, to: usize) -> LoroResult<()> { + if from == to { + return Ok(()); + } + + if from >= self.len() { + return Err(LoroError::OutOfBound { + pos: from, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: self.len(), + }); + } + + if to >= self.len() { + return Err(LoroError::OutOfBound { + pos: to, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: self.len(), + }); + } + + let (op_from, op_to, elem_id, value) = self.with_state(|state| { + let list = state.as_movable_list_state().unwrap(); + let (elem_id, elem) = list + .get_elem_at_given_pos(from, IndexType::ForUser) + .unwrap(); + Ok(( + list.convert_index(from, IndexType::ForUser, IndexType::ForOp) + .unwrap(), + list.convert_index(to, IndexType::ForUser, IndexType::ForOp) + .unwrap(), + elem_id, + elem.value().clone(), + )) + })?; + + let inner = self.inner.try_attached_state()?; + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Move { + from: op_from as u32, + to: op_to as u32, + elem_id: elem_id.to_id(), + }), + EventHint::Move { + value, + from: from as u32, + to: to as u32, + }, + &inner.doc, + ) + } + + pub fn push(&self, v: LoroValue) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(d) => { + let mut d = d.lock(); + d.value.push(v.into()); + Ok(()) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| self.push_with_txn(txn, v)), + } + } + + pub fn push_with_txn(&self, txn: &mut Transaction, v: LoroValue) -> LoroResult<()> { + let pos = self.len(); + self.insert_with_txn(txn, pos, v) + } + + pub fn pop_(&self) -> LoroResult<Option<ValueOrHandler>> { + match &self.inner { + MaybeDetached::Detached(d) => { + let mut d = d.lock(); + Ok(d.value.pop()) + } + MaybeDetached::Attached(a) => { + if self.is_empty() { + return Ok(None); + } + let last = self.len() - 1; + let ans = self.get_(last); + a.with_txn(|txn| self.pop_with_txn(txn))?; + Ok(ans) + } + } + } + + pub fn pop(&self) -> LoroResult<Option<LoroValue>> { + match &self.inner { + MaybeDetached::Detached(a) => { + let mut a = a.lock(); + Ok(a.value.pop().map(|x| x.to_value())) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| self.pop_with_txn(txn)), + } + } + + pub fn pop_with_txn(&self, txn: &mut Transaction) -> LoroResult<Option<LoroValue>> { + let len = self.len(); + if len == 0 { + return Ok(None); + } + + let v = self.get(len - 1); + self.delete_with_txn(txn, len - 1, 1)?; + Ok(v) + } + + pub fn insert_container<H: HandlerTrait>(&self, pos: usize, child: H) -> LoroResult<H> { + match &self.inner { + MaybeDetached::Detached(d) => { + let mut d = d.lock(); + if pos > d.value.len() { + return Err(LoroError::OutOfBound { + pos, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: d.value.len(), + }); + } + d.value + .insert(pos, ValueOrHandler::Handler(child.to_handler())); + Ok(child) + } + MaybeDetached::Attached(a) => { + a.with_txn(|txn| self.insert_container_with_txn(txn, pos, child)) + } + } + } + + pub fn push_container<H: HandlerTrait>(&self, child: H) -> LoroResult<H> { + self.insert_container(self.len(), child) + } + + pub fn insert_container_with_txn<H: HandlerTrait>( + &self, + txn: &mut Transaction, + pos: usize, + child: H, + ) -> LoroResult<H> { + if pos > self.len() { + return Err(LoroError::OutOfBound { + pos, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: self.len(), + }); + } + + let op_index = self.with_state(|state| { + let list = state.as_movable_list_state().unwrap(); + Ok(list + .convert_index(pos, IndexType::ForUser, IndexType::ForOp) + .unwrap()) + })?; + + let inner = self.inner.try_attached_state()?; + ensure_not_attached_to_other_doc(&child, &inner.doc)?; + let id = txn.next_id(); + let container_id = ContainerID::new_normal(id, child.kind()); + let v = LoroValue::Container(container_id.clone()); + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Insert { + slice: ListSlice::RawData(Cow::Owned(vec![v.clone()])), + pos: op_index, + }), + EventHint::InsertList { len: 1, pos }, + &inner.doc, + )?; + child.attach(txn, inner, container_id) + } + + pub fn set(&self, index: usize, value: impl Into<LoroValue>) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(d) => { + let mut d = d.lock(); + if index >= d.value.len() { + return Err(LoroError::OutOfBound { + pos: index, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: d.value.len(), + }); + } + let value = value.into(); + ensure_no_regular_container_value(&value)?; + d.value[index] = ValueOrHandler::Value(value); + Ok(()) + } + MaybeDetached::Attached(a) => { + a.with_txn(|txn| self.set_with_txn(txn, index, value.into())) + } + } + } + + pub fn set_with_txn( + &self, + txn: &mut Transaction, + index: usize, + value: LoroValue, + ) -> LoroResult<()> { + if index >= self.len() { + return Err(LoroError::OutOfBound { + pos: index, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: self.len(), + }); + } + + let inner = self.inner.try_attached_state()?; + let Some(elem_id) = self.with_state(|state| { + let list = state.as_movable_list_state().unwrap(); + Ok(list.get_elem_id_at(index, IndexType::ForUser)) + })? + else { + unreachable!() + }; + ensure_no_regular_container_value(&value)?; + + let op = crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Set { + elem_id: elem_id.to_id(), + value: value.clone(), + }); + + let hint = EventHint::SetList { index, value }; + txn.apply_local_op(inner.container_idx, op, hint, &inner.doc) + } + + pub fn set_container<H: HandlerTrait>(&self, pos: usize, child: H) -> LoroResult<H> { + match &self.inner { + MaybeDetached::Detached(d) => { + let mut d = d.lock(); + if pos >= d.value.len() { + return Err(LoroError::OutOfBound { + pos, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: d.value.len(), + }); + } + d.value[pos] = ValueOrHandler::Handler(child.to_handler()); + Ok(child) + } + MaybeDetached::Attached(a) => { + a.with_txn(|txn| self.set_container_with_txn(txn, pos, child)) + } + } + } + + pub fn set_container_with_txn<H: HandlerTrait>( + &self, + txn: &mut Transaction, + pos: usize, + child: H, + ) -> LoroResult<H> { + let inner = self.inner.try_attached_state()?; + ensure_not_attached_to_other_doc(&child, &inner.doc)?; + let id = txn.next_id(); + let container_id = ContainerID::new_normal(id, child.kind()); + let v = LoroValue::Container(container_id.clone()); + let Some(elem_id) = self.with_state(|state| { + let list = state.as_movable_list_state().unwrap(); + Ok(list.get_elem_id_at(pos, IndexType::ForUser)) + })? + else { + let len = self.len(); + if pos >= len { + return Err(LoroError::OutOfBound { + pos, + len, + info: "".into(), + }); + } else { + unreachable!() + } + }; + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::List(crate::container::list::list_op::ListOp::Set { + elem_id: elem_id.to_id(), + value: v.clone(), + }), + EventHint::SetList { + index: pos, + value: v, + }, + &inner.doc, + )?; + + child.attach(txn, inner, container_id) + } + + pub fn delete(&self, pos: usize, len: usize) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(d) => { + let mut d = d.lock(); + let end = checked_range_end(pos, len, d.value.len(), || { + format!("Position: {}:{}", file!(), line!()).into_boxed_str() + })?; + d.value.drain(pos..end); + Ok(()) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| self.delete_with_txn(txn, pos, len)), + } + } + + #[instrument(skip_all)] + pub fn delete_with_txn(&self, txn: &mut Transaction, pos: usize, len: usize) -> LoroResult<()> { + if len == 0 { + return Ok(()); + } + + let list_len = self.len(); + let end = checked_range_end(pos, len, list_len, || { + format!("Position: {}:{}", file!(), line!()).into_boxed_str() + })?; + + let (ids, new_poses) = self.with_state(|state| { + let list = state.as_movable_list_state().unwrap(); + let ids: Vec<_> = (pos..end) + .map(|i| list.get_list_id_at(i, IndexType::ForUser).unwrap()) + .collect(); + let poses: Vec<_> = (pos..end) + // need to -i because we delete the previous ones + .map(|user_index| { + let op_index = list + .convert_index(user_index, IndexType::ForUser, IndexType::ForOp) + .unwrap(); + assert!(op_index >= user_index); + op_index - (user_index - pos) + }) + .collect(); + Ok((ids, poses)) + })?; + + loro_common::info!(?pos, ?len, ?ids, ?new_poses, "delete_with_txn"); + let user_pos = pos; + let inner = self.inner.try_attached_state()?; + for (id, op_pos) in ids.into_iter().zip(new_poses.into_iter()) { + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::List(ListOp::Delete(DeleteSpanWithId::new( + id, + op_pos as isize, + 1, + ))), + EventHint::DeleteList(DeleteSpan::new(user_pos as isize, 1)), + &inner.doc, + )?; + } + + Ok(()) + } + + pub fn get_child_handler(&self, index: usize) -> LoroResult<Handler> { + match &self.inner { + MaybeDetached::Detached(l) => { + let list = l.lock(); + let value = list.value.get(index).ok_or(LoroError::OutOfBound { + pos: index, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: list.value.len(), + })?; + match value { + ValueOrHandler::Handler(h) => Ok(h.clone()), + _ => Err(LoroError::ArgErr( + format!( + "Expected container at index {}, but found {:?}", + index, value + ) + .into_boxed_str(), + )), + } + } + MaybeDetached::Attached(_) => { + let Some(value) = self.get_(index) else { + return Err(LoroError::OutOfBound { + pos: index, + info: format!("Position: {}:{}", file!(), line!()).into_boxed_str(), + len: self.len(), + }); + }; + match value { + ValueOrHandler::Handler(handler) => Ok(handler), + ValueOrHandler::Value(value) => Err(LoroError::ArgErr( + format!( + "Expected container at index {}, but found {:?}", + index, value + ) + .into_boxed_str(), + )), + } + } + } + } + + pub fn len(&self) -> usize { + match &self.inner { + MaybeDetached::Detached(d) => { + let d = d.lock(); + d.value.len() + } + MaybeDetached::Attached(a) => { + a.with_doc_state(|state| state.get_list_len(a.container_idx)) + } + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub fn get_deep_value_with_id(&self) -> LoroResult<LoroValue> { + let inner = self.inner.try_attached_state()?; + Ok(inner.with_doc_state(|state| { + state.get_container_deep_value_with_id(inner.container_idx, None) + })) + } + + /// Get the deep value of the elements in the range `[start, end)`. + /// + /// Child containers in the range are recursively resolved to `{ cid, value }` + /// nodes. Out-of-range bounds are clamped to the list length; an empty or + /// inverted range returns an empty list. + pub fn get_slice_deep_value_with_id(&self, start: usize, end: usize) -> LoroResult<LoroValue> { + let inner = self.inner.try_attached_state()?; + Ok(inner.with_doc_state(|state| { + state.get_list_range_deep_value(inner.container_idx, start, end, true) + })) + } + + /// Get the deep value of the elements in the range `[start, end)`. + /// + /// Child containers in the range are recursively resolved to their deep value. + /// Out-of-range bounds are clamped to the list length; an empty or inverted + /// range returns an empty list. + pub fn get_slice_deep_value(&self, start: usize, end: usize) -> LoroResult<LoroValue> { + let inner = self.inner.try_attached_state()?; + Ok(inner.with_doc_state(|state| { + state.get_list_range_deep_value(inner.container_idx, start, end, false) + })) + } + + pub fn get(&self, index: usize) -> Option<LoroValue> { + match &self.inner { + MaybeDetached::Detached(d) => { + let d = d.lock(); + d.value.get(index).map(|v| v.to_value()) + } + MaybeDetached::Attached(a) => { + a.with_doc_state(|state| state.get_list_value_at(a.container_idx, index)) + } + } + } + + /// Get value at given index, if it's a container, return a handler to the container + pub fn get_(&self, index: usize) -> Option<ValueOrHandler> { + match &self.inner { + MaybeDetached::Detached(d) => { + let d = d.lock(); + d.value.get(index).cloned() + } + MaybeDetached::Attached(m) => { + let value = + m.with_doc_state(|state| state.get_list_value_at(m.container_idx, index)); + value.map(|value| value_to_value_or_handler(m, value)) + } + } + } + + pub fn for_each<I>(&self, mut f: I) + where + I: FnMut(ValueOrHandler), + { + match &self.inner { + MaybeDetached::Detached(d) => { + let d = d.lock(); + for v in d.value.iter() { + f(v.clone()); + } + } + MaybeDetached::Attached(m) => { + let temp = m.with_doc_state(|state| { + state + .get_list_values(m.container_idx) + .into_iter() + .map(|value| value_to_value_or_handler(m, value)) + .collect::<Vec<_>>() + }); + + for v in temp.into_iter() { + f(v); + } + } + } + } + + pub fn log_internal_state(&self) -> String { + match &self.inner { + MaybeDetached::Detached(d) => { + let d = d.lock(); + format!("{:#?}", &d.value) + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_movable_list_state().unwrap(); + format!("{a:#?}") + }), + } + } + + pub fn new_detached() -> MovableListHandler { + MovableListHandler { + inner: MaybeDetached::new_detached(Default::default()), + } + } + + pub fn get_cursor(&self, pos: usize, side: Side) -> Option<Cursor> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(inner) => { + let (id, len) = inner.with_state(|s| { + let l = s.as_movable_list_state().unwrap(); + (l.get_list_item_id_at(pos), l.len()) + }); + + if len == 0 { + return Some(Cursor { + id: None, + container: self.id(), + side: if side == Side::Middle { + Side::Left + } else { + side + }, + origin_pos: 0, + }); + } + + if len <= pos { + return Some(Cursor { + id: None, + container: self.id(), + side: Side::Right, + origin_pos: len, + }); + } + + let id = id?; + Some(Cursor { + id: Some(id.id()), + container: self.id(), + side, + origin_pos: pos, + }) + } + } + } + + pub(crate) fn op_pos_to_user_pos(&self, new_pos: usize) -> usize { + match &self.inner { + MaybeDetached::Detached(_) => new_pos, + MaybeDetached::Attached(inner) => { + let mut pos = new_pos; + inner.with_state(|s| { + let l = s.as_movable_list_state().unwrap(); + pos = l + .convert_index(new_pos, IndexType::ForOp, IndexType::ForUser) + .unwrap_or(l.len()); + }); + pos + } + } + } + + pub fn is_deleted(&self) -> bool { + match &self.inner { + MaybeDetached::Detached(_) => false, + MaybeDetached::Attached(a) => a.is_deleted(), + } + } + + pub fn clear(&self) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(d) => { + let mut d = d.lock(); + d.value.clear(); + Ok(()) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| self.clear_with_txn(txn)), + } + } + + pub fn clear_with_txn(&self, txn: &mut Transaction) -> LoroResult<()> { + self.delete_with_txn(txn, 0, self.len()) + } + + pub fn get_creator_at(&self, pos: usize) -> Option<PeerID> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => { + a.with_state(|state| state.as_movable_list_state().unwrap().get_creator_at(pos)) + } + } + } + + pub fn get_last_mover_at(&self, pos: usize) -> Option<PeerID> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => a.with_state(|state| { + state + .as_movable_list_state() + .unwrap() + .get_last_mover_at(pos) + }), + } + } + + pub fn get_last_editor_at(&self, pos: usize) -> Option<PeerID> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => a.with_state(|state| { + state + .as_movable_list_state() + .unwrap() + .get_last_editor_at(pos) + }), + } + } +} + +impl MapHandler { + /// Create a new container that is detached from the document. + /// The edits on a detached container will not be persisted. + /// To attach the container to the document, please insert it into an attached container. + pub fn new_detached() -> Self { + Self { + inner: MaybeDetached::new_detached(Default::default()), + } + } + + pub fn insert(&self, key: &str, value: impl Into<LoroValue>) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(m) => { + let mut m = m.lock(); + let value = value.into(); + ensure_no_regular_container_value(&value)?; + m.value.insert(key.into(), ValueOrHandler::Value(value)); + Ok(()) + } + MaybeDetached::Attached(a) => { + a.with_txn(|txn| self.insert_with_txn(txn, key, value.into())) + } + } + } + + /// This method will insert the value even if the same value is already in the given entry. + fn insert_without_skipping(&self, key: &str, value: impl Into<LoroValue>) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(m) => { + let mut m = m.lock(); + let value = value.into(); + ensure_no_regular_container_value(&value)?; + m.value.insert(key.into(), ValueOrHandler::Value(value)); + Ok(()) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| { + let this = &self; + let value = value.into(); + ensure_no_regular_container_value(&value)?; + + let inner = this.inner.try_attached_state()?; + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::Map(crate::container::map::MapSet { + key: key.into(), + value: Some(value.clone()), + }), + EventHint::Map { + key: key.into(), + value: Some(value.clone()), + }, + &inner.doc, + ) + }), + } + } + + pub fn insert_with_txn( + &self, + txn: &mut Transaction, + key: &str, + value: LoroValue, + ) -> LoroResult<()> { + ensure_no_regular_container_value(&value)?; + + if self.get(key).map(|x| x == value).unwrap_or(false) { + // skip if the value is already set + return Ok(()); + } + + let inner = self.inner.try_attached_state()?; + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::Map(crate::container::map::MapSet { + key: key.into(), + value: Some(value.clone()), + }), + EventHint::Map { + key: key.into(), + value: Some(value.clone()), + }, + &inner.doc, + ) + } + + pub fn insert_container<T: HandlerTrait>(&self, key: &str, handler: T) -> LoroResult<T> { + match &self.inner { + MaybeDetached::Detached(m) => { + let mut m = m.lock(); + let to_insert = handler.to_handler(); + m.value + .insert(key.into(), ValueOrHandler::Handler(to_insert.clone())); + Ok(handler) + } + MaybeDetached::Attached(a) => { + a.with_txn(|txn| self.insert_container_with_txn(txn, key, handler)) + } + } + } + + pub fn insert_container_with_txn<H: HandlerTrait>( + &self, + txn: &mut Transaction, + key: &str, + child: H, + ) -> LoroResult<H> { + let inner = self.inner.try_attached_state()?; + ensure_not_attached_to_other_doc(&child, &inner.doc)?; + let id = txn.next_id(); + let container_id = ContainerID::new_normal(id, child.kind()); + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::Map(crate::container::map::MapSet { + key: key.into(), + value: Some(LoroValue::Container(container_id.clone())), + }), + EventHint::Map { + key: key.into(), + value: Some(LoroValue::Container(container_id.clone())), + }, + &inner.doc, + )?; + + child.attach(txn, inner, container_id) + } + + pub fn delete(&self, key: &str) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(m) => { + let mut m = m.lock(); + m.value.remove(key); + Ok(()) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| self.delete_with_txn(txn, key)), + } + } + + pub fn delete_with_txn(&self, txn: &mut Transaction, key: &str) -> LoroResult<()> { + let inner = self.inner.try_attached_state()?; + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::Map(crate::container::map::MapSet { + key: key.into(), + value: None, + }), + EventHint::Map { + key: key.into(), + value: None, + }, + &inner.doc, + ) + } + + pub fn for_each<I>(&self, mut f: I) + where + I: FnMut(&str, ValueOrHandler), + { + match &self.inner { + MaybeDetached::Detached(m) => { + let m = m.lock(); + for (k, v) in m.value.iter() { + f(k, v.clone()); + } + } + MaybeDetached::Attached(inner) => { + let temp = inner.with_doc_state(|state| { + state + .get_map_entries(inner.container_idx) + .into_iter() + .map(|(key, value)| { + let translated = loro_common::translate_mergeable_marker_value( + &inner.id, + key.as_ref(), + value, + ); + ( + key.to_string(), + value_to_value_or_handler(inner, translated), + ) + }) + .collect::<Vec<_>>() + }); + + for (k, v) in temp.into_iter() { + f(&k, v.clone()); + } + } + } + } + + pub fn get_child_handler(&self, key: &str) -> LoroResult<Handler> { + match &self.inner { + MaybeDetached::Detached(m) => { + let m = m.lock(); + let value = m.value.get(key).unwrap(); + match value { + ValueOrHandler::Value(v) => Err(LoroError::ArgErr( + format!("Expected Handler but found {:?}", v).into_boxed_str(), + )), + ValueOrHandler::Handler(h) => Ok(h.clone()), + } + } + MaybeDetached::Attached(_) => { + let Some(value) = self.get_(key) else { + return Err(LoroError::ArgErr( + format!("Key {key} does not exist").into_boxed_str(), + )); + }; + match value { + ValueOrHandler::Handler(handler) => Ok(handler), + ValueOrHandler::Value(value) => Err(LoroError::ArgErr( + format!("Expected Handler but found {:?}", value).into_boxed_str(), + )), + } + } + } + } + + pub fn get_deep_value_with_id(&self) -> LoroResult<LoroValue> { + match &self.inner { + MaybeDetached::Detached(_) => Err(LoroError::MisuseDetachedContainer { + method: "get_deep_value_with_id", + }), + MaybeDetached::Attached(inner) => Ok(inner.with_doc_state(|state| { + state.get_container_deep_value_with_id(inner.container_idx, None) + })), + } + } + + pub fn get(&self, key: &str) -> Option<LoroValue> { + match &self.inner { + MaybeDetached::Detached(m) => { + let m = m.lock(); + m.value.get(key).map(|v| v.to_value()) + } + MaybeDetached::Attached(inner) => { + let value = inner + .with_doc_state(|state| state.get_map_value_by_key(inner.container_idx, key))?; + Some(loro_common::translate_mergeable_marker_value( + &inner.id, key, value, + )) + } + } + } + + /// Get the value at given key, if value is a container, return a handler to the container + pub fn get_(&self, key: &str) -> Option<ValueOrHandler> { + match &self.inner { + MaybeDetached::Detached(m) => { + let m = m.lock(); + m.value.get(key).cloned() + } + MaybeDetached::Attached(inner) => { + let value = inner + .with_doc_state(|state| state.get_map_value_by_key(inner.container_idx, key))?; + let value = loro_common::translate_mergeable_marker_value(&inner.id, key, value); + Some(value_to_value_or_handler(inner, value)) + } + } + } + + /// Get or create a regular child container at `key`. + /// + /// This legacy method creates regular op-id child containers when the key is empty or `null`. + /// It is not mergeable: concurrent first creation at the same map key can fork child state and + /// leave one branch hidden by map conflict resolution. Prefer `ensure_mergeable_*` for lazy + /// map-key child creation. + #[deprecated( + note = "use ensure_mergeable_map/list/movable_list/text/tree/counter for lazy map-key child creation; this method creates regular op-id children" + )] + pub fn get_or_create_container<C: HandlerTrait>(&self, key: &str, child: C) -> LoroResult<C> { + if let Some(ans) = self.get_(key) { + if let ValueOrHandler::Handler(h) = ans { + let kind = h.kind(); + return C::from_handler(h).ok_or_else(move || { + LoroError::ArgErr( + format!("Expected value type {} but found {:?}", child.kind(), kind) + .into_boxed_str(), + ) + }); + } else if let ValueOrHandler::Value(LoroValue::Null) = ans { + // do nothing + } else { + return Err(LoroError::ArgErr( + format!("Expected value type {} but found {:?}", child.kind(), ans) + .into_boxed_str(), + )); + } + } + + self.insert_container(key, child) + } + + /// Shared implementation for all `ensure_mergeable_*` methods. + /// + /// Computes a deterministic [`ContainerID::Root`] in the mergeable namespace from + /// `(parent.id, key, child.kind())` and constructs the handler from it. Two peers calling this + /// with the same `(parent, key, kind)` receive handlers with identical container ids, which is + /// what makes the child container mergeable on concurrent first-write. + /// + /// # Errors + /// + /// Returns [`LoroError::MisuseDetachedContainer`] when called on a detached handler. The + /// deterministic cid is computed from the parent's cid, which a detached parent does not have + /// yet; falling back to a non-deterministic regular child would silently drop the mergeable + /// guarantee at attach time. Detached callers must attach the parent first. + /// + /// Returns [`LoroError::ArgErr`] if the parent slot already holds a non-mergeable value, or if + /// `C::from_handler` rejects the handler built from the deterministic cid (unreachable by + /// construction; guards against future drift between `from_handler` and `kind`). + fn ensure_mergeable_container<C: HandlerTrait>(&self, key: &str, child: C) -> LoroResult<C> { + let MaybeDetached::Attached(parent) = &self.inner else { + return Err(LoroError::MisuseDetachedContainer { + method: "ensure_mergeable_container", + }); + }; + + // Compare against the raw marker bytes (skipping `MapHandler::get`'s user-facing + // marker → Container translation) so the non-mergeable-occupant guard sees the real + // slot value and the same-kind idempotent-skip can match. + let existing_raw = + parent.with_doc_state(|state| state.get_map_value_by_key(parent.container_idx, key)); + + // A non-mergeable occupant (scalar, arbitrary binary, regular child container) would be + // silently clobbered by the marker write, so reject rather than overwrite under a + // `get_`-named API. Only the exact binary marker for this `(parent, key, kind)` is + // accepted as an existing mergeable occupant. + if let Some(existing) = &existing_raw { + if !matches!(existing, LoroValue::Null) + && loro_common::parse_mergeable_marker(&parent.id, key, existing).is_none() + { + return Err(LoroError::ArgErr( + format!( + "Cannot create a mergeable {} at key {key:?}: the key already holds a non-mergeable value", + child.kind() + ) + .into_boxed_str(), + )); + } + } + + let cid = ContainerID::new_mergeable(&parent.id, key, child.kind()); + let marker = loro_common::mergeable_marker(&parent.id, key, child.kind()); + + // Idempotent-skip on same marker: `MapHandler::get` translates markers to Container, so + // `insert_with_txn`'s equality check can't see this collision — do it directly. + // A different-kind marker is a deliberate kind change; let the insert through. + if existing_raw.as_ref() != Some(&marker) { + self.insert(key, marker)?; + } + + C::from_handler(create_handler(parent, cid.clone())).ok_or_else(|| { + LoroError::ArgErr( + format!( + "Expected value type {} but found {}", + child.kind(), + cid.container_type() + ) + .into_boxed_str(), + ) + }) + } + + #[cfg(feature = "counter")] + /// Ensure a mergeable Counter child exists under `key` and return its handler. + /// + /// Returns [`LoroError::MisuseDetachedContainer`] when called on a detached map. + /// Returns [`LoroError::ArgErr`] if the parent slot already holds a non-mergeable value. + /// Repeated same-kind calls are idempotent; different mergeable kinds deliberately rewrite + /// the active marker while preserving each mergeable child's deterministic state. + pub fn ensure_mergeable_counter(&self, key: &str) -> LoroResult<counter::CounterHandler> { + self.ensure_mergeable_container(key, counter::CounterHandler::new_detached()) + } + + /// Ensure a mergeable Map child exists under `key` and return its handler. + /// + /// Returns [`LoroError::MisuseDetachedContainer`] when called on a detached map. + /// Returns [`LoroError::ArgErr`] if the parent slot already holds a non-mergeable value. + /// Repeated same-kind calls are idempotent; different mergeable kinds deliberately rewrite + /// the active marker while preserving each mergeable child's deterministic state. + /// + /// Prefer to avoid very deep mergeable-map chains: mergeable cids encode their flattened + /// logical path, so cid size still grows with depth and rides through every op/snapshot + /// reference to it. See [`MERGEABLE_NAMESPACE_PREFIX`](loro_common::MERGEABLE_NAMESPACE_PREFIX). + pub fn ensure_mergeable_map(&self, key: &str) -> LoroResult<MapHandler> { + self.ensure_mergeable_container(key, MapHandler::new_detached()) + } + + /// Ensure a mergeable List child exists under `key` and return its handler. + /// + /// Returns [`LoroError::MisuseDetachedContainer`] when called on a detached map. + /// Returns [`LoroError::ArgErr`] if the parent slot already holds a non-mergeable value. + /// Repeated same-kind calls are idempotent; different mergeable kinds deliberately rewrite + /// the active marker while preserving each mergeable child's deterministic state. + pub fn ensure_mergeable_list(&self, key: &str) -> LoroResult<ListHandler> { + self.ensure_mergeable_container(key, ListHandler::new_detached()) + } + + /// Ensure a mergeable MovableList child exists under `key` and return its handler. + /// + /// Returns [`LoroError::MisuseDetachedContainer`] when called on a detached map. + /// Returns [`LoroError::ArgErr`] if the parent slot already holds a non-mergeable value. + /// Repeated same-kind calls are idempotent; different mergeable kinds deliberately rewrite + /// the active marker while preserving each mergeable child's deterministic state. + pub fn ensure_mergeable_movable_list(&self, key: &str) -> LoroResult<MovableListHandler> { + self.ensure_mergeable_container(key, MovableListHandler::new_detached()) + } + + /// Ensure a mergeable Text child exists under `key` and return its handler. + /// + /// Returns [`LoroError::MisuseDetachedContainer`] when called on a detached map. + /// Returns [`LoroError::ArgErr`] if the parent slot already holds a non-mergeable value. + /// Repeated same-kind calls are idempotent; different mergeable kinds deliberately rewrite + /// the active marker while preserving each mergeable child's deterministic state. + pub fn ensure_mergeable_text(&self, key: &str) -> LoroResult<TextHandler> { + self.ensure_mergeable_container(key, TextHandler::new_detached()) + } + + /// Ensure a mergeable Tree child exists under `key` and return its handler. + /// + /// Returns [`LoroError::MisuseDetachedContainer`] when called on a detached map. + /// Returns [`LoroError::ArgErr`] if the parent slot already holds a non-mergeable value. + /// Repeated same-kind calls are idempotent; different mergeable kinds deliberately rewrite + /// the active marker while preserving each mergeable child's deterministic state. + pub fn ensure_mergeable_tree(&self, key: &str) -> LoroResult<TreeHandler> { + self.ensure_mergeable_container(key, TreeHandler::new_detached()) + } + + pub fn contains_key(&self, key: &str) -> bool { + self.get(key).is_some() + } + + pub fn len(&self) -> usize { + match &self.inner { + MaybeDetached::Detached(m) => m.lock().value.len(), + MaybeDetached::Attached(a) => { + a.with_doc_state(|state| state.get_map_len(a.container_idx)) + } + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub fn is_deleted(&self) -> bool { + match &self.inner { + MaybeDetached::Detached(_) => false, + MaybeDetached::Attached(a) => a.is_deleted(), + } + } + + pub fn clear(&self) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(m) => { + let mut m = m.lock(); + m.value.clear(); + Ok(()) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| self.clear_with_txn(txn)), + } + } + + pub fn clear_with_txn(&self, txn: &mut Transaction) -> LoroResult<()> { + let keys: Vec<InternalString> = self.inner.try_attached_state()?.with_state(|state| { + state + .as_map_state() + .unwrap() + .iter() + .map(|(k, _)| k.clone()) + .collect() + }); + + for key in keys { + self.delete_with_txn(txn, &key)?; + } + + Ok(()) + } + + pub fn keys(&self) -> impl Iterator<Item = InternalString> + '_ { + let keys: Vec<InternalString> = match &self.inner { + MaybeDetached::Detached(m) => { + let m = m.lock(); + m.value.keys().map(|x| x.as_str().into()).collect() + } + MaybeDetached::Attached(a) => { + a.with_doc_state(|state| state.get_map_keys(a.container_idx)) + } + }; + + keys.into_iter() + } + + pub fn values(&self) -> impl Iterator<Item = ValueOrHandler> + '_ { + let values: Vec<ValueOrHandler> = match &self.inner { + MaybeDetached::Detached(m) => { + let m = m.lock(); + m.value.values().cloned().collect() + } + MaybeDetached::Attached(a) => a.with_doc_state(|state| { + // A mergeable child's marker lives in the parent map's value table; iterate + // entries (key + value) so the user-boundary translation can resolve each marker + // to the deterministic child cid before wrapping into a handler. + state + .get_map_entries(a.container_idx) + .into_iter() + .map(|(key, value)| { + let translated = loro_common::translate_mergeable_marker_value( + &a.id, + key.as_ref(), + value, + ); + value_to_value_or_handler(a, translated) + }) + .collect() + }), + }; + + values.into_iter() + } + + pub fn get_last_editor(&self, key: &str) -> Option<PeerID> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => a.with_state(|state| { + let m = state.as_map_state().unwrap(); + m.get_last_edit_peer(key) + }), + } + } +} + +fn with_txn<R>(doc: &LoroDoc, f: impl FnOnce(&mut Transaction) -> LoroResult<R>) -> LoroResult<R> { + let txn = &doc.txn; + let mut txn = txn.lock(); + loop { + if let Some(txn) = &mut *txn { + return f(txn); + } else if cfg!(target_arch = "wasm32") || !doc.can_edit() { + return Err(LoroError::AutoCommitNotStarted); + } else { + drop(txn); + #[cfg(loom)] + loom::thread::yield_now(); + doc.start_auto_commit(); + txn = doc.txn.lock(); + } + } +} + +#[cfg(feature = "counter")] +pub mod counter { + + use loro_common::LoroResult; + + use crate::{ + txn::{EventHint, Transaction}, + HandlerTrait, + }; + + use super::{create_handler, Handler, MaybeDetached}; + + #[derive(Clone)] + pub struct CounterHandler { + pub(super) inner: MaybeDetached<f64>, + } + + impl CounterHandler { + pub fn new_detached() -> Self { + Self { + inner: MaybeDetached::new_detached(0.), + } + } + + pub fn increment(&self, n: f64) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(d) => { + let d = &mut d.lock().value; + *d += n; + Ok(()) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| self.increment_with_txn(txn, n)), + } + } + + pub fn decrement(&self, n: f64) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(d) => { + let d = &mut d.lock().value; + *d -= n; + Ok(()) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| self.increment_with_txn(txn, -n)), + } + } + + fn increment_with_txn(&self, txn: &mut Transaction, n: f64) -> LoroResult<()> { + let inner = self.inner.try_attached_state()?; + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::Counter(n), + EventHint::Counter(n), + &inner.doc, + ) + } + + pub fn is_deleted(&self) -> bool { + match &self.inner { + MaybeDetached::Detached(_) => false, + MaybeDetached::Attached(a) => a.is_deleted(), + } + } + + pub fn clear(&self) -> LoroResult<()> { + self.decrement(self.get_value().into_double().unwrap()) + } + } + + impl std::fmt::Debug for CounterHandler { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.inner { + MaybeDetached::Detached(_) => write!(f, "CounterHandler Detached"), + MaybeDetached::Attached(a) => write!(f, "CounterHandler {}", a.id), + } + } + } + + impl HandlerTrait for CounterHandler { + fn is_attached(&self) -> bool { + matches!(&self.inner, MaybeDetached::Attached(..)) + } + + fn attached_handler(&self) -> Option<&crate::BasicHandler> { + self.inner.attached_handler() + } + + fn get_value(&self) -> loro_common::LoroValue { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.into() + } + MaybeDetached::Attached(a) => a.get_value(), + } + } + + fn get_deep_value(&self) -> loro_common::LoroValue { + self.get_value() + } + + fn kind(&self) -> loro_common::ContainerType { + loro_common::ContainerType::Counter + } + + fn to_handler(&self) -> super::Handler { + Handler::Counter(self.clone()) + } + + fn from_handler(h: super::Handler) -> Option<Self> { + match h { + Handler::Counter(x) => Some(x), + _ => None, + } + } + + fn attach( + &self, + txn: &mut crate::txn::Transaction, + parent: &crate::BasicHandler, + self_id: loro_common::ContainerID, + ) -> loro_common::LoroResult<Self> { + match &self.inner { + MaybeDetached::Detached(v) => { + let mut v = v.lock(); + let inner = create_handler(parent, self_id); + let c = inner.into_counter().unwrap(); + + c.increment_with_txn(txn, v.value)?; + + v.attached = c.attached_handler().cloned(); + Ok(c) + } + MaybeDetached::Attached(a) => { + let new_inner = create_handler(a, self_id); + let ans = new_inner.into_counter().unwrap(); + let delta = *self.get_value().as_double().unwrap(); + ans.increment_with_txn(txn, delta)?; + Ok(ans) + } + } + } + + fn get_attached(&self) -> Option<Self> { + match &self.inner { + MaybeDetached::Attached(a) => Some(Self { + inner: MaybeDetached::Attached(a.clone()), + }), + MaybeDetached::Detached(v) => v.lock().attached.clone().map(|x| Self { + inner: MaybeDetached::Attached(x), + }), + } + } + + fn doc(&self) -> Option<crate::LoroDoc> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => Some(a.doc()), + } + } + } +} + +#[cfg(test)] +mod test { + use std::borrow::Cow; + + use super::{ + Handler, HandlerTrait, ListHandler, MapHandler, MovableListHandler, TextDelta, TextHandler, + ValueOrHandler, + }; + use crate::container::list::list_op::ListOp; + use crate::cursor::PosType; + use crate::loro::ExportMode; + use crate::op::ListSlice; + use crate::state::TreeParentId; + use crate::txn::EventHint; + use crate::version::Frontiers; + use crate::LoroDoc; + use crate::{fx_map, ToJson}; + use loro_common::{ContainerID, ContainerType, LoroError, LoroValue, ID}; + use serde_json::json; + + fn recheck_fast_blob(mut bytes: Vec<u8>) -> Vec<u8> { + let checksum = xxhash_rust::xxh32::xxh32(&bytes[20..], u32::from_le_bytes(*b"LORO")); + bytes[16..20].copy_from_slice(&checksum.to_le_bytes()); + bytes + } + + fn replace_fast_snapshot_state_bytes(mut snapshot: Vec<u8>, state_bytes: &[u8]) -> Vec<u8> { + let mut body = &snapshot[22..]; + let oplog_len = u32::from_le_bytes(body[..4].try_into().unwrap()) as usize; + body = &body[4 + oplog_len..]; + let old_state_len = u32::from_le_bytes(body[..4].try_into().unwrap()) as usize; + let state_len_pos = 22 + 4 + oplog_len; + let state_start = state_len_pos + 4; + let state_end = state_start + old_state_len; + snapshot[state_len_pos..state_start] + .copy_from_slice(&(state_bytes.len() as u32).to_le_bytes()); + snapshot.splice(state_start..state_end, state_bytes.iter().copied()); + recheck_fast_blob(snapshot) + } + + fn insert_many_with_single_list_op( + txn: &mut crate::txn::Transaction, + list: &crate::handler::ListHandler, + pos: usize, + values: Vec<LoroValue>, + ) { + let len = values.len(); + let inner = list.inner.try_attached_state().unwrap(); + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::List(ListOp::Insert { + slice: ListSlice::RawData(Cow::Owned(values)), + pos, + }), + EventHint::InsertList { + len: len as u32, + pos, + }, + &inner.doc, + ) + .unwrap(); + } + + #[test] + fn richtext_handler() { + let loro = LoroDoc::new(); + loro.set_peer_id(1).unwrap(); + let loro2 = LoroDoc::new(); + loro2.set_peer_id(2).unwrap(); + + let mut txn = loro.txn().unwrap(); + let text = txn.get_text("hello"); + text.insert_with_txn(&mut txn, 0, "hello", PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + let exported = loro.export(ExportMode::all_updates()).unwrap(); + + loro2.import(&exported).unwrap(); + let mut txn = loro2.txn().unwrap(); + let text = txn.get_text("hello"); + assert_eq!(&**text.get_value().as_string().unwrap(), "hello"); + text.insert_with_txn(&mut txn, 5, " world", PosType::Unicode) + .unwrap(); + assert_eq!(&**text.get_value().as_string().unwrap(), "hello world"); + txn.commit().unwrap(); + + loro.import(&loro2.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + let txn = loro.txn().unwrap(); + let text = txn.get_text("hello"); + assert_eq!(&**text.get_value().as_string().unwrap(), "hello world"); + txn.commit().unwrap(); + + // test checkout + loro.checkout(&Frontiers::from_id(ID::new(2, 1))).unwrap(); + assert_eq!(&**text.get_value().as_string().unwrap(), "hello w"); + } + + #[test] + fn richtext_handler_concurrent() { + let loro = LoroDoc::new(); + let mut txn = loro.txn().unwrap(); + let handler = loro.get_text("richtext"); + handler + .insert_with_txn(&mut txn, 0, "hello", PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + for i in 0..100 { + let new_loro = LoroDoc::new(); + new_loro + .import(&loro.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + let mut txn = new_loro.txn().unwrap(); + let handler = new_loro.get_text("richtext"); + handler + .insert_with_txn(&mut txn, i % 5, &i.to_string(), PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + loro.import( + &new_loro + .export(ExportMode::updates(&loro.oplog_vv())) + .unwrap(), + ) + .unwrap(); + } + } + + #[test] + fn cross_doc_txn_is_rejected() { + // `insert_with_txn`/`delete_with_txn` are public API, so a transaction + // from one document can be fed to another document's handler. That must + // be rejected with `UnmatchedContext` rather than silently stamping the + // target doc's state/oplog with the wrong peer+counter. Regression test + // for the always-on (release included) context check in + // `Transaction::apply_local_op`. + let doc_a = LoroDoc::new(); + doc_a.set_peer_id(1).unwrap(); + let doc_b = LoroDoc::new(); + doc_b.set_peer_id(2).unwrap(); + + // Seed doc_b so it has real state we can prove stays untouched. + { + let mut txn_b = doc_b.txn().unwrap(); + doc_b + .get_text("text") + .insert_with_txn(&mut txn_b, 0, "ok", PosType::Unicode) + .unwrap(); + txn_b.commit().unwrap(); + } + let vv_before = doc_b.oplog_vv(); + + // Feed doc_a's transaction to doc_b's handler. + let mut txn_a = doc_a.txn().unwrap(); + let text_b = doc_b.get_text("text"); + let insert_err = text_b + .insert_with_txn(&mut txn_a, 0, "x", PosType::Unicode) + .unwrap_err(); + assert!(matches!(insert_err, LoroError::UnmatchedContext { .. })); + let delete_err = text_b + .delete_with_txn(&mut txn_a, 0, 1, PosType::Unicode) + .unwrap_err(); + assert!(matches!(delete_err, LoroError::UnmatchedContext { .. })); + txn_a.commit().unwrap(); + + // doc_b is unchanged: content and version vector identical. + assert_eq!(&**text_b.get_value().as_string().unwrap(), "ok"); + assert_eq!(doc_b.oplog_vv(), vv_before); + } + + #[test] + fn list_import_batch_stays_consistent_after_repeated_tail_splits() { + let doc_a = LoroDoc::new(); + doc_a.set_peer_id(1).unwrap(); + let mut txn = doc_a.txn().unwrap(); + let list_a = txn.get_list("list"); + insert_many_with_single_list_op( + &mut txn, + &list_a, + 0, + (0..300).map(|i| LoroValue::I64(i)).collect(), + ); + txn.commit().unwrap(); + + let doc_b = LoroDoc::new(); + doc_b.set_peer_id(2).unwrap(); + doc_b + .import(&doc_a.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + + let list_b = doc_b.get_list("list"); + let mut vv = doc_a.oplog_vv(); + let mut updates = Vec::new(); + for (i, pos) in [100, 201, 252, 278].into_iter().enumerate() { + list_b.insert(pos, 1000 + i as i64).unwrap(); + updates.push(doc_b.export(ExportMode::updates(&vv)).unwrap()); + vv = doc_b.oplog_vv(); + } + + doc_a.import_batch(&updates).unwrap(); + doc_a.check_state_diff_calc_consistency_slow(); + doc_b.check_state_diff_calc_consistency_slow(); + assert_eq!(doc_a.get_deep_value(), doc_b.get_deep_value()); + } + + #[test] + fn richtext_handler_mark() { + let loro = LoroDoc::new_auto_commit(); + let handler = loro.get_text("richtext"); + handler.insert(0, "hello world", PosType::Unicode).unwrap(); + handler + .mark(0, 5, "bold", true.into(), PosType::Event) + .unwrap(); + loro.commit_then_renew(); + + // assert has bold + let value = handler.get_richtext_value(); + assert_eq!(value[0]["insert"], "hello".into()); + let meta = value[0]["attributes"].as_map().unwrap(); + assert_eq!(meta.len(), 1); + meta.get("bold").unwrap(); + + let loro2 = LoroDoc::new_auto_commit(); + loro2 + .import(&loro.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + let handler2 = loro2.get_text("richtext"); + assert_eq!(&**handler2.get_value().as_string().unwrap(), "hello world"); + + // assert has bold + let value = handler2.get_richtext_value(); + assert_eq!(value[0]["insert"], "hello".into()); + let meta = value[0]["attributes"].as_map().unwrap(); + assert_eq!(meta.len(), 1); + meta.get("bold").unwrap(); + + // insert after bold should be bold + { + handler2.insert(5, " new", PosType::Unicode).unwrap(); + let value = handler2.get_richtext_value(); + assert_eq!( + value.to_json_value(), + serde_json::json!([ + {"insert": "hello new", "attributes": {"bold": true}}, + {"insert": " world"} + ]) + ); + } + } + + #[test] + fn richtext_snapshot() { + let loro = LoroDoc::new(); + let mut txn = loro.txn().unwrap(); + let handler = loro.get_text("richtext"); + handler + .insert_with_txn(&mut txn, 0, "hello world", PosType::Unicode) + .unwrap(); + handler + .mark_with_txn(&mut txn, 0, 5, "bold", true.into(), PosType::Event) + .unwrap(); + txn.commit().unwrap(); + + let loro2 = LoroDoc::new(); + loro2 + .import(&loro.export(ExportMode::snapshot()).unwrap()) + .unwrap(); + let handler2 = loro2.get_text("richtext"); + assert_eq!( + handler2.get_richtext_value().to_json_value(), + serde_json::json!([ + {"insert": "hello", "attributes": {"bold": true}}, + {"insert": " world"} + ]) + ); + } + + #[test] + fn text_snapshot_string_queries_do_not_decode_state() { + let loro = LoroDoc::new_auto_commit(); + let text = loro.get_text("text"); + text.insert(0, "a😀文", PosType::Unicode).unwrap(); + text.mark(1, 3, "bold", true.into(), PosType::Unicode) + .unwrap(); + + let restored = LoroDoc::new(); + restored + .import(&loro.export(ExportMode::snapshot()).unwrap()) + .unwrap(); + let text = restored.get_text("text"); + assert!(!text.attached_handler().unwrap().has_decoded_state()); + + assert_eq!(text.len_unicode(), 3); + assert_eq!(text.len_utf16(), 4); + assert_eq!(text.len_utf8(), "a😀文".len()); + assert_eq!(text.char_at(1, PosType::Unicode).unwrap(), '😀'); + assert_eq!(text.slice(1, 3, PosType::Unicode).unwrap(), "😀文"); + assert_eq!( + text.convert_pos(2, PosType::Unicode, PosType::Utf16), + Some(3) + ); + assert!(matches!( + text.delete_utf16(2, 1), + Err(LoroError::UTF16InUnicodeCodePoint { pos: 2 }) + )); + assert!(matches!( + text.delete_utf8(2, 1), + Err(LoroError::UTF8InUnicodeCodePoint { pos: 2 }) + )); + assert!(matches!( + text.slice_delta(2, 3, PosType::Utf16), + Err(LoroError::UTF16InUnicodeCodePoint { pos: 2 }) + )); + assert!(matches!( + text.slice_delta(2, 3, PosType::Bytes), + Err(LoroError::UTF8InUnicodeCodePoint { pos: 2 }) + )); + assert!(!text.attached_handler().unwrap().has_decoded_state()); + + assert_eq!(text.get_delta().len(), 2); + assert!(text.attached_handler().unwrap().has_decoded_state()); + } + + #[test] + fn text_lazy_event_queries_match_decoded_state() { + let loro = LoroDoc::new_auto_commit(); + let text = loro.get_text("text"); + text.insert(0, "ab😀cd", PosType::Unicode).unwrap(); + text.mark(1, 4, "bold", true.into(), PosType::Unicode) + .unwrap(); + text.mark(2, 3, "link", "x".into(), PosType::Unicode) + .unwrap(); + + let lazy_doc = LoroDoc::new(); + lazy_doc + .import(&loro.export(ExportMode::snapshot()).unwrap()) + .unwrap(); + let lazy_text = lazy_doc.get_text("text"); + + let decoded_doc = LoroDoc::new(); + decoded_doc + .import(&loro.export(ExportMode::snapshot()).unwrap()) + .unwrap(); + let decoded_text = decoded_doc.get_text("text"); + decoded_text.get_delta(); + + assert!(!lazy_text.attached_handler().unwrap().has_decoded_state()); + assert!(decoded_text.attached_handler().unwrap().has_decoded_state()); + + for pos_type in [ + PosType::Event, + PosType::Unicode, + PosType::Utf16, + PosType::Bytes, + ] { + assert_eq!(lazy_text.len(pos_type), decoded_text.len(pos_type)); + for pos in 0..=decoded_text.len(pos_type) { + assert_eq!( + lazy_text.convert_pos(pos, pos_type, PosType::Unicode), + decoded_text.convert_pos(pos, pos_type, PosType::Unicode), + "convert {pos_type:?} pos {pos} to unicode" + ); + assert_eq!( + lazy_text.convert_pos(pos, pos_type, PosType::Event), + decoded_text.convert_pos(pos, pos_type, PosType::Event), + "convert {pos_type:?} pos {pos} to event" + ); + if pos < decoded_text.len(pos_type) { + assert_eq!( + lazy_text.char_at(pos, pos_type), + decoded_text.char_at(pos, pos_type), + "char_at {pos_type:?} pos {pos}" + ); + } + for end in pos..=decoded_text.len(pos_type) { + assert_eq!( + lazy_text.slice(pos, end, pos_type), + decoded_text.slice(pos, end, pos_type), + "slice {pos_type:?} {pos}..{end}" + ); + } + } + } + } + + #[test] + fn deep_value_with_id_uses_lazy_values_for_snapshot_roots() { + let loro = LoroDoc::new_auto_commit(); + let text = loro.get_text("text"); + text.insert(0, "hello", PosType::Unicode).unwrap(); + let map = loro.get_map("map"); + map.insert("key", "value").unwrap(); + let list = loro.get_list("list"); + list.push("item").unwrap(); + + let restored = LoroDoc::new(); + restored + .import(&loro.export(ExportMode::snapshot()).unwrap()) + .unwrap(); + let text = restored.get_text("text"); + let map = restored.get_map("map"); + let list = restored.get_list("list"); + + let value = restored.get_deep_value_with_id(); + assert_eq!(value["text"]["value"], "hello".into()); + assert_eq!(value["map"]["value"]["key"], "value".into()); + assert_eq!(value["list"]["value"][0], "item".into()); + assert!(!text.attached_handler().unwrap().has_decoded_state()); + assert!(!map.attached_handler().unwrap().has_decoded_state()); + assert!(!list.attached_handler().unwrap().has_decoded_state()); + } + + #[test] + fn lazy_value_reads_do_not_write_stale_snapshot_after_mutation() { + let loro = LoroDoc::new_auto_commit(); + let map = loro.get_map("map"); + map.insert("key", "old").unwrap(); + let child = map + .insert_container("child", MapHandler::new_detached()) + .unwrap(); + child.insert("nested", "old").unwrap(); + let list = loro.get_list("list"); + list.push("old").unwrap(); + let child_list = list.push_container(ListHandler::new_detached()).unwrap(); + child_list.push("nested-old").unwrap(); + + let restored = LoroDoc::new(); + restored + .import(&loro.export(ExportMode::snapshot()).unwrap()) + .unwrap(); + let map = restored.get_map("map"); + let list = restored.get_list("list"); + + assert_eq!(map.get("key").unwrap(), "old".into()); + assert_eq!(list.get(0).unwrap(), "old".into()); + let child = match map.get_("child").unwrap() { + ValueOrHandler::Handler(handler) => handler.into_map().unwrap(), + ValueOrHandler::Value(value) => panic!("expected child map, got {value:?}"), + }; + let child_list = match list.get_(1).unwrap() { + ValueOrHandler::Handler(handler) => handler.into_list().unwrap(), + ValueOrHandler::Value(value) => panic!("expected child list, got {value:?}"), + }; + + map.insert("key", "new").unwrap(); + child.insert("nested", "new").unwrap(); + list.delete(0, 1).unwrap(); + list.insert(0, "new").unwrap(); + child_list.delete(0, 1).unwrap(); + child_list.insert(0, "nested-new").unwrap(); + restored.commit_then_renew(); + + let roundtrip = LoroDoc::new(); + roundtrip + .import(&restored.export(ExportMode::snapshot()).unwrap()) + .unwrap(); + assert_eq!( + roundtrip.get_deep_value().to_json_value(), + serde_json::json!({ + "map": { "key": "new", "child": { "nested": "new" } }, + "list": ["new", ["nested-new"]] + }) + ); + } + + #[test] + fn fast_snapshot_with_trailing_bytes_is_rejected_on_import() { + let loro = LoroDoc::new_auto_commit(); + let map = loro.get_map("map"); + map.insert("key", "value").unwrap(); + let mut snapshot = loro.export(ExportMode::snapshot()).unwrap(); + snapshot.push(0xff); + let corrupted = recheck_fast_blob(snapshot); + + let doc = LoroDoc::new(); + assert!(doc.import(&corrupted).is_err()); + } + + #[test] + fn fast_snapshot_with_trailing_bytes_is_rejected_by_meta_decoder() { + let loro = LoroDoc::new_auto_commit(); + let map = loro.get_map("map"); + map.insert("key", "value").unwrap(); + let mut snapshot = loro.export(ExportMode::snapshot()).unwrap(); + snapshot.push(0xff); + let corrupted = recheck_fast_blob(snapshot); + + assert!(LoroDoc::decode_import_blob_meta(&corrupted, true).is_err()); + } + + #[test] + fn fast_snapshot_empty_sstable_meta_is_rejected_on_import() { + let loro = LoroDoc::new_auto_commit(); + let map = loro.get_map("map"); + map.insert("key", "value").unwrap(); + let snapshot = loro.export(ExportMode::snapshot()).unwrap(); + + let mut malformed_state = Vec::new(); + malformed_state.extend_from_slice(b"LORO"); + malformed_state.push(0); + malformed_state.extend_from_slice(&0u32.to_le_bytes()); + let checksum = xxhash_rust::xxh32::xxh32(&[], u32::from_le_bytes(*b"LORO")); + malformed_state.extend_from_slice(&checksum.to_le_bytes()); + malformed_state.extend_from_slice(&5u32.to_le_bytes()); + let corrupted = replace_fast_snapshot_state_bytes(snapshot, &malformed_state); + + let doc = LoroDoc::new(); + assert!(doc.import(&corrupted).is_err()); + } + + #[test] + fn tree_meta() { + let loro = LoroDoc::new_auto_commit(); + loro.set_peer_id(1).unwrap(); + let tree = loro.get_tree("root"); + let id = tree.create(TreeParentId::Root).unwrap(); + let meta = tree.get_meta(id).unwrap(); + meta.insert("a", 123).unwrap(); + loro.commit_then_renew(); + let meta = tree.get_meta(id).unwrap(); + assert_eq!(meta.get("a").unwrap(), 123.into()); + assert_eq!( + json!([{"parent":null,"meta":{"a":123},"id":"0@1","index":0,"children":[],"fractional_index":"80"}]), + tree.get_deep_value().to_json_value() + ); + let bytes = loro.export(ExportMode::snapshot()).unwrap(); + let loro2 = LoroDoc::new(); + loro2.import(&bytes).unwrap(); + } + + #[test] + fn tree_meta_event() { + use std::sync::Arc; + let loro = LoroDoc::new_auto_commit(); + let tree = loro.get_tree("root"); + let text = loro.get_text("text"); + + let id = tree.create(TreeParentId::Root).unwrap(); + let meta = tree.get_meta(id).unwrap(); + meta.insert("a", 1).unwrap(); + text.insert(0, "abc", PosType::Unicode).unwrap(); + let _id2 = tree.create(TreeParentId::Root).unwrap(); + meta.insert("b", 2).unwrap(); + + let loro2 = LoroDoc::new_auto_commit(); + let _g = loro2.subscribe_root(Arc::new(|e| { + println!("{} {:?} ", e.event_meta.by, e.event_meta.diff) + })); + loro2 + .import(&loro.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + assert_eq!(loro.get_deep_value(), loro2.get_deep_value()); + } + + #[test] + fn richtext_apply_delta() { + let loro = LoroDoc::new_auto_commit(); + let text = loro.get_text("text"); + text.apply_delta(&[TextDelta::Insert { + insert: "Hello World!".into(), + attributes: None, + }]) + .unwrap(); + dbg!(text.get_richtext_value()); + text.apply_delta(&[ + TextDelta::Retain { + retain: 6, + attributes: Some(fx_map!("italic".into() => loro_common::LoroValue::Bool(true))), + }, + TextDelta::Insert { + insert: "New ".into(), + attributes: Some(fx_map!("bold".into() => loro_common::LoroValue::Bool(true))), + }, + ]) + .unwrap(); + dbg!(text.get_richtext_value()); + loro.commit_then_renew(); + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([ + {"insert": "Hello ", "attributes": {"italic": true}}, + {"insert": "New ", "attributes": {"bold": true}}, + {"insert": "World!"} + + ]) + ) + } + + #[test] + fn richtext_apply_delta_marks_without_growth() { + let loro = LoroDoc::new_auto_commit(); + let text = loro.get_text("text"); + text.insert(0, "abc", PosType::Unicode).unwrap(); + + text.apply_delta(&[TextDelta::Retain { + retain: 3, + attributes: Some(fx_map!("bold".into() => LoroValue::Bool(true))), + }]) + .unwrap(); + loro.commit_then_renew(); + + assert_eq!(text.to_string(), "abc"); + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([{"insert": "abc", "attributes": {"bold": true}}]) + ); + } + + #[test] + fn richtext_apply_delta_grows_for_mark_gap() { + let loro = LoroDoc::new_auto_commit(); + let text = loro.get_text("text"); + + text.apply_delta(&[TextDelta::Retain { + retain: 1, + attributes: Some(fx_map!("bold".into() => LoroValue::Bool(true))), + }]) + .unwrap(); + loro.commit_then_renew(); + + assert_eq!(text.to_string(), "\n"); + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([{"insert": "\n", "attributes": {"bold": true}}]) + ); + } + + #[test] + fn richtext_apply_delta_ignores_empty_inserts() { + let loro = LoroDoc::new_auto_commit(); + let text = loro.get_text("text"); + text.insert(0, "seed", PosType::Unicode).unwrap(); + + text.apply_delta(&[TextDelta::Insert { + insert: "".into(), + attributes: Some(fx_map!("bold".into() => LoroValue::Bool(true))), + }]) + .unwrap(); + loro.commit_then_renew(); + + assert_eq!(text.to_string(), "seed"); + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([{"insert": "seed"}]) + ); + } + + #[test] + fn handler_trait_dispatch_reports_attached_container_identity() { + let loro = LoroDoc::new_auto_commit(); + let handlers = [ + (loro.get_text("text").to_handler(), ContainerType::Text), + (loro.get_map("map").to_handler(), ContainerType::Map), + (loro.get_list("list").to_handler(), ContainerType::List), + ( + loro.get_movable_list("movable").to_handler(), + ContainerType::MovableList, + ), + (loro.get_tree("tree").to_handler(), ContainerType::Tree), + ]; + + for (handler, expected_type) in handlers { + assert!(handler.is_attached()); + assert!(handler.attached_handler().is_some()); + assert!(handler.doc().is_some()); + assert!(handler.get_attached().is_some()); + assert_eq!(handler.kind(), expected_type); + assert_eq!(handler.c_type(), expected_type); + assert_eq!(handler.id().container_type(), expected_type); + assert_eq!( + Handler::from_handler(handler.clone()).unwrap().c_type(), + expected_type + ); + + handler.get_value(); + handler.get_deep_value(); + handler.clear().unwrap(); + } + } + + #[test] + fn handler_trait_dispatch_reports_detached_container_identity() { + let handlers = [ + ( + Handler::new_unattached(ContainerType::Text).unwrap(), + ContainerType::Text, + ), + ( + Handler::new_unattached(ContainerType::Map).unwrap(), + ContainerType::Map, + ), + ( + Handler::new_unattached(ContainerType::List).unwrap(), + ContainerType::List, + ), + ( + Handler::new_unattached(ContainerType::MovableList).unwrap(), + ContainerType::MovableList, + ), + ( + Handler::new_unattached(ContainerType::Tree).unwrap(), + ContainerType::Tree, + ), + ]; + + for (handler, expected_type) in handlers { + assert!(!handler.is_attached()); + assert!(handler.attached_handler().is_none()); + assert!(handler.doc().is_none()); + assert!(handler.get_attached().is_none()); + assert_eq!(handler.kind(), expected_type); + assert_eq!(handler.c_type(), expected_type); + assert_eq!(handler.id().container_type(), expected_type); + assert_eq!(handler.idx().get_type(), expected_type); + assert_eq!( + Handler::from_handler(handler.clone()).unwrap().c_type(), + expected_type + ); + } + } + + #[test] + fn attaching_detached_handlers_sets_parent_and_attached_back_reference() { + let loro = LoroDoc::new_auto_commit(); + + let map = loro.get_map("map"); + let detached_text = TextHandler::new_detached(); + detached_text + .insert(0, "detached", PosType::Unicode) + .unwrap(); + let attached_text = map.insert_container("text", detached_text.clone()).unwrap(); + assert!(attached_text.is_attached()); + assert_eq!(attached_text.to_string(), "detached"); + assert_eq!(attached_text.parent().unwrap().c_type(), ContainerType::Map); + assert_eq!( + detached_text.get_attached().unwrap().id(), + attached_text.id() + ); + + let list = loro.get_list("list"); + let detached_map = MapHandler::new_detached(); + detached_map.insert("k", 1_i64).unwrap(); + let attached_map = list.insert_container(0, detached_map.clone()).unwrap(); + assert!(attached_map.is_attached()); + assert_eq!(attached_map.parent().unwrap().c_type(), ContainerType::List); + assert_eq!(detached_map.get_attached().unwrap().id(), attached_map.id()); + + let movable = loro.get_movable_list("movable"); + let detached_list = ListHandler::new_detached(); + detached_list.push("item").unwrap(); + let attached_list = movable.insert_container(0, detached_list.clone()).unwrap(); + assert!(attached_list.is_attached()); + assert_eq!( + attached_list.parent().unwrap().c_type(), + ContainerType::MovableList + ); + assert_eq!( + detached_list.get_attached().unwrap().id(), + attached_list.id() + ); + + let nested = attached_map + .insert_container("movable", MovableListHandler::new_detached()) + .unwrap(); + assert_eq!(nested.parent().unwrap().id(), attached_map.id()); + } + + #[test] + fn unknown_handler_reports_identity_without_materializing_value() { + let loro = LoroDoc::new_auto_commit(); + let id = ContainerID::Root { + name: "unknown".into(), + container_type: ContainerType::Unknown(7), + }; + let handler = Handler::new_attached(id.clone(), loro.clone()); + let unknown = handler.as_unknown().unwrap(); + + assert!(unknown.is_attached()); + assert_eq!(unknown.kind(), ContainerType::Unknown(7)); + assert_eq!(unknown.id(), id); + assert_eq!(unknown.to_handler().c_type(), ContainerType::Unknown(7)); + assert!(unknown.doc().is_some()); + assert!(!unknown.is_deleted()); + assert_eq!(format!("{unknown:?}"), "UnknownHandler"); + assert!(unknown.get_attached().is_some()); + assert!(super::UnknownHandler::from_handler(handler.clone()).is_some()); + + // This version cannot create or copy a container of an unknown type + assert!(matches!( + Handler::new_unattached(ContainerType::Unknown(7)), + Err(LoroError::ArgErr(_)) + )); + let map = loro.get_map("map"); + assert!(matches!( + map.insert_container("k", handler), + Err(LoroError::ArgErr(_)) + )); + assert!(map.is_empty()); + } + + #[test] + fn deep_value_with_id_cid_matches_container_id_string() { + let loro = LoroDoc::new_auto_commit(); + let map = loro.get_map("map"); + map.insert("key", "value").unwrap(); + let child = map + .insert_container("child", ListHandler::new_detached()) + .unwrap(); + child.push("item").unwrap(); + + let value = loro.get_deep_value_with_id(); + assert_eq!( + value["map"]["cid"].to_json_value(), + json!(map.id().to_string()) + ); + assert_eq!( + value["map"]["cid"].to_json_value(), + json!("cid:root-map:Map") + ); + let child_cid = value["map"]["value"]["child"]["cid"].to_json_value(); + assert_eq!(child_cid, json!(child.id().to_string())); + let child_cid = child_cid.as_str().unwrap(); + assert!(child_cid.starts_with("cid:"), "unexpected cid: {child_cid}"); + assert!(!child_cid.contains("idx:"), "unexpected cid: {child_cid}"); + + // The per-container handler API emits the same node shape + let map_value = map.get_deep_value_with_id().unwrap(); + assert_eq!( + map_value["cid"].to_json_value(), + json!(map.id().to_string()) + ); + assert_eq!( + map_value["value"]["child"]["cid"].to_json_value(), + json!(child.id().to_string()) + ); + assert_eq!( + map_value["value"]["child"]["value"][0].to_json_value(), + json!("item") + ); + } + + #[test] + fn text_and_tree_deep_value_with_id() { + let loro = LoroDoc::new_auto_commit(); + let text = loro.get_text("text"); + text.insert(0, "hello", PosType::Unicode).unwrap(); + let text_value = text.get_deep_value_with_id().unwrap(); + assert_eq!( + text_value.to_json_value(), + json!({"cid": text.id().to_string(), "value": "hello"}) + ); + + let tree = loro.get_tree("tree"); + let node = tree.create(TreeParentId::Root).unwrap(); + tree.get_meta(node).unwrap().insert("name", "root").unwrap(); + let tree_value = tree.get_deep_value_with_id().unwrap(); + assert_eq!( + tree_value["cid"].to_json_value(), + json!(tree.id().to_string()) + ); + assert_eq!( + tree_value["value"][0]["meta"]["name"].to_json_value(), + json!("root") + ); + + // Detached containers must error rather than panic + let detached_text = TextHandler::new_detached(); + assert!(matches!( + detached_text.get_deep_value_with_id(), + Err(LoroError::MisuseDetachedContainer { .. }) + )); + let detached_tree = crate::handler::TreeHandler::new_detached(); + assert!(matches!( + detached_tree.get_deep_value_with_id(), + Err(LoroError::MisuseDetachedContainer { .. }) + )); + } + + #[test] + fn list_slice_deep_value() { + let loro = LoroDoc::new_auto_commit(); + let list = loro.get_list("list"); + list.push("a").unwrap(); + list.push("b").unwrap(); + let child = list.push_container(MapHandler::new_detached()).unwrap(); + child.insert("k", "v").unwrap(); + list.push("d").unwrap(); + + // Full range with ids: containers become { cid, value } nodes + let all = list.get_slice_deep_value_with_id(0, 4).unwrap(); + assert_eq!(all[0].to_json_value(), json!("a")); + assert_eq!( + all[2].to_json_value(), + json!({"cid": child.id().to_string(), "value": {"k": "v"}}) + ); + + // Sub-range without ids: containers become their plain deep value + let mid = list.get_slice_deep_value(1, 3).unwrap(); + assert_eq!(mid.to_json_value(), json!(["b", {"k": "v"}])); + + // Bounds are clamped to the list length + let clamped = list.get_slice_deep_value_with_id(2, 100).unwrap(); + assert_eq!(clamped.to_json_value().as_array().unwrap().len(), 2); + let clamped_start = list.get_slice_deep_value_with_id(100, 200).unwrap(); + assert_eq!(clamped_start.to_json_value(), json!([])); + + // Empty and inverted ranges return an empty list + assert_eq!( + list.get_slice_deep_value(2, 2).unwrap().to_json_value(), + json!([]) + ); + assert_eq!( + list.get_slice_deep_value(3, 1).unwrap().to_json_value(), + json!([]) + ); + + // Detached lists must error rather than panic + let detached = ListHandler::new_detached(); + assert!(matches!( + detached.get_slice_deep_value_with_id(0, 1), + Err(LoroError::MisuseDetachedContainer { .. }) + )); + assert!(matches!( + detached.get_slice_deep_value(0, 1), + Err(LoroError::MisuseDetachedContainer { .. }) + )); + } + + #[test] + fn movable_list_slice_deep_value() { + let loro = LoroDoc::new_auto_commit(); + let list = loro.get_movable_list("list"); + list.push("a".into()).unwrap(); + let child = list.push_container(ListHandler::new_detached()).unwrap(); + child.push("x").unwrap(); + list.push("b".into()).unwrap(); + + let all = list.get_slice_deep_value_with_id(0, 3).unwrap(); + assert_eq!( + all[1].to_json_value(), + json!({"cid": child.id().to_string(), "value": ["x"]}) + ); + + let plain = list.get_slice_deep_value(0, 2).unwrap(); + assert_eq!(plain.to_json_value(), json!(["a", ["x"]])); + + // Whole-container deep value with id errors on detached containers + let attached = list.get_deep_value_with_id().unwrap(); + assert_eq!( + attached["cid"].to_json_value(), + json!(list.id().to_string()) + ); + let detached = MovableListHandler::new_detached(); + assert!(matches!( + detached.get_deep_value_with_id(), + Err(LoroError::MisuseDetachedContainer { .. }) + )); + assert!(matches!( + detached.get_slice_deep_value_with_id(0, 1), + Err(LoroError::MisuseDetachedContainer { .. }) + )); + assert!(matches!( + detached.get_slice_deep_value(0, 1), + Err(LoroError::MisuseDetachedContainer { .. }) + )); + } +} diff --git a/vendor/loro-internal/src/handler/full_state.rs b/vendor/loro-internal/src/handler/full_state.rs new file mode 100644 index 0000000..fc74a59 --- /dev/null +++ b/vendor/loro-internal/src/handler/full_state.rs @@ -0,0 +1,377 @@ +//! Applying a full-state diff to a re-activated mergeable child in `LoroDoc::apply_diff`. +//! +//! Events and `LoroDoc::diff` describe a container that becomes visible with its full state. +//! `apply_diff` recreates a regular container under a fresh id, so a full state is exactly +//! right for it. A mergeable child is re-activated at its deterministic cid, which may already +//! hold hidden state in the target doc (the same, different, or none). [`align_full_state`] +//! turns the full state into an edit of that hidden state, keeping the characters, elements, +//! entries and tree nodes the two share. See context/mergeable-containers.md. + +use super::{Handler, ValueOrHandler}; +use crate::{ + delta::{ResolvedMapDelta, ResolvedMapValue, TreeDiff, TreeDiffItem, TreeExternalDiff}, + event::{Diff, ListDeltaMeta, ListDiff, TextDiff, TextMeta}, + state::TreeParentId, + utils::{ + string_slice::StringSlice, + utf16::{count_unicode_chars, count_utf16_len}, + }, +}; +use fractional_index::FractionalIndex; +use loro_common::{ContainerID, InternalString, LoroValue, TreeID}; +use loro_delta::{array_vec::ArrayVec, DeltaItem, DeltaRope}; +use rustc_hash::{FxHashMap, FxHashSet}; + +/// Given `target`, a full-state diff for `handler`, and `current`, the handler's current state +/// as a full-state diff, returns the edit that turns `current` into `target`, or `None` if +/// there is nothing to do. Returns `target` unchanged if it is not a full-state diff. +/// +/// Has no side effects, so `LoroDoc::_apply_diff` can plan a whole batch before applying it. +/// Child containers that keep their id are added to `full_state_targets`: their own diffs in +/// the batch are full states as well. +pub(crate) fn align_full_state( + handler: &Handler, + target: &Diff, + current: Diff, + full_state_targets: &mut FxHashSet<ContainerID>, +) -> Option<Diff> { + match (target, current) { + (Diff::Map(target), Diff::Map(current)) => { + align_map(target, current, full_state_targets).map(Diff::Map) + } + #[cfg(feature = "counter")] + (Diff::Counter(target), Diff::Counter(current)) => { + let delta = target - current; + (matches!(handler, Handler::Counter(_)) && delta != 0.0).then_some(Diff::Counter(delta)) + } + (Diff::Text(target), Diff::Text(current)) => match align_text(target, ¤t) { + Some(edit) => (!edit.is_empty()).then_some(Diff::Text(edit)), + None => Some(Diff::Text(target.clone())), + }, + (Diff::List(target), Diff::List(current)) => { + let movable = matches!(handler, Handler::MovableList(_)); + match align_list(target, ¤t, movable, full_state_targets) { + Some(edit) => (!edit.is_empty()).then_some(Diff::List(edit)), + None => Some(Diff::List(target.clone())), + } + } + (Diff::Tree(target), Diff::Tree(current)) => { + match align_tree(target, ¤t, full_state_targets) { + Some(edit) => (!edit.diff.is_empty()).then_some(Diff::Tree(edit)), + None => Some(Diff::Tree(target.clone())), + } + } + (Diff::Unknown, _) => None, + (target, _) => Some(target.clone()), + } +} + +fn map_value(v: &ResolvedMapValue) -> Option<LoroValue> { + v.value.as_ref().map(ValueOrHandler::to_value) +} + +/// Per key, so entries (and the child containers they hold) that already match are kept. +fn align_map( + target: &ResolvedMapDelta, + current: ResolvedMapDelta, + full_state_targets: &mut FxHashSet<ContainerID>, +) -> Option<ResolvedMapDelta> { + let current: FxHashMap<InternalString, LoroValue> = current + .updated + .iter() + .filter_map(|(k, v)| Some((k.clone(), map_value(v)?))) + .collect(); + let mut updated = FxHashMap::default(); + let mut target_keys = FxHashSet::default(); + for (key, value) in target.updated.iter() { + let Some(target_value) = map_value(value) else { + continue; + }; + target_keys.insert(key.clone()); + if current.get(key) == Some(&target_value) { + if let LoroValue::Container(id) = target_value { + full_state_targets.insert(id); + } + } else { + updated.insert(key.clone(), value.clone()); + } + } + for key in current.keys() { + if !target_keys.contains(key) { + updated.insert(key.clone(), ResolvedMapValue::new_unset()); + } + } + (!updated.is_empty()).then_some(ResolvedMapDelta { updated }) +} + +/// Length of `s` in the units of text diffs (see `StringSlice::rle_len`). +fn text_len(s: &str) -> usize { + if cfg!(feature = "wasm") { + count_utf16_len(s.as_bytes()) + } else { + count_unicode_chars(s.as_bytes()) + } +} + +/// Style runs of a pure-insertion text diff, or `None` if it is not one. +fn text_runs(diff: &TextDiff) -> Option<Vec<(&str, &TextMeta)>> { + let mut ans = Vec::new(); + for item in diff.iter() { + let DeltaItem::Replace { + value, + attr, + delete: 0, + } = item + else { + return None; + }; + ans.push((value.as_str(), attr)); + } + Some(ans) +} + +/// The pieces of `runs` that cover the byte range `range` of their concatenated text. +fn slice_runs<'a>( + runs: &[(&'a str, &'a TextMeta)], + range: std::ops::Range<usize>, +) -> Vec<(&'a str, &'a TextMeta)> { + let mut ans = Vec::new(); + let mut offset = 0; + for &(text, attr) in runs { + let (start, end) = (offset, offset + text.len()); + offset = end; + let (from, to) = (range.start.max(start), range.end.min(end)); + if from < to { + ans.push((&text[from - start..to - start], attr)); + } + } + ans +} + +/// Lengths of the longest common prefix and of the longest common suffix of the rest. +fn common_ends<T: PartialEq>(a: &[T], b: &[T]) -> (usize, usize) { + common_ends_by(a, b, |x, y| x == y) +} + +fn common_ends_by<T>(a: &[T], b: &[T], eq: impl Fn(&T, &T) -> bool) -> (usize, usize) { + let prefix = a.iter().zip(b).take_while(|(x, y)| eq(x, y)).count(); + let suffix = a[prefix..] + .iter() + .rev() + .zip(b[prefix..].iter().rev()) + .take_while(|(x, y)| eq(x, y)) + .count(); + (prefix, suffix) +} + +/// The styles to mark on a kept char so that `current` becomes `target` (`null` unmarks). +fn style_change(current: &TextMeta, target: &TextMeta) -> TextMeta { + let mut change = TextMeta::default(); + for (key, value) in target.0.iter() { + if current.0.get(key) != Some(value) { + change.0.insert(key.clone(), value.clone()); + } + } + for key in current.0.keys() { + if !target.0.contains_key(key) { + change.0.insert(key.clone(), LoroValue::Null); + } + } + change +} + +/// Retains a kept text range given as the `current` and `target` runs over the same text, +/// re-marking the pieces whose styles differ. +fn push_restyled_retain( + edit: &mut TextDiff, + current: &[(&str, &TextMeta)], + target: &[(&str, &TextMeta)], +) { + let (mut ci, mut ti) = (0, 0); + let (mut c_off, mut t_off) = (0, 0); + while ci < current.len() && ti < target.len() { + let (c_text, c_attr) = current[ci]; + let (t_text, t_attr) = target[ti]; + let take = (c_text.len() - c_off).min(t_text.len() - t_off); + let piece = &c_text[c_off..c_off + take]; + let change = if c_attr == t_attr { + TextMeta::default() + } else { + style_change(c_attr, t_attr) + }; + edit.push_retain(text_len(piece), change); + c_off += take; + t_off += take; + if c_off == c_text.len() { + ci += 1; + c_off = 0; + } + if t_off == t_text.len() { + ti += 1; + t_off = 0; + } + } +} + +/// Keeps the text of the common prefix and suffix (compared by content; differing styles are +/// re-marked) and replaces the middle. Works on style runs, so its cost is a byte comparison +/// of the two texts plus the number of runs. +fn align_text(target: &TextDiff, current: &TextDiff) -> Option<TextDiff> { + let target = text_runs(target)?; + let current = text_runs(current)?; + let target_text: String = target.iter().map(|(s, _)| *s).collect(); + let current_text: String = current.iter().map(|(s, _)| *s).collect(); + let (t, c) = (target_text.as_bytes(), current_text.as_bytes()); + let mut prefix = t.iter().zip(c).take_while(|(x, y)| x == y).count(); + while !target_text.is_char_boundary(prefix) { + prefix -= 1; + } + let mut suffix = t[prefix..] + .iter() + .rev() + .zip(c[prefix..].iter().rev()) + .take_while(|(x, y)| x == y) + .count(); + while !target_text.is_char_boundary(t.len() - suffix) { + suffix -= 1; + } + let mut edit = TextDiff::new(); + push_restyled_retain( + &mut edit, + &slice_runs(¤t, 0..prefix), + &slice_runs(&target, 0..prefix), + ); + edit.push_delete(text_len(¤t_text[prefix..c.len() - suffix])); + for (text, attr) in slice_runs(&target, prefix..t.len() - suffix) { + edit.push_insert(StringSlice::from(text), attr.clone()); + } + push_restyled_retain( + &mut edit, + &slice_runs(¤t, c.len() - suffix..c.len()), + &slice_runs(&target, t.len() - suffix..t.len()), + ); + Some(edit) +} + +/// `None` if `diff` is not a pure insertion. +fn list_items(diff: &ListDiff) -> Option<Vec<&ValueOrHandler>> { + let mut ans = Vec::new(); + for item in diff.iter() { + let DeltaItem::Replace { + value, delete: 0, .. + } = item + else { + return None; + }; + ans.extend(value.iter()); + } + Some(ans) +} + +/// Keeps the common prefix and suffix (equal values, containers by id) and replaces the middle. +/// +/// In a movable list, `apply_delta` turns deleting a child container and re-inserting it into +/// a move (see `movable_list_apply_delta.rs`), so middle children that exist in both lists +/// keep their id as well. A plain list recreates them under fresh ids. +fn align_list( + target: &ListDiff, + current: &ListDiff, + movable: bool, + full_state_targets: &mut FxHashSet<ContainerID>, +) -> Option<ListDiff> { + let target = list_items(target)?; + let current = list_items(current)?; + let target_values: Vec<LoroValue> = target.iter().map(|v| v.to_value()).collect(); + let current_values: Vec<LoroValue> = current.iter().map(|v| v.to_value()).collect(); + let (prefix, suffix) = common_ends(&target_values, ¤t_values); + let mut kept: Vec<&LoroValue> = target_values[..prefix] + .iter() + .chain(&target_values[target_values.len() - suffix..]) + .collect(); + if movable { + let current_middle: FxHashSet<&ContainerID> = current_values + [prefix..current_values.len() - suffix] + .iter() + .filter_map(|v| v.as_container()) + .collect(); + kept.extend( + target_values[prefix..target_values.len() - suffix] + .iter() + .filter(|v| { + v.as_container() + .is_some_and(|id| current_middle.contains(id)) + }), + ); + } + for v in kept { + if let LoroValue::Container(id) = v { + full_state_targets.insert(id.clone()); + } + } + let mut edit: ListDiff = DeltaRope::new(); + if prefix == target.len() && prefix == current.len() { + return Some(edit); + } + edit.push_retain(prefix, ListDeltaMeta::default()); + edit.push_delete(current.len() - prefix - suffix); + for v in &target[prefix..target.len() - suffix] { + edit.push_insert(ArrayVec::from([(*v).clone()]), ListDeltaMeta::default()); + } + Some(edit) +} + +/// Keeps nodes by `TreeID`: creates missing ones, moves kept ones whose parent or position +/// differ, and deletes the rest. +fn align_tree( + target: &TreeDiff, + current: &TreeDiff, + full_state_targets: &mut FxHashSet<ContainerID>, +) -> Option<TreeDiff> { + let mut current_nodes: FxHashMap<TreeID, (TreeParentId, &FractionalIndex, usize)> = + FxHashMap::default(); + for item in current.diff.iter() { + let TreeExternalDiff::Create { + parent, + index, + position, + } = &item.action + else { + return None; + }; + current_nodes.insert(item.target, (*parent, position, *index)); + } + let mut edit = TreeDiff::default(); + let mut target_nodes = FxHashSet::default(); + for item in target.diff.iter() { + let TreeExternalDiff::Create { + parent, position, .. + } = &item.action + else { + return None; + }; + target_nodes.insert(item.target); + match current_nodes.get(&item.target) { + Some((p, pos, _)) if p == parent && *pos == position => { + full_state_targets.insert(item.target.associated_meta_container()); + } + Some(_) => { + // `apply_diff` moves a `Create` target that is still alive. + full_state_targets.insert(item.target.associated_meta_container()); + edit.diff.push(item.clone()); + } + None => edit.diff.push(item.clone()), + } + } + for (id, (parent, _, index)) in current_nodes { + if !target_nodes.contains(&id) { + edit.diff.push(TreeDiffItem { + target: id, + action: TreeExternalDiff::Delete { + old_parent: parent, + old_index: index, + }, + }); + } + } + Some(edit) +} diff --git a/vendor/loro-internal/src/handler/movable_list_apply_delta.rs b/vendor/loro-internal/src/handler/movable_list_apply_delta.rs new file mode 100644 index 0000000..102814c --- /dev/null +++ b/vendor/loro-internal/src/handler/movable_list_apply_delta.rs @@ -0,0 +1,361 @@ +//! `MovableListHandler::apply_delta`: turn a list delta into local movable-list +//! ops. +//! +//! A delete of a child container followed by an insert of the same container +//! id is applied as a move, so the child keeps its identity and content. The +//! delta is applied in three passes: +//! +//! 1. Plan: record the delete ranges in original indices and decide which +//! deleted children are re-inserted ("claimed"). +//! 2. Delete every unclaimed element of the delete ranges, right to left, so +//! the remaining original indices stay valid. +//! 3. Walk the delta again with a cursor in live indices. Every inserted value +//! is placed right after the previously placed target element: new values +//! and containers are inserted there, claimed children are moved there. +//! +//! In pass 3, `live[cursor..]` is always the unplaced claimed children of the +//! current delete gap followed by the unmoved original elements at or after +//! the delta position. A retain therefore skips those pending children plus +//! the retained run. A claimed child found before the cursor was left behind by +//! an earlier retain; moving it to `cursor - 1` keeps the cursor in place. + +use super::*; +use crate::{event::Index, state::ContainerState}; +use rustc_hash::FxHashSet; +use std::ops::Range; + +/// Pass 1 output of [`MovableListHandler::apply_delta`]. +struct MovePlan { + /// Delete ranges of the delta in original indices, ascending. + deleted: Vec<Range<usize>>, + /// Original indices of the deleted children that the delta re-inserts, + /// ascending. + claimed: Vec<usize>, + /// One entry per inserted container value, in delta order: the original + /// index and id of the deleted child it claims, if any. + claims: Vec<Option<(usize, ContainerID)>>, +} + +impl MovableListHandler { + /// Applies a list delta to the movable list. + /// + /// Container values inserted by the delta move the matching child out of a + /// deleted range of the same delta when there is one, following + /// `container_remap` for children recreated by earlier undo/apply_diff + /// calls. Other container values create new children and record the + /// `old id -> new id` mapping in `container_remap`. An insert with + /// `from_move` whose child still exists elsewhere in the list is skipped. + #[tracing::instrument(level = "debug", skip_all)] + pub fn apply_delta( + &self, + delta: loro_delta::DeltaRope< + loro_delta::array_vec::ArrayVec<ValueOrHandler, 8>, + crate::event::ListDeltaMeta, + >, + container_remap: &mut FxHashMap<ContainerID, ContainerID>, + ) -> LoroResult<()> { + { + // Test whether the delta is valid + let len = self.len(); + let mut index = 0; + for delta_item in delta.iter() { + match delta_item { + loro_delta::DeltaItem::Retain { len, .. } => { + index += *len; + } + loro_delta::DeltaItem::Replace { delete, .. } => { + index += *delete; + } + } + + if index > len { + return Err(LoroError::OutOfBound { + pos: index, + len, + info: "apply_delta".into(), + }); + } + } + } + + if let MaybeDetached::Detached(_) = &self.inner { + unimplemented!(); + } + + let plan = self.plan_moves(&delta, container_remap)?; + self.delete_unclaimed(&plan)?; + self.place_inserted_values(&delta, container_remap, plan) + } + + fn plan_moves( + &self, + delta: &loro_delta::DeltaRope< + loro_delta::array_vec::ArrayVec<ValueOrHandler, 8>, + crate::event::ListDeltaMeta, + >, + container_remap: &FxHashMap<ContainerID, ContainerID>, + ) -> LoroResult<MovePlan> { + let mut deleted = Vec::new(); + let mut deleted_children: FxHashMap<ContainerID, usize> = FxHashMap::default(); + self.with_state(|state| { + let list = state.as_movable_list_state().unwrap(); + let mut index = 0; + for delta_item in delta.iter() { + match delta_item { + loro_delta::DeltaItem::Retain { len, .. } => { + index += *len; + } + loro_delta::DeltaItem::Replace { delete, .. } => { + if *delete == 0 { + continue; + } + + for i in index..index + *delete { + if let Some(LoroValue::Container(c)) = list.get(i, IndexType::ForUser) { + deleted_children.insert(c.clone(), i); + } + } + deleted.push(index..index + *delete); + index += *delete; + } + } + } + Ok(()) + })?; + + let mut claimed = Vec::new(); + let mut claims = Vec::new(); + if !deleted_children.is_empty() { + for delta_item in delta.iter() { + let loro_delta::DeltaItem::Replace { value, .. } = delta_item else { + continue; + }; + for v in value.iter() { + let Some(mut id) = inserted_container_id(v) else { + continue; + }; + if !deleted_children.contains_key(&id) { + while let Some(new_id) = container_remap.get(&id) { + id = new_id.clone(); + if deleted_children.contains_key(&id) { + break; + } + } + } + let claim = deleted_children.remove(&id).map(|i| (i, id)); + if let Some((i, _)) = &claim { + claimed.push(*i); + } + claims.push(claim); + } + } + claimed.sort_unstable(); + } + + Ok(MovePlan { + deleted, + claimed, + claims, + }) + } + + fn delete_unclaimed(&self, plan: &MovePlan) -> LoroResult<()> { + let mut claimed = plan.claimed.iter().rev().peekable(); + for range in plan.deleted.iter().rev() { + let mut end = range.end; + while let Some(&&i) = claimed.peek() { + if i < range.start { + break; + } + debug_assert!(i < range.end); + claimed.next(); + if end > i + 1 { + self.delete(i + 1, end - i - 1)?; + } + end = i; + } + if end > range.start { + self.delete(range.start, end - range.start)?; + } + } + + Ok(()) + } + + fn place_inserted_values( + &self, + delta: &loro_delta::DeltaRope< + loro_delta::array_vec::ArrayVec<ValueOrHandler, 8>, + crate::event::ListDeltaMeta, + >, + container_remap: &mut FxHashMap<ContainerID, ContainerID>, + plan: MovePlan, + ) -> LoroResult<()> { + let MovePlan { + claimed, claims, .. + } = plan; + let mut claims = claims.into_iter(); + let mut placed = vec![false; claimed.len()]; + // Live index where the next target element goes + let mut cursor = 0; + // Delta position in original indices + let mut orig = 0; + // Start of the deletions since the last retain, in original indices + let mut gap_start = 0; + // Unplaced claimed children of the current gap; they are at + // `live[cursor..cursor + pending]` + let mut pending = 0; + for delta_item in delta.iter() { + match delta_item { + loro_delta::DeltaItem::Retain { len, .. } => { + cursor += pending + *len; + pending = 0; + orig += *len; + gap_start = orig; + } + loro_delta::DeltaItem::Replace { + value, + delete, + attr, + } => { + if *delete > 0 { + let start = claimed.partition_point(|&i| i < orig); + let end = claimed.partition_point(|&i| i < orig + *delete); + pending += placed[start..end].iter().filter(|&&p| !p).count(); + orig += *delete; + } + + for v in value.iter() { + let id = match v { + ValueOrHandler::Value(LoroValue::Container(id)) => id.clone(), + ValueOrHandler::Handler(h) => h.id(), + ValueOrHandler::Value(v) => { + self.insert(cursor, v.clone())?; + cursor += 1; + continue; + } + }; + + match claims.next().flatten() { + Some((orig_index, child)) => { + let k = claimed.binary_search(&orig_index).unwrap(); + placed[k] = true; + if gap_start <= orig_index && orig_index < orig { + pending -= 1; + } + let from = self.child_index(&child)?; + if from >= cursor { + self.mov(from, cursor)?; + cursor += 1; + } else { + self.mov(from, cursor - 1)?; + } + } + None => { + let mut id = id; + while let Some(new_id) = container_remap.get(&id) { + id = new_id.clone(); + } + if !attr.from_move || !self.contains_child(&id)? { + let new_handler = self.insert_container( + cursor, + Handler::new_unattached(id.container_type())?, + )?; + container_remap.insert(id, new_handler.id()); + cursor += 1; + } + } + } + } + } + } + } + + debug_assert_eq!(pending, 0); + debug_assert!(placed.iter().all(|&p| p)); + Ok(()) + } + + /// Live index of a child container that must be in the list. + fn child_index(&self, id: &ContainerID) -> LoroResult<usize> { + let index = self.with_state(|state| Ok(state.get_child_index(id)))?; + match index { + Some(Index::Seq(i)) => Ok(i), + _ => panic!( + "moved child {id} is missing from movable list {}", + self.id() + ), + } + } + + /// The first container value of `delta` with an unknown type that + /// [`Self::apply_delta`] would create instead of move. Mirrors its plan: + /// a value moves a claimed deleted child, or is skipped with `from_move` + /// when the child stays in the list. + pub(crate) fn unknown_container_created_by_delta( + &self, + delta: &loro_delta::DeltaRope< + loro_delta::array_vec::ArrayVec<ValueOrHandler, 8>, + crate::event::ListDeltaMeta, + >, + container_remap: &FxHashMap<ContainerID, ContainerID>, + ) -> LoroResult<Option<ContainerID>> { + let plan = self.plan_moves(delta, container_remap)?; + let mut claims = plan.claims.iter(); + // Children deleted by the delta and not claimed; only read when needed + let mut deleted_unclaimed: Option<FxHashSet<ContainerID>> = None; + for delta_item in delta.iter() { + let loro_delta::DeltaItem::Replace { value, attr, .. } = delta_item else { + continue; + }; + for id in value.iter().filter_map(inserted_container_id) { + if claims.next().is_some_and(|c| c.is_some()) || !id.is_unknown() { + continue; + } + let mut id = id; + while let Some(new_id) = container_remap.get(&id) { + id = new_id.clone(); + } + if attr.from_move && self.contains_child(&id)? { + let deleted_unclaimed = match &mut deleted_unclaimed { + Some(x) => x, + None => deleted_unclaimed.insert(self.with_state(|state| { + let list = state.as_movable_list_state().unwrap(); + let mut ans = FxHashSet::default(); + for range in plan.deleted.iter() { + for i in range.clone() { + if plan.claimed.binary_search(&i).is_ok() { + continue; + } + if let Some(LoroValue::Container(c)) = + list.get(i, IndexType::ForUser) + { + ans.insert(c.clone()); + } + } + } + Ok(ans) + })?), + }; + if !deleted_unclaimed.contains(&id) { + continue; + } + } + return Ok(Some(id)); + } + } + Ok(None) + } + + fn contains_child(&self, id: &ContainerID) -> LoroResult<bool> { + self.with_state(|state| Ok(state.contains_child(id))) + } +} + +fn inserted_container_id(v: &ValueOrHandler) -> Option<ContainerID> { + match v { + ValueOrHandler::Value(LoroValue::Container(id)) => Some(id.clone()), + ValueOrHandler::Handler(h) => Some(h.id()), + ValueOrHandler::Value(_) => None, + } +} diff --git a/vendor/loro-internal/src/handler/text_update.rs b/vendor/loro-internal/src/handler/text_update.rs new file mode 100644 index 0000000..6202262 --- /dev/null +++ b/vendor/loro-internal/src/handler/text_update.rs @@ -0,0 +1,149 @@ +use std::{char, sync::Arc}; + +use itertools::Itertools; +use rustc_hash::FxHashMap; + +use crate::diff::DiffHandler; + +use super::TextHandler; + +pub(super) struct DiffHook<'a> { + text: &'a TextHandler, + new: &'a [u32], + last_old_index: usize, + current_index: usize, +} + +impl<'a> DiffHook<'a> { + pub(crate) fn new(text: &'a TextHandler, new: &'a [u32]) -> Self { + Self { + text, + new, + last_old_index: 0, + current_index: 0, + } + } +} + +impl DiffHandler for DiffHook<'_> { + fn insert(&mut self, old_index: usize, new_index: usize, new_len: usize) { + if old_index > self.last_old_index { + self.current_index += old_index - self.last_old_index; + self.last_old_index = old_index; + } + + self.text + .insert_unicode( + self.current_index, + &self.new[new_index..new_index + new_len] + .iter() + .map(|x| char::from_u32(*x).unwrap()) + .collect::<String>(), + ) + .unwrap(); + self.current_index += new_len; + } + + fn delete(&mut self, old_index: usize, old_len: usize) { + self.current_index += old_index - self.last_old_index; + self.text + .delete_unicode(self.current_index, old_len) + .unwrap(); + self.last_old_index = old_index + old_len; + } +} + +pub(super) struct DiffHookForLine<'a> { + text: &'a TextHandler, + old: Vec<u32>, + new: Vec<u32>, + lines: Vec<Arc<str>>, + lines_lookup: FxHashMap<Arc<str>, usize>, + + last_old_index: usize, + current_index: usize, +} + +impl<'a> DiffHookForLine<'a> { + pub(crate) fn new(text: &'a TextHandler, new_str: &str) -> Self { + let mut this = Self { + text, + old: Vec::new(), + new: Vec::new(), + lines: Vec::new(), + lines_lookup: FxHashMap::default(), + last_old_index: 0, + current_index: 0, + }; + + let text_str = text.to_string(); + for line in text_str.split_inclusive('\n') { + let line: Arc<str> = Arc::from(line); + let id = this.register_line(line); + this.old.push(id as u32); + } + + for line in new_str.split_inclusive('\n') { + let line: Arc<str> = Arc::from(line); + let id = this.register_line(line); + this.new.push(id as u32); + } + + this + } + + fn register_line(&mut self, line: Arc<str>) -> usize { + if let Some(&index) = self.lines_lookup.get(&line) { + return index; + } + + self.lines.push(line.clone()); + self.lines_lookup.insert(line, self.lines.len() - 1); + self.lines.len() - 1 + } + + pub fn get_old_arr(&self) -> &[u32] { + &self.old + } + + pub fn get_new_arr(&self) -> &[u32] { + &self.new + } +} + +impl DiffHandler for DiffHookForLine<'_> { + fn insert(&mut self, old_index: usize, new_index: usize, new_len: usize) { + if self.last_old_index < old_index { + assert!(self.last_old_index < old_index); + self.current_index += (self.last_old_index..old_index) + .map(|x| self.lines[self.old[x] as usize].chars().count()) + .sum::<usize>(); + self.last_old_index = old_index; + } + + let s = self.new[new_index..new_index + new_len] + .iter() + .map(|x| self.lines[*x as usize].clone()) + .join(""); + self.text.insert_unicode(self.current_index, &s).unwrap(); + self.current_index += s.chars().count(); + } + + fn delete(&mut self, old_index: usize, old_len: usize) { + if self.last_old_index != old_index { + assert!(self.last_old_index < old_index); + self.current_index += (self.last_old_index..old_index) + .map(|x| self.lines[self.old[x] as usize].chars().count()) + .sum::<usize>(); + } + + self.last_old_index = old_index + old_len; + let delete_len = (old_index..old_index + old_len) + .map(|x| self.lines[self.old[x] as usize].chars().count()) + .sum::<usize>(); + + self.text + .delete_unicode(self.current_index, delete_len) + .unwrap(); + } +} diff --git a/vendor/loro-internal/src/handler/tree.rs b/vendor/loro-internal/src/handler/tree.rs new file mode 100644 index 0000000..8e88baf --- /dev/null +++ b/vendor/loro-internal/src/handler/tree.rs @@ -0,0 +1,1197 @@ +use std::{collections::VecDeque, sync::Arc}; + +use fractional_index::FractionalIndex; +use loro_common::{ + ContainerID, ContainerType, Counter, IdFull, IdLp, LoroError, LoroResult, LoroTreeError, + LoroValue, PeerID, TreeID, ID, +}; +use rustc_hash::FxHashMap; +use smallvec::smallvec; + +use crate::{ + container::tree::tree_op::TreeOp, + delta::{TreeDiffItem, TreeExternalDiff}, + state::{ + FiIfNotConfigured, FractionalIndexGenResult, NodePosition, TreeNode, TreeNodeWithChildren, + TreeParentId, + }, + txn::{EventHint, Transaction}, + BasicHandler, HandlerTrait, MapHandler, +}; + +use super::{create_handler, Handler, MaybeDetached}; + +#[derive(Clone)] +pub struct TreeHandler { + pub(super) inner: MaybeDetached<TreeInner>, +} + +#[derive(Clone)] +pub(super) struct TreeInner { + next_counter: Counter, + map: FxHashMap<TreeID, MapHandler>, + parent_links: FxHashMap<TreeID, Option<TreeID>>, + children_links: FxHashMap<Option<TreeID>, Vec<TreeID>>, +} + +impl TreeInner { + fn new() -> Self { + TreeInner { + next_counter: 0, + map: FxHashMap::default(), + parent_links: FxHashMap::default(), + children_links: FxHashMap::default(), + } + } + + fn create(&mut self, parent: Option<TreeID>, index: usize) -> TreeID { + let id = TreeID::new(PeerID::MAX, self.next_counter); + self.next_counter += 1; + self.map.insert(id, MapHandler::new_detached()); + self.parent_links.insert(id, parent); + let children = self.children_links.entry(parent).or_default(); + children.insert(index, id); + id + } + + fn mov(&mut self, target: TreeID, new_parent: Option<TreeID>, index: usize) -> LoroResult<()> { + let old_parent = self + .parent_links + .get_mut(&target) + .ok_or(LoroTreeError::TreeNodeNotExist(target))?; + let children = self.children_links.get_mut(old_parent).unwrap(); + children.retain(|x| x != &target); + self.parent_links.insert(target, new_parent); + let children = self.children_links.entry(new_parent).or_default(); + children.insert(index, target); + Ok(()) + } + + fn delete(&mut self, id: TreeID) -> LoroResult<()> { + self.map.remove(&id); + let parent = self + .parent_links + .remove(&id) + .ok_or(LoroTreeError::TreeNodeNotExist(id))?; + let children = self.children_links.get_mut(&parent).unwrap(); + children.retain(|x| x != &id); + self.children_links.remove(&Some(id)); + Ok(()) + } + + fn get_id_by_index(&self, parent: &Option<TreeID>, index: usize) -> Option<TreeID> { + self.children_links + .get(parent) + .and_then(|x| x.get(index).cloned()) + } + + fn get_parent(&self, id: &TreeID) -> Option<Option<TreeID>> { + self.parent_links.get(id).cloned() + } + + fn get_children(&self, parent: Option<TreeID>) -> Option<Vec<TreeID>> { + self.children_links.get(&parent).cloned() + } + + fn children_num(&self, parent: Option<TreeID>) -> Option<usize> { + self.children_links.get(&parent).map(|x| x.len()) + } + + fn is_parent(&self, target: &TreeID, parent: &Option<TreeID>) -> bool { + self.parent_links.get(target) == Some(parent) + } + + fn get_index_by_tree_id(&self, target: &TreeID) -> Option<usize> { + self.parent_links + .get(target) + .and_then(|parent| self.children_links.get(parent)) + .and_then(|children| children.iter().position(|x| x == target)) + } + + fn get_value(&self, deep: bool) -> LoroValue { + let mut ans = vec![]; + + let empty_vec = vec![]; + let mut q = VecDeque::from_iter( + self.children_links + .get(&None) + .unwrap_or(&empty_vec) + .iter() + .enumerate() + .zip(std::iter::repeat(None::<TreeID>)), + ); + + while let Some(((idx, target), parent)) = q.pop_front() { + let map = self.map.get(target).unwrap(); + let mut loro_map_value = FxHashMap::default(); + loro_map_value.insert("id".to_string(), target.to_string().into()); + let parent = parent + .map(|p| p.to_string().into()) + .unwrap_or(LoroValue::Null); + loro_map_value.insert("parent".to_string(), parent); + loro_map_value.insert( + "meta".to_string(), + if deep { + map.get_deep_value() + } else { + String::from("UnResolved").into() + }, + ); + loro_map_value.insert("index".to_string(), (idx as i64).into()); + ans.push(loro_map_value); + if let Some(children) = self.children_links.get(&Some(*target)) { + for (idx, child) in children.iter().enumerate() { + q.push_back(((idx, child), Some(*target))); + } + } + } + ans.into() + } + + fn get_nodes_under(&self, root: TreeParentId) -> Vec<TreeNode> { + let root_id = root.tree_id(); + let mut ans = vec![]; + let empty_vec = vec![]; + let mut q = VecDeque::from_iter( + self.children_links + .get(&root_id) + .unwrap_or(&empty_vec) + .iter() + .enumerate() + .zip(std::iter::repeat(root)), + ); + + while let Some(((index, target), parent)) = q.pop_front() { + ans.push(TreeNode { + id: *target, + parent, + fractional_index: FractionalIndex::default(), + index, + last_move_op: IdFull { + peer: target.peer, + lamport: 0, + counter: target.counter, + }, + }); + if let Some(children) = self.children_links.get(&Some(*target)) { + let parent = TreeParentId::Node(*target); + q.extend( + children + .iter() + .enumerate() + .map(|(index, target)| ((index, target), parent)), + ); + } + } + + ans + } +} + +impl HandlerTrait for TreeHandler { + fn to_handler(&self) -> Handler { + Handler::Tree(self.clone()) + } + + fn attach( + &self, + txn: &mut Transaction, + parent: &BasicHandler, + self_id: ContainerID, + ) -> LoroResult<Self> { + match &self.inner { + MaybeDetached::Detached(t) => { + let mut t = t.lock(); + let inner = create_handler(parent, self_id); + let tree = inner.into_tree().unwrap(); + + let children = t.value.children_links.get(&None); + let mut q = children + .map(|c| { + VecDeque::from_iter( + c.iter() + .enumerate() + .zip(std::iter::repeat(TreeParentId::Root)), + ) + }) + .unwrap_or_default(); + while let Some(((idx, target), parent)) = q.pop_front() { + let real_id = + tree.create_with_txn(txn, parent, idx, FiIfNotConfigured::UseJitterZero)?; + let map = t.value.map.get(target).unwrap(); + map.attach( + txn, + tree.inner.try_attached_state()?, + real_id.associated_meta_container(), + )?; + + if let Some(children) = t.value.children_links.get(&Some(*target)) { + for (idx, child) in children.iter().enumerate() { + q.push_back(((idx, child), TreeParentId::Node(real_id))); + } + } + } + t.attached = tree.attached_handler().cloned(); + Ok(tree) + } + MaybeDetached::Attached(a) => { + let new_inner = create_handler(a, self_id); + let ans = new_inner.into_tree().unwrap(); + + let mut pending = self + .get_all_hierarchy_nodes_under(TreeParentId::Root) + .into_iter() + .rev() + .map(|node| (TreeParentId::Root, node)) + .collect::<Vec<_>>(); + while let Some((parent, mut node)) = pending.pop() { + let real_id = ans.create_with_txn( + txn, + parent, + node.index, + FiIfNotConfigured::UseJitterZero, + )?; + self.get_meta(node.id)?.attach( + txn, + ans.inner.try_attached_state()?, + real_id.associated_meta_container(), + )?; + pending.extend( + std::mem::take(&mut node.children) + .into_iter() + .rev() + .map(|child| (TreeParentId::Node(real_id), child)), + ); + } + Ok(ans) + } + } + } + + fn is_attached(&self) -> bool { + self.inner.is_attached() + } + + fn attached_handler(&self) -> Option<&BasicHandler> { + self.inner.attached_handler() + } + + fn get_value(&self) -> LoroValue { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.get_value(false) + } + MaybeDetached::Attached(a) => a.get_value(), + } + } + + fn get_deep_value(&self) -> LoroValue { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.get_value(true) + } + MaybeDetached::Attached(a) => a.get_deep_value(), + } + } + + fn kind(&self) -> ContainerType { + ContainerType::Tree + } + + fn get_attached(&self) -> Option<Self> { + match &self.inner { + MaybeDetached::Detached(d) => d.lock().attached.clone().map(|x| Self { + inner: MaybeDetached::Attached(x), + }), + MaybeDetached::Attached(_a) => Some(self.clone()), + } + } + + fn from_handler(h: Handler) -> Option<Self> { + match h { + Handler::Tree(x) => Some(x), + _ => None, + } + } + + fn doc(&self) -> Option<crate::LoroDoc> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => Some(a.doc()), + } + } +} + +impl std::fmt::Debug for TreeHandler { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.inner { + MaybeDetached::Detached(_) => write!(f, "TreeHandler Detached"), + MaybeDetached::Attached(a) => write!(f, "TreeHandler {}", a.id), + } + } +} + +impl TreeHandler { + /// Create a new container that is detached from the document. + /// + /// The edits on a detached container will not be persisted/synced. + /// To attach the container to the document, please insert it into an attached + /// container. + pub fn new_detached() -> Self { + Self { + inner: MaybeDetached::new_detached(TreeInner::new()), + } + } + + /// Meta maps of a detached tree's nodes; empty when the tree is attached. + pub(super) fn detached_meta_maps(&self) -> Vec<MapHandler> { + match &self.inner { + MaybeDetached::Detached(t) => t.lock().value.map.values().cloned().collect(), + MaybeDetached::Attached(_) => Vec::new(), + } + } + + /// Get the deep value of the tree with its container id, as a + /// `{ cid, value }` map. Each node in `value` carries the deep value of its + /// associated meta map under the `meta` field. + pub fn get_deep_value_with_id(&self) -> LoroResult<LoroValue> { + let inner = self.inner.try_attached_state()?; + Ok(inner.with_doc_state(|state| { + state.get_container_deep_value_with_id(inner.container_idx, None) + })) + } + + pub fn delete(&self, target: TreeID) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(t) => { + let mut t = t.lock(); + t.value.delete(target)?; + Ok(()) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| self.delete_with_txn(txn, target)), + } + } + + pub(crate) fn delete_with_txn(&self, txn: &mut Transaction, target: TreeID) -> LoroResult<()> { + let inner = self.inner.try_attached_state()?; + let index = match self.get_index_by_tree_id(&target) { + Some(i) => i, + None => { + return Err(LoroTreeError::TreeNodeDeletedOrNotExist(target).into()); + } + }; + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::Tree(Arc::new(TreeOp::Delete { target })), + EventHint::Tree(smallvec![TreeDiffItem { + target, + action: TreeExternalDiff::Delete { + old_parent: self + .get_node_parent(&target) + .ok_or(LoroTreeError::TreeNodeDeletedOrNotExist(target))?, + old_index: index + }, + }]), + &inner.doc, + ) + } + + pub fn create(&self, parent: TreeParentId) -> LoroResult<TreeID> { + match parent { + TreeParentId::Deleted | TreeParentId::Unexist => { + return Err(LoroTreeError::InvalidParent.into()); + } + _ => {} + } + let index: usize = self.children_num(&parent).unwrap_or(0); + match &self.inner { + MaybeDetached::Detached(t) => { + let t = &mut t.lock().value; + Ok(t.create(parent.tree_id(), index)) + } + MaybeDetached::Attached(a) => { + a.with_txn(|txn| self.create_with_txn(txn, parent, index, FiIfNotConfigured::Zero)) + } + } + } + + pub fn create_at(&self, parent: TreeParentId, index: usize) -> LoroResult<TreeID> { + match parent { + TreeParentId::Deleted | TreeParentId::Unexist => { + return Err(LoroTreeError::InvalidParent.into()); + } + _ => {} + } + let children_len = self.children_num(&parent).unwrap_or(0); + if index > children_len { + return Err(LoroTreeError::IndexOutOfBound { + len: children_len, + index, + } + .into()); + } + match &self.inner { + MaybeDetached::Detached(t) => { + let t = &mut t.lock().value; + Ok(t.create(parent.tree_id(), index)) + } + MaybeDetached::Attached(a) => { + a.with_txn(|txn| self.create_with_txn(txn, parent, index, FiIfNotConfigured::Throw)) + } + } + } + + /// For undo/redo, Specify the TreeID of the created node + pub(crate) fn create_at_with_target_for_apply_diff( + &self, + parent: TreeParentId, + position: FractionalIndex, + target: TreeID, + ) -> LoroResult<bool> { + let MaybeDetached::Attached(a) = &self.inner else { + unreachable!(); + }; + + if let Some(p) = self.get_node_parent(&target) { + if p == parent { + return Ok(false); + // If parent is deleted, we need to create the node, so this op from move_apply_diff + } + match p { + TreeParentId::Node(p) => { + if !self.is_node_unexist(&target) && !self.is_node_deleted(&p)? { + return self.move_at_with_target_for_apply_diff(parent, position, target); + } + } + TreeParentId::Root => { + return self.move_at_with_target_for_apply_diff(parent, position, target); + } + TreeParentId::Deleted | TreeParentId::Unexist => {} + } + } + + // A diff made for another version of the doc can name a parent this doc + // doesn't have: an error, which `apply_diff` rolls back. + let with_event = match parent.tree_id() { + Some(p) => !self.is_node_deleted(&p)?, + None => true, + }; + if !with_event { + return Ok(false); + } + + // println!( + // "create_at_with_target_for_apply_diff: {:?} {:?}", + // target, parent + // ); + + let index = self + .get_index_by_fractional_index( + &parent, + &NodePosition { + position: position.clone(), + idlp: self.next_idlp(), + }, + ) + // TODO: parent has deleted? + .unwrap_or(0); + + let children = a.with_txn(|txn| { + let inner = self.inner.try_attached_state()?; + + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::Tree(Arc::new(TreeOp::Create { + target, + parent: parent.tree_id(), + position: position.clone(), + })), + EventHint::Tree(smallvec![TreeDiffItem { + target, + action: TreeExternalDiff::Create { + parent, + index, + position: position.clone(), + }, + }]), + &inner.doc, + )?; + + Ok(self + .children(&TreeParentId::Node(target)) + .unwrap_or_default()) + })?; + for child in children { + let position = self.get_position_by_tree_id(&child).unwrap(); + self.create_at_with_target_for_apply_diff(TreeParentId::Node(target), position, child)?; + } + Ok(true) + } + + /// For undo/redo, Specify the TreeID of the created node + pub(crate) fn move_at_with_target_for_apply_diff( + &self, + parent: TreeParentId, + position: FractionalIndex, + target: TreeID, + ) -> LoroResult<bool> { + let MaybeDetached::Attached(a) = &self.inner else { + unreachable!(); + }; + + // // the move node does not exist, create it + // if self.is_node_unexist(&target) || self.is_node_deleted(&target).unwrap() { + // return self.create_at_with_target_for_apply_diff(parent, position, target); + // } + + if let (Some(p), Some(fi)) = ( + self.get_node_parent(&target), + self.get_position_by_tree_id(&target), + ) { + if p == parent && position == fi { + return Ok(false); + } + } + + let old_parent = self.get_node_parent(&target).unwrap(); + let old_index = self.get_index_by_tree_id(&target).unwrap(); + let mut index = self + .get_index_by_fractional_index( + &parent, + &NodePosition { + position: position.clone(), + idlp: self.next_idlp(), + }, + ) + .unwrap_or(0); + if old_parent == parent && old_index < index { + index -= 1; + } + let with_event = match parent.tree_id() { + Some(p) => !self.is_node_deleted(&p)?, + None => true, + }; + + if !with_event { + return Ok(false); + } + + // println!( + // "move_at_with_target_for_apply_diff: {:?} {:?}", + // target, parent + // ); + + a.with_txn(|txn| { + let inner = self.inner.try_attached_state()?; + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::Tree(Arc::new(TreeOp::Move { + target, + parent: parent.tree_id(), + position: position.clone(), + })), + EventHint::Tree(smallvec![TreeDiffItem { + target, + action: TreeExternalDiff::Move { + parent, + index, + position: position.clone(), + // the old parent should be exist, so we can unwrap + old_parent, + old_index, + }, + }]), + &inner.doc, + ) + })?; + Ok(true) + } + + pub(crate) fn create_with_txn( + &self, + txn: &mut Transaction, + parent: TreeParentId, + index: usize, + cfg: FiIfNotConfigured, + ) -> LoroResult<TreeID> { + let inner = self.inner.try_attached_state()?; + let target = TreeID::from_id(txn.next_id()); + + match self.generate_position_at(&target, &parent, index, cfg) { + FractionalIndexGenResult::Ok(position) => { + self.create_with_position(inner, txn, target, parent, index, position) + } + FractionalIndexGenResult::Rearrange(ids) => { + for (i, (id, position)) in ids.into_iter().enumerate() { + if i == 0 { + self.create_with_position(inner, txn, id, parent, index, position)?; + continue; + } + self.mov_with_position(inner, txn, id, parent, index + i, position, index + i)?; + } + Ok(target) + } + FractionalIndexGenResult::NotConfigured => { + Err(LoroTreeError::FractionalIndexNotEnabled.into()) + } + } + } + + pub fn mov(&self, target: TreeID, parent: TreeParentId) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(_) => { + let mut index: usize = self.children_num(&parent).unwrap_or(0); + if self.is_parent(&target, &parent) { + index -= 1; + } + self.move_to(target, parent, index) + } + MaybeDetached::Attached(a) => { + let mut index: usize = self.children_num(&parent).unwrap_or(0); + if self.is_parent(&target, &parent) { + index -= 1; + } + a.with_txn(|txn| { + self.mov_with_txn(txn, target, parent, index, FiIfNotConfigured::Zero) + }) + } + } + } + + pub fn mov_after(&self, target: TreeID, other: TreeID) -> LoroResult<()> { + let parent = self + .get_node_parent(&other) + .ok_or(LoroTreeError::TreeNodeNotExist(other))?; + let mut index = self + .get_index_by_tree_id(&other) + .ok_or(LoroTreeError::TreeNodeDeletedOrNotExist(other))? + + 1; + if self.is_parent(&target, &parent) { + if let Some(target_index) = self.get_index_by_tree_id(&target) { + if target_index < index { + index -= 1; + } + } + } + self.move_to(target, parent, index) + } + + pub fn mov_before(&self, target: TreeID, other: TreeID) -> LoroResult<()> { + let parent = self + .get_node_parent(&other) + .ok_or(LoroTreeError::TreeNodeNotExist(other))?; + let mut index = self + .get_index_by_tree_id(&other) + .ok_or(LoroTreeError::TreeNodeDeletedOrNotExist(other))?; + if self.is_parent(&target, &parent) && index >= 1 { + if let Some(target_index) = self.get_index_by_tree_id(&target) { + if target_index < index { + index -= 1; + } + } + } + self.move_to(target, parent, index) + } + + pub fn move_to(&self, target: TreeID, parent: TreeParentId, index: usize) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(t) => { + let mut t = t.lock(); + t.value.mov(target, parent.tree_id(), index) + } + MaybeDetached::Attached(a) => a.with_txn(|txn| { + self.mov_with_txn(txn, target, parent, index, FiIfNotConfigured::Throw) + }), + } + } + + pub(crate) fn mov_with_txn( + &self, + txn: &mut Transaction, + target: TreeID, + parent: TreeParentId, + index: usize, + cfg: FiIfNotConfigured, + ) -> LoroResult<()> { + let inner = self.inner.try_attached_state()?; + let mut children_len = self.children_num(&parent).unwrap_or(0); + let mut already_in_parent = false; + // check the input is valid + if self.is_parent(&target, &parent) { + // If the position after moving is same as the current position , do nothing + if let Some(current_index) = self.get_index_by_tree_id(&target) { + if current_index == index { + return Ok(()); + } + // move out first, we cannot delete the position here + // If throw error, the tree will be in a inconsistent state + children_len -= 1; + already_in_parent = true; + } + }; + if index > children_len { + return Err(LoroTreeError::IndexOutOfBound { + len: children_len, + index, + } + .into()); + } + let Some(old_index) = self.get_index_by_tree_id(&target) else { + return Err(LoroError::TreeError( + LoroTreeError::TreeNodeDeletedOrNotExist(target), + )); + }; + + if already_in_parent { + self.delete_position(&parent, &target); + } + + match self.generate_position_at(&target, &parent, index, cfg) { + FractionalIndexGenResult::Ok(position) => { + self.mov_with_position(inner, txn, target, parent, index, position, old_index) + } + FractionalIndexGenResult::Rearrange(ids) => { + for (i, (id, position)) in ids.into_iter().enumerate() { + self.mov_with_position(inner, txn, id, parent, index + i, position, old_index)?; + } + Ok(()) + } + FractionalIndexGenResult::NotConfigured => { + Err(LoroTreeError::FractionalIndexNotEnabled.into()) + } + } + } + + #[allow(clippy::too_many_arguments)] + fn create_with_position( + &self, + inner: &BasicHandler, + txn: &mut Transaction, + tree_id: TreeID, + parent: TreeParentId, + index: usize, + position: FractionalIndex, + ) -> LoroResult<TreeID> { + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::Tree(Arc::new(TreeOp::Create { + target: tree_id, + parent: parent.tree_id(), + position: position.clone(), + })), + EventHint::Tree(smallvec![TreeDiffItem { + target: tree_id, + action: TreeExternalDiff::Create { + parent, + index, + position, + }, + }]), + &inner.doc, + )?; + Ok(tree_id) + } + + #[allow(clippy::too_many_arguments)] + fn mov_with_position( + &self, + inner: &BasicHandler, + txn: &mut Transaction, + target: TreeID, + parent: TreeParentId, + index: usize, + position: FractionalIndex, + old_index: usize, + ) -> LoroResult<()> { + txn.apply_local_op( + inner.container_idx, + crate::op::RawOpContent::Tree(Arc::new(TreeOp::Move { + target, + parent: parent.tree_id(), + position: position.clone(), + })), + EventHint::Tree(smallvec![TreeDiffItem { + target, + action: TreeExternalDiff::Move { + parent, + index, + position, + old_parent: self + .get_node_parent(&target) + .ok_or(LoroTreeError::TreeNodeDeletedOrNotExist(target))?, + old_index, + }, + }]), + &inner.doc, + ) + } + + pub fn get_meta(&self, target: TreeID) -> LoroResult<MapHandler> { + match &self.inner { + MaybeDetached::Detached(d) => { + let d = d.lock(); + d.value + .map + .get(&target) + .cloned() + .ok_or(LoroTreeError::TreeNodeNotExist(target).into()) + } + MaybeDetached::Attached(a) => { + if self.is_node_unexist(&target) { + return Err(LoroTreeError::TreeNodeNotExist(target).into()); + } + let map_container_id = target.associated_meta_container(); + let handler = create_handler(a, map_container_id); + handler.into_map().map_err(|_| { + LoroError::DecodeError( + "Tree node's associated meta container is not a map".into(), + ) + }) + } + } + } + + pub fn is_node_unexist(&self, target: &TreeID) -> bool { + match &self.inner { + MaybeDetached::Detached(d) => { + let d = d.lock(); + !d.value.map.contains_key(target) + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.is_node_unexist(target) + }), + } + } + + pub fn is_node_deleted(&self, target: &TreeID) -> LoroResult<bool> { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value + .map + .get(target) + .and(Some(true)) + .ok_or(LoroTreeError::TreeNodeNotExist(*target).into()) + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.is_node_deleted(target) + .ok_or(LoroTreeError::TreeNodeNotExist(*target).into()) + }), + } + } + + /// Get the parent of the node, if the node does not exist, return None + pub fn get_node_parent(&self, target: &TreeID) -> Option<TreeParentId> { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.get_parent(target).map(TreeParentId::from) + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.parent(target) + }), + } + } + + // TODO: iterator + pub fn children(&self, parent: &TreeParentId) -> Option<Vec<TreeID>> { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.get_children(parent.tree_id()) + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.get_children(parent).map(|x| x.collect()) + }), + } + } + + pub fn children_num(&self, parent: &TreeParentId) -> Option<usize> { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.children_num(parent.tree_id()) + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.children_num(parent) + }), + } + } + + /// Check if the node is exist. include deleted node. + pub fn contains(&self, target: TreeID) -> bool { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.map.contains_key(&target) + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + !a.is_node_unexist(&target) + }), + } + } + + pub fn get_child_at(&self, parent: &TreeParentId, index: usize) -> Option<TreeID> { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.get_id_by_index(&parent.tree_id(), index) + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.get_id_by_index(parent, index) + }), + } + } + + pub fn is_parent(&self, target: &TreeID, parent: &TreeParentId) -> bool { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.is_parent(target, &parent.tree_id()) + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.is_parent(target, parent) + }), + } + } + + /// Get all nodes in the tree, including deleted nodes + pub fn nodes(&self) -> Vec<TreeID> { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.map.keys().cloned().collect() + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.nodes() + }), + } + } + + pub fn get_nodes_under(&self, parent: TreeParentId) -> Vec<TreeNode> { + match &self.inner { + MaybeDetached::Detached(t) => t.lock().value.get_nodes_under(parent), + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.get_all_tree_nodes_under(parent) + }), + } + } + pub fn roots(&self) -> Vec<TreeID> { + self.children(&TreeParentId::Root).unwrap_or_default() + } + + pub fn get_all_hierarchy_nodes_under(&self, parent: TreeParentId) -> Vec<TreeNodeWithChildren> { + match &self.inner { + MaybeDetached::Detached(_t) => { + unreachable!() + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.get_all_hierarchy_nodes_under(parent) + }), + } + } + + #[allow(non_snake_case)] + pub fn __internal__next_tree_id(&self) -> TreeID { + match &self.inner { + MaybeDetached::Detached(d) => { + let d = d.lock(); + TreeID::new(PeerID::MAX, d.value.next_counter) + } + MaybeDetached::Attached(a) => a + .with_txn(|txn| Ok(TreeID::from_id(txn.next_id()))) + .unwrap(), + } + } + + fn generate_position_at( + &self, + target: &TreeID, + parent: &TreeParentId, + index: usize, + cfg: FiIfNotConfigured, + ) -> FractionalIndexGenResult { + let MaybeDetached::Attached(a) = &self.inner else { + unreachable!() + }; + a.with_state(|state| { + let a = state.as_tree_state_mut().unwrap(); + a.generate_position_at(target, parent, index, cfg) + }) + } + + /// Get the index of the target node in the parent node + /// + /// O(logN) + pub fn get_index_by_tree_id(&self, target: &TreeID) -> Option<usize> { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.get_index_by_tree_id(target) + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.get_index_by_tree_id(target) + }), + } + } + + pub fn get_position_by_tree_id(&self, target: &TreeID) -> Option<FractionalIndex> { + match &self.inner { + MaybeDetached::Detached(t) => t + .lock() + .value + .parent_links + .contains_key(target) + .then(FractionalIndex::default), + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.get_position(target) + }), + } + } + + fn delete_position(&self, parent: &TreeParentId, target: &TreeID) { + let MaybeDetached::Attached(a) = &self.inner else { + unreachable!() + }; + a.with_state(|state| { + let a = state.as_tree_state_mut().unwrap(); + a.try_delete_position_cache(parent, target) + }) + } + + // use for apply diff + pub(crate) fn get_index_by_fractional_index( + &self, + parent: &TreeParentId, + node_position: &NodePosition, + ) -> Option<usize> { + match &self.inner { + MaybeDetached::Detached(_) => { + unreachable!(); + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.get_index_by_position(parent, node_position) + }), + } + } + + pub(crate) fn next_idlp(&self) -> IdLp { + match &self.inner { + MaybeDetached::Detached(_) => { + unreachable!() + } + MaybeDetached::Attached(a) => a.with_txn(|txn| Ok(txn.next_idlp())).unwrap(), + } + } + + pub fn is_fractional_index_enabled(&self) -> bool { + match &self.inner { + MaybeDetached::Detached(_) => true, + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.is_fractional_index_enabled() + }), + } + } + + /// Set whether to generate fractional index for Tree Position. The LoroDoc is set to use jitter 0 by default. + /// + /// The jitter is used to avoid conflicts when multiple users are creating the node at the same position. + /// value 0 is default, which means no jitter, any value larger than 0 will enable jitter. + /// + /// Generally speaking, jitter will affect the growth rate of document size. + /// [Read more about it](https://www.loro.dev/blog/movable-tree#implementation-and-encoding-size) + pub fn enable_fractional_index(&self, jitter: u8) { + match &self.inner { + MaybeDetached::Detached(_) => { + // No-op on detached trees + let _ = jitter; + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state_mut().unwrap(); + a.enable_generate_fractional_index(jitter); + }), + } + } + + /// Disable the fractional index generation for Tree Position when + /// you don't need the Tree's siblings to be sorted. The fractional index will be always default. + /// + /// The LoroDoc is set to disable fractional index by default. + pub fn disable_fractional_index(&self) { + match &self.inner { + MaybeDetached::Detached(_) => { + // No-op on detached trees + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state_mut().unwrap(); + a.disable_generate_fractional_index(); + }), + } + } + + pub fn is_deleted(&self) -> bool { + match &self.inner { + MaybeDetached::Detached(_) => false, + MaybeDetached::Attached(a) => a.is_deleted(), + } + } + + pub fn is_empty(&self) -> bool { + match &self.inner { + MaybeDetached::Detached(t) => { + let t = t.lock(); + t.value.map.is_empty() + } + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.is_empty() + }), + } + } + + pub fn get_last_move_id(&self, target: &TreeID) -> Option<ID> { + match &self.inner { + MaybeDetached::Detached(_) => None, + MaybeDetached::Attached(a) => a.with_state(|state| { + let a = state.as_tree_state().unwrap(); + a.get_last_move_id(target) + }), + } + } + + pub fn clear(&self) -> LoroResult<()> { + match &self.inner { + MaybeDetached::Detached(t) => { + let mut t = t.lock(); + t.value.map.clear(); + t.value.children_links.clear(); + t.value.parent_links.clear(); + Ok(()) + } + MaybeDetached::Attached(_) => { + let nodes = self.get_nodes_under(TreeParentId::Root); + for node in nodes { + self.delete(node.id)?; + } + Ok(()) + } + } + } +} diff --git a/vendor/loro-internal/src/history_cache.rs b/vendor/loro-internal/src/history_cache.rs new file mode 100644 index 0000000..71941ce --- /dev/null +++ b/vendor/loro-internal/src/history_cache.rs @@ -0,0 +1,1070 @@ +use std::{ + collections::{BTreeMap, BTreeSet}, + marker::PhantomData, + ops::Bound, + sync::Arc, +}; + +use crate::sync::Mutex; +use either::Either; +use enum_as_inner::EnumAsInner; +use enum_dispatch::enum_dispatch; +use generic_btree::rle::{HasLength as _, Sliceable}; +use loro_common::{ + ContainerType, Counter, HasLamport, IdFull, IdLp, InternalString, LoroValue, PeerID, ID, +}; +use rle::HasLength; +use rustc_hash::{FxHashMap, FxHashSet}; + +use crate::{ + change::{Change, Lamport}, + container::{ + idx::ContainerIdx, + list::list_op::InnerListOp, + richtext::{richtext_state::RichtextStateChunk, AnchorType, StyleOp}, + tree::tree_op::TreeOp, + }, + delta::MapValue, + diff_calc::tree::{MoveLamportAndID, TreeCacheForDiff}, + encoding::value_register::ValueRegister, + op::{InnerContent, RichOp, SliceWithId}, + oplog::ChangeStore, + state::{ContainerCreationContext, GcStore, TreeParentId}, + OpLog, VersionVector, +}; + +/// A cache for the history of a container. +/// +/// There are cases where a container needs a view of the history of the container. +/// For example, when switching to an older version, a map container may need to know the value of a key at a certain version. +/// This cache provides a faster way to do that than scanning the oplog. +#[derive(Debug)] +pub(crate) struct ContainerHistoryCache { + change_store: ChangeStore, + shallow_root_state: Option<Arc<GcStore>>, + for_checkout: Option<ForCheckout>, + for_importing: Option<FxHashMap<ContainerIdx, HistoryCacheForImporting>>, + /// Maps whose shallow-root entries are already in the checkout index. + /// Map entries are seeded per container on first use; see + /// [`Self::ensure_shallow_map_seeded`]. + shallow_maps_seeded: FxHashSet<ContainerIdx>, +} + +#[derive(Debug, Default)] +pub(crate) struct ForCheckout { + pub(crate) map: MapHistoryCache, + pub(crate) movable_list: MovableListHistoryCache, +} + +#[derive(Clone, Copy)] +pub(crate) struct HasImportingCacheMark { + _private: PhantomData<()>, +} + +impl HistoryCacheTrait for ForCheckout { + fn insert(&mut self, op: &RichOp) { + match op.raw_op().container.get_type() { + ContainerType::Map => self.map.insert(op), + ContainerType::MovableList => self.movable_list.insert(op), + _ => {} + } + } +} + +impl ContainerHistoryCache { + pub(crate) fn new(change_store: ChangeStore, gc: Option<Arc<GcStore>>) -> Self { + Self { + change_store, + for_checkout: Default::default(), + for_importing: Default::default(), + shallow_root_state: gc, + shallow_maps_seeded: Default::default(), + } + } + + pub(crate) fn insert_by_new_change( + &mut self, + change: &Change, + for_checkout: bool, + for_importing: bool, + ) { + if self.for_checkout.is_none() && self.for_importing.is_none() { + return; + } + + for op in change.ops.iter() { + match op.container.get_type() { + ContainerType::Map | ContainerType::MovableList + if self.for_checkout.is_some() && for_checkout => + { + let rich_op = RichOp::new_by_change(change, op); + self.for_checkout.as_mut().unwrap().insert(&rich_op) + } + ContainerType::Tree if self.for_importing.is_some() && for_importing => { + let container_idx = op.container; + let rich_op = RichOp::new_by_change(change, op); + let manager = self + .for_importing + .as_mut() + .unwrap() + .entry(container_idx) + .or_insert_with(|| match op.container.get_type() { + ContainerType::Tree => { + HistoryCacheForImporting::Tree(TreeOpGroup::default()) + } + _ => unreachable!(), + }); + manager.insert(&rich_op) + } + _ => continue, + } + } + } + + pub(crate) fn get_checkout_index(&mut self) -> &ForCheckout { + self.ensure_all_caches_exist(); + self.for_checkout.as_ref().unwrap() + } + + pub(crate) fn ensure_all_caches_exist(&mut self) { + let mut record_for_checkout = false; + let mut record_for_importing = false; + if self.for_checkout.is_none() { + self.for_checkout = Some(ForCheckout::default()); + record_for_checkout = true; + } + + if self.for_importing.is_none() { + self.for_importing = Some(FxHashMap::default()); + record_for_importing = true; + } + + if !record_for_checkout && !record_for_importing { + return; + } + + self.init_cache_by_visit_all_change_slow(record_for_checkout, record_for_importing); + } + + pub(crate) fn ensure_importing_caches_exist(&mut self) -> HasImportingCacheMark { + if self.for_importing.is_some() { + return HasImportingCacheMark { + _private: PhantomData, + }; + } + + self.for_importing = Some(FxHashMap::default()); + self.init_cache_by_visit_all_change_slow(false, true); + HasImportingCacheMark { + _private: PhantomData, + } + } + + fn init_cache_by_visit_all_change_slow(&mut self, for_checkout: bool, for_importing: bool) { + if self.for_checkout.is_none() && self.for_importing.is_none() { + return; + } + + if !for_checkout && !for_importing { + return; + } + + self.change_store.visit_all_changes(&mut |c| { + for op in c.ops.iter() { + match op.container.get_type() { + ContainerType::Map | ContainerType::MovableList + if self.for_checkout.is_some() && for_checkout => + { + let rich_op = RichOp::new_by_change(c, op); + self.for_checkout.as_mut().unwrap().insert(&rich_op) + } + ContainerType::Tree if self.for_importing.is_some() && for_importing => { + let container_idx = op.container; + let rich_op = RichOp::new_by_change(c, op); + let manager = self + .for_importing + .as_mut() + .unwrap() + .entry(container_idx) + .or_insert_with(|| match op.container.get_type() { + ContainerType::Tree => { + HistoryCacheForImporting::Tree(TreeOpGroup::default()) + } + _ => unreachable!(), + }); + manager.insert(&rich_op) + } + _ => continue, + } + } + }); + + let default_ctx = ContainerCreationContext { + configure: &Default::default(), + peer: 0, + }; + + if let Some(state) = self.shallow_root_state.as_ref() { + ensure_cov::notify_cov( + "loro_internal::history_cache::init_cache_by_visit_all_change_slow::visit_gc", + ); + let mut store = state.store.lock(); + // Maps are seeded per container on first use, so only movable lists + // and trees are loaded here; decoding every container of a large + // shallow root dominated the first concurrent map import. + for idx in store.tree_and_movable_list_idxs() { + let Some(c) = store.get_mut(idx) else { + continue; + }; + match idx.get_type() { + ContainerType::Text | ContainerType::List | ContainerType::Unknown(_) => { + continue + } + #[cfg(feature = "counter")] + ContainerType::Counter => continue, + ContainerType::Map => continue, + ContainerType::MovableList => {} + ContainerType::Tree => {} + } + + let state = c.get_state_mut(idx, default_ctx); + + match state { + crate::state::State::MapState(m) => { + if for_checkout { + let c = self.for_checkout.as_mut().unwrap(); + for (k, v) in m.iter() { + c.map.record_shallow_root_state_entry(idx, k, v); + } + } + } + crate::state::State::MovableListState(l) => { + for (idlp, elem) in l.elements() { + if for_checkout { + let c = self.for_checkout.as_mut().unwrap(); + let item = l.get_list_item(elem.pos).unwrap(); + c.movable_list.record_shallow_root_state( + item.id, + idlp.peer, + idlp.lamport.into(), + elem.value.clone(), + ); + } + } + } + crate::state::State::TreeState(t) => { + if for_importing { + let c = self.for_importing.as_mut().unwrap(); + let tree = c.entry(idx).or_insert_with(|| { + HistoryCacheForImporting::Tree(Default::default()) + }); + // Deleted nodes are seeded too: a retained op can revive a node + // deleted before the shallow root (e.g. move a child out of a + // deleted parent), and the diff calculator then needs the node's + // subtree at the root to re-create it and to retreat later moves. + tree.as_tree_mut().unwrap().record_shallow_root_state( + t.tree_nodes() + .into_iter() + .chain(t.deleted_tree_nodes()) + .map(|node| MoveLamportAndID { + id: node.last_move_op, + op: Arc::new(if node.parent == TreeParentId::Deleted { + TreeOp::Delete { target: node.id } + } else { + TreeOp::Create { + target: node.id, + parent: node.parent.tree_id(), + position: node.fractional_index.clone(), + } + }), + effected: true, + }) + .collect(), + ); + } + } + _ => unreachable!(), + } + } + } + } + + pub(crate) fn get_tree( + &self, + container_idx: &ContainerIdx, + _: HasImportingCacheMark, + ) -> Option<&TreeOpGroup> { + self.for_importing + .as_ref() + .unwrap() + .get(container_idx) + .map(|group| match group { + HistoryCacheForImporting::Tree(tree) => tree, + }) + } + + pub(crate) fn has_cache(&self) -> bool { + self.for_checkout.is_some() + } + + pub(crate) fn free(&mut self) { + self.for_checkout = None; + self.shallow_maps_seeded.clear(); + } + + pub(crate) fn free_all(&mut self) { + self.for_checkout = None; + self.for_importing = None; + self.shallow_maps_seeded.clear(); + } + + pub(crate) fn set_shallow_root_store(&mut self, shallow_root_store: Option<Arc<GcStore>>) { + self.shallow_root_state = shallow_root_store; + self.shallow_maps_seeded.clear(); + } + + /// Ensure the checkout index exists and holds `idx`'s shallow-root map entries. + /// + /// Map entries are only read per container (`MapDiffCalculator` asks for its + /// own container's changed keys), so each map is seeded the first time a + /// diff needs it instead of seeding every map in the shallow root up front. + pub(crate) fn ensure_shallow_map_seeded(&mut self, idx: ContainerIdx) { + self.ensure_all_caches_exist(); + if !self.shallow_maps_seeded.insert(idx) { + return; + } + let Some(state) = self.shallow_root_state.as_ref() else { + return; + }; + let default_ctx = ContainerCreationContext { + configure: &Default::default(), + peer: 0, + }; + let mut store = state.store.lock(); + let Some(c) = store.get_mut(idx) else { + return; + }; + if let crate::state::State::MapState(m) = c.get_state_mut(idx, default_ctx) { + let cache = self.for_checkout.as_mut().unwrap(); + for (k, v) in m.iter() { + cache.map.record_shallow_root_state_entry(idx, k, v); + } + } + } + + /// Whether the movable list `idx` holds `elem_id` in the shallow root state. + /// + /// Elements created before the shallow root cannot be resolved from the trimmed + /// history; the checkout index only knows the ones still alive at the root + /// (`MovableListHistoryCache::record_shallow_root_state`). + pub(crate) fn shallow_root_has_movable_list_elem( + &self, + idx: ContainerIdx, + elem_id: IdLp, + ) -> bool { + let Some(state) = self.shallow_root_state.as_ref() else { + return false; + }; + let mut store = state.store.lock(); + let Some(c) = store.get_mut(idx) else { + return false; + }; + let ctx = ContainerCreationContext { + configure: &Default::default(), + peer: 0, + }; + match c.get_state_mut(idx, ctx) { + crate::state::State::MovableListState(l) => { + l.elements().contains_key(&elem_id.compact()) + } + _ => false, + } + } + + pub(crate) fn find_text_chunks_in( + &self, + idx: ContainerIdx, + target_span: loro_common::IdSpan, + ) -> Vec<RichtextStateChunk> { + ensure_cov::notify_cov("loro_internal::history_cache::find_text_chunks_in"); + let Some(state) = self.shallow_root_state.as_ref() else { + return Vec::new(); + }; + + let mut binding = state.store.lock(); + let Some(text) = binding.get_mut(idx) else { + return Vec::new(); + }; + + let text_state = text + .get_state( + idx, + ContainerCreationContext { + configure: &Default::default(), + peer: 0, + }, + ) + .as_richtext_state() + .unwrap(); + + // TODO: FIXME: This could be super slow in some cases + let mut ans = Vec::new(); + text_state.iter_raw(&mut |chunk| { + let c_span = chunk.get_id_span(); + if let Some(range) = target_span.get_slice_range_on(&c_span) { + let c = chunk.slice(range.0..range.1); + ans.push(c); + } + }); + + ans.sort_unstable_by_key(|x| x.counter()); + let mut normalized = Vec::with_capacity(ans.len()); + let mut covered_end = target_span.counter.start; + for chunk in ans { + let span = chunk.get_id_span(); + let start = span.counter.start.max(covered_end); + let end = span.counter.end.min(target_span.counter.end); + if start >= end { + continue; + } + + normalized.push( + chunk.slice( + (start - span.counter.start) as usize..(end - span.counter.start) as usize, + ), + ); + covered_end = end; + } + + normalized + } + + pub(crate) fn find_text_chunks_in_shallow_root_order( + &self, + idx: ContainerIdx, + ) -> Vec<RichtextStateChunk> { + ensure_cov::notify_cov( + "loro_internal::history_cache::find_text_chunks_in_shallow_root_order", + ); + let Some(state) = self.shallow_root_state.as_ref() else { + return Vec::new(); + }; + + let mut binding = state.store.lock(); + let Some(text) = binding.get_mut(idx) else { + return Vec::new(); + }; + + let text_state = text + .get_state( + idx, + ContainerCreationContext { + configure: &Default::default(), + peer: 0, + }, + ) + .as_richtext_state() + .unwrap(); + + let mut ans = Vec::new(); + text_state.iter_raw(&mut |chunk| { + ans.push(chunk.slice(0..chunk.rle_len())); + }); + + ans + } + + pub(crate) fn find_text_style_end_in_shallow_root( + &self, + idx: ContainerIdx, + style_start_id: ID, + ) -> Option<(StyleOp, usize)> { + ensure_cov::notify_cov("loro_internal::history_cache::find_text_style_end_in_shallow_root"); + let state = self.shallow_root_state.as_ref()?; + + let mut binding = state.store.lock(); + let text = binding.get_mut(idx)?; + + let text_state = text + .get_state( + idx, + ContainerCreationContext { + configure: &Default::default(), + peer: 0, + }, + ) + .as_richtext_state() + .unwrap(); + + let mut entity_index = 0; + let mut ans = None; + text_state.iter_raw(&mut |chunk| { + if ans.is_some() { + return; + } + + match chunk { + RichtextStateChunk::Text(text) => { + entity_index += text.unicode_len() as usize; + } + RichtextStateChunk::Style { style, anchor_type } => { + if style.id() == style_start_id && *anchor_type == AnchorType::End { + ans = Some((style.as_ref().clone(), entity_index.saturating_sub(1))); + } + entity_index += 1; + } + } + }); + + ans + } + + pub(crate) fn find_list_chunks_in( + &self, + idx: ContainerIdx, + target_span: loro_common::IdSpan, + ) -> Vec<SliceWithId> { + ensure_cov::notify_cov("loro_internal::history_cache::find_list_chunks_in"); + let Some(state) = self.shallow_root_state.as_ref() else { + return Vec::new(); + }; + + let mut binding = state.store.lock(); + let Some(list) = binding.get_mut(idx) else { + return Vec::new(); + }; + + let list_state = list.get_state( + idx, + ContainerCreationContext { + configure: &Default::default(), + peer: 0, + }, + ); + + let mut ans = Vec::with_capacity(target_span.atom_len()); + match list_state { + crate::state::State::ListState(list) => { + for v in list.iter_with_id() { + if target_span.contains(v.id.id()) { + ans.push(SliceWithId { + values: Either::Right(v.v.clone()), + id: v.id, + elem_id: None, + }) + } + } + } + crate::state::State::MovableListState(list) => { + for (move_id, elem_id, v) in list.iter_with_last_move_id_and_elem_id() { + if target_span.contains(move_id.id()) { + ans.push(SliceWithId { + values: Either::Right(v.clone()), + id: move_id, + elem_id: Some(elem_id), + }) + } + } + } + _ => unreachable!(), + } + + ans.sort_unstable_by_key(|x| x.id.counter); + ans + } +} + +#[enum_dispatch(OpGroupTrait)] +#[derive(Debug, EnumAsInner)] +pub(crate) enum HistoryCacheForImporting { + Tree(TreeOpGroup), +} + +impl HistoryCacheForImporting { + fn insert(&mut self, op: &RichOp) { + match self { + HistoryCacheForImporting::Tree(t) => t.insert(op), + } + } +} + +#[enum_dispatch] +trait HistoryCacheTrait { + fn insert(&mut self, op: &RichOp); +} + +#[derive(Debug, Clone)] +pub(crate) struct GroupedMapOpInfo<T = Option<LoroValue>> { + pub(crate) value: T, + pub(crate) lamport: Lamport, + pub(crate) peer: PeerID, +} + +impl<T> PartialEq for GroupedMapOpInfo<T> { + fn eq(&self, other: &Self) -> bool { + self.lamport == other.lamport && self.peer == other.peer + } +} + +impl<T> Eq for GroupedMapOpInfo<T> {} + +impl<T> PartialOrd for GroupedMapOpInfo<T> { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl<T> Ord for GroupedMapOpInfo<T> { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.lamport + .cmp(&other.lamport) + .then_with(|| self.peer.cmp(&other.peer)) + } +} + +#[derive(Debug, Clone)] +struct MapHistoryCacheEntry { + container: ContainerIdx, + key: u32, + lamport: Lamport, + peer: PeerID, + counter_or_value: Either<Counter, Box<Option<LoroValue>>>, +} + +impl PartialEq for MapHistoryCacheEntry { + fn eq(&self, other: &Self) -> bool { + self.container == other.container + && self.key == other.key + && self.lamport == other.lamport + && self.peer == other.peer + } +} + +impl Eq for MapHistoryCacheEntry {} + +impl PartialOrd for MapHistoryCacheEntry { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for MapHistoryCacheEntry { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.container + .cmp(&other.container) + .then_with(|| self.key.cmp(&other.key)) + .then_with(|| self.lamport.cmp(&other.lamport)) + .then_with(|| self.peer.cmp(&other.peer)) + } +} + +#[derive(Debug, Default)] +pub(crate) struct MapHistoryCache { + keys: ValueRegister<InternalString>, + map: BTreeSet<MapHistoryCacheEntry>, +} + +impl HistoryCacheTrait for MapHistoryCache { + fn insert(&mut self, op: &RichOp) { + let container = op.raw_op().container; + let key = match &op.raw_op().content { + InnerContent::Map(map) => map.key.clone(), + _ => unreachable!(), + }; + + let key_idx = self.keys.register(&key); + self.map.insert(MapHistoryCacheEntry { + container, + key: key_idx as u32, + lamport: op.lamport(), + peer: op.peer, + counter_or_value: Either::Left(op.counter()), + }); + } +} + +impl MapHistoryCache { + fn record_shallow_root_state_entry( + &mut self, + idx: ContainerIdx, + k: &InternalString, + v: &MapValue, + ) { + let key_idx = self.keys.register(k); + self.map.insert(MapHistoryCacheEntry { + container: idx, + key: key_idx as u32, + lamport: v.lamport(), + peer: v.peer, + counter_or_value: Either::Right(Box::new(v.value.clone())), + }); + } + + /// The entry of the op that wins `key` at `vv`, if any. + fn latest_entry_at_vv( + &self, + container: ContainerIdx, + key: u32, + vv: &VersionVector, + ) -> Option<&MapHistoryCacheEntry> { + let bound = |lamport, peer| MapHistoryCacheEntry { + container, + key, + lamport, + peer, + counter_or_value: Either::Left(0), + }; + self.map + .range(bound(0, 0)..=bound(Lamport::MAX, PeerID::MAX)) + .rev() + .find(|entry| match &entry.counter_or_value { + Either::Left(cnt) => vv.get(&entry.peer).copied().unwrap_or(0) > *cnt, + // Shallow-root entries are part of every version the doc can reach. + Either::Right(_) => true, + }) + } + + fn entry_info(entry: &MapHistoryCacheEntry, oplog: &OpLog) -> GroupedMapOpInfo { + let value = match &entry.counter_or_value { + Either::Left(cnt) => { + let op = oplog + .get_op_that_includes(ID::new(entry.peer, *cnt)) + .unwrap(); + debug_assert_eq!(op.atom_len(), 1); + match &op.content { + InnerContent::Map(map) => map.value.clone(), + _ => unreachable!(), + } + } + Either::Right(v) => (**v).clone(), + }; + GroupedMapOpInfo { + value, + lamport: entry.lamport, + peer: entry.peer, + } + } + + /// For each key, the op that wins it at `to_vv` when that differs from the + /// op that wins it at `from_vv`; `None` when no op sets the key at `to_vv`. + /// + /// Every key whose value can differ between two versions must have been + /// written by an op inside the replayed span, so a diff only ever needs the + /// candidate keys instead of the whole container. This keeps map diffing + /// proportional to the update instead of to the size of the map. + /// + /// Winners are compared by op id only, so only the `to` value is ever + /// fetched. A different winner can still carry an equal value; the caller's + /// state has the `from` value and tells the two cases apart (see + /// `MapDiffCalculator::calculate_diff`). + pub fn changed_winners_for_keys( + &self, + container: ContainerIdx, + from_vv: &VersionVector, + to_vv: &VersionVector, + keys: impl Iterator<Item = InternalString>, + oplog: &OpLog, + ) -> Vec<(InternalString, Option<GroupedMapOpInfo>)> { + let mut ans = Vec::new(); + for key in keys { + let Some(key_idx) = self.keys.get(&key) else { + continue; + }; + let key_idx = key_idx as u32; + let from = self.latest_entry_at_vv(container, key_idx, from_vv); + let to = self.latest_entry_at_vv(container, key_idx, to_vv); + match (from, to) { + (None, None) => {} + (Some(_), None) => ans.push((key, None)), + (Some(a), Some(b)) if a.lamport == b.lamport && a.peer == b.peer => {} + (_, Some(b)) => ans.push((key, Some(Self::entry_info(b, oplog)))), + } + } + + ans + } +} + +#[derive(Debug, Clone)] +pub(crate) struct GroupedTreeOpInfo { + pub(crate) counter: Counter, + pub(crate) value: Arc<TreeOp>, +} + +#[derive(Debug, Default)] +pub(crate) struct TreeOpGroup { + ops: BTreeMap<IdLp, GroupedTreeOpInfo>, + tree_for_diff: Mutex<TreeCacheForDiff>, +} + +impl HistoryCacheTrait for TreeOpGroup { + fn insert(&mut self, op: &RichOp) { + let tree_op = op.raw_op().content.as_tree().unwrap(); + self.ops.insert( + op.idlp(), + GroupedTreeOpInfo { + value: tree_op.clone(), + counter: op.raw_op().counter, + }, + ); + } +} + +impl TreeOpGroup { + pub fn ops(&self) -> &BTreeMap<IdLp, GroupedTreeOpInfo> { + &self.ops + } + + pub fn tree(&self) -> &Mutex<TreeCacheForDiff> { + &self.tree_for_diff + } + + pub(crate) fn record_shallow_root_state(&mut self, nodes: Vec<MoveLamportAndID>) { + let mut tree = self.tree_for_diff.lock(); + for node in nodes.iter() { + self.ops.insert( + node.id.idlp(), + GroupedTreeOpInfo { + counter: node.id.counter, + value: node.op.clone(), + }, + ); + } + tree.init_tree_with_shallow_root_version(nodes); + } +} + +#[derive(Debug, Default)] +pub(crate) struct MovableListHistoryCache { + move_set: BTreeSet<MovableListInnerDeltaEntry>, + set_set: BTreeSet<MovableListSetDeltaEntry>, +} + +#[derive(Debug, Eq, PartialEq, Clone)] +struct MovableListInnerDeltaEntry { + element_lamport: Lamport, + element_peer: PeerID, + lamport: Lamport, + peer: PeerID, + counter: Counter, +} + +#[derive(Debug, Eq, PartialEq, Clone)] +struct MovableListSetDeltaEntry { + element_lamport: Lamport, + element_peer: PeerID, + lamport: Lamport, + peer: PeerID, + counter_or_value: Either<Counter, Box<LoroValue>>, +} + +impl Ord for MovableListInnerDeltaEntry { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.element_lamport + .cmp(&other.element_lamport) + .then_with(|| self.element_peer.cmp(&other.element_peer)) + .then_with(|| self.lamport.cmp(&other.lamport)) + .then_with(|| self.peer.cmp(&other.peer)) + } +} + +impl PartialOrd for MovableListInnerDeltaEntry { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl PartialOrd for MovableListSetDeltaEntry { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for MovableListSetDeltaEntry { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.element_lamport + .cmp(&other.element_lamport) + .then_with(|| self.element_peer.cmp(&other.element_peer)) + .then_with(|| self.lamport.cmp(&other.lamport)) + .then_with(|| self.peer.cmp(&other.peer)) + } +} + +impl HistoryCacheTrait for MovableListHistoryCache { + fn insert(&mut self, op: &RichOp) { + let cur_id = op.id_full(); + match &op.op().content { + InnerContent::List(l) => match l { + crate::container::list::list_op::InnerListOp::Move { elem_id, .. } => { + self.move_set.insert(MovableListInnerDeltaEntry { + element_lamport: elem_id.lamport, + element_peer: elem_id.peer, + lamport: cur_id.lamport, + peer: cur_id.peer, + counter: cur_id.counter, + }); + } + crate::container::list::list_op::InnerListOp::Set { elem_id, .. } => { + self.set_set.insert(MovableListSetDeltaEntry { + element_lamport: elem_id.lamport, + element_peer: elem_id.peer, + lamport: cur_id.lamport, + peer: cur_id.peer, + counter_or_value: Either::Left(cur_id.counter), + }); + } + _ => {} + }, + _ => unreachable!(), + } + } +} + +impl MovableListHistoryCache { + pub(crate) fn record_shallow_root_state( + &mut self, + id: IdFull, + elem_peer: PeerID, + elem_lamport: Lamport, + value: LoroValue, + ) { + self.set_set.insert(MovableListSetDeltaEntry { + element_lamport: elem_lamport, + element_peer: elem_peer, + lamport: id.lamport, + peer: id.peer, + counter_or_value: Either::Right(Box::new(value.clone())), + }); + self.move_set.insert(MovableListInnerDeltaEntry { + element_lamport: elem_lamport, + element_peer: elem_peer, + lamport: id.lamport, + peer: id.peer, + counter: id.counter, + }); + } + + pub(crate) fn last_value( + &self, + key: IdLp, + vv: &VersionVector, + max_lamport: Lamport, + oplog: &OpLog, + ) -> Option<GroupedMapOpInfo<LoroValue>> { + self.set_set + .range(( + Bound::Included(MovableListSetDeltaEntry { + element_lamport: key.lamport, + element_peer: key.peer, + lamport: 0, + peer: 0, + counter_or_value: Either::Left(0), + }), + Bound::Excluded(MovableListSetDeltaEntry { + element_lamport: key.lamport, + element_peer: key.peer, + lamport: max_lamport, + peer: PeerID::MAX, + counter_or_value: Either::Left(Counter::MAX), + }), + )) + .rev() + .find(|e| { + let counter = match &e.counter_or_value { + Either::Left(c) => *c, + Either::Right(_) => -1, + }; + vv.get(&e.peer).copied().unwrap_or(0) > counter + }) + .map_or_else( + || { + let id = oplog.idlp_to_id(key).unwrap(); + if vv.get(&id.peer).copied().unwrap_or(0) <= id.counter { + return None; + } + let op = oplog.get_op_that_includes(id).unwrap(); + let offset = id.counter - op.counter; + match &op.content { + InnerContent::List(InnerListOp::Insert { slice, .. }) => { + let value = slice.as_slice()[offset as usize].clone(); + Some(GroupedMapOpInfo { + value, + lamport: key.lamport, + peer: id.peer, + }) + } + _ => { + unreachable!() + } + } + }, + |e| { + let (lamport, value) = match &e.counter_or_value { + Either::Left(c) => { + let id = ID::new(e.peer, *c); + let op = oplog.get_op_that_includes(id).unwrap(); + debug_assert_eq!(op.atom_len(), 1); + let lamport = op.lamport(); + match &op.content { + InnerContent::List(InnerListOp::Set { value, .. }) => { + (lamport, value.clone()) + } + _ => { + unreachable!() + } + } + } + Either::Right(v) => (e.lamport, v.as_ref().clone()), + }; + Some(GroupedMapOpInfo { + value: value.clone(), + lamport, + peer: e.peer, + }) + }, + ) + } + + pub(crate) fn last_pos( + &self, + key: IdLp, + vv: &VersionVector, + max_lamport: Lamport, + oplog: &OpLog, + ) -> Option<IdFull> { + self.move_set + .range(( + Bound::Included(MovableListInnerDeltaEntry { + element_lamport: key.lamport, + element_peer: key.peer, + lamport: 0, + peer: 0, + counter: 0, + }), + Bound::Excluded(MovableListInnerDeltaEntry { + element_lamport: key.lamport, + element_peer: key.peer, + lamport: max_lamport, + peer: PeerID::MAX, + counter: Counter::MAX, + }), + )) + .rev() + .find(|e| vv.get(&e.peer).copied().unwrap_or(0) > e.counter) + .map_or_else( + || { + let id = oplog.idlp_to_id(key).unwrap(); + if vv.get(&id.peer).copied().unwrap_or(0) > id.counter { + Some(IdFull::new(id.peer, id.counter, key.lamport)) + } else { + None + } + }, + |e| { + let id = ID::new(e.peer, e.counter); + let lamport = oplog.get_lamport_at(id).unwrap_or(e.lamport); + Some(IdFull::new(e.peer, e.counter, lamport)) + }, + ) + } +} diff --git a/vendor/loro-internal/src/id.rs b/vendor/loro-internal/src/id.rs new file mode 100644 index 0000000..1c8882b --- /dev/null +++ b/vendor/loro-internal/src/id.rs @@ -0,0 +1,4 @@ +pub use loro_common::Counter; +pub use loro_common::PeerID; +pub use loro_common::TreeID; +pub use loro_common::ID; diff --git a/vendor/loro-internal/src/jsonpath/ast.rs b/vendor/loro-internal/src/jsonpath/ast.rs new file mode 100644 index 0000000..cd06c31 --- /dev/null +++ b/vendor/loro-internal/src/jsonpath/ast.rs @@ -0,0 +1,458 @@ +use crate::jsonpath::errors::JSONPathError; +use crate::jsonpath::JSONPathParser; +use std::fmt::{self, Write}; + +#[derive(Debug, Clone)] +pub struct Query { + pub segments: Segment, +} + +#[derive(Debug, Clone)] +pub enum Segment { + Root {}, + Child { + left: Box<Segment>, + selectors: Vec<Selector>, + }, + Recursive { + left: Box<Segment>, + selectors: Vec<Selector>, + }, +} + +#[derive(Debug, Clone)] +pub enum Selector { + Name { + name: String, + }, + Index { + index: i64, + }, + Slice { + start: Option<i64>, + stop: Option<i64>, + step: Option<i64>, + }, + Wild {}, + Filter { + expression: Box<FilterExpression>, + }, +} + +#[derive(Debug, Clone)] +pub enum FilterExpression { + True_ {}, + False_ {}, + Null {}, + Array { + values: Vec<FilterExpression>, + }, + StringLiteral { + value: String, + }, + Int { + value: i64, + }, + Float { + value: f64, + }, + Not { + expression: Box<FilterExpression>, + }, + Logical { + left: Box<FilterExpression>, + operator: LogicalOperator, + right: Box<FilterExpression>, + }, + Comparison { + left: Box<FilterExpression>, + operator: ComparisonOperator, + right: Box<FilterExpression>, + }, + RelativeQuery { + query: Box<Query>, + }, + RootQuery { + query: Box<Query>, + }, + Function { + name: String, + args: Vec<FilterExpression>, + }, +} + +#[derive(Debug, Clone)] +pub enum LogicalOperator { + And, + Or, +} + +#[derive(Debug, Clone)] +pub enum ComparisonOperator { + Eq, + Ne, + Ge, + Gt, + Le, + Lt, + Contains, + In, +} + +impl Query { + pub fn standard(expr: &str) -> Result<Self, JSONPathError> { + JSONPathParser::new().parse(expr) + } + + pub fn is_singular(&self) -> bool { + self.segments.is_singular() + } +} + +impl Segment { + // Returns `true` if this query can resolve to at most one node, or `false` otherwise. + pub fn is_singular(&self) -> bool { + match self { + Segment::Child { left, selectors } => { + selectors.len() == 1 + && selectors.first().is_some_and(|selector| { + matches!(selector, Selector::Name { .. } | Selector::Index { .. }) + }) + && left.is_singular() + } + Segment::Recursive { .. } => false, + Segment::Root {} => true, + } + } +} + +impl FilterExpression { + pub fn is_literal(&self) -> bool { + matches!( + self, + FilterExpression::True_ { .. } + | FilterExpression::False_ { .. } + | FilterExpression::Null { .. } + | FilterExpression::StringLiteral { .. } + | FilterExpression::Int { .. } + | FilterExpression::Float { .. } + | FilterExpression::Array { .. } + ) + } +} + +impl fmt::Display for Query { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "${}", self.segments) + } +} + +impl fmt::Display for Segment { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Segment::Child { left, selectors } => write!( + f, + "{}[{}]", + left, + selectors + .iter() + .map(|s| s.to_string()) + .collect::<Vec<String>>() + .join(", ") + ), + Segment::Recursive { left, selectors } => write!( + f, + "{}..[{}]", + left, + selectors + .iter() + .map(|s| s.to_string()) + .collect::<Vec<String>>() + .join(", ") + ), + Segment::Root {} => Ok(()), + } + } +} + +impl fmt::Display for Selector { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Selector::Name { name, .. } => write!(f, "'{name}'"), + Selector::Index { + index: array_index, .. + } => write!(f, "{array_index}"), + Selector::Slice { + start, stop, step, .. + } => { + write!( + f, + "{}:{}:{}", + start + .and_then(|i| Some(i.to_string())) + .unwrap_or(String::from("")), + stop.and_then(|i| Some(i.to_string())) + .unwrap_or(String::from("")), + step.and_then(|i| Some(i.to_string())) + .unwrap_or(String::from("1")), + ) + } + Selector::Wild { .. } => f.write_char('*'), + Selector::Filter { expression, .. } => write!(f, "?{expression}"), + } + } +} + +impl fmt::Display for FilterExpression { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FilterExpression::True_ { .. } => f.write_str("true"), + FilterExpression::False_ { .. } => f.write_str("false"), + FilterExpression::Null { .. } => f.write_str("null"), + FilterExpression::StringLiteral { value, .. } => write!(f, "'{value}'"), + FilterExpression::Array { values, .. } => { + write!( + f, + "[{}]", + values + .iter() + .map(|e| e.to_string()) + .collect::<Vec<String>>() + .join(", ") + ) + } + FilterExpression::Int { value, .. } => write!(f, "{value}"), + FilterExpression::Float { value, .. } => write!(f, "{value}"), + FilterExpression::Not { expression, .. } => write!(f, "!{expression}"), + FilterExpression::Logical { + left, + operator, + right, + .. + } => write!(f, "({left} {operator} {right})"), + FilterExpression::Comparison { + left, + operator, + right, + .. + } => write!(f, "{left} {operator} {right}"), + FilterExpression::RelativeQuery { query, .. } => { + write!(f, "@{}", query.segments) + } + FilterExpression::RootQuery { query, .. } => { + write!(f, "${}", query.segments) + } + FilterExpression::Function { name, args, .. } => { + write!( + f, + "{}({})", + name, + args.iter() + .map(|a| a.to_string()) + .collect::<Vec<String>>() + .join(", ") + ) + } + } + } +} + +impl fmt::Display for LogicalOperator { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + LogicalOperator::And => f.write_str("&&"), + LogicalOperator::Or => f.write_str("||"), + } + } +} + +impl fmt::Display for ComparisonOperator { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ComparisonOperator::Eq => f.write_str("=="), + ComparisonOperator::Ne => f.write_str("!="), + ComparisonOperator::Ge => f.write_str(">="), + ComparisonOperator::Gt => f.write_str(">"), + ComparisonOperator::Le => f.write_str("<="), + ComparisonOperator::Lt => f.write_str("<"), + ComparisonOperator::Contains => f.write_str("contains"), + ComparisonOperator::In => f.write_str("in"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(expr: &str) -> Query { + Query::standard(expr).unwrap() + } + + fn relative_query(selector: Selector) -> Query { + Query { + segments: Segment::Child { + left: Box::new(Segment::Root {}), + selectors: vec![selector], + }, + } + } + + #[test] + fn query_standard_reports_singular_queries_correctly() { + let cases = [ + ("$", true), + ("$.store", true), + ("$['store']", true), + ("$.store.books[0]", true), + ("$.store.books[0][1]", true), + ("$.store.books[0, 1]", false), + ("$.store.books[*]", false), + ("$.store.books[?(@.available == true)]", false), + ("$.store..title", false), + ]; + + for (expr, expected) in cases { + assert_eq!( + parse(expr).is_singular(), + expected, + "{expr} should have singular={expected}" + ); + } + } + + #[test] + fn filter_expression_is_literal_matches_jsonpath_contract() { + let literal_cases = [ + FilterExpression::True_ {}, + FilterExpression::False_ {}, + FilterExpression::Null {}, + FilterExpression::StringLiteral { + value: "hello".to_owned(), + }, + FilterExpression::Int { value: 42 }, + FilterExpression::Float { value: 3.5 }, + FilterExpression::Array { + values: vec![ + FilterExpression::Int { value: 1 }, + FilterExpression::StringLiteral { + value: "two".to_owned(), + }, + FilterExpression::Array { + values: vec![FilterExpression::Null {}], + }, + ], + }, + ]; + + for expr in literal_cases { + assert!(expr.is_literal(), "{expr:?} should be literal"); + } + + let non_literal_cases = [ + FilterExpression::RelativeQuery { + query: Box::new(relative_query(Selector::Name { + name: "title".to_owned(), + })), + }, + FilterExpression::RootQuery { + query: Box::new(parse("$.store.books[0]")), + }, + FilterExpression::Function { + name: "count".to_owned(), + args: vec![FilterExpression::RelativeQuery { + query: Box::new(relative_query(Selector::Name { + name: "title".to_owned(), + })), + }], + }, + FilterExpression::Not { + expression: Box::new(FilterExpression::True_ {}), + }, + FilterExpression::Logical { + left: Box::new(FilterExpression::True_ {}), + operator: LogicalOperator::And, + right: Box::new(FilterExpression::False_ {}), + }, + FilterExpression::Comparison { + left: Box::new(FilterExpression::Int { value: 1 }), + operator: ComparisonOperator::Eq, + right: Box::new(FilterExpression::Int { value: 2 }), + }, + ]; + + for expr in non_literal_cases { + assert!(!expr.is_literal(), "{expr:?} should not be literal"); + } + } + + #[test] + fn query_and_ast_display_are_stable() { + let query = parse("$.store.books[0]"); + assert_eq!(query.to_string(), "$['store']['books'][0]"); + assert_eq!( + parse("$.store.books[0, 1]").to_string(), + "$['store']['books'][0, 1]" + ); + assert_eq!(parse("$.store..title").to_string(), "$['store']..['title']"); + + let selector_display = [ + ( + Selector::Name { + name: "field".into(), + }, + "'field'", + ), + (Selector::Index { index: -2 }, "-2"), + ( + Selector::Slice { + start: Some(1), + stop: Some(3), + step: None, + }, + "1:3:1", + ), + (Selector::Wild {}, "*"), + ]; + + for (selector, expected) in selector_display { + assert_eq!(selector.to_string(), expected); + } + + let filter_display = FilterExpression::Logical { + left: Box::new(FilterExpression::Comparison { + left: Box::new(FilterExpression::RelativeQuery { + query: Box::new(relative_query(Selector::Name { + name: "available".to_owned(), + })), + }), + operator: ComparisonOperator::Eq, + right: Box::new(FilterExpression::True_ {}), + }), + operator: LogicalOperator::And, + right: Box::new(FilterExpression::Not { + expression: Box::new(FilterExpression::Function { + name: "count".to_owned(), + args: vec![FilterExpression::RootQuery { + query: Box::new(parse("$.store.books[*]")), + }], + }), + }), + }; + assert_eq!( + filter_display.to_string(), + "(@['available'] == true && !count($['store']['books'][*]))" + ); + + assert_eq!(LogicalOperator::And.to_string(), "&&"); + assert_eq!(LogicalOperator::Or.to_string(), "||"); + assert_eq!(ComparisonOperator::Eq.to_string(), "=="); + assert_eq!(ComparisonOperator::Ne.to_string(), "!="); + assert_eq!(ComparisonOperator::Ge.to_string(), ">="); + assert_eq!(ComparisonOperator::Gt.to_string(), ">"); + assert_eq!(ComparisonOperator::Le.to_string(), "<="); + assert_eq!(ComparisonOperator::Lt.to_string(), "<"); + assert_eq!(ComparisonOperator::Contains.to_string(), "contains"); + assert_eq!(ComparisonOperator::In.to_string(), "in"); + } +} diff --git a/vendor/loro-internal/src/jsonpath/errors.rs b/vendor/loro-internal/src/jsonpath/errors.rs new file mode 100644 index 0000000..65e1311 --- /dev/null +++ b/vendor/loro-internal/src/jsonpath/errors.rs @@ -0,0 +1,61 @@ +use std::fmt; + +#[derive(Debug)] +pub enum JSONPathErrorType { + LexerError, + SyntaxError, + TypeError, + NameError, +} + +#[derive(Debug)] +pub struct JSONPathError { + pub kind: JSONPathErrorType, + pub msg: String, +} + +impl JSONPathError { + pub fn new(error: JSONPathErrorType, msg: String) -> Self { + Self { kind: error, msg } + } + + pub fn syntax(msg: String) -> Self { + Self { + kind: JSONPathErrorType::SyntaxError, + msg, + } + } + + pub fn typ(msg: String) -> Self { + Self { + kind: JSONPathErrorType::TypeError, + msg, + } + } + + pub fn name(msg: String) -> Self { + Self { + kind: JSONPathErrorType::NameError, + msg, + } + } +} + +impl fmt::Display for JSONPathErrorType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + JSONPathErrorType::LexerError => f.write_str("lexer error:"), + JSONPathErrorType::SyntaxError => f.write_str("syntax error:"), + JSONPathErrorType::TypeError => f.write_str("type error:"), + JSONPathErrorType::NameError => f.write_str("name error:"), + } + } +} + +impl std::error::Error for JSONPathError {} + +impl fmt::Display for JSONPathError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.msg) + } +} diff --git a/vendor/loro-internal/src/jsonpath/jsonpath.pest b/vendor/loro-internal/src/jsonpath/jsonpath.pest new file mode 100644 index 0000000..6a34d33 --- /dev/null +++ b/vendor/loro-internal/src/jsonpath/jsonpath.pest @@ -0,0 +1,110 @@ +// JSONPath Parser +// This grammar defines the structure for parsing JSONPath expressions. +// It follows a structured approach with grouped rules for clarity and maintainability. + +// Entry Point +// Defines the overall structure of a JSONPath expression, starting with SOI (start of input) and ending with EOI (end of input). +jsonpath = _{ SOI ~ jsonpath_query ~ EOI } + +// Core Query Structure +jsonpath_query = _{ root_identifier ~ segments } + +// Segments +segments = _{ (S ~ segment)* } + +// Whitespace Handling +B = _{ "\x20" | "\x09" | "\x0A" | "\x0D" } // Basic whitespace characters: space, tab, newline, carriage return +S = _{ B* } // Optional whitespace + +// Identifiers +root_identifier = _{ "$" } // Root node identifier +current_node_identifier = _{ "@" } // Current node identifier + +// Segment Types +segment = _{ child_segment | descendant_segment } +child_segment = { bracketed_selection | ("." ~ (wildcard_selector | member_name_shorthand)) } +descendant_segment = { ".." ~ (bracketed_selection | wildcard_selector | member_name_shorthand) } + +// Bracketed Selection +bracketed_selection = { "[" ~ S ~ selector ~ (S ~ "," ~ S ~ selector)* ~ S ~ "]" } + +// Selectors +selector = _{ name_selector | wildcard_selector | slice_selector | index_selector | filter_selector } +wildcard_selector = { "*" } // Matches any element +name_selector = _{ string_literal } // Matches a specific name +index_selector = @{ int } // Matches a specific index +slice_selector = { (start ~ S)? ~ ":" ~ S ~ (stop ~ S)? ~ (":" ~ (S ~ step)?)? } // Array slicing +filter_selector = { "?" ~ S ~ logical_expr } // Filter based on logical expression + +// Integer and Slice Components +int = { "0" | ("-"? ~ ASCII_NONZERO_DIGIT ~ ASCII_DIGIT*) } +start = @{ int } +stop = @{ int } +step = @{ int } + +// String Literals +string_literal = _{ ("\x22" ~ double_quoted ~ "\x22") | ("\x27" ~ single_quoted ~ "\x27") } +double_quoted = { double_quoted_char* } +single_quoted = { single_quoted_char* } +double_quoted_char = _{ unescaped | "\x27" | (ESC ~ "\x22") | (ESC ~ escapable) } +single_quoted_char = _{ unescaped | "\x22" | (ESC ~ "\x27") | (ESC ~ escapable) } +ESC = _{ "\x5C" } // Escape character (backslash) + +// Escapable Characters +escapable = _{ "\x62" | "\x66" | "\x6E" | "\x72" | "\x74" | "/" | "\\" | ("\x75" ~ hexchar) } +hexchar = _{ non_surrogate | (high_surrogate ~ "\\u" ~ low_surrogate) } +non_surrogate = _{ ((ASCII_DIGIT | ^"A" | ^"B" | ^"C" | ^"E" | ^"F") ~ ASCII_HEX_DIGIT{3}) | (^"D" ~ '\u{30}'..'\u{37}' ~ ASCII_HEX_DIGIT{2}) } +high_surrogate = _{ ^"D" ~ ("8" | "9" | ^"A" | ^"B") ~ ASCII_HEX_DIGIT{2} } +low_surrogate = _{ ^"D" ~ (^"C" | ^"D" | ^"E" | ^"F") ~ ASCII_HEX_DIGIT{2} } + +// Unescaped Characters +unescaped = _{ '\u{20}'..'\u{21}' | '\u{23}'..'\u{26}' | '\u{28}'..'\u{5B}' | '\u{5D}'..'\u{D7FF}' | '\u{E000}'..'\u{10FFFF}' } + +// Logical Expressions +logical_expr = _{ logical_or_expr } +logical_or_expr = { logical_and_expr ~ (S ~ "||" ~ S ~ logical_and_expr)* } +logical_and_expr = { basic_expr ~ (S ~ "&&" ~ S ~ basic_expr)* } +basic_expr = _{ paren_expr | comparison_expr | test_expr } +paren_expr = { (logical_not_op ~ S)? ~ "(" ~ S ~ logical_expr ~ S ~ ")" } +logical_not_op = { "!" } +test_expr = { (logical_not_op ~ S)? ~ (filter_query | function_expr) } + +// Queries in Filters +filter_query = _{ rel_query | root_query } +root_query = { jsonpath_query } +rel_query = { current_node_identifier ~ segments } + +// Comparison Expressions +comparison_expr = { comparable ~ S ~ comparison_op ~ S ~ comparable } +comparison_op = { "==" | "!=" | "<=" | ">=" | "<" | ">" | "contains" | "in" } +comparable = _{ literal | singular_query | function_expr } + +// Literals +literal = _{ number | string_literal | array_literal | true_literal | false_literal | null } +true_literal = { "true" } +false_literal = { "false" } +null = { "null" } +number = { (int | "-0") ~ frac? ~ exp? } +frac = { "." ~ ASCII_DIGIT+ } +exp = { ^"e" ~ ("-" | "+")? ~ ASCII_DIGIT+ } +array_literal = { "[" ~ S ~ (literal ~ (S ~ "," ~ S ~ literal)*)? ~ S ~ "]" } + +// Singular Queries +singular_query = _{ rel_singular_query | abs_singular_query } +rel_singular_query = { current_node_identifier ~ singular_query_segments } +abs_singular_query = { root_identifier ~ singular_query_segments } +singular_query_segments = _{ (S ~ (name_segment | index_segment))* } +name_segment = { ("[" ~ name_selector ~ "]") | ("." ~ member_name_shorthand) } +index_segment = { "[" ~ index_selector ~ "]" } + +// Function Expressions +function_expr = { function_name ~ "(" ~ S ~ (function_argument ~ (S ~ "," ~ S ~ function_argument)*)? ~ S ~ ")" } +function_name = { function_name_first ~ function_name_char* } +function_name_first = _{ ASCII_ALPHA_LOWER } +function_name_char = _{ function_name_first | "_" | ASCII_DIGIT } +function_argument = _{ filter_query | logical_expr | function_expr | literal } + +// Member Names +member_name_shorthand = { name_first ~ name_char* } +name_first = _{ ASCII_ALPHA | "_" | '\u{80}'..'\u{D7FF}' | '\u{E000}'..'\u{10FFFF}' } +name_char = _{ name_first | ASCII_DIGIT } \ No newline at end of file diff --git a/vendor/loro-internal/src/jsonpath/jsonpath_impl.rs b/vendor/loro-internal/src/jsonpath/jsonpath_impl.rs new file mode 100644 index 0000000..9a9aed7 --- /dev/null +++ b/vendor/loro-internal/src/jsonpath/jsonpath_impl.rs @@ -0,0 +1,1635 @@ +use crate::handler::{ + Handler, ListHandler, MapHandler, MovableListHandler, TextHandler, TreeHandler, ValueOrHandler, +}; +use crate::jsonpath::ast::{ + ComparisonOperator, FilterExpression, LogicalOperator, Segment, Selector, +}; +use crate::jsonpath::JSONPathParser; +use crate::{HandlerTrait, LoroDoc}; +use loro_common::{ContainerID, LoroValue}; +use std::ops::ControlFlow; +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum JsonPathError { + #[error("Invalid JSONPath: {0}")] + InvalidJsonPath(String), + #[error("JSONPath evaluation error: {0}")] + EvaluationError(String), +} +impl LoroDoc { + #[inline] + pub fn jsonpath(&self, jsonpath: &str) -> Result<Vec<ValueOrHandler>, JsonPathError> { + evaluate_jsonpath(self, jsonpath) + } +} + +enum ExprValue { + Bool(bool), + Value(LoroValue), + Nodes(Vec<ValueOrHandler>), +} + +pub fn evaluate_jsonpath( + root: &dyn PathValue, + jsonpath: &str, +) -> Result<Vec<ValueOrHandler>, JsonPathError> { + let parser = JSONPathParser::new(); + let query = parser + .parse(jsonpath) + .map_err(|e| JsonPathError::InvalidJsonPath(e.to_string()))?; + + let mut results = Vec::new(); + evaluate_segment(root, &query.segments, &mut results); + Ok(results) +} + +fn evaluate_segment(root: &dyn PathValue, segment: &Segment, results: &mut Vec<ValueOrHandler>) { + match segment { + Segment::Root {} => { + if let Ok(cloned) = root.clone_this() { + results.push(cloned); + } + } + Segment::Child { left, selectors } => { + if left.is_singular() && matches!(**left, Segment::Root {}) { + apply_selectors(root, root, selectors, results); + } else { + let mut intermediate = Vec::new(); + evaluate_segment(root, left, &mut intermediate); + for node in intermediate { + apply_selectors(root, &node, selectors, results); + } + } + } + Segment::Recursive { left, selectors } => { + if left.is_singular() && matches!(**left, Segment::Root {}) { + recursive_descent(root, root, selectors, results); + } else { + let mut intermediate = Vec::new(); + evaluate_segment(root, left, &mut intermediate); + for node in intermediate { + recursive_descent(root, &node, selectors, results); + } + } + } + } +} + +fn apply_selectors( + root: &dyn PathValue, + node: &dyn PathValue, + selectors: &[Selector], + results: &mut Vec<ValueOrHandler>, +) { + for sel in selectors { + match sel { + Selector::Name { name } => { + if let Some(child) = node.get_by_key(name) { + results.push(child); + } + } + Selector::Index { index } => { + let mut idx = *index; + if idx < 0 { + idx += node.length_for_path() as i64; + } + if idx >= 0 { + if let Some(child) = node.get_by_index(idx as isize) { + results.push(child); + } + } + } + Selector::Slice { start, stop, step } => { + let len = node.length_for_path() as i64; + let eff_start = start.unwrap_or(if step.unwrap_or(1) > 0 { 0 } else { len - 1 }); + let eff_stop = stop.unwrap_or(if step.unwrap_or(1) > 0 { len } else { -len - 1 }); + let eff_step = step.unwrap_or(1); + + if eff_step == 0 { + continue; + } + + let mut start_idx = if eff_start < 0 { + eff_start + len + } else { + eff_start + }; + let mut stop_idx = if eff_stop < 0 { + eff_stop + len + } else { + eff_stop + }; + start_idx = start_idx.max(0).min(len); + stop_idx = stop_idx.max(-1).min(len); + + // Pre-allocate if positive step for better perf + if eff_step > 0 { + let approx_count = ((stop_idx - start_idx) / eff_step).max(0) as usize; + results.reserve(approx_count); + let mut i = start_idx; + while i < stop_idx { + if let Some(child) = node.get_by_index(i as isize) { + results.push(child); + } + i += eff_step; + } + } else { + let approx_count = ((start_idx - stop_idx) / -eff_step).max(0) as usize; + results.reserve(approx_count); + let mut i = start_idx; + while i > stop_idx { + if let Some(child) = node.get_by_index(i as isize) { + results.push(child); + } + i += eff_step; + } + } + } + Selector::Wild {} => { + node.for_each_for_path(&mut |child| { + results.push(child); + ControlFlow::Continue(()) + }); + } + Selector::Filter { expression } => { + node.for_each_for_path(&mut |child| { + if eval_filter_expr(root, &child, expression) { + results.push(child); + } + ControlFlow::Continue(()) + }); + } + } + } +} + +fn recursive_descent( + root: &dyn PathValue, + node: &dyn PathValue, + selectors: &[Selector], + results: &mut Vec<ValueOrHandler>, +) { + // 1. apply selectors to the *current* node + apply_selectors(root, node, selectors, results); + + // 2. recurse into children + node.for_each_for_path(&mut |child| { + recursive_descent(root, &child, selectors, results); + ControlFlow::Continue(()) + }); +} + +fn eval_filter_expr( + root: &dyn PathValue, + current: &dyn PathValue, + expr: &FilterExpression, +) -> bool { + to_logical(eval_expr(root, current, expr)) +} + +fn eval_expr(root: &dyn PathValue, current: &dyn PathValue, expr: &FilterExpression) -> ExprValue { + match expr { + FilterExpression::True_ {} => ExprValue::Bool(true), + FilterExpression::False_ {} => ExprValue::Bool(false), + FilterExpression::Null {} => ExprValue::Value(LoroValue::Null), + FilterExpression::StringLiteral { value } => { + ExprValue::Value(LoroValue::String(value.clone().into())) + } + FilterExpression::Int { value } => ExprValue::Value(LoroValue::I64(*value)), + FilterExpression::Float { value } => ExprValue::Value(LoroValue::Double(*value)), + FilterExpression::Array { values } => { + let mut list = Vec::with_capacity(values.len()); + for val in values { + match eval_expr(root, current, val) { + ExprValue::Value(v) => list.push(v), + ExprValue::Bool(b) => list.push(LoroValue::Bool(b)), + ExprValue::Nodes(_) => return ExprValue::Value(LoroValue::Null), + } + } + ExprValue::Value(LoroValue::List(list.into())) + } + FilterExpression::Not { expression } => { + ExprValue::Bool(!to_logical(eval_expr(root, current, expression))) + } + FilterExpression::Logical { + left, + operator, + right, + } => { + // Short-circuit evaluation + let l = to_logical(eval_expr(root, current, left)); + match operator { + LogicalOperator::And => { + if !l { + return ExprValue::Bool(false); + } + ExprValue::Bool(to_logical(eval_expr(root, current, right))) + } + LogicalOperator::Or => { + if l { + return ExprValue::Bool(true); + } + ExprValue::Bool(to_logical(eval_expr(root, current, right))) + } + } + } + FilterExpression::Comparison { + left, + operator, + right, + } => { + let l = eval_expr(root, current, left); + let r = eval_expr(root, current, right); + ExprValue::Bool(compare_expr(l, operator, r)) + } + FilterExpression::RelativeQuery { query } => { + let mut query_results = Vec::new(); + evaluate_segment(current, &query.segments, &mut query_results); + ExprValue::Nodes(query_results) + } + FilterExpression::RootQuery { query } => { + let mut query_results = Vec::new(); + evaluate_segment(root, &query.segments, &mut query_results); + ExprValue::Nodes(query_results) + } + FilterExpression::Function { name, args } => eval_function(root, current, name, args), + } +} + +#[inline] +fn eval_function( + root: &dyn PathValue, + current: &dyn PathValue, + name: &str, + args: &[FilterExpression], +) -> ExprValue { + match name { + "count" if args.len() == 1 => { + let arg = eval_expr(root, current, &args[0]); + if let ExprValue::Nodes(ns) = arg { + ExprValue::Value(LoroValue::I64(ns.len() as i64)) + } else { + ExprValue::Value(LoroValue::I64(0)) + } + } + "length" if args.len() == 1 => { + let arg = eval_expr(root, current, &args[0]); + if let ExprValue::Value(v) = arg { + let len = match v { + LoroValue::List(l) => l.len(), + LoroValue::Map(m) => m.len(), + LoroValue::String(s) => s.len(), + _ => 0, + }; + ExprValue::Value(LoroValue::I64(len as i64)) + } else { + ExprValue::Value(LoroValue::I64(0)) + } + } + "value" if args.len() == 1 => { + let arg = eval_expr(root, current, &args[0]); + if let ExprValue::Nodes(ns) = arg { + if ns.len() == 1 { + match &ns[0] { + ValueOrHandler::Value(v) => ExprValue::Value(v.clone()), + ValueOrHandler::Handler(h) => ExprValue::Value(h.get_value()), + } + } else { + ExprValue::Value(LoroValue::Null) + } + } else { + ExprValue::Value(LoroValue::Null) + } + } + "match" => { + unimplemented!("JSONPath function `match()` is declared but not implemented"); + } + "search" => { + unimplemented!("JSONPath function `search()` is declared but not implemented"); + } + other => { + unimplemented!( + "JSONPath function `{}` is declared but does not have an evaluator", + other + ); + } + } +} + +#[inline(always)] +fn to_logical(v: ExprValue) -> bool { + match v { + ExprValue::Bool(b) => b, + ExprValue::Value(v) => match v { + LoroValue::Bool(b) => b, + LoroValue::Null => false, + LoroValue::String(s) => !s.is_empty(), + LoroValue::I64(0) => false, + LoroValue::I64(_) => true, + LoroValue::Double(f) => f != 0.0 && !f.is_nan(), + LoroValue::List(l) => !l.is_empty(), + LoroValue::Map(m) => !m.is_empty(), + _ => false, + }, + ExprValue::Nodes(ns) => !ns.is_empty(), + } +} + +#[inline] +fn compare_expr(l: ExprValue, op: &ComparisonOperator, r: ExprValue) -> bool { + match (l, r) { + (ExprValue::Value(l), ExprValue::Value(r)) => compare_values(&l, op, &r), + (ExprValue::Value(l), ExprValue::Bool(r)) => compare_values(&l, op, &LoroValue::Bool(r)), + (ExprValue::Bool(l), ExprValue::Value(r)) => compare_values(&LoroValue::Bool(l), op, &r), + (ExprValue::Bool(l), ExprValue::Bool(r)) => compare_bools(l, op, r), + (ExprValue::Nodes(ls), ExprValue::Nodes(rs)) => { + // Optimized: check if either is empty first + if ls.is_empty() || rs.is_empty() { + return false; + } + ls.iter().any(|a| { + let a_val = get_value(a); + rs.iter().any(|b| compare_values(&a_val, op, &get_value(b))) + }) + } + (ExprValue::Nodes(ls), v) => { + if ls.is_empty() { + return false; + } + let r_val = get_other_value(&v); + ls.iter().any(|a| compare_values(&get_value(a), op, &r_val)) + } + (v, ExprValue::Nodes(rs)) => { + if rs.is_empty() { + return false; + } + let l_val = get_other_value(&v); + rs.iter().any(|b| compare_values(&l_val, op, &get_value(b))) + } + } +} + +#[inline(always)] +fn compare_values(l: &LoroValue, op: &ComparisonOperator, r: &LoroValue) -> bool { + match op { + ComparisonOperator::In => { + if let LoroValue::List(list) = r { + list.iter() + .any(|item| compare_values(l, &ComparisonOperator::Eq, item)) + } else { + false + } + } + _ => match (l, r) { + (LoroValue::Double(a), LoroValue::Double(b)) => compare_nums(*a, op, *b), + (LoroValue::I64(a), LoroValue::I64(b)) => compare_i64(*a, op, *b), + (LoroValue::Double(a), LoroValue::I64(b)) => compare_nums(*a, op, *b as f64), + (LoroValue::I64(a), LoroValue::Double(b)) => compare_nums(*a as f64, op, *b), + (LoroValue::String(a), LoroValue::String(b)) => { + compare_strs(a.as_ref(), op, b.as_ref()) + } + (LoroValue::Bool(a), LoroValue::Bool(b)) => compare_bools(*a, op, *b), + (LoroValue::Null, LoroValue::Null) => matches!(op, ComparisonOperator::Eq), + _ => false, + }, + } +} + +#[inline(always)] +fn compare_i64(a: i64, op: &ComparisonOperator, b: i64) -> bool { + match op { + ComparisonOperator::Eq => a == b, + ComparisonOperator::Ne => a != b, + ComparisonOperator::Lt => a < b, + ComparisonOperator::Le => a <= b, + ComparisonOperator::Gt => a > b, + ComparisonOperator::Ge => a >= b, + _ => false, + } +} + +#[inline(always)] +fn compare_nums(a: f64, op: &ComparisonOperator, b: f64) -> bool { + match op { + ComparisonOperator::Eq => (a - b).abs() < f64::EPSILON, + ComparisonOperator::Ne => (a - b).abs() >= f64::EPSILON, + ComparisonOperator::Lt => a < b, + ComparisonOperator::Le => a <= b, + ComparisonOperator::Gt => a > b, + ComparisonOperator::Ge => a >= b, + _ => false, + } +} + +#[inline(always)] +fn compare_strs(a: &str, op: &ComparisonOperator, b: &str) -> bool { + match op { + ComparisonOperator::Eq => a == b, + ComparisonOperator::Ne => a != b, + ComparisonOperator::Lt => a < b, + ComparisonOperator::Le => a <= b, + ComparisonOperator::Gt => a > b, + ComparisonOperator::Ge => a >= b, + ComparisonOperator::Contains => a.contains(b), + _ => false, + } +} + +#[inline(always)] +fn compare_bools(a: bool, op: &ComparisonOperator, b: bool) -> bool { + match op { + ComparisonOperator::Eq => a == b, + ComparisonOperator::Ne => a != b, + _ => false, + } +} + +#[inline(always)] +fn get_value(node: &ValueOrHandler) -> LoroValue { + match node { + ValueOrHandler::Value(v) => v.clone(), + ValueOrHandler::Handler(h) => h.get_value(), + } +} + +#[inline(always)] +fn get_other_value(v: &ExprValue) -> LoroValue { + match v { + ExprValue::Value(v) => v.clone(), + ExprValue::Bool(b) => LoroValue::Bool(*b), + _ => LoroValue::Null, + } +} + +// Implement necessary trait bounds for PathValue +pub trait PathValue { + fn get_by_key(&self, key: &str) -> Option<ValueOrHandler>; + fn get_by_index(&self, index: isize) -> Option<ValueOrHandler>; + fn for_each_for_path(&self, f: &mut dyn FnMut(ValueOrHandler) -> ControlFlow<()>); + fn length_for_path(&self) -> usize; + fn get_child_by_id(&self, id: ContainerID) -> Option<Handler>; + fn clone_this(&self) -> Result<ValueOrHandler, JsonPathError>; +} + +// Implement PathValue for ValueOrHandler +impl PathValue for ValueOrHandler { + fn get_by_key(&self, key: &str) -> Option<ValueOrHandler> { + match self { + ValueOrHandler::Value(v) => v.get_by_key(key).cloned().map(ValueOrHandler::Value), + ValueOrHandler::Handler(h) => h.get_by_key(key), + } + } + + fn get_by_index(&self, index: isize) -> Option<ValueOrHandler> { + match self { + ValueOrHandler::Value(v) => v.get_by_index(index).cloned().map(ValueOrHandler::Value), + ValueOrHandler::Handler(h) => h.get_by_index(index), + } + } + + fn for_each_for_path(&self, f: &mut dyn FnMut(ValueOrHandler) -> ControlFlow<()>) { + match self { + ValueOrHandler::Value(v) => v.for_each_for_path(f), + ValueOrHandler::Handler(h) => h.for_each_for_path(f), + } + } + + fn length_for_path(&self) -> usize { + match self { + ValueOrHandler::Value(v) => v.length_for_path(), + ValueOrHandler::Handler(h) => h.length_for_path(), + } + } + + fn get_child_by_id(&self, id: ContainerID) -> Option<Handler> { + match self { + ValueOrHandler::Handler(h) => h.get_child_by_id(id), + _ => None, + } + } + + fn clone_this(&self) -> Result<ValueOrHandler, JsonPathError> { + match self { + ValueOrHandler::Value(v) => Ok(ValueOrHandler::Value(v.clone())), + ValueOrHandler::Handler(h) => Ok(ValueOrHandler::Handler(h.clone())), + } + } +} + +// Implement PathValue for LoroDoc +impl PathValue for LoroDoc { + fn get_by_key(&self, key: &str) -> Option<ValueOrHandler> { + self.get_by_str_path(key) + } + + fn get_by_index(&self, _index: isize) -> Option<ValueOrHandler> { + None // LoroDoc doesn't support index-based access + } + + fn for_each_for_path(&self, f: &mut dyn FnMut(ValueOrHandler) -> ControlFlow<()>) { + let roots = self.state.lock().preferred_root_containers(); + let arena = self.arena(); + for c in roots { + let cid = arena.idx_to_id(c).unwrap(); + let h = self.get_handler(cid).unwrap(); + if f(ValueOrHandler::Handler(h)) == ControlFlow::Break(()) { + break; + } + } + } + + fn length_for_path(&self) -> usize { + self.state.lock().preferred_root_containers().len() + } + + fn get_child_by_id(&self, id: ContainerID) -> Option<Handler> { + self.get_handler(id) + } + + fn clone_this(&self) -> Result<ValueOrHandler, JsonPathError> { + Ok(ValueOrHandler::Value(self.get_deep_value())) + } +} + +// Implement PathValue for Handler +impl PathValue for Handler { + fn get_by_key(&self, key: &str) -> Option<ValueOrHandler> { + match self { + Handler::Map(h) => h.get_by_key(key), + Handler::Tree(h) => h.get_by_key(key), + _ => None, + } + } + + fn get_by_index(&self, index: isize) -> Option<ValueOrHandler> { + match self { + Handler::List(h) => h.get_by_index(index), + Handler::MovableList(h) => h.get_by_index(index), + _ => None, + } + } + + fn for_each_for_path(&self, f: &mut dyn FnMut(ValueOrHandler) -> ControlFlow<()>) { + match self { + Handler::Map(h) => h.for_each_for_path(f), + Handler::List(h) => h.for_each_for_path(f), + Handler::MovableList(h) => h.for_each_for_path(f), + Handler::Tree(h) => h.for_each_for_path(f), + _ => {} + } + } + + fn length_for_path(&self) -> usize { + match self { + Handler::Map(h) => h.length_for_path(), + Handler::List(h) => h.length_for_path(), + Handler::MovableList(h) => h.length_for_path(), + Handler::Tree(h) => h.length_for_path(), + Handler::Text(h) => h.length_for_path(), + _ => 0, + } + } + + fn get_child_by_id(&self, id: ContainerID) -> Option<Handler> { + match self { + Handler::Map(h) => h.get_child_by_id(id), + Handler::List(h) => h.get_child_by_id(id), + Handler::MovableList(h) => h.get_child_by_id(id), + Handler::Tree(h) => h.get_child_by_id(id), + _ => None, + } + } + + fn clone_this(&self) -> Result<ValueOrHandler, JsonPathError> { + Ok(ValueOrHandler::Handler(self.clone())) + } +} + +// Implementations for specific handlers +impl PathValue for MapHandler { + fn get_by_key(&self, key: &str) -> Option<ValueOrHandler> { + self.get_(key) + } + + fn get_by_index(&self, _index: isize) -> Option<ValueOrHandler> { + None + } + + fn for_each_for_path(&self, f: &mut dyn FnMut(ValueOrHandler) -> ControlFlow<()>) { + let mut done = false; + self.for_each(|_, v| { + if done { + return; + } + + if let ControlFlow::Break(_) = f(v) { + done = true; + } + }); + } + + fn length_for_path(&self) -> usize { + self.len() + } + + fn get_child_by_id(&self, id: ContainerID) -> Option<Handler> { + self.get_child_handler(id.to_string().as_str()).ok() + } + + fn clone_this(&self) -> Result<ValueOrHandler, JsonPathError> { + Ok(ValueOrHandler::Handler(Handler::Map(self.clone()))) + } +} + +impl PathValue for ListHandler { + fn get_by_key(&self, _key: &str) -> Option<ValueOrHandler> { + None + } + + fn get_by_index(&self, index: isize) -> Option<ValueOrHandler> { + if index < 0 { + self.get_(self.len() - (-index) as usize) + } else { + self.get_(index as usize) + } + } + + fn for_each_for_path(&self, f: &mut dyn FnMut(ValueOrHandler) -> ControlFlow<()>) { + let mut done = false; + self.for_each(|v| { + if done { + return; + } + + if let ControlFlow::Break(_) = f(v) { + done = true; + } + }); + } + + fn length_for_path(&self) -> usize { + self.len() + } + + fn get_child_by_id(&self, _id: ContainerID) -> Option<Handler> { + unimplemented!() + } + + fn clone_this(&self) -> Result<ValueOrHandler, JsonPathError> { + Ok(ValueOrHandler::Handler(Handler::List(self.clone()))) + } +} + +impl PathValue for MovableListHandler { + fn get_by_key(&self, _key: &str) -> Option<ValueOrHandler> { + None + } + + fn get_by_index(&self, index: isize) -> Option<ValueOrHandler> { + if index < 0 { + if self.len() > (-index) as usize { + self.get_(self.len() - (-index) as usize) + } else { + None + } + } else { + self.get_(index as usize) + } + } + + fn for_each_for_path(&self, f: &mut dyn FnMut(ValueOrHandler) -> ControlFlow<()>) { + let mut done = false; + self.for_each(|v| { + if done { + return; + } + + if let ControlFlow::Break(_) = f(v) { + done = true; + } + }) + } + + fn length_for_path(&self) -> usize { + self.len() + } + + fn get_child_by_id(&self, _id: ContainerID) -> Option<Handler> { + unimplemented!() + } + + fn clone_this(&self) -> Result<ValueOrHandler, JsonPathError> { + Ok(ValueOrHandler::Handler(Handler::MovableList(self.clone()))) + } +} + +impl PathValue for TextHandler { + fn get_by_key(&self, _key: &str) -> Option<ValueOrHandler> { + None + } + + fn get_by_index(&self, _index: isize) -> Option<ValueOrHandler> { + None + } + + fn for_each_for_path(&self, _f: &mut dyn FnMut(ValueOrHandler) -> ControlFlow<()>) { + // TextHandler doesn't have children to iterate over + } + + fn length_for_path(&self) -> usize { + self.len_unicode() + } + + fn get_child_by_id(&self, _id: ContainerID) -> Option<Handler> { + None + } + + fn clone_this(&self) -> Result<ValueOrHandler, JsonPathError> { + Ok(ValueOrHandler::Handler(Handler::Text(self.clone()))) + } +} + +impl PathValue for TreeHandler { + fn get_by_key(&self, _key: &str) -> Option<ValueOrHandler> { + None + } + + fn get_by_index(&self, _index: isize) -> Option<ValueOrHandler> { + None + } + + fn for_each_for_path(&self, _f: &mut dyn FnMut(ValueOrHandler) -> ControlFlow<()>) { + unimplemented!() + } + + fn length_for_path(&self) -> usize { + unimplemented!() + } + + fn get_child_by_id(&self, _id: ContainerID) -> Option<Handler> { + unimplemented!() + } + + fn clone_this(&self) -> Result<ValueOrHandler, JsonPathError> { + Ok(ValueOrHandler::Handler(Handler::Tree(self.clone()))) + } +} + +impl PathValue for LoroValue { + fn get_by_key(&self, key: &str) -> Option<ValueOrHandler> { + match self { + LoroValue::Map(map) => map.get(key).map(|v| ValueOrHandler::Value(v.clone())), + _ => None, + } + } + + fn get_by_index(&self, index: isize) -> Option<ValueOrHandler> { + match self { + LoroValue::List(list) => { + let index = if index < 0 { + if list.len() > (-index) as usize { + list.len() - (-index) as usize + } else { + return None; + } + } else { + index as usize + }; + list.get(index).map(|v| ValueOrHandler::Value(v.clone())) + } + _ => None, + } + } + + fn for_each_for_path(&self, f: &mut dyn FnMut(ValueOrHandler) -> ControlFlow<()>) { + match self { + LoroValue::List(list) => { + for item in list.iter() { + if let ControlFlow::Break(_) = f(ValueOrHandler::Value(item.clone())) { + break; + } + } + } + LoroValue::Map(map) => { + for (_, value) in map.iter() { + if let ControlFlow::Break(_) = f(ValueOrHandler::Value(value.clone())) { + break; + } + } + } + _ => {} + } + } + + fn length_for_path(&self) -> usize { + match self { + LoroValue::List(list) => list.len(), + LoroValue::Map(map) => map.len(), + LoroValue::String(s) => s.len(), + _ => 0, + } + } + + fn get_child_by_id(&self, _id: ContainerID) -> Option<Handler> { + None + } + + fn clone_this(&self) -> Result<ValueOrHandler, JsonPathError> { + Ok(ValueOrHandler::Value(self.clone())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ListHandler, LoroDoc, LoroValue, MapHandler}; + + fn setup_test_doc() -> LoroDoc { + let doc = LoroDoc::new(); + doc.start_auto_commit(); + let store = doc.get_map("store"); + let books = store + .insert_container("books", ListHandler::new_detached()) + .unwrap(); + + // Book 1: 1984 + let book = books + .insert_container(0, MapHandler::new_detached()) + .unwrap(); + book.insert("title", "1984").unwrap(); + book.insert("author", "George Orwell").unwrap(); + book.insert("price", 10).unwrap(); + book.insert("available", true).unwrap(); + book.insert("isbn", "978-0451524935").unwrap(); + + // Book 2: Animal Farm + let book = books + .insert_container(1, MapHandler::new_detached()) + .unwrap(); + book.insert("title", "Animal Farm").unwrap(); + book.insert("author", "George Orwell").unwrap(); + book.insert("price", 8).unwrap(); + book.insert("available", true).unwrap(); + + // Book 3: Brave New World + let book = books + .insert_container(2, MapHandler::new_detached()) + .unwrap(); + book.insert("title", "Brave New World").unwrap(); + book.insert("author", "Aldous Huxley").unwrap(); + book.insert("price", 12).unwrap(); + book.insert("available", false).unwrap(); + book.insert("isbn", "978-0060850524").unwrap(); + + // Book 4: Fahrenheit 451 + let book = books + .insert_container(3, MapHandler::new_detached()) + .unwrap(); + book.insert("title", "Fahrenheit 451").unwrap(); + book.insert("author", "Ray Bradbury").unwrap(); + book.insert("price", 9).unwrap(); + book.insert("available", true).unwrap(); + book.insert("isbn", "978-1451673319").unwrap(); + + // Book 5: The Great Gatsby + let book = books + .insert_container(4, MapHandler::new_detached()) + .unwrap(); + book.insert("title", "The Great Gatsby").unwrap(); + book.insert("author", "F. Scott Fitzgerald").unwrap(); + book.insert("price", LoroValue::Null).unwrap(); + book.insert("available", true).unwrap(); + + // Book 6: To Kill a Mockingbird + let book = books + .insert_container(5, MapHandler::new_detached()) + .unwrap(); + book.insert("title", "To Kill a Mockingbird").unwrap(); + book.insert("author", "Harper Lee").unwrap(); + book.insert("price", 11).unwrap(); + book.insert("available", true).unwrap(); + + // Book 7: The Catcher in the Rye + let book = books + .insert_container(6, MapHandler::new_detached()) + .unwrap(); + book.insert("title", "The Catcher in the Rye").unwrap(); + book.insert("author", "J.D. Salinger").unwrap(); + book.insert("price", 10).unwrap(); + book.insert("available", false).unwrap(); + + // Book 8: Lord of the Flies + let book = books + .insert_container(7, MapHandler::new_detached()) + .unwrap(); + book.insert("title", "Lord of the Flies").unwrap(); + book.insert("author", "William Golding").unwrap(); + book.insert("price", 9).unwrap(); + book.insert("available", true).unwrap(); + + // Book 9: Pride and Prejudice + let book = books + .insert_container(8, MapHandler::new_detached()) + .unwrap(); + book.insert("title", "Pride and Prejudice").unwrap(); + book.insert("author", "Jane Austen").unwrap(); + book.insert("price", 7).unwrap(); + book.insert("available", true).unwrap(); + + // Book 10: The Hobbit + let book = books + .insert_container(9, MapHandler::new_detached()) + .unwrap(); + book.insert("title", "The Hobbit").unwrap(); + book.insert("author", "J.R.R. Tolkien").unwrap(); + book.insert("price", 14).unwrap(); + book.insert("available", true).unwrap(); + + // Additional metadata + store.insert("featured_author", "George Orwell").unwrap(); + let featured_authors = store + .insert_container("featured_authors", ListHandler::new_detached()) + .unwrap(); + featured_authors.push("George Orwell").unwrap(); + featured_authors.push("Aldous Huxley").unwrap(); + featured_authors.push("Ray Bradbury").unwrap(); + store.insert("min_price", 10).unwrap(); + doc + } + + mod jsonpath_selectors { + use super::*; + + #[test] + fn handles_child_selectors() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[0].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 1); + assert_eq!( + &**result[0].as_value().unwrap().as_string().unwrap(), + "1984" + ); + Ok(()) + } + + #[test] + fn handles_wildcard_selector() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[*].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 10); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec![ + "1984", + "Animal Farm", + "Brave New World", + "Fahrenheit 451", + "The Great Gatsby", + "To Kill a Mockingbird", + "The Catcher in the Rye", + "Lord of the Flies", + "Pride and Prejudice", + "The Hobbit", + ]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + + #[test] + fn handles_recursive_descent() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$..title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 10); + Ok(()) + } + + #[test] + fn handles_quoted_keys() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store['books'][0]['title']"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 1); + assert_eq!( + &**result[0].as_value().unwrap().as_string().unwrap(), + "1984" + ); + Ok(()) + } + } + + mod string_filters { + use super::*; + + #[test] + fn filters_by_exact_string_match() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.title == '1984')].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 1); + assert_eq!( + &**result[0].as_value().unwrap().as_string().unwrap(), + "1984" + ); + Ok(()) + } + + #[test] + fn filters_by_string_contains() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.title contains 'Farm')].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 1); + assert_eq!( + &**result[0].as_value().unwrap().as_string().unwrap(), + "Animal Farm" + ); + Ok(()) + } + + #[test] + fn filters_by_recursive_string_match() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$..[?(@.author contains 'Orwell')].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 2); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec!["1984", "Animal Farm"]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + } + + mod logical_operators { + use super::*; + + #[test] + fn filters_with_and_operator() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.author == 'George Orwell' && @.price < 10)].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 1); + assert_eq!( + &**result[0].as_value().unwrap().as_string().unwrap(), + "Animal Farm" + ); + Ok(()) + } + + #[test] + fn filters_with_or_operator() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.author == 'George Orwell' || @.price >= 10)].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 6); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec![ + "1984", + "Animal Farm", + "Brave New World", + "To Kill a Mockingbird", + "The Catcher in the Rye", + "The Hobbit", + ]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + + #[test] + fn filters_with_complex_and_or_combination() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.author == 'George Orwell' && (@.price < 10 || @.available == true))].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 2); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec!["1984", "Animal Farm"]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + + #[test] + fn filters_with_not_operator() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(!(@.available == false))].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 8); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec![ + "1984", + "Animal Farm", + "Fahrenheit 451", + "The Great Gatsby", + "To Kill a Mockingbird", + "Lord of the Flies", + "Pride and Prejudice", + "The Hobbit", + ]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + } + + mod in_operator { + use super::*; + + #[test] + fn filters_by_author_in_list() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.author in ['George Orwell', 'Jane Austen'])].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 3); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec!["1984", "Animal Farm", "Pride and Prejudice"]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + + #[test] + fn filters_by_price_in_list() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.price in [7, 10, 14])].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 4); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec![ + "1984", + "Pride and Prejudice", + "The Catcher in the Rye", + "The Hobbit", + ]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + + #[test] + fn filters_with_in_operator_and_null_values() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.price in [null, 9])].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 3); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec!["Fahrenheit 451", "Lord of the Flies", "The Great Gatsby"]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + + #[test] + fn filters_with_in_operator_in_recursive_descent() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$..[?(@.author in ['George Orwell', 'Ray Bradbury'])].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 3); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec!["1984", "Animal Farm", "Fahrenheit 451"]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + + #[test] + fn filters_with_root_list_in() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.author in $.store.featured_authors)].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 4); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec!["1984", "Animal Farm", "Brave New World", "Fahrenheit 451"]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + } + + mod union_and_slice_operations { + use super::*; + + #[test] + fn handles_union_indexes() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[0,2].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 2); + assert_eq!( + &**result[0].as_value().unwrap().as_string().unwrap(), + "1984" + ); + assert_eq!( + &**result[1].as_value().unwrap().as_string().unwrap(), + "Brave New World" + ); + Ok(()) + } + + #[test] + fn handles_union_keys() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[0]['title','author']"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 2); + assert_eq!( + &**result[0].as_value().unwrap().as_string().unwrap(), + "1984" + ); + assert_eq!( + &**result[1].as_value().unwrap().as_string().unwrap(), + "George Orwell" + ); + Ok(()) + } + + #[test] + fn handles_union_with_negative_indexes() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[-2,-1].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 2); + assert_eq!( + &**result[0].as_value().unwrap().as_string().unwrap(), + "Pride and Prejudice" + ); + assert_eq!( + &**result[1].as_value().unwrap().as_string().unwrap(), + "The Hobbit" + ); + Ok(()) + } + + #[test] + fn handles_basic_slice() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[0:3].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 3); + let titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + assert_eq!(titles, vec!["1984", "Animal Farm", "Brave New World"]); + Ok(()) + } + + #[test] + fn handles_slice_with_step() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[0:5:2].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 3); + let titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + assert_eq!(titles, vec!["1984", "Brave New World", "The Great Gatsby"]); + Ok(()) + } + + #[test] + fn handles_negative_slice() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[-2:].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 2); + let titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + assert_eq!(titles, vec!["Pride and Prejudice", "The Hobbit"]); + Ok(()) + } + } + + mod complex_and_recursive_filters { + use super::*; + + #[test] + fn filters_with_multiple_conditions() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.price >= 10 && @.available == true && @.title contains '1984')].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 1); + assert_eq!( + &**result[0].as_value().unwrap().as_string().unwrap(), + "1984" + ); + Ok(()) + } + + #[test] + fn filters_with_path_expressions() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.author == 'George Orwell' && @.title != '1984')].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 1); + assert_eq!( + &**result[0].as_value().unwrap().as_string().unwrap(), + "Animal Farm" + ); + Ok(()) + } + + #[test] + fn filters_with_null_checks() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.price == null || @.price < 10)].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 5); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec![ + "Animal Farm", + "Fahrenheit 451", + "The Great Gatsby", + "Pride and Prejudice", + "Lord of the Flies", + ]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + + #[test] + fn handles_recursive_filter_with_price_condition() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$..[?(@.price > 10)].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 3); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec!["Brave New World", "To Kill a Mockingbird", "The Hobbit"]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + + #[test] + fn handles_recursive_filter_with_logical_operators() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$..[?(@.author == 'George Orwell' || @.price > 10)].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 5); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec![ + "1984", + "Animal Farm", + "Brave New World", + "To Kill a Mockingbird", + "The Hobbit", + ]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + } + + mod edge_cases_and_error_handling { + use super::*; + + #[test] + fn handles_quoted_keys_with_special_characters() -> Result<(), JsonPathError> { + let doc = LoroDoc::new(); + doc.start_auto_commit(); + let map = doc.get_map("store"); + let book = map + .insert_container("book-with-dash", MapHandler::new_detached()) + .unwrap(); + book.insert("price-$10", "cheap").unwrap(); + let path = "$['store']['book-with-dash']['price-$10']"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 1); + assert_eq!( + &**result[0].as_value().unwrap().as_string().unwrap(), + "cheap" + ); + Ok(()) + } + + #[test] + fn handles_quoted_keys_with_escaped_quotes() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.author == 'George Orwell')].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 2); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec!["1984", "Animal Farm"]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + } + + mod root_filters { + use super::*; + + #[test] + fn filters_with_root_reference() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.author == $.store.featured_author)].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 2); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec!["1984", "Animal Farm"]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + + #[test] + fn filters_with_root_numerical_comparison() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.price > $.store.min_price)].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 3); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec!["Brave New World", "The Hobbit", "To Kill a Mockingbird"]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + + #[test] + fn filters_with_root_not_equal() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.author != $.store.featured_author)].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 8); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec![ + "Brave New World", + "Fahrenheit 451", + "The Great Gatsby", + "To Kill a Mockingbird", + "The Catcher in the Rye", + "Lord of the Flies", + "Pride and Prejudice", + "The Hobbit", + ]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + + #[test] + fn filters_with_root_complex() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.author == $.store.featured_author && @.price <= $.store.min_price)].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 2); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec!["1984", "Animal Farm"]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + } + + mod existence_filters { + use super::*; + #[test] + fn filters_by_existence_of_isbn() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.isbn)].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 3); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec!["1984", "Brave New World", "Fahrenheit 451"]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + + #[test] + fn filters_by_non_existence_of_isbn() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(!@.isbn)].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 7); + let mut titles: Vec<&str> = result + .iter() + .map(|v| v.as_value().unwrap().as_string().unwrap().as_str()) + .collect(); + titles.sort(); + let mut expected = vec![ + "Animal Farm", + "The Great Gatsby", + "To Kill a Mockingbird", + "The Catcher in the Rye", + "Lord of the Flies", + "Pride and Prejudice", + "The Hobbit", + ]; + expected.sort(); + assert_eq!(titles, expected); + Ok(()) + } + + #[test] + fn filters_by_existence_of_price() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(@.price)].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 10); + Ok(()) + } + + #[test] + fn filters_by_non_existence_of_price() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?(!@.price)].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 0); + Ok(()) + } + + #[test] + fn filters_by_non_existence_of_root_path() -> Result<(), JsonPathError> { + let doc = setup_test_doc(); + let path = "$.store.books[?($.store.nonexistent)].title"; + let result = evaluate_jsonpath(&doc, path)?; + assert_eq!(result.len(), 0); + Ok(()) + } + } +} diff --git a/vendor/loro-internal/src/jsonpath/mod.rs b/vendor/loro-internal/src/jsonpath/mod.rs new file mode 100644 index 0000000..9bbcdee --- /dev/null +++ b/vendor/loro-internal/src/jsonpath/mod.rs @@ -0,0 +1,10 @@ +pub mod ast; +pub mod errors; +pub mod jsonpath_impl; +pub mod subscription; + +pub use subscription::SubscribeJsonPathCallback; +pub mod parser; + +pub use ast::Query; +pub use parser::JSONPathParser; diff --git a/vendor/loro-internal/src/jsonpath/parser.rs b/vendor/loro-internal/src/jsonpath/parser.rs new file mode 100644 index 0000000..60425fe --- /dev/null +++ b/vendor/loro-internal/src/jsonpath/parser.rs @@ -0,0 +1,708 @@ +//! A JSONPath parser using [pest]. +//! +//! Refer to `jsonpath.pest` and the [pest book]. +//! +//! [pest]: https://pest.rs/ +//! [pest book]: https://pest.rs/book/ + +use std::{collections::HashMap, ops::RangeInclusive}; + +use pest::{iterators::Pair, Parser}; +use pest_derive::Parser; + +use crate::jsonpath::ast::{ + ComparisonOperator, FilterExpression, LogicalOperator, Segment, Selector, +}; +use crate::jsonpath::errors::JSONPathError; +use crate::jsonpath::Query; + +#[derive(Parser)] +#[grammar = "jsonpath/jsonpath.pest"] +struct JSONPath; + +#[derive(Debug)] +pub enum ExpressionType { + Logical, + Nodes, + Value, +} + +#[derive(Debug)] +pub struct FunctionSignature { + pub param_types: Vec<ExpressionType>, + pub return_type: ExpressionType, +} + +pub fn standard_functions() -> HashMap<String, FunctionSignature> { + let mut functions = HashMap::new(); + + functions.insert( + "count".to_owned(), + FunctionSignature { + param_types: vec![ExpressionType::Nodes], + return_type: ExpressionType::Value, + }, + ); + + functions.insert( + "length".to_owned(), + FunctionSignature { + param_types: vec![ExpressionType::Value], + return_type: ExpressionType::Value, + }, + ); + + functions.insert( + "match".to_owned(), + FunctionSignature { + param_types: vec![ExpressionType::Value, ExpressionType::Value], + return_type: ExpressionType::Logical, + }, + ); + + functions.insert( + "search".to_owned(), + FunctionSignature { + param_types: vec![ExpressionType::Value, ExpressionType::Value], + return_type: ExpressionType::Logical, + }, + ); + + functions.insert( + "value".to_owned(), + FunctionSignature { + param_types: vec![ExpressionType::Nodes], + return_type: ExpressionType::Value, + }, + ); + + functions +} + +#[derive(Debug)] +pub struct JSONPathParser { + pub index_range: RangeInclusive<i64>, + pub function_signatures: HashMap<String, FunctionSignature>, +} + +impl Default for JSONPathParser { + fn default() -> Self { + Self::new() + } +} + +impl JSONPathParser { + pub fn new() -> Self { + JSONPathParser { + index_range: ((-2_i64).pow(53) + 1..=2_i64.pow(53) - 1), + function_signatures: standard_functions(), + } + } + + pub fn add_function( + &mut self, + name: &str, + params: Vec<ExpressionType>, + returns: ExpressionType, + ) { + self.function_signatures.insert( + name.to_owned(), + FunctionSignature { + param_types: params, + return_type: returns, + }, + ); + } + + pub fn parse(&self, query: &str) -> Result<Query, JSONPathError> { + let segments = JSONPath::parse(Rule::jsonpath, query) + .map_err(|err| JSONPathError::syntax(err.to_string()))? + .try_fold(Segment::Root {}, |acc, segment| { + self.parse_segment(acc, segment) + })?; + Ok(Query { segments }) + } + + fn parse_segment(&self, acc: Segment, segment: Pair<Rule>) -> Result<Segment, JSONPathError> { + Ok(match segment.as_rule() { + Rule::child_segment => Segment::Child { + left: Box::new(acc), + selectors: self.parse_segment_inner(segment.into_inner().next().unwrap())?, + }, + Rule::descendant_segment => Segment::Recursive { + left: Box::new(acc), + selectors: self.parse_segment_inner(segment.into_inner().next().unwrap())?, + }, + Rule::name_segment | Rule::index_segment => Segment::Child { + left: Box::new(acc), + selectors: vec![self.parse_selector(segment.into_inner().next().unwrap())?], + }, + Rule::EOI => acc, + _ => unreachable!(), + }) + } + + fn parse_segment_inner(&self, segment: Pair<Rule>) -> Result<Vec<Selector>, JSONPathError> { + Ok(match segment.as_rule() { + Rule::bracketed_selection => { + let seg: Result<Vec<_>, _> = segment + .into_inner() + .map(|selector| self.parse_selector(selector)) + .collect(); + seg? + } + Rule::wildcard_selector => vec![Selector::Wild {}], + Rule::member_name_shorthand => vec![Selector::Name { + // for child_segment name: + name: segment.as_str().to_owned(), + }], + _ => unreachable!(), + }) + } + + fn parse_selector(&self, selector: Pair<Rule>) -> Result<Selector, JSONPathError> { + Ok(match selector.as_rule() { + Rule::double_quoted => Selector::Name { + name: unescape_string(selector.as_str()), + }, + Rule::single_quoted => Selector::Name { + name: unescape_string(&selector.as_str().replace("\\'", "'")), + }, + Rule::wildcard_selector => Selector::Wild {}, + Rule::slice_selector => self.parse_slice_selector(selector)?, + Rule::index_selector => Selector::Index { + index: self.parse_i_json_int(selector.as_str())?, + }, + Rule::filter_selector => self.parse_filter_selector(selector)?, + Rule::member_name_shorthand => Selector::Name { + // for name_segment name: + name: selector.as_str().to_owned(), + }, + _ => unreachable!(), + }) + } + + fn parse_slice_selector(&self, selector: Pair<Rule>) -> Result<Selector, JSONPathError> { + let mut start: Option<i64> = None; + let mut stop: Option<i64> = None; + let mut step: Option<i64> = None; + + for i in selector.into_inner() { + match i.as_rule() { + Rule::start => start = Some(self.parse_i_json_int(i.as_str())?), + Rule::stop => stop = Some(self.parse_i_json_int(i.as_str())?), + Rule::step => step = Some(self.parse_i_json_int(i.as_str())?), + _ => unreachable!(), + } + } + + Ok(Selector::Slice { start, stop, step }) + } + + fn parse_filter_selector(&self, selector: Pair<Rule>) -> Result<Selector, JSONPathError> { + Ok(Selector::Filter { + expression: Box::new( + self.parse_logical_or_expression(selector.into_inner().next().unwrap(), true)?, + ), + }) + } + + fn parse_logical_or_expression( + &self, + expr: Pair<Rule>, + assert_compared: bool, + ) -> Result<FilterExpression, JSONPathError> { + let mut it = expr.into_inner(); + let mut or_expr = self.parse_logical_and_expression(it.next().unwrap(), assert_compared)?; + if assert_compared { + self.assert_compared(&or_expr)?; + } + for and_expr in it { + let right = self.parse_logical_and_expression(and_expr, assert_compared)?; + if assert_compared { + self.assert_compared(&right)?; + } + or_expr = FilterExpression::Logical { + left: Box::new(or_expr), + operator: LogicalOperator::Or, + right: Box::new(right), + }; + } + Ok(or_expr) + } + + fn parse_logical_and_expression( + &self, + expr: Pair<Rule>, + assert_compared: bool, + ) -> Result<FilterExpression, JSONPathError> { + let mut it = expr.into_inner(); + let mut and_expr = self.parse_basic_expression(it.next().unwrap())?; + if assert_compared { + self.assert_compared(&and_expr)?; + } + for basic_expr in it { + let right = self.parse_basic_expression(basic_expr)?; + if assert_compared { + self.assert_compared(&right)?; + } + and_expr = FilterExpression::Logical { + left: Box::new(and_expr), + operator: LogicalOperator::And, + right: Box::new(right), + }; + } + Ok(and_expr) + } + + fn parse_basic_expression(&self, expr: Pair<Rule>) -> Result<FilterExpression, JSONPathError> { + match expr.as_rule() { + Rule::paren_expr => self.parse_paren_expression(expr), + Rule::comparison_expr => self.parse_comparison_expression(expr), + Rule::test_expr => self.parse_test_expression(expr), + _ => unreachable!(), + } + } + + fn parse_paren_expression(&self, expr: Pair<Rule>) -> Result<FilterExpression, JSONPathError> { + let mut it = expr.into_inner(); + let p = it.next().unwrap(); + match p.as_rule() { + Rule::logical_not_op => Ok(FilterExpression::Not { + expression: Box::new(self.parse_logical_or_expression(it.next().unwrap(), true)?), + }), + Rule::logical_or_expr => self.parse_logical_or_expression(p, true), + _ => unreachable!(), + } + } + + fn parse_comparison_expression( + &self, + expr: Pair<Rule>, + ) -> Result<FilterExpression, JSONPathError> { + let mut it = expr.into_inner(); + let left = self.parse_comparable(it.next().unwrap())?; + let operator = match it.next().unwrap().as_str() { + "==" => ComparisonOperator::Eq, + "!=" => ComparisonOperator::Ne, + "<=" => ComparisonOperator::Le, + ">=" => ComparisonOperator::Ge, + "<" => ComparisonOperator::Lt, + ">" => ComparisonOperator::Gt, + "contains" => ComparisonOperator::Contains, + "in" => ComparisonOperator::In, + _ => unreachable!(), + }; + let right = self.parse_comparable(it.next().unwrap())?; + self.assert_comparable(&left)?; + self.assert_comparable(&right)?; + Ok(FilterExpression::Comparison { + left: Box::new(left), + operator, + right: Box::new(right), + }) + } + + fn parse_comparable(&self, expr: Pair<Rule>) -> Result<FilterExpression, JSONPathError> { + Ok(match expr.as_rule() { + Rule::number => self.parse_number(expr)?, + Rule::double_quoted => FilterExpression::StringLiteral { + value: unescape_string(expr.as_str()), + }, + Rule::single_quoted => FilterExpression::StringLiteral { + value: unescape_string(&expr.as_str().replace("\\'", "'")), + }, + Rule::true_literal => FilterExpression::True_ {}, + Rule::false_literal => FilterExpression::False_ {}, + Rule::null => FilterExpression::Null {}, + Rule::array_literal => self.parse_array_literal(expr)?, + Rule::rel_singular_query => { + let segments = expr + .into_inner() + .try_fold(Segment::Root {}, |acc, segment| { + self.parse_segment(acc, segment) + }); + FilterExpression::RelativeQuery { + query: Box::new(Query { + segments: segments?, + }), + } + } + Rule::abs_singular_query => { + let segments = expr + .into_inner() + .try_fold(Segment::Root {}, |acc, segment| { + self.parse_segment(acc, segment) + }); + FilterExpression::RootQuery { + query: Box::new(Query { + segments: segments?, + }), + } + } + Rule::function_expr => self.parse_function_expression(expr)?, + _ => unreachable!(), + }) + } + + fn parse_number(&self, expr: Pair<Rule>) -> Result<FilterExpression, JSONPathError> { + let raw = expr.as_str(); + if raw == "-0" { + return Ok(FilterExpression::Int { value: 0 }); + } + let is_float = raw.contains('.') || raw.contains('e') || raw.contains('E'); + if !is_float { + if let Ok(value) = raw.parse::<i64>() { + return Ok(FilterExpression::Int { value }); + } + } + Ok(FilterExpression::Float { + value: raw + .parse::<f64>() + .map_err(|_| JSONPathError::syntax(String::from("invalid float literal")))?, + }) + } + + fn parse_array_literal(&self, expr: Pair<Rule>) -> Result<FilterExpression, JSONPathError> { + let values: Result<Vec<_>, _> = expr + .into_inner() + .map(|p| self.parse_comparable(p)) + .collect(); + Ok(FilterExpression::Array { values: values? }) + } + + fn parse_test_expression(&self, expr: Pair<Rule>) -> Result<FilterExpression, JSONPathError> { + let mut it = expr.into_inner(); + let pair = it.next().unwrap(); + Ok(match pair.as_rule() { + Rule::logical_not_op => FilterExpression::Not { + expression: Box::new(self.parse_test_expression_inner(it.next().unwrap())?), + }, + _ => self.parse_test_expression_inner(pair)?, + }) + } + + fn parse_test_expression_inner( + &self, + expr: Pair<Rule>, + ) -> Result<FilterExpression, JSONPathError> { + Ok(match expr.as_rule() { + Rule::rel_query => { + let segments = expr + .into_inner() + .try_fold(Segment::Root {}, |acc, segment| { + self.parse_segment(acc, segment) + }); + FilterExpression::RelativeQuery { + query: Box::new(Query { + segments: segments?, + }), + } + } + Rule::root_query => { + let segments = expr + .into_inner() + .try_fold(Segment::Root {}, |acc, segment| { + self.parse_segment(acc, segment) + }); + FilterExpression::RootQuery { + query: Box::new(Query { + segments: segments?, + }), + } + } + Rule::function_expr => self.parse_function_expression(expr)?, + _ => unreachable!(), + }) + } + + fn parse_function_expression( + &self, + expr: Pair<Rule>, + ) -> Result<FilterExpression, JSONPathError> { + let mut it = expr.into_inner(); + let name = it.next().unwrap().as_str(); + let args: Result<Vec<_>, _> = it.map(|ex| self.parse_function_argument(ex)).collect(); + Ok(FilterExpression::Function { + name: name.to_string(), + args: self.assert_well_typed(name, args?)?, + }) + } + + fn parse_function_argument(&self, expr: Pair<Rule>) -> Result<FilterExpression, JSONPathError> { + Ok(match expr.as_rule() { + Rule::number => self.parse_number(expr)?, + Rule::double_quoted => FilterExpression::StringLiteral { + value: unescape_string(expr.as_str()), + }, + Rule::single_quoted => FilterExpression::StringLiteral { + value: unescape_string(&expr.as_str().replace("\\'", "'")), + }, + Rule::true_literal => FilterExpression::True_ {}, + Rule::false_literal => FilterExpression::False_ {}, + Rule::null => FilterExpression::Null {}, + Rule::array_literal => self.parse_array_literal(expr)?, + Rule::rel_query => { + let segments = expr + .into_inner() + .try_fold(Segment::Root {}, |acc, segment| { + self.parse_segment(acc, segment) + }); + FilterExpression::RelativeQuery { + query: Box::new(Query { + segments: segments?, + }), + } + } + Rule::root_query => { + let segments = expr + .into_inner() + .try_fold(Segment::Root {}, |acc, segment| { + self.parse_segment(acc, segment) + }); + FilterExpression::RootQuery { + query: Box::new(Query { + segments: segments?, + }), + } + } + Rule::logical_or_expr => self.parse_logical_or_expression(expr, false)?, + Rule::function_expr => self.parse_function_expression(expr)?, + _ => unreachable!(), + }) + } + + fn parse_i_json_int(&self, value: &str) -> Result<i64, JSONPathError> { + let i = value + .parse::<i64>() + .map_err(|_| JSONPathError::syntax(format!("index out of range `{}`", value)))?; + if !self.index_range.contains(&i) { + return Err(JSONPathError::syntax(format!( + "index out of range `{}`", + value + ))); + } + Ok(i) + } + + fn assert_comparable(&self, expr: &FilterExpression) -> Result<(), JSONPathError> { + // TODO: accept span/position for better errors + match expr { + FilterExpression::RelativeQuery { query, .. } + | FilterExpression::RootQuery { query, .. } => { + if !query.is_singular() { + Err(JSONPathError::typ(String::from( + "non-singular query is not comparable", + ))) + } else { + Ok(()) + } + } + FilterExpression::Function { name, .. } => { + if let Some(FunctionSignature { + return_type: ExpressionType::Value, + .. + }) = self.function_signatures.get(name) + { + Ok(()) + } else { + Err(JSONPathError::typ(format!( + "result of {}() is not comparable", + name + ))) + } + } + _ => Ok(()), + } + } + + fn assert_compared(&self, expr: &FilterExpression) -> Result<(), JSONPathError> { + match expr { + FilterExpression::Function { name, .. } => { + if let Some(FunctionSignature { + return_type: ExpressionType::Value, + .. + }) = self.function_signatures.get(name) + { + Err(JSONPathError::typ(format!( + "result of {}() must be compared", + name + ))) + } else { + Ok(()) + } + } + _ => Ok(()), + } + } + + fn assert_well_typed( + &self, + func_name: &str, + args: Vec<FilterExpression>, + ) -> Result<Vec<FilterExpression>, JSONPathError> { + // TODO: accept span/position for better errors + let signature = self + .function_signatures + .get(func_name) + .ok_or_else(|| JSONPathError::name(format!("unknown function `{}`", func_name)))?; + + // correct number of arguments? + if args.len() != signature.param_types.len() { + return Err(JSONPathError::typ(format!( + "{}() takes {} argument{} but {} were given", + func_name, + signature.param_types.len(), + if signature.param_types.len() > 1 { + "s" + } else { + "" + }, + args.len() + ))); + } + + // correct argument types? + for (idx, typ) in signature.param_types.iter().enumerate() { + let arg = &args[idx]; + match typ { + ExpressionType::Value => { + if !self.is_value_type(arg) { + return Err(JSONPathError::typ(format!( + "argument {} of {}() must be of a 'Value' type", + idx + 1, + func_name + ))); + } + } + ExpressionType::Logical => { + if !matches!( + arg, + FilterExpression::RelativeQuery { .. } + | FilterExpression::RootQuery { .. } + | FilterExpression::Logical { .. } + | FilterExpression::Comparison { .. }, + ) { + return Err(JSONPathError::typ(format!( + "argument {} of {}() must be of a 'Logical' type", + idx + 1, + func_name + ))); + } + } + ExpressionType::Nodes => { + if !self.is_nodes_type(arg) { + return Err(JSONPathError::typ(format!( + "argument {} of {}() must be of a 'Nodes' type", + idx + 1, + func_name + ))); + } + } + } + } + + Ok(args) + } + + fn is_value_type(&self, expr: &FilterExpression) -> bool { + // literals are values + if expr.is_literal() { + return true; + } + + match expr { + FilterExpression::RelativeQuery { query, .. } + | FilterExpression::RootQuery { query, .. } => { + // singular queries will be coerced to a value + query.is_singular() + } + FilterExpression::Function { name, .. } => { + // some functions return a value + matches!( + self.function_signatures.get(name), + Some(FunctionSignature { + return_type: ExpressionType::Value, + .. + }) + ) + } + FilterExpression::Array { .. } => true, + _ => false, + } + } + + fn is_nodes_type(&self, expr: &FilterExpression) -> bool { + match expr { + FilterExpression::RelativeQuery { .. } | FilterExpression::RootQuery { .. } => true, + FilterExpression::Function { name, .. } => { + matches!( + self.function_signatures.get(name), + Some(FunctionSignature { + return_type: ExpressionType::Nodes, + .. + }) + ) + } + _ => false, + } + } +} + +fn unescape_string(value: &str) -> String { + let chars = value.chars().collect::<Vec<char>>(); + let length = chars.len(); + let mut rv = String::new(); + let mut index: usize = 0; + + while index < length { + match chars[index] { + '\\' => { + index += 1; + match chars[index] { + '"' => rv.push('"'), + '\\' => rv.push('\\'), + '/' => rv.push('/'), + 'b' => rv.push('\x08'), + 'f' => rv.push('\x0C'), + 'n' => rv.push('\n'), + 'r' => rv.push('\r'), + 't' => rv.push('\t'), + 'u' => { + index += 1; + let digits = chars + .get(index..index + 4) + .unwrap() + .iter() + .collect::<String>(); + let mut codepoint = u32::from_str_radix(&digits, 16).unwrap(); + + if index + 5 < length && chars[index + 4] == '\\' && chars[index + 5] == 'u' + { + let digits = &chars + .get(index + 6..index + 10) + .unwrap() + .iter() + .collect::<String>(); + let low_surrogate = u32::from_str_radix(digits, 16).unwrap(); + codepoint = + 0x10000 + (((codepoint & 0x03FF) << 10) | (low_surrogate & 0x03FF)); + index += 6; + } + + let unescaped = char::from_u32(codepoint).unwrap(); + rv.push(unescaped); + index += 3; + } + _ => unreachable!(), + } + } + c => { + rv.push(c); + } + } + index += 1; + } + + rv +} diff --git a/vendor/loro-internal/src/jsonpath/subscription.rs b/vendor/loro-internal/src/jsonpath/subscription.rs new file mode 100644 index 0000000..599bc18 --- /dev/null +++ b/vendor/loro-internal/src/jsonpath/subscription.rs @@ -0,0 +1,551 @@ +//! # JSONPath Subscription Module +//! +//! This module provides a mechanism to subscribe to changes that may affect a JSONPath query +//! result, without re-evaluating the query on every change. +//! +//! ## Design Goals +//! +//! - **Conservative matching**: The matcher may produce false positives (triggering when +//! the query result hasn't actually changed) but must never produce false negatives +//! (missing a notification when the result did change). +//! - **Lightweight notifications**: Callbacks receive no payload; applications can +//! debounce/throttle and evaluate the JSONPath themselves. +//! - **Efficient matching**: Uses an NFA (non-deterministic finite automaton) approach +//! to match event paths against compiled JSONPath queries in O(path_len × steps) time. +//! +//! ## Algorithm Overview +//! +//! 1. **Compilation**: JSONPath is parsed and converted into a sequence of lightweight +//! `MatchSelector`s (no AST storage needed for matching). +//! +//! 2. **NFA Simulation**: When an event arrives, we simulate an NFA where: +//! - States are positions in the step sequence (0..steps.len()) +//! - Transitions occur when a selector matches the current path element +//! - Recursive steps allow staying at the same state while consuming input +//! - Acceptance occurs when any state reaches or exceeds `steps.len()` + +use std::sync::Arc; + +use loro_common::TreeID; +use smallvec::SmallVec; + +use crate::{ + event::{Diff, Index}, + jsonpath::{ + ast::{Query, Segment, Selector}, + JSONPathParser, + }, + utils::subscription::Subscription, + LoroDoc, LoroError, LoroResult, +}; + +/// Callback used by `subscribe_jsonpath`. +/// +/// Note: the callback does **not** carry the query result. It is intended as a +/// lightweight notification so applications can debounce/throttle and evaluate +/// JSONPath themselves if needed. +pub type SubscribeJsonPathCallback = Arc<dyn Fn() + Send + Sync + 'static>; + +/// Represents a single path segment used for matching against events. +/// +/// Path elements are derived from event paths and represent the location of a change +/// in the document tree. They form the "input alphabet" for our NFA simulation. +#[derive(Debug, Clone, PartialEq, Eq)] +enum PathElem { + /// A map key (e.g., "title" in `$.books[0].title`) + Key(Arc<str>), + /// A sequence (list/array) index. + /// - `Some(i)` means a specific index changed + /// - `None` means "some index changed" (used for list/tree child mutations + /// where we don't know which specific indices are affected) + Seq(Option<usize>), + /// A tree node identifier (for Loro's tree CRDT) + Node(TreeID), +} + +impl From<&Index> for PathElem { + fn from(value: &Index) -> Self { + match value { + Index::Key(k) => PathElem::Key(k.as_ref().into()), + Index::Seq(i) => PathElem::Seq(Some(*i)), + Index::Node(n) => PathElem::Node(*n), + } + } +} + +// ============================================================================= +// Lightweight Matching Types +// ============================================================================= +// +// Instead of storing the full Selector AST (which includes heavyweight +// FilterExpression trees), we convert selectors to a simple matching-only enum. +// This reduces memory usage and code complexity. + +/// Simplified selector for matching only - no AST storage needed. +/// +/// All complex selectors (Slice, Wild, Filter, negative Index) become `Wildcard` +/// since they can match any element during conservative path matching. +#[derive(Debug, Clone)] +enum MatchSelector { + /// Exact key match (from `Selector::Name`) + Name(Arc<str>), + /// Exact non-negative index match (from `Selector::Index` where index >= 0) + Index(usize), + /// Matches anything (from Wild, Slice, Filter, or negative Index) + Wildcard, +} + +/// A single step in the linearized JSONPath query. +#[derive(Debug, Clone)] +struct Step { + /// If true, this step uses recursive descent (`..`) and can match at any depth. + recursive: bool, + /// Simplified selectors for matching. + selectors: SmallVec<[MatchSelector; 2]>, +} + +/// A compiled matcher that conservatively checks whether a change at some path +/// can affect the JSONPath query. +#[derive(Debug, Clone)] +struct JsonPathMatcher { + /// Linearized sequence of matching steps + steps: Vec<Step>, +} + +impl JsonPathMatcher { + /// Compile a JSONPath query into a matcher. + fn new(query: &Query) -> Self { + let mut steps = Vec::new(); + build_steps(&query.segments, &mut steps); + JsonPathMatcher { steps } + } + + /// Returns true if the provided path (from root) could affect the query result. + fn may_match(&self, path: &[PathElem]) -> bool { + if self.steps.is_empty() { + return true; + } + let positions = self.positions_after(path); + positions.iter().any(|&p| p >= self.steps.len()) + } + + /// Check if any position was reached by passing through a Wildcard step. + /// Wildcard steps come from filter/wild/slice selectors - any key change + /// under them could affect the query result. + #[inline] + fn passed_through_wildcard(&self, positions: &[usize]) -> bool { + positions.iter().any(|&pos| { + pos > 0 + && self.steps[pos - 1] + .selectors + .iter() + .any(|s| matches!(s, MatchSelector::Wildcard)) + }) + } + + /// Simulate the NFA on a path and return all reachable positions after consuming it. + /// + /// - Position `== steps.len()`: Query fully matched + /// - Position `< steps.len()`: Partial match + /// - Empty result: No match possible + fn positions_after(&self, path: &[PathElem]) -> SmallVec<[usize; 8]> { + let mut positions = SmallVec::<[usize; 8]>::new(); + positions.push(0); + + for elem in path { + let mut next = SmallVec::<[usize; 8]>::new(); + + for &pos in positions.iter() { + if pos >= self.steps.len() { + next.push(pos); + continue; + } + + let step = &self.steps[pos]; + + // Recursive descent: can stay at same position + if step.recursive { + next.push(pos); + } + + // If selector matches, advance to next step + if selector_matches(&step.selectors, elem) { + next.push(pos + 1); + } + } + + dedup_positions(&mut next); + if next.is_empty() { + return next; + } + positions = next; + } + + positions + } +} + +/// Check if any selector matches the given path element. +fn selector_matches(selectors: &[MatchSelector], elem: &PathElem) -> bool { + selectors.iter().any(|sel| match sel { + MatchSelector::Name(name) => matches!(elem, PathElem::Key(k) if k == name), + MatchSelector::Index(idx) => match elem { + PathElem::Seq(Some(i)) => *i == *idx, + PathElem::Seq(None) => true, // Unknown index - conservative match + _ => false, + }, + MatchSelector::Wildcard => true, + }) +} + +/// Convert AST Selector to lightweight MatchSelector. +fn to_match_selector(sel: &Selector) -> MatchSelector { + match sel { + Selector::Name { name } => MatchSelector::Name(name.as_str().into()), + Selector::Index { index } if *index >= 0 => MatchSelector::Index(*index as usize), + // Negative index, Slice, Wild, Filter all become Wildcard + _ => MatchSelector::Wildcard, + } +} + +/// Linearize the JSONPath AST into a sequence of matching steps. +fn build_steps(segment: &Segment, steps: &mut Vec<Step>) { + match segment { + Segment::Root {} => {} + Segment::Child { left, selectors } => { + build_steps(left, steps); + steps.push(Step { + recursive: false, + selectors: selectors.iter().map(to_match_selector).collect(), + }); + } + Segment::Recursive { left, selectors } => { + build_steps(left, steps); + steps.push(Step { + recursive: true, + selectors: selectors.iter().map(to_match_selector).collect(), + }); + } + } +} + +/// Deduplicate positions in-place. +#[inline] +fn dedup_positions(v: &mut SmallVec<[usize; 8]>) { + v.sort_unstable(); + v.dedup(); +} + +// ============================================================================= +// Public API +// ============================================================================= + +impl LoroDoc { + /// Subscribe to updates that may affect the given JSONPath query. + /// + /// ## Behavior + /// + /// - **Conservative matching**: The callback may fire for changes that don't + /// actually affect the query result (false positives), but it will never + /// miss a change that does affect it (no false negatives). + /// - **Lightweight notifications**: The callback receives no payload. Applications + /// should debounce/throttle and re-evaluate the JSONPath if needed. + /// + /// ## Returns + /// + /// A `Subscription` handle. Drop it to unsubscribe. + #[cfg(feature = "jsonpath")] + pub fn subscribe_jsonpath( + &self, + jsonpath: &str, + callback: SubscribeJsonPathCallback, + ) -> LoroResult<Subscription> { + let query = JSONPathParser::new() + .parse(jsonpath) + .map_err(|e| LoroError::ArgErr(e.to_string().into_boxed_str()))?; + + let matcher = Arc::new(JsonPathMatcher::new(&query)); + + let sub = self.subscribe_root(Arc::new(move |event| { + if event.events.is_empty() { + return; + } + + let matcher = &matcher; + let mut fired = false; + + for container_diff in event.events.iter() { + if fired { + break; + } + + // Convert the container's path to PathElem representation + let base_path: SmallVec<[PathElem; 8]> = container_diff + .path + .iter() + .map(|(_, idx)| PathElem::from(idx)) + .collect(); + + // Check 1: Does the container path itself match the query? + if matcher.may_match(&base_path) { + fired = true; + break; + } + + // Check 2: Map-specific handling - check each changed key + if let Diff::Map(map) = &container_diff.diff { + let base_positions = matcher.positions_after(&base_path); + if base_positions.is_empty() { + continue; + } + + // If we passed through a Wildcard (filter/wild/slice), any key + // change could affect the result - be conservative. + let past_wildcard = matcher.passed_through_wildcard(&base_positions); + + for key in map.updated.keys() { + let mut extended: SmallVec<[PathElem; 8]> = base_path.clone(); + extended.push(PathElem::Key(key.as_ref().into())); + + let extended_positions = matcher.positions_after(&extended); + + // Trigger if key path could match OR we're inside a wildcard selection + if !extended_positions.is_empty() || past_wildcard { + fired = true; + break; + } + } + + if fired { + break; + } + } + + // Check 3: List/Tree/Counter child mutations + // These container types can have child changes at unknown indices + let has_child_changes = matches!( + &container_diff.diff, + Diff::List(_) | Diff::Tree(_) | Diff::Unknown + ); + #[cfg(feature = "counter")] + let has_child_changes = + has_child_changes || matches!(&container_diff.diff, Diff::Counter(_)); + + if has_child_changes { + let mut extended: SmallVec<[PathElem; 8]> = base_path.clone(); + extended.push(PathElem::Seq(None)); // "some child changed" + if !matcher.positions_after(&extended).is_empty() { + fired = true; + } + } + } + + if fired { + (callback)(); + } + })); + + Ok(sub) + } +} + +// ============================================================================= +// Tests +// ============================================================================= + +#[cfg(test)] +mod tests { + use super::*; + use crate::{LoroDoc, MapHandler}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn make_book( + doc: &LoroDoc, + idx: usize, + title: &str, + available: bool, + price: i64, + ) -> MapHandler { + let books = doc.get_list("books"); + let book = books + .insert_container(idx, MapHandler::new_detached()) + .unwrap(); + book.insert("title", title).unwrap(); + book.insert("available", available).unwrap(); + book.insert("price", price).unwrap(); + book + } + + #[test] + fn jsonpath_subscribe_triggers_on_specific_key() { + let doc = LoroDoc::new_auto_commit(); + let first_book = make_book(&doc, 0, "Old", true, 10); + doc.commit_then_renew(); + + let hit = Arc::new(AtomicUsize::new(0)); + let hit_ref = hit.clone(); + let _sub = doc + .subscribe_jsonpath( + "$.books[0].title", + Arc::new(move || { + hit_ref.fetch_add(1, Ordering::SeqCst); + }), + ) + .unwrap(); + + first_book.insert("title", "New").unwrap(); + doc.commit_then_renew(); + + assert!(hit.load(Ordering::SeqCst) >= 1); + } + + #[test] + fn jsonpath_subscribe_wildcard_on_list() { + let doc = LoroDoc::new_auto_commit(); + make_book(&doc, 0, "A", true, 10); + let second_book = make_book(&doc, 1, "B", true, 20); + doc.commit_then_renew(); + + let hit = Arc::new(AtomicUsize::new(0)); + let hit_ref = hit.clone(); + let _sub = doc + .subscribe_jsonpath( + "$.books[*].price", + Arc::new(move || { + hit_ref.fetch_add(1, Ordering::SeqCst); + }), + ) + .unwrap(); + + second_book.insert("price", 25).unwrap(); + doc.commit_then_renew(); + + assert!(hit.load(Ordering::SeqCst) >= 1); + } + + #[test] + fn jsonpath_subscribe_negative_index() { + let doc = LoroDoc::new_auto_commit(); + make_book(&doc, 0, "A", true, 10); + make_book(&doc, 1, "B", true, 20); + doc.commit_then_renew(); + + let hit = Arc::new(AtomicUsize::new(0)); + let hit_ref = hit.clone(); + let _sub = doc + .subscribe_jsonpath( + "$.books[-1].title", + Arc::new(move || { + hit_ref.fetch_add(1, Ordering::SeqCst); + }), + ) + .unwrap(); + + let books = doc.get_list("books"); + let last = books.get_child_handler(1).unwrap(); + last.as_map().unwrap().insert("title", "B updated").unwrap(); + doc.commit_then_renew(); + + assert!(hit.load(Ordering::SeqCst) >= 1); + } + + #[test] + fn jsonpath_subscribe_slice_range() { + let doc = LoroDoc::new_auto_commit(); + make_book(&doc, 0, "A", true, 10); + let second_book = make_book(&doc, 1, "B", true, 20); + make_book(&doc, 2, "C", true, 30); + doc.commit_then_renew(); + + let hit = Arc::new(AtomicUsize::new(0)); + let hit_ref = hit.clone(); + let _sub = doc + .subscribe_jsonpath( + "$.books[0:2].title", + Arc::new(move || { + hit_ref.fetch_add(1, Ordering::SeqCst); + }), + ) + .unwrap(); + + second_book.insert("title", "B updated").unwrap(); + doc.commit_then_renew(); + + assert!(hit.load(Ordering::SeqCst) >= 1); + } + + #[test] + fn jsonpath_subscribe_recursive() { + let doc = LoroDoc::new_auto_commit(); + let store = doc.get_map("store"); + let nested = store + .insert_container("inventory", MapHandler::new_detached()) + .unwrap(); + nested.insert("total", 3).unwrap(); + doc.commit_then_renew(); + + let hit = Arc::new(AtomicUsize::new(0)); + let hit_ref = hit.clone(); + let _sub = doc + .subscribe_jsonpath( + "$..total", + Arc::new(move || { + hit_ref.fetch_add(1, Ordering::SeqCst); + }), + ) + .unwrap(); + + nested.insert("total", 4).unwrap(); + doc.commit_then_renew(); + + assert!(hit.load(Ordering::SeqCst) >= 1); + } + + #[test] + fn jsonpath_subscribe_filter_treated_as_wildcard() { + let doc = LoroDoc::new_auto_commit(); + make_book(&doc, 0, "A", true, 10); + let second_book = make_book(&doc, 1, "B", false, 20); + doc.commit_then_renew(); + + let hit = Arc::new(AtomicUsize::new(0)); + let hit_ref = hit.clone(); + let _sub = doc + .subscribe_jsonpath( + "$.books[?@.available].title", + Arc::new(move || { + hit_ref.fetch_add(1, Ordering::SeqCst); + }), + ) + .unwrap(); + + second_book.insert("available", true).unwrap(); + doc.commit_then_renew(); + + assert!(hit.load(Ordering::SeqCst) >= 1); + } + + #[test] + fn jsonpath_subscribe_triggers_once_per_commit() { + let doc = LoroDoc::new_auto_commit(); + let book = make_book(&doc, 0, "A", true, 10); + doc.commit_then_renew(); + + let hit = Arc::new(AtomicUsize::new(0)); + let hit_ref = hit.clone(); + let _sub = doc + .subscribe_jsonpath( + "$.books[0].title", + Arc::new(move || { + hit_ref.fetch_add(1, Ordering::SeqCst); + }), + ) + .unwrap(); + + book.insert("title", "X").unwrap(); + book.insert("title", "Y").unwrap(); + doc.commit_then_renew(); + + assert_eq!(hit.load(Ordering::SeqCst), 1); + } +} diff --git a/vendor/loro-internal/src/kv_store.rs b/vendor/loro-internal/src/kv_store.rs new file mode 100644 index 0000000..4598b4d --- /dev/null +++ b/vendor/loro-internal/src/kv_store.rs @@ -0,0 +1,260 @@ +use crate::sync::Mutex; +use bytes::Bytes; +pub use loro_kv_store::compress::CompressionType; +pub use loro_kv_store::MemKvStore; +use std::sync::Arc; +use std::{collections::BTreeMap, ops::Bound}; + +pub trait KvStore: std::fmt::Debug + Send + Sync { + fn get(&self, key: &[u8]) -> Option<Bytes>; + fn set(&mut self, key: &[u8], value: Bytes); + fn compare_and_swap(&mut self, key: &[u8], old: Option<Bytes>, new: Bytes) -> bool; + fn remove(&mut self, key: &[u8]) -> Option<Bytes>; + fn contains_key(&self, key: &[u8]) -> bool; + fn scan( + &self, + start: Bound<&[u8]>, + end: Bound<&[u8]>, + ) -> Box<dyn DoubleEndedIterator<Item = (Bytes, Bytes)> + '_>; + fn len(&self) -> usize; + fn is_empty(&self) -> bool; + fn size(&self) -> usize; + fn export_all(&mut self) -> Bytes; + fn import_all(&mut self, bytes: Bytes) -> Result<(), String>; + /// Like [`Self::import_all`], but for callers that already guarantee the + /// blob's integrity via an outer checksum, so per-block checksums may be + /// skipped. The default falls back to the checked [`Self::import_all`]; only + /// override it where the fast path is safe (e.g. SsTable-backed stores). + fn import_all_unchecked(&mut self, bytes: Bytes) -> Result<(), String> { + self.import_all(bytes) + } + fn clone_store(&self) -> Arc<Mutex<dyn KvStore>>; +} + +fn get_common_prefix_len_and_strip<'a, T: AsRef<[u8]> + ?Sized>( + this: &'a T, + last: &T, +) -> (u8, &'a [u8]) { + let mut common_prefix_len = 0; + for (i, (a, b)) in this.as_ref().iter().zip(last.as_ref().iter()).enumerate() { + if a != b || i == 255 { + common_prefix_len = i; + break; + } + } + + let suffix = &this.as_ref()[common_prefix_len..]; + (common_prefix_len as u8, suffix) +} + +impl KvStore for MemKvStore { + fn get(&self, key: &[u8]) -> Option<Bytes> { + self.get(key) + } + + fn set(&mut self, key: &[u8], value: Bytes) { + self.set(key, value) + } + + fn compare_and_swap(&mut self, key: &[u8], old: Option<Bytes>, new: Bytes) -> bool { + self.compare_and_swap(key, old, new) + } + + fn remove(&mut self, key: &[u8]) -> Option<Bytes> { + let ans = self.get(key); + self.remove(key); + ans + } + + fn contains_key(&self, key: &[u8]) -> bool { + self.contains_key(key) + } + + fn scan( + &self, + start: Bound<&[u8]>, + end: Bound<&[u8]>, + ) -> Box<dyn DoubleEndedIterator<Item = (Bytes, Bytes)> + '_> { + self.scan(start, end) + } + + fn len(&self) -> usize { + self.len() + } + + fn is_empty(&self) -> bool { + self.is_empty() + } + + fn size(&self) -> usize { + self.size() + } + + fn export_all(&mut self) -> Bytes { + self.export_all() + } + + fn import_all(&mut self, bytes: Bytes) -> Result<(), String> { + self.import_all(bytes) + } + + fn import_all_unchecked(&mut self, bytes: Bytes) -> Result<(), String> { + self.import_all_unchecked(bytes) + } + + fn clone_store(&self) -> Arc<Mutex<dyn KvStore>> { + Arc::new(Mutex::new(self.clone())) + } +} + +mod default_binary_format { + //! Default binary format for the key-value store. + //! + //! It will compress the prefix of the keys that are common with the previous key. + + use bytes::Bytes; + + use super::get_common_prefix_len_and_strip; + + pub fn export_by_scan(store: &impl super::KvStore) -> bytes::Bytes { + let mut buf = Vec::new(); + let mut last_key: Option<Bytes> = None; + for (k, v) in store.scan(std::ops::Bound::Unbounded, std::ops::Bound::Unbounded) { + { + // Write the key + match last_key.take() { + None => { + leb128::write::unsigned(&mut buf, k.len() as u64).unwrap(); + buf.extend_from_slice(&k); + } + Some(last) => { + let (common, suffix) = get_common_prefix_len_and_strip(&k, &last); + buf.push(common); + leb128::write::unsigned(&mut buf, suffix.len() as u64).unwrap(); + buf.extend_from_slice(suffix); + } + }; + + last_key = Some(k); + } + + // Write the value + leb128::write::unsigned(&mut buf, v.len() as u64).unwrap(); + buf.extend_from_slice(&v); + } + + buf.into() + } + + pub fn import(store: &mut impl super::KvStore, bytes: bytes::Bytes) -> Result<(), String> { + let mut bytes: &[u8] = &bytes; + let mut last_key = Vec::new(); + + while !bytes.is_empty() { + // Read the key + let mut key = Vec::new(); + if last_key.is_empty() { + let key_len = leb128::read::unsigned(&mut bytes).map_err(|e| e.to_string())?; + let key_len = key_len as usize; + key.extend_from_slice(&bytes[..key_len]); + bytes = &bytes[key_len..]; + } else { + let common_prefix_len = bytes[0] as usize; + bytes = &bytes[1..]; + key.extend_from_slice(&last_key[..common_prefix_len]); + let suffix_len = leb128::read::unsigned(&mut bytes).map_err(|e| e.to_string())?; + let suffix_len = suffix_len as usize; + key.extend_from_slice(&bytes[..suffix_len]); + bytes = &bytes[suffix_len..]; + } + + // Read the value + let value_len = leb128::read::unsigned(&mut bytes).map_err(|e| e.to_string())?; + let value_len = value_len as usize; + let value = Bytes::copy_from_slice(&bytes[..value_len]); + bytes = &bytes[value_len..]; + + // Store the key-value pair + store.set(&key, value); + + last_key = key; + } + + Ok(()) + } +} + +impl KvStore for BTreeMap<Bytes, Bytes> { + fn get(&self, key: &[u8]) -> Option<Bytes> { + self.get(key).cloned() + } + + fn set(&mut self, key: &[u8], value: Bytes) { + self.insert(Bytes::copy_from_slice(key), value); + } + + fn compare_and_swap(&mut self, key: &[u8], old: Option<Bytes>, new: Bytes) -> bool { + let key = Bytes::copy_from_slice(key); + match self.get_mut(&key) { + Some(v) => { + if old.as_ref() == Some(v) { + self.insert(key, new); + true + } else { + false + } + } + None => { + if old.is_none() { + self.insert(key, new); + true + } else { + false + } + } + } + } + + fn remove(&mut self, key: &[u8]) -> Option<Bytes> { + self.remove(key) + } + + fn contains_key(&self, key: &[u8]) -> bool { + self.contains_key(key) + } + + fn scan( + &self, + start: Bound<&[u8]>, + end: Bound<&[u8]>, + ) -> Box<dyn DoubleEndedIterator<Item = (Bytes, Bytes)> + '_> { + Box::new( + self.range::<[u8], _>((start, end)) + .map(|(k, v)| (k.clone(), v.clone())), + ) + } + + fn len(&self) -> usize { + self.len() + } + + fn is_empty(&self) -> bool { + self.is_empty() + } + + fn size(&self) -> usize { + self.iter().fold(0, |acc, (k, v)| acc + k.len() + v.len()) + } + + fn export_all(&mut self) -> Bytes { + default_binary_format::export_by_scan(self) + } + + fn import_all(&mut self, bytes: Bytes) -> Result<(), String> { + default_binary_format::import(self, bytes) + } + + fn clone_store(&self) -> Arc<Mutex<dyn KvStore>> { + Arc::new(Mutex::new(self.clone())) + } +} diff --git a/vendor/loro-internal/src/lib.rs b/vendor/loro-internal/src/lib.rs new file mode 100644 index 0000000..83d3542 --- /dev/null +++ b/vendor/loro-internal/src/lib.rs @@ -0,0 +1,185 @@ +//! loro-internal is a CRDT framework. +//! +//! +//! +//! +#![deny(clippy::undocumented_unsafe_blocks)] +#![allow(unused_assignments)] +#![allow(clippy::uninlined_format_args)] +#![warn(rustdoc::broken_intra_doc_links)] +#![warn(missing_debug_implementations)] + +pub mod arena; +pub mod diff; +pub mod diff_calc; +pub mod handler; +pub mod sync; +pub use state::container_tree; + +use crate::sync::{AtomicBool, AtomicUsize}; +use std::sync::Arc; +mod change_meta; +pub(crate) mod lock; +use arena::SharedArena; +use configure::Configure; +use diff_calc::DiffCalculator; +use lock::LoroMutex; + +pub use change_meta::ChangeMeta; +pub use event::{ContainerDiff, DiffEvent, DocDiff, ListDiff, ListDiffInsertItem, ListDiffItem}; +pub use handler::{ + BasicHandler, HandlerTrait, ListHandler, MapHandler, MovableListHandler, TextHandler, + TreeHandler, UnknownHandler, +}; +pub use loro_common; +pub use oplog::OpLog; +use pre_commit::{ + FirstCommitFromPeerCallback, FirstCommitFromPeerPayload, PreCommitCallback, + PreCommitCallbackPayload, +}; +pub use rustc_hash::FxHashMap; +pub use state::DocState; +pub use state::{TreeNode, TreeNodeWithChildren, TreeParentId}; +use subscription::{LocalUpdateCallback, Observer, PeerIdUpdateCallback}; +use txn::Transaction; +pub use undo::UndoManager; +pub use utils::subscription::SubscriberSetWithQueue; +pub use utils::subscription::Subscription; +pub mod allocation; +pub mod awareness; +pub mod change; +pub mod configure; +pub mod container; +pub mod cursor; +pub mod dag; +pub mod encoding; +pub(crate) mod fork; +pub mod id; +#[cfg(feature = "jsonpath")] +pub mod jsonpath; +pub mod kv_store; +pub mod loro; +pub mod op; +pub mod oplog; +pub mod subscription; +pub mod txn; +pub mod version; + +mod error; +#[cfg(feature = "test_utils")] +pub mod fuzz; +mod parent; +pub mod pre_commit; +mod span; +#[cfg(test)] +pub mod tests; +mod utils; +pub use utils::string_slice::StringSlice; + +pub mod delta; +pub use loro_delta; +pub mod event; + +pub mod estimated_size; +pub(crate) mod history_cache; +pub(crate) mod macros; +pub(crate) mod state; +pub mod undo; +pub(crate) mod value; + +// TODO: rename as Key? +pub(crate) use loro_common::InternalString; + +pub use container::ContainerType; +pub use encoding::json_schema::json; +pub use fractional_index::FractionalIndex; +pub use loro_common::{loro_value, to_value}; +pub use loro_common::{ + Counter, CounterSpan, IdLp, IdSpan, IdSpanVector, Lamport, LoroEncodeError, LoroError, + LoroResult, LoroTreeError, PeerID, TreeID, ID, +}; +pub use loro_common::{LoroBinaryValue, LoroListValue, LoroMapValue, LoroStringValue}; +#[cfg(feature = "wasm")] +pub use value::wasm; +pub use value::{ApplyDiff, LoroValue, ToJson}; +pub use version::VersionVector; + +/// [`LoroDoc`] serves as the library's primary entry point. +/// It's constituted by an [OpLog] and an [DocState]. +/// +/// - [OpLog] encompasses all operations, signifying the document history. +/// - [DocState] signifies the current document state. +/// +/// They will share a [super::arena::SharedArena] +/// +/// # Detached Mode +/// +/// This mode enables separate usage of [OpLog] and [DocState]. +/// It facilitates temporal navigation. [DocState] can be reverted to +/// any version contained within the [OpLog]. +/// +/// `LoroDoc::detach()` separates [DocState] from [OpLog]. In this mode, +/// updates to [OpLog] won't affect [DocState], while updates to [DocState] +/// will continue to affect [OpLog]. +#[derive(Debug, Clone)] +#[repr(transparent)] +pub struct LoroDoc { + inner: Arc<LoroDocInner>, +} + +impl LoroDoc { + pub(crate) fn from_inner(inner: Arc<LoroDocInner>) -> Self { + Self { inner } + } +} + +impl std::ops::Deref for LoroDoc { + type Target = LoroDocInner; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +pub struct LoroDocInner { + oplog: Arc<LoroMutex<OpLog>>, + state: Arc<LoroMutex<DocState>>, + arena: SharedArena, + config: Configure, + visible_op_count: Arc<AtomicUsize>, + observer: Arc<Observer>, + diff_calculator: Arc<LoroMutex<DiffCalculator>>, + /// When dropping the doc, the txn will be committed + /// + /// # Internal Notes + /// + /// Txn can be accessed by different threads. But for certain methods we need to lock the txn and ensure it's empty: + /// + /// - `import` + /// - `export` + /// - `checkout` + /// - `checkout_to_latest` + /// - ... + /// + /// We need to lock txn and keep it None because otherwise the DocState may change due to a parallel edit on a new Txn, + /// which may break the invariants of `import`, `export` and `checkout`. + txn: Arc<LoroMutex<Option<Transaction>>>, + auto_commit: AtomicBool, + detached: AtomicBool, + local_update_subs: SubscriberSetWithQueue<(), LocalUpdateCallback, Vec<u8>>, + peer_id_change_subs: SubscriberSetWithQueue<(), PeerIdUpdateCallback, ID>, + first_commit_from_peer_subs: + SubscriberSetWithQueue<(), FirstCommitFromPeerCallback, FirstCommitFromPeerPayload>, + pre_commit_subs: SubscriberSetWithQueue<(), PreCommitCallback, PreCommitCallbackPayload>, +} + +/// The version of the loro crate +pub const LORO_VERSION: &str = include_str!("../VERSION"); + +impl Drop for LoroDoc { + fn drop(&mut self) { + if Arc::strong_count(&self.inner) == 1 { + let _ = self.implicit_commit_then_stop(); + } + } +} diff --git a/vendor/loro-internal/src/lock.rs b/vendor/loro-internal/src/lock.rs new file mode 100644 index 0000000..d1768c2 --- /dev/null +++ b/vendor/loro-internal/src/lock.rs @@ -0,0 +1,627 @@ +//! Lock-order-checked mutexes. +//! +//! This module provides a small utility to prevent deadlocks by enforcing a +//! strict, per-thread lock acquisition order across a set of related locks. +//! +//! Core ideas: +//! - Locks are created from a [`LoroLockGroup`]. Locks in the same group share +//! a per-thread stack that tracks the last acquired lock kind. +//! - Each lock has an associated [`LockKind`]. A thread may only acquire locks +//! in strictly increasing kind order (e.g. `Txn` → `OpLog` → `DocState` → `DiffCalculator`). +//! - Locks must be released in the reverse order they were acquired (LIFO). +//! - Violations are detected and reported with helpful panics that include the +//! callsite (via `#[track_caller]`) and a backtrace on release-order errors. +//! +//! The actual locking is backed by [`crate::sync::Mutex`], which resolves to +//! `std::sync::Mutex` in normal builds and `loom::sync::Mutex` under loom. This +//! keeps the code testable with loom while maintaining the same API. +//! +//! The per-thread order tracking is debug-only; in release builds those fields +//! and helpers are unused, hence the release-only `allow(dead_code)`. +#![cfg_attr(not(debug_assertions), allow(dead_code))] +use crate::sync::ThreadLocal; +use crate::sync::{Mutex, MutexGuard}; +#[cfg(debug_assertions)] +use std::backtrace::Backtrace; +use std::fmt::{Debug, Display}; +use std::ops::{Deref, DerefMut}; +use std::panic::Location; +use std::sync::atomic::Ordering; +use std::sync::Arc; + +/// A mutex that verifies lock acquisition and release order against a group-wide +/// strict ordering by [`LockKind`]. +/// +/// Create instances via [`LoroLockGroup::new_lock`]. Calling [`LoroMutex::lock`] +/// will panic if the current thread has already acquired a lock with a kind that +/// is greater than or equal to this lock’s kind, or if the underlying mutex was +/// poisoned by an earlier panic. Release order is also checked; dropping the +/// guard out of LIFO order results in a panic. +/// +/// This type wraps [`crate::sync::Mutex`], so it remains compatible with loom-based +/// concurrency testing. +#[derive(Debug)] +pub struct LoroMutex<T> { + lock: Mutex<T>, + kind: u8, + currently_locked_in_this_thread: Arc<ThreadLocal<Mutex<LockInfo>>>, + /// Used only by the `Txn` lock. Stored inline so the writer check reads the + /// same allocation (usually the same cache line) as the mutex itself. + txn_gate: TxnGate, +} + +/// Keeps other threads' transaction writers out while one thread runs a +/// compound operation (undo/redo) that releases and reacquires the +/// transaction lock. Ordinary writers only read `active` after taking the +/// mutex, so the common uncontended path costs one atomic load, not a lock. +#[derive(Debug)] +struct TxnGate { + /// True exactly while some thread holds `exclusive`. A plain std atomic + /// even under loom: it never blocks, and modelling it would add scheduling + /// branches to every transaction lock in every loom test. The blocking + /// parts (`exclusive`, `owner`) stay loom-aware. + active: std::sync::atomic::AtomicBool, + /// Held by the owner for the whole compound operation; other compound + /// operations and waiting writers block on it. + exclusive: Mutex<()>, + /// The owning thread and its reentrancy depth. + owner: Mutex<Option<(crate::sync::thread::ThreadId, usize)>>, +} + +impl TxnGate { + fn new() -> Self { + Self { + active: std::sync::atomic::AtomicBool::new(false), + exclusive: Mutex::new(()), + owner: Mutex::new(None), + } + } + + // The gate guards no data and `owner` is reset by `TxnExclusiveGuard::drop` + // during unwinding, so a panic inside an undo must not poison later writers. + fn owner(&self) -> MutexGuard<'_, Option<(crate::sync::thread::ThreadId, usize)>> { + self.owner.lock_ignoring_poison() + } + + fn wait_exclusive(&self) -> MutexGuard<'_, ()> { + self.exclusive.lock_ignoring_poison() + } + + fn is_owned_by_current_thread(&self) -> bool { + let me = crate::sync::thread::current().id(); + matches!(*self.owner(), Some((owner, _)) if owner == me) + } + + /// Whether a transaction writer on this thread must wait for another + /// thread's compound operation. + fn must_wait(&self) -> bool { + self.active.load(Ordering::SeqCst) && !self.is_owned_by_current_thread() + } +} + +/// Guard returned by [`LoroMutex::lock_exclusive`]. +pub(crate) struct TxnExclusiveGuard<'a> { + gate: &'a TxnGate, + /// Only the outermost guard of a thread holds the gate. + held: Option<MutexGuard<'a, ()>>, +} + +impl Drop for TxnExclusiveGuard<'_> { + fn drop(&mut self) { + let mut owner = self.gate.owner(); + if let Some((_, depth)) = owner.as_mut() { + *depth -= 1; + } + if self.held.is_some() { + debug_assert!(matches!(*owner, Some((_, 0)))); + *owner = None; + // Clear the flag before releasing the gate: waiting writers retry + // after acquiring the gate and must then see it cleared. + self.gate.active.store(false, Ordering::SeqCst); + } + drop(owner); + self.held.take(); + } +} + +/// Internal per-thread lock information used for diagnostics and order checks. +#[derive(Debug, Copy, Clone, Default)] +struct LockInfo { + kind: u8, + caller_location: Option<&'static Location<'static>>, +} + +impl Display for LockInfo { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.caller_location { + Some(location) => write!( + f, + "LockInfo(kind: {}, location: {}:{}:{})", + self.kind, + location.file(), + location.line(), + location.column() + ), + None => write!(f, "LockInfo(kind: {}, location: None)", self.kind), + } + } +} + +#[derive(Debug)] +/// A group that defines a shared locking order domain. +/// +/// All [`LoroMutex`] created from the same group participate in a single, +/// per-thread lock-order stack. Locks from different groups are independent and +/// do not affect each other’s ordering checks. +/// +/// Use [`LoroLockGroup::new_lock`] to create locks of specific [`LockKind`]. +pub struct LoroLockGroup { + g: Arc<ThreadLocal<Mutex<LockInfo>>>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +/// Logical lock kinds that define the allowed acquisition order. +/// +/// Kinds with smaller numeric values must be acquired before larger ones, and +/// they must be released in reverse order. The specific variants reflect the +/// high-level components in the system; extend this enum carefully to preserve +/// a consistent global ordering. +pub enum LockKind { + None = 0, + Txn = 1, + OpLog = 2, + DocState = 3, + DiffCalculator = 4, +} + +impl LoroLockGroup { + /// Create a new lock group. + /// + /// Cloning the returned group is cheap. All locks created from clones of + /// the same group still share the same ordering domain. + pub fn new() -> Self { + let g = Arc::new(ThreadLocal::new()); + LoroLockGroup { g } + } + + /// Create a new lock associated with this group and [`LockKind`]. + /// + /// The created lock participates in this group’s order checks. + pub fn new_lock<T>(&self, value: T, kind: LockKind) -> LoroMutex<T> { + LoroMutex { + lock: Mutex::new(value), + currently_locked_in_this_thread: self.g.clone(), + kind: kind as u8, + txn_gate: TxnGate::new(), + } + } +} + +impl Default for LoroLockGroup { + fn default() -> Self { + Self::new() + } +} + +impl<T> LoroMutex<T> { + /// Keep other threads' document writers out across a compound operation + /// that releases and reacquires the transaction lock. The owning thread + /// (including nested calls) keeps using the normal transaction lock. + /// + /// Must be called before the owner first takes the transaction lock in the + /// operation, so every other writer either finishes before that point or + /// observes `active` after acquiring the transaction mutex. + pub(crate) fn lock_exclusive(&self) -> TxnExclusiveGuard<'_> { + debug_assert_eq!(self.kind, LockKind::Txn as u8); + let gate = &self.txn_gate; + let me = crate::sync::thread::current().id(); + { + let mut owner = gate.owner(); + if let Some((id, depth)) = owner.as_mut() { + if *id == me { + *depth += 1; + return TxnExclusiveGuard { gate, held: None }; + } + } + } + let held = gate.wait_exclusive(); + *gate.owner() = Some((me, 1)); + gate.active.store(true, Ordering::SeqCst); + TxnExclusiveGuard { + gate, + held: Some(held), + } + } + + /// Acquire the underlying mutex. Transaction writers wait while another + /// thread runs a compound operation (see [`Self::lock_exclusive`]). + #[inline] + fn acquire(&self) -> MutexGuard<'_, T> { + let guard = self.lock.lock_with_kind("LoroMutex"); + if self.kind != LockKind::Txn as u8 || !self.txn_gate.must_wait() { + return guard; + } + self.acquire_after_exclusive(guard) + } + + /// Slow path: another thread owns the compound operation. Checking only + /// after taking the mutex is enough: the owner sets `active` before its + /// first transaction lock, so a writer either finishes before that point + /// or sees the flag here. + #[cold] + fn acquire_after_exclusive<'a>(&'a self, mut guard: MutexGuard<'a, T>) -> MutexGuard<'a, T> { + while self.txn_gate.must_wait() { + drop(guard); + drop(self.txn_gate.wait_exclusive()); + guard = self.lock.lock_with_kind("LoroMutex"); + } + guard + } + + #[track_caller] + /// Acquire the lock, enforcing strict increasing [`LockKind`] order. + /// + /// Returns a guard that unlocks when dropped and verifies that it is being + /// released in the reverse acquisition order (LIFO). The callsite is + /// recorded to improve panic diagnostics. + /// + /// Panics: + /// - If the underlying mutex was poisoned by an earlier panic. + /// - If the current thread already holds a lock with kind `>= self.kind`. + /// - If the guard is later dropped out of acquisition order. + pub fn lock(&self) -> LoroMutexGuard<'_, T> { + // Lock-order tracking is a debug-only deadlock-prevention aid. In release + // builds it is compiled out entirely: per-op locking is on the hot path + // (each local op takes the OpLog + DocState locks) and the per-thread + // bookkeeping (a ThreadLocal lookup plus an inner mutex acquired several + // times per lock/unlock) was measured at ~30% of B4 local-edit time. + #[cfg(debug_assertions)] + { + let caller = Location::caller(); + let v = self.currently_locked_in_this_thread.get_or_default(); + let last = *v.lock(); + let this = LockInfo { + kind: self.kind, + caller_location: Some(caller), + }; + if last.kind >= self.kind { + panic!( + "Locking order violation. Current lock: {}, New lock: {}", + last, this + ); + } + + let guard = self.acquire(); + *v.lock() = this; + LoroMutexGuard { + guard, + _inner: LoroMutexGuardInner { + inner: self, + this, + last, + }, + } + } + #[cfg(not(debug_assertions))] + { + let guard = self.acquire(); + LoroMutexGuard { + guard, + _inner: LoroMutexGuardInner { inner: self }, + } + } + } + + /// Returns whether the mutex appears locked at this instant. + /// + /// This is implemented via `try_lock().is_err()` and is intended only for + /// diagnostics. It is race-prone and should not be used to implement logic + /// that depends on the lock state. + pub fn is_locked(&self) -> bool { + self.lock.is_locked() + } + + /// Returns whether acquiring this lock would satisfy the current thread's + /// lock-order constraints. + /// + /// This only checks the order tracker for the current thread. It does not + /// guarantee that acquiring the underlying mutex will be non-blocking. + pub(crate) fn can_lock_in_this_thread(&self) -> bool { + #[cfg(debug_assertions)] + { + let v = self.currently_locked_in_this_thread.get_or_default(); + let last = *v.lock(); + last.kind < self.kind + } + // Without lock-order tracking (release) we cannot tell whether acquiring + // this lock would be reentrant/out-of-order, so we conservatively report + // "no" and let callers use their lock-free fallback (e.g. the cached + // `visible_op_count`, which is kept exact incrementally). + #[cfg(not(debug_assertions))] + { + false + } + } +} + +/// Guard returned by [`LoroMutex::lock`]. +/// +/// Dereferences to the protected data and enforces release-order checks on drop. +/// In most cases, you should keep using this guard type so order tracking remains +/// intact for the duration of the critical section. +pub struct LoroMutexGuard<'a, T> { + guard: MutexGuard<'a, T>, + _inner: LoroMutexGuardInner<'a, T>, +} + +/// RAII helper that updates the per-thread lock info on drop. +/// +/// This is an implementation detail of [`LoroMutexGuard`]. The order-tracking +/// fields exist only in debug builds; in release the inner is a thin wrapper. +struct LoroMutexGuardInner<'a, T> { + #[cfg_attr(not(debug_assertions), allow(dead_code))] + inner: &'a LoroMutex<T>, + #[cfg(debug_assertions)] + this: LockInfo, + #[cfg(debug_assertions)] + last: LockInfo, +} + +impl<T> Deref for LoroMutexGuard<'_, T> { + type Target = T; + + fn deref(&self) -> &Self::Target { + &self.guard + } +} + +impl<T> DerefMut for LoroMutexGuard<'_, T> { + fn deref_mut(&mut self) -> &mut T { + &mut self.guard + } +} + +impl<T: Debug> std::fmt::Debug for LoroMutexGuard<'_, T> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("LoroMutex") + .field("data", &self.guard) + .finish() + } +} + +impl<'a, T> LoroMutexGuard<'a, T> { + /// Extract the underlying [`MutexGuard`], detaching order tracking. + /// + /// This consumes `self`, performs the release-order bookkeeping immediately + /// (making the thread-local lock info revert to the previous state), and + /// returns the raw guard. Subsequent lock acquisitions in this thread will no + /// longer consider this guard as held, which means order violations will not + /// be detected relative to it. + /// + /// Prefer to keep using [`LoroMutexGuard`] unless integrating with APIs that + /// require a plain [`MutexGuard`]. Misuse can lead to missing diagnostics. + pub fn take_guard(self) -> MutexGuard<'a, T> { + self.guard + } +} + +impl<T> Drop for LoroMutexGuardInner<'_, T> { + #[cfg(not(debug_assertions))] + fn drop(&mut self) {} + + #[cfg(debug_assertions)] + fn drop(&mut self) { + let cur = self.inner.currently_locked_in_this_thread.get_or_default(); + let current_lock_info = *cur.lock(); + if current_lock_info.kind != self.this.kind { + let bt = Backtrace::capture(); + eprintln!("Locking release order violation callstack:\n{}", bt); + panic!( + "Locking release order violation. self.this: {}, self.last: {}, current: {}", + self.this, self.last, current_lock_info + ); + } + + *cur.lock() = self.last; + } +} + +// These tests exercise the lock-order instrumentation, which is only compiled +// in debug builds. Skip them under `cargo test --release`. +#[cfg(all(test, debug_assertions))] +mod tests { + use super::*; + + #[test] + #[should_panic(expected = "Locking order violation")] + fn test_locking_order_violation_shows_caller() { + let group = LoroLockGroup::new(); + let mutex1 = group.new_lock(1, LockKind::DocState); + let mutex2 = group.new_lock(2, LockKind::Txn); + + let _guard1 = mutex1.lock(); // Lock higher priority first + let _guard2 = mutex2.lock(); // This should panic with caller info + } + + #[test] + fn test_locking_order_when_dropped_in_order() { + let group = LoroLockGroup::new(); + let mutex1 = group.new_lock(1, LockKind::Txn); + let mutex2 = group.new_lock(2, LockKind::OpLog); + let mutex3 = group.new_lock(3, LockKind::DocState); + let _guard1 = mutex1.lock(); + drop(_guard1); + let _guard2 = mutex2.lock(); + drop(_guard2); + let _guard3 = mutex3.lock(); + } + + #[test] + #[should_panic] + fn test_locking_order_when_not_dropped_in_reverse_order() { + let group = LoroLockGroup::new(); + let mutex1 = group.new_lock(1, LockKind::Txn); + let mutex2 = group.new_lock(2, LockKind::OpLog); + let _guard1 = mutex1.lock(); + let _guard2 = mutex2.lock(); + drop(_guard1); + drop(_guard2); + } + + #[test] + fn test_dropping_should_restore_last_lock_info_0() { + let group = LoroLockGroup::new(); + let mutex1 = group.new_lock(1, LockKind::Txn); + let mutex2 = group.new_lock(2, LockKind::OpLog); + let mutex3 = group.new_lock(3, LockKind::DocState); + let _guard1 = mutex1.lock(); + let _guard3 = mutex3.lock(); + drop(_guard3); + let _guard2 = mutex2.lock(); + drop(_guard2); + } + + #[test] + #[should_panic] + fn test_dropping_should_restore_last_lock_info_1() { + let group = LoroLockGroup::new(); + let mutex1 = group.new_lock(1, LockKind::Txn); + let mutex2 = group.new_lock(2, LockKind::OpLog); + let mutex3 = group.new_lock(3, LockKind::DocState); + let _guard2 = mutex2.lock(); + let _guard3 = mutex3.lock(); + drop(_guard3); + let _guard1 = mutex1.lock(); + } + + #[test] + fn test_nested_locking_same_kind() { + let group = LoroLockGroup::new(); + let mutex1 = group.new_lock(1, LockKind::Txn); + let mutex2 = group.new_lock(2, LockKind::Txn); + + let guard1 = mutex1.lock(); + // Locking same kind should work (cur >= self.kind, so this would fail) + // Actually, let's test this properly - same kind should fail + drop(guard1); + + let _guard2 = mutex2.lock(); // This should work when guard1 is dropped + } + + #[test] + fn test_lock_kind_enum_values() { + assert_eq!(LockKind::None as u8, 0); + assert_eq!(LockKind::Txn as u8, 1); + assert_eq!(LockKind::OpLog as u8, 2); + assert_eq!(LockKind::DocState as u8, 3); + assert_eq!(LockKind::DiffCalculator as u8, 4); + } + + #[test] + fn test_is_locked_functionality() { + let group = LoroLockGroup::new(); + let mutex = group.new_lock(42, LockKind::Txn); + + assert!(!mutex.is_locked()); + + let _guard = mutex.lock(); + assert!(mutex.is_locked()); + } + + // Helper function to test that panic messages contain caller info + #[test] + #[should_panic(expected = "Locking order violation")] + fn test_panic_message_contains_location_info() { + let group = LoroLockGroup::new(); + let mutex1 = group.new_lock(1, LockKind::DocState); + let mutex2 = group.new_lock(2, LockKind::Txn); + + let _guard1 = mutex1.lock(); + + // This line should be reported in the panic message + let _guard2 = mutex2.lock(); + } + + #[test] + #[should_panic(expected = "poisoned LoroMutex")] + fn test_poisoned_lock_panics_after_unwind() { + let group = LoroLockGroup::new(); + let mutex = group.new_lock(42, LockKind::Txn); + + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _guard = mutex.lock(); + panic!("poison the lock"); + })); + + let _ = mutex.lock(); + } +} + +#[cfg(all(test, not(loom)))] +mod txn_gate_tests { + use super::*; + use std::sync::mpsc; + use std::time::Duration; + + #[test] + fn owner_thread_nests_and_writes_without_blocking() { + let group = LoroLockGroup::new(); + let txn = group.new_lock(0, LockKind::Txn); + let outer = txn.lock_exclusive(); + { + let _inner = txn.lock_exclusive(); + *txn.lock() += 1; + } + // The nested guard must not release the gate. + assert!(txn.txn_gate.active.load(Ordering::SeqCst)); + *txn.lock() += 1; + drop(outer); + assert!(!txn.txn_gate.active.load(Ordering::SeqCst)); + assert_eq!(*txn.lock(), 2); + } + + #[test] + fn other_writers_wait_for_the_compound_operation() { + let group = LoroLockGroup::new(); + let txn = Arc::new(group.new_lock(Vec::new(), LockKind::Txn)); + let exclusive = txn.lock_exclusive(); + txn.lock().push("owner-1"); + let (done, finished) = mpsc::channel(); + let writer = { + let txn = txn.clone(); + std::thread::spawn(move || { + txn.lock().push("writer"); + done.send(()).unwrap(); + }) + }; + // The writer cannot run between the owner's two transaction sections. + assert!(finished.recv_timeout(Duration::from_millis(100)).is_err()); + txn.lock().push("owner-2"); + drop(exclusive); + finished.recv_timeout(Duration::from_secs(10)).unwrap(); + writer.join().unwrap(); + assert_eq!(*txn.lock(), vec!["owner-1", "owner-2", "writer"]); + } + + #[test] + fn a_panic_inside_the_compound_operation_does_not_block_later_writers() { + let group = LoroLockGroup::new(); + let txn = Arc::new(group.new_lock(0, LockKind::Txn)); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _exclusive = txn.lock_exclusive(); + panic!("undo failed"); + })); + assert!(result.is_err()); + assert!(!txn.txn_gate.active.load(Ordering::SeqCst)); + let other = { + let txn = txn.clone(); + std::thread::spawn(move || { + *txn.lock() += 1; + drop(txn.lock_exclusive()); + }) + }; + other.join().unwrap(); + drop(txn.lock_exclusive()); + assert_eq!(*txn.lock(), 1); + } +} diff --git a/vendor/loro-internal/src/loro.rs b/vendor/loro-internal/src/loro.rs new file mode 100644 index 0000000..bfb4817 --- /dev/null +++ b/vendor/loro-internal/src/loro.rs @@ -0,0 +1,5041 @@ +use crate::encoding::json_schema::{encode_change, export_json_in_id_span}; +pub use crate::encoding::ExportMode; +use crate::pre_commit::{FirstCommitFromPeerCallback, FirstCommitFromPeerPayload}; +pub use crate::state::analyzer::{ContainerAnalysisInfo, DocAnalysis}; +use crate::sync::{AtomicBool, AtomicUsize}; +pub(crate) use crate::LoroDocInner; +use crate::{ + arena::{SharedArena, SharedArenaRollback}, + change::{Change, Timestamp}, + configure::{Configure, DefaultRandom, SecureRandomGenerator, StyleConfig}, + container::{ + idx::ContainerIdx, list::list_op::InnerListOp, richtext::config::StyleConfigMap, + IntoContainerId, + }, + cursor::{AbsolutePosition, CannotFindRelativePosition, Cursor, PosQueryResult}, + dag::{Dag, DagUtils}, + diff_calc::{DiffCalculator, DiffMode}, + encoding::{ + self, decode_snapshot, export_fast_snapshot, export_fast_updates, + export_fast_updates_in_range, export_shallow_snapshot, export_snapshot_at, + export_state_only_snapshot, + json_schema::{encode_change_to_json, json::JsonSchema}, + parse_header_and_body, EncodeMode, ImportBlobMetadata, ImportStatus, ParsedHeaderAndBody, + }, + event::{str_to_path, EventTriggerKind, Index, InternalDocDiff}, + handler::{Handler, MovableListHandler, TextHandler, TreeHandler, ValueOrHandler}, + id::PeerID, + json::JsonChange, + op::InnerContent, + oplog::{loro_dag::FrontiersNotIncluded, ImportedValues, OpLog}, + state::DocState, + subscription::{LocalUpdateCallback, Observer, Subscriber}, + undo::DiffBatch, + utils::subscription::{SubscriberSetWithQueue, Subscription}, + version::{Frontiers, ImVersionVector, VersionRange, VersionVectorDiff}, + ChangeMeta, DocDiff, HandlerTrait, InternalString, ListHandler, LoroDoc, LoroError, MapHandler, + VersionVector, +}; +use crate::{change::ChangeRef, lock::LockKind}; +use crate::{lock::LoroMutexGuard, pre_commit::PreCommitCallback}; +use crate::{ + lock::{LoroLockGroup, LoroMutex}, + txn::Transaction, +}; +use either::Either; + +#[cfg(test)] +thread_local! { + pub(crate) static FAIL_APPLY_DIFF_AFTER_HANDLER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + pub(crate) static RUN_APPLY_DIFF_HOOK_AFTER_NATIVE_PLAN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + pub(crate) static FAIL_APPLY_DIFF_WITH_ARG_ERR: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + pub(crate) static AFTER_APPLY_DIFF_HANDLER: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) }; +} + +#[cfg(test)] +fn after_apply_diff_handler() -> LoroResult<()> { + AFTER_APPLY_DIFF_HANDLER.with(|hook| { + if let Some(hook) = hook.borrow_mut().take() { + hook(); + } + }); + if FAIL_APPLY_DIFF_AFTER_HANDLER.with(|flag| flag.replace(false)) { + if FAIL_APPLY_DIFF_WITH_ARG_ERR.with(|flag| flag.replace(false)) { + return Err(LoroError::ArgErr("injected application error".into())); + } + Err(LoroError::OutOfBound { + pos: usize::MAX, + len: 0, + info: "injected apply failure".into(), + }) + } else { + Ok(()) + } +} +use loro_common::{ + ContainerID, ContainerType, HasCounterSpan, HasIdSpan, HasLamportSpan, IdSpan, LoroEncodeError, + LoroResult, LoroValue, ID, +}; +use rle::HasLength; +use rustc_hash::{FxHashMap, FxHashSet}; +use std::{ + borrow::Cow, + cmp::Ordering, + collections::{hash_map::Entry, BinaryHeap}, + ops::ControlFlow, + sync::{ + atomic::Ordering::{Acquire, Release}, + Arc, + }, +}; +use tracing::{debug_span, info_span, instrument, warn}; + +use crate::utils::subscription::DeferredPanic; + +impl Default for LoroDoc { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +thread_local! { + /// Countdown of blobs `LoroDoc::import_batch` may import before panicking, standing + /// in for the decode/apply panics that malformed remote data can trigger. + static PANIC_AT_BATCH_IMPORT_BLOB: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +pub(crate) fn panic_at_batch_import_blob_for_test(blobs_to_import_first: usize) { + PANIC_AT_BATCH_IMPORT_BLOB.with(|f| f.set(Some(blobs_to_import_first))); +} + +#[cfg(test)] +fn take_panic_at_batch_import_blob_for_test() { + PANIC_AT_BATCH_IMPORT_BLOB.with(|f| match f.get() { + Some(0) => { + f.set(None); + panic!("batch import failpoint"); + } + Some(n) => f.set(Some(n - 1)), + None => {} + }); +} + +impl std::fmt::Debug for LoroDocInner { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("LoroDoc") + .field("config", &self.config) + .field("auto_commit", &self.auto_commit) + .field("detached", &self.detached) + .finish() + } +} + +#[cfg(test)] +thread_local! { + /// How many imports took the independent scalar-root fast path. + static ISOLATED_FAST_PATH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +#[cfg(test)] +pub(crate) fn isolated_fast_path_hits_for_test() -> usize { + ISOLATED_FAST_PATH_HITS.with(|hits| hits.get()) +} + +impl LoroDoc { + /// Run the provided closure within a commit barrier. + /// + /// This finalizes any pending auto-commit transaction first (preserving + /// options across an empty txn), executes `f`, then renews the transaction + /// (carrying preserved options) if auto-commit is enabled. This is the + /// common implicit-commit pattern used by internal operations such as + /// import/export/checkouts. + #[inline] + pub fn with_barrier<F, R>(&self, f: F) -> R + where + F: FnOnce() -> R, + { + let (options, guard) = self.implicit_commit_then_stop(); + // `f` may call user code, e.g. subscribers of an import's events. If it + // panics, release the txn lock first, so the panic does not poison it. + // A panic inside Loro may have poisoned another lock, which makes the + // renewal panic too; `DeferredPanic` keeps the first one. + let mut panic = DeferredPanic::default(); + let result = panic.run(f); + drop(guard); + panic.run(|| self.renew_txn_if_auto_commit(options)); + panic.resume(); + result.unwrap() + } + + pub fn new() -> Self { + let visible_op_count = Arc::new(AtomicUsize::new(0)); + let oplog = OpLog::new(visible_op_count.clone()); + let arena = oplog.arena.clone(); + let config: Configure = oplog.configure.clone(); + let lock_group = LoroLockGroup::new(); + let global_txn = Arc::new(lock_group.new_lock(None, LockKind::Txn)); + let inner = Arc::new_cyclic(|w| { + let state = DocState::new_arc(w.clone(), arena.clone(), config.clone(), &lock_group); + LoroDocInner { + oplog: Arc::new(lock_group.new_lock(oplog, LockKind::OpLog)), + state, + config, + visible_op_count, + detached: AtomicBool::new(false), + auto_commit: AtomicBool::new(false), + observer: Arc::new(Observer::new(arena.clone())), + diff_calculator: Arc::new( + lock_group.new_lock(DiffCalculator::new(true), LockKind::DiffCalculator), + ), + txn: global_txn, + arena, + local_update_subs: SubscriberSetWithQueue::new(), + peer_id_change_subs: SubscriberSetWithQueue::new(), + pre_commit_subs: SubscriberSetWithQueue::new(), + first_commit_from_peer_subs: SubscriberSetWithQueue::new(), + } + }); + LoroDoc { inner } + } + + pub fn fork(&self) -> Self { + if self.is_detached() { + return self + .fork_at_inner(&self.state_frontiers(), false) + .expect("fork_at on detached doc should not fail"); + } + + let snapshot = self + .with_barrier(|| encoding::fast_snapshot::encode_snapshot_inner_for_fork(self)) + .expect("forking a valid document should encode a snapshot"); + let doc = Self::new(); + doc.with_barrier(|| { + encoding::fast_snapshot::decode_snapshot_inner(snapshot, &doc, Default::default()) + }) + .unwrap(); + doc.set_config(&self.config); + if self.auto_commit.load(std::sync::atomic::Ordering::Relaxed) { + doc.start_auto_commit(); + } + doc + } + /// Enables editing of the document in detached mode. + /// + /// By default, the document cannot be edited in detached mode (after calling + /// `detach` or checking out a version other than the latest). This method + /// allows editing in detached mode. + /// + /// # Important Notes: + /// + /// - After enabling this mode, the document will use a different PeerID. Each + /// time you call checkout, a new PeerID will be used. + /// - If you set a custom PeerID while this mode is enabled, ensure that + /// concurrent operations with the same PeerID are not possible. + /// - On detached mode, importing will not change the state of the document. + /// It also doesn't change the version of the [DocState]. The changes will be + /// recorded into [OpLog] only. You need to call `checkout` to make it take effect. + pub fn set_detached_editing(&self, enable: bool) { + self.config.set_detached_editing(enable); + if enable && self.is_detached() { + self.with_barrier(|| { + self.renew_peer_id(); + }); + } + } + + /// Create a doc with auto commit enabled. + #[inline] + pub fn new_auto_commit() -> Self { + let doc = Self::new(); + doc.start_auto_commit(); + doc + } + + #[inline(always)] + pub fn set_peer_id(&self, peer: PeerID) -> LoroResult<()> { + if peer == PeerID::MAX { + return Err(LoroError::InvalidPeerID); + } + let next_id = self.oplog.lock().next_id(peer); + if self.auto_commit.load(Acquire) { + let doc_state = self.state.lock(); + doc_state + .peer + .store(peer, std::sync::atomic::Ordering::Relaxed); + + if doc_state.is_in_txn() { + drop(doc_state); + // Use implicit-style barrier to avoid swallowing next-commit options + self.with_barrier(|| {}); + } + self.peer_id_change_subs.emit(&(), next_id); + return Ok(()); + } + + let doc_state = self.state.lock(); + if doc_state.is_in_txn() { + return Err(LoroError::TransactionError( + "Cannot change peer id during transaction" + .to_string() + .into_boxed_str(), + )); + } + + doc_state + .peer + .store(peer, std::sync::atomic::Ordering::Relaxed); + drop(doc_state); + self.peer_id_change_subs.emit(&(), next_id); + Ok(()) + } + + /// Renews the PeerID for the document. + pub(crate) fn renew_peer_id(&self) { + let mut peer_id = DefaultRandom.next_u64(); + while peer_id == PeerID::MAX { + peer_id = DefaultRandom.next_u64(); + } + self.set_peer_id(peer_id).unwrap(); + } + + /// Implicitly commit the cumulative auto-commit transaction. + /// This method only has effect when `auto_commit` is true. + /// + /// Follow-ups: the caller is responsible for renewing the transaction + /// as needed (e.g., via `renew_txn_if_auto_commit`). Prefer using + /// `with_barrier(...)` for most internal flows to handle this safely. + /// + /// Empty-commit behavior: if the pending transaction is empty, the returned + /// `Some(CommitOptions)` preserves next-commit options such as message and + /// timestamp so they can carry into the renewed transaction. Transient + /// labels like `origin` do not carry across an empty commit. + #[inline] + #[must_use] + pub fn implicit_commit_then_stop( + &self, + ) -> ( + Option<CommitOptions>, + LoroMutexGuard<'_, Option<Transaction>>, + ) { + // Implicit commit: preserve options on empty commit + let (a, b) = self.commit_internal(CommitOptions::new().immediate_renew(false), true); + (a, b.unwrap()) + } + + /// Commit the cumulative auto commit transaction. + /// It will start the next one immediately + /// + /// It only returns Some(options_of_the_empty_txn) when the txn is empty + #[inline] + pub fn commit_then_renew(&self) -> Option<CommitOptions> { + // Explicit commit: swallow options on empty commit + self.commit_internal(CommitOptions::new().immediate_renew(true), false) + .0 + } + + /// This method is called before the commit. + /// It can be used to modify the change before it is committed. + /// + /// It return Some(txn) if the txn is None + fn before_commit(&self) -> Option<LoroMutexGuard<'_, Option<Transaction>>> { + let mut txn_guard = self.txn.lock(); + let Some(txn) = txn_guard.as_mut() else { + return Some(txn_guard); + }; + + if txn.is_peer_first_appearance { + txn.is_peer_first_appearance = false; + drop(txn_guard); + // First commit from a peer + self.first_commit_from_peer_subs.emit( + &(), + FirstCommitFromPeerPayload { + peer: self.peer_id(), + }, + ); + } + + None + } + + /// Core implementation for committing the cumulative auto-commit transaction. + /// + /// - When `preserve_on_empty` is true (implicit commits like export/checkout), + /// commit options from an empty transaction are carried over to the next transaction + /// (except `origin`, which never carries across an empty commit). + /// - When `preserve_on_empty` is false (explicit commits), commit options from an + /// empty transaction are swallowed and NOT carried over. + /// + /// A pre-commit callback that panics does not stop the commit; its panic is + /// raised after the txn lock is released, so the lock is not poisoned. + #[instrument(skip_all)] + fn commit_internal( + &self, + config: CommitOptions, + preserve_on_empty: bool, + ) -> ( + Option<CommitOptions>, + Option<LoroMutexGuard<'_, Option<Transaction>>>, + ) { + let mut panic = DeferredPanic::default(); + let ans = self.commit_internal_inner(config, preserve_on_empty, &mut panic); + if !panic.has_panic() { + return ans; + } + drop(ans); + panic.resume(); + unreachable!("resume raises the deferred panic") + } + + fn commit_internal_inner( + &self, + config: CommitOptions, + preserve_on_empty: bool, + panic: &mut DeferredPanic, + ) -> ( + Option<CommitOptions>, + Option<LoroMutexGuard<'_, Option<Transaction>>>, + ) { + if !self.auto_commit.load(Acquire) { + let txn_guard = self.txn.lock(); + // if not auto_commit, nothing should happen + // because the global txn is not used + return (None, Some(txn_guard)); + } + + loop { + if let Some(txn_guard) = self.before_commit() { + return (None, Some(txn_guard)); + } + + let mut txn_guard = self.txn.lock(); + let txn = txn_guard.take(); + let Some(mut txn) = txn else { + return (None, Some(txn_guard)); + }; + let on_commit = txn.take_on_commit(); + if let Some(origin) = config.origin.clone() { + txn.set_origin(origin); + } + + if let Some(timestamp) = config.timestamp { + txn.set_timestamp(timestamp); + } + + if let Some(msg) = config.commit_msg.as_ref() { + txn.set_msg(Some(msg.clone())); + } + + let id_span = txn.id_span(); + let mut options = txn.commit_deferring_panic(panic).unwrap(); + // Empty commit returns Some(options). We may preserve parts of it for implicit commits. + if let Some(opts) = options.as_mut() { + // `origin` is an event-only label and never carries across an empty commit + if config.origin.is_some() { + opts.set_origin(None); + } + // For explicit commits, swallow options from empty commit entirely + if !preserve_on_empty { + options = None; + } + } + if config.immediate_renew && self.can_edit() { + let mut t = self.txn().unwrap(); + if let Some(options) = options.as_ref() { + t.set_options(options.clone()); + } + *txn_guard = Some(t); + } + + if let Some(on_commit) = on_commit { + drop(txn_guard); + on_commit(&self.state, &self.oplog, id_span); + txn_guard = self.txn.lock(); + if !config.immediate_renew && txn_guard.is_some() { + // make sure that txn_guard is None when config.immediate_renew is false + continue; + } + } + + return ( + options, + if !config.immediate_renew { + Some(txn_guard) + } else { + None + }, + ); + } + } + + /// Commit the cumulative auto commit transaction (explicit API). + /// + /// This is used by user-facing explicit commits. If the transaction is empty, + /// any provided commit options are swallowed and will NOT carry over. + #[instrument(skip_all)] + pub fn commit_with( + &self, + config: CommitOptions, + ) -> ( + Option<CommitOptions>, + Option<LoroMutexGuard<'_, Option<Transaction>>>, + ) { + self.commit_internal(config, false) + } + + /// Set the commit message of the next commit + pub fn set_next_commit_message(&self, message: &str) { + let mut binding = self.txn.lock(); + let Some(txn) = binding.as_mut() else { + return; + }; + + if message.is_empty() { + txn.set_msg(None) + } else { + txn.set_msg(Some(message.into())) + } + } + + /// Set the origin of the next commit + pub fn set_next_commit_origin(&self, origin: &str) { + let mut txn = self.txn.lock(); + if let Some(txn) = txn.as_mut() { + txn.set_origin(origin.into()); + } + } + + /// Set the timestamp of the next commit + pub fn set_next_commit_timestamp(&self, timestamp: Timestamp) { + let mut txn = self.txn.lock(); + if let Some(txn) = txn.as_mut() { + txn.set_timestamp(timestamp); + } + } + + /// Set the options of the next commit + pub fn set_next_commit_options(&self, options: CommitOptions) { + let mut txn = self.txn.lock(); + if let Some(txn) = txn.as_mut() { + txn.set_options(options); + } + } + + /// Clear the options of the next commit + pub fn clear_next_commit_options(&self) { + let mut txn = self.txn.lock(); + if let Some(txn) = txn.as_mut() { + txn.set_options(CommitOptions::new()); + } + } + + /// Set whether to record the timestamp of each change. Default is `false`. + /// + /// If enabled, the Unix timestamp will be recorded for each change automatically. + /// + /// You can also set each timestamp manually when you commit a change. + /// The timestamp manually set will override the automatic one. + /// + /// NOTE: Timestamps are forced to be in ascending order. + /// If you commit a new change with a timestamp that is less than the existing one, + /// the largest existing timestamp will be used instead. + #[inline] + pub fn set_record_timestamp(&self, record: bool) { + self.config.set_record_timestamp(record); + } + + pub fn decoded_value_cache_limit(&self) -> usize { + self.config.decoded_value_cache_limit() + } + + pub fn set_decoded_value_cache_limit(&self, limit: usize) { + self.state.lock().store.set_decoded_value_cache_limit(limit); + } + + /// Set the interval of mergeable changes, in seconds. + /// + /// If two continuous local changes are within the interval, they will be merged into one change. + /// The default value is 1000 seconds. + #[inline] + pub fn set_change_merge_interval(&self, interval: i64) { + self.config.set_merge_interval(interval); + } + + pub fn can_edit(&self) -> bool { + !self.is_detached() || self.config.detached_editing() + } + + pub fn is_detached_editing_enabled(&self) -> bool { + self.config.detached_editing() + } + + #[inline] + pub fn config_text_style(&self, text_style: StyleConfigMap) { + self.config.text_style_config.write().map = text_style.map; + } + + #[inline] + pub fn config_default_text_style(&self, text_style: Option<StyleConfig>) { + self.config.text_style_config.write().default_style = text_style; + } + pub fn from_snapshot(bytes: &[u8]) -> LoroResult<Self> { + let doc = Self::new(); + let ParsedHeaderAndBody { mode, body, .. } = parse_header_and_body(bytes, true)?; + if mode.is_snapshot() { + doc.with_barrier(|| -> Result<(), LoroError> { + decode_snapshot(&doc, mode, body, Default::default())?; + Ok(()) + })?; + Ok(doc) + } else { + Err(LoroError::DecodeError( + "Invalid encode mode".to_string().into(), + )) + } + } + + /// Is the document empty? (no ops) + #[inline(always)] + pub fn can_reset_with_snapshot(&self) -> bool { + let oplog = self.oplog.lock(); + if oplog.batch_importing { + return false; + } + + if self.is_detached() { + return false; + } + + oplog.is_empty() && self.state.lock().can_import_snapshot() + } + + /// Whether [OpLog] and [DocState] are detached. + /// + /// If so, the document is in readonly mode by default and importing will not change the state of the document. + /// It also doesn't change the version of the [DocState]. The changes will be recorded into [OpLog] only. + /// You need to call `checkout` to make it take effect. + #[inline(always)] + pub fn is_detached(&self) -> bool { + self.detached.load(Acquire) + } + + pub(crate) fn set_detached(&self, detached: bool) { + self.detached.store(detached, Release); + } + + #[inline(always)] + pub fn peer_id(&self) -> PeerID { + self.state + .lock() + .peer + .load(std::sync::atomic::Ordering::Relaxed) + } + + #[inline(always)] + pub fn detach(&self) { + self.with_barrier(|| self.set_detached(true)); + } + + #[inline(always)] + pub fn attach(&self) { + self.checkout_to_latest() + } + + /// Get the timestamp of the current state. + /// It's the last edit time of the [DocState]. + pub fn state_timestamp(&self) -> Timestamp { + // Acquire locks in correct order: read frontiers first, then query OpLog. + let f = { self.state.lock().frontiers.clone() }; + self.oplog.lock().get_timestamp_of_version(&f) + } + + #[inline(always)] + pub fn app_state(&self) -> &Arc<LoroMutex<DocState>> { + &self.state + } + + #[inline] + pub fn get_state_deep_value(&self) -> LoroValue { + self.state.lock().get_deep_value() + } + + #[inline(always)] + pub fn oplog(&self) -> &Arc<LoroMutex<OpLog>> { + &self.oplog + } + + #[inline(always)] + pub fn import(&self, bytes: &[u8]) -> Result<ImportStatus, LoroError> { + let s = debug_span!("import", peer = self.peer_id()); + let _e = s.enter(); + self.import_with(bytes, Default::default()) + } + + #[inline] + pub fn import_with( + &self, + bytes: &[u8], + origin: InternalString, + ) -> Result<ImportStatus, LoroError> { + self.import_with_history_mode(bytes, origin, false) + } + + /// Import binary bytes. `json_lossy` accepts only the equivalences a JSON hop + /// can introduce; the default binary path passes `false`. + pub fn import_with_history_mode( + &self, + bytes: &[u8], + origin: InternalString, + json_lossy: bool, + ) -> Result<ImportStatus, LoroError> { + let values = if json_lossy { + ImportedValues::JsonLossy + } else { + ImportedValues::Exact + }; + self.with_barrier(|| self._import_with(bytes, origin, values)) + } + + #[tracing::instrument(skip_all)] + fn _import_with( + &self, + bytes: &[u8], + origin: InternalString, + values: ImportedValues, + ) -> Result<ImportStatus, LoroError> { + let result = self.import_without_emitting(bytes, origin, values); + self.emit_events(); + result + } + + fn import_without_emitting( + &self, + bytes: &[u8], + origin: InternalString, + values: ImportedValues, + ) -> Result<ImportStatus, LoroError> { + ensure_cov::notify_cov("loro_internal::import"); + let parsed = parse_header_and_body(bytes, true)?; + loro_common::info!("Importing with mode={:?}", &parsed.mode); + match parsed.mode { + EncodeMode::OutdatedRle => { + if self.state.lock().is_in_txn() { + return Err(LoroError::ImportWhenInTxn); + } + + let s = tracing::span!( + tracing::Level::INFO, + "Import updates ", + peer = self.peer_id() + ); + let _e = s.enter(); + self.update_oplog_and_apply_delta_to_state_if_needed( + |oplog| oplog.decode(parsed, values), + origin, + ) + } + EncodeMode::OutdatedSnapshot => { + if self.can_reset_with_snapshot() { + loro_common::info!("Init by snapshot {}", self.peer_id()); + decode_snapshot(self, parsed.mode, parsed.body, origin) + } else { + self.update_oplog_and_apply_delta_to_state_if_needed( + |oplog| oplog.decode(parsed, values), + origin, + ) + } + } + EncodeMode::FastSnapshot => { + if self.can_reset_with_snapshot() { + ensure_cov::notify_cov("loro_internal::import::snapshot"); + loro_common::info!("Init by fast snapshot {}", self.peer_id()); + decode_snapshot(self, parsed.mode, parsed.body, origin) + } else { + self.import_changes_and_apply_delta_to_state_if_needed( + |oplog| encoding::decode_oplog_changes(oplog, parsed, values), + values, + origin, + ) + + // let new_doc = LoroDoc::new(); + // new_doc.import(bytes)?; + // let updates = new_doc.export(ExportMode::updates(&self.oplog_vv())).unwrap(); + // return self.import_with(updates.as_slice(), origin); + } + } + EncodeMode::FastUpdates => self.import_changes_and_apply_delta_to_state_if_needed( + |oplog| encoding::decode_oplog_changes(oplog, parsed, values), + values, + origin, + ), + EncodeMode::Auto => { + unreachable!() + } + } + } + + #[tracing::instrument(skip_all)] + pub(crate) fn update_oplog_and_apply_delta_to_state_if_needed( + &self, + f: impl FnOnce(&mut OpLog) -> Result<ImportStatus, LoroError>, + origin: InternalString, + ) -> Result<ImportStatus, LoroError> { + let mut oplog = self.oplog.lock(); + // `import_batch` opens a rollback scope that spans the whole batch. Rollback + // scopes cannot nest (the inner `begin` would clobber the outer journal), so + // when one is already open we let the owner decide what to keep: the batch + // scope rolls the whole batch back if its final reattach fails, and commits + // everything otherwise. + let owns_rollback = !oplog.has_import_rollback(); + if owns_rollback { + oplog.begin_import_rollback(); + } + if !self.is_detached() { + let old_vv = oplog.vv().clone(); + let old_frontiers = oplog.frontiers().clone(); + let result = f(&mut oplog); + if &old_vv != oplog.vv() { + let mut diff = DiffCalculator::new(false); + let computed = diff.try_calc_diff_internal( + &oplog, + &old_vv, + &old_frontiers, + oplog.vv(), + oplog.dag.get_frontiers(), + None, + ); + let (diff, diff_mode) = match computed { + Ok(diff) => diff, + Err(err) => { + oplog.rollback_owned_import(owns_rollback, &mut self.state.lock()); + return Err(err); + } + }; + let mut state = self.state.lock(); + if let Err(e) = state.apply_diff( + InternalDocDiff { + origin, + diff: (diff).into(), + by: EventTriggerKind::Import, + new_version: Cow::Owned(oplog.frontiers().clone()), + }, + diff_mode, + ) { + oplog.rollback_owned_import(owns_rollback, &mut state); + return Err(e); + } + } + match result { + Ok(result) => { + oplog.commit_owned_import_rollback(owns_rollback); + Ok(result) + } + Err(e) => { + // Some import errors are reported after a valid prefix has + // been inserted into the oplog. Keep that prefix if it was + // also applied to state; rollback is for failed state apply + // or decode errors that made no visible oplog progress. + let keep_prefix = &old_vv != oplog.vv(); + if keep_prefix { + oplog.commit_owned_import_rollback(owns_rollback); + } else { + oplog.rollback_owned_import(owns_rollback, &mut self.state.lock()); + } + Err(e) + } + } + } else { + match f(&mut oplog) { + Ok(result) => { + oplog.commit_owned_import_rollback(owns_rollback); + Ok(result) + } + Err(e) => { + oplog.rollback_owned_import(owns_rollback, &mut self.state.lock()); + Err(e) + } + } + } + } + + #[tracing::instrument(skip_all)] + pub(crate) fn import_changes_and_apply_delta_to_state_if_needed( + &self, + decode_changes: impl FnOnce(&mut OpLog) -> Result<Vec<Change>, LoroError>, + values: ImportedValues, + origin: InternalString, + ) -> Result<ImportStatus, LoroError> { + let mut oplog = self.oplog.lock(); + oplog.check_history_parsable()?; + let arena_checkpoint = oplog.arena.checkpoint_for_rollback(); + let changes = match decode_changes(&mut oplog) + .and_then(|changes| oplog.check_and_trim_known_part_of_changes(changes, values)) + { + Ok(changes) => changes, + Err(e) => { + oplog.rollback_arena(arena_checkpoint, &mut self.state.lock()); + return Err(e); + } + }; + + // Read once: attach/detach can change the flag without the oplog lock. + // The apply branch must use the same mode as preflight's rollback decision. + let detached = self.is_detached(); + let preflight = match oplog.preflight_import_changes(&changes, detached) { + Ok(preflight) => preflight, + Err(err) => { + oplog.rollback_arena(arena_checkpoint, &mut self.state.lock()); + return Err(err); + } + }; + if preflight.has_deps_before_shallow_root && (detached || !preflight.applies_to_dag) { + oplog.rollback_arena(arena_checkpoint, &mut self.state.lock()); + return Err(LoroError::ImportUpdatesThatDependsOnOutdatedVersion); + } + + if detached { + // An enclosing `import_batch` scope validates the whole batch before it + // reattaches (`BatchImportGuard::finish`). + let owns_rollback = + preflight.needs_state_apply_rollback && !oplog.has_import_rollback(); + if owns_rollback { + oplog.begin_import_rollback_with_arena(arena_checkpoint); + } + let result = match encoding::apply_decoded_changes_to_oplog(&mut oplog, changes) { + Ok(result) => result, + Err(err) => { + if owns_rollback { + oplog.rollback_import(&mut self.state.lock()); + } + return Err(err); + } + }; + if owns_rollback { + if let Err(e) = oplog.validate_movable_list_elem_refs_in_import_scope() { + oplog.rollback_import(&mut self.state.lock()); + return Err(e); + } + oplog.commit_import_rollback(); + } + if result.has_deps_before_shallow_root { + return Err(LoroError::ImportUpdatesThatDependsOnOutdatedVersion); + } + + return Ok(result.status); + } + + if !preflight.applies_to_dag { + let pending_root_containers = + match pending_root_containers_to_materialize(&oplog, &changes) { + Ok(ids) => ids, + Err(err) => { + oplog.rollback_arena(arena_checkpoint, &mut self.state.lock()); + return Err(err); + } + }; + let result = match encoding::apply_decoded_changes_to_oplog(&mut oplog, changes) { + Ok(result) => result, + Err(err) => { + if !oplog.has_import_rollback() { + oplog.rollback_arena(arena_checkpoint, &mut self.state.lock()); + } + return Err(err); + } + }; + if result.has_deps_before_shallow_root { + oplog.rollback_arena(arena_checkpoint, &mut self.state.lock()); + return Err(LoroError::ImportUpdatesThatDependsOnOutdatedVersion); + } + + if !pending_root_containers.is_empty() { + let mut state = self.state.lock(); + for id in pending_root_containers { + state.ensure_container(&id); + } + } + + return Ok(result.status); + } + + let old_vv = Arc::new(oplog.vv().clone()); + let old_frontiers = oplog.frontiers().clone(); + // Checked before the changes are applied, while the store still holds only old history. + let isolated_batch = isolated_scalar_root_batch(&oplog, &changes).filter(|(_, names)| { + let mut state = self.state.lock(); + names.iter().all(|name| { + let id = ContainerID::new_root(name, ContainerType::Map); + !state.store.contains_id(&id) + }) + }); + let rollback_enabled = + preflight.needs_state_apply_rollback || oplog.change_store().may_have_unparsed_bodies(); + if rollback_enabled { + oplog.begin_import_rollback_with_version(arena_checkpoint, old_vv.clone()); + } + + let result = match encoding::apply_decoded_changes_to_oplog(&mut oplog, changes) { + Ok(result) => result, + Err(err) => { + oplog.rollback_owned_import(rollback_enabled, &mut self.state.lock()); + return Err(err); + } + }; + if old_vv.as_ref() != oplog.vv() { + // The preflight enables rollback whenever the imported or unlocked + // pending changes hold movable-list ops, so other imports skip the scan. + if rollback_enabled { + if let Err(e) = oplog.validate_movable_list_elem_refs_in_import_scope() { + oplog.rollback_import(&mut self.state.lock()); + return Err(e); + } + } + let mut calc = DiffCalculator::new(false); + // Applying may have unlocked pending changes; the isolated fast path is only valid + // when exactly the candidate batch was appended on top of the old version. + let isolated_batch = isolated_batch.filter(|(component_vv, _)| { + component_vv + .iter() + .all(|(peer, end)| oplog.vv().get(peer) == Some(end)) + && oplog.vv().iter().all(|(peer, end)| { + let old_end = old_vv.get(peer).copied().unwrap_or(0); + let component_end = component_vv.get(peer).copied().unwrap_or(0); + *end == old_end.max(component_end) + }) + }); + let computed = (|| -> LoroResult<_> { + let (diff, diff_mode) = if let Some((component_vv, _)) = isolated_batch { + #[cfg(test)] + ISOLATED_FAST_PATH_HITS.with(|hits| hits.set(hits.get() + 1)); + let component_frontiers = oplog.dag.try_vv_to_frontiers(&component_vv)?; + let (diff, _) = calc.try_calc_diff_internal( + &oplog, + &VersionVector::default(), + &Frontiers::default(), + &component_vv, + &component_frontiers, + None, + )?; + (diff, DiffMode::Import) + } else { + calc.try_calc_diff_internal( + &oplog, + &old_vv, + &old_frontiers, + oplog.vv(), + oplog.dag.get_frontiers(), + None, + )? + }; + oplog.check_history_parsable()?; + Ok((diff, diff_mode)) + })(); + let (diff, diff_mode) = match computed { + Ok(diff) => diff, + Err(err) => { + oplog.rollback_owned_import(rollback_enabled, &mut self.state.lock()); + return Err(err); + } + }; + let mut state = self.state.lock(); + let diff = match recalc_in_checkout_mode_if_needed( + &mut state, + &oplog, + &old_vv, + &old_frontiers, + diff, + ) { + Ok(diff) => diff, + Err(err) => { + oplog.rollback_owned_import(rollback_enabled, &mut state); + return Err(err); + } + }; + if let Err(e) = state.apply_diff( + InternalDocDiff { + origin, + diff: (diff).into(), + by: EventTriggerKind::Import, + new_version: Cow::Owned(oplog.frontiers().clone()), + }, + diff_mode, + ) { + if rollback_enabled { + oplog.rollback_import(&mut state); + return Err(e); + } + + panic!("state apply returned Err for import without rollback guard: {e}"); + } + materialize_touched_roots(&mut state, &calc, &oplog.arena); + } + + if result.has_deps_before_shallow_root { + if rollback_enabled { + oplog.commit_import_rollback(); + } + return Err(LoroError::ImportUpdatesThatDependsOnOutdatedVersion); + } + + if rollback_enabled { + oplog.commit_import_rollback(); + } + Ok(result.status) + } + + fn emit_events(&self) { + // we should not hold the lock when emitting events + let events = { + let mut state = self.state.lock(); + state.take_events() + }; + let mut panic = DeferredPanic::default(); + for event in events { + panic.run(|| self.observer.emit(event)); + } + panic.resume(); + } + + pub(crate) fn drop_pending_events(&self) -> Vec<DocDiff> { + let mut state = self.state.lock(); + state.take_events() + } + + /// Import the json schema updates. + /// + /// only supports backward compatibility but not forward compatibility. + #[tracing::instrument(skip_all)] + pub fn import_json_updates<T: TryInto<JsonSchema>>(&self, json: T) -> LoroResult<ImportStatus> { + let json = json.try_into().map_err(|_| LoroError::InvalidJsonSchema)?; + self.with_barrier(|| { + let result = self.import_changes_and_apply_delta_to_state_if_needed( + |oplog| crate::encoding::json_schema::decode_json_changes(json, &oplog.arena), + ImportedValues::JsonLossy, + Default::default(), + ); + self.emit_events(); + result + }) + } + + pub fn export_json_updates( + &self, + start_vv: &VersionVector, + end_vv: &VersionVector, + with_peer_compression: bool, + ) -> LoroResult<JsonSchema> { + self.try_export_json_updates(start_vv, end_vv, with_peer_compression) + } + + pub fn try_export_json_updates( + &self, + start_vv: &VersionVector, + end_vv: &VersionVector, + with_peer_compression: bool, + ) -> LoroResult<JsonSchema> { + self.with_barrier(|| { + let oplog = self.oplog.lock(); + let mut start_vv = start_vv; + let _temp: Option<VersionVector>; + if !oplog.dag.shallow_since_vv().is_empty() { + // Make sure that start_vv >= shallow_since_vv + let mut include_all = true; + for (peer, counter) in oplog.dag.shallow_since_vv().iter() { + if start_vv.get(peer).unwrap_or(&0) < counter { + include_all = false; + break; + } + } + if !include_all { + let mut vv = start_vv.clone(); + for (&peer, &counter) in oplog.dag.shallow_since_vv().iter() { + vv.extend_to_include_end_id(ID::new(peer, counter)); + } + _temp = Some(vv); + start_vv = _temp.as_ref().unwrap(); + } + } + + crate::encoding::json_schema::try_export_json( + &oplog, + start_vv, + end_vv, + with_peer_compression, + ) + }) + } + + pub fn export_json_in_id_span(&self, id_span: IdSpan) -> Vec<JsonChange> { + let oplog = self.oplog.lock(); + let mut changes = export_json_in_id_span(&oplog, id_span); + if let Some(uncommit) = oplog.get_uncommitted_change_in_span(id_span) { + let change_json = encode_change(ChangeRef::from_change(&uncommit), &self.arena, None); + changes.push(change_json); + } + changes + } + + /// Get the version vector of the current OpLog + #[inline] + pub fn oplog_vv(&self) -> VersionVector { + self.oplog.lock().vv().clone() + } + + /// Get the version vector of the current [DocState]. + /// + /// When the state frontiers are the op-log frontiers, this clones the cached + /// op-log version vector and does not parse change blocks. Otherwise it + /// walks the frontiers. + /// + /// # Panics + /// + /// Panics if the state's version cannot be resolved from the document history. + /// Use [`Self::try_state_vv`] to handle unreadable history as an error. + #[inline] + pub fn state_vv(&self) -> VersionVector { + self.try_state_vv() + .expect("Cannot resolve the state version vector") + } + + /// Get the version vector of the current state, returning a decode error + /// when required history cannot be read. + /// + /// `Ok(None)` from the frontier walk (the frontiers are not in the dag) is + /// [`LoroError::FrontiersNotFound`] for an id that can be named, not an empty + /// version vector. + pub fn try_state_vv(&self) -> LoroResult<VersionVector> { + let oplog = self.oplog.lock(); + let frontiers = self.state.lock().frontiers.clone(); + if &frontiers == oplog.frontiers() { + // `OpLog::vv` is the cached DAG version vector. It does not parse blocks. + return Ok(oplog.vv().clone()); + } + frontiers_to_vv_or_not_found(&oplog, &frontiers) + } + + pub fn get_by_path(&self, path: &[Index]) -> Option<ValueOrHandler> { + let value: LoroValue = self.state.lock().get_value_by_path(path)?; + if let LoroValue::Container(c) = value { + Some(ValueOrHandler::Handler(Handler::new_attached( + c.clone(), + self.clone(), + ))) + } else { + Some(ValueOrHandler::Value(value)) + } + } + + /// Get the handler by the string path. + pub fn get_by_str_path(&self, path: &str) -> Option<ValueOrHandler> { + let path = str_to_path(path)?; + self.get_by_path(&path) + } + + pub fn get_uncommitted_ops_as_json(&self) -> Option<JsonSchema> { + let arena = &self.arena; + let txn = self.txn.lock(); + let txn = txn.as_ref()?; + let ops_ = txn.local_ops(); + let new_id = ID { + peer: *txn.peer(), + counter: ops_.first()?.counter, + }; + let change = ChangeRef { + id: &new_id, + deps: txn.frontiers(), + timestamp: &txn + .timestamp() + .as_ref() + .copied() + .unwrap_or_else(|| self.oplog.lock().get_timestamp_for_next_txn()), + commit_msg: txn.msg(), + ops: ops_, + lamport: txn.lamport(), + }; + let json = encode_change_to_json(change, arena); + Some(json) + } + + #[inline] + pub fn get_handler(&self, id: ContainerID) -> Option<Handler> { + if self.has_container(&id) { + self.ensure_root_container(&id); + Some(Handler::new_attached(id, self.clone())) + } else { + None + } + } + + #[inline] + fn ensure_root_container(&self, id: &ContainerID) { + // Mergeable roots stay lazily materialized: their existence is derived from the + // parent map's child ref, and a store entry only appears once the child gets its + // own ops (or via the shallow-export alive walk). + if id.is_root() && !id.is_mergeable() { + self.state.lock().ensure_container(id); + } + } + + /// id can be a str, ContainerID, or ContainerIdRaw. + /// if it's str it will use Root container, which will not be None + #[inline] + pub fn try_get_text<I: IntoContainerId>(&self, id: I) -> Option<TextHandler> { + let id = id.into_container_id(&self.arena, ContainerType::Text); + if !self.has_container(&id) { + return None; + } + self.ensure_root_container(&id); + Handler::new_attached(id, self.clone()).into_text().ok() + } + + /// id can be a str, ContainerID, or ContainerIdRaw. + /// if it's str it will use Root container, which will not be None + #[inline] + pub fn get_text<I: IntoContainerId>(&self, id: I) -> TextHandler { + self.try_get_text(id) + .expect("The container does not exist in the document. Use `try_get_text` or `get_container` to check for existence.") + } + + /// id can be a str, ContainerID, or ContainerIdRaw. + /// if it's str it will use Root container, which will not be None + #[inline] + pub fn try_get_list<I: IntoContainerId>(&self, id: I) -> Option<ListHandler> { + let id = id.into_container_id(&self.arena, ContainerType::List); + if !self.has_container(&id) { + return None; + } + self.ensure_root_container(&id); + Handler::new_attached(id, self.clone()).into_list().ok() + } + + /// id can be a str, ContainerID, or ContainerIdRaw. + /// if it's str it will use Root container, which will not be None + #[inline] + pub fn get_list<I: IntoContainerId>(&self, id: I) -> ListHandler { + self.try_get_list(id) + .expect("The container does not exist in the document. Use `try_get_list` or `get_container` to check for existence.") + } + + /// id can be a str, ContainerID, or ContainerIdRaw. + /// if it's str it will use Root container, which will not be None + #[inline] + pub fn try_get_movable_list<I: IntoContainerId>(&self, id: I) -> Option<MovableListHandler> { + let id = id.into_container_id(&self.arena, ContainerType::MovableList); + if !self.has_container(&id) { + return None; + } + self.ensure_root_container(&id); + Handler::new_attached(id, self.clone()) + .into_movable_list() + .ok() + } + + /// id can be a str, ContainerID, or ContainerIdRaw. + /// if it's str it will use Root container, which will not be None + #[inline] + pub fn get_movable_list<I: IntoContainerId>(&self, id: I) -> MovableListHandler { + self.try_get_movable_list(id) + .expect("The container does not exist in the document. Use `try_get_movable_list` or `get_container` to check for existence.") + } + + /// id can be a str, ContainerID, or ContainerIdRaw. + /// if it's str it will use Root container, which will not be None + #[inline] + pub fn try_get_map<I: IntoContainerId>(&self, id: I) -> Option<MapHandler> { + let id = id.into_container_id(&self.arena, ContainerType::Map); + if !self.has_container(&id) { + return None; + } + self.ensure_root_container(&id); + Handler::new_attached(id, self.clone()).into_map().ok() + } + + /// id can be a str, ContainerID, or ContainerIdRaw. + /// if it's str it will use Root container, which will not be None + #[inline] + pub fn get_map<I: IntoContainerId>(&self, id: I) -> MapHandler { + self.try_get_map(id) + .expect("The container does not exist in the document. Use `try_get_map` or `get_container` to check for existence.") + } + + /// id can be a str, ContainerID, or ContainerIdRaw. + /// if it's str it will use Root container, which will not be None + #[inline] + pub fn try_get_tree<I: IntoContainerId>(&self, id: I) -> Option<TreeHandler> { + let id = id.into_container_id(&self.arena, ContainerType::Tree); + if !self.has_container(&id) { + return None; + } + self.ensure_root_container(&id); + Handler::new_attached(id, self.clone()).into_tree().ok() + } + + /// id can be a str, ContainerID, or ContainerIdRaw. + /// if it's str it will use Root container, which will not be None + #[inline] + pub fn get_tree<I: IntoContainerId>(&self, id: I) -> TreeHandler { + self.try_get_tree(id) + .expect("The container does not exist in the document. Use `try_get_tree` or `get_container` to check for existence.") + } + + #[cfg(feature = "counter")] + pub fn try_get_counter<I: IntoContainerId>( + &self, + id: I, + ) -> Option<crate::handler::counter::CounterHandler> { + let id = id.into_container_id(&self.arena, ContainerType::Counter); + if !self.has_container(&id) { + return None; + } + self.ensure_root_container(&id); + Handler::new_attached(id, self.clone()).into_counter().ok() + } + + #[cfg(feature = "counter")] + pub fn get_counter<I: IntoContainerId>( + &self, + id: I, + ) -> crate::handler::counter::CounterHandler { + self.try_get_counter(id) + .expect("The container does not exist in the document. Use `try_get_counter` or `get_container` to check for existence.") + } + + #[must_use] + pub fn has_container(&self, id: &ContainerID) -> bool { + if id.is_root() && !id.is_mergeable() { + return true; + } + + let exist = self.state.lock().does_container_exist(id); + exist + } + + /// Undo the operations between the given id_span. It can be used even in a collaborative environment. + /// + /// This is an internal API. You should NOT use it directly. + /// + /// # Internal + /// + /// This method will use the diff calculator to calculate the diff required to time travel + /// from the end of id_span to the beginning of the id_span. Then it will convert the diff to + /// operations and apply them to the OpLog with a dep on the last id of the given id_span. + /// + /// This implementation is kinda slow, but it's simple and maintainable. We can optimize it + /// further when it's needed. The time complexity is O(n + m), n is the ops in the id_span, m is the + /// distance from id_span to the current latest version. + /// + /// Returns application errors after rolling back the inverse. Recreating + /// an unknown container is rejected before application with an `ArgErr`. + #[instrument(level = "info", skip_all)] + pub fn undo_internal( + &self, + id_span: IdSpan, + container_remap: &mut FxHashMap<ContainerID, ContainerID>, + post_transform_base: Option<&DiffBatch>, + before_diff: &mut dyn FnMut(&DiffBatch), + ) -> LoroResult<CommitWhenDrop<'_>> { + self.undo_internal_with( + id_span, + container_remap, + post_transform_base, + before_diff, + &mut None, + &mut Default::default(), + ) + } + + /// [`Self::undo_internal`]. When the step is rejected because it would + /// recreate a container of an unknown type, `rejected_step` is set to the + /// step's own changes, which stay in the doc: the undo manager treats them + /// like remote changes for the steps before it. + pub(crate) fn undo_internal_with( + &self, + id_span: IdSpan, + container_remap: &mut FxHashMap<ContainerID, ContainerID>, + post_transform_base: Option<&DiffBatch>, + before_diff: &mut dyn FnMut(&DiffBatch), + rejected_step: &mut Option<DiffBatch>, + element_remap: &mut crate::undo::movable_list::ElementRemap, + ) -> LoroResult<CommitWhenDrop<'_>> { + let _exclusive = self.txn.lock_exclusive(); + if !self.can_edit() { + return Err(LoroError::EditWhenDetached); + } + + let (options, mut txn) = self.implicit_commit_then_stop(); + if !self.oplog().lock().vv().includes_id(id_span.id_last()) { + self.renew_txn_if_auto_commit(options); + return Err(LoroError::UndoInvalidIdSpan(id_span.id_last())); + } + + let (was_recording, latest_frontiers) = { + let mut state = self.state.lock(); + let was_recording = state.is_recording(); + state.stop_and_clear_recording(); + (was_recording, state.frontiers.clone()) + }; + + let spans = self.oplog.lock().split_span_based_on_deps(id_span); + let (span_scopes, all_scopes) = match crate::undo::movable_list::scopes(self, &spans) { + Ok(scopes) => scopes, + Err(error) => { + if was_recording { + self.state.lock().start_recording(); + } + drop(txn); + self.renew_txn_if_auto_commit(options); + return Err(error); + } + }; + let inverse_lists = std::cell::RefCell::new(Vec::new()); + let revived_lists = std::cell::RefCell::new(Default::default()); + let calc_diff = |from: &Frontiers, to: &Frontiers| { + self._checkout_without_emitting(from, false, false).unwrap(); + let inverse_index = spans + .iter() + .position(|(span, deps)| Frontiers::from_id(span.id_last()) == *from && deps == to); + let after_lists: Vec<_> = inverse_index.map_or_else(Vec::new, |i| { + span_scopes[i] + .iter() + .map(|(cid, scope)| { + ( + cid.clone(), + crate::undo::movable_list::Snapshot::capture_span( + self, + cid, + scope, + &all_scopes[cid], + false, + ), + ) + }) + .collect() + }); + { + let mut state = self.state.lock(); + state.start_recording(); + state.set_record_changes_only(true); + } + self._checkout_without_emitting(to, false, false).unwrap(); + for (cid, after) in after_lists { + let i = inverse_index.unwrap(); + let before = crate::undo::movable_list::Snapshot::capture_span( + self, + &cid, + &span_scopes[i][&cid], + &all_scopes[&cid], + true, + ); + inverse_lists + .borrow_mut() + .push(crate::undo::movable_list::Inverse { + span_index: inverse_index.unwrap(), + cid, + before, + after, + before_frontiers: to.clone(), + }); + } + let mut state = self.state.lock(); + state.set_record_changes_only(false); + let e = state.take_events(); + state.stop_and_clear_recording(); + // Applied to this doc, which kept the state of re-activated mergeable children. + let diff = DiffBatch::from_changes(e); + drop(state); + if let Some(i) = inverse_index { + crate::undo::movable_list::capture_revivals( + self, + &diff, + i, + &mut revived_lists.borrow_mut(), + ); + } + diff + }; + // `before_diff` rebases the undo manager's other steps over this one, + // so it only runs once the step is accepted + let mut last_event_a = None; + let mut diff = crate::undo::undo( + spans.clone(), + match post_transform_base { + Some(d) => Either::Right(d), + None => Either::Left(&latest_frontiers), + }, + calc_diff, + &mut |d| last_event_a = Some(d.clone()), + ); + + self._checkout_without_emitting(&latest_frontiers, false, false)?; + self.set_detached(false); + let mut inverse_lists = inverse_lists.take(); + crate::undo::movable_list::complete_anchors( + self, + &mut inverse_lists, + &latest_frontiers, + &all_scopes, + element_remap, + container_remap, + )?; + let mut movable_plans = crate::undo::movable_list::prepare( + self, + &mut diff, + inverse_lists, + revived_lists.take(), + container_remap, + element_remap, + ); + // A step that would recreate an unknown container is rejected as a + // whole, before anything is applied + let rejected = self + .check_apply_diff_creates_no_unknown_container( + &diff, + None, + container_remap, + true, + &movable_plans, + ) + .err(); + if rejected.is_some() { + let mut changes = DiffBatch::default(); + for (span, deps) in spans.iter() { + changes.compose(&calc_diff(deps, &span.id_last().into())); + } + self._checkout_without_emitting(&latest_frontiers, false, false)?; + self.set_detached(false); + *rejected_step = Some(changes); + } + + if was_recording { + self.state.lock().start_recording(); + } + // Native identity edits must use the same transaction lock that + // protected capture/preparation. Releasing it here lets a waiting + // writer delete elements or anchors before the plan uses them. + let remap_before = container_remap.clone(); + let elements_before = element_remap.clone(); + let mut undo_scope = None; + let native_result: LoroResult<()> = (|| { + if rejected.is_some() { + return Ok(()); + } + *txn = Some(self.txn()?); + let transaction = txn + .as_mut() + .ok_or_else(|| LoroError::TransactionError("undo transaction is missing".into()))?; + // Keep the capture/preparation guard held while marking the scope + // and applying native plans. Ordinary handlers later reuse this + // same transaction and scope after the guard is released. + undo_scope = Some( + self.begin_apply_diff_scope_with_txn(transaction) + .expect("undo must own its rollback scope"), + ); + let ids: Vec<_> = diff + .order + .iter() + .filter(|id| movable_plans.get(*id).is_some_and(|p| p.is_native())) + .cloned() + .collect(); + for cid in ids { + let Some(plan) = movable_plans.remove(&cid) else { + continue; + }; + let (id, _) = resolve_container_remap(cid.clone(), container_remap); + let list = self + .get_handler(id) + .and_then(|h| h.into_movable_list().ok()) + .ok_or_else(|| { + LoroError::NotFoundError("MovableList undo container disappeared".into()) + })?; + plan.apply_with_txn(&list, transaction, container_remap, element_remap)?; + #[cfg(test)] + if RUN_APPLY_DIFF_HOOK_AFTER_NATIVE_PLAN.with(|flag| flag.replace(false)) { + after_apply_diff_handler()?; + } + diff.cid_to_events.remove(&cid); + } + diff.order.retain(|id| diff.cid_to_events.contains_key(id)); + Ok(()) + })(); + drop(txn); + self.start_auto_commit(); + let applied = native_result.and_then(|()| { + if rejected.is_none() { + self.apply_diff_with_movable_undo( + diff, + container_remap, + true, + false, + &mut movable_plans, + element_remap, + ) + } else { + Ok(()) + } + }); + if let Some(scope) = undo_scope { + self.finish_undo_rollback(scope, applied.is_ok()); + } + + if let Some(options) = options { + self.set_next_commit_options(options); + } + if let Some(e) = rejected { + return Err(e); + } + if let Err(e) = applied { + *container_remap = remap_before; + *element_remap = elements_before; + return Err(e); + } + if let Some(event_a) = &last_event_a { + before_diff(event_a); + } + Ok(CommitWhenDrop { + doc: self, + default_options: CommitOptions::new().origin("undo"), + }) + } + + /// Generate a series of local operations that can revert the current doc to the target + /// version. + /// + /// Internally, it will calculate the diff between the current state and the target state, + /// and apply the diff to the current state. + pub fn revert_to(&self, target: &Frontiers) -> LoroResult<()> { + // TODO: test when the doc is readonly + // TODO: test when the doc is detached but enabled editing + let f = self.state_frontiers(); + let diff = self.diff_events(&f, target, true)?; + // This doc kept the state of the mergeable children the target re-activates, so apply + // their actual changes rather than the full states `diff` reports. + self.apply_diff_all_or_nothing( + DiffBatch::from_changes(diff), + &mut Default::default(), + false, + false, + ) + } + + /// Calculate the diff between two versions so that apply diff on a will make the state same as b. + /// + /// NOTE: This method will make the doc enter the **detached mode**. + // FIXME: This method needs testing (no event should be emitted during processing this) + pub fn diff(&self, a: &Frontiers, b: &Frontiers) -> LoroResult<DiffBatch> { + self.diff_events(a, b, false).map(|e| DiffBatch { + full_state: true, + ..DiffBatch::new(e) + }) + } + + /// With `changes_only`, only [`DiffBatch::from_changes`] of the result is meaningful. + // Both callers return a `Result`, so a history that cannot be parsed is rejected here. + fn diff_events( + &self, + a: &Frontiers, + b: &Frontiers, + changes_only: bool, + ) -> LoroResult<Vec<DocDiff>> { + { + // Check whether a and b are valid before checkout so this returns a normal error + // instead of panicking on shallow docs. + let oplog = self.oplog.lock(); + oplog.check_history_parsable()?; + let validate_frontiers = |frontiers: &Frontiers| -> LoroResult<()> { + for id in frontiers.iter() { + if !oplog.dag.contains(id) { + return Err(LoroError::FrontiersNotFound(id)); + } + } + + if oplog.dag.is_before_shallow_root(frontiers) { + return Err(LoroError::SwitchToVersionBeforeShallowRoot); + } + + Ok(()) + }; + + validate_frontiers(a)?; + validate_frontiers(b)?; + } + + let (options, txn) = self.implicit_commit_then_stop(); + let was_detached = self.is_detached(); + let old_frontiers = self.state_frontiers(); + let was_recording = { + let mut state = self.state.lock(); + let is_recording = state.is_recording(); + state.stop_and_clear_recording(); + is_recording + }; + let result = (|| { + self._checkout_without_emitting(a, true, false)?; + { + let mut state = self.state.lock(); + state.start_recording(); + state.set_record_changes_only(changes_only); + } + let checkout = self._checkout_without_emitting(b, true, false); + let mut state = self.state.lock(); + state.set_record_changes_only(false); + checkout?; + let e = state.take_events(); + state.stop_and_clear_recording(); + Ok::<_, LoroError>(e) + })(); + + // Always restore state regardless of whether diff calculation succeeded + self._checkout_without_emitting(&old_frontiers, false, false) + .unwrap(); + drop(txn); + if !was_detached { + self.set_detached(false); + self.renew_txn_if_auto_commit(options); + } + if was_recording { + self.state.lock().start_recording(); + } + result + } + + /// Apply a diff to the current state. + #[inline(always)] + /// + /// A mergeable child that the batch re-activates is aligned with this doc's hidden state + /// only if `diff.full_state` is set (batches from [`LoroDoc::diff`]); otherwise its entry + /// is applied as an increment. See [`DiffBatch::full_state`]. + /// + /// All or nothing: when it returns `Err`, the doc, its history and its subscribers are as + /// before the call, and uncommitted edits made before it are kept. See + /// `context/apply-diff-atomicity.md`. + pub fn apply_diff(&self, diff: DiffBatch) -> LoroResult<()> { + let align = diff.full_state; + self.apply_diff_all_or_nothing(diff, &mut Default::default(), true, align) + } + + /// [`Self::_apply_diff`], rolled back when it fails (loro-dev/loro#1154). + /// Undo uses the same scope with its identity plans; see `context/undo-atomicity.md`. + pub(crate) fn apply_diff_all_or_nothing( + &self, + diff: DiffBatch, + container_remap: &mut FxHashMap<ContainerID, ContainerID>, + skip_unreachable: bool, + align_revived_mergeable: bool, + ) -> LoroResult<()> { + if !self.can_edit() { + return Err(LoroError::EditWhenDetached); + } + + // Rollback checks the state out through the current frontiers. If that + // history cannot be read, refuse before the batch mutates anything. + { + let oplog = self.oplog.lock(); + let frontiers = self.state.lock().frontiers.clone(); + frontiers_to_vv_or_not_found(&oplog, &frontiers)?; + } + + let scope = self.begin_apply_diff_scope(); + let result = self._apply_diff( + diff, + container_remap, + skip_unreachable, + align_revived_mergeable, + ); + if let Some(scope) = scope { + if result.is_ok() { + self.end_apply_diff_scope(scope); + } else if let Err(err) = self.rollback_apply_diff_scope(scope) { + return Err(err); + } + } + result + } + + /// Undo owns the writer gate and a fresh transaction. Losing its rollback + /// scope or failing to restore state is an invariant failure, not a normal + /// error that callers could safely retry on a partly changed document. + fn finish_undo_rollback(&self, scope: u64, succeeded: bool) { + if succeeded { + self.end_apply_diff_scope(scope); + } else { + assert!( + self.txn + .lock() + .as_ref() + .is_some_and(|txn| txn.rollback_scope_is_intact(scope)), + "undo lost its exclusive rollback scope" + ); + self.rollback_apply_diff_scope(scope) + .expect("undo rollback must restore the document"); + } + } + + /// Marks where the batch starts in the transaction it will run in. + /// + /// Returns `None`, and the batch runs without a rollback, when there is no transaction + /// to run it in (the batch then fails before it applies anything) or another thread's + /// batch runs in it. + fn begin_apply_diff_scope(&self) -> Option<u64> { + let mut guard = self.txn.lock(); + if guard.is_none() && !cfg!(target_arch = "wasm32") && self.can_edit() { + // Like the handlers' `with_txn`, which the batch's first op would call + drop(guard); + self.start_auto_commit(); + guard = self.txn.lock(); + } + self.begin_apply_diff_scope_with_txn(guard.as_mut()?) + } + + /// Also used by undo while it holds the preparation transaction guard. + fn begin_apply_diff_scope_with_txn(&self, txn: &mut Transaction) -> Option<u64> { + static NEXT_SCOPE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if txn.has_rollback_scope() { + return None; + } + let id = NEXT_SCOPE_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + txn.begin_rollback_scope(id); + self.state.lock().begin_local_rollback(id); + Some(id) + } + + fn end_apply_diff_scope(&self, scope: u64) { + let mut guard = self.txn.lock(); + if let Some(txn) = guard.as_mut() { + txn.end_rollback_scope(scope); + } + self.state.lock().end_local_rollback(scope); + } + + /// Undo the ops of a failed batch, keeping the ops the transaction held before it. + /// Emits nothing. + /// + /// The transaction's ops are inserted into the op log as a change, under an import + /// rollback scope, so that the diff calculator can compute the checkout from the batch's + /// last op back to the version before the batch; then the scope is rolled back and the + /// ops before the batch are put back into the DAG's version as pending local ops. + fn rollback_apply_diff_scope(&self, scope: u64) -> LoroResult<()> { + let mut guard = self.txn.lock(); + let Some(txn) = guard + .as_mut() + .filter(|txn| txn.rollback_scope_is_intact(scope)) + else { + // Another thread committed the transaction or applied ops in it while the batch + // ran. Undoing it would drop their edits, so the batch stays partly applied. + warn!("apply_diff failed while another thread edited the doc; not rolled back"); + if let Some(txn) = guard.as_mut() { + txn.end_rollback_scope(scope); + } + self.state.lock().end_local_rollback(scope); + return Ok(()); + }; + + let batch = txn.roll_back_scope(scope); + let mut oplog = self.oplog.lock(); + let mut state = self.state.lock(); + if batch.batch_start < batch.batch_end { + let peer = batch.peer; + let txn_ops_before = (batch.batch_start - batch.txn_start_counter) as usize; + let before_batch = if txn_ops_before == 0 { + batch.deps.clone() + } else { + Frontiers::from_id(ID::new(peer, batch.batch_start - 1)) + }; + #[cfg(debug_assertions)] + { + // Only the txn's ops changed the DAG's version since it began: anything else + // (an import, a checkout) commits the txn first. + let mut expected = batch.dag_frontiers_at_start.clone(); + expected.update_frontiers_on_new_change( + ID::new(peer, batch.batch_end - 1), + &batch.deps, + ); + assert_eq!(&expected, oplog.dag.frontiers()); + assert_eq!(oplog.dag.vv().get(&peer), Some(&batch.batch_end)); + } + oplog.dag.discard_pending_txn( + batch.dag_frontiers_at_start, + peer, + batch.txn_start_counter, + ); + oplog.begin_import_rollback(); + oplog.insert_new_change( + Change { + id: ID::new(peer, batch.txn_start_counter), + lamport: batch.txn_start_lamport, + deps: batch.deps.clone(), + timestamp: batch.timestamp, + commit_msg: None, + ops: batch.ops, + }, + false, + ); + + let batch_last = state.frontiers.clone(); + debug_assert_eq!( + batch_last, + Frontiers::from_id(ID::new(peer, batch.batch_end - 1)) + ); + let undone = (|| -> LoroResult<()> { + let from = frontiers_to_vv_or_not_found(&oplog, &batch_last)?; + let to = frontiers_to_vv_or_not_found(&oplog, &before_batch)?; + let (diff, diff_mode) = DiffCalculator::new(false).try_calc_diff_internal( + &oplog, + &from, + &batch_last, + &to, + &before_batch, + None, + )?; + // `DocState::apply_diff` refuses to run inside a transaction, and records nothing + // without its event recorder. + state.abort_txn(); + let recorder = state.take_event_recorder(); + let applied = state.apply_diff( + InternalDocDiff { + origin: Default::default(), + by: EventTriggerKind::Checkout, + diff: Cow::Owned(diff), + new_version: Cow::Owned(before_batch.clone()), + }, + diff_mode, + ); + state.restore_event_recorder(recorder); + state.resume_txn(); + applied + })(); + // The temporary change must not stay in the op log if the checkout cannot be read. + oplog.rollback_import_keeping_arena(&state); + if txn_ops_before > 0 { + oplog.dag.update_version_on_new_local_op( + &batch.deps, + ID::new(peer, batch.txn_start_counter), + batch.txn_start_lamport, + txn_ops_before, + ); + oplog.refresh_visible_op_count(); + } + undone?; + } + state.finish_local_rollback(scope, batch.peer, batch.batch_start); + Ok(()) + } + + /// Apply a diff to the current state. + /// + /// Regular containers are recreated with new [ContainerID]s. Reusing their + /// original IDs could break several internal invariants: + /// + /// 1. Each container should appear only once in the document. Allowing containers with the same ID + /// would result in multiple instances of the same container in the document. + /// 2. Unreachable containers should be removable from the state when necessary. + /// + /// However, the diff may contain operations that depend on container IDs. + /// Therefore, users need to provide a `container_remap` to record and retrieve the container ID remapping. + /// This remapping applies to the diff/undo workflow, not to imported operations. + /// Mergeable children instead restore a deterministic parent/key/type marker; + /// their identity is preserved only when the parent identity is preserved. + /// + /// With `align_revived_mergeable` (a [`DiffBatch::full_state`] batch), a mergeable child the + /// batch re-activates carries its full state (no entry means empty), which is aligned with + /// whatever hidden state this doc has at its deterministic cid. Otherwise entries are + /// increments; revert and undo pass batches of actual changes ([`DiffBatch::from_changes`]). + /// See context/mergeable-containers.md. + pub(crate) fn _apply_diff( + &self, + diff: DiffBatch, + container_remap: &mut FxHashMap<ContainerID, ContainerID>, + skip_unreachable: bool, + align_revived_mergeable: bool, + ) -> LoroResult<()> { + self.apply_diff_with_movable_undo( + diff, + container_remap, + skip_unreachable, + align_revived_mergeable, + &mut Default::default(), + &mut Default::default(), + ) + } + + fn apply_diff_with_movable_undo( + &self, + diff: DiffBatch, + container_remap: &mut FxHashMap<ContainerID, ContainerID>, + skip_unreachable: bool, + align_revived_mergeable: bool, + movable_plans: &mut FxHashMap<ContainerID, crate::undo::movable_list::Plan>, + element_remap: &mut crate::undo::movable_list::ElementRemap, + ) -> LoroResult<()> { + if !self.can_edit() { + return Err(LoroError::EditWhenDetached); + } + + // When the batch holds unknown containers, its full states are aligned + // before anything is applied, so the check sees what is applied; the + // loop below then applies the planned edits. Otherwise the loop aligns + // each full state itself. + let mut plan = + if align_revived_mergeable && diff.iter().any(|(_, d)| diff_has_unknown_value(d)) { + self.plan_full_state_batch(&diff, container_remap) + } else { + FullStatePlan::default() + }; + // Reject unsupported container recreation before touching the doc. + let predicted_skips = self.check_apply_diff_creates_no_unknown_container( + &diff, + align_revived_mergeable.then_some(&plan), + container_remap, + skip_unreachable, + movable_plans, + )?; + + let mut ans: LoroResult<()> = Ok(()); + let mut missing_containers: Vec<ContainerID> = Vec::new(); + // Containers whose diff in this batch is a full state while they keep an id that may + // already hold state: re-activated mergeable children and, transitively, the children + // of aligned containers that were kept. + let mut full_state_targets: FxHashSet<ContainerID> = FxHashSet::default(); + let mut applied: FxHashSet<ContainerID> = FxHashSet::default(); + for (mut id, diff) in diff.into_iter() { + let batch_id = id.clone(); + let mut remapped = false; + while let Some(rid) = container_remap.get(&id) { + remapped = true; + id = rid.clone(); + } + + let is_full_state = align_revived_mergeable && full_state_targets.remove(&id); + if align_revived_mergeable { + applied.insert(id.clone()); + } + + if matches!(&id, ContainerID::Normal { .. }) && self.arena.id_to_idx(&id).is_none() { + // Not in arena does not imply non-existent; consult state/kv and register lazily + let exists = self.state.lock().does_container_exist(&id); + if !exists { + missing_containers.push(id); + continue; + } + // Ensure registration so handlers can be created + self.state.lock().ensure_container(&id); + } + + if skip_unreachable && !is_full_state { + let mut state = self.state.lock(); + // A remapped target is normally recreated by this batch and is + // applied even before it is attached. An earlier undo may have + // recreated it, though, and it may have been deleted since: + // writing to it would fail with `ContainerDeleted`, so skip it + // like any other unreachable container. + let skip = if remapped { + self.arena + .id_to_idx(&id) + .is_some_and(|idx| state.is_deleted(idx)) + } else { + !state.get_reachable(&id) + }; + if skip { + continue; + } + } + debug_assert!( + !predicted_skips.contains(&batch_id), + "{batch_id} holds an unknown container and was predicted to be skipped" + ); + + let Some(h) = self.get_handler(id.clone()) else { + return Err(LoroError::ContainersNotFound { + containers: Box::new(vec![id]), + }); + }; + let planned = plan.aligned.remove(&batch_id); + let diff = if is_full_state { + match planned { + // The plan aligned this entry against the same container + Some(p) if p.target == id => { + full_state_targets.extend(p.kept); + match p.edit { + Some(edit) => edit, + None => continue, + } + } + _ => { + // Not planned (the batch holds no unknown container), + // or a mergeable child of a container this batch + // recreated: new and empty, which the plan checked as such + debug_assert!( + plan.fresh.contains(&batch_id) || !diff_has_unknown_value(&diff), + "{batch_id} holds an unknown container and was not planned" + ); + let current = self.state.lock().container_full_diff(h.container_idx()); + match crate::handler::align_full_state( + &h, + &diff, + current, + &mut full_state_targets, + ) { + Some(diff) => diff, + None => continue, + } + } + } + } else { + debug_assert!( + planned.is_none() || !diff_has_unknown_value(&diff), + "{batch_id} holds an unknown container and was planned as a full state" + ); + diff + }; + let result = if let Some(movable) = movable_plans.remove(&batch_id) { + let Handler::MovableList(list) = &h else { + unreachable!() + }; + movable.apply(list, diff, container_remap, element_remap) + } else { + h.apply_diff(diff, container_remap, &mut full_state_targets) + }; + // Fault injection after real operations exercises rollback. + #[cfg(test)] + let result = result.and_then(|()| after_apply_diff_handler()); + if let Err(e) = result { + debug_assert!( + !crate::handler::is_unknown_container_creation_err(&e), + "the unknown container check missed {e:?} in {batch_id}" + ); + ans = Err(e); + } + } + + if align_revived_mergeable { + // A full-state container without an entry in the batch is empty. + for id in full_state_targets { + if applied.contains(&id) { + continue; + } + let Some(h) = self.get_handler(id) else { + continue; + }; + let is_empty = self + .state + .lock() + .is_container_state_empty(h.container_idx()); + if !is_empty { + if let Err(e) = h.clear() { + ans = Err(e); + } + } + } + } + + if !missing_containers.is_empty() { + return Err(LoroError::ContainersNotFound { + containers: Box::new(missing_containers), + }); + } + + ans + } + + /// How `_apply_diff` treats a full-state batch holding unknown containers, + /// planned before anything is applied: which entries it aligns with the + /// state this doc kept, and the edits they turn into. The loop applies + /// these edits, so alignment is computed once, and the unknown container + /// check sees what is applied. + /// + /// The loop still keeps its own `full_state_targets`, because it follows + /// `container_remap` as it grows. It uses a planned edit only when it + /// aligns the same container as the plan did. + fn plan_full_state_batch( + &self, + diff: &DiffBatch, + container_remap: &FxHashMap<ContainerID, ContainerID>, + ) -> FullStatePlan { + let mut plan = FullStatePlan::default(); + // The loop's `full_state_targets` + let mut targets: FxHashSet<ContainerID> = FxHashSet::default(); + // Containers the loop may recreate under a new id: container values of + // Map/List diffs and the metas of created or moved tree nodes. Errs + // towards "recreated", which only makes the check stricter. + let mut recreated: FxHashSet<ContainerID> = FxHashSet::default(); + // Mergeable children of recreated containers: the loop aligns them + // against a new, empty container + let mut fresh_targets: FxHashSet<ContainerID> = FxHashSet::default(); + for (id, diff) in diff.iter() { + let (target, _) = resolve_container_remap(id.clone(), container_remap); + match diff { + crate::event::Diff::Map(map) => recreated.extend( + map.updated + .values() + .filter_map(|v| v.value.as_ref().and_then(diff_value_container_id)) + .filter(|c| !c.is_mergeable()), + ), + crate::event::Diff::List(delta) => { + recreated.extend(inserted_container_ids(delta)); + } + crate::event::Diff::Tree(tree) => recreated.extend( + tree.diff + .iter() + .filter(|item| { + !matches!(item.action, crate::delta::TreeExternalDiff::Delete { .. }) + }) + .map(|item| item.target.associated_meta_container()), + ), + _ => {} + } + + let effective = if fresh_targets.remove(&target) { + targets.remove(&target); + plan.always_applied.insert(target.clone()); + plan.fresh.insert(id.clone()); + recreated.insert(target.clone()); + Some(diff) + } else if targets.remove(&target) { + plan.always_applied.insert(target.clone()); + let Some(h) = self.get_handler(target.clone()) else { + // `_apply_diff` stops here with `ContainersNotFound` + continue; + }; + let current = self.state.lock().container_full_diff(h.container_idx()); + let mut kept = FxHashSet::default(); + let edit = crate::handler::align_full_state(&h, diff, current, &mut kept); + targets.extend(kept.iter().cloned()); + let entry = plan.aligned.entry(id.clone()).or_insert(PlannedAlignment { + target: target.clone(), + edit, + kept, + }); + entry.edit.as_ref() + } else if recreated.contains(&target) + || container_remap.contains_key(id) + || !self.has_container(&target) + || self.state.lock().get_reachable(&target) + { + Some(diff) + } else { + // The loop skips an entry whose target is unreachable before the + // batch, unless an earlier entry revived it, which would have + // made it a target above. So its marker writes don't count (the + // batch order is up to the caller). + None + }; + + // A mergeable marker written by a Map diff makes its child a target + if let Some(crate::event::Diff::Map(map)) = effective { + for (key, v) in map.updated.iter() { + if let Some(c) = v.value.as_ref().and_then(diff_value_container_id) { + if c.is_mergeable() { + let child = + ContainerID::new_mergeable(&target, key, c.container_type()); + if recreated.contains(&target) { + fresh_targets.insert(child); + } else { + targets.insert(child); + } + } + } + } + } + } + plan + } + + /// `_apply_diff` recreates the containers inserted by a diff, but this + /// version cannot create a container whose type it doesn't know + /// ([ContainerType::Unknown], e.g. `cid:0@1:Unknown(9)`). Such values may + /// only appear where nothing is created: mergeable map children (only the + /// marker is written), MovableList moves of an element already in the + /// list, diffs targeting an unknown container (a no-op), and diffs that + /// `_apply_diff` skips because their target is unreachable. + /// + /// With a full-state `plan`, the planned edits are checked instead of the + /// full states. Nothing is applied here, but the apply loop changes its own + /// inputs as it goes, so this predicts those changes from the whole batch: + /// + /// - fresh: container values of Map/List diffs, the metas of recreated + /// tree nodes, and mergeable children of those are recreated under a new + /// id (`container_remap`). Their diffs then apply to a new, empty + /// container and are never skipped. + /// - revived: writing a mergeable child's marker makes it and its + /// descendants reachable again. + /// - removed: a diff that deletes a child container makes it and its + /// descendants unreachable for the diffs after it. + /// + /// Every prediction errs towards checking a diff (a false rejection), + /// never towards skipping it, so an accepted batch cannot fail on an + /// unknown container half way through. Returns the batch ids of the + /// entries holding unknown containers that it predicted to be skipped; + /// `_apply_diff` asserts that in debug builds. + fn check_apply_diff_creates_no_unknown_container( + &self, + diff: &DiffBatch, + plan: Option<&FullStatePlan>, + container_remap: &FxHashMap<ContainerID, ContainerID>, + skip_unreachable: bool, + movable_plans: &FxHashMap<ContainerID, crate::undo::movable_list::Plan>, + ) -> LoroResult<FxHashSet<ContainerID>> { + let mut predicted_skips = FxHashSet::default(); + if !diff.iter().any(|(_, d)| diff_has_unknown_value(d)) { + return Ok(predicted_skips); + } + + // The batch as the loop applies it + let entries: Vec<(&ContainerID, &crate::event::Diff)> = diff + .iter() + .filter_map(|(id, d)| match plan.and_then(|p| p.aligned.get(id)) { + Some(p) => p.edit.as_ref().map(|edit| (id, edit)), + None => Some((id, d)), + }) + .collect(); + let empty = FxHashSet::default(); + let always_applied = plan.map_or(&empty, |p| &p.always_applied); + + // A handler for an existing container, without materializing roots + // that have no state yet + let existing = |id: &ContainerID| -> Option<Handler> { + if id.is_root() && !id.is_mergeable() && self.arena.id_to_idx(id).is_none() { + return None; + } + self.has_container(id) + .then(|| Handler::new_attached(id.clone(), self.clone())) + }; + + let mut fresh: FxHashSet<ContainerID> = plan.map(|p| p.fresh.clone()).unwrap_or_default(); + let mut revived: FxHashSet<ContainerID> = FxHashSet::default(); + // Container -> index of the first diff in the batch that removes it + let mut removed: FxHashMap<ContainerID, usize> = FxHashMap::default(); + for (i, &(id, diff)) in entries.iter().enumerate() { + let (target, _) = resolve_container_remap(id.clone(), container_remap); + let handler = if fresh.contains(id) || target.is_unknown() { + None + } else { + existing(&target) + }; + match diff { + crate::event::Diff::Map(map) => { + let map_handler = handler.and_then(|h| h.into_map().ok()); + for (key, v) in map.updated.iter() { + if let Some(LoroValue::Container(old)) = + map_handler.as_ref().and_then(|m| m.get(key)) + { + if !old.is_mergeable() { + removed.entry(old).or_insert(i); + } + } + if let Some(c) = v.value.as_ref().and_then(diff_value_container_id) { + if c.is_mergeable() { + // The loop writes the marker of `mergeable(target, + // key)` and remaps `c` to it. Unless that is `c` + // itself, the child is another container: new (under a + // recreated map) or one this check can't see into (a + // parent the undo manager already remapped, or a value + // under another key). Check it as new and empty. + let effective = + ContainerID::new_mergeable(&target, key, c.container_type()); + if fresh.contains(id) + || effective + != resolve_container_remap(c.clone(), container_remap).0 + { + fresh.insert(c.clone()); + } + revived.insert(c); + } else { + fresh.insert(c); + } + } + } + } + crate::event::Diff::List(delta) => { + if let Some(native) = movable_plans.get(id).and_then(|p| p.preflight()) { + fresh.extend(native.creates.iter().cloned()); + for child in &native.removes { + removed.entry(child.clone()).or_insert(i); + } + continue; + } + let values: FxHashSet<ContainerID> = inserted_container_ids(delta) + .map(|c| resolve_container_remap(c, container_remap).0) + .collect(); + let get = |i: usize| match &handler { + Some(Handler::List(l)) => l.get(i), + Some(Handler::MovableList(l)) => l.get(i), + _ => None, + }; + if handler.is_some() { + let movable = matches!(handler, Some(Handler::MovableList(_))); + let mut index = 0; + for item in delta.iter() { + match item { + loro_delta::DeltaItem::Retain { len, .. } => index += len, + loro_delta::DeltaItem::Replace { delete, .. } => { + for j in index..index + delete { + if let Some(LoroValue::Container(old)) = get(j) { + // A MovableList may move it instead + if !movable || !values.contains(&old) { + removed.entry(old).or_insert(i); + } + } + } + index += delete; + } + } + } + } + // Moves are counted too, which can only check more + fresh.extend(inserted_container_ids(delta)); + } + crate::event::Diff::Tree(tree) => { + for item in tree.diff.iter() { + let meta = item.target.associated_meta_container(); + if matches!(item.action, crate::delta::TreeExternalDiff::Delete { .. }) { + if handler.is_some() && !container_remap.contains_key(&meta) { + removed.entry(meta).or_insert(i); + } + } else { + fresh.insert(meta); + } + } + } + _ => {} + } + } + + for (i, &(id, diff)) in entries.iter().enumerate() { + if !diff_has_unknown_value(diff) { + continue; + } + let (target, remapped) = resolve_container_remap(id.clone(), container_remap); + if target.is_unknown() { + // `Handler::Unknown` ignores diffs + continue; + } + + let handler = if fresh.contains(id) { + None + } else { + existing(&target) + }; + if handler.is_some() + && skip_unreachable + && !remapped + && !always_applied.contains(&target) + { + let chain = self.arena_ancestors_and_self(&target); + let skipped = !chain.iter().any(|c| revived.contains(c)) + && (!self.state.lock().get_reachable(&target) + || chain.iter().any(|c| removed.get(c).is_some_and(|&j| j < i))); + if skipped { + // `_apply_diff` skips this diff + predicted_skips.insert(id.clone()); + continue; + } + } + + let created = match diff { + crate::event::Diff::Map(map) => map + .updated + .values() + .filter_map(|v| v.value.as_ref().and_then(diff_value_container_id)) + .find(|c| c.is_unknown() && !c.is_mergeable()), + crate::event::Diff::List(delta) + if movable_plans.get(id).and_then(|p| p.preflight()).is_some() => + { + let _ = delta; + movable_plans[id] + .preflight() + .and_then(|p| p.creates.iter().find(|c| c.is_unknown()).cloned()) + } + crate::event::Diff::List(delta) => match &handler { + // Only an existing MovableList can move an element instead + // of creating it + Some(Handler::MovableList(list)) => { + list.unknown_container_created_by_delta(delta, container_remap)? + } + _ => inserted_container_ids(delta).find(|c| c.is_unknown()), + }, + _ => None, + }; + if let Some(c) = created { + return Err(crate::handler::unknown_container_creation_err( + c.container_type(), + )); + } + } + + Ok(predicted_skips) + } + + /// `id` and its ancestors by arena parent, whether they are visible or + /// not (a hidden mergeable child has no path from a root, but its + /// descendants become reachable again when a batch revives it). + fn arena_ancestors_and_self(&self, id: &ContainerID) -> Vec<ContainerID> { + let mut ans = Vec::new(); + let idx = match self.arena.id_to_idx(id) { + Some(idx) => Some(idx), + None => { + let mut state = self.state.lock(); + if state.does_container_exist(id) { + state.ensure_container(id); + } + drop(state); + self.arena.id_to_idx(id) + } + }; + if let Some(mut idx) = idx { + while let Some(parent) = self.arena.get_parent(idx) { + if let Some(parent_id) = self.arena.idx_to_id(parent) { + ans.push(parent_id); + } + idx = parent; + } + } + ans.push(id.clone()); + ans + } + + /// This is for debugging purpose. It will travel the whole oplog + #[inline] + pub fn diagnose_size(&self) { + self.oplog().lock().diagnose_size(); + } + + #[inline] + pub fn oplog_frontiers(&self) -> Frontiers { + self.oplog().lock().frontiers().clone() + } + + #[inline] + pub fn state_frontiers(&self) -> Frontiers { + self.state.lock().frontiers.clone() + } + + /// - Ordering::Less means self is less than target or parallel + /// - Ordering::Equal means versions equal + /// - Ordering::Greater means self's version is greater than target + #[inline] + pub fn cmp_with_frontiers(&self, other: &Frontiers) -> Ordering { + self.oplog().lock().cmp_with_frontiers(other) + } + + /// Compare two [Frontiers] causally. + /// + /// If one of the [Frontiers] are not included, it will return [FrontiersNotIncluded]. + #[inline] + pub fn cmp_frontiers( + &self, + a: &Frontiers, + b: &Frontiers, + ) -> Result<Option<Ordering>, FrontiersNotIncluded> { + let oplog = self.oplog.lock(); + oplog + .check_history_parsable() + .map_err(FrontiersNotIncluded::unreadable)?; + oplog.cmp_frontiers(a, b) + } + + pub fn subscribe_root(&self, callback: Subscriber) -> Subscription { + let mut state = self.state.lock(); + if !state.is_recording() { + state.start_recording(); + } + + self.observer.subscribe_root(callback) + } + + pub fn subscribe(&self, container_id: &ContainerID, callback: Subscriber) -> Subscription { + let mut state = self.state.lock(); + if !state.is_recording() { + state.start_recording(); + } + + self.observer.subscribe(container_id, callback) + } + + pub fn subscribe_local_update(&self, callback: LocalUpdateCallback) -> Subscription { + let (sub, activate) = self.local_update_subs.inner().insert((), callback); + activate(); + sub + } + + // PERF: opt + #[tracing::instrument(skip_all)] + pub fn import_batch(&self, bytes: &[Vec<u8>]) -> LoroResult<ImportStatus> { + self.import_batch_with_history_mode(bytes, false) + } + + /// Like [`Self::import_batch`]. `json_lossy` is the same opt-in as + /// [`Self::import_with_history_mode`]. + pub fn import_batch_with_history_mode( + &self, + bytes: &[Vec<u8>], + json_lossy: bool, + ) -> LoroResult<ImportStatus> { + let values = if json_lossy { + ImportedValues::JsonLossy + } else { + ImportedValues::Exact + }; + if bytes.is_empty() { + return Ok(ImportStatus::default()); + } + + if bytes.len() == 1 { + return self.import_with_history_mode(&bytes[0], Default::default(), json_lossy); + } + + let mut success = VersionRange::default(); + let mut meta_arr = bytes + .iter() + .map(|b| Ok((LoroDoc::decode_import_blob_meta(b, false)?, b))) + .collect::<LoroResult<Vec<(ImportBlobMetadata, &Vec<u8>)>>>()?; + meta_arr.sort_by(|a, b| { + a.0.mode + .cmp(&b.0.mode) + .then(b.0.change_num.cmp(&a.0.change_num)) + }); + + let (options, txn) = self.implicit_commit_then_stop(); + // Why we should keep locking `txn` here + // + // In a multi-threaded environment, `import_batch` used to drop the txn lock + // (via `commit_then_stop` + `drop(txn)`) and call `detach()`/`checkout_to_latest()` + // around the batch import. That created a race where another thread could + // start or renew the auto-commit txn and perform local edits while we were + // importing and temporarily detached. Those interleaved local edits could + // violate invariants between `OpLog` and `DocState` (e.g., state being + // updated when we expect it not to, missed events, or inconsistent + // frontiers), as exposed by the loom test `local_edits_during_batch_import`. + // + // The fix is to hold the txn mutex for the entire critical section: + // - Stop the current txn and keep the mutex guard. + // - Force-detach with `set_detached(true)` (avoids `detach()` side effects), + // then run each `_import_with(...)` while detached so imports only touch + // the `OpLog`. + // - After importing, reattach by checking out to latest and renew the txn in + // `BatchImportGuard::finish`, which keeps the mutex held while (re)starting + // the auto-commit txn. + // + // Holding the lock ensures no concurrent thread can create/renew a txn and + // do local edits in the middle of the batch import, making the whole + // operation atomic with respect to local edits. + // + // The force-detach must be undone on *every* exit path. A blob that returns + // `Err`, and just as importantly a panic out of decode/apply, used to skip the + // reattach below and strand the document in detached mode, where it silently + // stops reflecting later imports and local edits. `BatchImportGuard::finish` + // owns that cleanup and the blob loop runs inside `catch_unwind` so it also + // runs before a panic is re-raised. + let was_attached = !self.is_detached(); + // A full snapshot can initialize state lazily, just as in `import`. + // Pending-only history must not be replaced by the snapshot, either. + // Keep the pre-snapshot arena checkpoint so a failed closing checkout + // can discard the snapshot's state as well as the following updates. + let snapshot_checkpoint = if was_attached + && meta_arr[0].0.mode == encoding::EncodedBlobMode::Snapshot + { + let oplog = self.oplog.lock(); + let mut state = self.state.lock(); + (oplog.is_empty() && oplog.pending_changes.is_empty() && state.can_import_snapshot()) + .then(|| BatchSnapshotRollback { + arena: oplog.arena.checkpoint_for_rollback(), + empty_containers: state.store.iter_all_container_ids().collect(), + }) + } else { + None + }; + self.set_detached(true); + { + let mut oplog = self.oplog.lock(); + oplog.batch_importing = true; + // The history-only path touches just the `OpLog`, so a rollback + // scope spanning the whole batch lets `BatchImportGuard::finish` restore + // the pre-batch version if the closing reattach cannot apply the imported + // changes to `DocState`. Without it the doc would be left detached at a + // version it can never check out. + if was_attached && snapshot_checkpoint.is_none() { + oplog.begin_import_rollback(); + } + } + + let mut guard = BatchImportGuard { + doc: self, + was_attached, + txn: Some(txn), + options, + snapshot_checkpoint, + #[cfg(debug_assertions)] + finished: false, + }; + + // Catch here rather than in a `Drop`: releasing a mutex guard while a panic is + // in flight poisons that mutex, so the reattach has to happen after unwinding + // has stopped. Under `panic = "abort"` (e.g. wasm) a genuine panic still + // terminates execution; only returned errors can be recovered there. + let loop_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let mut err = None; + for (index, (_meta, data)) in meta_arr.into_iter().enumerate() { + #[cfg(test)] + take_panic_at_batch_import_blob_for_test(); + let result = if let Some(checkpoint) = + guard.snapshot_checkpoint.as_ref().filter(|_| index == 0) + { + // Do not emit the snapshot event until the closing checkout + // succeeds. Its state is part of the batch's rollback scope. + let result = parse_header_and_body(data, true).and_then(|parsed| { + decode_snapshot(guard.doc, parsed.mode, parsed.body, Default::default()) + }); + if result.is_err() { + // The standalone decoder resets a failed snapshot to an + // empty store. Restore pre-existing empty handles, too. + let mut state = guard.doc.state.lock(); + for id in &checkpoint.empty_containers { + state.ensure_container(id); + } + } + let mut oplog = guard.doc.oplog.lock(); + // Snapshot decoding installs a new DAG; start the ordinary + // suffix journal only after that installation (or its reset). + oplog.batch_importing = true; + oplog.begin_import_rollback(); + result + } else { + guard + .doc + .import_without_emitting(data, Default::default(), values) + }; + match result { + Ok(s) => { + for (peer, (start, end)) in s.success.iter() { + match success.0.entry(*peer) { + Entry::Occupied(mut e) => { + e.get_mut().1 = *end.max(&e.get().1); + } + Entry::Vacant(e) => { + e.insert((*start, *end)); + } + } + } + } + Err(e) => { + err = Some(e); + } + } + } + err + })); + + let err = match loop_result { + Ok(err) => err, + Err(payload) => { + // Reattach first, then re-raise the original panic. `finish` can panic + // itself when the interrupted blob poisoned a doc lock; that document + // is unusable either way, so keep the original payload. + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = guard.finish(); + })); + std::panic::resume_unwind(payload); + } + }; + + let pending = guard.finish()?; + if let Some(err) = err { + return Err(err); + } + + Ok(ImportStatus { + success, + pending: if pending.is_empty() { + None + } else { + Some(pending) + }, + }) + } + + /// Get shallow value of the document. + #[inline] + pub fn get_value(&self) -> LoroValue { + self.state.lock().get_value() + } + + /// Get deep value of the document. + #[inline] + pub fn get_deep_value(&self) -> LoroValue { + self.state.lock().get_deep_value() + } + + /// Get deep value of the document with container id + #[inline] + pub fn get_deep_value_with_id(&self) -> LoroValue { + self.state.lock().get_deep_value_with_id() + } + + pub fn checkout_to_latest(&self) { + let (options, _guard) = self.implicit_commit_then_stop(); + if !self.is_detached() { + drop(_guard); + self.renew_txn_if_auto_commit(options); + return; + } + + self._checkout_to_latest_without_commit(true) + .expect("checkout to oplog frontiers should succeed"); + self.emit_events(); + drop(_guard); + self.renew_txn_if_auto_commit(options); + } + + /// NOTE: The caller of this method should ensure the txn is locked and set to None + pub(crate) fn _checkout_to_latest_without_commit( + &self, + to_commit_then_renew: bool, + ) -> LoroResult<()> { + self._checkout_to_latest_without_commit_with_event( + to_commit_then_renew, + "checkout".into(), + EventTriggerKind::Checkout, + ) + } + + pub(crate) fn _checkout_to_latest_without_commit_as_import( + &self, + to_commit_then_renew: bool, + origin: InternalString, + ) -> LoroResult<()> { + self._checkout_to_latest_without_commit_with_event( + to_commit_then_renew, + origin, + EventTriggerKind::Import, + ) + } + + fn _checkout_to_latest_without_commit_with_event( + &self, + to_commit_then_renew: bool, + origin: InternalString, + triggered_by: EventTriggerKind, + ) -> LoroResult<()> { + tracing::info_span!("CheckoutToLatest", peer = self.peer_id()).in_scope(|| { + let f = self.oplog_frontiers(); + let this = &self; + let frontiers = &f; + this._checkout_without_emitting_with_event( + frontiers, + false, + to_commit_then_renew, + origin, + triggered_by, + )?; + // We don't need to shrink frontiers because oplog's frontiers are already shrinked. + this.emit_events(); + if this.config.detached_editing() { + this.renew_peer_id(); + } + + self.set_detached(false); + Ok(()) + }) + } + + /// Checkout [DocState] to a specific version. + /// + /// This will make the current [DocState] detached from the latest version of [OpLog]. + /// Any further import will not be reflected on the [DocState], until user call [LoroDoc::attach()] + pub fn checkout(&self, frontiers: &Frontiers) -> LoroResult<()> { + // Checked here and not in `_checkout_without_emitting`: undo, `checkout_to_latest` + // and the exporters call that and cannot return this error. + self.oplog.lock().check_history_parsable()?; + let was_detached = self.is_detached(); + let (options, guard) = self.implicit_commit_then_stop(); + let result = self._checkout_without_emitting(frontiers, true, true); + if result.is_ok() { + self.emit_events(); + } + drop(guard); + if self.config.detached_editing() { + if result.is_ok() { + self.renew_peer_id(); + } + self.renew_txn_if_auto_commit(options); + } else if result.is_err() { + if !was_detached { + self.renew_txn_if_auto_commit(options); + } + } else if !self.is_detached() { + self.renew_txn_if_auto_commit(options); + } + + result + } + + /// NOTE: The caller of this method should ensure the txn is locked and set to None + #[instrument(level = "info", skip(self))] + pub(crate) fn _checkout_without_emitting( + &self, + frontiers: &Frontiers, + to_shrink_frontiers: bool, + to_commit_then_renew: bool, + ) -> Result<(), LoroError> { + self._checkout_without_emitting_with_event( + frontiers, + to_shrink_frontiers, + to_commit_then_renew, + "checkout".into(), + EventTriggerKind::Checkout, + ) + } + + fn _checkout_without_emitting_with_event( + &self, + frontiers: &Frontiers, + to_shrink_frontiers: bool, + _to_commit_then_renew: bool, + origin: InternalString, + triggered_by: EventTriggerKind, + ) -> Result<(), LoroError> { + if !self.txn.is_locked() { + return Err(LoroError::TransactionError( + "checkout requires the transaction mutex to be held" + .to_string() + .into_boxed_str(), + )); + } + let from_frontiers = self.state_frontiers(); + loro_common::info!( + "checkout from={:?} to={:?} cur_vv={:?}", + from_frontiers, + frontiers, + self.oplog_vv() + ); + + if &from_frontiers == frontiers { + self.set_detached(frontiers != &self.oplog_frontiers()); + return Ok(()); + } + + let oplog = self.oplog.lock(); + if oplog.dag.is_before_shallow_root(frontiers) { + return Err(LoroError::SwitchToVersionBeforeShallowRoot); + } + + let frontiers = if to_shrink_frontiers { + crate::version::try_shrink_frontiers(frontiers, &oplog.dag)? + } else { + frontiers.clone() + }; + + if from_frontiers == frontiers { + return Ok(()); + } + + let mut state = self.state.lock(); + let mut calc = self.diff_calculator.lock(); + for i in frontiers.iter() { + if !oplog.dag.contains(i) { + return Err(LoroError::FrontiersNotFound(i)); + } + } + + let before = oplog + .dag + .try_frontiers_to_vv(&state.frontiers)? + .ok_or_else(|| { + LoroError::NotFoundError( + format!( + "Cannot find the current state version {:?}", + state.frontiers + ) + .into_boxed_str(), + ) + })?; + let Some(after) = &oplog.dag.try_frontiers_to_vv(&frontiers)? else { + return Err(LoroError::NotFoundError( + format!("Cannot find the specified version {:?}", frontiers).into_boxed_str(), + )); + }; + + let (diff, diff_mode) = calc.try_calc_diff_internal( + &oplog, + &before, + &state.frontiers, + after, + &frontiers, + None, + )?; + self.set_detached(true); + state.apply_diff( + InternalDocDiff { + origin, + diff: Cow::Owned(diff), + by: triggered_by, + new_version: Cow::Owned(frontiers.clone()), + }, + diff_mode, + )?; + // Only at the latest version: every root the calculator has seen is then in + // the history of the target version. Checking out an older version keeps + // whatever roots the state already had. + if after == oplog.vv() { + materialize_touched_roots(&mut state, &calc, &oplog.arena); + } + + Ok(()) + } + + #[inline] + pub fn vv_to_frontiers(&self, vv: &VersionVector) -> Frontiers { + self.oplog.lock().dag.vv_to_frontiers(vv) + } + + #[inline] + pub fn frontiers_to_vv(&self, frontiers: &Frontiers) -> Option<VersionVector> { + self.oplog.lock().dag.frontiers_to_vv(frontiers) + } + + /// Converts frontiers to a version vector, reporting unreadable history. + pub fn try_frontiers_to_vv(&self, frontiers: &Frontiers) -> LoroResult<Option<VersionVector>> { + let oplog = self.oplog.lock(); + oplog.check_history_parsable()?; + oplog.dag.try_frontiers_to_vv(frontiers) + } + + /// Converts a version vector to frontiers, reporting unreadable history. + pub fn try_vv_to_frontiers(&self, vv: &VersionVector) -> LoroResult<Frontiers> { + let oplog = self.oplog.lock(); + oplog.check_history_parsable()?; + oplog.dag.try_vv_to_frontiers(vv) + } + + /// Removes redundant frontiers, reporting unreadable history or an absent id. + pub fn try_minimize_frontiers(&self, frontiers: &Frontiers) -> LoroResult<Frontiers> { + let oplog = self.oplog.lock(); + oplog.check_history_parsable()?; + crate::version::try_shrink_frontiers(frontiers, &oplog.dag) + } + + /// Reads change metadata, distinguishing unreadable history from an absent id. + pub fn try_get_change(&self, id: ID) -> LoroResult<Option<ChangeMeta>> { + let oplog = self.oplog.lock(); + let change = oplog.try_get_change_at(id)?; + Ok(change.as_deref().map(ChangeMeta::from_change)) + } + + /// Import ops from other doc. + /// + /// After `a.merge(b)` and `b.merge(a)`, `a` and `b` will have the same content if they are in attached mode. + pub fn merge(&self, other: &Self) -> LoroResult<ImportStatus> { + let updates = other + .export(ExportMode::updates(&self.oplog_vv())) + .map_err(LoroError::from)?; + self.import(&updates) + } + + pub(crate) fn arena(&self) -> &SharedArena { + &self.arena + } + + #[inline] + pub fn len_ops(&self) -> usize { + if self.oplog.can_lock_in_this_thread() { + return self.oplog.lock().visible_op_count_exact(); + } + + self.visible_op_count.load(Acquire) + } + + #[inline] + pub fn len_changes(&self) -> usize { + let oplog = self.oplog.lock(); + oplog.len_changes() + } + + pub fn config(&self) -> &Configure { + &self.config + } + + /// This method compare the consistency between the current doc state + /// and the state calculated by diff calculator from beginning. + /// + /// Panic when it's not consistent + pub fn check_state_diff_calc_consistency_slow(&self) { + // #[cfg(any(test, debug_assertions, feature = "test_utils"))] + { + static IS_CHECKING: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); + if IS_CHECKING.load(std::sync::atomic::Ordering::Acquire) { + return; + } + + IS_CHECKING.store(true, std::sync::atomic::Ordering::Release); + let peer_id = self.peer_id(); + let s = info_span!("CheckStateDiffCalcConsistencySlow", ?peer_id); + let _g = s.enter(); + let options = self.implicit_commit_then_stop().0; + self.oplog.lock().check_dag_correctness(); + if self.is_shallow() { + // For shallow documents, we cannot replay from the beginning as the history is not complete. + // + // Instead, we: + // 1. Export the initial state from the GC snapshot. + // 2. Create a new document and import the initial snapshot. + // 3. Export updates from the shallow start version vector to the current version. + // 4. Import these updates into the new document. + // 5. Compare the states of the new document and the current document. + + // Step 1: Export the initial state from the GC snapshot. + let initial_snapshot = self + .export(ExportMode::state_only(Some( + &self.shallow_since_frontiers(), + ))) + .unwrap(); + + // Step 2: Create a new document and import the initial snapshot. + let doc = LoroDoc::new(); + doc.import(&initial_snapshot).unwrap(); + self.checkout(&self.shallow_since_frontiers()).unwrap(); + assert_eq!(self.get_deep_value(), doc.get_deep_value()); + + // Step 3: Export updates since the shallow start version vector to the current version. + let updates = self.export(ExportMode::all_updates()).unwrap(); + + // Step 4: Import these updates into the new document. + doc.import(&updates).unwrap(); + self.checkout_to_latest(); + + // Step 5: Checkout to the current state's frontiers and compare the states. + // doc.checkout(&self.state_frontiers()).unwrap(); + assert_eq!(doc.get_deep_value(), self.get_deep_value()); + let mut calculated_state = doc.app_state().lock(); + let mut current_state = self.app_state().lock(); + current_state.check_is_the_same(&mut calculated_state); + } else { + let f = self.state_frontiers(); + let vv = self.oplog().lock().dag.frontiers_to_vv(&f).unwrap(); + let bytes = self.export(ExportMode::updates_till(&vv)).unwrap(); + let doc = Self::new(); + doc.import(&bytes).unwrap(); + let mut calculated_state = doc.app_state().lock(); + let mut current_state = self.app_state().lock(); + current_state.check_is_the_same(&mut calculated_state); + } + + self.renew_txn_if_auto_commit(options); + IS_CHECKING.store(false, std::sync::atomic::Ordering::Release); + } + } + + pub fn query_pos(&self, pos: &Cursor) -> Result<PosQueryResult, CannotFindRelativePosition> { + match self.query_pos_internal(pos, true) { + Ok(ans) => Ok(ans), + Err(QueryPosError::Missing(err)) => Err(err), + // `CannotFindRelativePosition` is `Copy` and has no room for the + // decode error. `HistoryUnreadable` is the non-panicking mapping. + Err(QueryPosError::History(_)) => Err(CannotFindRelativePosition::HistoryUnreadable), + } + } + + /// [`query_pos`](Self::query_pos), preserving a decode error from unreadable history. + pub fn try_get_cursor_pos(&self, pos: &Cursor) -> LoroResult<PosQueryResult> { + match self.query_pos_internal(pos, true) { + Ok(ans) => Ok(ans), + Err(QueryPosError::History(err)) => Err(err), + Err(QueryPosError::Missing(err)) => { + Err(LoroError::NotFoundError(err.to_string().into_boxed_str())) + } + } + } + + /// Get position in a seq container + pub(crate) fn query_pos_internal( + &self, + pos: &Cursor, + ret_event_index: bool, + ) -> Result<PosQueryResult, QueryPosError> { + // Public construction and Serde can bypass Cursor::decode. Reject invalid + // ids before taking document locks or tracing their history in the DAG. + if pos.id.is_some_and(|id| id.counter < 0) { + return Err(CannotFindRelativePosition::IdNotFound.into()); + } + + if !self.has_container(&pos.container) { + return Err(CannotFindRelativePosition::IdNotFound.into()); + } + + // Cursors can only point into sequence containers + if !matches!( + pos.container.container_type(), + ContainerType::Text | ContainerType::List | ContainerType::MovableList + ) { + return Err(CannotFindRelativePosition::IdNotFound.into()); + } + + let mut state = self.state.lock(); + if let Some(ans) = state.get_relative_position(pos, ret_event_index) { + Ok(PosQueryResult { + update: None, + current: AbsolutePosition { + pos: ans, + side: pos.side, + }, + }) + } else { + // We need to trace back to the version where the relative position is valid. + // The optimal way to find that version is to have succ info like Automerge. + // + // But we don't have that info now, so an alternative way is to trace back + // to version with frontiers of `[pos.id]`. But this may be very slow even if + // the target is just deleted a few versions ago. + // + // What we need is to trace back to the latest version that deletes the target + // id. + + // commit the txn to make sure we can query the history correctly, preserving options + drop(state); + let result = self.with_barrier(|| { + let oplog = self.oplog().lock(); + // TODO: assert pos.id is not unknown + if let Some(id) = pos.id { + // Ensure the container is registered if it exists lazily + if oplog.arena.id_to_idx(&pos.container).is_none() { + let mut s = self.state.lock(); + if !s.does_container_exist(&pos.container) { + return Err(CannotFindRelativePosition::ContainerDeleted.into()); + } + s.ensure_container(&pos.container); + drop(s); + } + let idx = oplog.arena.id_to_idx(&pos.container).unwrap(); + // We know where the target id is when we trace back to the delete_op_id. + let Some(delete_op_id) = find_last_delete_op(&oplog, id, idx)? else { + if oplog.shallow_since_vv().includes_id(id) { + return Err(CannotFindRelativePosition::HistoryCleared.into()); + } + + tracing::error!("Cannot find id {}", id); + return Err(CannotFindRelativePosition::IdNotFound.into()); + }; + // Should use persist mode so that it will force all the diff calculators to use the `checkout` mode + let mut diff_calc = DiffCalculator::new(true); + let before_frontiers: Frontiers = oplog.dag.find_deps_of_id(delete_op_id); + let before = frontiers_to_vv_or_not_found(&oplog, &before_frontiers)?; + // TODO: PERF: it doesn't need to calc the effects here + diff_calc.try_calc_diff_internal( + &oplog, + &before, + &before_frontiers, + oplog.vv(), + oplog.frontiers(), + Some(&|target| idx == target), + )?; + // TODO: remove depth info + let depth = self.arena.get_depth(idx); + let (_, diff_calc) = &mut diff_calc.get_or_create_calc(idx, depth); + match diff_calc { + crate::diff_calc::ContainerDiffCalculator::Richtext(text) => { + let c = text.get_id_latest_pos(id).unwrap(); + let new_pos = c.pos; + let handler = self.get_text(&pos.container); + let current_pos = handler.convert_entity_index_to_event_index(new_pos); + Ok(PosQueryResult { + update: handler.get_cursor(current_pos, c.side), + current: AbsolutePosition { + pos: current_pos, + side: c.side, + }, + }) + } + crate::diff_calc::ContainerDiffCalculator::List(list) => { + let c = list.get_id_latest_pos(id).unwrap(); + let new_pos = c.pos; + let handler = self.get_list(&pos.container); + Ok(PosQueryResult { + update: handler.get_cursor(new_pos, c.side), + current: AbsolutePosition { + pos: new_pos, + side: c.side, + }, + }) + } + crate::diff_calc::ContainerDiffCalculator::MovableList(list) => { + let c = list.get_id_latest_pos(id).unwrap(); + let new_pos = c.pos; + let handler = self.get_movable_list(&pos.container); + let new_pos = handler.op_pos_to_user_pos(new_pos); + Ok(PosQueryResult { + update: handler.get_cursor(new_pos, c.side), + current: AbsolutePosition { + pos: new_pos, + side: c.side, + }, + }) + } + crate::diff_calc::ContainerDiffCalculator::Tree(_) => unreachable!(), + crate::diff_calc::ContainerDiffCalculator::Map(_) => unreachable!(), + #[cfg(feature = "counter")] + crate::diff_calc::ContainerDiffCalculator::Counter(_) => unreachable!(), + crate::diff_calc::ContainerDiffCalculator::Unknown(_) => unreachable!(), + } + } else { + match pos.container.container_type() { + ContainerType::Text => { + let text = self.get_text(&pos.container); + Ok(PosQueryResult { + update: Some(Cursor { + id: None, + container: text.id(), + side: pos.side, + origin_pos: text.len_unicode(), + }), + current: AbsolutePosition { + pos: text.len_event(), + side: pos.side, + }, + }) + } + ContainerType::List => { + let list = self.get_list(&pos.container); + Ok(PosQueryResult { + update: Some(Cursor { + id: None, + container: list.id(), + side: pos.side, + origin_pos: list.len(), + }), + current: AbsolutePosition { + pos: list.len(), + side: pos.side, + }, + }) + } + ContainerType::MovableList => { + let list = self.get_movable_list(&pos.container); + Ok(PosQueryResult { + update: Some(Cursor { + id: None, + container: list.id(), + side: pos.side, + origin_pos: list.len(), + }), + current: AbsolutePosition { + pos: list.len(), + side: pos.side, + }, + }) + } + ContainerType::Map | ContainerType::Tree | ContainerType::Unknown(_) => { + unreachable!() + } + #[cfg(feature = "counter")] + ContainerType::Counter => unreachable!(), + } + } + }); + result + } + } + + /// Free the history cache that is used for making checkout faster. + /// + /// If you use checkout that switching to an old/concurrent version, the history cache will be built. + /// You can free it by calling this method. + pub fn free_history_cache(&self) { + self.oplog.lock().free_history_cache(); + } + + /// Free the cached diff calculator that is used for checkout. + pub fn free_diff_calculator(&self) { + *self.diff_calculator.lock() = DiffCalculator::new(true); + } + + /// If you use checkout that switching to an old/concurrent version, the history cache will be built. + /// You can free it by calling `free_history_cache`. + pub fn has_history_cache(&self) -> bool { + self.oplog.lock().has_history_cache() + } + + /// Encoded all ops and history cache to bytes and store them in the kv store. + /// + /// The parsed ops will be dropped + #[inline] + pub fn compact_change_store(&self) { + self.with_barrier(|| { + self.oplog.lock().compact_change_store(); + }); + } + + /// Analyze the container info of the doc + /// + /// This is used for development and debugging + #[inline] + pub fn analyze(&self) -> DocAnalysis { + DocAnalysis::analyze(self) + } + + /// Get the path from the root to the container + pub fn get_path_to_container(&self, id: &ContainerID) -> Option<Vec<(ContainerID, Index)>> { + let mut state = self.state.lock(); + if state.arena.id_to_idx(id).is_none() { + if id.is_mergeable() { + // Mergeable children can be logically active via the parent map marker + // before they have their own encoded state. Register only the arena edge; do not + // create container state or change `has_container` semantics. + state.arena.register_container(id); + } else if !state.does_container_exist(id) { + return None; + } else { + state.ensure_container(id); + } + } + // The registration above can already be gone: a failed import on another thread + // rolls back every registration made since it began (loro-dev/loro#1164). + let idx = state.arena.id_to_idx(id)?; + state.get_path(idx) + } + + #[instrument(skip(self))] + pub fn export(&self, mode: ExportMode) -> Result<Vec<u8>, LoroEncodeError> { + self.export_inner(mode, true) + } + + /// With `reject_partial_history`, the export fails if a change block that cannot be + /// parsed was found, before or during the export, instead of returning bytes that + /// silently miss those changes. `fork` passes `false`: it has no error to return. + pub(crate) fn export_inner( + &self, + mode: ExportMode, + reject_partial_history: bool, + ) -> Result<Vec<u8>, LoroEncodeError> { + self.with_barrier(|| { + if reject_partial_history { + self.oplog.lock().check_history_parsable()?; + } + let ans = match mode { + ExportMode::Snapshot => export_fast_snapshot(self)?, + ExportMode::Updates { from } => export_fast_updates(self, &from), + ExportMode::UpdatesInRange { spans } => { + export_fast_updates_in_range(&self.oplog.lock(), spans.as_ref()) + } + ExportMode::ShallowSnapshot(f) => export_shallow_snapshot(self, &f)?, + ExportMode::StateOnly(f) => match f { + Some(f) => export_state_only_snapshot(self, &f)?, + None => export_state_only_snapshot(self, &self.oplog_frontiers())?, + }, + ExportMode::SnapshotAt { version } => export_snapshot_at(self, &version)?, + }; + if reject_partial_history { + self.oplog.lock().check_history_parsable()?; + } + Ok(ans) + }) + } + + /// Export received remote changes waiting for causal dependencies, excluding + /// local uncommitted operations. Returns `None` when nothing remains pending. + /// This method does not commit, consume pending, emit events, or advance the + /// applied version/frontiers. Ordinary snapshot/update exports omit pending. + /// + /// Capture snapshot and sidecar without concurrent document mutations/imports + /// and persist them as one consistent checkpoint. `None` in a new checkpoint + /// must clear its old sidecar; errors must not be treated as `None`. Restore + /// snapshot then sidecar with ordinary `import`; actual missing dependencies + /// must still arrive. This method cannot supply never-received predecessors + /// and does not define cursor advancement or whether the document is synced. + pub fn export_pending_updates(&self) -> Result<Option<Vec<u8>>, LoroEncodeError> { + encoding::export_pending_updates(&self.oplog.lock()) + } + + /// The doc only contains the history since the shallow history start version vector. + /// + /// This is empty if the doc is not shallow. + /// + /// The ops included by the shallow history start version vector are not in the doc. + pub fn shallow_since_vv(&self) -> ImVersionVector { + self.oplog().lock().shallow_since_vv().clone() + } + + pub fn shallow_since_frontiers(&self) -> Frontiers { + self.oplog().lock().shallow_since_frontiers().clone() + } + + /// Check if the doc contains the full history. + pub fn is_shallow(&self) -> bool { + !self.oplog().lock().shallow_since_vv().is_empty() + } + + /// Get the number of operations in the pending transaction. + /// + /// The pending transaction is the one that is not committed yet. It will be committed + /// after calling `doc.commit()`, `doc.export(mode)` or `doc.checkout(version)`. + pub fn get_pending_txn_len(&self) -> usize { + if let Some(txn) = self.txn.lock().as_ref() { + txn.len() + } else { + 0 + } + } + + #[inline] + pub fn find_id_spans_between(&self, from: &Frontiers, to: &Frontiers) -> VersionVectorDiff { + self.oplog().lock().dag.find_path(from, to) + } + + /// Finds operation spans between versions, reporting unreadable history. + pub fn try_find_id_spans_between( + &self, + from: &Frontiers, + to: &Frontiers, + ) -> LoroResult<VersionVectorDiff> { + let oplog = self.oplog.lock(); + oplog.check_history_parsable()?; + for id in from.iter().chain(to.iter()) { + if !oplog.vv().includes_id(id) { + return Err(LoroError::FrontiersNotFound(id)); + } + } + oplog.dag.try_find_path(from, to) + } + + /// Subscribe to the first commit from a peer. Operations performed on the `LoroDoc` within this callback + /// will be merged into the current commit. + /// + /// This is useful for managing the relationship between `PeerID` and user information. + /// For example, you could store user names in a `LoroMap` using `PeerID` as the key and the `UserID` as the value. + pub fn subscribe_first_commit_from_peer( + &self, + callback: FirstCommitFromPeerCallback, + ) -> Subscription { + let (s, enable) = self + .first_commit_from_peer_subs + .inner() + .insert((), callback); + enable(); + s + } + + /// Subscribe to the pre-commit event. + /// + /// The callback will be called when the changes are committed but not yet applied to the OpLog. + /// You can modify the commit message and timestamp in the callback by [`ChangeModifier`]. + pub fn subscribe_pre_commit(&self, callback: PreCommitCallback) -> Subscription { + let (s, enable) = self.pre_commit_subs.inner().insert((), callback); + enable(); + s + } +} + +/// A root container touched by any op in a doc's history is part of its value, even +/// when the ops add up to an empty value: the peer that wrote them created the root's +/// state with its first local op. A replay whose net diff for the root is empty never +/// creates that state, so create it here (loro-dev/loro#1156). +/// +/// `calc` must have computed diffs whose ranges all lie in the history of the state's +/// new version. +fn materialize_touched_roots(state: &mut DocState, calc: &DiffCalculator, arena: &SharedArena) { + for idx in calc.touched_containers() { + if let Some(id) = arena.idx_to_id(idx) { + if id.is_root() && !id.is_mergeable() && !state.store.contains_id(&id) { + state.ensure_container(&id); + } + } + } +} + +fn pending_root_containers_to_materialize( + oplog: &OpLog, + changes: &[Change], +) -> LoroResult<Vec<ContainerID>> { + let mut roots = FxHashSet::default(); + for change in changes { + if change.ctr_end() <= oplog.vv().get(&change.id.peer).copied().unwrap_or(0) { + continue; + } + + if oplog.dag.is_before_shallow_root(&change.deps) + || oplog + .dag + .try_get_change_lamport_from_deps(&change.deps)? + .is_some() + { + continue; + } + + for op in change.ops.iter() { + let id = oplog + .arena + .get_container_id(op.container) + .expect("decoded op container should be registered"); + // Mergeable containers share the `ContainerID::Root` namespace but are logical + // *children*: their existence is governed by their parent map's marker, and their + // parent can be any (possibly not-yet-imported) map. Eagerly materializing one + // while its causal dependencies are still pending has no valid parent edge to + // resolve its depth against, which used to panic in `ContainerWrapper::new`. + // They get materialized correctly through the normal diff path once the creating + // change applies, so skip them here (mirrors the `!is_mergeable()` guard in + // `ensure_root_container`). See the `mergeable_container::pending` regression test. + if id.is_root() && !id.is_mergeable() { + roots.insert(id); + } + } + } + + Ok(roots.into_iter().collect()) +} + +/// Version vector of `frontiers`. `None` from the dag walk is a missing id, not +/// an empty vector and not a panic. +fn frontiers_to_vv_or_not_found(oplog: &OpLog, frontiers: &Frontiers) -> LoroResult<VersionVector> { + match oplog.dag.try_frontiers_to_vv(frontiers)? { + Some(vv) => Ok(vv), + None => { + for id in frontiers.iter() { + if oplog.dag.try_get(id)?.is_none() { + return Err(LoroError::FrontiersNotFound(id)); + } + } + Err(LoroError::NotFoundError( + format!("Cannot find the specified version {frontiers:?}").into_boxed_str(), + )) + } + } +} + +/// Identify a causally closed update component that can be applied without replaying unrelated +/// history. The first version is deliberately narrow: it accepts only scalar Map operations on +/// top-level roots that never appeared in the existing history. +fn isolated_scalar_root_batch( + oplog: &OpLog, + changes: &[Change], +) -> Option<(VersionVector, FxHashSet<InternalString>)> { + if changes.is_empty() || !oplog.shallow_since_vv().is_empty() { + return None; + } + + // Every peer in the batch must be brand new and contiguously covered from counter 0. + // (`changes` is sorted by lamport, so one peer's changes appear in counter order.) + let mut component_vv = VersionVector::new(); + let mut root_names = FxHashSet::default(); + for change in changes { + let peer = change.id.peer; + if oplog.vv().get(&peer).copied().unwrap_or(0) != 0 { + return None; + } + let end = component_vv.entry(peer).or_insert(0); + if change.id.counter != *end { + return None; + } + *end = change.ctr_end(); + + for op in change.ops.iter() { + let cid = oplog.arena.idx_to_id(op.container)?; + if cid.is_mergeable() { + return None; + } + let ContainerID::Root { + name, + container_type: ContainerType::Map, + } = cid + else { + return None; + }; + let InnerContent::Map(map) = &op.content else { + return None; + }; + if let Some(value) = &map.value { + if value.is_container() + || loro_common::parse_mergeable_marker( + &ContainerID::new_root(&name, ContainerType::Map), + &map.key, + value, + ) + .is_some() + { + return None; + } + } + root_names.insert(name); + } + } + + // The batch must be causally closed: every dependency points inside the batch itself. + for change in changes { + for dep in change.deps.iter() { + if dep.counter >= component_vv.get(&dep.peer).copied().unwrap_or(0) { + return None; + } + } + } + + if oplog + .change_store() + .old_history_may_touch_root_names(&root_names) + { + return None; + } + + Some((component_vv, root_names)) +} + +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum ChangeTravelError { + #[error(transparent)] + HistoryUnreadable(#[from] LoroError), + #[error("Target id not found {0:?}")] + TargetIdNotFound(ID), + #[error("The shallow history of the doc doesn't include the target version")] + TargetVersionNotIncluded, +} + +impl LoroDoc { + pub fn travel_change_ancestors( + &self, + ids: &[ID], + f: &mut dyn FnMut(ChangeMeta) -> ControlFlow<()>, + ) -> Result<(), ChangeTravelError> { + let (options, guard) = self.implicit_commit_then_stop(); + drop(guard); + struct PendingNode(ChangeMeta); + impl PartialEq for PendingNode { + fn eq(&self, other: &Self) -> bool { + self.0.lamport_last() == other.0.lamport_last() && self.0.id.peer == other.0.id.peer + } + } + + impl Eq for PendingNode {} + impl PartialOrd for PendingNode { + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { + Some(self.cmp(other)) + } + } + + impl Ord for PendingNode { + fn cmp(&self, other: &Self) -> Ordering { + self.0 + .lamport_last() + .cmp(&other.0.lamport_last()) + .then_with(|| self.0.id.peer.cmp(&other.0.id.peer)) + } + } + + let ans = (|| { + for id in ids { + let op_log = &self.oplog().lock(); + op_log.check_history_parsable()?; + if !op_log.vv().includes_id(*id) { + return Err(ChangeTravelError::TargetIdNotFound(*id)); + } + if op_log.dag.shallow_since_vv().includes_id(*id) { + return Err(ChangeTravelError::TargetVersionNotIncluded); + } + } + + let mut visited = FxHashSet::default(); + let mut pending: BinaryHeap<PendingNode> = BinaryHeap::new(); + for id in ids { + let change = self + .oplog() + .lock() + .try_get_change_at(*id)? + .ok_or(ChangeTravelError::TargetIdNotFound(*id))?; + pending.push(PendingNode(ChangeMeta::from_change(&change))); + } + while let Some(PendingNode(node)) = pending.pop() { + let deps = node.deps.clone(); + if f(node).is_break() { + break; + } + + for dep in deps.iter() { + let Some(dep_node) = self.oplog().lock().try_get_change_at(dep)? else { + continue; + }; + if visited.contains(&dep_node.id) { + continue; + } + + visited.insert(dep_node.id); + pending.push(PendingNode(ChangeMeta::from_change(&dep_node))); + } + } + + Ok(()) + })(); + self.renew_txn_if_auto_commit(options); + ans + } + + pub fn get_changed_containers_in(&self, id: ID, len: usize) -> FxHashSet<ContainerID> { + self.with_barrier(|| { + let mut set = FxHashSet::default(); + let len = i64::try_from(len).unwrap_or(i64::MAX); + let start = i64::from(id.counter); + let end = start.saturating_add(len); + if end <= 0 { + return set; + } + + let start = start.max(0).min(i64::from(i32::MAX)); + let end = end.max(0).min(i64::from(i32::MAX)); + if start >= end { + return set; + } + + { + let oplog = self.oplog().lock(); + let span = IdSpan::new(id.peer, start as i32, end as i32); + for op in oplog.iter_ops(span) { + let id = oplog.arena.get_container_id(op.container()).unwrap(); + set.insert(id); + } + } + set + }) + } + + /// Gets modified container IDs, reporting unreadable history. + pub fn try_get_changed_containers_in( + &self, + id: ID, + len: usize, + ) -> LoroResult<FxHashSet<ContainerID>> { + self.oplog.lock().check_history_parsable()?; + let containers = self.get_changed_containers_in(id, len); + self.oplog.lock().check_history_parsable()?; + Ok(containers) + } + + pub fn delete_root_container(&self, cid: ContainerID) { + if !cid.is_root() { + return; + } + + // Do not treat "not in arena" as non-existence; consult state/kv + if !self.has_container(&cid) { + return; + } + + let Some(h) = self.get_handler(cid.clone()) else { + return; + }; + + self.config + .deleted_root_containers + .lock() + .insert(cid.clone()); + if let Err(e) = h.clear() { + self.config.deleted_root_containers.lock().remove(&cid); + eprintln!("Failed to clear handler: {:?}", e); + } + } + + pub fn set_hide_empty_root_containers(&self, hide: bool) { + self.config + .hide_empty_root_containers + .store(hide, std::sync::atomic::Ordering::Relaxed); + } +} + +pub(crate) enum QueryPosError { + Missing(CannotFindRelativePosition), + History(LoroError), +} + +impl From<LoroError> for QueryPosError { + fn from(err: LoroError) -> Self { + QueryPosError::History(err) + } +} + +impl From<CannotFindRelativePosition> for QueryPosError { + fn from(err: CannotFindRelativePosition) -> Self { + QueryPosError::Missing(err) + } +} + +fn find_last_delete_op(oplog: &OpLog, id: ID, idx: ContainerIdx) -> LoroResult<Option<ID>> { + // Any delete op that covers `id` must have observed it, so its peer's counter + // at delete time was > id.counter. start_vv (the vv at `id`) is therefore a + // valid lower bound: changes at or before start_vv[peer] predate `id` and can + // be skipped. We scan peer-by-peer rather than using the DAG-ordered + // iter_changes_causally_rev, which is O(total changes). + // + // We choose the matching delete op with the greatest (op_lamport, peer, counter) + // ordering. op_lamport is the Lamport of the specific op within the change + // (change.lamport + op offset), not just the change's starting Lamport, so + // concurrent deletes with equal change Lamports are broken deterministically. + let start_vv = match oplog.dag.try_frontiers_to_vv(&id.into())? { + Some(vv) => vv, + None => oplog.shallow_since_vv().to_vv(), + }; + + // (op_lamport, peer) gives a deterministic total order for concurrent deletes. + // A single peer cannot produce two ops with the same lamport, so peer suffices + // as a tie-breaker. + let mut best: Option<((loro_common::Lamport, loro_common::PeerID), ID)> = None; + + for change in oplog.iter_changes_peer_by_peer(&start_vv, oplog.vv()) { + let peer = change.peer(); + for op in change.ops.iter() { + if op.container != idx { + continue; + } + if let InnerContent::List(InnerListOp::Delete(d)) = &op.content { + if d.id_start.to_span(d.atom_len()).contains(id) { + debug_assert!(op.counter >= change.id().counter); + let op_lamport = + change.lamport + (op.counter - change.id().counter) as loro_common::Lamport; + let key = (op_lamport, peer); + if best.is_none_or(|(bk, _)| key > bk) { + best = Some((key, ID::new(peer, op.counter))); + } + } + } + } + } + + // The legacy peer iterator records a bad block and skips it. A skipped + // block may hold the delete, so that is a decode error, not a missing id. + oplog.check_history_parsable()?; + Ok(best.map(|(_, op_id)| op_id)) +} + +/// Cleanup for the critical section of [`LoroDoc::import_batch`]. +/// +/// `import_batch` force-detaches the document so each blob only touches the `OpLog`, +/// then reattaches once at the end. Leaving that section without reattaching strands +/// the document in detached mode: further imports stop being reflected in `DocState`, +/// local edits branch off a stale version, and every later `attach()` re-runs the same +/// failing checkout. `finish` owns that reattach, and `import_batch` must call it +/// explicitly on every exit path — including after catching a panic, because cleanup +/// cannot run *while* unwinding (`MutexGuard::drop` poisons its mutex when a panic is +/// in flight, and a second panic during unwind aborts the process). A `Drop` impl +/// therefore cannot help; the debug-only one below only asserts the contract. +struct BatchImportGuard<'a> { + doc: &'a LoroDoc, + /// Whether the doc was attached before the batch and therefore owes a reattach. + /// It also decides whether we own the batch-wide import rollback scope. + was_attached: bool, + /// Held for the whole batch so no other thread can renew the txn and edit while + /// we are detached. `_checkout_to_latest_without_commit` requires it to be held. + txn: Option<LoroMutexGuard<'a, Option<Transaction>>>, + options: Option<CommitOptions>, + /// A full snapshot initialized a previously empty document. On checkout + /// failure both its lazy state and its history must be reset, not just the + /// updates recorded in the suffix journal. + snapshot_checkpoint: Option<BatchSnapshotRollback>, + #[cfg(debug_assertions)] + finished: bool, +} + +struct BatchSnapshotRollback { + arena: SharedArenaRollback, + // Even an empty doc may expose empty containers acquired through getters. + empty_containers: Vec<ContainerID>, +} + +/// Forward import diffs of movable lists take untouched element fields from +/// `DocState`. When a (forged) op targets an element the state no longer holds, +/// recompute the diff in Checkout mode, which resolves elements from history the +/// same way `checkout`, `import_batch` and snapshot replay do. +/// See `context/movable-list-op-validation.md`. +fn recalc_in_checkout_mode_if_needed( + state: &mut DocState, + oplog: &OpLog, + old_vv: &VersionVector, + old_frontiers: &Frontiers, + diff: Vec<crate::event::InternalContainerDiff>, +) -> LoroResult<Vec<crate::event::InternalContainerDiff>> { + if !state.needs_checkout_diff(&diff) { + return Ok(diff); + } + + Ok(DiffCalculator::new(true) + .try_calc_diff_internal( + oplog, + old_vv, + old_frontiers, + oplog.vv(), + oplog.dag.get_frontiers(), + None, + )? + .0) +} + +impl BatchImportGuard<'_> { + /// Leave batch-import mode, reattach if the doc was attached, and renew the txn. + /// + /// Returns the still-pending version range on success. If the accumulated changes + /// cannot be applied to `DocState` (malformed remote ops reach state validation + /// only here, because the blobs were imported while detached), the whole batch is + /// rolled back out of the `OpLog` so the document stays attached and unchanged, + /// and the state-apply error is returned. + fn finish(&mut self) -> LoroResult<VersionRange> { + #[cfg(debug_assertions)] + { + self.finished = true; + } + let doc = self.doc; + let txn = self.txn.take().expect("finish called twice"); + let options = self.options.take(); + + let pending = { + let mut oplog = doc.oplog.lock(); + oplog.batch_importing = false; + oplog.pending_changes.version_range() + }; + + // The txn guard must stay held across the checkout, and the renew below must + // reuse it: dropping it first and re-locking would panic when this runs after + // a caught panic, because releasing a `Mutex` guard while a panic is in + // flight poisons the mutex. + let mut checkout = Ok(()); + if self.was_attached { + // The blobs were imported while detached inside this scope, so their + // movable-list element references are validated here, once per batch. + let validation = doc + .oplog + .lock() + .validate_movable_list_elem_refs_in_import_scope(); + checkout = validation.and_then(|()| doc._checkout_to_latest_without_commit(true)); + if let Err(e) = &checkout { + // Validation precedes mutation: state is still at its pre-batch + // version, or at the bootstrapped snapshot. Restore the matching + // baseline in both state and history before leaving attached. + tracing::warn!("import_batch cannot reattach, rolling the batch back: {e}"); + let mut oplog = doc.oplog.lock(); + let mut state = doc.state.lock(); + if let Some(checkpoint) = self.snapshot_checkpoint.take() { + state.reset_to_empty_for_failed_snapshot_import(); + oplog.reset_to_empty_for_failed_snapshot_import(checkpoint.arena, &mut state); + for id in checkpoint.empty_containers { + state.ensure_container(&id); + } + } else { + oplog.rollback_import(&mut state); + } + drop(state); + drop(oplog); + // The shared diff calculator cached ranges against the rolled-back + // history; drop that cache instead of reusing stale entries. + *doc.diff_calculator.lock() = DiffCalculator::new(true); + doc.set_detached(false); + } else { + doc.oplog.lock().commit_import_rollback(); + } + } + + doc._renew_txn_if_auto_commit_with_guard(options, txn); + checkout.map(|()| pending) + } +} + +/// Debug-only tripwire: `finish` must be called explicitly (see the struct docs for +/// why `Drop` cannot do the cleanup itself). Release builds compile this out. +#[cfg(debug_assertions)] +impl Drop for BatchImportGuard<'_> { + fn drop(&mut self) { + if !std::thread::panicking() { + assert!( + self.finished, + "BatchImportGuard dropped without calling finish()" + ); + } + } +} + +#[derive(Debug)] +pub struct CommitWhenDrop<'a> { + doc: &'a LoroDoc, + default_options: CommitOptions, +} + +impl Drop for CommitWhenDrop<'_> { + fn drop(&mut self) { + { + let mut guard = self.doc.txn.lock(); + if let Some(txn) = guard.as_mut() { + txn.set_default_options(std::mem::take(&mut self.default_options)); + }; + } + + self.doc.commit_then_renew(); + } +} + +/// Options for configuring a commit operation. +#[derive(Debug, Clone)] +pub struct CommitOptions { + /// Origin identifier for the commit event, used to track the source of changes. + /// It doesn't persist. + pub origin: Option<InternalString>, + + /// Whether to immediately start a new transaction after committing. + /// Defaults to true. + pub immediate_renew: bool, + + /// Custom timestamp for the commit in seconds since Unix epoch. + /// If None, the current time will be used. + pub timestamp: Option<Timestamp>, + + /// Optional commit message to attach to the changes. It will be persisted. + pub commit_msg: Option<Arc<str>>, +} + +impl CommitOptions { + /// Creates a new CommitOptions with default values. + pub fn new() -> Self { + Self { + origin: None, + immediate_renew: true, + timestamp: None, + commit_msg: None, + } + } + + /// Sets the origin identifier for this commit. + pub fn origin(mut self, origin: &str) -> Self { + self.origin = Some(origin.into()); + self + } + + /// Sets whether to immediately start a new transaction after committing. + pub fn immediate_renew(mut self, immediate_renew: bool) -> Self { + self.immediate_renew = immediate_renew; + self + } + + /// Set the timestamp of the commit. + /// + /// The timestamp is the number of **seconds** that have elapsed since 00:00:00 UTC on January 1, 1970. + pub fn timestamp(mut self, timestamp: Timestamp) -> Self { + self.timestamp = Some(timestamp); + self + } + + /// Sets a commit message to be attached to the changes. + pub fn commit_msg(mut self, commit_msg: &str) -> Self { + self.commit_msg = Some(commit_msg.into()); + self + } + + /// Sets the origin identifier for this commit. + pub fn set_origin(&mut self, origin: Option<&str>) { + self.origin = origin.map(|x| x.into()) + } + + /// Sets the timestamp for this commit. + pub fn set_timestamp(&mut self, timestamp: Option<Timestamp>) { + self.timestamp = timestamp; + } +} + +impl Default for CommitOptions { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod test { + use std::{ + panic::AssertUnwindSafe, + sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, + }, + }; + + use crate::{ + cursor::PosType, + encoding::json_schema::json::{JsonOpContent, JsonSchema, ListOp}, + encoding::{fast_snapshot::EMPTY_MARK, EncodeMode}, + loro::ExportMode, + version::{Frontiers, VersionVector}, + LoroDoc, ToJson, TreeParentId, + }; + use bytes::{BufMut, Bytes}; + use loro_common::{ContainerID, ContainerType, ID}; + use loro_kv_store::{mem_store::MemKvConfig, MemKvStore}; + + const XXH_SEED: u32 = u32::from_le_bytes(*b"LORO"); + + fn encode_import_blob(mode: EncodeMode, body: &[u8]) -> Vec<u8> { + let mut ans = Vec::new(); + ans.extend_from_slice(b"loro"); + ans.extend_from_slice(&[0; 16]); + ans.extend_from_slice(&mode.to_bytes()); + ans.extend_from_slice(body); + let checksum = xxhash_rust::xxh32::xxh32(&ans[20..], XXH_SEED); + ans[16..20].copy_from_slice(&checksum.to_le_bytes()); + ans + } + + fn encode_fast_snapshot_import(oplog_bytes: &[u8]) -> Vec<u8> { + let mut body = Vec::new(); + body.put_u32_le(oplog_bytes.len() as u32); + body.extend_from_slice(oplog_bytes); + body.put_u32_le(EMPTY_MARK.len() as u32); + body.extend_from_slice(EMPTY_MARK); + body.put_u32_le(0); + encode_import_blob(EncodeMode::FastSnapshot, &body) + } + + fn sstable_with_huge_meta_block_count() -> Vec<u8> { + let mut bytes = Vec::new(); + bytes.extend_from_slice(b"LORO"); + bytes.push(0); + bytes.put_u32_le(10_000_000); + bytes.put_u32_le(xxhash_rust::xxh32::xxh32(&[], XXH_SEED)); + bytes.put_u32_le(5); + bytes + } + + fn snapshot_oplog_with_malformed_block() -> Vec<u8> { + let peer = 1; + let id = ID::new(peer, 0); + let vv = VersionVector::from_iter([(peer, 1)]); + let frontiers = Frontiers::from_id(id); + let mut store = MemKvStore::new(MemKvConfig::default()); + store.set(b"vv", vv.encode().into()); + store.set(b"fr", frontiers.encode().into()); + store.set(&id.to_bytes(), Bytes::from_static(&[0])); + store.export_all().to_vec() + } + + fn make_json_import_stress_doc(peer: u64) -> LoroDoc { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(peer).unwrap(); + + let text = doc.get_text("text"); + let mut text_pos = 0; + for i in 0..32 { + let chunk = format!("segment-{i}-abcdefghijklmnopqrstuvwxyz;"); + text.insert_unicode(text_pos, &chunk).unwrap(); + text_pos += chunk.chars().count(); + } + + let list = doc.get_list("list"); + for i in 0..32 { + list.insert(i, format!("item-{i}")).unwrap(); + } + + let map = doc.get_map("map"); + for i in 0..32 { + let key = format!("key-{i}"); + map.insert(&key, format!("value-{i}")).unwrap(); + } + + let tree = doc.get_tree("tree"); + let mut parent = TreeParentId::Root; + for i in 0..16 { + let node = tree.create(parent).unwrap(); + let meta = tree.get_meta(node).unwrap(); + meta.insert("name", format!("node-{i}")).unwrap(); + meta.insert("payload", format!("payload-{i}-{}", "x".repeat(16))) + .unwrap(); + parent = TreeParentId::Node(node); + } + + doc + } + + fn make_json_list_update_with_four_ops(peer: u64) -> (LoroDoc, JsonSchema) { + let doc = LoroDoc::new(); + doc.set_peer_id(peer).unwrap(); + let map = doc.get_map("map"); + let list = doc.get_list("list"); + let text = doc.get_text("text"); + + let mut txn = doc.txn().unwrap(); + map.insert_with_txn(&mut txn, "prefix", "map-value".into()) + .unwrap(); + list.insert_with_txn(&mut txn, 0, "seed".into()).unwrap(); + text.insert_with_txn(&mut txn, 0, "text-value", PosType::Unicode) + .unwrap(); + list.insert_with_txn(&mut txn, 1, "tail".into()).unwrap(); + txn.commit().unwrap(); + + let json = doc + .export_json_updates(&Default::default(), &doc.oplog_vv(), false) + .unwrap(); + assert_eq!(json.changes.len(), 1); + assert_eq!(json.changes[0].ops.len(), 4); + (doc, json) + } + + fn move_last_list_insert_far_out_of_bounds(json: &mut JsonSchema) { + let last_change = json.changes.last_mut().unwrap(); + let last_op = last_change.ops.last_mut().unwrap(); + match &mut last_op.content { + JsonOpContent::List(ListOp::Insert { pos, .. }) => { + *pos = 1_000; + } + other => panic!("expected list insert op, got {other:?}"), + } + } + + #[test] + fn test_sync() { + fn is_send_sync<T: Send + Sync>(_v: T) {} + let loro = super::LoroDoc::new(); + is_send_sync(loro) + } + + #[test] + fn import_rejects_huge_sstable_meta_block_count_without_panic() { + let bytes = encode_fast_snapshot_import(&sstable_with_huge_meta_block_count()); + + let result = std::panic::catch_unwind(AssertUnwindSafe(|| LoroDoc::new().import(&bytes))); + assert!(result.is_ok(), "malformed import should not panic"); + assert!(result.unwrap().is_err()); + } + + #[test] + fn import_rejects_malformed_change_block_without_panic() { + let bytes = encode_fast_snapshot_import(&snapshot_oplog_with_malformed_block()); + + let result = std::panic::catch_unwind(AssertUnwindSafe(|| LoroDoc::new().import(&bytes))); + assert!(result.is_ok(), "malformed import should not panic"); + assert!(result.unwrap().is_err()); + } + + #[test] + fn failed_import_rolls_back_oplog_and_arena() { + let src = LoroDoc::new(); + src.set_peer_id(1).unwrap(); + let text = src.get_text("text"); + let mut txn = src.txn().unwrap(); + text.insert_with_txn(&mut txn, 0, "hello", PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + let update = src.export(ExportMode::all_updates()).unwrap(); + + let dst = LoroDoc::new(); + let vv_before_import = dst.oplog_vv(); + let state_before_import = dst.get_deep_value(); + let err = dst + .import_with(&update, "__loro_fail_import_state_apply".into()) + .unwrap_err(); + assert!(err.to_string().contains("state apply failpoint")); + assert_eq!(dst.oplog_vv(), vv_before_import); + assert_eq!(dst.get_deep_value(), state_before_import); + assert!(dst.oplog().lock().is_empty()); + + dst.import(&update).unwrap(); + assert_eq!(dst.get_deep_value(), src.get_deep_value()); + } + + #[test] + fn failed_incremental_import_restores_previous_change_store_block() { + let src = LoroDoc::new(); + src.set_peer_id(1).unwrap(); + let text = src.get_text("text"); + let mut txn = src.txn().unwrap(); + text.insert_with_txn(&mut txn, 0, "a", PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + let first_update = src.export(ExportMode::all_updates()).unwrap(); + let first_vv = src.oplog_vv(); + + let mut txn = src.txn().unwrap(); + text.insert_with_txn(&mut txn, 1, "b", PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + let second_update = src.export(ExportMode::updates(&first_vv)).unwrap(); + + let dst = LoroDoc::new(); + dst.import(&first_update).unwrap(); + let vv_before_import = dst.oplog_vv(); + let state_before_import = dst.get_deep_value(); + dst.import_with(&second_update, "__loro_fail_import_state_apply".into()) + .unwrap_err(); + assert_eq!(dst.oplog_vv(), vv_before_import); + assert_eq!(dst.get_deep_value(), state_before_import); + + dst.import(&second_update).unwrap(); + assert_eq!(dst.get_deep_value(), src.get_deep_value()); + } + + #[test] + fn failed_import_json_updates_rolls_back_complex_empty_doc() { + let src = make_json_import_stress_doc(11); + let json = src + .export_json_updates(&Default::default(), &src.oplog_vv(), false) + .unwrap(); + + let dst = LoroDoc::new(); + let vv_before_import = dst.oplog_vv(); + let frontiers_before_import = dst.oplog_frontiers(); + let state_before_import = dst.get_deep_value(); + for _ in 0..3 { + crate::state::fail_next_import_state_apply_for_test(); + let err = dst.import_json_updates(json.clone()).unwrap_err(); + assert!(err.to_string().contains("state apply failpoint")); + assert_eq!(dst.oplog_vv(), vv_before_import); + assert_eq!(dst.oplog_frontiers(), frontiers_before_import); + assert_eq!(dst.get_deep_value(), state_before_import); + assert!(dst.oplog().lock().is_empty()); + } + + dst.import_json_updates(json).unwrap(); + assert_eq!(dst.oplog_vv(), src.oplog_vv()); + assert_eq!(dst.oplog_frontiers(), src.oplog_frontiers()); + assert_eq!(dst.get_deep_value(), src.get_deep_value()); + } + + #[test] + fn failed_incremental_import_json_updates_restores_previous_change_store_block() { + let src = LoroDoc::new_auto_commit(); + src.set_peer_id(12).unwrap(); + let text = src.get_text("text"); + text.insert_unicode(0, "a").unwrap(); + let list = src.get_list("list"); + list.push("seed").unwrap(); + let map = src.get_map("map"); + map.insert("seed", "value").unwrap(); + let tree = src.get_tree("tree"); + let root = tree.create(TreeParentId::Root).unwrap(); + tree.get_meta(root).unwrap().insert("name", "root").unwrap(); + + let first_vv = src.oplog_vv(); + let first_json = src + .export_json_updates(&Default::default(), &first_vv, false) + .unwrap(); + + let mut text_pos = text.len_unicode(); + for i in 0..64 { + let chunk = format!("chunk-{i};"); + text.insert_unicode(text_pos, &chunk).unwrap(); + text_pos += chunk.chars().count(); + } + for i in 0..32 { + list.push(format!("after-{i}")).unwrap(); + let key = format!("after-{i}"); + map.insert(&key, format!("value-{i}")).unwrap(); + } + let child = tree.create(TreeParentId::Node(root)).unwrap(); + tree.get_meta(child) + .unwrap() + .insert("name", "child") + .unwrap(); + + let second_json = src + .export_json_updates(&first_vv, &src.oplog_vv(), false) + .unwrap(); + + let dst = LoroDoc::new(); + dst.import_json_updates(first_json).unwrap(); + let vv_before_import = dst.oplog_vv(); + let frontiers_before_import = dst.oplog_frontiers(); + let state_before_import = dst.get_deep_value(); + + for _ in 0..2 { + crate::state::fail_next_import_state_apply_for_test(); + let err = dst.import_json_updates(second_json.clone()).unwrap_err(); + assert!(err.to_string().contains("state apply failpoint")); + assert_eq!(dst.oplog_vv(), vv_before_import); + assert_eq!(dst.oplog_frontiers(), frontiers_before_import); + assert_eq!(dst.get_deep_value(), state_before_import); + } + + dst.import_json_updates(second_json).unwrap(); + assert_eq!(dst.oplog_vv(), src.oplog_vv()); + assert_eq!(dst.oplog_frontiers(), src.oplog_frontiers()); + assert_eq!(dst.get_deep_value(), src.get_deep_value()); + } + + #[test] + fn malformed_later_import_json_update_rolls_back_after_valid_prefix_enters_oplog() { + let peer = 13; + let (src, good_json) = make_json_list_update_with_four_ops(peer); + let mut bad_json = good_json.clone(); + move_last_list_insert_far_out_of_bounds(&mut bad_json); + + let good_dst = LoroDoc::new(); + good_dst.import_json_updates(good_json.clone()).unwrap(); + assert_eq!(good_dst.get_deep_value(), src.get_deep_value()); + + let last_op_counter = good_json.changes[0].ops.last().unwrap().counter; + let prefix_vv = VersionVector::from_iter([(peer, last_op_counter)]); + let prefix_json = src + .export_json_updates(&Default::default(), &prefix_vv, false) + .unwrap(); + assert_eq!( + prefix_json.changes[0].ops.len(), + good_json.changes[0].ops.len() - 1 + ); + let good_suffix_json = src + .export_json_updates(&prefix_vv, &src.oplog_vv(), false) + .unwrap(); + assert_eq!(good_suffix_json.changes[0].ops.len(), 1); + let mut bad_suffix_json = good_suffix_json.clone(); + move_last_list_insert_far_out_of_bounds(&mut bad_suffix_json); + + let prefix_dst = LoroDoc::new(); + prefix_dst.import_json_updates(prefix_json.clone()).unwrap(); + let vv_before_bad_suffix = prefix_dst.oplog_vv(); + let frontiers_before_bad_suffix = prefix_dst.oplog_frontiers(); + let state_before_bad_suffix = prefix_dst.get_deep_value(); + + let bad_suffix_json = serde_json::to_string(&bad_suffix_json).unwrap(); + let err = prefix_dst + .import_json_updates(&bad_suffix_json) + .unwrap_err(); + assert!( + err.to_string().contains("list diff"), + "expected state list bounds validation, got {err:?}" + ); + assert_eq!(prefix_dst.oplog_vv(), vv_before_bad_suffix); + assert_eq!(prefix_dst.oplog_frontiers(), frontiers_before_bad_suffix); + assert_eq!(prefix_dst.get_deep_value(), state_before_bad_suffix); + + prefix_dst.import_json_updates(good_suffix_json).unwrap(); + assert_eq!(prefix_dst.get_deep_value(), src.get_deep_value()); + assert_eq!(prefix_dst.oplog_vv(), src.oplog_vv()); + + let dst = LoroDoc::new(); + let vv_before_import = dst.oplog_vv(); + let frontiers_before_import = dst.oplog_frontiers(); + let state_before_import = dst.get_deep_value(); + let bad_json = serde_json::to_string(&bad_json).unwrap(); + let err = dst.import_json_updates(&bad_json).unwrap_err(); + assert!( + err.to_string().contains("list diff"), + "expected state list bounds validation, got {err:?}" + ); + assert_eq!(dst.oplog_vv(), vv_before_import); + assert_eq!(dst.oplog_frontiers(), frontiers_before_import); + assert_eq!(dst.get_deep_value(), state_before_import); + assert!(dst.oplog().lock().is_empty()); + } + + #[test] + fn failed_import_restores_pending_changes_that_were_applied_during_import() { + let src = LoroDoc::new(); + src.set_peer_id(14).unwrap(); + let text = src.get_text("text"); + + let mut txn = src.txn().unwrap(); + text.insert_with_txn(&mut txn, 0, "a", PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + let first_update = src.export(ExportMode::all_updates()).unwrap(); + let first_vv = src.oplog_vv(); + + let mut txn = src.txn().unwrap(); + text.insert_with_txn(&mut txn, 1, "b", PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + let second_update = src.export(ExportMode::updates(&first_vv)).unwrap(); + + let dst = LoroDoc::new(); + let status = dst.import(&second_update).unwrap(); + assert!(status.success.is_empty()); + assert!(status.pending.is_some()); + let vv_before_dependency = dst.oplog_vv(); + let frontiers_before_dependency = dst.oplog_frontiers(); + let state_before_dependency = dst.get_deep_value(); + + crate::state::fail_next_import_state_apply_for_test(); + let err = dst.import(&first_update).unwrap_err(); + assert!(err.to_string().contains("state apply failpoint")); + assert_eq!(dst.oplog_vv(), vv_before_dependency); + assert_eq!(dst.oplog_frontiers(), frontiers_before_dependency); + assert_eq!(dst.get_deep_value(), state_before_dependency); + + dst.import(&first_update).unwrap(); + assert_eq!(dst.oplog_vv(), src.oplog_vv()); + assert_eq!(dst.oplog_frontiers(), src.oplog_frontiers()); + assert_eq!(dst.get_deep_value(), src.get_deep_value()); + } + + #[test] + fn failed_import_json_updates_does_not_emit_or_leave_events() { + let (src, good_json) = make_json_list_update_with_four_ops(15); + let mut bad_json = good_json.clone(); + move_last_list_insert_far_out_of_bounds(&mut bad_json); + + let dst = LoroDoc::new(); + let event_count = Arc::new(AtomicUsize::new(0)); + let event_count_cloned = event_count.clone(); + let _sub = dst.subscribe_root(Arc::new(move |_| { + event_count_cloned.fetch_add(1, Ordering::SeqCst); + })); + + let bad_json = serde_json::to_string(&bad_json).unwrap(); + let err = dst.import_json_updates(&bad_json).unwrap_err(); + assert!( + err.to_string().contains("list diff"), + "expected state list bounds validation, got {err:?}" + ); + assert_eq!(event_count.load(Ordering::SeqCst), 0); + assert!(dst.drop_pending_events().is_empty()); + assert!(dst.oplog().lock().is_empty()); + + dst.import_json_updates(good_json).unwrap(); + assert_eq!(event_count.load(Ordering::SeqCst), 1); + assert_eq!(dst.get_deep_value(), src.get_deep_value()); + } + + #[test] + fn test_checkout() { + let loro = LoroDoc::new(); + loro.set_peer_id(1).unwrap(); + let text = loro.get_text("text"); + let map = loro.get_map("map"); + let list = loro.get_list("list"); + let mut txn = loro.txn().unwrap(); + for i in 0..10 { + map.insert_with_txn(&mut txn, "key", i.into()).unwrap(); + text.insert_with_txn(&mut txn, 0, &i.to_string(), PosType::Unicode) + .unwrap(); + list.insert_with_txn(&mut txn, 0, i.into()).unwrap(); + } + txn.commit().unwrap(); + let b = LoroDoc::new(); + b.import(&loro.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + loro.checkout(&Frontiers::default()).unwrap(); + { + let json = &loro.get_deep_value(); + assert_eq!( + json.to_json_value(), + serde_json::json!({"text":"","list":[],"map":{}}) + ); + } + + b.checkout(&ID::new(1, 2).into()).unwrap(); + { + let json = &b.get_deep_value(); + assert_eq!( + json.to_json_value(), + serde_json::json!({"text":"0","list":[0],"map":{"key":0}}) + ); + } + + loro.checkout(&ID::new(1, 3).into()).unwrap(); + { + let json = &loro.get_deep_value(); + assert_eq!( + json.to_json_value(), + serde_json::json!({"text":"0","list":[0],"map":{"key":1}}) + ); + } + + b.checkout(&ID::new(1, 29).into()).unwrap(); + { + let json = &b.get_deep_value(); + assert_eq!( + json.to_json_value(), + serde_json::json!({"text":"9876543210","list":[9,8,7,6,5,4,3,2,1,0],"map":{"key":9}}) + ); + } + } + + #[test] + fn import_batch_err_181() { + let a = LoroDoc::new_auto_commit(); + let update_a = a.export(ExportMode::Snapshot); + let b = LoroDoc::new_auto_commit(); + b.import_batch(&[update_a.unwrap()]).unwrap(); + b.get_text("text") + .insert(0, "hello", PosType::Unicode) + .unwrap(); + b.commit_then_renew(); + let oplog = b.oplog().lock(); + drop(oplog); + b.export(ExportMode::all_updates()).unwrap(); + } + + #[test] + fn poisoned_mutex_keeps_follow_up_operations_failed() { + let doc = LoroDoc::new(); + let oplog = doc.oplog.clone(); + let _ = std::panic::catch_unwind(AssertUnwindSafe(|| { + let _guard = oplog.lock(); + panic!("poison oplog"); + })); + + let err = std::panic::catch_unwind(AssertUnwindSafe(|| doc.oplog_vv())) + .expect_err("poisoned lock should continue to fail fast"); + let msg = if let Some(msg) = err.downcast_ref::<&str>() { + (*msg).to_string() + } else if let Some(msg) = err.downcast_ref::<String>() { + msg.clone() + } else { + String::new() + }; + assert!(msg.contains("poisoned LoroMutex"), "{msg}"); + } + + #[test] + fn repeated_independent_scalar_root_imports_scan_history_once() { + let base = LoroDoc::new_auto_commit(); + base.set_peer_id(1).unwrap(); + for i in 0..64 { + base.get_map("existing") + .insert(&format!("key-{i}"), i) + .unwrap(); + base.commit_then_renew(); + } + + let target = LoroDoc::new(); + target + .import(&base.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + assert!(!target.has_history_cache()); + + for i in 0_u64..8 { + let remote = LoroDoc::new_auto_commit(); + remote.set_peer_id(2 + i).unwrap(); + remote + .get_map(format!("isolated-{i}")) + .insert("value", i as i32) + .unwrap(); + let update = remote.export(ExportMode::all_updates()).unwrap(); + target.import(&update).unwrap(); + assert_eq!( + target.get_map(format!("isolated-{i}")).get("value"), + Some((i as i32).into()) + ); + } + + assert!(!target.has_history_cache()); + assert_eq!( + target + .oplog + .lock() + .change_store() + .root_history_scan_count_for_test(), + 1 + ); + } + + #[test] + fn independent_fast_path_rejects_root_present_only_in_snapshot_state() { + fn snapshot_sections(doc: &LoroDoc) -> crate::encoding::fast_snapshot::Snapshot { + let (_, txn_guard) = doc.implicit_commit_then_stop(); + drop(txn_guard); + crate::encoding::fast_snapshot::encode_snapshot_inner(doc).unwrap() + } + + let base = LoroDoc::new_auto_commit(); + base.set_peer_id(1).unwrap(); + base.get_map("existing").insert("value", "base").unwrap(); + let base_sections = snapshot_sections(&base); + + // The donor's value must lose the register comparison against the real + // ops below (same lamport, lower peer), so both the general path and a + // wrongly-taken fast path would end with "winner"; the fast-path + // counter is what proves the rejection. + let state_donor = LoroDoc::new_auto_commit(); + state_donor.set_peer_id(0).unwrap(); + state_donor + .get_map("isolated") + .insert("value", "stale") + .unwrap(); + let donor_sections = snapshot_sections(&state_donor); + + let target = LoroDoc::new(); + crate::encoding::fast_snapshot::decode_snapshot_inner( + crate::encoding::fast_snapshot::Snapshot { + oplog_bytes: base_sections.oplog_bytes, + state_bytes: donor_sections.state_bytes, + shallow_root_state_bytes: Bytes::new(), + }, + &target, + Default::default(), + ) + .unwrap(); + assert!(!target.has_history_cache()); + + let left = LoroDoc::new_auto_commit(); + left.set_peer_id(2).unwrap(); + left.get_map("isolated").insert("value", "left").unwrap(); + let right = LoroDoc::new_auto_commit(); + right.set_peer_id(3).unwrap(); + right.get_map("isolated").insert("value", "winner").unwrap(); + let aggregate = LoroDoc::new(); + aggregate + .import(&left.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + aggregate + .import(&right.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + + let hits = super::isolated_fast_path_hits_for_test(); + target + .import(&aggregate.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + + assert_eq!( + target.get_map("isolated").get("value"), + Some("winner".into()) + ); + assert_eq!(super::isolated_fast_path_hits_for_test(), hits); + } + + #[test] + fn independent_scalar_root_import_rolls_back_after_state_failure() { + let base = LoroDoc::new_auto_commit(); + base.set_peer_id(1).unwrap(); + base.get_map("existing").insert("value", "base").unwrap(); + + let target = LoroDoc::new(); + target + .import(&base.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + let vv_before = target.oplog_vv(); + let state_before = target.get_deep_value(); + + let remote = LoroDoc::new_auto_commit(); + remote.set_peer_id(2).unwrap(); + remote.get_map("isolated").insert("value", 7).unwrap(); + let update = remote.export(ExportMode::all_updates()).unwrap(); + + crate::state::fail_next_import_state_apply_for_test(); + let err = target.import(&update).unwrap_err(); + assert!(err.to_string().contains("state apply failpoint")); + assert_eq!(target.oplog_vv(), vv_before); + assert_eq!(target.get_deep_value(), state_before); + assert!(!target.has_history_cache()); + + target.import(&update).unwrap(); + assert_eq!(target.get_map("isolated").get("value"), Some(7.into())); + } + + #[test] + fn independent_fast_path_rejects_root_name_seen_in_history() { + let base = LoroDoc::new_auto_commit(); + base.set_peer_id(1).unwrap(); + base.get_map("shared").insert("value", "base").unwrap(); + + let target = LoroDoc::new(); + target + .import(&base.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + assert!(!target.has_history_cache()); + + let remote = LoroDoc::new_auto_commit(); + remote.set_peer_id(999).unwrap(); + remote.get_map("shared").insert("value", "remote").unwrap(); + let hits = super::isolated_fast_path_hits_for_test(); + target + .import(&remote.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + + assert_eq!(target.get_map("shared").get("value"), Some("remote".into())); + assert_eq!(super::isolated_fast_path_hits_for_test(), hits); + } + + #[test] + fn independent_fast_path_rejects_deleted_root_name() { + let base = LoroDoc::new_auto_commit(); + base.set_peer_id(1).unwrap(); + let root_id = ContainerID::new_root("deleted", ContainerType::Map); + base.get_map("deleted").insert("value", "base").unwrap(); + base.delete_root_container(root_id); + + let target = LoroDoc::new(); + target + .import(&base.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + assert!(!target.has_history_cache()); + + let remote = LoroDoc::new_auto_commit(); + remote.set_peer_id(2).unwrap(); + remote.get_map("deleted").insert("value", "remote").unwrap(); + let hits = super::isolated_fast_path_hits_for_test(); + target + .import(&remote.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + + assert_eq!(super::isolated_fast_path_hits_for_test(), hits); + // The root's clearing ops outrank the remote write, so the map stays + // empty; `deleted_root_containers` only affects root visibility, so + // compare the container value with a doc that saw the other order. + let reference = LoroDoc::new(); + reference + .import(&remote.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + reference + .import(&base.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + use crate::handler::HandlerTrait; + assert_eq!( + target.get_map("deleted").get_deep_value(), + reference.get_map("deleted").get_deep_value() + ); + assert!(target.get_map("deleted").is_empty()); + } +} + +// Helpers of `LoroDoc::check_apply_diff_creates_no_unknown_container` + +fn resolve_container_remap( + mut id: ContainerID, + container_remap: &FxHashMap<ContainerID, ContainerID>, +) -> (ContainerID, bool) { + let mut remapped = false; + while let Some(rid) = container_remap.get(&id) { + remapped = true; + id = rid.clone(); + } + (id, remapped) +} + +fn diff_value_container_id(v: &ValueOrHandler) -> Option<ContainerID> { + match v { + ValueOrHandler::Value(LoroValue::Container(id)) => Some(id.clone()), + ValueOrHandler::Handler(h) => Some(h.id()), + ValueOrHandler::Value(_) => None, + } +} + +fn inserted_container_ids( + delta: &crate::event::ListDiff, +) -> impl Iterator<Item = ContainerID> + '_ { + delta + .iter() + .flat_map(|item| match item { + loro_delta::DeltaItem::Replace { value, .. } => { + Some(value.iter().filter_map(diff_value_container_id)) + } + loro_delta::DeltaItem::Retain { .. } => None, + }) + .flatten() +} + +fn diff_has_unknown_value(diff: &crate::event::Diff) -> bool { + match diff { + crate::event::Diff::Map(map) => map.updated.values().any(|v| { + v.value + .as_ref() + .and_then(diff_value_container_id) + .is_some_and(|c| c.is_unknown()) + }), + crate::event::Diff::List(delta) => inserted_container_ids(delta).any(|c| c.is_unknown()), + _ => false, + } +} + +/// See `LoroDoc::plan_full_state_batch`. +#[derive(Default)] +struct FullStatePlan { + /// Batch id -> how the loop applies that full-state entry + aligned: FxHashMap<ContainerID, PlannedAlignment>, + /// Targets the loop applies even when they are unreachable before the batch + always_applied: FxHashSet<ContainerID>, + /// Batch ids of mergeable children of containers this batch recreates. + /// They are new and empty when the loop reaches them. + fresh: FxHashSet<ContainerID>, +} + +struct PlannedAlignment { + /// The container the full state was aligned with + target: ContainerID, + /// `None` when there is nothing to do + edit: Option<crate::event::Diff>, + /// Children kept by the alignment, whose own entries are full states too + kept: FxHashSet<ContainerID>, +} diff --git a/vendor/loro-internal/src/macros.rs b/vendor/loro-internal/src/macros.rs new file mode 100644 index 0000000..1fbd90a --- /dev/null +++ b/vendor/loro-internal/src/macros.rs @@ -0,0 +1,98 @@ +/// ```no_run +/// use rustc_hash::FxHashMap; +/// use loro_internal::fx_map; +/// +/// let mut expected = FxHashMap::default(); +/// expected.insert("test".to_string(), "test".to_string()); +/// expected.insert("test2".to_string(), "test2".to_string()); +/// let actual = fx_map!("test".into() => "test".into(), "test2".into() => "test2".into()); +/// assert_eq!(expected, actual); +/// ``` +#[macro_export] +macro_rules! fx_map { + ($($key:expr => $value:expr),*) => { + { + let mut m = rustc_hash::FxHashMap::default(); + $( + m.insert($key, $value); + )* + m + } + }; +} + +/// ```no_run +/// use loro_internal::vv; +/// +/// let v = vv!(1 => 2, 2 => 3); +/// assert_eq!(v.get(&1), Some(&2)); +/// assert_eq!(v.get(&2), Some(&3)); +/// ``` +#[macro_export] +macro_rules! vv { + ($($key:expr => $value:expr),*) => { + { + let mut m = $crate::version::VersionVector::default(); + $( + m.insert($key, $value); + )* + m + } + }; +} + +#[macro_export] +macro_rules! array_mut_ref { + ($arr:expr, [$a0:expr, $a1:expr]) => {{ + #[inline] + fn borrow_mut_ref<T>(arr: &mut [T], a0: usize, a1: usize) -> (&mut T, &mut T) { + assert!(a0 != a1); + // SAFETY: this is safe because we know a0 != a1 + unsafe { + ( + &mut *(&mut arr[a0] as *mut _), + &mut *(&mut arr[a1] as *mut _), + ) + } + } + + borrow_mut_ref($arr, $a0, $a1) + }}; + ($arr:expr, [$a0:expr, $a1:expr, $a2:expr]) => {{ + #[inline] + fn borrow_mut_ref<T>( + arr: &mut [T], + a0: usize, + a1: usize, + a2: usize, + ) -> (&mut T, &mut T, &mut T) { + assert!(a0 != a1 && a1 != a2 && a0 != a2); + // SAFETY: this is safe because we know there are not multiple mutable references to the same element + unsafe { + ( + &mut *(&mut arr[a0] as *mut _), + &mut *(&mut arr[a1] as *mut _), + &mut *(&mut arr[a2] as *mut _), + ) + } + } + + borrow_mut_ref($arr, $a0, $a1, $a2) + }}; +} + +#[cfg(test)] +mod test { + + #[test] + fn test_macro() { + let mut arr = vec![100, 101, 102, 103]; + let (a, b, _c) = array_mut_ref!(&mut arr, [1, 2, 3]); + assert_eq!(*a, 101); + assert_eq!(*b, 102); + *a = 50; + *b = 51; + assert!(arr[1] == 50); + assert!(arr[2] == 51); + } +} diff --git a/vendor/loro-internal/src/op.rs b/vendor/loro-internal/src/op.rs new file mode 100644 index 0000000..a8971d1 --- /dev/null +++ b/vendor/loro-internal/src/op.rs @@ -0,0 +1,749 @@ +use crate::{ + change::{Change, Lamport, Timestamp}, + container::{idx::ContainerIdx, ContainerID}, + estimated_size::EstimatedSize, + id::{Counter, PeerID, ID}, + oplog::BlockChangeRef, + span::{HasCounter, HasId, HasLamport}, +}; +use crate::{delta::DeltaValue, LoroValue}; +use either::Either; +use enum_as_inner::EnumAsInner; +use loro_common::{CompactIdLp, ContainerType, CounterSpan, IdFull, IdLp, IdSpan}; +use rle::{HasIndex, HasLength, Mergable, Sliceable}; +use serde::{Deserialize, Serialize}; +use std::{borrow::Cow, sync::Arc}; + +mod content; +pub use content::*; + +/// Operation is a unit of change. +/// +/// A Op may have multiple atomic operations, since Op can be merged. +#[derive(Debug, Clone)] +pub struct Op { + pub(crate) counter: Counter, + pub(crate) container: ContainerIdx, + pub(crate) content: InnerContent, +} + +impl EstimatedSize for Op { + fn estimate_storage_size(&self) -> usize { + // TODO: use benchmark to get the optimal estimated size for each container type + self.content + .estimate_storage_size(self.container.get_type()) + } +} + +#[derive(Debug, Clone)] +pub(crate) struct OpWithId { + pub peer: PeerID, + pub op: Op, +} + +impl OpWithId { + #[allow(unused)] + pub fn id_span(&self) -> IdSpan { + IdSpan::new( + self.peer, + self.op.counter, + self.op.counter + self.op.atom_len() as Counter, + ) + } +} + +#[derive(Debug, Clone, PartialEq)] +#[cfg_attr(feature = "wasm", derive(Serialize, Deserialize))] +pub struct RemoteOp<'a> { + pub(crate) counter: Counter, + pub(crate) container: ContainerID, + pub(crate) content: RawOpContent<'a>, +} + +/// This is used to propagate messages between inner module. +/// It's a temporary struct, and will be converted to Op when it's persisted. +#[derive(Debug, Clone)] +pub struct RawOp<'a> { + pub id: ID, + pub lamport: Lamport, + pub container: ContainerIdx, + pub content: RawOpContent<'a>, +} + +impl RawOp<'_> { + pub(crate) fn id_full(&self) -> loro_common::IdFull { + IdFull::new(self.id.peer, self.id.counter, self.lamport) + } + + pub(crate) fn idlp(&self) -> loro_common::IdLp { + IdLp::new(self.id.peer, self.lamport) + } +} + +/// RichOp includes lamport and timestamp info, which is used for conflict resolution. +#[derive(Debug, Clone)] +pub struct RichOp<'a> { + op: Cow<'a, Op>, + pub peer: PeerID, + lamport: Lamport, + pub timestamp: Timestamp, + pub start: usize, + pub end: usize, +} + +impl Op { + #[inline] + #[allow(unused)] + pub(crate) fn new(id: ID, content: InnerContent, container: ContainerIdx) -> Self { + Op { + counter: id.counter, + content, + container, + } + } + + /// If the estimated storage size of the content is greater than the given size, + /// return the length of the content that makes the estimated storage size equal to the given size. + /// Otherwise, return None. + pub(crate) fn check_whether_slice_content_to_fit_in_size(&self, size: usize) -> Option<usize> { + if self.estimate_storage_size() <= size { + return None; + } + + match &self.content { + InnerContent::List(l) => match l { + crate::container::list::list_op::InnerListOp::Insert { .. } => { + if matches!(self.container.get_type(), ContainerType::Text) { + Some(size.min(self.atom_len())) + } else { + Some((size / 4).min(self.atom_len())) + } + } + crate::container::list::list_op::InnerListOp::InsertText { .. } => { + Some(size.min(self.atom_len())) + } + _ => unreachable!(), + }, + _ => unreachable!(), + } + } +} + +impl RemoteOp<'_> { + #[allow(unused)] + pub(crate) fn into_static(self) -> RemoteOp<'static> { + RemoteOp { + counter: self.counter, + container: self.container, + content: self.content.to_static(), + } + } +} + +impl Mergable for Op { + fn is_mergable(&self, other: &Self, cfg: &()) -> bool { + self.counter + self.content_len() as Counter == other.counter + && self.container == other.container + && self.content.is_mergable(&other.content, cfg) + } + + fn merge(&mut self, other: &Self, cfg: &()) { + self.content.merge(&other.content, cfg) + } +} + +impl HasLength for Op { + fn content_len(&self) -> usize { + self.content.content_len() + } +} + +impl Sliceable for Op { + fn slice(&self, from: usize, to: usize) -> Self { + assert!(to > from, "{to} should be greater than {from}"); + assert!(to <= self.atom_len()); + let content: InnerContent = self.content.slice(from, to); + Op { + counter: (self.counter + from as Counter), + content, + container: self.container, + } + } +} + +impl Mergable for RemoteOp<'_> { + fn is_mergable(&self, _other: &Self, _cfg: &()) -> bool { + // don't merge remote op, because it's already merged. + false + } + + fn merge(&mut self, _other: &Self, _: &()) { + unreachable!() + } +} + +impl HasLength for RemoteOp<'_> { + fn content_len(&self) -> usize { + self.content.atom_len() + } +} + +impl HasIndex for Op { + type Int = Counter; + + fn get_start_index(&self) -> Self::Int { + self.counter + } +} + +impl HasIndex for RemoteOp<'_> { + type Int = Counter; + + fn get_start_index(&self) -> Self::Int { + self.counter + } +} + +impl HasCounter for Op { + fn ctr_start(&self) -> Counter { + self.counter + } +} + +impl HasCounter for RemoteOp<'_> { + fn ctr_start(&self) -> Counter { + self.counter + } +} + +impl HasId for RichOp<'_> { + fn id_start(&self) -> ID { + ID { + peer: self.peer, + counter: self.op.counter + self.start as Counter, + } + } +} + +impl HasLength for RichOp<'_> { + fn content_len(&self) -> usize { + self.end - self.start + } +} + +impl HasLamport for RichOp<'_> { + fn lamport(&self) -> Lamport { + self.lamport + self.start as Lamport + } +} + +impl<'a> RichOp<'a> { + pub fn new_by_change(change: &Change<Op>, op: &'a Op) -> Self { + let diff = op.counter - change.id.counter; + RichOp { + op: Cow::Borrowed(op), + peer: change.id.peer, + lamport: change.lamport + diff as Lamport, + timestamp: change.timestamp, + start: 0, + end: op.atom_len(), + } + } + + /// we want the overlap part of the op and change[start..end] + /// + /// op is contained in the change, but it's not necessary overlap with change[start..end] + pub fn new_by_slice_on_change(change: &Change<Op>, start: i32, end: i32, op: &'a Op) -> Self { + debug_assert!(end > start); + let op_index_in_change = op.counter - change.id.counter; + let op_slice_start = (start - op_index_in_change).clamp(0, op.atom_len() as i32); + let op_slice_end = (end - op_index_in_change).clamp(0, op.atom_len() as i32); + RichOp { + op: Cow::Borrowed(op), + peer: change.id.peer, + lamport: change.lamport + op_index_in_change as Lamport, + timestamp: change.timestamp, + start: op_slice_start as usize, + end: op_slice_end as usize, + } + } + + pub fn new_by_cnt_range(change: &Change<Op>, span: CounterSpan, op: &'a Op) -> Option<Self> { + let op_index_in_change = op.counter - change.id.counter; + let op_slice_start = (span.start - op.counter).clamp(0, op.atom_len() as i32); + let op_slice_end = (span.end - op.counter).clamp(0, op.atom_len() as i32); + if op_slice_start == op_slice_end { + return None; + } + Some(RichOp { + op: Cow::Borrowed(op), + peer: change.id.peer, + lamport: change.lamport + op_index_in_change as Lamport, + timestamp: change.timestamp, + start: op_slice_start as usize, + end: op_slice_end as usize, + }) + } + + pub(crate) fn new_iter_by_cnt_range( + change: BlockChangeRef, + span: CounterSpan, + ) -> RichOpBlockIter { + // Start at the first op that reaches into `span`. + let op_index = change + .ops + .vec() + .partition_point(|op| op.counter + op.atom_len() as Counter <= span.start); + RichOpBlockIter { + change, + span, + op_index, + } + } + + pub fn op(&self) -> Cow<'_, Op> { + if self.start == 0 && self.end == self.op.content_len() { + self.op.clone() + } else { + Cow::Owned(self.op.slice(self.start, self.end)) + } + } + + pub fn raw_op(&self) -> &Op { + &self.op + } + + pub fn client_id(&self) -> u64 { + self.peer + } + + pub fn container(&self) -> ContainerIdx { + self.op.container + } + + pub fn timestamp(&self) -> i64 { + self.timestamp + } + + pub fn start(&self) -> usize { + self.start + } + + pub fn end(&self) -> usize { + self.end + } + + pub fn counter(&self) -> Counter { + self.op.counter + self.start as Counter + } + + #[allow(unused)] + pub(crate) fn id(&self) -> ID { + ID { + peer: self.peer, + counter: self.op.counter + self.start as Counter, + } + } + + pub(crate) fn id_full(&self) -> IdFull { + IdFull::new( + self.peer, + self.op.counter + self.start as Counter, + self.lamport + self.start as Lamport, + ) + } + + pub fn idlp(&self) -> IdLp { + IdLp { + lamport: self.lamport + self.start as Lamport, + peer: self.peer, + } + } +} + +pub(crate) struct RichOpBlockIter { + change: BlockChangeRef, + span: CounterSpan, + op_index: usize, +} + +impl Iterator for RichOpBlockIter { + type Item = RichOp<'static>; + + fn next(&mut self) -> Option<Self::Item> { + // Clone only the ops that are returned: cloning a list insert clones its + // values' handle. + let (op, op_slice_start, op_slice_end) = loop { + let op = self.change.ops.get(self.op_index)?; + self.op_index += 1; + let op_slice_start = (self.span.start - op.counter).clamp(0, op.atom_len() as i32); + let op_slice_end = (self.span.end - op.counter).clamp(0, op.atom_len() as i32); + if op_slice_start != op_slice_end { + break (op.clone(), op_slice_start, op_slice_end); + } + }; + let op_offset_in_change = op.counter - self.change.id.counter; + + Some(RichOp { + op: Cow::Owned(op), + peer: self.change.id.peer, + lamport: self.change.lamport + op_offset_in_change as Lamport, + timestamp: self.change.timestamp, + start: op_slice_start as usize, + end: op_slice_end as usize, + }) + } +} + +// Note: It will be encoded into binary format, so the order of its fields should not be changed. +#[derive(PartialEq, Debug, EnumAsInner, Clone, Serialize, Deserialize)] +pub enum ListSlice<'a> { + RawData(Cow<'a, [LoroValue]>), + RawStr { + str: Cow<'a, str>, + unicode_len: usize, + }, +} + +impl<'a> ListSlice<'a> { + pub fn from_borrowed_str(str: &'a str) -> Self { + Self::RawStr { + str: Cow::Borrowed(str), + unicode_len: str.chars().count(), + } + } +} + +/// The values of a list insert op. +/// +/// The op owns them. They used to be a range in the doc-wide values arena, +/// which never frees, so every parse of a change block appended its values to it +/// again (`context/text-arena-growth.md`). +#[derive(Clone)] +pub struct ValueSlice(Repr); + +#[derive(Clone)] +enum Repr { + /// A single value, as most local inserts have. It needs no allocation. + One(LoroValue), + Shared { + values: Arc<Vec<LoroValue>>, + start: u32, + end: u32, + }, +} + +impl ValueSlice { + pub fn new(mut values: Vec<LoroValue>) -> Self { + if values.len() == 1 { + return Self::one(values.pop().unwrap()); + } + + let end = u32::try_from(values.len()).expect("too many values in one list op"); + Self(Repr::Shared { + values: Arc::new(values), + start: 0, + end, + }) + } + + pub(crate) fn one(value: LoroValue) -> Self { + Self(Repr::One(value)) + } + + /// A slice of `buffer` that is not filled yet. See + /// `DecodedBlockBuffers::push_values`. + pub(crate) fn pending(buffer: &Arc<Vec<LoroValue>>, range: std::ops::Range<usize>) -> Self { + let end = u32::try_from(range.end).expect("too many values in one change block"); + Self(Repr::Shared { + values: buffer.clone(), + start: range.start as u32, + end, + }) + } + + /// Points this slice at `to` if it points at `from`. + pub(crate) fn replace_buffer(&mut self, from: &Arc<Vec<LoroValue>>, to: &Arc<Vec<LoroValue>>) { + if let Repr::Shared { values, .. } = &mut self.0 { + if Arc::ptr_eq(values, from) { + *values = to.clone(); + } + } + } + + #[inline] + pub fn as_slice(&self) -> &[LoroValue] { + match &self.0 { + Repr::One(value) => std::slice::from_ref(value), + Repr::Shared { values, start, end } => &values[*start as usize..*end as usize], + } + } + + #[inline] + pub fn len(&self) -> usize { + match &self.0 { + Repr::One(_) => 1, + Repr::Shared { start, end, .. } => (end - start) as usize, + } + } + + #[inline] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Whether `other` follows this slice in the same buffer. + fn is_followed_by(&self, other: &Self) -> bool { + matches!( + (&self.0, &other.0), + ( + Repr::Shared { values, end, .. }, + Repr::Shared { values: other_values, start, .. }, + ) if Arc::ptr_eq(values, other_values) && end == start + ) + } + + /// Extends this slice by `other` if it follows this slice in the same buffer. + pub(crate) fn extend_if_adjacent(&mut self, other: &Self) -> bool { + if !self.is_followed_by(other) { + return false; + } + if let (Repr::Shared { end, .. }, Repr::Shared { end: other_end, .. }) = + (&mut self.0, &other.0) + { + *end = *other_end; + } + true + } + + /// Whether this slice ends its buffer and is the buffer's only owner. + fn can_append(&self) -> bool { + match &self.0 { + Repr::One(_) => false, + Repr::Shared { values, end, .. } => { + *end as usize == values.len() + && Arc::strong_count(values) == 1 + && Arc::weak_count(values) == 0 + } + } + } +} + +impl PartialEq for ValueSlice { + fn eq(&self, other: &Self) -> bool { + self.as_slice() == other.as_slice() + } +} + +impl Eq for ValueSlice {} + +impl std::fmt::Debug for ValueSlice { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.0 { + // A slice from `DecodedBlockBuffers::push_values` before `finish`: + // its values are not decoded yet. Decoding formats ops in errors + // (`check_positions`), so this must not read them. + Repr::Shared { values, start, end } if *end as usize > values.len() => f + .debug_struct("ValueSlice") + .field("pending", &(*start..*end)) + .finish(), + _ => f.debug_tuple("ValueSlice").field(&self.as_slice()).finish(), + } + } +} + +impl HasLength for ValueSlice { + fn content_len(&self) -> usize { + self.len() + } +} + +impl Sliceable for ValueSlice { + fn slice(&self, from: usize, to: usize) -> Self { + assert!(from <= to && to <= self.len()); + match &self.0 { + Repr::One(_) if from == 0 && to == 1 => self.clone(), + Repr::One(_) => Self::new(Vec::new()), + Repr::Shared { values, start, .. } => Self(Repr::Shared { + values: values.clone(), + start: start + from as u32, + end: start + to as u32, + }), + } + } +} + +impl Mergable for ValueSlice { + fn merge(&mut self, other: &Self, _: &()) { + if self.extend_if_adjacent(other) { + return; + } + + if self.can_append() { + let Repr::Shared { values, end, .. } = &mut self.0 else { + unreachable!() + }; + let values = Arc::get_mut(values).unwrap(); + values.extend_from_slice(other.as_slice()); + *end = u32::try_from(values.len()).expect("too many values in one list op"); + return; + } + + // Copy only this slice, not the whole shared buffer. The merged slice + // owns its buffer, so later merges append to it. + let mut values = Vec::with_capacity((self.len() + other.len()).max(4)); + values.extend_from_slice(self.as_slice()); + values.extend_from_slice(other.as_slice()); + *self = Self::new(values); + } + + /// Mergeable when the merge never copies this slice's shared buffer: + /// `other` follows it in one buffer (nothing is copied), this slice owns + /// the end of its buffer (`other` is appended to it), or this slice is a + /// single value (it and `other` are copied into a new buffer, which later + /// merges append to). Each value is copied once per op it is merged into. + fn is_mergable(&self, other: &Self, _conf: &()) -> bool + where + Self: Sized, + { + self.is_followed_by(other) || self.can_append() || matches!(self.0, Repr::One(_)) + } +} + +impl ListSlice<'_> { + pub fn to_static(&self) -> ListSlice<'static> { + match self { + ListSlice::RawData(x) => ListSlice::RawData(Cow::Owned(x.to_vec())), + ListSlice::RawStr { str, unicode_len } => ListSlice::RawStr { + str: Cow::Owned(str.to_string()), + unicode_len: *unicode_len, + }, + } + } +} + +impl HasLength for ListSlice<'_> { + fn content_len(&self) -> usize { + match self { + ListSlice::RawStr { unicode_len, .. } => *unicode_len, + ListSlice::RawData(x) => x.len(), + } + } +} + +impl Sliceable for ListSlice<'_> { + fn slice(&self, from: usize, to: usize) -> Self { + match self { + ListSlice::RawStr { + str, + unicode_len: _, + } => { + let ans = str.chars().skip(from).take(to - from).collect::<String>(); + ListSlice::RawStr { + str: Cow::Owned(ans), + unicode_len: to - from, + } + } + ListSlice::RawData(x) => match x { + Cow::Borrowed(x) => ListSlice::RawData(Cow::Borrowed(&x[from..to])), + Cow::Owned(x) => ListSlice::RawData(Cow::Owned(x[from..to].into())), + }, + } + } +} + +impl Mergable for ListSlice<'_> { + fn is_mergable(&self, _other: &Self, _: &()) -> bool { + false + } +} + +#[derive(Debug, Clone)] +pub struct SliceWithId { + pub values: Either<ValueSlice, LoroValue>, + /// This field is no-none when diff calculating movable list that need to handle_unknown + pub elem_id: Option<CompactIdLp>, + pub id: IdFull, +} + +impl DeltaValue for SliceWithId { + fn value_extend(&mut self, other: Self) -> Result<(), Self> { + if self.id.peer != other.id.peer { + return Err(other); + } + + if self.id.counter + self.length() as Counter != other.id.counter { + return Err(other); + } + + if self.id.lamport + self.length() as Lamport != other.id.lamport { + return Err(other); + } + + match (&mut self.values, &other.values) { + (Either::Left(left), Either::Left(right)) => { + if left.extend_if_adjacent(right) { + Ok(()) + } else { + Err(other) + } + } + _ => { + // Values in different buffers, or a ValueSlice and a LoroValue + Err(other) + } + } + } + + fn take(&mut self, target_len: usize) -> Self { + match &mut self.values { + Either::Left(range) => { + let ans = range.slice(0, target_len); + let this = range.slice(target_len, range.atom_len()); + *range = this; + let old_id = self.id; + self.id = self.id.inc(target_len as i32); + Self { + id: old_id, + values: Either::Left(ans), + elem_id: None, + } + } + Either::Right(_) => unimplemented!(), + } + } + + fn length(&self) -> usize { + match &self.values { + Either::Left(r) => r.atom_len(), + Either::Right(_) => 1, + } + } +} + +#[cfg(test)] +mod test { + use crate::LoroValue; + + use super::ListSlice; + + #[test] + fn fix_fields_order() { + let list_slice = vec![ + ListSlice::RawData(vec![LoroValue::Bool(true)].into()), + ListSlice::RawStr { + str: "".into(), + unicode_len: 0, + }, + ]; + let list_slice_buf = vec![2, 0, 1, 1, 1, 1, 0, 0]; + assert_eq!( + &postcard::to_allocvec(&list_slice).unwrap(), + &list_slice_buf + ); + assert_eq!( + postcard::from_bytes::<Vec<ListSlice>>(&list_slice_buf).unwrap(), + list_slice + ); + } +} diff --git a/vendor/loro-internal/src/op/content.rs b/vendor/loro-internal/src/op/content.rs new file mode 100644 index 0000000..f02a4bf --- /dev/null +++ b/vendor/loro-internal/src/op/content.rs @@ -0,0 +1,470 @@ +use std::sync::Arc; + +use enum_as_inner::EnumAsInner; +use loro_common::{ContainerID, ContainerType, LoroValue}; +use rle::{HasLength, Mergable, Sliceable}; +#[cfg(feature = "wasm")] +use serde::{Deserialize, Serialize}; + +use crate::{ + container::{ + list::list_op::{InnerListOp, ListOp}, + map::MapSet, + tree::tree_op::TreeOp, + }, + encoding::OwnedValue, +}; + +#[derive(EnumAsInner, Debug, Clone)] +pub enum InnerContent { + List(InnerListOp), + Map(MapSet), + Tree(Arc<TreeOp>), + // The future content should not use any encoded arena context. + Future(FutureInnerContent), +} + +impl InnerContent { + pub fn visit_created_children(&self, f: &mut dyn FnMut(&ContainerID)) { + match self { + InnerContent::List(l) => match l { + InnerListOp::Insert { slice, .. } => { + for v in slice.as_slice() { + if let LoroValue::Container(c) = v { + f(c); + } + } + } + InnerListOp::Set { value, .. } => { + if let LoroValue::Container(c) = value { + f(c); + } + } + + InnerListOp::Move { .. } => {} + InnerListOp::InsertText { .. } => {} + InnerListOp::Delete(_) => {} + InnerListOp::StyleStart { .. } => {} + InnerListOp::StyleEnd => {} + }, + crate::op::InnerContent::Map(m) => { + if let Some(LoroValue::Container(c)) = &m.value { + f(c); + } + } + crate::op::InnerContent::Tree(t) => { + if let TreeOp::Create { target, .. } = t.as_ref() { + let id = target.associated_meta_container(); + f(&id); + } + } + crate::op::InnerContent::Future(f) => match &f { + #[cfg(feature = "counter")] + crate::op::FutureInnerContent::Counter(_) => {} + crate::op::FutureInnerContent::Unknown { .. } => {} + }, + } + } +} + +impl InnerContent { + pub fn estimate_storage_size(&self, kind: ContainerType) -> usize { + match self { + InnerContent::List(l) => l.estimate_storage_size(kind), + InnerContent::Map(_) => 3, + InnerContent::Tree(_) => 8, + InnerContent::Future(f) => f.estimate_storage_size(), + } + } +} + +#[derive(EnumAsInner, Debug, Clone)] +pub enum FutureInnerContent { + #[cfg(feature = "counter")] + Counter(f64), + Unknown { + prop: i32, + value: Box<OwnedValue>, + }, +} +impl FutureInnerContent { + fn estimate_storage_size(&self) -> usize { + match self { + #[cfg(feature = "counter")] + FutureInnerContent::Counter(_) => 4, + FutureInnerContent::Unknown { .. } => 6, + } + } +} + +// Note: It will be encoded into binary format, so the order of its fields should not be changed. +#[derive(EnumAsInner, Debug, PartialEq)] +#[cfg_attr(feature = "wasm", derive(Serialize, Deserialize,))] +pub enum RawOpContent<'a> { + Map(MapSet), + List(ListOp<'a>), + Tree(Arc<TreeOp>), + #[cfg(feature = "counter")] + Counter(f64), + Unknown { + prop: i32, + value: OwnedValue, + }, +} + +impl Clone for RawOpContent<'_> { + fn clone(&self) -> Self { + match self { + Self::Map(arg0) => Self::Map(arg0.clone()), + Self::List(arg0) => Self::List(arg0.clone()), + Self::Tree(arg0) => Self::Tree(arg0.clone()), + #[cfg(feature = "counter")] + Self::Counter(x) => Self::Counter(*x), + Self::Unknown { prop, value } => Self::Unknown { + prop: *prop, + value: value.clone(), + }, + } + } +} + +impl RawOpContent<'_> { + pub fn to_static(&self) -> RawOpContent<'static> { + match self { + Self::Map(arg0) => RawOpContent::Map(arg0.clone()), + Self::List(arg0) => match arg0 { + ListOp::Insert { slice, pos } => RawOpContent::List(ListOp::Insert { + slice: slice.to_static(), + pos: *pos, + }), + ListOp::Delete(x) => RawOpContent::List(ListOp::Delete(*x)), + ListOp::StyleStart { + start, + end, + key, + value, + info, + } => RawOpContent::List(ListOp::StyleStart { + start: *start, + end: *end, + key: key.clone(), + value: value.clone(), + info: *info, + }), + ListOp::StyleEnd => RawOpContent::List(ListOp::StyleEnd), + ListOp::Move { + from, + to, + elem_id: from_id, + } => RawOpContent::List(ListOp::Move { + from: *from, + to: *to, + elem_id: *from_id, + }), + ListOp::Set { elem_id, value } => RawOpContent::List(ListOp::Set { + elem_id: *elem_id, + value: value.clone(), + }), + }, + Self::Tree(arg0) => RawOpContent::Tree(arg0.clone()), + #[cfg(feature = "counter")] + Self::Counter(x) => RawOpContent::Counter(*x), + Self::Unknown { prop, value } => RawOpContent::Unknown { + prop: *prop, + value: value.clone(), + }, + } + } +} + +impl HasLength for RawOpContent<'_> { + fn content_len(&self) -> usize { + match self { + RawOpContent::Map(x) => x.content_len(), + RawOpContent::List(x) => x.content_len(), + RawOpContent::Tree(x) => x.content_len(), + #[cfg(feature = "counter")] + RawOpContent::Counter(_) => 1, + RawOpContent::Unknown { .. } => 1, + } + } +} + +impl Mergable for RawOpContent<'_> { + fn is_mergable(&self, other: &Self, _conf: &()) -> bool + where + Self: Sized, + { + match (self, other) { + (RawOpContent::List(x), RawOpContent::List(y)) => x.is_mergable(y, &()), + (RawOpContent::Tree(x), RawOpContent::Tree(y)) => x.is_mergable(y, &()), + _ => false, + } + } + + fn merge(&mut self, _other: &Self, _conf: &()) + where + Self: Sized, + { + match self { + RawOpContent::List(x) => match _other { + RawOpContent::List(y) => x.merge(y, &()), + _ => unreachable!(), + }, + _ => unreachable!(), + } + } +} + +impl HasLength for InnerContent { + fn content_len(&self) -> usize { + match self { + InnerContent::List(list) => list.atom_len(), + InnerContent::Map(_) => 1, + InnerContent::Tree(_) => 1, + InnerContent::Future(_) => 1, + } + } +} + +impl Sliceable for InnerContent { + fn slice(&self, from: usize, to: usize) -> Self { + match self { + a @ InnerContent::Map(_) => { + assert!(from == 0 && to == 1); + a.clone() + } + a @ InnerContent::Tree(_) => { + assert!(from == 0 && to == 1); + a.clone() + } + InnerContent::List(x) => InnerContent::List(x.slice(from, to)), + InnerContent::Future(f) => { + assert!(from == 0 && to == 1); + InnerContent::Future(f.clone()) + } + } + } +} + +impl Mergable for InnerContent { + fn is_mergable(&self, other: &Self, _conf: &()) -> bool + where + Self: Sized, + { + match (self, other) { + (InnerContent::List(x), InnerContent::List(y)) => x.is_mergable(y, &()), + _ => false, + } + } + + fn merge(&mut self, _other: &Self, _conf: &()) + where + Self: Sized, + { + match self { + InnerContent::List(x) => match _other { + InnerContent::List(y) => x.merge(y, &()), + _ => unreachable!(), + }, + _ => unreachable!(), + } + } +} + +#[cfg(test)] +mod tests { + use std::{borrow::Cow, sync::Arc}; + + use fractional_index::FractionalIndex; + use loro_common::{ContainerID, ContainerType, TreeID}; + use rle::{HasLength, Mergable, Sliceable}; + + use super::*; + use crate::{ + container::{ + list::list_op::{DeleteSpanWithId, ListOp}, + map::MapSet, + tree::tree_op::TreeOp, + }, + op::{ListSlice, ValueSlice}, + InternalString, LoroValue, ID, + }; + + #[test] + fn raw_op_content_reports_lengths_and_static_content_without_borrowing() { + let raw_insert = RawOpContent::List(ListOp::Insert { + slice: ListSlice::RawData(Cow::Owned(vec![1_i64.into(), 2_i64.into()])), + pos: 3, + }); + assert_eq!(raw_insert.content_len(), 2); + match raw_insert.to_static() { + RawOpContent::List(ListOp::Insert { slice, pos }) => { + assert_eq!(pos, 3); + assert_eq!( + slice, + ListSlice::RawData(Cow::Owned(vec![1_i64.into(), 2_i64.into()])) + ); + } + other => panic!("expected list insert, got {other:?}"), + } + + let raw_map = RawOpContent::Map(MapSet { + key: InternalString::from("title"), + value: Some("draft".into()), + }); + assert_eq!(raw_map.content_len(), 1); + assert_eq!(raw_map.to_static(), raw_map); + + let raw_tree = RawOpContent::Tree(Arc::new(TreeOp::Delete { + target: TreeID::new(2, 9), + })); + assert_eq!(raw_tree.content_len(), 1); + assert_eq!(raw_tree.to_static(), raw_tree); + + let raw_unknown = RawOpContent::Unknown { + prop: 7, + value: OwnedValue::I64(11), + }; + assert_eq!(raw_unknown.content_len(), 1); + assert_eq!(raw_unknown.to_static(), raw_unknown); + + #[cfg(feature = "counter")] + { + let raw_counter = RawOpContent::Counter(1.25); + assert_eq!(raw_counter.content_len(), 1); + assert_eq!(raw_counter.to_static(), raw_counter); + } + } + + #[test] + fn raw_op_content_merges_only_mergeable_list_operations() { + let mut left = + RawOpContent::List(ListOp::Delete(DeleteSpanWithId::new(ID::new(1, 0), 0, 1))); + let right = RawOpContent::List(ListOp::Delete(DeleteSpanWithId::new(ID::new(1, 1), 0, 1))); + assert!(left.is_mergable(&right, &())); + left.merge(&right, &()); + assert_eq!(left.content_len(), 2); + + let map = RawOpContent::Map(MapSet { + key: InternalString::from("k"), + value: Some(1_i64.into()), + }); + assert!(!left.is_mergable(&map, &())); + } + + #[test] + fn inner_content_lengths_storage_estimates_slices_and_merges_follow_inner_ops() { + let mut left = InnerContent::List(InnerListOp::Insert { + slice: ValueSlice::new(vec![0_i64.into(), 1_i64.into()]), + pos: 0, + }); + let right = InnerContent::List(InnerListOp::Insert { + slice: ValueSlice::new(vec![2_i64.into(), 3_i64.into()]), + pos: 2, + }); + assert_eq!(left.content_len(), 2); + assert_eq!(left.estimate_storage_size(ContainerType::List), 8); + assert!(left.is_mergable(&right, &())); + left.merge(&right, &()); + assert_eq!(left.content_len(), 4); + + let sliced = left.slice(1, 3); + match sliced { + InnerContent::List(InnerListOp::Insert { slice, pos }) => { + assert_eq!(slice, ValueSlice::new(vec![1_i64.into(), 2_i64.into()])); + assert_eq!(pos, 1); + } + other => panic!("expected sliced list insert, got {other:?}"), + } + + let map = InnerContent::Map(MapSet { + key: InternalString::from("flag"), + value: Some(true.into()), + }); + assert_eq!(map.content_len(), 1); + assert_eq!(map.estimate_storage_size(ContainerType::Map), 3); + assert!(matches!(map.slice(0, 1), InnerContent::Map(_))); + + let tree = InnerContent::Tree(Arc::new(TreeOp::Delete { + target: TreeID::new(4, 5), + })); + assert_eq!(tree.content_len(), 1); + assert_eq!(tree.estimate_storage_size(ContainerType::Tree), 8); + assert!(matches!(tree.slice(0, 1), InnerContent::Tree(_))); + + let future = InnerContent::Future(FutureInnerContent::Unknown { + prop: 99, + value: Box::new(OwnedValue::Null), + }); + assert_eq!(future.content_len(), 1); + assert_eq!(future.estimate_storage_size(ContainerType::Unknown(3)), 6); + assert!(matches!(future.slice(0, 1), InnerContent::Future(_))); + + #[cfg(feature = "counter")] + { + let counter = InnerContent::Future(FutureInnerContent::Counter(2.0)); + assert_eq!(counter.estimate_storage_size(ContainerType::Counter), 4); + } + } + + #[test] + fn visit_created_children_reports_containers_created_by_list_map_and_tree_content() { + let list_child = ContainerID::new_normal(ID::new(1, 1), ContainerType::List); + let text_child = ContainerID::new_normal(ID::new(1, 2), ContainerType::Text); + let list = InnerContent::List(InnerListOp::Insert { + slice: ValueSlice::new(vec![ + LoroValue::Container(list_child.clone()), + "plain".into(), + LoroValue::Container(text_child.clone()), + ]), + pos: 0, + }); + let mut children = Vec::new(); + list.visit_created_children(&mut |id| children.push(id.clone())); + assert_eq!(children, vec![list_child.clone(), text_child.clone()]); + + let map_child = ContainerID::new_normal(ID::new(2, 1), ContainerType::Map); + let map = InnerContent::Map(MapSet { + key: InternalString::from("child"), + value: Some(LoroValue::Container(map_child.clone())), + }); + let mut children = Vec::new(); + map.visit_created_children(&mut |id| children.push(id.clone())); + assert_eq!(children, vec![map_child]); + + let tree_target = TreeID::new(3, 7); + let tree = InnerContent::Tree(Arc::new(TreeOp::Create { + target: tree_target, + parent: None, + position: FractionalIndex::default(), + })); + let mut children = Vec::new(); + tree.visit_created_children(&mut |id| children.push(id.clone())); + assert_eq!(children, vec![tree_target.associated_meta_container()]); + + for tree in [ + TreeOp::Move { + target: tree_target, + parent: None, + position: FractionalIndex::default(), + }, + TreeOp::Delete { + target: tree_target, + }, + ] { + let tree = InnerContent::Tree(Arc::new(tree)); + let mut children = Vec::new(); + tree.visit_created_children(&mut |id| children.push(id.clone())); + assert!(children.is_empty()); + } + + let future = InnerContent::Future(FutureInnerContent::Unknown { + prop: 1, + value: Box::new(OwnedValue::False), + }); + let mut children = Vec::new(); + future.visit_created_children(&mut |id| children.push(id.clone())); + assert!(children.is_empty()); + } +} diff --git a/vendor/loro-internal/src/oplog.rs b/vendor/loro-internal/src/oplog.rs new file mode 100644 index 0000000..5ecd94e --- /dev/null +++ b/vendor/loro-internal/src/oplog.rs @@ -0,0 +1,1759 @@ +mod change_store; +mod known_history; +pub(crate) use known_history::ImportedValues; +pub(crate) mod loro_dag; +mod pending_changes; + +use crate::sync::{AtomicUsize, Mutex}; +use bytes::Bytes; +use std::borrow::Cow; +use std::cell::RefCell; +use std::cmp::Ordering; +use std::rc::Rc; +use std::sync::Arc; +use tracing::trace_span; + +use self::change_store::iter::MergedChangeIter; +use self::pending_changes::{PendingChanges, PendingChangesRollback}; +use super::arena::{SharedArena, SharedArenaRollback}; +use crate::change::{get_sys_timestamp, Change, Lamport, Timestamp}; +use crate::configure::Configure; +use crate::container::idx::ContainerIdx; +use crate::container::list::list_op; +use crate::dag::{Dag, DagUtils, MeetAsBase}; +use crate::diff_calc::DiffMode; +use crate::encoding::decode_oplog; +use crate::encoding::{ImportStatus, ParsedHeaderAndBody}; +use crate::history_cache::ContainerHistoryCache; +use crate::id::{Counter, PeerID, ID}; +use crate::op::{FutureInnerContent, InnerContent, ListSlice, RawOpContent, RemoteOp, RichOp}; +use crate::span::{HasCounterSpan, HasLamportSpan}; +use crate::state::DocState; +use crate::version::{Frontiers, ImVersionVector, VersionVector}; +use crate::LoroError; +use change_store::{BlockOpRef, ChangeStoreRollback}; +use loro_common::{ContainerType, HasIdSpan, IdLp, IdSpan}; +use rle::{HasLength, RleVec, Sliceable}; +use rustc_hash::{FxHashMap, FxHashSet}; +use smallvec::SmallVec; + +pub use self::loro_dag::{AppDag, AppDagNode, FrontiersNotIncluded}; +pub(crate) use change_store::encode_change_block; +pub use change_store::{BlockChangeRef, ChangeStore}; + +/// [OpLog] store all the ops i.e. the history. +/// It allows multiple [AppState] to attach to it. +/// So you can derive different versions of the state from the [OpLog]. +/// It allows us to build a version control system. +/// +/// The causal graph should always be a DAG and complete, so two versions always have a replay base (at worst the empty version). +/// If deps are missing, we can't import the change. It will be put into the `pending_changes`. +pub struct OpLog { + pub(crate) dag: AppDag, + pub(crate) arena: SharedArena, + visible_op_count: Arc<AtomicUsize>, + change_store: ChangeStore, + history_cache: Mutex<ContainerHistoryCache>, + /// Pending changes that haven't been applied to the dag. + /// A change can be imported only when all its deps are already imported. + /// Key is the ID of the missing dep + pub(crate) pending_changes: PendingChanges, + /// Whether we are importing a batch of changes. + /// If so the Dag's frontiers won't be updated until the batch is finished. + pub(crate) batch_importing: bool, + pub(crate) configure: Configure, + /// The uncommitted change, it's a placeholder for the change + /// that is being edited in pre-commit callback. + pub(crate) uncommitted_change: Option<Change>, + pub(crate) import_rollback: Option<ImportRollback>, +} + +pub(crate) struct ImportRollback { + arena: SharedArenaRollback, + change_store: ChangeStoreRollback, + pending: PendingChangesRollback, + /// Movable-list `Move`/`Set` element references inserted in this scope and not + /// validated yet (`OpLog::validate_movable_list_elem_refs_in_import_scope`). + movable_list_refs: Vec<MovableListElemRef>, +} + +#[derive(Clone, Copy)] +struct ResolvedElem { + target: ID, + container: ContainerIdx, + is_insert: bool, +} + +struct MovableListElemRef { + container: ContainerIdx, + op_id: ID, + op_lamport: Lamport, + elem_id: IdLp, +} + +#[derive(Debug, Default, Clone, Copy)] +pub(crate) struct ImportChangesPreflight { + pub applies_to_dag: bool, + pub has_deps_before_shallow_root: bool, + /// Attached: state apply can reject. Detached: element validation can reject. + pub needs_state_apply_rollback: bool, +} + +impl std::fmt::Debug for OpLog { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("OpLog") + .field("dag", &self.dag) + .field("pending_changes", &self.pending_changes) + .finish() + } +} + +#[cfg(test)] +thread_local! { + /// Counts falls from the multi-head critical version search back to the + /// single-head whole-DAG descent. Test observability only; thread-local + /// so concurrently running tests cannot disturb each other's counts + /// (diff calc runs on the importing thread). + pub(crate) static CRITICAL_BASE_FALLBACK_COUNT: std::cell::Cell<u64> = + const { std::cell::Cell::new(0) }; +} + +/// Result of [`OpLog::latest_critical_version_below_meet`]. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum CriticalVersionSearch { + /// The greatest critical version ≤ `meet(from, to)`. + Found(VersionVector), + /// Provably no non-empty critical version ≤ meet exists: the fixpoint + /// bottomed out at ∅, and every critical cut ≤ meet survives every + /// lowering step, so the single-head descent cannot find one either — + /// callers should skip its whole-DAG walk. + NoneBelowMeet, + /// A change's deps reach below trimmed history; nothing is known. Fall + /// back to the single-head descent. + Unknown, +} + +/// The replay base [`OpLog::iter_from_replay_base_causally`] chose. +#[derive(Debug)] +pub(crate) struct ReplayBase { + pub vv: VersionVector, + pub diff_mode: DiffMode, + /// The base is a *critical version* of `ancestry(from) ∪ ancestry(to)`: + /// no event above it is concurrent with any event inside it. Calculators + /// that seed their CRDT state with one opaque "unknown" span for + /// everything below the base need exactly this property, because such a + /// span can never be retreated. + pub is_critical: bool, + /// `Some` when the import was proved register-only concurrent with + /// `from` and replays from it (see `OpLog::register_only_concurrency`): + /// every container with an op in the concurrent old history. + pub concurrent_containers: Option<FxHashSet<ContainerIdx>>, +} + +/// Whether an imported op on a container of type `ty` can be rejected by +/// `ContainerState::validate_diff` (e.g. a sequence position past the end), so +/// the import needs a rollback scope to undo the op log on that error. +pub(crate) fn state_apply_can_reject(ty: ContainerType) -> bool { + matches!( + ty, + ContainerType::List + | ContainerType::MovableList + | ContainerType::Text + | ContainerType::Tree + ) +} + +/// Detached imports do not apply state. Only Move/Set element validation can +/// reject after adding history; an enclosing batch still owns its full scope. +pub(super) fn import_op_can_reject(op: &crate::op::Op, detached: bool) -> bool { + if detached { + op.container.get_type() == ContainerType::MovableList + && matches!( + op.content, + InnerContent::List( + list_op::InnerListOp::Move { .. } | list_op::InnerListOp::Set { .. } + ) + ) + } else { + state_apply_can_reject(op.container.get_type()) + } +} + +impl OpLog { + #[inline] + pub(crate) fn new(visible_op_count: Arc<AtomicUsize>) -> Self { + let arena = SharedArena::new(); + let cfg = Configure::default(); + let change_store = ChangeStore::new_mem(&arena, cfg.merge_interval_in_s.clone()); + arena.set_creator_resolver(change_store.creator_resolver()); + Self { + visible_op_count, + history_cache: Mutex::new(ContainerHistoryCache::new(change_store.clone(), None)), + dag: AppDag::new(change_store.clone()), + change_store, + arena, + pending_changes: Default::default(), + batch_importing: false, + configure: cfg, + uncommitted_change: None, + import_rollback: None, + } + } + + #[inline] + fn calc_visible_op_count(&self) -> usize { + let total = self.dag.vv().values().sum::<i32>() as usize; + let shallow = self + .dag + .shallow_since_vv() + .iter() + .map(|(_, ops)| *ops) + .sum::<i32>() as usize; + total - shallow + } + + #[inline] + pub(crate) fn visible_op_count_exact(&self) -> usize { + self.calc_visible_op_count() + } + + #[inline] + pub(crate) fn refresh_visible_op_count(&self) -> usize { + let count = self.calc_visible_op_count(); + self.visible_op_count + .store(count, std::sync::atomic::Ordering::Release); + count + } + + /// Incrementally bump the cached visible op count for newly applied *local* + /// ops. Local ops are always visible (never behind the shallow root), so the + /// visible count grows by exactly `delta`. This avoids a per-op full + /// recompute via [`Self::calc_visible_op_count`], which iterates the version + /// vectors and heap-allocates an `im::HashMap` iterator on every call. + #[inline] + pub(crate) fn inc_visible_op_count(&self, delta: usize) { + self.visible_op_count + .fetch_add(delta, std::sync::atomic::Ordering::Release); + } + + #[cfg(test)] + pub(crate) fn cached_visible_op_count(&self) -> usize { + self.visible_op_count + .load(std::sync::atomic::Ordering::Acquire) + } + + #[inline] + pub fn dag(&self) -> &AppDag { + &self.dag + } + + pub fn change_store(&self) -> &ChangeStore { + &self.change_store + } + + /// `Err` once a read of the history has hit a change block that cannot be parsed (see + /// `ChangeStore::corrupt_block_error`). Only public entry points that return a `Result` + /// check it: internal callers of the same code `unwrap` their results. + pub(crate) fn check_history_parsable(&self) -> Result<(), LoroError> { + self.change_store.corrupt_block_error() + } + + /// Get the change with the given peer and lamport. + /// + /// If not found, return the change with the greatest lamport that is smaller than the given lamport. + pub fn get_change_with_lamport_lte( + &self, + peer: PeerID, + lamport: Lamport, + ) -> Option<BlockChangeRef> { + let ans = self + .change_store + .get_change_by_lamport_lte(IdLp::new(peer, lamport))?; + debug_assert!(ans.lamport <= lamport); + Some(ans) + } + + pub fn try_get_change_with_lamport_lte( + &self, + peer: PeerID, + lamport: Lamport, + ) -> Result<Option<BlockChangeRef>, LoroError> { + self.check_history_parsable()?; + let change = self.get_change_with_lamport_lte(peer, lamport); + self.check_history_parsable()?; + Ok(change) + } + + pub fn get_timestamp_of_version(&self, f: &Frontiers) -> Timestamp { + let mut timestamp = Timestamp::default(); + for id in f.iter() { + if let Some(change) = self.lookup_change(id) { + timestamp = timestamp.max(change.timestamp); + } + } + + timestamp + } + + /// No history, not even pending changes: a snapshot import may replace + /// this op log wholesale. + #[inline] + pub fn is_empty(&self) -> bool { + self.dag.is_empty() && self.pending_changes.is_empty() + } + + /// This is the **only** place to update the `OpLog.changes` + pub(crate) fn insert_new_change(&mut self, change: Change, from_local: bool) { + let s = trace_span!( + "insert_new_change", + id = ?change.id, + lamport = change.lamport, + deps = ?change.deps + ); + let _enter = s.enter(); + let rollback_old_vv = self + .import_rollback + .as_ref() + .map(|x| x.change_store.old_vv()) + .filter(|vv| !vv.is_empty()); + self.dag + .handle_new_change(&change, from_local, rollback_old_vv); + self.history_cache + .lock() + .insert_by_new_change(&change, true, true); + #[cfg(debug_assertions)] + if from_local { + crate::parent::assert_local_parent_links_registered(&self.arena, &change); + } + self.register_container_and_parent_link(&change); + if let Some(rollback) = self.import_rollback.as_mut() { + for op in change.ops.iter() { + if op.container.get_type() != ContainerType::MovableList { + continue; + } + if let InnerContent::List( + list_op::InnerListOp::Move { elem_id, .. } + | list_op::InnerListOp::Set { elem_id, .. }, + ) = &op.content + { + rollback.movable_list_refs.push(MovableListElemRef { + container: op.container, + op_id: ID::new(change.id.peer, op.counter), + op_lamport: change.lamport + (op.counter - change.id.counter) as Lamport, + elem_id: *elem_id, + }); + } + } + self.change_store.insert_change_with_rollback( + change, + true, + from_local, + &mut rollback.change_store, + ); + } else { + self.change_store.insert_change(change, true, from_local); + } + self.refresh_visible_op_count(); + } + + pub(crate) fn begin_import_rollback(&mut self) { + let arena = self.arena.checkpoint_for_rollback(); + self.begin_import_rollback_with_arena(arena); + } + + pub(crate) fn begin_import_rollback_with_arena(&mut self, arena: SharedArenaRollback) { + let old_vv = Arc::new(self.vv().clone()); + self.begin_import_rollback_with_version(arena, old_vv); + } + + /// Share the attached import's existing version snapshot with both journals. + pub(crate) fn begin_import_rollback_with_version( + &mut self, + arena: SharedArenaRollback, + old_vv: Arc<VersionVector>, + ) { + debug_assert!(self.import_rollback.is_none()); + self.dag.begin_import_rollback(old_vv.clone()); + self.import_rollback = Some(ImportRollback { + arena, + change_store: ChangeStoreRollback::new(old_vv), + pending: Default::default(), + movable_list_refs: Vec::new(), + }); + } + + /// Whether an import rollback scope is currently open. + /// + /// Scopes cannot nest: [`Self::begin_import_rollback_with_arena`] overwrites the + /// journal, and the matching commit/rollback clears it. Callers that may run + /// inside another scope (e.g. a blob imported by `LoroDoc::import_batch`) must + /// check this first and leave the scope to its owner. + pub(crate) fn has_import_rollback(&self) -> bool { + self.import_rollback.is_some() + } + + pub(crate) fn commit_import_rollback(&mut self) { + self.dag.commit_import_rollback(); + self.import_rollback = None; + } + + /// Commit an import rollback scope this caller owns. No-op when `owns` is false — the + /// scope then belongs to an outer owner such as `import_batch`. + pub(crate) fn commit_owned_import_rollback(&mut self, owns: bool) { + if owns { + self.commit_import_rollback(); + } + } + + /// Roll back an import rollback scope this caller owns (see [`Self::rollback_import`]). + /// No-op when `owns` is false — the scope then belongs to an outer owner such as + /// `import_batch`. + pub(crate) fn rollback_owned_import(&mut self, owns: bool, state: &mut DocState) { + if owns { + self.rollback_import(state); + } + } + + pub(crate) fn preflight_import_changes( + &self, + changes: &[Change], + detached: bool, + ) -> Result<ImportChangesPreflight, LoroError> { + let mut ans = ImportChangesPreflight::default(); + for change in changes { + if change.ctr_end() <= self.vv().get(&change.id.peer).copied().unwrap_or(0) { + continue; + } + + if self.dag.try_import_deps_before_shallow_root(&change.deps)? { + ans.has_deps_before_shallow_root = true; + continue; + } + + // Inspect the ops even when the deps are not in the DAG yet: they may be + // earlier changes of this same import, which then unlock this one. + if change + .ops + .iter() + .any(|op| import_op_can_reject(op, detached)) + { + ans.needs_state_apply_rollback = true; + } + + if self + .dag + .try_get_change_lamport_from_deps(&change.deps)? + .is_some() + { + ans.applies_to_dag = true; + } + } + + // Any newly applied change can unlock pending changes whose ops are not + // visible in `changes`, so include pending in the rollback decision. + // Keep this narrow: map-only pending changes cannot return a + // state-apply error, and forcing rollback there adds lock traffic to + // small sync/import workloads. + // + // Scan pending last, and only when it can still change the answer: + // `has_import_rollback_ops` walks every parked change and every op in + // it, while a blob that only parks (deps not here yet) leaves + // `applies_to_dag` false. Evaluating it eagerly made a batch of N + // out-of-order blobs quadratic, since each blob re-scanned the pending set + // the earlier blobs had grown. + if ans.applies_to_dag + && !ans.needs_state_apply_rollback + && self.pending_changes.has_import_rollback_ops(detached) + { + ans.needs_state_apply_rollback = true; + } + + #[cfg(test)] + if ans.applies_to_dag && !detached { + ans.needs_state_apply_rollback = true; + } + + Ok(ans) + } + + /// Undo the open import rollback scope, including the arena. + /// + /// `state` shows that the caller holds the state lock. A reader under that lock can + /// register containers through the creator resolver, which runs without the op log lock, + /// and resolve their parent links before it returns; the arena rollback must not drop + /// those links in between. See `context/arena-parent-links.md`. The state's caches that + /// depend on parent links are cleared as well + /// (`context/failed-import-arena-indices.md`). + pub(crate) fn rollback_import(&mut self, state: &mut DocState) { + let Some(rollback) = self.import_rollback.take() else { + return; + }; + state.forget_parent_link_caches_after_failed_import(); + + // Also rolls back the arena; see `ChangeStore::rollback_import`. + self.change_store + .rollback_import(rollback.change_store, rollback.arena); + self.dag.rollback_import(); + rollback.pending.rollback(&mut self.pending_changes); + self.history_cache.lock().free_all(); + self.refresh_visible_op_count(); + } + + /// [`Self::rollback_import`] without the arena rollback, for a scope that only inserted a + /// discarded local transaction (`LoroDoc::rollback_apply_diff_scope`): its containers were + /// registered by the transaction, and undoing it from the state may register old + /// containers and create state for them. See `context/apply-diff-atomicity.md`. + pub(crate) fn rollback_import_keeping_arena(&mut self, _state: &DocState) { + let Some(rollback) = self.import_rollback.take() else { + return; + }; + + self.change_store + .rollback_import_keeping_arena(rollback.change_store); + self.dag.rollback_import(); + rollback.pending.rollback(&mut self.pending_changes); + self.history_cache.lock().free_all(); + self.refresh_visible_op_count(); + } + + /// Rolls the arena back to a checkpoint taken before an import that failed before its + /// import rollback scope began. See [`ChangeStore::rollback_arena`], and + /// [`Self::rollback_import`] for `state`. + pub(crate) fn rollback_arena( + &self, + arena_checkpoint: SharedArenaRollback, + state: &mut DocState, + ) { + state.forget_parent_link_caches_after_failed_import(); + self.change_store.rollback_arena(arena_checkpoint); + } + + /// See [`Self::rollback_import`] for `state`. + pub(crate) fn reset_to_empty_for_failed_snapshot_import( + &mut self, + arena_checkpoint: SharedArenaRollback, + state: &mut DocState, + ) { + state.forget_parent_link_caches_after_failed_import(); + let arena = self.arena.clone(); + let configure = self.configure.clone(); + // Also rolls back the arena; see `ChangeStore::retire`. + self.change_store.retire(arena_checkpoint); + let change_store = ChangeStore::new_mem(&arena, configure.merge_interval_in_s.clone()); + arena.set_creator_resolver(change_store.creator_resolver()); + self.history_cache = Mutex::new(ContainerHistoryCache::new(change_store.clone(), None)); + self.dag = AppDag::new(change_store.clone()); + self.change_store = change_store; + self.pending_changes = Default::default(); + self.batch_importing = false; + self.configure = configure; + self.uncommitted_change = None; + self.import_rollback = None; + self.visible_op_count + .store(0, std::sync::atomic::Ordering::Release); + } + + #[inline(always)] + pub(crate) fn with_history_cache<F, R>(&self, f: F) -> R + where + F: FnOnce(&mut ContainerHistoryCache) -> R, + { + let mut history_cache = self.history_cache.lock(); + f(&mut history_cache) + } + + pub fn has_history_cache(&self) -> bool { + self.history_cache.lock().has_cache() + } + + pub fn free_history_cache(&self) { + let mut history_cache = self.history_cache.lock(); + history_cache.free(); + } + + #[cfg(test)] + #[allow(dead_code)] + pub(crate) fn pending_changes_len(&self) -> usize { + self.pending_changes.len() + } + + /// Import a change. + /// + /// Pending changes that haven't been applied to the dag. + /// A change can be imported only when all its deps are already imported. + /// Key is the ID of the missing dep + /// + /// # Err + /// + /// - Return Err(LoroError::UsedOpID) when the change's id is occupied + /// - Return Err(LoroError::DecodeError) when the change's deps are missing + pub(crate) fn import_local_change(&mut self, change: Change) -> Result<(), LoroError> { + self.insert_new_change(change, true); + Ok(()) + } + + /// Trim the known part of change + pub(crate) fn trim_the_known_part_of_change(&self, change: Change) -> Option<Change> { + let Some(&end) = self.dag.vv().get(&change.id.peer) else { + return Some(change); + }; + + if change.id.counter >= end { + return Some(change); + } + + if change.ctr_end() <= end { + return None; + } + + let offset = (end - change.id.counter) as usize; + Some(change.slice(offset, change.atom_len())) + } + + #[allow(unused)] + fn check_id_is_not_duplicated(&self, id: ID) -> Result<(), LoroError> { + let cur_end = self.dag.vv().get(&id.peer).cloned().unwrap_or(0); + if cur_end > id.counter { + return Err(LoroError::UsedOpID { id }); + } + + Ok(()) + } + + /// Ensure the new change is greater than the last peer's id and the counter is continuous. + /// + /// It can be false when users use detached editing mode and use a custom peer id. + // This method might be slow and can be optimized if needed in the future. + pub(crate) fn check_change_greater_than_last_peer_id( + &self, + peer: PeerID, + counter: Counter, + deps: &Frontiers, + ) -> Result<(), LoroError> { + if counter == 0 { + return Ok(()); + } + + if !self.configure.detached_editing() { + return Ok(()); + } + + let mut max_last_counter = -1; + for dep in deps.iter() { + let dep_vv = self + .dag + .get_vv(dep) + .ok_or(LoroError::FrontiersNotFound(dep))?; + max_last_counter = max_last_counter.max(dep_vv.get(&peer).cloned().unwrap_or(0) - 1); + } + + if counter != max_last_counter + 1 { + return Err(LoroError::ConcurrentOpsWithSamePeerID { + peer, + last_counter: max_last_counter, + current: counter, + }); + } + + Ok(()) + } + + pub(crate) fn next_id(&self, peer: PeerID) -> ID { + let cnt = self.dag.vv().get(&peer).copied().unwrap_or(0); + ID::new(peer, cnt) + } + + pub(crate) fn vv(&self) -> &VersionVector { + self.dag.vv() + } + + pub(crate) fn frontiers(&self) -> &Frontiers { + self.dag.frontiers() + } + + /// - Ordering::Less means self is less than target or parallel + /// - Ordering::Equal means versions equal + /// - Ordering::Greater means self's version is greater than target + pub fn cmp_with_frontiers(&self, other: &Frontiers) -> Ordering { + self.dag.cmp_with_frontiers(other) + } + + /// Compare two [Frontiers] causally. + /// + /// If one of the [Frontiers] are not included, it will return [FrontiersNotIncluded]. + #[inline] + pub fn cmp_frontiers( + &self, + a: &Frontiers, + b: &Frontiers, + ) -> Result<Option<Ordering>, FrontiersNotIncluded> { + self.dag.cmp_frontiers(a, b) + } + + pub(crate) fn get_lamport_at(&self, id: ID) -> Option<Lamport> { + self.get_change_at(id) + .map(|c| c.lamport + (id.counter - c.id.counter) as Lamport) + } + + pub(crate) fn iter_ops(&self, id_span: IdSpan) -> impl Iterator<Item = RichOp<'static>> + '_ { + let change_iter = self.change_store.iter_changes(id_span); + change_iter.flat_map(move |c| RichOp::new_iter_by_cnt_range(c, id_span.counter)) + } + + pub(crate) fn iter_changes( + &self, + id_span: IdSpan, + ) -> impl Iterator<Item = BlockChangeRef> + '_ { + self.change_store.iter_changes(id_span) + } + + pub(crate) fn get_max_lamport_at(&self, id: ID) -> Lamport { + self.get_change_at(id) + .map(|c| { + let change_counter = c.id.counter as u32; + c.lamport + c.ops().last().map(|op| op.counter).unwrap_or(0) as u32 - change_counter + }) + .unwrap_or(Lamport::MAX) + } + + pub fn get_change_at(&self, id: ID) -> Option<BlockChangeRef> { + self.change_store.get_change(id) + } + + pub fn try_get_change_at(&self, id: ID) -> Result<Option<BlockChangeRef>, LoroError> { + self.check_history_parsable()?; + let change = self.get_change_at(id); + self.check_history_parsable()?; + Ok(change) + } + + pub(crate) fn set_uncommitted_change(&mut self, change: Change) { + self.uncommitted_change = Some(change); + } + + pub(crate) fn get_uncommitted_change_in_span( + &self, + id_span: IdSpan, + ) -> Option<Cow<'_, Change>> { + self.uncommitted_change.as_ref().and_then(|c| { + if c.id_span() == id_span { + Some(Cow::Borrowed(c)) + } else if let Some((start, end)) = id_span.get_slice_range_on(&c.id_span()) { + Some(Cow::Owned(c.slice(start, end))) + } else { + None + } + }) + } + + pub fn get_deps_of(&self, id: ID) -> Option<Frontiers> { + self.get_change_at(id).map(|c| { + if c.id.counter == id.counter { + c.deps.clone() + } else { + Frontiers::from_id(id.inc(-1)) + } + }) + } + + pub fn get_remote_change_at(&self, id: ID) -> Option<Change<RemoteOp<'static>>> { + let change = self.get_change_at(id)?; + Some(convert_change_to_remote(&self.arena, &change)) + } + + pub fn try_get_remote_change_at( + &self, + id: ID, + ) -> Result<Option<Change<RemoteOp<'static>>>, LoroError> { + let change = self.try_get_change_at(id)?; + Ok(change.map(|change| convert_change_to_remote(&self.arena, &change))) + } + + pub(crate) fn import_unknown_lamport_pending_changes( + &mut self, + remote_changes: Vec<Change>, + would_affect: Option<&mut crate::version::VersionRange>, + ) -> crate::version::VersionRange { + self.extend_pending_changes_with_unknown_lamport(remote_changes, would_affect) + } + + /// lookup change by id. + /// + /// if id does not included in this oplog, return None + pub(crate) fn lookup_change(&self, id: ID) -> Option<BlockChangeRef> { + self.change_store.get_change(id) + } + + #[inline(always)] + pub(crate) fn export_change_store_from(&self, vv: &VersionVector, f: &Frontiers) -> Bytes { + self.change_store + .export_from(vv, f, self.vv(), self.frontiers()) + } + + #[inline(always)] + pub(crate) fn export_change_store_in_range( + &self, + vv: &VersionVector, + f: &Frontiers, + to_vv: &VersionVector, + to_frontiers: &Frontiers, + ) -> Bytes { + self.change_store.export_from(vv, f, to_vv, to_frontiers) + } + + #[inline(always)] + pub(crate) fn export_blocks_from<W: std::io::Write>(&self, vv: &VersionVector, w: &mut W) { + self.change_store + .export_blocks_from(vv, self.shallow_since_vv(), self.vv(), w) + } + + #[inline(always)] + pub(crate) fn export_blocks_in_range<W: std::io::Write>(&self, spans: &[IdSpan], w: &mut W) { + self.change_store.export_blocks_in_range(spans, w) + } + + pub(crate) fn fork_changes_up_to( + &self, + frontiers: &Frontiers, + ) -> Result<Option<Bytes>, LoroError> { + let Some(vv) = self.dag.try_frontiers_to_vv(frontiers)? else { + return Ok(None); + }; + Ok(Some(self.change_store.fork_changes_up_to( + self.dag.shallow_since_vv(), + frontiers, + &vv, + )?)) + } + + #[inline(always)] + pub(crate) fn decode( + &mut self, + data: ParsedHeaderAndBody, + values: ImportedValues, + ) -> Result<ImportStatus, LoroError> { + decode_oplog(self, data, values) + } + + /// Containers that have at least one op inside `spans`. + /// + /// Only `op.container` is needed, so this scans the borrowed changes + /// directly instead of materializing a cloned RichOp per op. + pub(crate) fn try_containers_in_spans( + &self, + spans: impl Iterator<Item = IdSpan>, + ) -> Result<FxHashSet<ContainerIdx>, LoroError> { + let mut containers = FxHashSet::default(); + // Consecutive ops overwhelmingly share a container; skip the hash + // probe when it hasn't changed. + let mut last_container = None; + for span in spans { + for change in self.change_store.try_iter_changes(span)? { + let start_counter = span.counter.min().max(change.id.counter); + let end_counter = span.counter.norm_end(); + let start = change + .ops + .binary_search_by(|op| op.ctr_last().cmp(&start_counter)) + .unwrap_or_else(|e| e); + for op in &change.ops.vec()[start..] { + if op.counter >= end_counter { + break; + } + + if last_container != Some(op.container) { + containers.insert(op.container); + last_container = Some(op.container); + } + } + } + } + + Ok(containers) + } + + /// For `to ⊇ from`: the old-parent frontiers of every entry change of the + /// new region `to − from` that does not causally cover all of `from`. + /// + /// An entry change is a new change (or the new suffix of a change that + /// straddles `from`) whose causal parents — explicit deps plus the + /// implicit same-peer predecessor — are all old. Every new event is a + /// descendant of some entry change, so `⋂ Events(parents)` over the + /// uncovered entries is causally before the whole new region and only + /// `Events(from)` outside it can be concurrent with a new op. + /// + /// This is the version-vector form of the DAG's + /// `new_region_uncovered_entry_parents` (see + /// `docs/critical-version-spec.md` L12): it only scans the new changes + /// and answers coverage with cached version vectors, so it costs + /// `O(|new changes|)` instead of a lamport-pruned ancestor walk. An empty + /// vector means the `ImportGreaterUpdates` contract holds outright; + /// `None` means trimmed history got in the way. + fn uncovered_entry_parents( + &self, + from: &VersionVector, + from_frontiers: &Frontiers, + to: &VersionVector, + ) -> Result<Option<Vec<Frontiers>>, LoroError> { + let mut uncovered = Vec::new(); + for (peer, span) in from.diff(to).forward.iter() { + let id_span = IdSpan::new(*peer, span.start, span.end); + for change in self.change_store.try_iter_changes(id_span)? { + let start = change.id.counter.max(span.start); + let parents = if start > change.id.counter { + // The change straddles `from`; the new suffix only has + // the implicit predecessor as parent. + Frontiers::from_id(ID::new(*peer, start - 1)) + } else { + let mut parents = change.deps().clone(); + if change.id.counter > 0 { + let prev = ID::new(*peer, change.id.counter - 1); + if !parents.contains(&prev) { + parents.push(prev); + } + } + parents + }; + + // The everyday shape: the change depends on exactly the + // current frontiers. Covered without touching any version vector. + if &parents == from_frontiers { + continue; + } + + if !parents.iter().all(|id| from.includes_id(id)) { + // Not an entry change; it inherits coverage through its + // new parents. + continue; + } + + let Some(parents_vv) = self.dag.try_frontiers_to_vv(&parents)? else { + return Ok(None); + }; + if !parents_vv.includes_vv(from) { + uncovered.push(parents); + } + } + } + + Ok(Some(uncovered)) + } + + /// Decide whether an import whose new region `to − from` is concurrent + /// with part of `from` can still be replayed from `from`. + /// + /// `entry_parents` comes from [`OpLog::uncovered_entry_parents`]: the old + /// history that is causally before the *whole* new region is + /// `⋂ Events(parents)`, so the old ops that may be concurrent with a new op + /// are `Events(from) − ⋂ Events(parents)`. + /// + /// Sequence and tree containers need every concurrent op of the same + /// container as context, so a container with ops on both sides forces the + /// conservative replay. Map and counter are registers: a counter diff is + /// a commutative sum, and a map diff can be resolved per key from the + /// history cache without positional context, so concurrency on them is + /// harmless. (The map must NOT be resolved by comparing lamports against + /// the current state: persisted state drops metadata for deleted roots and + /// dead containers, so the diff calculator is told to use the history + /// cache for these containers, see `DiffCalculator::calc_diff_internal`.) + /// + /// Returns the containers touched by the concurrent old history when the + /// overlap is register-only, `None` otherwise. + fn register_only_concurrency( + &self, + from: &VersionVector, + to: &VersionVector, + entry_parents: &[Frontiers], + ) -> Result<Option<FxHashSet<ContainerIdx>>, LoroError> { + // ⋂ Events(parents) as a version vector: per-peer minimum. + let mut causal_past = from.clone(); + for parents in entry_parents { + let Some(parents_vv) = self.dag.try_frontiers_to_vv(parents)? else { + return Ok(None); + }; + causal_past.retain(|peer, end| { + let bound = parents_vv.get(peer).copied().unwrap_or(0); + *end = (*end).min(bound); + *end > 0 + }); + } + + // A shallow snapshot may retain changes that are concurrent with its + // root (independent peer chains, for example), and `from` counts the + // trimmed ops below the root. If `concurrent_old` would reach into + // that trimmed history we cannot see which containers it touched, so + // the decision has to stay with the DAG. + if !causal_past.includes_vv(&self.dag.shallow_since_vv().to_vv()) { + return Ok(None); + } + + let concurrent_old = causal_past.diff(from).forward; + let old_containers = self.try_containers_in_spans( + concurrent_old + .iter() + .map(|(peer, span)| IdSpan::new(*peer, span.start, span.end)), + )?; + if old_containers.is_empty() { + return Ok(Some(old_containers)); + } + + let new_region = from.diff(to).forward; + let new_containers = self.try_containers_in_spans( + new_region + .iter() + .map(|(peer, span)| IdSpan::new(*peer, span.start, span.end)), + )?; + let harmless = old_containers + .iter() + .filter(|idx| new_containers.contains(idx)) + .all(|idx| match idx.get_type() { + ContainerType::Map => true, + #[cfg(feature = "counter")] + ContainerType::Counter => true, + _ => false, + }); + Ok(harmless.then_some(old_containers)) + } + + /// The latest critical version below `from ∩ to`: the greatest causally + /// closed `V ⊆ from ∩ to` such that every op in `(from ∪ to) − V` is + /// causally after every op in `V`. "Causally after" is measured in the + /// ancestry the replay hands the diff calculators — a change's recorded + /// deps plus the author's own earlier ops — which is exactly what a + /// calculator trusting the base relies on. Unlike + /// `dag::latest_single_head_critical_version` the result may be + /// multi-head, which is what makes it usable on the criss-cross DAG that + /// continuous two-peer sync produces — there every merge point has two + /// heads, so the single-head descent walks to genesis and returns nothing. + /// + /// Method: start at the meet `min(from, to)` — the largest candidate — and + /// lower it to a fixpoint. `V` is critical iff for every change of the + /// region above it, the context of the change's first op above `V` + /// covers `V` (the change's later ops only add to that context). Each + /// violating change lowers `V` to the intersection with that context, + /// which preserves every critical cut below `V`, so the fixpoint is the + /// greatest critical version ≤ the meet (spec L13). Lowering cannot + /// change a verdict already reached — a context that covered `V` covers + /// the smaller one, and the violator covers the lowered `V` by + /// construction — it only exposes the spans between the old and the new + /// `V`, which go on a worklist; a change is examined once per lowering + /// that moves its peer's cut into it. The scan is thus bounded by the + /// replay it enables, which walks the same region and computes the same + /// contexts, so it needs no budget of its own. + #[cfg(test)] + pub(crate) fn latest_critical_version_below_meet( + &self, + from: &VersionVector, + to: &VersionVector, + merged: &VersionVector, + ) -> CriticalVersionSearch { + self.try_latest_critical_version_below_meet(from, to, merged) + .unwrap() + } + + pub(crate) fn try_latest_critical_version_below_meet( + &self, + from: &VersionVector, + to: &VersionVector, + merged: &VersionVector, + ) -> Result<CriticalVersionSearch, LoroError> { + use CriticalVersionSearch::*; + + // An intersection of two causally closed sets is causally closed, so + // `min(from, to)` is a version, and it is the meet of the two. + let mut v = from.intersection(to); + if v.is_empty() { + return Ok(NoneBelowMeet); + } + + let mut pending: Vec<IdSpan> = v.diff_iter(merged).1.collect(); + while let Some(span) = pending.pop() { + for change in self.change_store.try_iter_changes(span)? { + // The context of the change's first op above `v`, as + // `iter_from_replay_base_causally` computes it for the + // replay: the recorded deps plus the same-peer prefix. + let Some(mut ctx) = self.dag.try_frontiers_to_vv(&change.deps)? else { + // The deps reach below trimmed history; nothing can be + // proved from here. + return Ok(Unknown); + }; + let cut = v.get(&change.id.peer).copied().unwrap_or(0); + let first_above = change.id.counter.max(cut); + ctx.extend_to_include_end_id(ID::new(change.id.peer, first_above)); + + if !ctx.includes_vv(&v) { + let above = v.clone(); + v.intersect_with(&ctx); + if v.is_empty() { + return Ok(NoneBelowMeet); + } + pending.extend(v.diff_iter(&above).1); + } + } + } + + Ok(Found(v)) + } + + /// Iterates causally over all changes between the replay base (the meet + /// from `find_meet_and_mode` when it is valid for the diff mode, else a + /// critical version below it in the Eg-walker sense, see + /// `docs/critical-version-spec.md`) and the merged version of `from`/`to`. + /// + /// Tht iterator will include a version vector when the change is applied + /// + /// returns: (replay_base, iterator) + /// + /// Note: the change returned by the iterator may include redundant ops at the beginning, you should trim it by yourself. + /// You can trim it by the provided counter value. It should start with the counter. + /// + /// If frontiers are provided, it will be faster (because we don't need to calculate it from version vector + /// + /// The third item is `Some(containers)` when part of the new region is + /// concurrent with `from` but the oplog proved the concurrency + /// register-only (see [`OpLog::register_only_concurrency`]); the replay + /// then starts at `from` in `ImportGreaterUpdates` mode. The set lists + /// every container with an op in the concurrent old history: the diff + /// calculator resolves those from history and treats them as "source not + /// in op context", and may trust `from` as the base for everything else. + #[allow(clippy::type_complexity)] + pub(crate) fn iter_from_replay_base_causally( + &self, + from: &VersionVector, + from_frontiers: &Frontiers, + to: &VersionVector, + to_frontiers: &Frontiers, + ) -> ( + ReplayBase, + impl Iterator< + Item = ( + BlockChangeRef, + (Counter, Counter), + Rc<RefCell<VersionVector>>, + ), + > + '_, + ) { + let (base, iter) = self + .try_iter_from_replay_base_causally(from, from_frontiers, to, to_frontiers) + .unwrap(); + (base, iter.map(Result::unwrap)) + } + + #[allow(clippy::type_complexity)] + pub(crate) fn try_iter_from_replay_base_causally( + &self, + from: &VersionVector, + from_frontiers: &Frontiers, + to: &VersionVector, + to_frontiers: &Frontiers, + ) -> Result< + ( + ReplayBase, + impl Iterator< + Item = Result< + ( + BlockChangeRef, + (Counter, Counter), + Rc<RefCell<VersionVector>>, + ), + LoroError, + >, + > + '_, + ), + LoroError, + > { + let mut merged_vv = from.clone(); + merged_vv.merge(to); + loro_common::debug!("to_frontiers={:?} vv={:?}", &to_frontiers, to); + let mut concurrent_containers = None; + let mut register_only_base = None; + if to > from { + // `to ⊇ from`, but some new ops may be concurrent with part of + // `from`. The DAG walk must then assume the worst and retreat + // to a critical version; with container knowledge we can often + // prove the concurrency harmless and replay from `from` + // without touching the DAG at all. + if let Some(entry_parents) = self.uncovered_entry_parents(from, from_frontiers, to)? { + if !entry_parents.is_empty() { + if let Some(containers) = + self.register_only_concurrency(from, to, &entry_parents)? + { + concurrent_containers = Some(containers); + register_only_base = Some(from_frontiers.clone()); + } + } + } + } + + let (meet, mut diff_mode) = if let Some(base) = register_only_base { + (MeetAsBase::Valid(base), DiffMode::ImportGreaterUpdates) + } else { + self.dag + .try_find_meet_and_mode(from_frontiers, to_frontiers)? + }; + if diff_mode == DiffMode::Checkout && to > from { + diff_mode = DiffMode::Import; + } + + let shallow_since_vv = self.dag.shallow_since_vv().to_vv(); + let mut replay_base_is_critical = false; + let mut replay_base_frontiers = match meet { + MeetAsBase::Valid(meet) => meet, + MeetAsBase::NeedsCriticalRetreat => { + // Some event above the meet is concurrent with it. Retreat to + // a critical version — the latest *multi-head* one when we + // can find it, because the single-head descent is both a + // whole-DAG walk and, on the criss-cross DAG that continuous + // two-peer sync produces, doomed to return the empty version. + let descend = || { + #[cfg(test)] + CRITICAL_BASE_FALLBACK_COUNT.with(|c| c.set(c.get() + 1)); + self.dag + .try_latest_single_head_critical_version(from_frontiers, to_frontiers) + }; + match self.try_latest_critical_version_below_meet(from, to, &merged_vv)? { + CriticalVersionSearch::Found(v) => { + // Only replay from the version whose criticality was + // proved. A shallow doc cannot replay from below its + // seed version, and a cut assembled from recorded + // deps plus the author's own prefix is causally + // closed only when those deps cover that prefix + // (spec axiom A6, which imported data is not checked + // against) — a version that fails to round-trip + // through frontiers is not one. Both are left to the + // descent, as before. + let f = self.dag.try_vv_to_frontiers(&v)?; + let seed = self + .dag + .try_frontiers_to_vv(self.dag.shallow_since_frontiers())? + .unwrap(); + if v.includes_vv(&seed) + && self.dag.try_frontiers_to_vv(&f)?.as_ref() == Some(&v) + { + replay_base_is_critical = true; + f + } else { + descend()? + } + } + CriticalVersionSearch::NoneBelowMeet => { + // ∅ is trivially critical (spec D8b), and the + // single-head descent provably cannot find a better + // cut (spec L13(ii); under A6, where its ancestry + // coincides with the replay's) — skip its whole-DAG + // walk. + Frontiers::default() + } + CriticalVersionSearch::Unknown => descend()?, + } + } + }; + + let mut replay_base_vv = self + .dag + .try_frontiers_to_vv(&replay_base_frontiers)? + .unwrap(); + replay_base_is_critical |= replay_base_vv.is_empty(); + if !replay_base_vv.includes_vv(&shallow_since_vv) { + // The replay base cannot point before shallow history because those + // ops are no longer available to the causal iterator. + replay_base_frontiers = self.dag.shallow_since_frontiers().clone(); + replay_base_vv = self + .dag + .try_frontiers_to_vv(&replay_base_frontiers)? + .unwrap_or(shallow_since_vv); + replay_base_is_critical = false; + } + + // go from the replay base to merged_vv + let diff = replay_base_vv.diff(&merged_vv).forward; + let mut iter = crate::dag::DagCausalIter::try_new(&self.dag, replay_base_frontiers, diff)?; + let mut node = iter.next(); + let mut cur_cnt = 0; + let vv = Rc::new(RefCell::new(VersionVector::default())); + Ok(( + ReplayBase { + vv: replay_base_vv.clone(), + diff_mode, + is_critical: replay_base_is_critical, + concurrent_containers, + }, + std::iter::from_fn(move || { + let result = (|| -> Result<_, LoroError> { + if let Some(inner) = &node { + let mut inner_vv = vv.borrow_mut(); + // FIXME: PERF: it looks slow for large vv, like 10000+ entries + inner_vv.clear(); + self.dag.try_ensure_vv_for(&inner.data)?; + inner_vv.extend_to_include_vv(inner.data.vv.get().unwrap().iter()); + let peer = inner.data.peer; + let cnt = inner + .data + .cnt + .max(cur_cnt) + .max(replay_base_vv.get(&peer).copied().unwrap_or(0)); + let dag_node_end = (inner.data.cnt + inner.data.len as Counter) + .min(merged_vv.get(&peer).copied().unwrap_or(0)); + let change = match self.change_store.get_change(ID::new(peer, cnt)) { + Some(change) => change, + None => { + self.check_history_parsable()?; + panic!("DAG node must have a change"); + } + }; + + if change.ctr_end() < dag_node_end { + cur_cnt = change.ctr_end(); + } else { + node = iter.next(); + cur_cnt = 0; + } + + inner_vv.extend_to_include_end_id(change.id); + + Ok(Some((change, (cnt, dag_node_end), vv.clone()))) + } else { + Ok(None) + } + })(); + match result { + Ok(item) => item.map(Ok), + Err(err) => { + node = None; + Some(Err(err)) + } + } + }), + )) + } + + pub fn len_changes(&self) -> usize { + self.change_store.change_num() + } + + pub fn diagnose_size(&self) -> SizeInfo { + let mut total_changes = 0; + let mut total_ops = 0; + let mut total_atom_ops = 0; + let total_dag_node = self.dag.total_parsed_dag_node(); + self.change_store.visit_all_changes(&mut |change| { + total_changes += 1; + total_ops += change.ops.len(); + total_atom_ops += change.atom_len(); + }); + + println!("total changes: {}", total_changes); + println!("total ops: {}", total_ops); + println!("total atom ops: {}", total_atom_ops); + println!("total dag node: {}", total_dag_node); + SizeInfo { + total_changes, + total_ops, + total_atom_ops, + total_dag_node, + } + } + + pub(crate) fn iter_changes_peer_by_peer<'a>( + &'a self, + from: &VersionVector, + to: &VersionVector, + ) -> impl Iterator<Item = BlockChangeRef> + 'a { + let spans: Vec<_> = from.diff_iter(to).1.collect(); + spans + .into_iter() + .flat_map(move |span| self.change_store.iter_changes(span)) + } + + #[allow(dead_code)] + pub(crate) fn iter_changes_causally_rev<'a>( + &'a self, + from: &VersionVector, + to: &VersionVector, + ) -> impl Iterator<Item = BlockChangeRef> + 'a { + MergedChangeIter::new_change_iter_rev(self, from, to) + } + + pub fn get_timestamp_for_next_txn(&self) -> Timestamp { + if self.configure.record_timestamp() { + get_timestamp_now_txn() + } else { + 0 + } + } + + #[inline(never)] + pub(crate) fn idlp_to_id(&self, id: loro_common::IdLp) -> Option<ID> { + let change = self.change_store.get_change_by_lamport_lte(id)?; + + if change.lamport > id.lamport || change.lamport_end() <= id.lamport { + return None; + } + + Some(ID::new( + change.id.peer, + (id.lamport - change.lamport) as Counter + change.id.counter, + )) + } + + /// Reject the movable-list `Move`/`Set` ops inserted since the open import rollback + /// scope began whose `elem_id` is not an element inserted into the same list within + /// the op's causal history. + /// + /// Honest peers can only target elements they can see, and the movable-list diff + /// calculator relies on it (`last_pos`/`last_value` lookups). The refs are recorded + /// by `insert_new_change` while the scope is open, which covers directly imported + /// changes, unlocked pending changes and every blob of an `import_batch`. See + /// `context/movable-list-op-validation.md`. + pub(crate) fn validate_movable_list_elem_refs_in_import_scope( + &mut self, + ) -> Result<(), LoroError> { + let Some(rollback) = self.import_rollback.as_mut() else { + return Ok(()); + }; + let refs = std::mem::take(&mut rollback.movable_list_refs); + // Moves and sets keep hitting the same elements, and what an element id + // resolves to does not depend on the op, so resolve each one once. + let mut elems: FxHashMap<IdLp, Option<ResolvedElem>> = FxHashMap::default(); + for r in refs { + let elem = *elems + .entry(r.elem_id) + .or_insert_with(|| self.resolve_movable_list_elem(r.elem_id)); + if elem.is_none() { + self.check_history_parsable()?; + } + if !self.is_visible_movable_list_elem(&r, elem)? { + return Err(LoroError::DecodeError( + format!( + "Movable list op {} targets element {}, which is not in the list's \ + causal history", + r.op_id, r.elem_id + ) + .into_boxed_str(), + )); + } + } + + Ok(()) + } + + /// Where `elem_id`'s insert op lives, or `None` if its lamport is not in the stored + /// history. The lookup searches both parsed and KV-only blocks of the peer, so + /// `None` means the element never existed or was trimmed before a shallow root. + fn resolve_movable_list_elem(&self, elem_id: IdLp) -> Option<ResolvedElem> { + let change = self.change_store.get_change_by_lamport_lte(elem_id)?; + if change.lamport_end() <= elem_id.lamport { + return None; + } + let target = ID::new( + change.id.peer, + (elem_id.lamport - change.lamport) as Counter + change.id.counter, + ); + let op = change.get_op_with_counter(target.counter)?; + Some(ResolvedElem { + target, + container: op.container, + is_insert: matches!( + op.content, + InnerContent::List(list_op::InnerListOp::Insert { .. }) + ), + }) + } + + fn is_visible_movable_list_elem( + &self, + r: &MovableListElemRef, + elem: Option<ResolvedElem>, + ) -> Result<bool, LoroError> { + if r.elem_id.lamport >= r.op_lamport { + return Ok(false); + } + + let Some(elem) = elem else { + // History before a shallow root is trimmed. An op after the root can + // only see pre-root elements that are still alive at the root. + return Ok(!self.dag.shallow_since_vv().is_empty() + && self.with_history_cache(|h| { + h.shallow_root_has_movable_list_elem(r.container, r.elem_id) + })); + }; + if !elem.is_insert || elem.container != r.container { + return Ok(false); + } + + // Earlier ops of the op's own DAG node are by the same peer, so the node's + // start version covers every other peer's part of its causal history. + let target = elem.target; + if target.peer == r.op_id.peer && target.counter < r.op_id.counter { + return Ok(true); + } + let Some(node) = self.dag.try_get(r.op_id)? else { + return Ok(false); + }; + Ok(self.dag.try_ensure_vv_for(&node)?.includes_id(target)) + } + + #[allow(unused)] + pub(crate) fn id_to_idlp(&self, id_start: ID) -> IdLp { + let change = self.get_change_at(id_start).unwrap(); + let lamport = change.lamport + (id_start.counter - change.id.counter) as Lamport; + let peer = id_start.peer; + loro_common::IdLp { peer, lamport } + } + + /// NOTE: This may return a op that includes the given id, not necessarily start with the given id + pub(crate) fn get_op_that_includes(&self, id: ID) -> Option<BlockOpRef> { + let change = self.get_change_at(id)?; + change.get_op_with_counter(id.counter) + } + + pub(crate) fn split_span_based_on_deps(&self, id_span: IdSpan) -> Vec<(IdSpan, Frontiers)> { + let peer = id_span.peer; + let mut counter = id_span.counter.min(); + let span_end = id_span.counter.norm_end(); + let mut ans = Vec::new(); + + while counter < span_end { + let id = ID::new(peer, counter); + let node = self.dag.get(id).unwrap(); + + let f = if node.cnt == counter { + node.deps.clone() + } else if counter > 0 { + id.inc(-1).into() + } else { + unreachable!() + }; + + let cur_end = node.cnt + node.len as Counter; + let len = cur_end.min(span_end) - counter; + ans.push((id.to_span(len as usize), f)); + counter += len; + } + + ans + } + + #[inline] + pub fn compact_change_store(&mut self) { + self.change_store + .flush_and_compact(self.dag.vv(), self.dag.frontiers()); + } + + #[inline] + pub fn change_store_kv_size(&self) -> usize { + self.change_store.kv_size() + } + + pub fn encode_change_store(&self) -> bytes::Bytes { + self.change_store + .encode_all(self.dag.vv(), self.dag.frontiers()) + } + + pub fn check_dag_correctness(&self) { + self.dag.check_dag_correctness(); + } + + pub fn shallow_since_vv(&self) -> &ImVersionVector { + self.dag.shallow_since_vv() + } + + pub fn shallow_since_frontiers(&self) -> &Frontiers { + self.dag.shallow_since_frontiers() + } + + pub fn is_shallow(&self) -> bool { + !self.dag.shallow_since_vv().is_empty() + } + + pub fn get_greatest_timestamp(&self, frontiers: &Frontiers) -> Timestamp { + let mut max_timestamp = Timestamp::default(); + for id in frontiers.iter() { + let change = self.get_change_at(id).unwrap(); + if change.timestamp > max_timestamp { + max_timestamp = change.timestamp; + } + } + + max_timestamp + } +} + +#[derive(Debug)] +pub struct SizeInfo { + pub total_changes: usize, + pub total_ops: usize, + pub total_atom_ops: usize, + pub total_dag_node: usize, +} + +pub(crate) fn convert_change_to_remote( + arena: &SharedArena, + change: &Change, +) -> Change<RemoteOp<'static>> { + let mut ops = RleVec::new(); + for op in change.ops.iter() { + for op in local_op_to_remote(arena, op) { + ops.push(op); + } + } + + Change { + ops, + id: change.id, + deps: change.deps.clone(), + lamport: change.lamport, + timestamp: change.timestamp, + commit_msg: change.commit_msg.clone(), + } +} + +pub(crate) fn local_op_to_remote( + arena: &SharedArena, + op: &crate::op::Op, +) -> SmallVec<[RemoteOp<'static>; 1]> { + let container = arena.get_container_id(op.container).unwrap(); + let mut contents: SmallVec<[_; 1]> = SmallVec::new(); + match &op.content { + crate::op::InnerContent::List(list) => match list { + list_op::InnerListOp::Insert { slice, pos } => match container.container_type() { + loro_common::ContainerType::List | loro_common::ContainerType::MovableList => { + contents.push(RawOpContent::List(list_op::ListOp::Insert { + slice: ListSlice::RawData(Cow::Owned(slice.as_slice().to_vec())), + pos: *pos, + })) + } + _ => unreachable!(), + }, + list_op::InnerListOp::InsertText { + slice, + unicode_len: len, + pos, + } => match container.container_type() { + loro_common::ContainerType::Text => { + contents.push(RawOpContent::List(list_op::ListOp::Insert { + slice: ListSlice::RawStr { + unicode_len: *len as usize, + str: Cow::Owned(std::str::from_utf8(slice).unwrap().to_owned()), + }, + pos: *pos as usize, + })); + } + _ => unreachable!(), + }, + list_op::InnerListOp::Delete(del) => { + contents.push(RawOpContent::List(list_op::ListOp::Delete(*del))) + } + list_op::InnerListOp::StyleStart { + start, + end, + key, + value, + info, + } => contents.push(RawOpContent::List(list_op::ListOp::StyleStart { + start: *start, + end: *end, + key: key.clone(), + value: value.clone(), + info: *info, + })), + list_op::InnerListOp::StyleEnd => { + contents.push(RawOpContent::List(list_op::ListOp::StyleEnd)) + } + list_op::InnerListOp::Move { + from, + elem_id: from_id, + to, + } => contents.push(RawOpContent::List(list_op::ListOp::Move { + from: *from, + elem_id: *from_id, + to: *to, + })), + list_op::InnerListOp::Set { elem_id, value } => { + contents.push(RawOpContent::List(list_op::ListOp::Set { + elem_id: *elem_id, + value: value.clone(), + })) + } + }, + crate::op::InnerContent::Map(map) => { + let value = map.value.clone(); + contents.push(RawOpContent::Map(crate::container::map::MapSet { + key: map.key.clone(), + value, + })) + } + crate::op::InnerContent::Tree(tree) => contents.push(RawOpContent::Tree(tree.clone())), + crate::op::InnerContent::Future(f) => match f { + #[cfg(feature = "counter")] + crate::op::FutureInnerContent::Counter(c) => contents.push(RawOpContent::Counter(*c)), + FutureInnerContent::Unknown { prop, value } => { + contents.push(crate::op::RawOpContent::Unknown { + prop: *prop, + value: (**value).clone(), + }) + } + }, + }; + + let mut ans = SmallVec::with_capacity(contents.len()); + for content in contents { + ans.push(RemoteOp { + container: container.clone(), + content, + counter: op.counter, + }) + } + ans +} + +pub(crate) fn get_timestamp_now_txn() -> Timestamp { + (get_sys_timestamp() as Timestamp + 500) / 1000 +} + +#[cfg(test)] +mod visible_op_count_tests { + use crate::{cursor::PosType, loro::ExportMode, LoroDoc}; + + /// The cached `visible_op_count` (bumped incrementally for local ops, and + /// the only value read in release builds where `can_lock_in_this_thread` + /// returns false) must always equal a from-scratch recompute. + #[test] + fn cached_visible_op_count_matches_exact() { + let doc = LoroDoc::new(); + let text = doc.get_text("text"); + let mut txn = doc.txn().unwrap(); + for i in 0..50 { + text.insert_with_txn(&mut txn, i, "a", PosType::Unicode) + .unwrap(); + } + txn.commit().unwrap(); + { + let oplog = doc.oplog().lock(); + assert_eq!( + oplog.cached_visible_op_count(), + oplog.visible_op_count_exact(), + "after local edits" + ); + } + + // Import keeps the cached count exact via full refresh; subsequent local + // edits then increment from that exact base. + let doc2 = LoroDoc::new(); + doc2.import(&doc.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + let text2 = doc2.get_text("text"); + let mut txn2 = doc2.txn().unwrap(); + text2 + .insert_with_txn(&mut txn2, 0, "bbb", PosType::Unicode) + .unwrap(); + txn2.commit().unwrap(); + { + let oplog = doc2.oplog().lock(); + assert_eq!( + oplog.cached_visible_op_count(), + oplog.visible_op_count_exact(), + "after import + local edits" + ); + } + } +} diff --git a/vendor/loro-internal/src/oplog/change_store.rs b/vendor/loro-internal/src/oplog/change_store.rs new file mode 100644 index 0000000..f8f85d8 --- /dev/null +++ b/vendor/loro-internal/src/oplog/change_store.rs @@ -0,0 +1,3274 @@ +use self::block_encode::{ + decode_block, decode_cids, decode_header, encode_block, ChangesBlockHeader, +}; +use super::{loro_dag::AppDagNodeInner, AppDagNode}; +use crate::sync::Mutex; +use crate::{ + arena::{ArenaExtent, CreatorOp, SharedArena, SharedArenaRollback}, + change::Change, + estimated_size::EstimatedSize, + kv_store::KvStore, + op::Op, + parent::register_container_and_parent_link, + version::{Frontiers, ImVersionVector}, + InternalString, VersionVector, +}; +use block_encode::decode_block_range; +use bytes::Bytes; +use loro_common::{ + ContainerID, Counter, HasCounterSpan, HasId, HasIdSpan, HasLamportSpan, IdLp, IdSpan, Lamport, + LoroError, LoroResult, PeerID, ID, +}; +use loro_kv_store::{mem_store::MemKvConfig, MemKvStore}; +use once_cell::sync::OnceCell; +use rle::{HasLength, Mergable, RlePush, RleVec, Sliceable}; +use rustc_hash::{FxHashMap, FxHashSet}; +use std::sync::atomic::AtomicI64; +#[cfg(test)] +use std::sync::atomic::AtomicUsize; +use std::{ + cmp::Ordering, + collections::{BTreeMap, VecDeque}, + ops::{Bound, Deref}, + sync::Arc, +}; +use tracing::{info_span, warn}; +mod block_encode; +pub(crate) use block_encode::encode_block as encode_change_block; +mod block_meta_encode; +pub(super) mod iter; + +#[cfg(not(test))] +const MAX_BLOCK_SIZE: usize = 1024 * 4; +#[cfg(test)] +const MAX_BLOCK_SIZE: usize = 128; +const MAX_ROOT_HISTORY_NAME_BYTES: usize = 256 * 1024; + +/// # Invariance +/// +/// - We don't allow holes in a block or between two blocks with the same peer id. +/// The [Change] should be continuous for each peer. +/// - However, the first block of a peer can have counter > 0 so that we can trim the history. +/// +/// # Locking +/// +/// Take the locks in this order, and release them before calling out: `root_history_names`, +/// `external_kv`, `inner`, `external_vv`. Parsing a block takes the arena's lock under them. +/// `parse_failures` is a leaf: it is taken under any of them and takes nothing itself. +/// Most callers hold the document's op log lock, which serializes them, but the arena's +/// creator resolver ([`ChangeStore::creator_resolver`]) does not, so a method that takes two +/// of these locks in another order can deadlock against it. See +/// `context/arena-parent-links.md`. +/// +/// # Encoding Schema +/// +/// It's based on the underlying KV store. +/// +/// The entries of the KV store is made up of the following fields +/// +/// |Key |Value | +/// |:-- |:---- | +/// |b"vv" |VersionVector | +/// |b"fr" |Frontiers | +/// |b"sv" |Shallow VV | +/// |b"sf" |Shallow Frontiers | +/// |12 bytes PeerID + Counter |Encoded Block | +#[derive(Debug, Clone)] +pub struct ChangeStore { + inner: Arc<Mutex<ChangeStoreInner>>, + arena: SharedArena, + /// A change may be in external_kv or in the mem_parsed_kv. + /// mem_parsed_kv is more up-to-date. + /// + /// We cannot directly write into the external_kv except from the initial load + external_kv: Arc<Mutex<dyn KvStore>>, + /// The version vector of the external kv store. + external_vv: Arc<Mutex<VersionVector>>, + merge_interval: Arc<AtomicI64>, + root_history_names: Arc<Mutex<RootHistoryNamesState>>, + parse_failures: Arc<ParseFailures>, + #[cfg(test)] + root_history_scan_count: Arc<AtomicUsize>, +} + +/// The blocks of a store that could not be decoded or parsed. +/// +/// Snapshot import validates the KV checksums, so such a block is forged or truncated +/// external input. Every reader of the store answers "no such change" for it, because most +/// of them cannot return an error. They all record it here, so the document's fallible entry +/// points can refuse to work from a partial history. See `context/arena-parent-links.md`. +#[derive(Debug, Default)] +struct ParseFailures { + /// The first block that failed, with its error. + first: Mutex<Option<(ID, Box<str>)>>, +} + +impl ParseFailures { + fn record(&self, block_id: ID, err: &LoroError) { + let mut first = self.first.lock(); + if first.is_none() { + *first = Some((block_id, err.to_string().into_boxed_str())); + } + } +} + +/// A conservative, size-capped set of every top-level root name that appears in the store's +/// history. It only answers "may history have touched this root?", so retaining stale names +/// (e.g. from a rolled-back import) is harmless — it just forces the general diff path. +#[derive(Debug, Default)] +enum RootHistoryNamesState { + #[default] + Uninitialized, + Valid { + names: FxHashSet<InternalString>, + name_bytes: usize, + }, + Invalid, +} + +/// Return false when retaining the name would exceed the fixed memory bound. +fn record_root_name( + names: &mut FxHashSet<InternalString>, + name_bytes: &mut usize, + cid: &ContainerID, +) -> bool { + let ContainerID::Root { name, .. } = cid else { + return true; + }; + if cid.is_mergeable() || names.contains(name) { + return true; + } + + let Some(new_bytes) = name_bytes.checked_add(name.len()) else { + return false; + }; + if new_bytes > MAX_ROOT_HISTORY_NAME_BYTES { + return false; + } + + names.insert(name.clone()); + *name_bytes = new_bytes; + true +} + +#[derive(Debug, Clone)] +struct ChangeStoreInner { + /// The start version vector of the first block for each peer. + /// It allows us to trim the history + start_vv: ImVersionVector, + /// The last version of the shallow history. + start_frontiers: Frontiers, + /// It's more like a parsed cache for binary_kv. + mem_parsed_kv: BTreeMap<ID, Arc<ChangesBlock>>, + /// Set by [`ChangeStore::retire`]: the op log replaced this store, so loading from it + /// must not register anything in the arena any more. + retired: bool, + /// Conservative until a full history walk: headers do not validate block bodies. + may_have_unparsed_bodies: bool, +} + +#[derive(Debug)] +pub(crate) struct ChangeStoreRollback { + old_vv: Arc<VersionVector>, + /// Pre-scope blocks that an import appended to, keyed by block id. `None` means the + /// block was flushed, so its KV copy is the pre-scope version. + blocks_before_mutation: BTreeMap<ID, Option<BlockShape>>, +} + +/// What an unflushed block looked like before an import appended to it. +/// +/// Imports only append to a block (`ChangesBlock::push_change`): they push changes, +/// or push ops onto its last change, where an op may merge into the last op. So the +/// shape only needs the change count, the last change's op count and its last op. +/// Keeping an `Arc` of the whole block instead made the next append copy the block's +/// changes, and cloning the last change costs as much once remote changes keep +/// merging into it. +#[derive(Debug)] +struct BlockShape { + counter_end: Counter, + lamport_end: Lamport, + estimated_size: usize, + n_changes: usize, + /// `(merged op count, last op)` of the last change. + last_change_ops: Option<(usize, Option<Op>)>, +} + +impl ChangeStoreRollback { + pub(crate) fn new(old_vv: Arc<VersionVector>) -> Self { + Self { + old_vv, + blocks_before_mutation: BTreeMap::new(), + } + } + + /// The version when the import scope began. + pub(crate) fn old_vv(&self) -> &VersionVector { + &self.old_vv + } + + fn record_block_before_mutation(&mut self, id: ID, block: &ChangesBlock) { + let old_end = self.old_vv.get(&id.peer).copied().unwrap_or(0); + if id.counter >= old_end { + return; + } + + self.blocks_before_mutation.entry(id).or_insert_with(|| { + if block.flushed { + return None; + } + let changes = block + .content + .try_changes() + .expect("an unflushed block always holds parsed changes"); + Some(BlockShape { + counter_end: block.counter_range.1, + lamport_end: block.lamport_range.1, + estimated_size: block.estimated_size, + n_changes: changes.len(), + last_change_ops: changes.last().map(|c| (c.ops.len(), c.ops.last().cloned())), + }) + }); + } +} + +#[derive(Debug, Clone)] +pub(crate) struct ChangesBlock { + peer: PeerID, + counter_range: (Counter, Counter), + lamport_range: (Lamport, Lamport), + /// Estimated size of the block in bytes + estimated_size: usize, + flushed: bool, + content: ChangesBlockContent, + /// Where the arena reached when `content` was parsed from its bytes (`Both`). See + /// [`ChangeStore::rollback_arena`]. + parsed_extent: ArenaExtent, +} + +#[derive(Clone)] +pub(crate) enum ChangesBlockContent { + Changes(Arc<Vec<Change>>), + Bytes(ChangesBlockBytes), + Both(Arc<Vec<Change>>, ChangesBlockBytes), +} + +/// It's cheap to clone this struct because it's cheap to clone the bytes +#[derive(Clone)] +pub(crate) struct ChangesBlockBytes { + bytes: Bytes, + header: OnceCell<Arc<ChangesBlockHeader>>, +} + +pub const START_VV_KEY: &[u8] = b"sv"; +pub const START_FRONTIERS_KEY: &[u8] = b"sf"; +pub const VV_KEY: &[u8] = b"vv"; +pub const FRONTIERS_KEY: &[u8] = b"fr"; + +impl ChangeStore { + pub fn new_mem(a: &SharedArena, merge_interval: Arc<AtomicI64>) -> Self { + Self { + inner: Arc::new(Mutex::new(ChangeStoreInner { + start_vv: ImVersionVector::new(), + start_frontiers: Frontiers::default(), + mem_parsed_kv: BTreeMap::new(), + retired: false, + may_have_unparsed_bodies: false, + })), + arena: a.clone(), + external_vv: Arc::new(Mutex::new(VersionVector::new())), + external_kv: Arc::new(Mutex::new(MemKvStore::new(MemKvConfig::default()))), + // external_kv: Arc::new(Mutex::new(BTreeMap::default())), + merge_interval, + root_history_names: Arc::new(Mutex::new(RootHistoryNamesState::Uninitialized)), + parse_failures: Default::default(), + #[cfg(test)] + root_history_scan_count: Arc::new(AtomicUsize::new(0)), + } + } + + #[cfg(test)] + fn new_for_test() -> Self { + Self::new_mem(&SharedArena::new(), Arc::new(AtomicI64::new(0))) + } + + pub(super) fn encode_all(&self, vv: &VersionVector, frontiers: &Frontiers) -> Bytes { + self.flush_and_compact(vv, frontiers); + let mut kv = self.external_kv.lock(); + kv.export_all() + } + + #[tracing::instrument(skip(self), level = "debug")] + pub(super) fn export_from( + &self, + start_vv: &VersionVector, + start_frontiers: &Frontiers, + latest_vv: &VersionVector, + latest_frontiers: &Frontiers, + ) -> Bytes { + let new_store = ChangeStore::new_mem(&self.arena, self.merge_interval.clone()); + for span in latest_vv.sub_iter(start_vv) { + // PERF: this can be optimized by reusing the current encoded blocks + // In the current method, it needs to parse and re-encode the blocks + for c in self.iter_changes(span) { + let start = ((start_vv.get(&c.id.peer).copied().unwrap_or(0) - c.id.counter).max(0) + as usize) + .min(c.atom_len()); + let end = ((latest_vv.get(&c.id.peer).copied().unwrap_or(0) - c.id.counter).max(0) + as usize) + .min(c.atom_len()); + + if start == end { + continue; + } + + let ch = c.slice(start, end); + new_store.insert_change(ch, false, false); + } + } + + loro_common::debug!( + "start_vv={:?} start_frontiers={:?}", + &start_vv, + start_frontiers + ); + new_store.encode_from(start_vv, start_frontiers, latest_vv, latest_frontiers) + } + + pub(super) fn export_blocks_in_range<W: std::io::Write>(&self, spans: &[IdSpan], w: &mut W) { + // A change store needs each peer's counters to be contiguous, so merge the + // ranges of each peer and put the k-th range of every peer into the k-th + // store. The blocks of all stores are written one after another, which the + // update decoder reads the same way (loro-dev/loro#1155). + let mut ranges: FxHashMap<PeerID, Vec<(Counter, Counter)>> = FxHashMap::default(); + for span in spans { + let mut span = *span; + span.normalize_(); + let start = span.counter.start.max(0); + let end = span.counter.end.max(0); + if start < end { + ranges.entry(span.peer).or_default().push((start, end)); + } + } + + let mut layers: Vec<Vec<IdSpan>> = Vec::new(); + for (peer, mut peer_ranges) in ranges { + peer_ranges.sort_unstable(); + let mut merged: Vec<(Counter, Counter)> = Vec::with_capacity(peer_ranges.len()); + for (start, end) in peer_ranges { + match merged.last_mut() { + Some(last) if start <= last.1 => last.1 = last.1.max(end), + _ => merged.push((start, end)), + } + } + for (i, (start, end)) in merged.into_iter().enumerate() { + if layers.len() <= i { + layers.push(Vec::new()); + } + layers[i].push(IdSpan::new(peer, start, end)); + } + } + + for layer in layers { + let new_store = ChangeStore::new_mem(&self.arena, self.merge_interval.clone()); + for span in layer { + // PERF: this can be optimized by reusing the current encoded blocks + // In the current method, it needs to parse and re-encode the blocks + let Ok(changes) = self.try_iter_changes(span) else { + return; + }; + for c in changes { + let start = + ((span.counter.start - c.id.counter).max(0) as usize).min(c.atom_len()); + let end = ((span.counter.end - c.id.counter).max(0) as usize).min(c.atom_len()); + if start == end { + continue; + } + + let ch = c.slice(start, end); + new_store.insert_change(ch, false, false); + } + } + + encode_blocks_in_store(new_store, &self.arena, w); + } + } + + fn encode_from( + &self, + start_vv: &VersionVector, + start_frontiers: &Frontiers, + latest_vv: &VersionVector, + latest_frontiers: &Frontiers, + ) -> Bytes { + { + let mut store = self.external_kv.lock(); + store.set(START_VV_KEY, start_vv.encode().into()); + store.set(START_FRONTIERS_KEY, start_frontiers.encode().into()); + let mut inner = self.inner.lock(); + inner.start_frontiers = start_frontiers.clone(); + inner.start_vv = ImVersionVector::from_vv(start_vv); + } + self.flush_and_compact(latest_vv, latest_frontiers); + self.external_kv.lock().export_all() + } + + /// Read a cold block for comparison without caching parsed ops in the arena. + /// Cached parsed history keeps using the ordinary, already cheap path. + pub(crate) fn unparsed_block_bytes(&self, id: ID) -> Option<Bytes> { + let external = self.external_kv.lock(); + let inner = self.inner.lock(); + if inner.retired { + return None; + } + if let Some((_, block)) = inner.mem_parsed_kv.range(..=id).next_back() { + if block.peer == id.peer && block.counter_range.1 > id.counter { + return match &block.content { + ChangesBlockContent::Bytes(b) => Some(b.bytes.clone()), + _ => None, + }; + } + } + let (key, bytes) = external + .scan(Bound::Unbounded, Bound::Included(&id.to_bytes())) + .rfind(|(key, _)| key.len() == 12)?; + if ID::from_bytes(&key).peer != id.peer + || decode_block_range(&bytes).ok()?.0 .1 <= id.counter + { + return None; + } + Some(bytes) + } + + pub(crate) fn encoded_block_counter_range(bytes: &[u8]) -> LoroResult<(Counter, Counter)> { + Ok(decode_block_range(bytes)?.0) + } + + pub(crate) fn check_text_insert_block( + &self, + bytes: &[u8], + mut on_insert: impl FnMut(Counter, &ContainerID, u32, &str, u32, &Frontiers) -> LoroResult<()>, + ) -> LoroResult<bool> { + // This reader has stricter eligibility checks than decode_block. Only + // the normal parser may declare local history unparsable. Delay a content + // mismatch until the entire block is eligible, otherwise fall back too. + let mut comparison = Ok(()); + let result = + block_encode::visit_text_insert_block(bytes, |counter, cid, pos, text, len, deps| { + if comparison.is_ok() { + comparison = on_insert(counter, cid, pos, text, len, deps); + } + Ok(()) + }); + match result { + Ok(true) => comparison.map(|()| true), + Ok(false) | Err(_) => Ok(false), + } + } + + /// Byte-identical, fully known blocks need neither decoding nor comparison. + /// An unflushed cached block shadows its older KV copy; never compare against + /// that stale copy. Different encodings fall back to semantic comparison. + pub(crate) fn contains_encoded_block(&self, id: ID, bytes: &[u8]) -> bool { + let external = self.external_kv.lock(); + let inner = self.inner.lock(); + if let Some(block) = inner.mem_parsed_kv.get(&id) { + return match &block.content { + ChangesBlockContent::Bytes(b) | ChangesBlockContent::Both(_, b) => { + b.bytes.as_ref() == bytes + } + ChangesBlockContent::Changes(_) => false, + }; + } + external + .get(&id.to_bytes()) + .is_some_and(|b| b.as_ref() == bytes) + } + + /// Decode only unmatched snapshot blocks in a temporary arena. Known content + /// never gets copied into the document's arena; move only the checked suffix. + pub(crate) fn decode_snapshot_for_updates( + bytes: Bytes, + oplog: &crate::OpLog, + values: super::ImportedValues, + ) -> Result<Vec<Change>, LoroError> { + let arena = SharedArena::new(); + let store = ChangeStore::new_mem(&arena, Arc::new(AtomicI64::new(0))); + let _ = store.import_all(bytes)?; + let external = store.external_kv.lock(); + let mut inner = store.inner.lock(); + let mut changes = Vec::new(); + for (key, bytes) in external.scan(Bound::Unbounded, Bound::Unbounded) { + if key.len() != 12 { + continue; + } + let id = ID::from_bytes(&key); + if oplog.change_store.contains_encoded_block(id, &bytes) { + continue; + } + // import_all parsed the frontier blocks. Take their changes instead + // of parsing them again or cloning changes that will be dropped. + if let Some(block) = inner.mem_parsed_kv.remove(&id) { + let block = Arc::try_unwrap(block).expect("temporary store owns its blocks"); + match block.content { + ChangesBlockContent::Changes(c) | ChangesBlockContent::Both(c, _) => { + changes + .extend(Arc::try_unwrap(c).expect("temporary store owns its changes")); + } + ChangesBlockContent::Bytes(b) => changes.extend(b.parse(&arena)?), + } + } else { + changes.extend(Self::decode_block_bytes(bytes, &arena)?); + } + } + drop(inner); + drop(external); + changes.sort_unstable_by_key(|c| c.lamport); + let changes = oplog.check_and_trim_known_part_in_arena(changes, values, &arena)?; + Ok(changes + .into_iter() + .map(|mut change| { + let mut ops = RleVec::new(); + for op in change.ops.iter() { + for remote in super::local_op_to_remote(&arena, op) { + ops.push(oplog.arena.convert_single_op( + &remote.container, + change.id.peer, + remote.counter, + change.lamport + (remote.counter - change.id.counter) as Lamport, + remote.content, + )); + } + } + change.ops = ops; + register_container_and_parent_link(&oplog.arena, &change); + change + }) + .collect()) + } + + pub(crate) fn decode_block_bytes(bytes: Bytes, arena: &SharedArena) -> LoroResult<Vec<Change>> { + ChangesBlockBytes::new(bytes).parse(arena) + } + + /// Reuse the header on fallback so a new block is decoded only once. + pub(crate) fn decode_update_block( + &self, + bytes: Bytes, + vv: &VersionVector, + ) -> LoroResult<Vec<Change>> { + let block = ChangesBlockBytes::new(bytes); + block.ensure_header()?; + let header = block.header.get().unwrap(); + let id = ID::new(header.peer, header.counter); + if header.counters.last().copied().unwrap_or(0) + <= vv.get(&header.peer).copied().unwrap_or(0) + && self.contains_encoded_block(id, &block.bytes) + { + Ok(Vec::new()) + } else { + block.parse(&self.arena) + } + } + + /// Rolls back the store and the arena (to `arena`, the checkpoint taken when the import + /// began). See [`Self::rollback_arena`]. + pub(crate) fn rollback_import( + &self, + rollback: ChangeStoreRollback, + arena: SharedArenaRollback, + ) { + let mut inner = self.inner.lock(); + Self::rollback_changes_in(&self.arena, &mut inner, rollback); + self.rollback_arena_in(&mut inner, arena); + } + + /// [`Self::rollback_import`] without rolling the arena back: everything registered in it + /// since the scope began stays registered. For a scope that only held changes whose + /// containers were registered before it (a rolled back local transaction), where freeing + /// the registrations made while undoing it from the state would leave state entries at + /// freed indices. + pub(crate) fn rollback_import_keeping_arena(&self, rollback: ChangeStoreRollback) { + let mut inner = self.inner.lock(); + Self::rollback_changes_in(&self.arena, &mut inner, rollback); + } + + fn rollback_changes_in( + arena: &SharedArena, + inner: &mut ChangeStoreInner, + rollback: ChangeStoreRollback, + ) { + // The name set may already include names from changes this rollback removes. That is + // fine: stale names only make `old_history_may_touch_root_names` conservatively true. + let mut touched_peers = FxHashSet::default(); + inner.mem_parsed_kv.retain(|id, _| { + let old_end = rollback.old_vv.get(&id.peer).copied().unwrap_or(0); + let keep = id.counter < old_end; + if !keep { + touched_peers.insert(id.peer); + } + keep + }); + + for (id, shape) in rollback.blocks_before_mutation { + touched_peers.insert(id.peer); + let Some(shape) = shape else { + // Flushed before the scope: the KV copy is the pre-scope block. + inner.mem_parsed_kv.remove(&id); + continue; + }; + let block = inner + .mem_parsed_kv + .get_mut(&id) + .expect("a block appended to during the scope stays cached"); + let block = Arc::make_mut(block); + let changes = Arc::make_mut( + block + .content + .changes_mut(arena) + .expect("an unflushed block always holds parsed changes"), + ); + changes.truncate(shape.n_changes); + if let Some((n_ops, last_op)) = shape.last_change_ops { + let ops = changes.last_mut().unwrap().ops.vec_mut(); + ops.truncate(n_ops); + if let Some(last_op) = last_op { + *ops.last_mut().unwrap() = last_op; + } + } + block.counter_range.1 = shape.counter_end; + block.lamport_range.1 = shape.lamport_end; + block.estimated_size = shape.estimated_size; + } + + // `insert_change_inner` merges a change into the cached block right before it. + // A read during the scope (e.g. an lamport lookup) may have cached an older + // KV block of a touched peer, and removing the scope's newer blocks leaves it + // in front of the next insert with a counter gap ("counter should be + // continuous"). Blocks that are flushed are identical to their KV copy, so + // evict them; they are reloaded on demand. + if !touched_peers.is_empty() { + inner + .mem_parsed_kv + .retain(|id, block| !block.flushed || !touched_peers.contains(&id.peer)); + } + } + + /// Rolls the arena back to `arena`, a checkpoint taken before a failed import, and drops + /// the parsed changes of the cached blocks that were parsed since. Every arena rollback must + /// go through here (or [`Self::rollback_import`] / [`Self::retire`]). + /// + /// Parsing a block registers the containers its ops use with their parent links and + /// allocates their values. The arena rollback truncates the values and text allocated after + /// the checkpoint and drops the parent links of containers registered after it (their + /// indices stay; see `SharedArena::rollback`), so a block parsed in between may hold value + /// slices that no longer exist, and parsing it again is what registers those links again. + /// Such a block keeps only its bytes, so the next access parses and registers again. A block parsed before the checkpoint can only refer to what was there + /// then (its `parsed_extent`), and keeps its parsed changes. A block without bytes was built + /// in memory from changes inserted before the import, whose containers were registered + /// then. + /// + /// This happens under `inner`, where blocks are parsed. The creator resolver parses + /// without the op log lock, so otherwise it could parse a block after the bytes are + /// restored and before the arena is rolled back. + pub(crate) fn rollback_arena(&self, arena: SharedArenaRollback) { + let mut inner = self.inner.lock(); + self.rollback_arena_in(&mut inner, arena); + } + + fn rollback_arena_in(&self, inner: &mut ChangeStoreInner, arena: SharedArenaRollback) { + let mut dropped_body = false; + for block in inner.mem_parsed_kv.values_mut() { + if let ChangesBlockContent::Both(_, bytes) = &block.content { + if !arena.keeps(block.parsed_extent) { + let bytes = bytes.clone(); + Arc::make_mut(block).content = ChangesBlockContent::Bytes(bytes); + dropped_body = true; + } + } + } + inner.may_have_unparsed_bodies |= dropped_body; + self.arena.rollback(arena); + } + + /// Rolls the arena back to `arena` after the op log replaced this store (a failed + /// snapshot import), and stops loading from it. A creator resolver that reached this store + /// before the replacement then finds nothing instead of registering containers of the + /// discarded history in the arena. + pub(crate) fn retire(&self, arena: SharedArenaRollback) { + let mut inner = self.inner.lock(); + self.arena.rollback(arena); + inner.mem_parsed_kv.clear(); + inner.retired = true; + } + + pub fn get_dag_nodes_that_contains(&self, id: ID) -> Option<Vec<AppDagNode>> { + let block = self.get_block_that_contains(id)?; + Some(block.content.iter_dag_nodes()) + } + + pub fn get_last_dag_nodes_for_peer(&self, peer: PeerID) -> Option<Vec<AppDagNode>> { + let block = self.get_the_last_block_of_peer(peer)?; + Some(block.content.iter_dag_nodes()) + } + + /// Whether diff calculation may still encounter an unvalidated snapshot body. + /// Loading all DAG headers cannot clear this; only a successful full body walk can. + pub(crate) fn may_have_unparsed_bodies(&self) -> bool { + self.inner.lock().may_have_unparsed_bodies + } + + pub fn visit_all_changes(&self, f: &mut dyn FnMut(&Change)) { + self.ensure_block_loaded_in_range(Bound::Unbounded, Bound::Unbounded); + let mut inner = self.inner.lock(); + for (id, block) in inner.mem_parsed_kv.iter_mut() { + if let Err(err) = block.ensure_changes(&self.arena) { + warn!(block_id = ?id, ?err, "failed to parse change block"); + self.parse_failures.record(*id, &err); + continue; + } + for c in block.content.try_changes().unwrap() { + f(c); + } + } + if self.corrupt_block_error().is_ok() { + inner.may_have_unparsed_bodies = false; + } + } + + fn build_root_history_names(&self) -> RootHistoryNamesState { + let mut names = FxHashSet::default(); + let mut name_bytes = 0; + + { + let external = self.external_kv.lock(); + for (key, bytes) in external.scan(Bound::Unbounded, Bound::Unbounded) { + if key.len() != 12 { + continue; + } + let header = match decode_header(&bytes) + .and_then(|header| decode_cids(&bytes, Some(header))) + { + Ok(header) => header, + Err(_) => return RootHistoryNamesState::Invalid, + }; + let Some(cids) = header.cids.get() else { + return RootHistoryNamesState::Invalid; + }; + for cid in cids.iter() { + if !record_root_name(&mut names, &mut name_bytes, cid) { + return RootHistoryNamesState::Invalid; + } + } + } + } + + let inner = self.inner.lock(); + for block in inner.mem_parsed_kv.values() { + match &block.content { + ChangesBlockContent::Changes(changes) | ChangesBlockContent::Both(changes, _) => { + for change in changes.iter() { + for op in change.ops.iter() { + let Some(cid) = self.arena.idx_to_id(op.container) else { + return RootHistoryNamesState::Invalid; + }; + if !record_root_name(&mut names, &mut name_bytes, &cid) { + return RootHistoryNamesState::Invalid; + } + } + } + } + ChangesBlockContent::Bytes(bytes) => { + let header = bytes.header.get().map(|header| header.as_ref().clone()); + let header = match decode_cids(&bytes.bytes, header) { + Ok(header) => header, + Err(_) => return RootHistoryNamesState::Invalid, + }; + let Some(cids) = header.cids.get() else { + return RootHistoryNamesState::Invalid; + }; + for cid in cids.iter() { + if !record_root_name(&mut names, &mut name_bytes, cid) { + return RootHistoryNamesState::Invalid; + } + } + } + } + } + + RootHistoryNamesState::Valid { names, name_bytes } + } + + fn record_change_in_root_history_names(&self, change: &Change) { + let mut cached = self.root_history_names.lock(); + let RootHistoryNamesState::Valid { names, name_bytes } = &mut *cached else { + return; + }; + + for op in change.ops.iter() { + let recorded = self + .arena + .idx_to_id(op.container) + .is_some_and(|cid| record_root_name(names, name_bytes, &cid)); + if !recorded { + *cached = RootHistoryNamesState::Invalid; + return; + } + } + } + + /// Return whether the history already in this store may have touched any top-level root in + /// `names`. Must be called before the candidate changes are inserted. + /// + /// The first call scans encoded block container arenas without parsing operations or + /// populating the parsed-change cache; later inserts update the cached name set, so repeated + /// independent imports do not rescan the old history. Decode failures or exceeding the size + /// cap permanently disable this optimization for the store. + pub(crate) fn old_history_may_touch_root_names( + &self, + names: &FxHashSet<InternalString>, + ) -> bool { + if names.is_empty() { + return false; + } + + let mut cached = self.root_history_names.lock(); + if matches!(*cached, RootHistoryNamesState::Uninitialized) { + #[cfg(test)] + self.root_history_scan_count + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + *cached = self.build_root_history_names(); + } + + match &*cached { + RootHistoryNamesState::Valid { + names: history_names, + .. + } => names.iter().any(|name| history_names.contains(name)), + RootHistoryNamesState::Invalid | RootHistoryNamesState::Uninitialized => true, + } + } + + #[cfg(test)] + pub(crate) fn root_history_scan_count_for_test(&self) -> usize { + self.root_history_scan_count + .load(std::sync::atomic::Ordering::Relaxed) + } + + pub(crate) fn iter_blocks(&self, id_span: IdSpan) -> Vec<(Arc<ChangesBlock>, usize, usize)> { + self.iter_blocks_inner(id_span, false).unwrap() + } + + fn try_iter_blocks( + &self, + id_span: IdSpan, + ) -> LoroResult<Vec<(Arc<ChangesBlock>, usize, usize)>> { + self.iter_blocks_inner(id_span, true) + } + + fn iter_blocks_inner( + &self, + id_span: IdSpan, + fail_on_corrupt: bool, + ) -> LoroResult<Vec<(Arc<ChangesBlock>, usize, usize)>> { + if id_span.counter.start == id_span.counter.end { + return Ok(vec![]); + } + assert!(id_span.counter.start < id_span.counter.end); + if fail_on_corrupt { + self.try_ensure_block_loaded_in_range( + Bound::Included(id_span.id_start()), + Bound::Excluded(id_span.id_end()), + )?; + } else { + self.ensure_block_loaded_in_range( + Bound::Included(id_span.id_start()), + Bound::Excluded(id_span.id_end()), + ); + } + let mut inner = self.inner.lock(); + let start_counter = inner + .mem_parsed_kv + .range(..=id_span.id_start()) + .next_back() + .filter(|(id, _)| id.peer == id_span.peer) + .map_or(id_span.counter.start, |(id, _)| id.counter); + let mut blocks = Vec::new(); + for (block_id, block) in inner.mem_parsed_kv.range_mut( + ID::new(id_span.peer, start_counter)..ID::new(id_span.peer, id_span.counter.end), + ) { + if block.counter_range.1 < id_span.counter.start { + continue; + } + if let Err(err) = block.ensure_changes(&self.arena) { + warn!(?block_id, ?err, "failed to parse change block"); + self.parse_failures.record(*block_id, &err); + if fail_on_corrupt { + return Err(self.corrupt_block_error().unwrap_err()); + } + continue; + } + let changes = block.content.try_changes().unwrap(); + let (start, end) = if id_span.counter.start <= block.counter_range.0 + && id_span.counter.end >= block.counter_range.1 + { + (0, changes.len()) + } else { + let start = block + .get_change_index_by_counter(id_span.counter.start) + .unwrap_or_else(|x| x); + let end = match block.get_change_index_by_counter(id_span.counter.end - 1) { + Ok(end) => end + 1, + Err(0) => continue, + Err(end) => end, + }; + (start, end) + }; + if start != end { + blocks.push((block.clone(), start, end)); + } + } + Ok(blocks) + } + + pub fn iter_changes(&self, id_span: IdSpan) -> impl Iterator<Item = BlockChangeRef> + '_ { + let v = self.iter_blocks(id_span); + #[cfg(debug_assertions)] + { + if !v.is_empty() && self.corrupt_block_error().is_ok() { + assert_eq!(v[0].0.peer, id_span.peer); + assert_eq!(v.last().unwrap().0.peer, id_span.peer); + { + // Test start + let (block, start, _end) = v.first().unwrap(); + let changes = block.content.try_changes().unwrap(); + assert!(changes[*start].id.counter <= id_span.counter.start); + } + { + // Test end + let (block, _start, end) = v.last().unwrap(); + let changes = block.content.try_changes().unwrap(); + assert!(changes[*end - 1].ctr_end() >= id_span.counter.end); + assert!(changes[*end - 1].id.counter < id_span.counter.end); + } + } + } + + v.into_iter().flat_map(move |(block, start, end)| { + (start..end).map(move |i| BlockChangeRef { + change_index: i, + block: block.clone(), + }) + }) + } + + /// Parse the range before handing any changes to a consumer: a missing middle + /// block must not become a counter gap in an export's scratch store. + pub(crate) fn try_iter_changes( + &self, + id_span: IdSpan, + ) -> LoroResult<impl Iterator<Item = BlockChangeRef>> { + let blocks = self.try_iter_blocks(id_span)?; + Ok(blocks.into_iter().flat_map(|(block, start, end)| { + (start..end).map(move |change_index| BlockChangeRef { + change_index, + block: block.clone(), + }) + })) + } + + #[allow(dead_code)] + pub(crate) fn get_blocks_in_range(&self, id_span: IdSpan) -> VecDeque<Arc<ChangesBlock>> { + let mut inner = self.inner.lock(); + let start_counter = inner + .mem_parsed_kv + .range(..=id_span.id_start()) + .next_back() + .map(|(id, _)| id.counter) + .unwrap_or(0); + let vec = inner + .mem_parsed_kv + .range_mut( + ID::new(id_span.peer, start_counter)..ID::new(id_span.peer, id_span.counter.end), + ) + .filter_map(|(_id, block)| { + if block.counter_range.1 < id_span.counter.start { + return None; + } + + if let Err(err) = block.ensure_changes(&self.arena) { + warn!(block_id = ?_id, ?err, "failed to parse change block"); + self.parse_failures.record(*_id, &err); + return None; + } + Some(block.clone()) + }) + // TODO: PERF avoid alloc + .collect(); + vec + } + + pub(crate) fn get_block_that_contains(&self, id: ID) -> Option<Arc<ChangesBlock>> { + self.ensure_block_loaded_in_range(Bound::Included(id), Bound::Included(id)); + let inner = self.inner.lock(); + let block = inner + .mem_parsed_kv + .range(..=id) + .next_back() + .filter(|(_, block)| { + block.peer == id.peer + && block.counter_range.0 <= id.counter + && id.counter < block.counter_range.1 + }) + .map(|(_, block)| block.clone()); + + block + } + + pub(crate) fn get_the_last_block_of_peer(&self, peer: PeerID) -> Option<Arc<ChangesBlock>> { + let end_id = ID::new(peer, Counter::MAX); + self.ensure_id_lte(end_id); + let inner = self.inner.lock(); + let block = inner + .mem_parsed_kv + .range(..=end_id) + .next_back() + .filter(|(_, block)| block.peer == peer) + .map(|(_, block)| block.clone()); + + block + } + + pub fn change_num(&self) -> usize { + self.ensure_block_loaded_in_range(Bound::Unbounded, Bound::Unbounded); + let mut inner = self.inner.lock(); + inner + .mem_parsed_kv + .iter_mut() + .map(|(_, block)| block.change_num()) + .sum() + } + + pub fn fork( + &self, + arena: SharedArena, + merge_interval: Arc<AtomicI64>, + vv: &VersionVector, + frontiers: &Frontiers, + ) -> Self { + self.flush_and_compact(vv, frontiers); + let external_kv = self.external_kv.lock().clone_store(); + let inner = self.inner.lock(); + Self { + inner: Arc::new(Mutex::new(ChangeStoreInner { + start_vv: inner.start_vv.clone(), + start_frontiers: inner.start_frontiers.clone(), + mem_parsed_kv: BTreeMap::new(), + retired: false, + may_have_unparsed_bodies: !vv.is_empty(), + })), + arena, + external_vv: Arc::new(Mutex::new(self.external_vv.lock().clone())), + external_kv, + merge_interval, + root_history_names: Arc::new(Mutex::new(RootHistoryNamesState::Uninitialized)), + parse_failures: Default::default(), + #[cfg(test)] + root_history_scan_count: Arc::new(AtomicUsize::new(0)), + } + } + + pub fn kv_size(&self) -> usize { + self.external_kv + .lock() + .scan(Bound::Unbounded, Bound::Unbounded) + .map(|(k, v)| k.len() + v.len()) + .sum() + } + + pub(crate) fn export_blocks_from<W: std::io::Write>( + &self, + start_vv: &VersionVector, + shallow_since_vv: &ImVersionVector, + latest_vv: &VersionVector, + w: &mut W, + ) { + let new_store = ChangeStore::new_mem(&self.arena, self.merge_interval.clone()); + for mut span in latest_vv.sub_iter(start_vv) { + let counter_lower_bound = shallow_since_vv.get(&span.peer).copied().unwrap_or(0); + span.counter.start = span.counter.start.max(counter_lower_bound); + span.counter.end = span.counter.end.max(counter_lower_bound); + if span.counter.start >= span.counter.end { + continue; + } + + // PERF: this can be optimized by reusing the current encoded blocks + // In the current method, it needs to parse and re-encode the blocks + let Ok(changes) = self.try_iter_changes(span) else { + return; + }; + for c in changes { + let start = ((start_vv.get(&c.id.peer).copied().unwrap_or(0) - c.id.counter).max(0) + as usize) + .min(c.atom_len()); + let end = ((latest_vv.get(&c.id.peer).copied().unwrap_or(0) - c.id.counter).max(0) + as usize) + .min(c.atom_len()); + + assert_ne!(start, end); + let ch = c.slice(start, end); + new_store.insert_change(ch, false, false); + } + } + + let arena = &self.arena; + encode_blocks_in_store(new_store, arena, w); + } + + pub(crate) fn fork_changes_up_to( + &self, + start_vv: &ImVersionVector, + frontiers: &Frontiers, + vv: &VersionVector, + ) -> LoroResult<Bytes> { + let new_store = ChangeStore::new_mem(&self.arena, self.merge_interval.clone()); + for mut span in vv.sub_iter_im(start_vv) { + let counter_lower_bound = start_vv.get(&span.peer).copied().unwrap_or(0); + span.counter.start = span.counter.start.max(counter_lower_bound); + span.counter.end = span.counter.end.max(counter_lower_bound); + if span.counter.start >= span.counter.end { + continue; + } + + // PERF: this can be optimized by reusing the current encoded blocks + // In the current method, it needs to parse and re-encode the blocks + for c in self.try_iter_changes(span)? { + let start = ((start_vv.get(&c.id.peer).copied().unwrap_or(0) - c.id.counter).max(0) + as usize) + .min(c.atom_len()); + let end = ((vv.get(&c.id.peer).copied().unwrap_or(0) - c.id.counter).max(0) + as usize) + .min(c.atom_len()); + + assert_ne!(start, end); + let ch = c.slice(start, end); + new_store.insert_change(ch, false, false); + } + } + + Ok(new_store.encode_all(vv, frontiers)) + } +} + +fn encode_blocks_in_store<W: std::io::Write>( + new_store: ChangeStore, + arena: &SharedArena, + w: &mut W, +) { + let mut inner = new_store.inner.lock(); + for (_id, block) in inner.mem_parsed_kv.iter_mut() { + let bytes = block.to_bytes(arena); + leb128::write::unsigned(w, bytes.bytes.len() as u64).unwrap(); + w.write_all(&bytes.bytes).unwrap(); + } +} + +mod mut_external_kv { + //! Only this module contains the code that mutate the external kv store + //! All other modules should only read from the external kv store + use super::*; + + impl ChangeStore { + #[tracing::instrument(skip_all, level = "debug", name = "change_store import_all")] + pub(crate) fn import_all(&self, bytes: Bytes) -> Result<BatchDecodeInfo, LoroError> { + let mut kv_store = self.external_kv.lock(); + assert!( + // 2 because there are vv and frontiers + kv_store.len() <= 2, + "kv store should be empty when using decode_all" + ); + // Snapshot/update bytes are external input. Validate the checksums embedded in each + // SSTable block as well as the document envelope so malformed lazy blocks are rejected + // during import instead of surfacing from a later read. + kv_store + .import_all(bytes) + .map_err(|e| LoroError::DecodeError(e.into_boxed_str()))?; + drop(kv_store); + *self.root_history_names.lock() = RootHistoryNamesState::Uninitialized; + let vv_bytes = self.external_kv.lock().get(VV_KEY).unwrap_or_default(); + let vv = VersionVector::decode(&vv_bytes) + .map_err(|_| LoroError::DecodeDataCorruptionError)?; + let start_vv_bytes = self + .external_kv + .lock() + .get(START_VV_KEY) + .unwrap_or_default(); + let start_vv = if start_vv_bytes.is_empty() { + Default::default() + } else { + VersionVector::decode(&start_vv_bytes) + .map_err(|_| LoroError::DecodeDataCorruptionError)? + }; + + #[cfg(test)] + { + // This is for tests + for (peer, cnt) in vv.iter() { + self.get_change(ID::new(*peer, *cnt - 1)) + .ok_or(LoroError::DecodeDataCorruptionError)?; + } + } + + self.inner.lock().may_have_unparsed_bodies = !vv.is_empty(); + *self.external_vv.lock() = vv.clone(); + let frontiers_bytes = self + .external_kv + .lock() + .get(FRONTIERS_KEY) + .unwrap_or_default(); + let frontiers = Frontiers::decode(&frontiers_bytes) + .map_err(|_| LoroError::DecodeDataCorruptionError)?; + let start_frontiers = self + .external_kv + .lock() + .get(START_FRONTIERS_KEY) + .unwrap_or_default(); + let start_frontiers = if start_frontiers.is_empty() { + Default::default() + } else { + Frontiers::decode(&start_frontiers) + .map_err(|_| LoroError::DecodeDataCorruptionError)? + }; + + let mut max_lamport = None; + let mut max_timestamp = 0; + for id in frontiers.iter() { + let c = self + .get_change(id) + .ok_or(LoroError::DecodeDataCorruptionError)?; + debug_assert_ne!(c.atom_len(), 0); + let l = c.lamport_last(); + if let Some(x) = max_lamport { + if l > x { + max_lamport = Some(l); + } + } else { + max_lamport = Some(l); + } + + let t = c.timestamp; + if t > max_timestamp { + max_timestamp = t; + } + } + + Ok(BatchDecodeInfo { + vv, + frontiers, + start_version: if start_vv.is_empty() { + None + } else { + let mut inner = self.inner.lock(); + inner.start_frontiers = start_frontiers.clone(); + inner.start_vv = ImVersionVector::from_vv(&start_vv); + Some((start_vv, start_frontiers)) + }, + }) + } + + /// Flush the cached change to kv_store + pub(crate) fn flush_and_compact(&self, vv: &VersionVector, frontiers: &Frontiers) { + let mut store = self.external_kv.lock(); + let mut inner = self.inner.lock(); + let mut external_vv = self.external_vv.lock(); + for (id, block) in inner.mem_parsed_kv.iter_mut() { + if !block.flushed { + let id_bytes = id.to_bytes(); + let counter_start = external_vv.get(&id.peer).copied().unwrap_or(0); + assert!( + counter_start < block.counter_range.1, + "Peer={} Block Counter Range={:?}, counter_start={}", + id.peer, + &block.counter_range, + counter_start + ); + if counter_start > block.counter_range.0 { + assert!(store.get(&id_bytes).is_some()); + } + external_vv.insert(id.peer, block.counter_range.1); + let bytes = block.to_bytes(&self.arena); + store.set(&id_bytes, bytes.bytes); + Arc::make_mut(block).flushed = true; + } + } + + if inner.start_vv.is_empty() { + assert_eq!(&*external_vv, vv); + } else { + #[cfg(debug_assertions)] + { + // TODO: makes some assertions here? + } + } + let vv_bytes = vv.encode(); + let frontiers_bytes = frontiers.encode(); + store.set(VV_KEY, vv_bytes.into()); + store.set(FRONTIERS_KEY, frontiers_bytes.into()); + } + } +} + +mod mut_inner_kv { + //! Only this module contains the code that mutate the internal kv store + //! All other modules should only read from the internal kv store + + use super::*; + impl ChangeStore { + /// This method is the **only place** that push a new change into the change store + /// + /// The new change either merges with the previous block or is put into a new block. + /// This method only updates the internal kv store. + pub fn insert_change(&self, change: Change, split_when_exceeds: bool, is_local: bool) { + self.insert_change_inner(change, split_when_exceeds, is_local, None); + } + + pub(crate) fn insert_change_with_rollback( + &self, + change: Change, + split_when_exceeds: bool, + is_local: bool, + rollback: &mut ChangeStoreRollback, + ) { + self.insert_change_inner(change, split_when_exceeds, is_local, Some(rollback)); + } + + fn insert_change_inner( + &self, + mut change: Change, + split_when_exceeds: bool, + is_local: bool, + mut rollback: Option<&mut ChangeStoreRollback>, + ) { + self.record_change_in_root_history_names(&change); + + #[cfg(debug_assertions)] + { + let vv = self.external_vv.lock(); + assert!(vv.get(&change.id.peer).copied().unwrap_or(0) <= change.id.counter); + } + + let s = info_span!("change_store insert_change", id = ?change.id); + let _e = s.enter(); + let estimated_size = change.estimate_storage_size(); + if estimated_size > MAX_BLOCK_SIZE && split_when_exceeds { + self.split_change_then_insert(change, rollback.as_deref_mut()); + return; + } + + let id = change.id; + let mut inner = self.inner.lock(); + + // try to merge with previous block + if let Some((_id, block)) = inner.mem_parsed_kv.range_mut(..id).next_back() { + if block.peer == change.id.peer { + if block.counter_range.1 != change.id.counter { + panic!("counter should be continuous") + } + + if let Some(rollback) = &mut rollback { + rollback.record_block_before_mutation(*_id, block); + } + + match block.push_change( + change, + estimated_size, + if is_local { + // local change should try to merge with previous change when + // the timestamp interval <= the `merge_interval` + self.merge_interval + .load(std::sync::atomic::Ordering::Acquire) + } else { + 0 + }, + &self.arena, + ) { + Ok(_) => { + drop(inner); + debug_assert!(self.get_change(id).is_some()); + return; + } + Err(c) => change = c, + } + } + } + + inner + .mem_parsed_kv + .insert(id, Arc::new(ChangesBlock::new(change, &self.arena))); + drop(inner); + debug_assert!(self.get_change(id).is_some()); + } + + pub fn get_change(&self, id: ID) -> Option<BlockChangeRef> { + let block = self.get_parsed_block(id)?; + Some(BlockChangeRef { + change_index: block.get_change_index_by_counter(id.counter).unwrap(), + block: block.clone(), + }) + } + + /// Get the change with the given peer and lamport. + /// + /// If not found, return the change with the greatest lamport that is smaller than the given lamport. + pub fn get_change_by_lamport_lte(&self, idlp: IdLp) -> Option<BlockChangeRef> { + // This method is complicated because we impl binary search on top of the range api + // It can be simplified + // Lock order: `external_kv` before `inner`. The scan below may need it. + let kv_store = self.external_kv.lock(); + let mut inner = self.inner.lock(); + let mut iter = inner + .mem_parsed_kv + .range_mut(ID::new(idlp.peer, 0)..ID::new(idlp.peer, i32::MAX)); + + // This won't change, we only adjust upper_bound + let mut lower_bound = 0; + let mut upper_bound = i32::MAX; + let mut is_binary_searching = false; + // The binary search below can stop making progress (e.g. when + // `(lower_bound + upper_bound) / 2` becomes a fixed point while the + // target block is missing from `mem_parsed_kv`, or when block + // metadata is inconsistent). Cap its steps and fall back to the + // external kv scan, which is always correct. + let mut binary_search_steps = 0; + loop { + if is_binary_searching { + binary_search_steps += 1; + if binary_search_steps > 128 { + warn!( + "get_change_by_lamport_lte binary search did not converge; \ + falling back to kv scan" + ); + break; + } + } + match iter.next_back() { + Some((&id, block)) => { + if block.lamport_range.0 <= idlp.lamport + && (!is_binary_searching || idlp.lamport < block.lamport_range.1) + { + if !is_binary_searching + && upper_bound != i32::MAX + && upper_bound != block.counter_range.1 + { + warn!( + "There is a hole between the last block and the current block" + ); + // There is hole between the last block and the current block + // We need to load it from the kv store + break; + } + + // Found the block + if let Err(err) = block.ensure_changes(&self.arena) { + warn!(block_id = ?id, ?err, "failed to parse change block"); + self.parse_failures.record(id, &err); + return None; + } + let index = block.get_change_index_by_lamport_lte(idlp.lamport)?; + return Some(BlockChangeRef { + change_index: index, + block: block.clone(), + }); + } + + if is_binary_searching { + let mid_bound = (lower_bound + upper_bound) / 2; + if block.lamport_range.1 <= idlp.lamport { + // Target is larger than the current block (pointed by mid_bound) + lower_bound = mid_bound; + } else { + debug_assert!( + idlp.lamport < block.lamport_range.0, + "{} {:?}", + idlp, + &block.lamport_range + ); + // Target is smaller than the current block (pointed by mid_bound) + upper_bound = mid_bound; + } + + let mid_bound = (lower_bound + upper_bound) / 2; + iter = inner + .mem_parsed_kv + .range_mut(ID::new(idlp.peer, 0)..ID::new(idlp.peer, mid_bound)); + } else { + // Test whether we need to switch to binary search by measuring the gap + if block.lamport_range.0 - idlp.lamport > MAX_BLOCK_SIZE as Lamport * 8 + { + // Use binary search to find the block + upper_bound = id.counter; + let mid_bound = (lower_bound + upper_bound) / 2; + iter = inner.mem_parsed_kv.range_mut( + ID::new(idlp.peer, 0)..ID::new(idlp.peer, mid_bound), + ); + is_binary_searching = true; + } + + upper_bound = id.counter; + } + } + None => { + if !is_binary_searching { + break; + } + + let mid_bound = (lower_bound + upper_bound) / 2; + lower_bound = mid_bound; + if upper_bound - lower_bound <= MAX_BLOCK_SIZE as i32 { + // If they are too close, we can just scan the range + iter = inner.mem_parsed_kv.range_mut( + ID::new(idlp.peer, lower_bound)..ID::new(idlp.peer, upper_bound), + ); + is_binary_searching = false; + } else { + let mid_bound = (lower_bound + upper_bound) / 2; + iter = inner + .mem_parsed_kv + .range_mut(ID::new(idlp.peer, 0)..ID::new(idlp.peer, mid_bound)); + } + } + } + } + + let counter_end = upper_bound; + + // The answer may live only in `mem_parsed_kv` (e.g. local changes + // that have not been flushed to the external kv store yet) or only + // in `external_kv` (blocks that were never parsed into memory). + // Check both and use the block with the greatest start counter: + // within a peer, lamport grows with counter, so that block holds + // the greatest matching lamport. + let mem_block_id: Option<ID> = inner + .mem_parsed_kv + .range(ID::new(idlp.peer, 0)..ID::new(idlp.peer, counter_end)) + .rev() + .find(|(_, block)| block.lamport_range.0 <= idlp.lamport) + .map(|(id, _)| *id); + + let external_block = 'block_scan: { + let scan_end = ID::new(idlp.peer, counter_end).to_bytes(); + let iter = kv_store + .scan( + Bound::Included(&ID::new(idlp.peer, 0).to_bytes()), + Bound::Excluded(&scan_end), + ) + .rev(); + + for (id, bytes) in iter { + let mut block = ChangesBlockBytes::new(bytes.clone()); + let (lamport_start, _lamport_end) = match block.lamport_range() { + Ok(range) => range, + Err(err) => { + let block_id = ID::from_bytes(&id); + warn!( + ?block_id, + ?err, + "failed to decode external change block range" + ); + self.parse_failures.record(block_id, &err); + continue; + } + }; + if lamport_start <= idlp.lamport { + break 'block_scan Some((ID::from_bytes(&id), bytes)); + } + } + + None + }; + + let use_external = match (mem_block_id, &external_block) { + (Some(mem_id), Some((external_id, _))) => external_id.counter > mem_id.counter, + (Some(_), None) => false, + (None, Some(_)) => true, + (None, None) => return None, + }; + + if !use_external { + let block_id = mem_block_id.unwrap(); + let block = inner.mem_parsed_kv.get_mut(&block_id).unwrap(); + if let Err(err) = block.ensure_changes(&self.arena) { + warn!(?block_id, ?err, "failed to parse change block"); + self.parse_failures.record(block_id, &err); + return None; + } + let block = block.clone(); + let index = block.get_change_index_by_lamport_lte(idlp.lamport)?; + return Some(BlockChangeRef { + change_index: index, + block, + }); + } + + let (block_id, bytes) = external_block.unwrap(); + let mut block = match ChangesBlock::from_bytes(bytes) { + Ok(block) => Arc::new(block), + Err(err) => { + warn!(?block_id, ?err, "failed to decode external change block"); + self.parse_failures.record(block_id, &err); + return None; + } + }; + if let Err(err) = block.ensure_changes(&self.arena) { + warn!(?block_id, ?err, "failed to parse external change block"); + self.parse_failures.record(block_id, &err); + return None; + } + inner.mem_parsed_kv.insert(block_id, block.clone()); + let index = block.get_change_index_by_lamport_lte(idlp.lamport)?; + Some(BlockChangeRef { + change_index: index, + block, + }) + } + + fn split_change_then_insert( + &self, + change: Change, + mut rollback: Option<&mut ChangeStoreRollback>, + ) { + let original_len = change.atom_len(); + let mut new_change = Change { + ops: RleVec::new(), + deps: change.deps, + id: change.id, + lamport: change.lamport, + timestamp: change.timestamp, + commit_msg: change.commit_msg.clone(), + }; + + let mut total_len = 0; + let mut estimated_size = new_change.estimate_storage_size(); + 'outer: for mut op in change.ops.into_iter() { + if op.estimate_storage_size() >= MAX_BLOCK_SIZE - estimated_size { + new_change = self._insert_splitted_change( + new_change, + &mut total_len, + &mut estimated_size, + rollback.as_deref_mut(), + ); + } + + while let Some(end) = + op.check_whether_slice_content_to_fit_in_size(MAX_BLOCK_SIZE - estimated_size) + { + // The new op can take the rest of the room + let new = op.slice(0, end); + new_change.ops.push(new); + new_change = self._insert_splitted_change( + new_change, + &mut total_len, + &mut estimated_size, + rollback.as_deref_mut(), + ); + + if end < op.atom_len() { + op = op.slice(end, op.atom_len()); + } else { + continue 'outer; + } + } + + estimated_size += op.estimate_storage_size(); + if estimated_size > MAX_BLOCK_SIZE && !new_change.ops.is_empty() { + new_change = self._insert_splitted_change( + new_change, + &mut total_len, + &mut estimated_size, + rollback.as_deref_mut(), + ); + new_change.ops.push(op); + } else { + new_change.ops.push(op); + } + } + + if !new_change.ops.is_empty() { + total_len += new_change.atom_len(); + self.insert_change_inner(new_change, false, false, rollback); + } + + assert_eq!(total_len, original_len); + } + + fn _insert_splitted_change( + &self, + new_change: Change, + total_len: &mut usize, + estimated_size: &mut usize, + rollback: Option<&mut ChangeStoreRollback>, + ) -> Change { + if new_change.atom_len() == 0 { + return new_change; + } + + let ctr_end = new_change.id.counter + new_change.atom_len() as Counter; + let next_lamport = new_change.lamport + new_change.atom_len() as Lamport; + *total_len += new_change.atom_len(); + let ans = Change { + ops: RleVec::new(), + deps: ID::new(new_change.id.peer, ctr_end - 1).into(), + id: ID::new(new_change.id.peer, ctr_end), + lamport: next_lamport, + timestamp: new_change.timestamp, + commit_msg: new_change.commit_msg.clone(), + }; + + self.insert_change_inner(new_change, false, false, rollback); + *estimated_size = ans.estimate_storage_size(); + ans + } + + /// A callback for [`SharedArena::set_creator_resolver`]: loads and parses the change + /// block holding the op with the given ID, if the store has it. Parsing registers the + /// parent link of every container the block's ops create. + /// + /// It holds weak references, so the arena (which this store refers to) does not keep + /// the store alive. + /// + /// Locking: this is the only access to the store that does not hold the document's op + /// log lock (it runs under the state lock, or under none while events are emitted), so + /// it relies on the store's lock order (see [`ChangeStore`]). It takes the arena's lock + /// after the store's, so the arena must call it without holding its own. See + /// `context/arena-parent-links.md`. + pub(crate) fn creator_resolver( + &self, + ) -> impl Fn(&SharedArena, ID) -> CreatorOp + Send + Sync + 'static { + let inner = Arc::downgrade(&self.inner); + let external_kv = Arc::downgrade(&self.external_kv); + let parse_failures = self.parse_failures.clone(); + move |arena, id| { + let (Some(inner), Some(external_kv)) = (inner.upgrade(), external_kv.upgrade()) + else { + // The op log is gone, and its history with it. + return CreatorOp::Absent; + }; + match Self::load_parsed_block(&inner, &external_kv, arena, id) { + Ok(Some(_)) => CreatorOp::Loaded, + Ok(None) => CreatorOp::Absent, + // Answering "no such op" alone would report the container as deleted, + // and a panic here would unwind under the state lock (and trap the + // WASM instance). Record the block instead; see [`ParseFailures`]. + Err((block_id, err)) => { + tracing::error!( + %block_id, %id, ?err, + "cannot parse change block; the document's history is corrupt" + ); + parse_failures.record(block_id, &err); + CreatorOp::Corrupt + } + } + } + } + + /// `Err` once a read of this store has hit a block it cannot decode or parse. See + /// [`ParseFailures`]. + pub(crate) fn corrupt_block_error(&self) -> LoroResult<()> { + match &*self.parse_failures.first.lock() { + None => Ok(()), + Some((block_id, err)) => Err(LoroError::DecodeError( + format!("cannot parse change block {block_id}: {err}").into_boxed_str(), + )), + } + } + + fn get_parsed_block(&self, id: ID) -> Option<Arc<ChangesBlock>> { + match Self::load_parsed_block(&self.inner, &self.external_kv, &self.arena, id) { + Ok(block) => block, + Err((block_id, err)) => { + warn!(?block_id, ?err, "failed to parse change block"); + self.parse_failures.record(block_id, &err); + None + } + } + } + + /// The parsed block holding `id`, `Ok(None)` if the store has no such block, or the ID + /// of a block of `id`'s peer that cannot be decoded or parsed. + fn load_parsed_block( + inner: &Mutex<ChangeStoreInner>, + external_kv: &Mutex<dyn KvStore>, + arena: &SharedArena, + id: ID, + ) -> Result<Option<Arc<ChangesBlock>>, (ID, LoroError)> { + // A cached block needs only `inner`. + { + let mut inner = inner.lock(); + if inner.retired { + return Ok(None); + } + if let Some(block) = Self::parse_cached_block(&mut inner, arena, id) { + return block.map(Some); + } + } + + // Lock order: `external_kv` before `inner`. Another thread may have loaded the + // block (or retired the store) in between, so look again. + let store = external_kv.lock(); + let mut inner = inner.lock(); + if inner.retired { + return Ok(None); + } + if let Some(block) = Self::parse_cached_block(&mut inner, arena, id) { + return block.map(Some); + } + + let Some((b_id, b_bytes)) = store + .scan(Bound::Unbounded, Bound::Included(&id.to_bytes())) + .rfind(|(id, _)| id.len() == 12) + else { + return Ok(None); + }; + let block_id: ID = ID::from_bytes(&b_id[..]); + if block_id.peer != id.peer { + return Ok(None); + } + let block = ChangesBlock::from_bytes(b_bytes).map_err(|err| (block_id, err))?; + if block.counter_range.1 <= id.counter { + return Ok(None); + } + let mut block = Arc::new(block); + block.ensure_changes(arena).map_err(|err| (block_id, err))?; + inner.mem_parsed_kv.insert(block_id, block.clone()); + Ok(Some(block)) + } + + /// `Some` if a cached block holds `id`: the block, parsed, or why it cannot be parsed. + fn parse_cached_block( + inner: &mut ChangeStoreInner, + arena: &SharedArena, + id: ID, + ) -> Option<Result<Arc<ChangesBlock>, (ID, LoroError)>> { + let (block_id, block) = inner.mem_parsed_kv.range_mut(..=id).next_back()?; + if block.peer != id.peer || block.counter_range.1 <= id.counter { + return None; + } + Some(match block.ensure_changes(arena) { + Ok(()) => Ok(block.clone()), + Err(err) => Err((*block_id, err)), + }) + } + + /// Load all the blocks that have overlapped with the given ID range into `inner_mem_parsed_kv` + /// + /// This is fast because we don't actually parse the content. + // TODO: PERF: This method feels slow. + pub(super) fn ensure_block_loaded_in_range(&self, start: Bound<ID>, end: Bound<ID>) { + let _ = self.load_blocks_in_range(start, end, false); + } + + pub(super) fn try_ensure_block_loaded_in_range( + &self, + start: Bound<ID>, + end: Bound<ID>, + ) -> LoroResult<()> { + self.load_blocks_in_range(start, end, true) + } + + fn load_blocks_in_range( + &self, + start: Bound<ID>, + end: Bound<ID>, + stop_on_error: bool, + ) -> LoroResult<()> { + let mut whether_need_scan_backward = match start { + Bound::Included(id) => Some(id), + Bound::Excluded(id) => Some(id.inc(1)), + Bound::Unbounded => None, + }; + + // Nothing of this peer from `start` on is in the kv: skip the scan, which + // decodes the neighbouring block of another peer each time (a whole imported + // snapshot's block: milliseconds per export of a single keystroke). + // (project_note patch) + if let Some(first) = whether_need_scan_backward { + let same_peer = match end { + Bound::Included(e) | Bound::Excluded(e) => e.peer == first.peer, + Bound::Unbounded => false, + }; + if same_peer && self.external_vv.lock().get(&first.peer).copied().unwrap_or(0) <= first.counter { + return Ok(()); + } + } + + { + let start = start.map(|id| id.to_bytes()); + let end = end.map(|id| id.to_bytes()); + let kv = self.external_kv.lock(); + let mut inner = self.inner.lock(); + for (id, bytes) in kv + .scan( + start.as_ref().map(|x| x.as_slice()), + end.as_ref().map(|x| x.as_slice()), + ) + .filter(|(id, _)| id.len() == 12) + { + let id = ID::from_bytes(&id); + if let Some(expected_start_id) = whether_need_scan_backward { + if id == expected_start_id { + whether_need_scan_backward = None; + } + } + + if inner.mem_parsed_kv.contains_key(&id) { + continue; + } + + let block = match ChangesBlock::from_bytes(bytes.clone()) { + Ok(block) => block, + Err(err) => { + warn!(?id, ?err, "failed to decode external change block"); + self.parse_failures.record(id, &err); + if stop_on_error { + return Err(self.corrupt_block_error().unwrap_err()); + } + continue; + } + }; + inner.mem_parsed_kv.insert(id, Arc::new(block)); + } + } + + if let Some(start_id) = whether_need_scan_backward { + if stop_on_error { + self.try_ensure_id_lte(start_id)?; + } else { + self.ensure_id_lte(start_id); + } + } + Ok(()) + } + + pub(super) fn ensure_id_lte(&self, id: ID) { + let _ = self.try_ensure_id_lte(id); + } + + pub(super) fn try_ensure_id_lte(&self, id: ID) -> LoroResult<()> { + let kv = self.external_kv.lock(); + let mut inner = self.inner.lock(); + let Some((next_back_id, next_back_bytes)) = kv + .scan(Bound::Unbounded, Bound::Included(&id.to_bytes())) + .rfind(|(id, _)| id.len() == 12) + else { + return Ok(()); + }; + + let next_back_id = ID::from_bytes(&next_back_id); + if next_back_id.peer == id.peer { + if inner.mem_parsed_kv.contains_key(&next_back_id) { + return Ok(()); + } + + let block = match ChangesBlock::from_bytes(next_back_bytes) { + Ok(block) => block, + Err(err) => { + warn!( + ?next_back_id, + ?err, + "failed to decode external change block" + ); + self.parse_failures.record(next_back_id, &err); + return Err(self.corrupt_block_error().unwrap_err()); + } + }; + inner.mem_parsed_kv.insert(next_back_id, Arc::new(block)); + } + Ok(()) + } + } +} + +#[must_use] +#[derive(Clone, Debug)] +pub(crate) struct BatchDecodeInfo { + pub vv: VersionVector, + pub frontiers: Frontiers, + pub start_version: Option<(VersionVector, Frontiers)>, +} + +#[derive(Clone, Debug)] +pub struct BlockChangeRef { + block: Arc<ChangesBlock>, + change_index: usize, +} + +impl Deref for BlockChangeRef { + type Target = Change; + fn deref(&self) -> &Change { + &self.block.content.try_changes().unwrap()[self.change_index] + } +} + +impl BlockChangeRef { + pub(crate) fn get_op_with_counter(&self, counter: Counter) -> Option<BlockOpRef> { + if counter >= self.ctr_end() { + return None; + } + + let index = self.ops.search_atom_index(counter); + Some(BlockOpRef { + block: self.block.clone(), + change_index: self.change_index, + op_index: index, + }) + } +} + +#[derive(Clone, Debug)] +pub(crate) struct BlockOpRef { + pub block: Arc<ChangesBlock>, + pub change_index: usize, + pub op_index: usize, +} + +impl Deref for BlockOpRef { + type Target = Op; + + fn deref(&self) -> &Op { + &self.block.content.try_changes().unwrap()[self.change_index].ops[self.op_index] + } +} + +impl BlockOpRef { + pub fn lamport(&self) -> Lamport { + let change = &self.block.content.try_changes().unwrap()[self.change_index]; + let op = &change.ops[self.op_index]; + (op.counter - change.id.counter) as Lamport + change.lamport + } +} + +impl ChangesBlock { + fn from_bytes(bytes: Bytes) -> LoroResult<Self> { + let len = bytes.len(); + let bytes = ChangesBlockBytes::new(bytes); + bytes.ensure_header()?; + let header = bytes + .header + .get() + .expect("header should be initialized after ensure_header"); + let peer = header.peer; + let counter_range = ( + header.counter, + *header.counters.last().ok_or_else(|| { + LoroError::DecodeError("Decode block error: missing counters".into()) + })?, + ); + // `header.lamports` only stores the start lamport of each change (n entries), + // while `header.counters` has n + 1 entries ending with the block's end counter. + // The block's exclusive end lamport is the last change's start lamport plus its len. + let last_change_start = *header + .counters + .len() + .checked_sub(2) + .and_then(|i| header.counters.get(i)) + .ok_or_else(|| LoroError::DecodeError("Decode block error: missing counters".into()))?; + let last_change_len = counter_range.1 - last_change_start; + let lamport_range = ( + *header.lamports.first().ok_or_else(|| { + LoroError::DecodeError("Decode block error: missing lamports".into()) + })?, + header + .lamports + .last() + .ok_or_else(|| { + LoroError::DecodeError("Decode block error: missing lamports".into()) + })? + .checked_add(last_change_len as Lamport) + .ok_or_else(|| { + LoroError::DecodeError("Decode block error: lamport overflow".into()) + })?, + ); + let content = ChangesBlockContent::Bytes(bytes); + Ok(Self { + peer, + estimated_size: len, + counter_range, + lamport_range, + flushed: true, + content, + parsed_extent: ArenaExtent::default(), + }) + } + + #[allow(dead_code)] + pub(crate) fn content(&self) -> &ChangesBlockContent { + &self.content + } + + fn new(change: Change, _a: &SharedArena) -> Self { + let atom_len = change.atom_len(); + let counter_range = (change.id.counter, change.id.counter + atom_len as Counter); + let lamport_range = (change.lamport, change.lamport + atom_len as Lamport); + let estimated_size = change.estimate_storage_size(); + let peer = change.id.peer; + let content = ChangesBlockContent::Changes(Arc::new(vec![change])); + Self { + peer, + counter_range, + lamport_range, + estimated_size, + content, + flushed: false, + parsed_extent: ArenaExtent::default(), + } + } + + #[allow(unused)] + fn cmp_id(&self, id: ID) -> Ordering { + self.peer.cmp(&id.peer).then_with(|| { + if self.counter_range.0 > id.counter { + Ordering::Greater + } else if self.counter_range.1 <= id.counter { + Ordering::Less + } else { + Ordering::Equal + } + }) + } + + #[allow(unused)] + fn cmp_idlp(&self, idlp: (PeerID, Lamport)) -> Ordering { + self.peer.cmp(&idlp.0).then_with(|| { + if self.lamport_range.0 > idlp.1 { + Ordering::Greater + } else if self.lamport_range.1 <= idlp.1 { + Ordering::Less + } else { + Ordering::Equal + } + }) + } + + #[allow(unused)] + fn is_full(&self) -> bool { + self.estimated_size > MAX_BLOCK_SIZE + } + + #[allow(clippy::result_large_err)] + fn push_change( + self: &mut Arc<Self>, + change: Change, + new_change_size: usize, + merge_interval: i64, + a: &SharedArena, + ) -> Result<(), Change> { + if self.counter_range.1 != change.id.counter { + return Err(change); + } + + let atom_len = change.atom_len(); + let next_lamport = change.lamport + atom_len as Lamport; + let next_counter = change.id.counter + atom_len as Counter; + + let is_full = new_change_size + self.estimated_size > MAX_BLOCK_SIZE; + let this = Arc::make_mut(self); + let changes = this.content.changes_mut(a).unwrap(); + let changes = Arc::make_mut(changes); + match changes.last_mut() { + Some(last) + if last.can_merge_right(&change, merge_interval) + && (!is_full + || (change.ops.len() == 1 + && last.ops.last().unwrap().is_mergable(&change.ops[0], &()))) => + { + for op in change.ops.into_iter() { + let size = op.estimate_storage_size(); + if !last.ops.push(op) { + this.estimated_size += size; + } + } + } + _ => { + if is_full { + return Err(change); + } else { + this.estimated_size += new_change_size; + changes.push(change); + } + } + } + + this.flushed = false; + this.counter_range.1 = next_counter; + this.lamport_range.1 = next_lamport; + Ok(()) + } + + fn to_bytes(self: &mut Arc<Self>, a: &SharedArena) -> ChangesBlockBytes { + match &self.content { + ChangesBlockContent::Bytes(bytes) => bytes.clone(), + ChangesBlockContent::Both(_, bytes) => { + let bytes = bytes.clone(); + let this = Arc::make_mut(self); + this.content = ChangesBlockContent::Bytes(bytes.clone()); + bytes + } + ChangesBlockContent::Changes(changes) => { + let bytes = ChangesBlockBytes::serialize(changes, a); + let this = Arc::make_mut(self); + this.content = ChangesBlockContent::Bytes(bytes.clone()); + bytes + } + } + } + + fn ensure_changes(self: &mut Arc<Self>, a: &SharedArena) -> LoroResult<()> { + match &self.content { + ChangesBlockContent::Changes(_) => Ok(()), + ChangesBlockContent::Both(_, _) => Ok(()), + ChangesBlockContent::Bytes(bytes) => { + let changes = bytes.parse(a)?; + let b = bytes.clone(); + let this = Arc::make_mut(self); + this.content = ChangesBlockContent::Both(Arc::new(changes), b); + this.parsed_extent = a.extent(); + Ok(()) + } + } + } + + fn get_change_index_by_counter(&self, counter: Counter) -> Result<usize, usize> { + let changes = self.content.try_changes().unwrap(); + changes.binary_search_by(|c| { + if c.id.counter > counter { + Ordering::Greater + } else if (c.id.counter + c.content_len() as Counter) <= counter { + Ordering::Less + } else { + Ordering::Equal + } + }) + } + + fn get_change_index_by_lamport_lte(&self, lamport: Lamport) -> Option<usize> { + let changes = self.content.try_changes().unwrap(); + let r = changes.binary_search_by(|c| { + if c.lamport > lamport { + Ordering::Greater + } else if (c.lamport + c.content_len() as Lamport) <= lamport { + Ordering::Less + } else { + Ordering::Equal + } + }); + + match r { + Ok(found) => Some(found), + Err(idx) => { + if idx == 0 { + None + } else { + Some(idx - 1) + } + } + } + } + + #[allow(unused)] + fn id(&self) -> ID { + ID::new(self.peer, self.counter_range.0) + } + + pub fn change_num(&self) -> usize { + match &self.content { + ChangesBlockContent::Changes(c) => c.len(), + ChangesBlockContent::Bytes(b) => b.len_changes(), + ChangesBlockContent::Both(c, _) => c.len(), + } + } +} + +impl ChangesBlockContent { + // TODO: PERF: We can use Iter to replace Vec + pub fn iter_dag_nodes(&self) -> Vec<AppDagNode> { + let mut dag_nodes = Vec::new(); + match self { + ChangesBlockContent::Changes(c) | ChangesBlockContent::Both(c, _) => { + for change in c.iter() { + let new_node = AppDagNodeInner { + peer: change.id.peer, + cnt: change.id.counter, + lamport: change.lamport, + deps: change.deps.clone(), + vv: OnceCell::new(), + has_succ: false, + len: change.atom_len(), + } + .into(); + + dag_nodes.push_rle_element(new_node); + } + } + ChangesBlockContent::Bytes(b) => { + b.ensure_header().unwrap(); + let header = b.header.get().unwrap(); + let n = header.n_changes; + for i in 0..n { + let new_node = AppDagNodeInner { + peer: header.peer, + cnt: header.counters[i], + lamport: header.lamports[i], + deps: header.deps_groups[i].clone(), + vv: OnceCell::new(), + has_succ: false, + len: (header.counters[i + 1] - header.counters[i]) as usize, + } + .into(); + + dag_nodes.push_rle_element(new_node); + } + } + } + + dag_nodes + } + + /// Note that this method will invalidate the stored bytes + fn changes_mut(&mut self, a: &SharedArena) -> LoroResult<&mut Arc<Vec<Change>>> { + match self { + ChangesBlockContent::Changes(changes) => Ok(changes), + ChangesBlockContent::Both(changes, _) => { + *self = ChangesBlockContent::Changes(std::mem::take(changes)); + self.changes_mut(a) + } + ChangesBlockContent::Bytes(bytes) => { + let changes = bytes.parse(a)?; + *self = ChangesBlockContent::Changes(Arc::new(changes)); + self.changes_mut(a) + } + } + } + + pub(crate) fn try_changes(&self) -> Option<&Vec<Change>> { + match self { + ChangesBlockContent::Changes(changes) => Some(changes), + ChangesBlockContent::Both(changes, _) => Some(changes), + ChangesBlockContent::Bytes(_) => None, + } + } + + #[allow(dead_code)] + pub(crate) fn len_changes(&self) -> usize { + match self { + ChangesBlockContent::Changes(changes) => changes.len(), + ChangesBlockContent::Both(changes, _) => changes.len(), + ChangesBlockContent::Bytes(bytes) => bytes.len_changes(), + } + } +} + +impl std::fmt::Debug for ChangesBlockContent { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ChangesBlockContent::Changes(changes) => f + .debug_tuple("ChangesBlockContent::Changes") + .field(changes) + .finish(), + ChangesBlockContent::Bytes(_bytes) => { + f.debug_tuple("ChangesBlockContent::Bytes").finish() + } + ChangesBlockContent::Both(changes, _bytes) => f + .debug_tuple("ChangesBlockContent::Both") + .field(changes) + .finish(), + } + } +} + +impl ChangesBlockBytes { + fn new(bytes: Bytes) -> Self { + Self { + header: OnceCell::new(), + bytes, + } + } + + fn ensure_header(&self) -> LoroResult<()> { + self.header + .get_or_try_init(|| decode_header(&self.bytes).map(Arc::new))?; + Ok(()) + } + + fn parse(&self, a: &SharedArena) -> LoroResult<Vec<Change>> { + self.ensure_header()?; + let ans: Vec<Change> = decode_block(&self.bytes, a, self.header.get().map(|h| h.as_ref()))?; + for c in ans.iter() { + // PERF: This can be made faster (low priority) + register_container_and_parent_link(a, c) + } + + Ok(ans) + } + + fn serialize(changes: &[Change], a: &SharedArena) -> Self { + let bytes = encode_block(changes, a); + // TODO: Perf we can calculate header directly without parsing the bytes + let bytes = ChangesBlockBytes::new(Bytes::from(bytes)); + bytes.ensure_header().unwrap(); + bytes + } + + fn lamport_range(&mut self) -> LoroResult<(Lamport, Lamport)> { + if let Some(header) = self.header.get() { + Ok((header.lamports[0], *header.lamports.last().unwrap())) + } else { + decode_block_range(&self.bytes).map(|(_, lamport_range)| lamport_range) + } + } + + /// Length of the changes + fn len_changes(&self) -> usize { + self.ensure_header().unwrap(); + self.header.get().unwrap().n_changes + } +} + +#[cfg(test)] +mod test { + use crate::cursor::PosType; + use crate::{ + loro::ExportMode, oplog::convert_change_to_remote, state::TreeParentId, ListHandler, + LoroDoc, MovableListHandler, TextHandler, TreeHandler, + }; + + use super::*; + + fn test_encode_decode(doc: LoroDoc) { + doc.commit_then_renew(); + let oplog = doc.oplog().lock(); + let bytes = oplog + .change_store + .encode_all(oplog.vv(), oplog.dag.frontiers()); + let store = ChangeStore::new_for_test(); + let _ = store.import_all(bytes.clone()).unwrap(); + assert_eq!(store.external_kv.lock().export_all(), bytes); + let mut changes_parsed = Vec::new(); + let a = store.arena.clone(); + store.visit_all_changes(&mut |c| { + changes_parsed.push(convert_change_to_remote(&a, c)); + }); + let mut changes = Vec::new(); + oplog.change_store.visit_all_changes(&mut |c| { + changes.push(convert_change_to_remote(&oplog.arena, c)); + }); + assert_eq!(changes_parsed, changes); + } + + #[test] + fn identical_encoded_block_stays_lazy_and_dirty_cache_shadows_kv() { + let source = LoroDoc::new_auto_commit(); + source.set_peer_id(1).unwrap(); + source.set_change_merge_interval(-1); + for _ in 0..40 { + let text = source.get_text("t"); + text.insert(text.len_unicode(), "abcd", PosType::Unicode) + .unwrap(); + source.commit_then_renew(); + } + let bytes = { + let oplog = source.oplog().lock(); + oplog.change_store.encode_all(oplog.vv(), oplog.frontiers()) + }; + let store = ChangeStore::new_for_test(); + store.import_all(bytes).unwrap(); + let (id, block_bytes) = store + .external_kv + .lock() + .scan(Bound::Unbounded, Bound::Unbounded) + .find(|(key, _)| key.len() == 12) + .map(|(key, bytes)| (ID::from_bytes(&key), bytes)) + .unwrap(); + assert!(!store.inner.lock().mem_parsed_kv.contains_key(&id)); + let before = store.arena.utf16_len(); + assert!(store + .decode_update_block(block_bytes.clone(), &source.oplog_vv()) + .unwrap() + .is_empty()); + assert_eq!(store.arena.utf16_len(), before); + assert!(!store.inner.lock().mem_parsed_kv.contains_key(&id)); + + let original = store.get_change(id).unwrap(); + let mut dirty = original.block.as_ref().clone(); + // Model an unflushed mutation. Its stale KV copy must not authorize a + // shortcut, even if the imported bytes match that old copy exactly. + let mut changes = dirty.content.try_changes().unwrap().clone(); + changes[0].deps = Frontiers::from_id(ID::new(9, 0)); + dirty.content = ChangesBlockContent::Changes(Arc::new(changes)); + dirty.flushed = false; + store.inner.lock().mem_parsed_kv.insert(id, Arc::new(dirty)); + assert!(!store.contains_encoded_block(id, &block_bytes)); + assert!(!store + .decode_update_block(block_bytes, &source.oplog_vv()) + .unwrap() + .is_empty()); + } + + #[test] + fn merged_cold_text_overlap_is_accepted_without_parsing_the_known_block() { + let history = LoroDoc::new_auto_commit(); + history.set_peer_id(1).unwrap(); + history.set_change_merge_interval(-1); + for i in 0..40 { + history.get_text("t").insert_unicode(i * 2, "a😀").unwrap(); + history.commit_then_renew(); + } + let target = LoroDoc::new_auto_commit(); + target + .import(&history.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + + let merged = LoroDoc::new_auto_commit(); + merged.set_peer_id(1).unwrap(); + merged + .get_text("t") + .insert_unicode(0, &("a😀".repeat(40) + "Z")) + .unwrap(); + merged.commit_then_renew(); + { + let incoming = merged.oplog().lock(); + let change = (*incoming.get_change_at(ID::new(1, 0)).unwrap()).clone(); + let local = target.oplog().lock(); + // cfg(test) loads the frontier block at snapshot import; explicitly + // clear that cache to exercise the real cold-block comparison. + local.change_store.inner.lock().mem_parsed_kv.clear(); + let id = ID::new(1, 0); + let bytes = local.change_store.unparsed_block_bytes(id).unwrap(); + assert_ne!( + bytes.as_ref(), + block_encode::encode_block(&[change.clone()], &incoming.arena) + ); + let suffix = local + .check_and_trim_known_part_in_arena( + vec![change], + crate::oplog::known_history::ImportedValues::Exact, + &incoming.arena, + ) + .unwrap(); + assert_eq!(suffix.len(), 1); + assert_eq!(suffix[0].id, ID::new(1, 80)); + // A general comparison would have populated the parsed cache. + assert!(local.change_store.unparsed_block_bytes(id).is_some()); + } + target + .import(&merged.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + assert_eq!(target.get_deep_value(), merged.get_deep_value()); + assert_eq!(target.oplog_vv(), merged.oplog_vv()); + } + + #[test] + fn repeated_snapshot_updates_allocate_only_the_new_text_and_list_values() { + let source = LoroDoc::new_auto_commit(); + source.set_peer_id(1).unwrap(); + source.set_change_merge_interval(-1); + for i in 0..40 { + let text = source.get_text("t"); + text.insert(text.len_unicode(), "wörld 😀", PosType::Unicode) + .unwrap(); + source.get_list("l").push(i).unwrap(); + source.commit_then_renew(); + } + let target = LoroDoc::new_auto_commit(); + target + .import(&source.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + // Once local history is parsed, repeated snapshots must not allocate + // another copy of any known strings, even with Unicode. List values + // have no shared store: ops own them. + target + .oplog() + .lock() + .change_store + .visit_all_changes(&mut |_| {}); + let text_before = target.oplog().lock().arena.utf16_len(); + for i in 0..4 { + let text = source.get_text("t"); + text.insert(text.len_unicode(), "Z", PosType::Unicode) + .unwrap(); + source.get_list("l").push(100 + i).unwrap(); + source.commit_then_renew(); + target + .import(&source.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + assert_eq!( + target.oplog().lock().arena.utf16_len(), + text_before + i as usize + 1 + ); + } + assert_eq!(target.get_deep_value(), source.get_deep_value()); + } + + #[test] + fn decoded_block_lamport_range_matches_counter_range() { + // Regression test for a checkout hang after snapshot import. + // `ChangesBlock::from_bytes` used the start lamport of the block's last + // change as the block's end lamport, producing degenerate lamport + // ranges (empty for single-change blocks). The binary search in + // `get_change_by_lamport_lte` then misclassified the block containing + // the target lamport and looped forever. + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + // One big commit that splits into many blocks, with enough ops that + // lamport lookups engage the binary search path + // (lamport gap > MAX_BLOCK_SIZE * 8). + for i in 0..100 { + let text = doc.get_text(format!("t{i}").as_str()); + text.insert(0, &"x".repeat(30), PosType::Unicode).unwrap(); + } + doc.commit_then_renew(); + + let (bytes, end_counter) = { + let oplog = doc.oplog().lock(); + let end = oplog.vv().get(&1).copied().unwrap(); + let bytes = oplog + .change_store + .encode_all(oplog.vv(), oplog.dag.frontiers()); + (bytes, end) + }; + + let store = ChangeStore::new_for_test(); + let _ = store.import_all(bytes).unwrap(); + // Parse every block out of the external kv store + let mut c = 0; + while c < end_counter { + let change = store.get_change(ID::new(1, c)).unwrap(); + c = change.id.counter + change.atom_len() as Counter; + } + + { + let inner = store.inner.lock(); + assert!( + inner.mem_parsed_kv.len() > 1, + "the change should be split into multiple blocks" + ); + for (id, block) in inner.mem_parsed_kv.iter() { + // Single-peer linear history: lamport == counter for every op + assert_eq!(id.counter, block.counter_range.0); + assert_eq!(block.lamport_range.0 as Counter, block.counter_range.0); + assert_eq!(block.lamport_range.1 as Counter, block.counter_range.1); + } + } + + for l in (0..end_counter as Lamport).step_by(7) { + let change = store.get_change_by_lamport_lte(IdLp::new(1, l)).unwrap(); + assert!(change.lamport <= l); + assert!(l < change.lamport + change.atom_len() as Lamport); + } + } + + /// Peer 1 history split into many blocks, encoded into a fresh store's KV only + /// (nothing parsed into `mem_parsed_kv`), plus the change that comes next. + fn kv_only_store_and_next_change() -> (ChangeStore, Counter, Change) { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + for i in 0..100 { + let text = doc.get_text(format!("t{i}").as_str()); + text.insert(0, &"x".repeat(30), PosType::Unicode).unwrap(); + doc.commit_then_renew(); + } + let (bytes, end) = { + let oplog = doc.oplog().lock(); + let end = oplog.vv().get(&1).copied().unwrap(); + let bytes = oplog + .change_store + .encode_all(oplog.vv(), oplog.dag.frontiers()); + (bytes, end) + }; + doc.get_text("t0").insert(0, "y", PosType::Unicode).unwrap(); + doc.commit_then_renew(); + let next = { + let oplog = doc.oplog().lock(); + let change = oplog.get_change_at(ID::new(1, end)).unwrap(); + (*change).clone() + }; + let store = ChangeStore::new_for_test(); + let _ = store.import_all(bytes).unwrap(); + // Test builds of `import_all` parse each peer's last block; release builds do not. + store.inner.lock().mem_parsed_kv.clear(); + (store, end, next) + } + + #[test] + fn lamport_lookup_reads_kv_only_blocks() { + // Regression: `decode_block_range` read a version varint the block encoding + // does not have, shifting every field. KV-only blocks that did not start at + // counter 0 were skipped and block `0@P` got its lamport length as its start. + let (store, end, _) = kv_only_store_and_next_change(); + for l in (0..end as Lamport).step_by(13) { + store.inner.lock().mem_parsed_kv.clear(); + let change = store + .get_change_by_lamport_lte(IdLp::new(1, l)) + .unwrap_or_else(|| panic!("lamport {l} should be found")); + assert!(change.lamport <= l); + assert!(l < change.lamport + change.atom_len() as Lamport); + } + } + + #[test] + fn rollback_drops_only_blocks_parsed_after_the_checkpoint() { + // A failed import must not keep blocks it parsed (they may refer to what the arena + // rollback drops), but the blocks parsed before it are still valid, and reparsing them + // after every failed import would cost a full history pass. + let (store, end, _) = kv_only_store_and_next_change(); + let is_parsed = |id: ID| { + let inner = store.inner.lock(); + let (_, block) = inner.mem_parsed_kv.range(..=id).next_back().unwrap(); + matches!(block.content, ChangesBlockContent::Both(..)) + }; + let early = ID::new(1, 0); + let late = ID::new(1, end - 1); + store.get_change(early).unwrap(); + let checkpoint = store.arena.checkpoint_for_rollback(); + // Something the failed import registered. + store.arena.register_container(&ContainerID::new_root( + "new", + loro_common::ContainerType::Map, + )); + store.get_change(late).unwrap(); + assert!(is_parsed(early) && is_parsed(late)); + store.rollback_arena(checkpoint); + assert!(is_parsed(early)); + assert!(!is_parsed(late)); + assert!(store.get_change(late).is_some()); + } + + #[test] + fn a_retired_store_resolves_nothing() { + // A resolver that reached the store before a failed snapshot import replaced it + // must not register containers of the discarded history. + let (store, _, _) = kv_only_store_and_next_change(); + let resolve = store.creator_resolver(); + let checkpoint = store.arena.checkpoint_for_rollback(); + assert_eq!(resolve(&store.arena, ID::new(1, 0)), CreatorOp::Loaded); + store.retire(checkpoint); + assert_eq!(resolve(&store.arena, ID::new(1, 0)), CreatorOp::Absent); + assert!(store.inner.lock().mem_parsed_kv.is_empty()); + } + + /// Truncates the stored bytes of the block holding `id`: its header still names the + /// counter range, but the body no longer parses. + fn truncate_block(store: &ChangeStore, id: ID) { + let mut kv = store.external_kv.lock(); + let (key, bytes) = kv + .scan(Bound::Unbounded, Bound::Included(&id.to_bytes())) + .rfind(|(key, _)| key.len() == 12) + .unwrap(); + assert_eq!(ID::from_bytes(&key).peer, id.peer); + kv.set(&key, bytes.slice(..bytes.len() / 2)); + drop(kv); + store.inner.lock().mem_parsed_kv.clear(); + } + + #[test] + fn legacy_block_iteration_skips_only_the_broken_block() { + for position in 0..3 { + let (store, end, _) = kv_only_store_and_next_change(); + let ids: Vec<_> = store + .external_kv + .lock() + .scan(Bound::Unbounded, Bound::Unbounded) + .filter(|(key, _)| key.len() == 12) + .map(|(key, _)| ID::from_bytes(&key)) + .collect(); + assert!(ids.len() >= 3); + let broken = ids[match position { + 0 => 0, + 1 => ids.len() / 2, + _ => ids.len() - 1, + }]; + truncate_block(&store, broken); + let span = IdSpan::new(1, 0, end); + let blocks = store.iter_blocks(span); + assert_eq!(blocks.len(), ids.len() - 1, "position={position}"); + assert!(blocks + .iter() + .all(|(block, _, _)| block.counter_range.0 != broken.counter)); + assert!(store + .corrupt_block_error() + .unwrap_err() + .to_string() + .contains("cannot parse change block")); + // The legacy iterator also yields the healthy portions, without bounds asserts. + assert!(store.iter_changes(span).count() > 0); + assert!(store + .try_iter_blocks(span) + .unwrap_err() + .to_string() + .contains("cannot parse change block")); + } + } + + #[test] + fn body_validation_stays_lazy_after_header_reads_and_can_be_reset_by_rollback() { + let (store, end, _) = kv_only_store_and_next_change(); + assert!(store.may_have_unparsed_bodies()); + assert!(store.get_dag_nodes_that_contains(ID::new(1, 0)).is_some()); + assert!(store.may_have_unparsed_bodies()); + let arena = store.arena.checkpoint_for_rollback(); + store.visit_all_changes(&mut |_| {}); + assert!(!store.may_have_unparsed_bodies()); + store.rollback_arena(arena); + assert!(store.may_have_unparsed_bodies()); + assert!(store.get_change(ID::new(1, end - 1)).is_some()); + store.visit_all_changes(&mut |_| {}); + assert!(!store.may_have_unparsed_bodies()); + } + + #[test] + fn the_creator_resolver_reports_an_unparsable_block_instead_of_panicking() { + let (store, _, _) = kv_only_store_and_next_change(); + truncate_block(&store, ID::new(1, 0)); + let resolve = store.creator_resolver(); + assert!(store.corrupt_block_error().is_ok()); + assert_eq!(resolve(&store.arena, ID::new(1, 0)), CreatorOp::Corrupt); + let err = store.corrupt_block_error().unwrap_err(); + assert!( + matches!(&err, LoroError::DecodeError(msg) if msg.contains("cannot parse change block")), + "{err}" + ); + } + + #[test] + fn every_reader_records_an_unparsable_block() { + let (store, end, _) = kv_only_store_and_next_change(); + truncate_block(&store, ID::new(1, 0)); + // Readers of the other blocks do not record anything. + assert!(store.get_change(ID::new(1, end - 1)).is_some()); + assert!(store.corrupt_block_error().is_ok()); + assert!(store.get_change(ID::new(1, 0)).is_none()); + assert!(store.corrupt_block_error().is_err()); + + let (store, _, _) = kv_only_store_and_next_change(); + truncate_block(&store, ID::new(1, 0)); + let mut visited = 0; + store.visit_all_changes(&mut |_| visited += 1); + assert!(visited > 0); + assert!(store.corrupt_block_error().is_err()); + + let (store, _, _) = kv_only_store_and_next_change(); + truncate_block(&store, ID::new(1, 0)); + assert!(store.get_change_by_lamport_lte(IdLp::new(1, 0)).is_none()); + assert!(store.corrupt_block_error().is_err()); + } + + /// A doc loaded from a snapshot whose history holds the metadata of a tree node that was + /// created under a deleted parent: only the change that created the node knows the + /// container (loro-dev/loro#1158), and that change is in a block that is not parsed at + /// load. Returns the snapshot, the metadata id, and the peer that created the node. + fn snapshot_with_a_container_only_the_history_knows() -> (Vec<u8>, ContainerID, PeerID) { + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + let tree = a.get_tree("tree"); + let parent = tree.create(TreeParentId::Root).unwrap(); + a.commit_then_renew(); + let b = a.fork(); + b.set_peer_id(2).unwrap(); + let child = b + .get_tree("tree") + .create(TreeParentId::Node(parent)) + .unwrap(); + b.commit_then_renew(); + // Test builds parse each peer's last block at load, so push the create out of it. + for _ in 0..60 { + b.get_text("filler") + .insert(0, &"x".repeat(30), PosType::Unicode) + .unwrap(); + b.commit_then_renew(); + } + tree.delete(parent).unwrap(); + a.commit_then_renew(); + a.import(&b.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + let snapshot = a.export(ExportMode::Snapshot).unwrap(); + (snapshot, child.associated_meta_container(), 2) + } + + #[test] + fn a_doc_with_an_unparsable_block_neither_panics_nor_exports_partial_history() { + let (snapshot, meta, peer) = snapshot_with_a_container_only_the_history_knows(); + let load = || { + let doc = LoroDoc::new(); + doc.import(&snapshot).unwrap(); + doc + }; + // With the block intact, the lookup finds the container through the history. + assert!(load().has_container(&meta)); + + let doc = load(); + truncate_block(&doc.oplog().lock().change_store, ID::new(peer, 0)); + let value = doc.get_deep_value(); + // The same lookup reaches the creator resolver, which used to panic under the state + // lock. It now answers "not a container" and records the block. + assert!(!doc.has_container(&meta)); + assert_eq!(doc.get_deep_value(), value); + + // Entry points that return a `Result` refuse to work from the partial history. + let is_corrupt = |err: LoroError| { + assert!( + err.to_string().contains("cannot parse change block"), + "{err}" + ); + }; + is_corrupt( + doc.checkout(&Frontiers::from(ID::new(peer, 10))) + .unwrap_err(), + ); + is_corrupt( + doc.diff(&Frontiers::from(ID::new(peer, 10)), &doc.oplog_frontiers()) + .unwrap_err(), + ); + is_corrupt(doc.import(&snapshot).unwrap_err()); + is_corrupt(doc.fork_at(&doc.oplog_frontiers()).map(|_| ()).unwrap_err()); + assert!(doc.export(ExportMode::all_updates()).is_err()); + assert!(doc.export(ExportMode::Snapshot).is_err()); + assert!(LoroDoc::new().merge(&doc).is_err()); + assert_eq!(doc.get_deep_value(), value); + } + + #[test] + fn the_first_dag_reader_reports_unparsable_tree_history_without_changing_state() { + let (snapshot, _, peer) = snapshot_with_a_container_only_the_history_knows(); + for api in ["checkout", "diff", "revert", "frontiers", "travel", "cmp"] { + let doc = LoroDoc::new(); + doc.import(&snapshot).unwrap(); + truncate_block(&doc.oplog().lock().change_store, ID::new(peer, 0)); + assert!(doc.oplog().lock().check_history_parsable().is_ok()); + let value = doc.get_deep_value(); + let state_frontiers = doc.state_frontiers(); + let mid = Frontiers::from(ID::new(peer, 10)); + let result = match api { + "checkout" => doc.checkout(&mid).map_err(|err| err.to_string()), + "diff" => doc + .diff(&mid, &state_frontiers) + .map(|_| ()) + .map_err(|err| err.to_string()), + "revert" => doc.revert_to(&mid).map_err(|err| err.to_string()), + "frontiers" => doc + .try_frontiers_to_vv(&mid) + .map(|_| ()) + .map_err(|err| err.to_string()), + "travel" => doc + .travel_change_ancestors(&[ID::new(peer, 10)], &mut |_| { + std::ops::ControlFlow::Continue(()) + }) + .map_err(|err| err.to_string()), + "cmp" => doc + .cmp_frontiers(&mid, &state_frontiers) + .map(|_| ()) + .map_err(|err| err.to_string()), + _ => unreachable!(), + }; + assert!( + result.unwrap_err().contains("cannot parse change block"), + "{api}" + ); + assert_eq!(doc.get_deep_value(), value, "{api}"); + assert_eq!(doc.state_frontiers(), state_frontiers, "{api}"); + assert!(matches!( + doc.oplog().lock().check_history_parsable(), + Err(LoroError::DecodeError(_)) + )); + } + } + + #[test] + fn a_detached_fork_records_unparsable_history_before_its_infallible_boundary_panics() { + let (snapshot, _, peer) = snapshot_with_a_container_only_the_history_knows(); + let doc = LoroDoc::new(); + doc.import(&snapshot).unwrap(); + truncate_block(&doc.oplog().lock().change_store, ID::new(peer, 0)); + let value = doc.get_deep_value(); + doc.detach(); + assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| doc.fork())).is_err()); + assert_eq!(doc.get_deep_value(), value); + assert!(doc + .checkout(&doc.oplog_frontiers()) + .unwrap_err() + .to_string() + .contains("cannot parse change block")); + } + + #[test] + fn a_recorded_parse_failure_does_not_panic_where_no_error_can_be_returned() { + // `undo`, `checkout_to_latest` and a detached `fork` run the same checkout and export + // code as the public entry points, and `unwrap` its result. So the recorded failure + // must only be checked by the entry points that return it. It is recorded by hand + // here: with a block that is really broken, these calls can still panic when the DAG + // needs a node of that block, as they did before the failure was recorded at all. + let (snapshot, _, _) = snapshot_with_a_container_only_the_history_knows(); + let doc = LoroDoc::new(); + doc.import(&snapshot).unwrap(); + doc.set_peer_id(9).unwrap(); + doc.start_auto_commit(); + let undo = crate::UndoManager::new(&doc); + doc.get_text("new") + .insert(0, "edit", PosType::Unicode) + .unwrap(); + doc.commit_then_renew(); + let latest = doc.oplog_frontiers(); + doc.oplog() + .lock() + .change_store + .parse_failures + .record(ID::new(2, 0), &LoroError::DecodeDataCorruptionError); + + assert!(doc.checkout(&latest).is_err()); + assert!(doc.export(ExportMode::Snapshot).is_err()); + assert!(doc.fork_at(&latest).is_err()); + assert!(doc.diff(&latest, &latest).is_err()); + assert!(doc.revert_to(&latest).is_err()); + + doc.detach(); + let fork = doc.fork(); + assert_eq!(fork.get_deep_value(), doc.get_deep_value()); + doc.checkout_to_latest(); + assert!(!doc.is_detached()); + assert_eq!(doc.fork().get_deep_value(), doc.get_deep_value()); + assert!(undo.undo().unwrap()); + assert_eq!(doc.get_text("new").to_string(), ""); + } + + #[test] + fn an_export_that_finds_an_unparsable_block_fails_instead_of_skipping_it() { + // Nothing has recorded the block yet, so the export starts; it must not return + // updates that silently leave the block's changes out. + let (snapshot, _, peer) = snapshot_with_a_container_only_the_history_knows(); + let doc = LoroDoc::new(); + doc.import(&snapshot).unwrap(); + truncate_block(&doc.oplog().lock().change_store, ID::new(peer, 0)); + let err = doc.export(ExportMode::all_updates()).unwrap_err(); + assert!( + err.to_string().contains("cannot parse change block"), + "{err}" + ); + } + + #[test] + fn rollback_evicts_older_blocks_cached_during_the_scope() { + // An import creates the peer's newest block without loading the older ones, + // then a read caches an old KV block (the element lookup of the movable-list + // validator does this). Rolling back removes the newest block; the cached old + // block must not end up right before the next insert of the same change. + let (store, end, next) = kv_only_store_and_next_change(); + let mut old_vv = VersionVector::new(); + old_vv.insert(1, end); + let mut rollback = ChangeStoreRollback::new(Arc::new(old_vv)); + let arena = store.arena.checkpoint_for_rollback(); + store.insert_change_with_rollback(next.clone(), true, false, &mut rollback); + assert!(store.get_change(ID::new(1, 0)).is_some()); + store.rollback_import(rollback, arena); + store.insert_change(next, true, false); + assert!(store.get_change(ID::new(1, end)).is_some()); + assert!(store.get_change(ID::new(1, 0)).is_some()); + } + + #[test] + fn rollback_restores_unflushed_block_that_was_appended_to() { + // The rollback keeps only the shape of a block an import appended to and + // truncates back to it. Appends both push changes and merge ops into the last + // change, so the restored store must encode exactly like one that never saw + // the rolled-back changes. + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + // Keep the commits as separate changes; the store below merges them itself. + doc.set_change_merge_interval(-1); + let text = doc.get_text("t"); + for i in 0..40 { + text.insert(i, "a", PosType::Unicode).unwrap(); + if i % 3 == 0 { + doc.get_map("m").insert("k", i as i64).unwrap(); + } + doc.commit_then_renew(); + } + let mut changes = Vec::new(); + let arena = { + let oplog = doc.oplog().lock(); + oplog + .change_store + .visit_all_changes(&mut |c| changes.push(c.clone())); + oplog.arena.clone() + }; + // The changes reference the doc's containers and values. + let new_store = || ChangeStore::new_mem(&arena, Arc::new(AtomicI64::new(0))); + assert!(changes.len() > 10); + let (first, rest) = changes.split_at(changes.len() / 2); + let vv_of = |cs: &[Change]| { + let mut vv = VersionVector::new(); + vv.insert(1, cs.last().unwrap().ctr_end()); + vv + }; + + let rolled_back = new_store(); + for c in first { + rolled_back.insert_change(c.clone(), true, false); + } + let mut rollback = ChangeStoreRollback::new(Arc::new(vv_of(first))); + let arena_checkpoint = arena.checkpoint_for_rollback(); + for c in &rest[..rest.len() / 2] { + rolled_back.insert_change_with_rollback(c.clone(), true, false, &mut rollback); + } + rolled_back.rollback_import(rollback, arena_checkpoint); + assert!(rolled_back + .get_change(ID::new(1, vv_of(first)[&1])) + .is_none()); + for c in rest { + rolled_back.insert_change(c.clone(), true, false); + } + + let direct = new_store(); + for c in &changes { + direct.insert_change(c.clone(), true, false); + } + let vv = vv_of(&changes); + let frontiers = Frontiers::from_id(changes.last().unwrap().id_last()); + assert_eq!( + rolled_back.encode_all(&vv, &frontiers), + direct.encode_all(&vv, &frontiers) + ); + } + + #[test] + fn lamport_lookup_finds_unflushed_mem_blocks() { + // Regression: when the lamport binary search bails out, the fallback + // used to scan only the external kv store. Local changes may exist + // solely in `mem_parsed_kv` before any flush, so a lookup targeting a + // lamport gap incorrectly returned `None`. + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let text = doc.get_text("t"); + text.insert(0, &"x".repeat(500), PosType::Unicode).unwrap(); + doc.commit_then_renew(); + + // An independent large change from peer 2 pushes peer 1's next + // lamport far above its first change (gap > MAX_BLOCK_SIZE * 8, so + // lookups below engage the binary search path). + let doc2 = LoroDoc::new_auto_commit(); + doc2.set_peer_id(2).unwrap(); + let text2 = doc2.get_text("t2"); + text2 + .insert(0, &"y".repeat(3000), PosType::Unicode) + .unwrap(); + doc2.commit_then_renew(); + doc.import(&doc2.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + + let text = doc.get_text("t"); + text.insert(0, &"z".repeat(500), PosType::Unicode).unwrap(); + doc.commit_then_renew(); + + // Query a lamport inside the gap between peer 1's two changes, + // without flushing the change store. The answer (the tail of peer 1's + // first commit) lives only in `mem_parsed_kv`. + let oplog = doc.oplog().lock(); + let change = oplog + .change_store + .get_change_by_lamport_lte(IdLp::new(1, 700)) + .expect("the change should be found in the unflushed mem blocks"); + assert_eq!(change.id.peer, 1); + assert!(change.lamport <= 700); + assert_eq!(change.id.counter + change.atom_len() as Counter, 500); + } + + #[test] + fn root_history_names_reject_oversized_name_without_retaining_it() { + let mut names = FxHashSet::default(); + let mut name_bytes = 0; + let oversized_name = "x".repeat(MAX_ROOT_HISTORY_NAME_BYTES + 1); + let oversized = ContainerID::new_root(&oversized_name, crate::ContainerType::Map); + + assert!(!record_root_name(&mut names, &mut name_bytes, &oversized)); + assert!(names.is_empty()); + assert_eq!(name_bytes, 0); + } + + #[test] + fn test_change_store() { + let doc = LoroDoc::new_auto_commit(); + doc.set_record_timestamp(true); + let t = doc.get_text("t"); + t.insert(0, "hello", PosType::Unicode).unwrap(); + doc.commit_then_renew(); + let t = doc.get_list("t"); + t.insert(0, "hello").unwrap(); + test_encode_decode(doc); + } + + #[test] + fn test_synced_doc() -> LoroResult<()> { + let doc_a = LoroDoc::new_auto_commit(); + let doc_b = LoroDoc::new_auto_commit(); + let doc_c = LoroDoc::new_auto_commit(); + + { + // A: Create initial structure + let map = doc_a.get_map("root"); + map.insert_container("text", TextHandler::new_detached())?; + map.insert_container("list", ListHandler::new_detached())?; + map.insert_container("tree", TreeHandler::new_detached())?; + } + + { + // Sync initial state to B and C + let initial_state = doc_a.export(ExportMode::all_updates()).unwrap(); + doc_b.import(&initial_state)?; + doc_c.import(&initial_state)?; + } + + { + // B: Edit text and list + let map = doc_b.get_map("root"); + let text = map + .insert_container("text", TextHandler::new_detached()) + .unwrap(); + text.insert(0, "Hello, ", PosType::Unicode)?; + + let list = map + .insert_container("list", ListHandler::new_detached()) + .unwrap(); + list.push("world")?; + } + + { + // C: Edit tree and movable list + let map = doc_c.get_map("root"); + let tree = map + .insert_container("tree", TreeHandler::new_detached()) + .unwrap(); + let node_id = tree.create(TreeParentId::Root)?; + tree.get_meta(node_id)?.insert("key", "value")?; + let node_b = tree.create(TreeParentId::Root)?; + tree.move_to(node_b, TreeParentId::Root, 0).unwrap(); + + let movable_list = map + .insert_container("movable", MovableListHandler::new_detached()) + .unwrap(); + movable_list.push("item1".into())?; + movable_list.push("item2".into())?; + movable_list.mov(0, 1)?; + } + + // Sync B's changes to A + let b_changes = doc_b + .export(ExportMode::updates(&doc_a.oplog_vv())) + .unwrap(); + doc_a.import(&b_changes)?; + + // Sync C's changes to A + let c_changes = doc_c + .export(ExportMode::updates(&doc_a.oplog_vv())) + .unwrap(); + doc_a.import(&c_changes)?; + + test_encode_decode(doc_a); + Ok(()) + } +} diff --git a/vendor/loro-internal/src/oplog/change_store/block_encode.rs b/vendor/loro-internal/src/oplog/change_store/block_encode.rs new file mode 100644 index 0000000..641fde0 --- /dev/null +++ b/vendor/loro-internal/src/oplog/change_store/block_encode.rs @@ -0,0 +1,1099 @@ +//! # Encode +//! +//! ```log +//! ≈4KB after compression +//! +//! N = Number of Changes +//! +//! Peer_1 = This Peer +//! +//! +//! ┌────────────────────────┬─────────────────────────────────────┐ +//! │ LEB Counter Start&Len │ LEB Lamport Start&Len │◁───┐ +//! └────────────────────────┴─────────────────────────────────────┘ │ +//! ┌──────────────┬──────────────┬────────────────────────────────┐ │ +//! │ LEB N │ LEB Peer Num │ 8B Peer_1,...,Peer_x │◁───┤ +//! └──────────────┴──────────────┴────────────────────────────────┘ │ +//! ┌──────────────────────────────────────────────────────────────┐ │ +//! │ N LEB128 Change AtomLen │◁───┼───── Important metadata +//! └──────────────────────────────────────────────────────────────┘ │ +//! ┌───────────────────┬────────────────────────┬─────────────────┐ │ +//! │N DepOnSelf BoolRle│ N Delta Rle Deps Lens │ Dep IDs │◁───┤ +//! └───────────────────┴────────────────────────┴─────────────────┘ │ +//! ┌──────────────────────────────────────────────────────────────┐ │ +//! │ N LEB128 Delta Lamports │◁───┘ +//! └──────────────────────────────────────────────────────────────┘ +//! ┌──────────────────────────────────────────────────────────────┐ +//! │ N LEB128 DeltaOfDelta Timestamps │ +//! └──────────────────────────────────────────────────────────────┘ +//! ┌────────────────────────────────┬─────────────────────────────┐ +//! │ N Rle Commit Msg Lengths │ Commit Messages │ +//! └────────────────────────────────┴─────────────────────────────┘ +//! +//! ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ Encoded Operations ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ +//! +//! ┌────────────────────┬─────────────────────────────────────────┐ +//! │ ContainerIDs Size │ ContainerIDs │ +//! └────────────────────┴─────────────────────────────────────────┘ +//! ┌────────────────────┬─────────────────────────────────────────┐ +//! │ Key Strings Size │ Key Strings │ +//! └────────────────────┴─────────────────────────────────────────┘ +//! ┌────────────────────┬─────────────────────────────────────────┐ +//! │ Position Size │ Position │ +//! └────────────────────┴─────────────────────────────────────────┘ +//! ┌────────┬──────────┬──────────┬───────┬───────────────────────┐ +//! │ │ │ │ │ │ +//! │ │ │ │ │ │ +//! │ │ │ │ │ │ +//! │ Ops │ LEB128 │ RLE │ Delta │ │ +//! │ Size │ Lengths │Containers│ RLE │ ValueType │ +//! │ │ │ │ Props │ │ +//! │ │ │ │ │ │ +//! │ │ │ │ │ │ +//! │ │ │ │ │ │ +//! └────────┴──────────┴──────────┴───────┴───────────────────────┘ +//! ┌──────────────────────────────────────────────────────────────┐ +//! │ (Encoded with Ops By serde_columnar) │ +//! │ Delete Start IDs │ +//! │ │ +//! └──────────────────────────────────────────────────────────────┘ +//! ┌────────────────┬─────────────────────────────────────────────┐ +//! │ │ │ +//! │Value Bytes Size│ Value Bytes │ +//! │ │ │ +//! └────────────────┴─────────────────────────────────────────────┘ +//! ``` + +use std::borrow::Cow; +use std::collections::BTreeSet; +use std::io::Write; +use std::sync::Arc; + +use fractional_index::FractionalIndex; +use loro_common::{ + ContainerID, Counter, HasCounterSpan, HasLamportSpan, InternalString, Lamport, LoroError, + LoroResult, PeerID, TreeID, ID, +}; +use once_cell::sync::OnceCell; +use rle::HasLength; +use serde::{Deserialize, Serialize}; +use serde_columnar::{columnar, AnyRleDecoder, DeltaOfDeltaDecoder, Itertools}; +use tracing::info; + +use super::block_meta_encode::decode_changes_header; +use crate::arena::SharedArena; +use crate::change::{Change, Timestamp}; +use crate::container::list::list_op::InnerListOp; +use crate::container::tree::tree_op; +use crate::encoding::arena::{ContainerArena, PositionArena}; +use crate::encoding::value_register::ValueRegister; +use crate::encoding::{ + self, decode_op, encode_op, get_op_prop, DecodedBlockBuffers, EncodedDeleteStartId, + IterableEncodedDeleteStartId, +}; +use crate::op::{InnerContent, Op}; + +#[derive(Debug, Serialize, Deserialize)] +struct EncodedBlock<'a> { + counter_start: u32, + counter_len: u32, + lamport_start: u32, + lamport_len: u32, + n_changes: u32, + #[serde(borrow)] + header: Cow<'a, [u8]>, + // timestamp and commit messages + #[serde(borrow)] + change_meta: Cow<'a, [u8]>, + // ---------------------- Ops ---------------------- + #[serde(borrow)] + cids: Cow<'a, [u8]>, + #[serde(borrow)] + keys: Cow<'a, [u8]>, + #[serde(borrow)] + positions: Cow<'a, [u8]>, + #[serde(borrow)] + ops: Cow<'a, [u8]>, + #[serde(borrow)] + delete_start_ids: Cow<'a, [u8]>, + #[serde(borrow)] + values: Cow<'a, [u8]>, +} + +fn diagnose_block(block: &EncodedBlock) { + info!("Diagnosing EncodedBlock:"); + info!(" header {} bytes", block.header.len()); + info!(" change_meta {} bytes", block.change_meta.len()); + info!(" cids: {} bytes", block.cids.len()); + info!(" keys: {} bytes", block.keys.len()); + info!(" positions: {} bytes", block.positions.len()); + info!(" ops: {} bytes", block.ops.len()); + info!(" delete_id_starts: {} bytes", block.delete_start_ids.len()); + info!(" values: {} bytes", block.values.len()); +} + +// MARK: encode_block +/// It's assume that every change in the block share the same peer. +pub fn encode_block(block: &[Change], arena: &SharedArena) -> Vec<u8> { + if block.is_empty() { + panic!("Empty block") + } + + let mut peer_register: ValueRegister<PeerID> = ValueRegister::new(); + let peer = block[0].peer(); + peer_register.register(&peer); + + let cid_register: ValueRegister<ContainerID> = ValueRegister::new(); + + let mut encoded_ops = Vec::new(); + let mut registers = Registers { + peer_register, + key_register: ValueRegister::new(), + cid_register, + position_register: ValueRegister::new(), + }; + + { + // Init position register, making it ordered by fractional index + let mut position_set = BTreeSet::default(); + for c in block { + for op in c.ops().iter() { + if let crate::op::InnerContent::Tree(tree_op) = &op.content { + match &**tree_op { + tree_op::TreeOp::Create { position, .. } => { + position_set.insert(position.clone()); + } + tree_op::TreeOp::Move { position, .. } => { + position_set.insert(position.clone()); + } + tree_op::TreeOp::Delete { .. } => {} + } + } + } + } + + for position in position_set { + registers.position_register.register(&position); + } + } + + let mut del_starts: Vec<_> = Vec::new(); + let mut value_writer = ValueWriter::new(); + for c in block { + for op in c.ops().iter() { + let cid = arena.get_container_id(op.container).unwrap(); + let cidx = registers.cid_register.register(&cid); + let prop = get_op_prop(op, &mut registers); + let value_kind = encode_op(op, &mut del_starts, &mut value_writer, &mut registers); + encoded_ops.push(EncodedOp { + container_index: cidx as u32, + prop, + value_type: value_kind.to_u8(), + len: op.atom_len() as u32, + }) + } + } + + let cids = registers.cid_register.unwrap_vec(); + let container_arena = ContainerArena::from_containers( + cids, + &mut registers.peer_register, + &mut registers.key_register, + ); + + // Write to output + + // ┌────────────────────┬─────────────────────────────────────────┐ + // │ Key Strings Size │ Key Strings │ + // └────────────────────┴─────────────────────────────────────────┘ + let keys = registers.key_register.unwrap_vec(); + let keys_bytes = encode_keys(keys); + + // ┌────────────────────┬─────────────────────────────────────────┐ + // │ Position Size │ Position │ + // └────────────────────┴─────────────────────────────────────────┘ + let position_vec = registers.position_register.unwrap_vec(); + let positions = PositionArena::from_positions(position_vec.iter().map(|p| p.as_bytes())); + let position_bytes = positions.encode_v2(); + + // ┌──────────┬──────────┬───────┬────────────────────────────────┐ + // │ │ │ │ │ + // │ │ │ │ │ + // │ │ │ │ │ + // │ LEB128 │ RLE │ Delta │ │ + // │ Lengths │Containers│ RLE │ ValueType │ + // │ │ │ Props │ │ + // │ │ │ │ │ + // │ │ │ │ │ + // │ │ │ │ │ + // └──────────┴──────────┴───────┴────────────────────────────────┘ + + let ops_bytes = serde_columnar::to_vec(&EncodedOps { ops: encoded_ops }).unwrap(); + + let delete_id_starts_bytes = if del_starts.is_empty() { + Vec::new() + } else { + serde_columnar::to_vec(&EncodedDeleteStartIds { + delete_start_ids: del_starts, + }) + .unwrap() + }; + // ┌────────────────┬─────────────────────────────────────────────┐ + // │Value Bytes Size│ Value Bytes │ + // └────────────────┴─────────────────────────────────────────────┘ + + // PeerIDs + let mut peer_register = registers.peer_register; + // .unwrap_vec(); + // let peer_bytes: Vec<u8> = peers.iter().flat_map(|p| p.to_le_bytes()).collect(); + + // Change meta + let (header, change_meta) = encode_changes(block, &mut peer_register); + + let value_bytes = value_writer.finish(); + let out = EncodedBlock { + counter_start: block[0].id.counter as u32, + counter_len: (block.last().unwrap().ctr_end() - block[0].id.counter) as u32, + lamport_start: block[0].lamport(), + lamport_len: block.last().unwrap().lamport_end() - block[0].lamport(), + n_changes: block.len() as u32, + header: header.into(), + change_meta: change_meta.into(), + cids: container_arena.encode().into(), + keys: keys_bytes.into(), + positions: position_bytes.into(), + ops: ops_bytes.into(), + delete_start_ids: delete_id_starts_bytes.into(), + values: value_bytes.into(), + }; + + diagnose_block(&out); + postcard::to_allocvec(&out).unwrap() +} + +fn encode_keys(keys: Vec<loro_common::InternalString>) -> Vec<u8> { + let mut keys_bytes = Vec::new(); + for key in keys { + let bytes = key.as_bytes(); + leb128::write::unsigned(&mut keys_bytes, bytes.len() as u64).unwrap(); + keys_bytes.write_all(bytes).unwrap(); + } + keys_bytes +} + +fn decode_keys(mut bytes: &[u8]) -> LoroResult<Vec<InternalString>> { + let mut keys = Vec::new(); + while !bytes.is_empty() { + let len = leb128::read::unsigned(&mut bytes) + .map_err(|_| LoroError::DecodeDataCorruptionError)? as usize; + if bytes.len() < len { + return Err(LoroError::DecodeDataCorruptionError); + } + let key = + std::str::from_utf8(&bytes[..len]).map_err(|_| LoroError::DecodeDataCorruptionError)?; + keys.push(key.into()); + bytes = &bytes[len..]; + } + + Ok(keys) +} + +struct Registers { + peer_register: ValueRegister<PeerID>, + key_register: ValueRegister<loro_common::InternalString>, + cid_register: ValueRegister<ContainerID>, + position_register: ValueRegister<FractionalIndex>, +} + +use crate::encoding::value::{ + RawTreeMove, Value, ValueDecodedArenasTrait, ValueEncodeRegister, ValueKind, ValueReader, + ValueWriter, +}; +use crate::oplog::change_store::block_meta_encode::encode_changes; +use crate::version::Frontiers; +impl ValueEncodeRegister for Registers { + fn key_mut(&mut self) -> &mut ValueRegister<loro_common::InternalString> { + &mut self.key_register + } + + fn peer_mut(&mut self) -> &mut ValueRegister<PeerID> { + &mut self.peer_register + } + + fn encode_tree_op(&mut self, op: &tree_op::TreeOp) -> encoding::value::Value<'static> { + match op { + tree_op::TreeOp::Create { + target, + parent, + position, + } => encoding::value::Value::RawTreeMove(RawTreeMove { + subject_peer_idx: self.peer_register.register(&target.peer), + subject_cnt: target.counter, + is_parent_null: parent.is_none(), + parent_peer_idx: parent.map_or(0, |p| self.peer_register.register(&p.peer)), + parent_cnt: parent.map_or(0, |p| p.counter), + position_idx: self.position_register.register(position), + }), + tree_op::TreeOp::Move { + target, + parent, + position, + } => encoding::value::Value::RawTreeMove(RawTreeMove { + subject_peer_idx: self.peer_register.register(&target.peer), + subject_cnt: target.counter, + is_parent_null: parent.is_none(), + parent_peer_idx: parent.map_or(0, |p| self.peer_register.register(&p.peer)), + parent_cnt: parent.map_or(0, |p| p.counter), + position_idx: self.position_register.register(position), + }), + tree_op::TreeOp::Delete { target } => { + let parent = TreeID::delete_root(); + encoding::value::Value::RawTreeMove(RawTreeMove { + subject_peer_idx: self.peer_register.register(&target.peer), + subject_cnt: target.counter, + is_parent_null: false, + parent_peer_idx: self.peer_register.register(&parent.peer), + parent_cnt: parent.counter, + position_idx: 0, + }) + } + } + } +} + +#[derive(Debug, Clone)] +pub(crate) struct ChangesBlockHeader { + pub peer: PeerID, + pub counter: Counter, + pub n_changes: usize, + pub peers: Vec<PeerID>, + /// This has n + 1 elements, where counters[n] is the end counter of the + /// last change in the block. + /// + /// You can infer the size of kth change by taking counters[k + 1] - counters[k] + pub counters: Vec<Counter>, + /// This has n elements + pub lamports: Vec<Lamport>, + pub deps_groups: Vec<Frontiers>, + pub keys: OnceCell<Vec<InternalString>>, + pub cids: OnceCell<Vec<ContainerID>>, +} + +pub fn decode_header(m_bytes: &[u8]) -> LoroResult<ChangesBlockHeader> { + let doc = postcard::from_bytes(m_bytes) + .map_err(|e| LoroError::DecodeError(format!("Decode block error {e}").into_boxed_str()))?; + + decode_header_from_doc(&doc) +} + +// MARK: decode_block_from_doc +fn decode_header_from_doc(doc: &EncodedBlock) -> Result<ChangesBlockHeader, LoroError> { + let EncodedBlock { + n_changes, + header, + counter_len, + counter_start, + lamport_len, + lamport_start, + .. + } = doc; + let ans: ChangesBlockHeader = decode_changes_header( + header, + *n_changes as usize, + *counter_start as Counter, + *counter_len as Counter, + *lamport_start, + *lamport_len, + )?; + Ok(ans) +} + +#[columnar(vec, ser, de, iterable)] +#[derive(Debug, Clone)] +struct EncodedOp { + #[columnar(strategy = "DeltaRle")] + container_index: u32, + #[columnar(strategy = "DeltaRle")] + prop: i32, + #[columnar(strategy = "Rle")] + value_type: u8, + #[columnar(strategy = "Rle")] + len: u32, +} + +#[columnar(ser, de)] +struct EncodedOps { + #[columnar(class = "vec", iter = "EncodedOp")] + ops: Vec<EncodedOp>, +} + +#[columnar(ser, de)] +struct EncodedDeleteStartIds { + #[columnar(class = "vec", iter = "EncodedDeleteStartId")] + delete_start_ids: Vec<EncodedDeleteStartId>, +} + +struct ValueDecodeArena<'a> { + peers: &'a [PeerID], + keys: &'a [InternalString], +} + +impl ValueDecodedArenasTrait for ValueDecodeArena<'_> { + fn keys(&self) -> &[InternalString] { + self.keys + } + + fn peers(&self) -> &[PeerID] { + self.peers + } + + fn decode_tree_op( + &self, + _positions: &[Vec<u8>], + _op: encoding::value::EncodedTreeMove, + _id: ID, + ) -> LoroResult<tree_op::TreeOp> { + Err(LoroError::DecodeDataCorruptionError) + } +} + +/// Read the counter and lamport ranges from the first fields of an encoded block +/// without decoding the rest. +/// +/// The block is a postcard-encoded [`EncodedBlock`], whose leading `u32` fields are +/// varints, so they can be read as LEB128 in declaration order. There is no version +/// prefix: reading one shifted every field and broke lamport lookups on blocks that +/// only live in the KV store (`ChangeStore::get_change_by_lamport_lte`). +pub fn decode_block_range( + mut bytes: &[u8], +) -> LoroResult<((Counter, Counter), (Lamport, Lamport))> { + let counter_start = leb128::read::unsigned(&mut bytes).map_err(|e| { + LoroError::DecodeError(format!("Failed to read counter start: {e}").into_boxed_str()) + })?; + let counter_start = + Counter::try_from(counter_start).map_err(|_| LoroError::DecodeDataCorruptionError)?; + let counter_len = leb128::read::unsigned(&mut bytes).map_err(|e| { + LoroError::DecodeError(format!("Failed to read counter length: {e}").into_boxed_str()) + })?; + let counter_len = + Counter::try_from(counter_len).map_err(|_| LoroError::DecodeDataCorruptionError)?; + let lamport_start = leb128::read::unsigned(&mut bytes).map_err(|e| { + LoroError::DecodeError(format!("Failed to read lamport start: {e}").into_boxed_str()) + })?; + let lamport_start = + Lamport::try_from(lamport_start).map_err(|_| LoroError::DecodeDataCorruptionError)?; + let lamport_len = leb128::read::unsigned(&mut bytes).map_err(|e| { + LoroError::DecodeError(format!("Failed to read lamport length: {e}").into_boxed_str()) + })?; + let lamport_len = + Lamport::try_from(lamport_len).map_err(|_| LoroError::DecodeDataCorruptionError)?; + Ok(( + ( + counter_start, + counter_start + .checked_add(counter_len) + .ok_or(LoroError::DecodeDataCorruptionError)?, + ), + ( + lamport_start, + lamport_start + .checked_add(lamport_len) + .ok_or(LoroError::DecodeDataCorruptionError)?, + ), + )) +} + +/// Ensure the cids in header are decoded +#[allow(unused)] +pub fn decode_cids( + bytes: &[u8], + header: Option<ChangesBlockHeader>, +) -> LoroResult<ChangesBlockHeader> { + let doc = postcard::from_bytes(bytes) + .map_err(|e| LoroError::DecodeError(format!("Decode block error {e}").into_boxed_str()))?; + let header = if let Some(h) = header { + h + } else { + let doc = postcard::from_bytes(bytes).map_err(|e| { + LoroError::DecodeError(format!("Decode block error {e}").into_boxed_str()) + })?; + decode_header_from_doc(&doc)? + }; + + if header.cids.get().is_some() { + return Ok(header); + } + + let EncodedBlock { cids, keys, .. } = doc; + let keys = header.keys.get_or_try_init(|| decode_keys(&keys))?; + let decode_arena = ValueDecodeArena { + peers: &header.peers, + keys, + }; + + header.cids.get_or_try_init(|| { + ContainerArena::decode(&cids)? + .iter() + .map(|x| x.as_container_id(&decode_arena)) + .try_collect() + })?; + Ok(header) +} + +/// Visit a Text-insert-only block without building changes or allocating arena +/// strings. Other op kinds use the general decoder and semantic comparison. +/// Timestamps/messages are intentionally irrelevant to known-history equality. +pub(super) fn visit_text_insert_block( + bytes: &[u8], + mut on_insert: impl FnMut(Counter, &ContainerID, u32, &str, u32, &Frontiers) -> LoroResult<()>, +) -> LoroResult<bool> { + use crate::encoding::value::{ValueKind, ValueReader}; + let doc: EncodedBlock<'_> = + postcard::from_bytes(bytes).map_err(|_| LoroError::DecodeDataCorruptionError)?; + let header = decode_cids(bytes, None)?; + let cids = header.cids.get().unwrap(); + let mut reader = ValueReader::new(&doc.values); + let ops = serde_columnar::iter_from_bytes::<EncodedOps>(&doc.ops)?.ops; + let mut counter = header.counter; + let mut change_index = 0; + for op in ops { + let op = op?; + let cid = cids + .get(op.container_index as usize) + .ok_or(LoroError::DecodeDataCorruptionError)?; + if cid.container_type() != loro_common::ContainerType::Text + || op.value_type != ValueKind::Str.to_u8() + { + return Ok(false); + } + let text = reader.read_str()?; + if text.chars().count() != op.len as usize { + return Err(LoroError::DecodeDataCorruptionError); + } + let implicit_deps = Frontiers::from_id(ID::new( + header.peer, + counter + .checked_sub(1) + .ok_or(LoroError::DecodeDataCorruptionError)?, + )); + let deps = if header.counters.get(change_index) == Some(&counter) { + header + .deps_groups + .get(change_index) + .ok_or(LoroError::DecodeDataCorruptionError)? + } else { + &implicit_deps + }; + on_insert(counter, cid, op.prop as u32, text, op.len, deps)?; + counter = counter + .checked_add(op.len as Counter) + .ok_or(LoroError::DecodeDataCorruptionError)?; + if header.counters.get(change_index + 1) == Some(&counter) { + change_index += 1; + } else if header + .counters + .get(change_index + 1) + .is_none_or(|&end| counter > end) + { + return Err(LoroError::DecodeDataCorruptionError); + } + } + if Some(&counter) != header.counters.last() { + return Err(LoroError::DecodeDataCorruptionError); + } + Ok(true) +} + +// MARK: decode_block +pub fn decode_block( + m_bytes: &[u8], + shared_arena: &SharedArena, + header: Option<&ChangesBlockHeader>, +) -> LoroResult<Vec<Change>> { + let doc = postcard::from_bytes(m_bytes) + .map_err(|e| LoroError::DecodeError(format!("Decode block error {e}").into_boxed_str()))?; + let header_on_stack; + let header = if let Some(header) = header { + header + } else { + header_on_stack = decode_header_from_doc(&doc)?; + &header_on_stack + }; + let EncodedBlock { + n_changes, + counter_start: first_counter, + change_meta, + cids, + keys, + ops, + delete_start_ids, + values, + positions, + .. + } = doc; + let n_changes = n_changes as usize; + let mut changes = Vec::with_capacity(n_changes); + let timestamp_decoder = DeltaOfDeltaDecoder::<i64>::new(&change_meta) + .map_err(|_| LoroError::DecodeDataCorruptionError)?; + let (timestamps, bytes) = timestamp_decoder + .take_n_finalize(n_changes) + .map_err(|_| LoroError::DecodeDataCorruptionError)?; + let commit_msg_len_decoder = AnyRleDecoder::<u32>::new(bytes); + let (commit_msg_lens, commit_msgs) = commit_msg_len_decoder + .take_n_finalize(n_changes) + .map_err(|_| LoroError::DecodeDataCorruptionError)?; + let mut commit_msg_index = 0u32; + let keys = header.keys.get_or_try_init(|| decode_keys(&keys))?; + let decode_arena = ValueDecodeArena { + peers: &header.peers, + keys, + }; + let positions = PositionArena::decode_v2(&positions)?; + let positions = positions.try_parse_to_positions()?; + let cids: &Vec<ContainerID> = header.cids.get_or_try_init(|| { + ContainerArena::decode(&cids)? + .iter() + .map(|x| x.as_container_id(&decode_arena)) + .try_collect() + })?; + // Text values are substrings of `values`, so its length bounds the text. + let mut buffers = DecodedBlockBuffers::new(values.len()); + let mut value_reader = ValueReader::new(&values); + let encoded_ops_iters = serde_columnar::iter_from_bytes::<EncodedOps>(&ops)?; + let op_iter = encoded_ops_iters.ops; + let encoded_delete_id_starts: EncodedDeleteStartIds = if delete_start_ids.is_empty() { + EncodedDeleteStartIds { + delete_start_ids: Vec::new(), + } + } else { + serde_columnar::from_bytes(&delete_start_ids)? + }; + let mut del_iter = encoded_delete_id_starts + .delete_start_ids + .into_iter() + .map(Ok); + for i in 0..n_changes { + let commit_msg: Option<Arc<str>> = { + let len = *commit_msg_lens + .get(i) + .ok_or(LoroError::DecodeDataCorruptionError)?; + if len == 0 { + None + } else { + let end = commit_msg_index + .checked_add(len) + .ok_or(LoroError::DecodeDataCorruptionError)?; + if commit_msgs.len() < end as usize { + return Err(LoroError::DecodeDataCorruptionError); + } + match std::str::from_utf8(&commit_msgs[commit_msg_index as usize..end as usize]) { + Ok(s) => { + commit_msg_index = end; + Some(Arc::from(s)) + } + Err(_) => { + tracing::error!("Invalid UTF8 String"); + return LoroResult::Err(LoroError::DecodeDataCorruptionError); + } + } + } + }; + changes.push(Change { + ops: Default::default(), + deps: header + .deps_groups + .get(i) + .ok_or(LoroError::DecodeDataCorruptionError)? + .clone(), + id: ID::new( + header.peer, + *header + .counters + .get(i) + .ok_or(LoroError::DecodeDataCorruptionError)?, + ), + lamport: *header + .lamports + .get(i) + .ok_or(LoroError::DecodeDataCorruptionError)?, + timestamp: *timestamps + .get(i) + .ok_or(LoroError::DecodeDataCorruptionError)? as Timestamp, + commit_msg, + }) + } + + let mut counter = first_counter as Counter; + let mut change_index = 0; + let peer = header.peer; + // Ops are pushed into their changes, which merges them, only after + // `buffers.finish` has filled their list values. + let mut decoded_ops: Vec<(usize, Op)> = Vec::new(); + for op in op_iter { + let EncodedOp { + container_index, + prop, + value_type, + len, + } = op?; + let value = Value::decode( + ValueKind::from_u8(value_type), + &mut value_reader, + &decode_arena, + ID::new(peer, counter), + )?; + + let cid = cids + .get(container_index as usize) + .ok_or(LoroError::DecodeDataCorruptionError)?; + let content = decode_op( + cid, + value, + &mut del_iter, + &mut buffers, + &decode_arena, + &positions, + prop, + ID::new(peer, counter), + )?; + + let c_idx = shared_arena.register_container(cid); + let op = Op { + counter, + container: c_idx, + content, + }; + + if change_index >= changes.len() { + return Err(LoroError::DecodeDataCorruptionError); + } + decoded_ops.push((change_index, op)); + counter = counter + .checked_add(len as Counter) + .ok_or(LoroError::DecodeDataCorruptionError)?; + let next_counter = header + .counters + .get(change_index + 1) + .ok_or(LoroError::DecodeDataCorruptionError)?; + if counter >= *next_counter { + change_index += 1; + } + } + buffers.finish( + decoded_ops + .iter_mut() + .filter_map(|(_, op)| match &mut op.content { + InnerContent::List(InnerListOp::Insert { slice, .. }) => Some(slice), + _ => None, + }), + ); + for (change_index, op) in decoded_ops { + changes[change_index].ops.push(op); + } + Ok(changes) +} + +#[cfg(test)] +mod test { + use std::{borrow::Cow, panic::AssertUnwindSafe}; + + use loro_common::ContainerType; + + use crate::encoding::value::{EncodedTreeMove, Value}; + use crate::{cursor::PosType, delta::DeltaValue, loro::ExportMode, LoroDoc}; + + use super::*; + + #[test] + fn block_range_rejects_overflow_instead_of_panicking_on_external_bytes() { + for fields in [ + [u64::MAX, 0, 0, 0], + [Counter::MAX as u64, 1, 0, 0], + [0, u64::MAX, 0, 0], + [0, 0, Lamport::MAX as u64, 1], + ] { + let mut bytes = Vec::new(); + for field in fields { + leb128::write::unsigned(&mut bytes, field).unwrap(); + } + assert!(decode_block_range(&bytes).is_err()); + } + } + + /// Blocks written by older versions or by loro.js can hold adjacent list + /// inserts that the current rules merge while decoding. A one-value insert + /// followed by a larger one used to merge with a slice whose values were not + /// decoded yet, and panicked (loro-dev/loro#1197 CI, loro.js differential). + #[test] + fn decode_block_with_unmerged_adjacent_list_inserts() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + doc.get_list("list").insert(0, "a").unwrap(); + doc.commit_then_renew(); + + let oplog = doc.oplog.lock(); + let mut changes = Vec::new(); + oplog + .change_store() + .visit_all_changes(&mut |change| changes.push(change.clone())); + assert_eq!(changes.len(), 1); + let mut change = changes.pop().unwrap(); + let first = change.ops.vec()[0].clone(); + let mut second = first.clone(); + second.counter = 1; + second.content = InnerContent::List(InnerListOp::Insert { + slice: crate::op::ValueSlice::new(vec!["b".into(), "c".into()]), + pos: 1, + }); + // Bypass `RleVec::push`, which would merge the two ops. + change.ops.vec_mut().push(second); + let bytes = encode_block(&[change], &oplog.arena); + + let decoded = decode_block(&bytes, &oplog.arena, None).unwrap(); + let mut values = Vec::new(); + for op in decoded[0].ops.iter() { + let InnerContent::List(InnerListOp::Insert { slice, .. }) = &op.content else { + unreachable!() + }; + values.extend_from_slice(slice.as_slice()); + } + assert_eq!(values, vec!["a".into(), "b".into(), "c".into()]); + } + + #[test] + fn decode_block_rejects_corrupt_payload_without_panic() { + let doc = LoroDoc::new_auto_commit(); + doc.get_map("map").insert("x", 100).unwrap(); + doc.commit_then_renew(); + + let oplog = doc.oplog.lock(); + let mut changes = Vec::new(); + oplog + .change_store() + .visit_all_changes(&mut |change| changes.push(change.clone())); + let block_bytes = encode_block(&changes, &oplog.arena); + let mut encoded: EncodedBlock = postcard::from_bytes(&block_bytes).unwrap(); + encoded.change_meta = Cow::Owned(vec![0x80]); + let corrupt = postcard::to_allocvec(&encoded).unwrap(); + + let result = std::panic::catch_unwind(AssertUnwindSafe(|| { + decode_block(&corrupt, &oplog.arena, None) + })); + assert!(result.is_ok(), "corrupt block payload should not panic"); + assert!(result.unwrap().is_err()); + } + + #[test] + fn cold_text_reader_errors_fall_back_without_recording_parse_failures() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + doc.set_change_merge_interval(-1); + doc.get_text("t").insert_unicode(0, "ab").unwrap(); + doc.commit_then_renew(); + doc.get_text("t").insert_unicode(2, "c").unwrap(); + doc.commit_then_renew(); + let oplog = doc.oplog.lock(); + let mut changes = Vec::new(); + oplog + .change_store() + .visit_all_changes(&mut |change| changes.push(change.clone())); + assert_eq!(changes.len(), 2); + let block_bytes = encode_block(&changes, &oplog.arena); + + for crosses_change_boundary in [false, true] { + let mut encoded: EncodedBlock = postcard::from_bytes(&block_bytes).unwrap(); + if crosses_change_boundary { + // The header starts with a peer count, peer IDs, then the first + // change's atom length. Move its end from counter 2 to counter 1 + // while keeping the two-character insert and total range intact. + let mut header = encoded.header.as_ref(); + let peers = leb128::read::unsigned(&mut header).unwrap() as usize; + let length_offset = encoded.header.len() - header.len() + peers * 8; + assert_eq!(encoded.header[length_offset], 2); + encoded.header.to_mut()[length_offset] = 1; + } else { + // decode_block uses the actual string length for the text op, + // while the cold reader requires it to equal the encoded length. + let mut ops: EncodedOps = serde_columnar::from_bytes(&encoded.ops).unwrap(); + ops.ops[0].len = 1; + encoded.ops = Cow::Owned(serde_columnar::to_vec(&ops).unwrap()); + } + let bytes = postcard::to_allocvec(&encoded).unwrap(); + assert!(visit_text_insert_block(&bytes, |_, _, _, _, _, _| Ok(())).is_err()); + assert!(decode_block(&bytes, &SharedArena::new(), None).is_ok()); + + let store = crate::oplog::ChangeStore::new_for_test(); + let id = ID::new(1, 0); + store + .external_kv + .lock() + .set(&id.to_bytes(), bytes.clone().into()); + let mut visits = 0; + assert!(!store + .check_text_insert_block(&bytes, |_, _, _, _, _, _| { + visits += 1; + // Even a mismatch before a later reader error must fall back. + Err(LoroError::UsedOpID { id }) + }) + .unwrap()); + if crosses_change_boundary { + assert_eq!(visits, 1); + } + assert!(store.corrupt_block_error().is_ok()); + assert!(store.get_change(id).is_some()); + assert!(store.corrupt_block_error().is_ok()); + } + } + + /// A list insert with several values and an out-of-range position must be + /// rejected. The error message formats the op, which read its values before + /// the block's value buffer was filled, and panicked under the op log lock + /// (loro-dev/loro#1197 review). + #[test] + fn invalid_position_of_multi_value_list_insert_is_rejected() { + for kind in [ContainerType::List, ContainerType::MovableList] { + let value_arena = ValueDecodeArena { + peers: &[1], + keys: &[], + }; + let result = decode_op( + &ContainerID::new_root("list", kind), + Value::LoroValue(vec![1_i64, 2].into()), + &mut std::iter::empty(), + &mut DecodedBlockBuffers::new(0), + &value_arena, + &[], + -1, + ID::new(1, 0), + ); + assert!(matches!(result, Err(LoroError::DecodeError(_)))); + } + + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let list = doc.get_list("list"); + list.push(1).unwrap(); + list.push(2).unwrap(); + doc.commit_then_renew(); + let block = { + let oplog = doc.oplog.lock(); + let mut changes = Vec::new(); + oplog + .change_store() + .visit_all_changes(&mut |change| changes.push(change.clone())); + let InnerContent::List(InnerListOp::Insert { slice, pos }) = + &mut changes[0].ops.vec_mut()[0].content + else { + unreachable!() + }; + assert_eq!(slice.len(), 2); + *pos = usize::MAX; + encode_block(&changes, &oplog.arena) + }; + let update = encoding::encode_with(encoding::EncodeMode::FastUpdates, &mut |ans| { + leb128::write::unsigned(ans, block.len() as u64).unwrap(); + ans.extend_from_slice(&block); + Ok(()) + }) + .unwrap(); + + let target = LoroDoc::new_auto_commit(); + assert!(target.import(&update).is_err()); + target.get_list("list").push(3).unwrap(); + target.commit_then_renew(); + assert_eq!( + crate::ToJson::to_json(&target.get_deep_value()), + r#"{"list":[3]}"# + ); + } + + #[test] + fn tree_move_payload_is_rejected_without_panic() { + let value_arena = ValueDecodeArena { + peers: &[1], + keys: &[], + }; + let cid = ContainerID::Root { + name: "tree".into(), + container_type: ContainerType::Tree, + }; + let value = Value::TreeMove(EncodedTreeMove { + target_idx: 0, + is_parent_null: true, + parent_idx: 0, + position: 0, + }); + let mut deletes = std::iter::empty(); + + let result = std::panic::catch_unwind(AssertUnwindSafe(|| { + decode_op( + &cid, + value, + &mut deletes, + &mut DecodedBlockBuffers::new(0), + &value_arena, + &[], + 0, + ID::new(1, 0), + ) + })); + + assert!(result.is_ok(), "tree move payload should not panic"); + assert!(matches!( + result.unwrap(), + Err(LoroError::DecodeDataCorruptionError) + )); + } + + #[test] + pub fn encode_single_text_edit() { + let doc = LoroDoc::new(); + doc.start_auto_commit(); + doc.get_map("map").insert("x", 100).unwrap(); + // doc.get_text("text").insert(0, "Hi").unwrap(); + // let node = doc.get_tree("tree").create(None).unwrap(); + // doc.get_tree("tree").create(node).unwrap(); + diagnose(&doc); + doc.get_map("map").insert("y", 20).unwrap(); + diagnose(&doc); + doc.get_map("map").insert("z", 1000).unwrap(); + diagnose(&doc); + doc.get_text("text") + .insert(0, "Hello", PosType::Unicode) + .unwrap(); + diagnose(&doc); + doc.get_text("text") + .insert(2, "He", PosType::Unicode) + .unwrap(); + diagnose(&doc); + doc.get_text("text").delete(1, 4, PosType::Unicode).unwrap(); + diagnose(&doc); + doc.get_text("text").delete(0, 2, PosType::Unicode).unwrap(); + diagnose(&doc); + } + + fn diagnose(doc: &LoroDoc) { + let bytes = doc.export(ExportMode::all_updates()).unwrap(); + println!("Old Update bytes {:?}", dev_utils::ByteSize(bytes.length())); + + let bytes = doc.export(ExportMode::all_updates()).unwrap(); + println!("Update bytes {:?}", dev_utils::ByteSize(bytes.length())); + // assert!(bytes.len() < 30); + + let bytes = doc.export(ExportMode::Snapshot).unwrap(); + println!("Snapshot bytes {:?}", dev_utils::ByteSize(bytes.length())); + // assert!(bytes.len() < 30); + + let json = doc + .export_json_updates(&Default::default(), &doc.oplog_vv(), true) + .unwrap(); + let json_string = serde_json::to_string(&json.changes).unwrap(); + println!( + "JSON string bytes {:?}", + dev_utils::ByteSize(json_string.len()) + ); + let bytes = postcard::to_allocvec(&json.changes).unwrap(); + println!("JSON update bytes {:?}", dev_utils::ByteSize(bytes.len())); + println!("\n\n") + } +} diff --git a/vendor/loro-internal/src/oplog/change_store/block_meta_encode.rs b/vendor/loro-internal/src/oplog/change_store/block_meta_encode.rs new file mode 100644 index 0000000..ef9695f --- /dev/null +++ b/vendor/loro-internal/src/oplog/change_store/block_meta_encode.rs @@ -0,0 +1,247 @@ +use loro_common::{Counter, Lamport, LoroError, LoroResult, PeerID, ID}; +use once_cell::sync::OnceCell; +use rle::HasLength; +use serde_columnar::{ + AnyRleDecoder, AnyRleEncoder, BoolRleDecoder, BoolRleEncoder, DeltaOfDeltaDecoder, + DeltaOfDeltaEncoder, +}; + +use crate::{change::Change, encoding::value_register::ValueRegister, version::Frontiers}; + +use super::block_encode::ChangesBlockHeader; + +pub(crate) fn encode_changes( + block: &[Change], + peer_register: &mut ValueRegister<PeerID>, +) -> (Vec<u8>, Vec<u8>) { + let peer = block[0].peer(); + let mut timestamp_encoder = DeltaOfDeltaEncoder::new(); + let mut lamport_encoder = DeltaOfDeltaEncoder::new(); + let mut commit_msg_len_encoder = AnyRleEncoder::<u32>::new(); + let mut commit_msgs = String::new(); + let mut dep_self_encoder = BoolRleEncoder::new(); + let mut dep_len_encoder = AnyRleEncoder::<usize>::new(); + let mut encoded_deps = EncodedDeps { + peer_idx: AnyRleEncoder::new(), + counter: DeltaOfDeltaEncoder::new(), + }; + // First Counter + Change Len + let mut lengths_bytes = Vec::new(); + let mut counter = vec![]; + + for (i, c) in block.iter().enumerate() { + counter.push(c.id.counter); + let is_last = i == block.len() - 1; + if !is_last { + leb128::write::unsigned(&mut lengths_bytes, c.atom_len() as u64).unwrap(); + lamport_encoder.append(c.lamport() as i64).unwrap(); + } + timestamp_encoder.append(c.timestamp()).unwrap(); + if let Some(msg) = c.commit_msg.as_ref() { + commit_msg_len_encoder.append(msg.len() as u32).unwrap(); + commit_msgs.push_str(msg); + } else { + commit_msg_len_encoder.append(0).unwrap(); + } + + let mut dep_on_self = false; + for dep in c.deps().iter() { + if dep.peer == peer { + dep_on_self = true; + } else { + let peer_idx = peer_register.register(&dep.peer); + encoded_deps.peer_idx.append(peer_idx as u32).unwrap(); + encoded_deps.counter.append(dep.counter as i64).unwrap(); + } + } + + dep_self_encoder.append(dep_on_self).unwrap(); + dep_len_encoder + .append(if dep_on_self { + c.deps().len() - 1 + } else { + c.deps().len() + }) + .unwrap(); + } + + // TODO: capacity + let mut ans = Vec::with_capacity(block.len() * 15); + let _ = leb128::write::unsigned(&mut ans, peer_register.vec().len() as u64); + ans.extend(peer_register.vec().iter().flat_map(|p| p.to_le_bytes())); + ans.append(&mut lengths_bytes); + ans.append(&mut dep_self_encoder.finish().unwrap()); + ans.append(&mut dep_len_encoder.finish().unwrap()); + ans.append(&mut encoded_deps.peer_idx.finish().unwrap()); + ans.append(&mut encoded_deps.counter.finish().unwrap()); + ans.append(&mut lamport_encoder.finish().unwrap()); + + let mut t = timestamp_encoder.finish().unwrap(); + let mut cml = commit_msg_len_encoder.finish().unwrap(); + let mut cms = commit_msgs.into_bytes(); + let mut meta = Vec::with_capacity(t.len() + cml.len() + cms.len()); + meta.append(&mut t); + meta.append(&mut cml); + meta.append(&mut cms); + + (ans, meta) +} + +pub(crate) fn decode_changes_header( + mut bytes: &[u8], + n_changes: usize, + first_counter: Counter, + counter_len: Counter, + lamport_start: Lamport, + lamport_len: Lamport, +) -> LoroResult<ChangesBlockHeader> { + if n_changes == 0 { + return Err(LoroError::DecodeError( + "Decode block error: empty change block".into(), + )); + } + + let mut this_counter = first_counter; + let peer_num = leb128::read::unsigned(&mut bytes) + .map_err(|e| LoroError::DecodeError(format!("Decode block error {e}").into_boxed_str()))? + as usize; + let peers_bytes_len = peer_num + .checked_mul(8) + .ok_or_else(|| LoroError::DecodeError("Decode block error: peer length overflow".into()))?; + if peer_num == 0 || bytes.len() < peers_bytes_len { + return Err(LoroError::DecodeError( + "Decode block error: invalid peer table".into(), + )); + } + let mut peers = Vec::with_capacity(peer_num); + for i in 0..peer_num { + let start = 8 * i; + let peer_id = PeerID::from_le_bytes( + bytes[start..start + 8] + .try_into() + .expect("peer byte range should be checked"), + ); + peers.push(peer_id); + } + let mut bytes = &bytes[peers_bytes_len..]; + + // ┌───────────────────┬──────────────────────────────────────────┐ │ + // │ LEB First Counter │ N LEB128 Change AtomLen │◁───┼───── Important metadata + // └───────────────────┴──────────────────────────────────────────┘ │ + + let mut lengths = Vec::with_capacity(n_changes); + for _ in 0..n_changes - 1 { + lengths.push(leb128::read::unsigned(&mut bytes).map_err(|e| { + LoroError::DecodeError(format!("Decode block error {e}").into_boxed_str()) + })? as Counter); + } + let known_len = lengths.iter().try_fold(0i32, |acc, len| { + acc.checked_add(*len).ok_or_else(|| { + LoroError::DecodeError("Decode block error: counter length overflow".into()) + }) + })?; + lengths.push(counter_len.checked_sub(known_len).ok_or_else(|| { + LoroError::DecodeError("Decode block error: invalid counter length".into()) + })?); + + // ┌───────────────────┬────────────────────────┬─────────────────┐ │ + // │N DepOnSelf BoolRle│ N Delta Rle Deps Lens │ N Dep IDs │◁───┘ + // └───────────────────┴────────────────────────┴─────────────────┘ + + let dep_self_decoder = BoolRleDecoder::new(bytes); + let (dep_self, bytes) = dep_self_decoder + .take_n_finalize(n_changes) + .map_err(|_| LoroError::DecodeError("Decode block error: invalid deps".into()))?; + let dep_len_decoder = AnyRleDecoder::<usize>::new(bytes); + let (deps_len, bytes) = dep_len_decoder + .take_n_finalize(n_changes) + .map_err(|_| LoroError::DecodeError("Decode block error: invalid deps".into()))?; + let other_dep_num = deps_len.iter().sum::<usize>(); + let dep_peer_decoder = AnyRleDecoder::<usize>::new(bytes); + let (dep_peers, bytes) = dep_peer_decoder + .take_n_finalize(other_dep_num) + .map_err(|_| LoroError::DecodeError("Decode block error: invalid deps".into()))?; + let mut deps_peers_iter = dep_peers.into_iter(); + let dep_counter_decoder = DeltaOfDeltaDecoder::<u32>::new(bytes) + .map_err(|_| LoroError::DecodeError("Decode block error: invalid deps".into()))?; + let (dep_counters, bytes) = dep_counter_decoder + .take_n_finalize(other_dep_num) + .map_err(|_| LoroError::DecodeError("Decode block error: invalid deps".into()))?; + let mut deps_counters_iter = dep_counters.into_iter(); + let mut deps = Vec::with_capacity(n_changes); + for i in 0..n_changes { + let mut f = Frontiers::default(); + if dep_self[i] { + let dep_counter = this_counter.checked_sub(1).ok_or_else(|| { + LoroError::DecodeError("Decode block error: invalid self dependency".into()) + })?; + f.push(ID::new(peers[0], dep_counter)) + } + + let len = deps_len[i]; + for _ in 0..len { + let peer_idx = deps_peers_iter + .next() + .ok_or_else(|| LoroError::DecodeError("Decode block error: invalid deps".into()))?; + let peer = peers.get(peer_idx).copied().ok_or_else(|| { + LoroError::DecodeError("Decode block error: invalid peer index".into()) + })?; + let counter = deps_counters_iter + .next() + .ok_or_else(|| LoroError::DecodeError("Decode block error: invalid deps".into()))? + as Counter; + f.push(ID::new(peer, counter)); + } + + deps.push(f); + this_counter = this_counter + .checked_add(lengths[i]) + .ok_or_else(|| LoroError::DecodeError("Decode block error: counter overflow".into()))?; + } + let mut counters = Vec::with_capacity(n_changes); + let mut last = first_counter; + for len in lengths.iter() { + counters.push(last); + last = last + .checked_add(*len) + .ok_or_else(|| LoroError::DecodeError("Decode block error: counter overflow".into()))?; + } + + let lamport_decoder = DeltaOfDeltaDecoder::new(bytes) + .map_err(|_| LoroError::DecodeError("Decode block error: invalid lamport".into()))?; + let (mut lamports, rest) = lamport_decoder + .take_n_finalize(n_changes.saturating_sub(1)) + .map_err(|_| LoroError::DecodeError("Decode block error: invalid lamport".into()))?; + // the last lamport + let last_len = *lengths.last().unwrap_or(&0) as u32; + let last_lamport = lamport_start + .checked_add(lamport_len) + .and_then(|end| end.checked_sub(last_len)) + .ok_or_else(|| LoroError::DecodeError("Decode block error: invalid lamport".into()))?; + lamports.push(last_lamport as Lamport); + + // we need counter range, so encode + counters.push( + first_counter + .checked_add(counter_len) + .ok_or_else(|| LoroError::DecodeError("Decode block error: counter overflow".into()))?, + ); + debug_assert!(rest.is_empty()); + + Ok(ChangesBlockHeader { + peer: peers[0], + counter: first_counter, + n_changes, + peers, + counters, + deps_groups: deps, + lamports, + keys: OnceCell::new(), + cids: OnceCell::new(), + }) +} + +struct EncodedDeps { + peer_idx: AnyRleEncoder<u32>, + counter: DeltaOfDeltaEncoder, +} diff --git a/vendor/loro-internal/src/oplog/change_store/iter.rs b/vendor/loro-internal/src/oplog/change_store/iter.rs new file mode 100644 index 0000000..153eaf0 --- /dev/null +++ b/vendor/loro-internal/src/oplog/change_store/iter.rs @@ -0,0 +1,139 @@ +#![allow(dead_code)] + +use std::{ + collections::{BinaryHeap, VecDeque}, + sync::Arc, +}; + +use loro_common::{CounterSpan, HasIdSpan}; + +use crate::{OpLog, VersionVector}; + +use super::{BlockChangeRef, ChangesBlock}; + +pub(crate) struct PeerChangesIter { + blocks: VecDeque<Arc<ChangesBlock>>, + change_index: usize, + counter_range: CounterSpan, +} + +impl PeerChangesIter { + fn new_change_iter_rev(mut changes: VecDeque<Arc<ChangesBlock>>, counter: CounterSpan) -> Self { + let mut index = changes + .back() + .map(|x| x.content().len_changes().saturating_sub(1)) + .unwrap_or(0); + + while let Some(block) = changes.back() { + if let Some(change) = block.content().try_changes().unwrap().get(index) { + if change.id.counter < counter.end { + break; + } + } else if index == 0 { + changes.pop_back(); + } else { + index -= 1; + } + } + + PeerChangesIter { + blocks: changes, + change_index: index, + counter_range: counter, + } + } + + fn current_weight(&self) -> i32 { + if self.blocks.is_empty() { + return 0; + } + + self.blocks + .back() + .map(|x| { + x.content() + .try_changes() + .unwrap() + .get(self.change_index) + .unwrap() + .lamport as i32 + }) + .unwrap_or(0) + } +} + +impl Ord for PeerChangesIter { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.current_weight().cmp(&other.current_weight()) + } +} + +impl PartialOrd for PeerChangesIter { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl PartialEq for PeerChangesIter { + fn eq(&self, other: &Self) -> bool { + self.current_weight() == other.current_weight() + } +} + +impl Eq for PeerChangesIter {} + +impl Iterator for PeerChangesIter { + type Item = BlockChangeRef; + + fn next(&mut self) -> Option<Self::Item> { + if self.blocks.is_empty() { + return None; + } + + let c = BlockChangeRef { + block: self.blocks.back().unwrap().clone(), + change_index: self.change_index, + }; + + if c.id_last().counter < self.counter_range.start { + return None; + } + + let ans = Some(c); + if self.change_index == 0 { + self.blocks.pop_back(); + } else { + self.change_index -= 1; + } + + ans + } +} + +pub(crate) struct MergedChangeIter { + heap: BinaryHeap<PeerChangesIter>, +} + +impl Iterator for MergedChangeIter { + type Item = BlockChangeRef; + + fn next(&mut self) -> Option<Self::Item> { + let mut iter = self.heap.pop()?; + let ans = iter.next(); + self.heap.push(iter); + ans + } +} + +impl MergedChangeIter { + pub fn new_change_iter_rev(oplog: &OpLog, from: &VersionVector, to: &VersionVector) -> Self { + let mut heap = BinaryHeap::new(); + for span in to.sub_iter(from) { + let blocks = oplog.change_store.get_blocks_in_range(span); + let iter = PeerChangesIter::new_change_iter_rev(blocks, span.counter); + heap.push(iter); + } + + Self { heap } + } +} diff --git a/vendor/loro-internal/src/oplog/known_history.rs b/vendor/loro-internal/src/oplog/known_history.rs new file mode 100644 index 0000000..282a2d3 --- /dev/null +++ b/vendor/loro-internal/src/oplog/known_history.rs @@ -0,0 +1,976 @@ +//! Imported changes that reuse op ids the doc already has. +//! +//! An import skips the part of each change the doc already has (by version vector) +//! and applies the rest on top of the local history. When two clients shared a +//! peer id, the "known" part is different history, and the rest is then applied to +//! a state it was not written against: it panicked inside state apply (poisoning +//! the doc) or silently scrambled it (loro-dev/loro#1118). See +//! `context/import-peer-id-reuse.md`. + +use loro_common::{Counter, HasCounterSpan, LoroError, LoroResult, LoroValue, PeerID, ID}; +use rle::{HasLength, Sliceable}; +use rustc_hash::FxHashMap; + +use crate::{ + arena::SharedArena, + change::Change, + container::list::list_op::InnerListOp, + op::{InnerContent, Op}, + version::Frontiers, + OpLog, +}; + +#[cfg(feature = "counter")] +use crate::op::FutureInnerContent; + +/// How to compare imported op values with known history. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ImportedValues { + /// Structural equality. Default for binary import. + Exact, + /// Equivalences JSON export/import is known to introduce. Callers opt in. + JsonLossy, +} + +impl ImportedValues { + fn eq(self, a: &LoroValue, b: &LoroValue) -> bool { + if self == Self::Exact { + return a == b; + } + + match (a, b) { + (LoroValue::I64(a), LoroValue::I64(b)) => { + // JS numbers can round distinct large integers to the same f64. + // Keep exact comparison in the range where every integer fits. + const MAX_EXACT_INTEGER: i64 = 1 << 53; + a == b + || ((a.unsigned_abs() > MAX_EXACT_INTEGER as u64 + || b.unsigned_abs() > MAX_EXACT_INTEGER as u64) + && *a as f64 == *b as f64) + } + (LoroValue::Double(d), LoroValue::I64(i)) + | (LoroValue::I64(i), LoroValue::Double(d)) => { + // Inside +/-2^53 this is exact numeric equality; outside it also + // accepts the rounded Double produced by a JS-number relay. + *d == *i as f64 + } + (LoroValue::String(string), LoroValue::Container(_)) + | (LoroValue::Container(_), LoroValue::String(string)) => { + // A marker-looking string also becomes a container reference. + // JSON peer compression can reinterpret its peer as an index, + // so the decoded id cannot safely be compared with that string. + loro_common::ContainerID::try_from_loro_value_string(string).is_some() + } + (LoroValue::Binary(bytes), LoroValue::List(list)) + | (LoroValue::List(list), LoroValue::Binary(bytes)) => { + bytes.len() == list.len() + && bytes + .iter() + .zip(list.iter()) + .all(|(&byte, value)| match value { + LoroValue::I64(number) => *number == i64::from(byte), + LoroValue::Double(number) => *number == f64::from(byte), + _ => false, + }) + } + (LoroValue::Double(number), LoroValue::Null) + | (LoroValue::Null, LoroValue::Double(number)) => !number.is_finite(), + (LoroValue::List(a), LoroValue::List(b)) => { + a.len() == b.len() && a.iter().zip(b.iter()).all(|(a, b)| self.eq(a, b)) + } + (LoroValue::Map(a), LoroValue::Map(b)) => { + a.len() == b.len() + && a.iter() + .all(|(key, a)| b.get(key).is_some_and(|b| self.eq(a, b))) + } + _ => a == b, + } + } +} + +impl OpLog { + /// Check the decoded `changes` against the history this doc already has for the + /// same op ids, then drop the parts it already has. + /// + /// Returns [`LoroError::UsedOpID`] with the first conflicting id when an imported + /// change differs from the local one (deps or op content), and + /// [`LoroError::DecodeError`] when a change skips counters of its peer (see + /// [`Self::check_changes_do_not_skip_counters`]). It reads the op log only, so a + /// caller can return the error before mutating anything. + /// + /// The comparison runs only when the import brings something new: that is what + /// would be applied on top of a conflicting prefix. An import made only of + /// known changes is a no-op either way and stays as cheap as before. + pub(crate) fn check_and_trim_known_part_of_changes( + &self, + changes: Vec<Change>, + values: ImportedValues, + ) -> LoroResult<Vec<Change>> { + self.check_and_trim_known_part_in_arena(changes, values, &self.arena) + } + + /// Snapshot overlap is decoded into a temporary arena. Compare before moving + /// only the retained suffix into the document's arena. + pub(crate) fn check_and_trim_known_part_in_arena( + &self, + mut changes: Vec<Change>, + values: ImportedValues, + imported_arena: &SharedArena, + ) -> LoroResult<Vec<Change>> { + let vv = self.vv(); + let known_end = |c: &Change| vv.get(&c.id.peer).copied().unwrap_or(0); + if changes.iter().any(|c| c.ctr_end() > known_end(c)) { + for change in changes.iter() { + if change.id.counter < known_end(change) { + self.check_known_part_of_change( + change, + known_end(change), + values, + imported_arena, + )?; + } + } + } + + changes.retain_mut(|c| { + let end = known_end(c); + if c.id.counter >= end { + true + } else if c.ctr_end() > end { + *c = c.slice((end - c.id.counter) as usize, c.atom_len()); + true + } else { + false + } + }); + self.check_changes_do_not_skip_counters(&changes)?; + Ok(changes) + } + + /// A change of peer `p` starting at counter `c > 0` is written after `p@c-1`, so + /// `p@c-1` is in the causal past of its deps. When all its deps are present but + /// `p@c-1` is not, the change skips counters and is invalid. The main pass of + /// `import_changes_to_oplog` applies any change whose deps are present and + /// would hit the counter assertion in `AppDag::update_version_on_new_change` + /// under the op log lock. (Changes parked as pending already wait for `p@c-1`, + /// see `remote_change_apply_state`.) + /// + /// This replays that pass on counter ends only: changes are visited in the same + /// order, and a change counts as applied when its deps are. + fn check_changes_do_not_skip_counters(&self, changes: &[Change]) -> LoroResult<()> { + let vv = self.vv(); + let mut ends: FxHashMap<PeerID, Counter> = FxHashMap::default(); + for change in changes { + let end_of = |ends: &FxHashMap<PeerID, Counter>, peer: &PeerID| { + ends.get(peer) + .or_else(|| vv.get(peer)) + .copied() + .unwrap_or(0) + }; + let peer = change.id.peer; + let end = end_of(&ends, &peer); + if change.ctr_end() <= end + || self.dag.try_import_deps_before_shallow_root(&change.deps)? + { + continue; + } + + if !change + .deps + .iter() + .all(|dep| dep.counter < end_of(&ends, &dep.peer)) + { + // Parked as pending. + continue; + } + + if change.id.counter > end { + return Err(LoroError::DecodeError( + format!( + "Invalid change {}: its deps are present but {} is not, so it skips counters of its peer", + change.id, + ID::new(peer, change.id.counter - 1), + ) + .into_boxed_str(), + )); + } + + ends.insert(peer, change.ctr_end()); + } + + Ok(()) + } + + fn check_known_part_of_change( + &self, + change: &Change, + known_end: Counter, + values: ImportedValues, + imported_arena: &SharedArena, + ) -> LoroResult<()> { + let peer = change.id.peer; + // History before the shallow root is not stored, so it cannot be compared. + let shallow_start = self.shallow_since_vv().get(&peer).copied().unwrap_or(0); + let end = change.ctr_end().min(known_end); + let mut ctr = change.id.counter.max(shallow_start); + while ctr < end { + if let Some(checked_end) = + self.check_known_text_in_cold_block(change, imported_arena, ctr, end)? + { + ctr = checked_end; + continue; + } + // Missing local history cannot be compared; keep the old behavior for it. + let Some(local) = self.change_store.get_change(ID::new(peer, ctr)) else { + break; + }; + let seg_end = end.min(local.ctr_end()); + if seg_end <= ctr { + break; + } + + if deps_at(change, ctr) != deps_at(&local, ctr) { + return Err(LoroError::UsedOpID { + id: ID::new(peer, ctr), + }); + } + + if let Some(bad) = first_mismatch( + imported_arena, + &self.arena, + values, + change, + &local, + ctr, + seg_end, + ) { + return Err(LoroError::UsedOpID { + id: ID::new(peer, bad), + }); + } + + ctr = seg_end; + } + + Ok(()) + } + /// Compare cold Text insert history directly from its encoded block. This + /// preserves every dependency boundary and op atom without retaining the + /// block's parsed changes or strings. Unsupported blocks use the full check. + fn check_known_text_in_cold_block( + &self, + change: &Change, + arena: &SharedArena, + start: Counter, + end: Counter, + ) -> LoroResult<Option<Counter>> { + let Some(bytes) = self + .change_store + .unparsed_block_bytes(ID::new(change.id.peer, start)) + else { + return Ok(None); + }; + let Ok(range) = crate::oplog::ChangeStore::encoded_block_counter_range(&bytes) else { + return Ok(None); + }; + // A short imported change must not rescan a large local block for each + // atom/change. Parse it once and reuse the general comparison instead. + if end < range.1 { + return Ok(None); + } + let block_end = end.min(range.1); + let mut cursor = OpCursor::new(change, start); + let checked = self.change_store.check_text_insert_block( + &bytes, + |counter, cid, pos, text, len, deps| { + let local_end = counter + len as Counter; + let mut ctr = counter.max(start); + let limit = local_end.min(end); + while ctr < limit { + let bad = || LoroError::UsedOpID { + id: ID::new(change.id.peer, ctr), + }; + let local_deps = if ctr == counter { + deps.clone() + } else { + Frontiers::from_id(ID::new(change.id.peer, ctr - 1)) + }; + if deps_at(change, ctr) != local_deps { + return Err(bad()); + } + let Some(op) = cursor.op_at(ctr) else { + return Err(bad()); + }; + let n = (limit - ctr).min(op.ctr_end() - ctr); + let slice = slice_op(op, ctr, n); + let InnerContent::List(InnerListOp::InsertText { + slice: imported, + pos: imported_pos, + unicode_len, + .. + }) = &slice.content + else { + return Err(bad()); + }; + if arena.idx_to_id(op.container).as_ref() != Some(cid) + || pos + .checked_add((ctr - counter) as u32) + .is_none_or(|p| *imported_pos != p) + || *unicode_len != n as u32 + { + return Err(bad()); + } + let imported = std::str::from_utf8(imported).unwrap(); + let offset = (ctr - counter) as usize; + let local = if offset == 0 && n as u32 == len { + text + } else { + let byte_start = text + .char_indices() + .nth(offset) + .map_or(text.len(), |(i, _)| i); + let byte_end = text[byte_start..] + .char_indices() + .nth(n as usize) + .map_or(text.len(), |(i, _)| byte_start + i); + &text[byte_start..byte_end] + }; + if local != imported { + let offset = local + .chars() + .zip(imported.chars()) + .position(|(a, b)| a != b) + .unwrap_or(0); + return Err(LoroError::UsedOpID { + id: ID::new(change.id.peer, ctr + offset as Counter), + }); + } + ctr += n; + } + Ok(()) + }, + )?; + Ok(checked.then_some(block_end)) + } +} + +/// The deps of the op at `ctr`. Inside a change every op depends on the previous +/// one, and changes only merge when that holds, so this does not depend on how +/// either side split its history into changes. +fn deps_at(change: &Change, ctr: Counter) -> Frontiers { + if ctr == change.id.counter { + change.deps.clone() + } else { + Frontiers::from_id(ID::new(change.id.peer, ctr - 1)) + } +} + +/// Walk the ops of `a` and `b` over `[start, end)` and return the first counter at +/// which they differ. Each side may split or merge the ops differently, so both +/// are cut at every boundary of either side before comparing. +fn first_mismatch( + a_arena: &SharedArena, + b_arena: &SharedArena, + values: ImportedValues, + a: &Change, + b: &Change, + start: Counter, + end: Counter, +) -> Option<Counter> { + let mut a_ops = OpCursor::new(a, start); + let mut b_ops = OpCursor::new(b, start); + let mut ctr = start; + while ctr < end { + let (Some(a_op), Some(b_op)) = (a_ops.op_at(ctr), b_ops.op_at(ctr)) else { + return Some(ctr); + }; + let len = (end - ctr) + .min(a_op.ctr_end() - ctr) + .min(b_op.ctr_end() - ctr); + let a_slice = slice_op(a_op, ctr, len); + let b_slice = slice_op(b_op, ctr, len); + if !op_eq(a_arena, b_arena, values, &a_slice, &b_slice) { + // Error path only: find the exact atom. + let offset = (0..len) + .find(|&i| { + !op_eq( + a_arena, + b_arena, + values, + &slice_op(a_op, ctr + i, 1), + &slice_op(b_op, ctr + i, 1), + ) + }) + .unwrap_or(0); + return Some(ctr + offset); + } + ctr += len; + } + + None +} + +struct OpCursor<'a> { + ops: &'a [Op], + index: usize, +} + +impl<'a> OpCursor<'a> { + fn new(change: &'a Change, start: Counter) -> Self { + let ops = change.ops.vec().as_slice(); + let index = ops.partition_point(|op| op.ctr_end() <= start); + Self { ops, index } + } + + /// The op containing `ctr`. Counters only move forward. + fn op_at(&mut self, ctr: Counter) -> Option<&'a Op> { + while let Some(op) = self.ops.get(self.index) { + if op.ctr_end() > ctr { + return (op.counter <= ctr).then_some(op); + } + self.index += 1; + } + None + } +} + +fn slice_op(op: &Op, ctr: Counter, len: Counter) -> std::borrow::Cow<'_, Op> { + let from = (ctr - op.counter) as usize; + let to = from + len as usize; + if from == 0 && to == op.atom_len() { + std::borrow::Cow::Borrowed(op) + } else { + std::borrow::Cow::Owned(op.slice(from, to)) + } +} + +/// Whether two ops with the same id range are the same op. Compares what the op +/// means, not how it is stored: arena offsets and the direction of a one-atom +/// delete are representation details. +fn op_eq( + a_arena: &SharedArena, + b_arena: &SharedArena, + values: ImportedValues, + a: &Op, + b: &Op, +) -> bool { + let same_container = if std::ptr::eq(a_arena, b_arena) { + a.container == b.container + } else { + a_arena.idx_to_id(a.container) == b_arena.idx_to_id(b.container) + }; + if !same_container || a.atom_len() != b.atom_len() { + return false; + } + + match (&a.content, &b.content) { + (InnerContent::List(a), InnerContent::List(b)) => list_op_eq(values, a, b), + (InnerContent::Map(a), InnerContent::Map(b)) => { + a.key == b.key + && match (&a.value, &b.value) { + (Some(a), Some(b)) => values.eq(a, b), + (None, None) => true, + _ => false, + } + } + (InnerContent::Tree(a), InnerContent::Tree(b)) => a == b, + (InnerContent::Future(a), InnerContent::Future(b)) => match (a, b) { + #[cfg(feature = "counter")] + (FutureInnerContent::Counter(a), FutureInnerContent::Counter(b)) => { + a == b || (a.is_nan() && b.is_nan()) + } + ( + crate::op::FutureInnerContent::Unknown { + prop: a_prop, + value: a_value, + }, + crate::op::FutureInnerContent::Unknown { + prop: b_prop, + value: b_value, + }, + ) => { + // A newer container's payload may contain LoroValues or arena + // indices whose meaning this version cannot interpret. JSON + // imports skip that payload; binary imports compare it. + a_prop == b_prop + && match values { + ImportedValues::JsonLossy => true, + ImportedValues::Exact => a_value == b_value, + } + } + #[allow(unreachable_patterns)] + _ => false, + }, + _ => false, + } +} + +fn list_op_eq(values: ImportedValues, a: &InnerListOp, b: &InnerListOp) -> bool { + match (a, b) { + ( + InnerListOp::Insert { + slice: a_slice, + pos: a_pos, + }, + InnerListOp::Insert { + slice: b_slice, + pos: b_pos, + }, + ) => { + let (a_values, b_values) = (a_slice.as_slice(), b_slice.as_slice()); + a_pos == b_pos + && a_values.len() == b_values.len() + && a_values.iter().zip(b_values).all(|(a, b)| values.eq(a, b)) + } + ( + InnerListOp::InsertText { + slice: a_slice, + unicode_len: a_len, + pos: a_pos, + .. + }, + InnerListOp::InsertText { + slice: b_slice, + unicode_len: b_len, + pos: b_pos, + .. + }, + ) => a_pos == b_pos && a_len == b_len && a_slice[..] == b_slice[..], + (InnerListOp::Delete(a), InnerListOp::Delete(b)) => { + // A one-atom delete has no direction: `signed_len` 1 and -1 delete the + // same element, and which one is stored depends on how it was sliced. + a.id_start == b.id_start + && a.span.pos == b.span.pos + && (a.span.signed_len == b.span.signed_len + || (a.span.signed_len.abs() == 1 && b.span.signed_len.abs() == 1)) + } + ( + InnerListOp::Move { + from: a_from, + elem_id: a_elem, + to: a_to, + }, + InnerListOp::Move { + from: b_from, + elem_id: b_elem, + to: b_to, + }, + ) => a_from == b_from && a_elem == b_elem && a_to == b_to, + ( + InnerListOp::Set { + elem_id: a_elem, + value: a_value, + }, + InnerListOp::Set { + elem_id: b_elem, + value: b_value, + }, + ) => a_elem == b_elem && values.eq(a_value, b_value), + ( + InnerListOp::StyleStart { + start: a_start, + end: a_end, + key: a_key, + value: a_value, + info: a_info, + }, + InnerListOp::StyleStart { + start: b_start, + end: b_end, + key: b_key, + value: b_value, + info: b_info, + }, + ) => { + a_start == b_start + && a_end == b_end + && a_key == b_key + && values.eq(a_value, b_value) + && a_info == b_info + } + (InnerListOp::StyleEnd, InnerListOp::StyleEnd) => true, + _ => false, + } +} + +#[cfg(test)] +mod json_lossy_value_tests { + use super::ImportedValues; + use loro_common::LoroValue; + + fn assert_lossy_pair(a: &LoroValue, b: &LoroValue, equal: bool) { + assert_eq!(ImportedValues::JsonLossy.eq(a, b), equal, "{a:?} vs {b:?}"); + assert_eq!(ImportedValues::JsonLossy.eq(b, a), equal, "{b:?} vs {a:?}"); + } + + #[test] + fn byte_lists_must_match_every_byte() { + let binary = LoroValue::from(vec![0u8, 1, 255]); + for list in [ + LoroValue::from(vec![0, 1, 255]), + LoroValue::from(vec![0.0, 1.0, 255.0]), + ] { + assert_lossy_pair(&binary, &list, true); + assert!(!ImportedValues::Exact.eq(&binary, &list)); + } + assert_lossy_pair( + &LoroValue::from(Vec::<u8>::new()), + &LoroValue::from(Vec::<i32>::new()), + true, + ); + for list in [ + LoroValue::from(vec![0, 1]), + LoroValue::from(vec![0, 1, 255, 0]), + LoroValue::from(vec![0, 1, 254]), + LoroValue::from(vec![0, -1, 255]), + LoroValue::from(vec![0, 1, 256]), + LoroValue::from(vec![0.0, 1.5, 255.0]), + LoroValue::from(vec![0.0, f64::NAN, 255.0]), + LoroValue::from(vec![ + LoroValue::I64(0), + LoroValue::Bool(true), + LoroValue::I64(255), + ]), + ] { + assert_lossy_pair(&binary, &list, false); + } + assert_lossy_pair(&binary, &LoroValue::from(vec![0u8, 1, 254]), false); + } + + #[test] + fn only_non_finite_numbers_match_null() { + for number in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let number = LoroValue::Double(number); + assert_lossy_pair(&number, &LoroValue::Null, true); + assert!(!ImportedValues::Exact.eq(&number, &LoroValue::Null)); + assert!(ImportedValues::Exact.eq(&number, &number)); + } + for number in [0.0, -0.0, 1.5, f64::MAX] { + assert_lossy_pair(&LoroValue::Double(number), &LoroValue::Null, false); + } + assert_lossy_pair(&LoroValue::I64(0), &LoroValue::Null, false); + assert_lossy_pair( + &LoroValue::Double(f64::INFINITY), + &LoroValue::Double(f64::NEG_INFINITY), + false, + ); + } + + #[test] + fn nested_values_allow_only_json_representations() { + let nested = + |value| LoroValue::Map(vec![("key".into(), LoroValue::from(vec![value]))].into()); + let original = nested(LoroValue::from(vec![ + LoroValue::from(vec![1u8, 2]), + LoroValue::Double(f64::NAN), + ])); + let json: LoroValue = + serde_json::from_str(&serde_json::to_string(&original).unwrap()).unwrap(); + assert_lossy_pair(&original, &json, true); + assert!(!ImportedValues::Exact.eq(&original, &json)); + assert_lossy_pair( + &original, + &nested(LoroValue::from(vec![ + LoroValue::from(vec![1, 3]), + LoroValue::Null, + ])), + false, + ); + assert_lossy_pair( + &original, + &LoroValue::Map(vec![("other".into(), original["key"].clone())].into()), + false, + ); + assert_lossy_pair(&original, &LoroValue::Map(Default::default()), false); + assert_lossy_pair( + &LoroValue::from(vec![1, 2]), + &LoroValue::from(vec![1, 2, 3]), + false, + ); + } + + #[test] + fn finite_doubles_one_ulp_apart_stay_different() { + let a = 1.0_f64; + let b = f64::from_bits(a.to_bits() + 1); + let (a, b) = (LoroValue::Double(a), LoroValue::Double(b)); + assert_lossy_pair(&a, &b, false); + assert!(!ImportedValues::Exact.eq(&a, &b)); + } + + #[test] + fn ordinary_values_still_require_exact_equality() { + let values = [ + LoroValue::Null, + LoroValue::Bool(false), + LoroValue::Bool(true), + LoroValue::I64(1), + LoroValue::I64(2), + LoroValue::Double(1.5), + LoroValue::from("one"), + LoroValue::from("two"), + LoroValue::from(loro_common::ContainerID::new_root( + "a", + loro_common::ContainerType::Map, + )), + LoroValue::from(loro_common::ContainerID::new_root( + "b", + loro_common::ContainerType::Map, + )), + ]; + for a in &values { + for b in &values { + assert_lossy_pair(a, b, a == b); + } + } + } + + #[test] + fn doubles_match_the_integer_as_f64() { + for integer in [0, 2, -2, 9_007_199_254_740_991, i64::MIN, i64::MAX] { + let double = LoroValue::Double(integer as f64); + let integer = LoroValue::I64(integer); + assert_lossy_pair(&double, &integer, true); + assert!(!ImportedValues::Exact.eq(&double, &integer)); + } + assert_lossy_pair(&LoroValue::Double(-0.0), &LoroValue::I64(0), true); + for number in [2.5, 3.0, f64::NAN, f64::INFINITY] { + assert_lossy_pair(&LoroValue::Double(number), &LoroValue::I64(2), false); + } + } + + #[test] + fn large_integers_match_only_the_same_js_number() { + const BOUND: i64 = 1 << 53; + const LARGE: i64 = 1 << 60; + for (original, rounded) in [ + (BOUND + 1, BOUND), + (-BOUND - 1, -BOUND), + (LARGE + 1, LARGE), + (LARGE + 1, LARGE + 24), // JSON.stringify spells 2^60 as ...7000. + (-LARGE - 1, -LARGE), + (-LARGE - 1, -LARGE - 24), + (i64::MAX, i64::MAX - 1), + (i64::MIN + 1, i64::MIN), + ] { + let original = LoroValue::I64(original); + for rounded in [LoroValue::I64(rounded), LoroValue::Double(rounded as f64)] { + assert_lossy_pair(&original, &rounded, true); + assert!(!ImportedValues::Exact.eq(&original, &rounded)); + } + } + for (a, b) in [ + (BOUND - 1, BOUND), + (-BOUND + 1, -BOUND), + (BOUND, BOUND + 2), + (-BOUND, -BOUND - 2), + (LARGE, LARGE + 256), + (-LARGE, -LARGE - 256), + (i64::MAX, i64::MAX - 1024), + (i64::MIN, i64::MIN + 1024), + ] { + assert_lossy_pair(&LoroValue::I64(a), &LoroValue::I64(b), false); + assert_lossy_pair(&LoroValue::I64(a), &LoroValue::Double(b as f64), false); + } + } + + #[test] + fn container_marker_strings_are_ambiguous_after_peer_compression() { + use loro_common::{ContainerID, ContainerType}; + let id = ContainerID::new_root("target", ContainerType::Text); + let marker = LoroValue::from(id.to_loro_value_string()); + let container = LoroValue::Container(id.clone()); + assert_lossy_pair(&marker, &container, true); + assert!(!ImportedValues::Exact.eq(&marker, &container)); + for string in ["plain text", "🦜:invalid"] { + assert_lossy_pair(&LoroValue::from(string), &container, false); + } + assert_lossy_pair( + &LoroValue::from("🦜:cid:0@0:Text"), + &LoroValue::Container(ContainerID::new_normal( + loro_common::ID::new(1, 0), + ContainerType::Text, + )), + true, + ); + assert_lossy_pair(&marker, &LoroValue::from("🦜:cid:root-other:Text"), false); + assert_lossy_pair( + &container, + &LoroValue::Container(ContainerID::new_root("other", ContainerType::Text)), + false, + ); + } + + #[test] + fn unknown_payload_bypass_still_compares_props_and_containers() { + use crate::{ + arena::SharedArena, + encoding::OwnedValue, + op::{FutureInnerContent, InnerContent, Op}, + }; + use loro_common::{ContainerID, ContainerType}; + let arena = SharedArena::new(); + let container = + arena.register_container(&ContainerID::new_root("future", ContainerType::Unknown(9))); + let make_op = |prop, value| Op { + counter: 0, + container, + content: InnerContent::Future(FutureInnerContent::Unknown { + prop, + value: Box::new(value), + }), + }; + let a = make_op(1, OwnedValue::LoroValue(LoroValue::Double(2.0))); + let b = make_op(1, OwnedValue::LoroValue(LoroValue::I64(2))); + assert!(super::op_eq( + &arena, + &arena, + ImportedValues::JsonLossy, + &a, + &b + )); + assert!(!super::op_eq(&arena, &arena, ImportedValues::Exact, &a, &b)); + let different_prop = make_op(2, OwnedValue::LoroValue(LoroValue::I64(2))); + assert!(!super::op_eq( + &arena, + &arena, + ImportedValues::JsonLossy, + &a, + &different_prop + )); + let mut different_container = b; + different_container.container = + arena.register_container(&ContainerID::new_root("other", ContainerType::Unknown(9))); + assert!(!super::op_eq( + &arena, + &arena, + ImportedValues::JsonLossy, + &a, + &different_container + )); + } + + #[cfg(feature = "counter")] + #[test] + fn counter_values_keep_numeric_equality_in_lossy_mode() { + use crate::{ + arena::SharedArena, + op::{FutureInnerContent, InnerContent, Op}, + }; + use loro_common::{ContainerID, ContainerType}; + let arena = SharedArena::new(); + let container = + arena.register_container(&ContainerID::new_root("counter", ContainerType::Counter)); + let make_op = |value| Op { + counter: 0, + container, + content: InnerContent::Future(FutureInnerContent::Counter(value)), + }; + for (a, b, equal) in [ + (2.0, 2.0, true), + (2.0, 3.0, false), + (-0.0, 0.0, true), + (f64::NAN, f64::NAN, true), + (f64::INFINITY, f64::INFINITY, true), + (f64::NAN, f64::INFINITY, false), + (1e-17, 0.0, false), + (-1e-17, 0.0, false), + ] { + for values in [ImportedValues::JsonLossy, ImportedValues::Exact] { + assert_eq!( + super::op_eq(&arena, &arena, values, &make_op(a), &make_op(b)), + equal + ); + } + } + } +} + +#[cfg(test)] +mod two_arena_tests { + use super::*; + use crate::{ + container::list::list_op::ListOp, + op::{ListSlice, RawOpContent}, + }; + use loro_common::{ContainerID, ContainerType}; + + fn text_change(arena: &SharedArena, text: &str) -> Change { + let op = arena.convert_single_op( + &ContainerID::new_root("t", ContainerType::Text), + 1, + 0, + 0, + RawOpContent::List(ListOp::Insert { + slice: ListSlice::RawStr { + str: text.into(), + unicode_len: text.chars().count(), + }, + pos: 0, + }), + ); + let mut ops = rle::RleVec::new(); + ops.push(op); + Change { + id: ID::new(1, 0), + lamport: 0, + timestamp: 0, + commit_msg: None, + deps: Frontiers::default(), + ops, + } + } + + #[test] + fn different_arenas_compare_container_ids_and_unicode_atoms() { + let a = SharedArena::new(); + let b = SharedArena::new(); + b.register_container(&ContainerID::new_root("other", ContainerType::Map)); + b.alloc_str("unrelated"); + let left = text_change(&a, "a😀bc"); + let same = text_change(&b, "a😀bc"); + let different = text_change(&b, "a😀Bc"); + assert_eq!( + first_mismatch(&a, &b, ImportedValues::Exact, &left, &same, 0, 4), + None + ); + assert_eq!( + first_mismatch(&a, &b, ImportedValues::Exact, &left, &different, 1, 4), + Some(2) + ); + } + + #[test] + fn cold_text_check_compares_dependencies_inside_a_merged_import() { + use crate::{cursor::PosType, LoroDoc}; + use std::sync::{atomic::AtomicI64, Arc}; + let source = LoroDoc::new_auto_commit(); + source.set_peer_id(1).unwrap(); + source.set_change_merge_interval(-1); + for i in 0..40 { + source + .get_text("t") + .insert(i, "a", PosType::Unicode) + .unwrap(); + source.commit_then_renew(); + } + let oplog = source.oplog().lock(); + let forged = crate::oplog::ChangeStore::new_mem(&oplog.arena, Arc::new(AtomicI64::new(-1))); + for i in 0..40 { + let mut c = (*oplog.get_change_at(ID::new(1, i)).unwrap()).clone(); + if i == 1 { + c.deps = Frontiers::default(); + } + forged.insert_change(c, false, true); + } + let bytes = forged.encode_all(oplog.vv(), oplog.frontiers()); + let local = crate::OpLog::new(Default::default()); + local.change_store.import_all(bytes).unwrap(); + let arena = SharedArena::new(); + let incoming = text_change(&arena, &"a".repeat(40)); + let err = local + .check_known_text_in_cold_block(&incoming, &arena, 0, 40) + .unwrap_err(); + assert!(matches!(err, LoroError::UsedOpID { id } if id == ID::new(1, 1))); + } +} diff --git a/vendor/loro-internal/src/oplog/loro_dag.rs b/vendor/loro-internal/src/oplog/loro_dag.rs new file mode 100644 index 0000000..eb8c05f --- /dev/null +++ b/vendor/loro-internal/src/oplog/loro_dag.rs @@ -0,0 +1,1619 @@ +use crate::change::{Change, Lamport}; +use crate::dag::{Dag, DagNode}; +use crate::id::{Counter, ID}; +use crate::span::{HasId, HasLamport}; +use crate::sync::Mutex; +use crate::version::{shrink_frontiers, Frontiers, ImVersionVector, VersionVector}; +use loro_common::{ + HasCounter, HasCounterSpan, HasIdSpan, HasLamportSpan, LoroError, LoroResult, PeerID, +}; +use once_cell::sync::OnceCell; +use rle::{HasIndex, HasLength, Mergable, Sliceable}; +use rustc_hash::FxHashSet; +use smallvec::SmallVec; +use std::cmp::Ordering; +use std::collections::{BTreeMap, BTreeSet, BinaryHeap}; +use std::fmt::Display; +use std::ops::{ControlFlow, Deref}; +use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; +use std::sync::Arc; +use tracing::instrument; + +use super::change_store::BatchDecodeInfo; +use super::ChangeStore; + +/// [AppDag] maintains the causal graph of the app. +/// It's faster to answer questions like what the meet of two versions is +#[derive(Debug)] +pub struct AppDag { + change_store: ChangeStore, + /// It only contains nodes that are already parsed. + /// + /// - All the unparsed op ids must be included in `unparsed_vv`. + /// - All the parsed and unparsed op ids must be included in `vv`. + map: Mutex<BTreeMap<ID, AppDagNode>>, + /// The latest known frontiers + frontiers: Frontiers, + /// The latest known version vector + vv: VersionVector, + /// The earliest known frontiers + shallow_since_frontiers: Frontiers, + /// The deps of the shallow frontiers + shallow_root_frontiers_deps: Frontiers, + /// The vv of shallow_frontiers_deps + shallow_since_vv: ImVersionVector, + /// Ops included in the version vector but not parsed yet + /// + /// # Invariants + /// + /// - `vv` >= `unparsed_vv` + unparsed_vv: Mutex<VersionVector>, + /// It's a set of points which are deps of some parsed ops. + /// But the ops in this set are not parsed yet. When they are parsed, + /// we need to make sure it breaks at the given point. + unhandled_dep_points: Mutex<BTreeSet<ID>>, + pending_txn_node: Option<AppDagNode>, + import_rollback_has_journal: AtomicBool, + import_rollback: Mutex<Option<AppDagRollback>>, +} + +#[derive(Debug)] +pub(crate) struct AppDagRollback { + frontiers: Frontiers, + vv: Arc<VersionVector>, + unparsed_vv: VersionVector, + shallow_since_frontiers: Frontiers, + shallow_root_frontiers_deps: Frontiers, + shallow_since_vv: ImVersionVector, + pending_txn_node: Option<AppDagNode>, + map_entries_before_mutation: BTreeMap<ID, Option<AppDagNode>>, + unhandled_dep_point_log: Vec<UnhandledDepPointLog>, +} + +#[derive(Debug)] +enum UnhandledDepPointLog { + Added(ID), + Removed(ID), +} + +#[derive(Debug, Clone)] +pub struct AppDagNode { + inner: Arc<AppDagNodeInner>, +} + +impl Deref for AppDagNode { + type Target = AppDagNodeInner; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +impl AppDagNode { + pub fn new(inner: AppDagNodeInner) -> Self { + Self { + inner: Arc::new(inner), + } + } +} + +#[derive(Debug, Clone)] +pub struct AppDagNodeInner { + pub(crate) peer: PeerID, + pub(crate) cnt: Counter, + pub(crate) lamport: Lamport, + pub(crate) deps: Frontiers, + pub(crate) vv: OnceCell<ImVersionVector>, + /// A flag indicating whether any other nodes from a different peer depend on this node. + /// The calculation of frontiers is based on the property that a node does not depend + /// on the middle of other nodes. + pub(crate) has_succ: bool, + pub(crate) len: usize, +} + +impl From<AppDagNodeInner> for AppDagNode { + fn from(inner: AppDagNodeInner) -> Self { + AppDagNode { + inner: Arc::new(inner), + } + } +} + +impl AppDag { + pub(super) fn new(change_store: ChangeStore) -> Self { + Self { + change_store, + map: Mutex::new(BTreeMap::new()), + frontiers: Frontiers::default(), + vv: VersionVector::default(), + unparsed_vv: Mutex::new(VersionVector::default()), + unhandled_dep_points: Mutex::new(BTreeSet::new()), + shallow_since_frontiers: Default::default(), + shallow_root_frontiers_deps: Default::default(), + shallow_since_vv: Default::default(), + pending_txn_node: None, + import_rollback_has_journal: AtomicBool::new(false), + import_rollback: Mutex::new(None), + } + } + + pub fn frontiers(&self) -> &Frontiers { + &self.frontiers + } + + pub fn vv(&self) -> &VersionVector { + &self.vv + } + + pub fn shallow_since_vv(&self) -> &ImVersionVector { + &self.shallow_since_vv + } + + pub fn shallow_since_frontiers(&self) -> &Frontiers { + &self.shallow_since_frontiers + } + + pub(crate) fn begin_import_rollback(&mut self, old_vv: Arc<VersionVector>) { + let old_vv_is_empty = self.vv.is_empty(); + let mut rollback = self.import_rollback.lock(); + debug_assert!(rollback.is_none()); + *rollback = Some(AppDagRollback { + frontiers: self.frontiers.clone(), + vv: old_vv, + unparsed_vv: self.unparsed_vv.lock().clone(), + shallow_since_frontiers: self.shallow_since_frontiers.clone(), + shallow_root_frontiers_deps: self.shallow_root_frontiers_deps.clone(), + shallow_since_vv: self.shallow_since_vv.clone(), + pending_txn_node: self.pending_txn_node.clone(), + map_entries_before_mutation: BTreeMap::new(), + unhandled_dep_point_log: Vec::new(), + }); + self.import_rollback_has_journal + .store(!old_vv_is_empty, AtomicOrdering::Relaxed); + } + + pub(crate) fn commit_import_rollback(&mut self) { + self.import_rollback_has_journal + .store(false, AtomicOrdering::Relaxed); + *self.import_rollback.lock() = None; + } + + pub(crate) fn rollback_import(&mut self) { + self.import_rollback_has_journal + .store(false, AtomicOrdering::Relaxed); + let Some(checkpoint) = self.import_rollback.lock().take() else { + return; + }; + + let imported_spans = self.vv.sub_iter(&checkpoint.vv).collect::<Vec<_>>(); + let mut map = self.map.lock(); + for span in imported_spans { + let start = ID::new(span.peer, span.counter.start); + let end = ID::new(span.peer, span.counter.end); + let keys = map.range(start..end).map(|(id, _)| *id).collect::<Vec<_>>(); + for key in keys { + map.remove(&key); + } + } + + for (id, node) in checkpoint.map_entries_before_mutation { + if let Some(node) = node { + map.insert(id, node); + } else { + map.remove(&id); + } + } + drop(map); + + self.frontiers = checkpoint.frontiers; + self.vv = (*checkpoint.vv).clone(); + self.shallow_since_frontiers = checkpoint.shallow_since_frontiers; + self.shallow_root_frontiers_deps = checkpoint.shallow_root_frontiers_deps; + self.shallow_since_vv = checkpoint.shallow_since_vv; + *self.unparsed_vv.lock() = checkpoint.unparsed_vv; + + let mut unhandled_dep_points = self.unhandled_dep_points.lock(); + if checkpoint.vv.is_empty() { + unhandled_dep_points.clear(); + } + for item in checkpoint.unhandled_dep_point_log.into_iter().rev() { + match item { + UnhandledDepPointLog::Added(id) => { + unhandled_dep_points.remove(&id); + } + UnhandledDepPointLog::Removed(id) => { + unhandled_dep_points.insert(id); + } + } + } + drop(unhandled_dep_points); + + self.pending_txn_node = checkpoint.pending_txn_node; + } + + fn record_map_entry_before_mutation(&self, map: &BTreeMap<ID, AppDagNode>, id: ID) { + if !self + .import_rollback_has_journal + .load(AtomicOrdering::Relaxed) + { + return; + } + + self.record_map_entry_before_replacement(id, map.get(&id).cloned()); + } + + fn record_map_entry_before_replacement(&self, id: ID, old: Option<AppDagNode>) { + if !self + .import_rollback_has_journal + .load(AtomicOrdering::Relaxed) + { + return; + } + + let mut rollback = self.import_rollback.lock(); + let Some(rollback) = rollback.as_mut() else { + return; + }; + + let old_end = rollback.vv.get(&id.peer).copied().unwrap_or(0); + if id.counter >= old_end { + return; + } + + rollback + .map_entries_before_mutation + .entry(id) + .or_insert(old); + } + + fn record_unhandled_dep_point_added(&self, id: ID) { + if !self + .import_rollback_has_journal + .load(AtomicOrdering::Relaxed) + { + return; + } + + if let Some(rollback) = self.import_rollback.lock().as_mut() { + rollback + .unhandled_dep_point_log + .push(UnhandledDepPointLog::Added(id)); + } + } + + fn record_unhandled_dep_point_removed(&self, id: ID) { + if !self + .import_rollback_has_journal + .load(AtomicOrdering::Relaxed) + { + return; + } + + if let Some(rollback) = self.import_rollback.lock().as_mut() { + rollback + .unhandled_dep_point_log + .push(UnhandledDepPointLog::Removed(id)); + } + } + + pub fn is_empty(&self) -> bool { + self.vv.is_empty() + } + + #[tracing::instrument(skip_all, name = "handle_new_change")] + pub(super) fn handle_new_change( + &mut self, + change: &Change, + from_local: bool, + rollback_old_vv: Option<&VersionVector>, + ) { + let len = change.content_len(); + self.update_version_on_new_change(change, from_local); + #[cfg(debug_assertions)] + { + let unhandled_dep_points = self.unhandled_dep_points.lock(); + let c = unhandled_dep_points + .range(change.id_start()..change.id_end()) + .count(); + assert!(c == 0); + } + + let mut inserted = false; + if change.deps_on_self() { + let record_old_node_before_merge = rollback_old_vv + .and_then(|vv| vv.get(&change.id.peer).copied()) + .filter(|old_end| *old_end == change.id.counter); + // We may not need to push new element to dag because it only depends on itself + inserted = + self.with_last_mut_of_peer(change.id.peer, record_old_node_before_merge, |last| { + let (_, last) = last.unwrap(); + if last.has_succ { + // Don't merge the node if there are other nodes depending on it + return false; + } + + assert_eq!(last.peer, change.id.peer, "peer id is not the same"); + assert_eq!( + last.cnt + last.len as Counter, + change.id.counter, + "counter is not continuous" + ); + assert_eq!( + last.lamport + last.len as Lamport, + change.lamport, + "lamport is not continuous" + ); + let last = Arc::make_mut(&mut last.inner); + last.len = (change.id.counter - last.cnt) as usize + len; + last.has_succ = false; + true + }); + } + + if !inserted { + let node: AppDagNode = AppDagNodeInner { + vv: OnceCell::new(), + peer: change.id.peer, + cnt: change.id.counter, + lamport: change.lamport, + deps: change.deps.clone(), + has_succ: false, + len, + } + .into(); + + let mut map = self.map.lock(); + map.insert(node.id_start(), node); + self.handle_deps_break_points(change.deps.iter(), change.id.peer, Some(&mut map)); + } + } + + fn try_with_node_mut<R>( + &self, + map: &mut BTreeMap<ID, AppDagNode>, + id: ID, + f: impl FnOnce(Option<(ID, &mut AppDagNode)>) -> R, + ) -> R { + let x = map.range_mut(..=id).next_back(); + if let Some((node_id, node)) = x { + if node.contains_id(id) { + f(Some((*node_id, node))) + } else { + f(None) + } + } else { + f(None) + } + } + + /// If the lamport of change can be calculated, return Ok, otherwise, Err + pub(crate) fn calc_unknown_lamport_change(&self, change: &mut Change) -> Result<(), ()> { + for dep in change.deps.iter() { + match self.get_lamport(&dep) { + Some(lamport) => { + change.lamport = change.lamport.max(lamport + 1); + } + None => return Err(()), + } + } + Ok(()) + } + + pub(crate) fn find_deps_of_id(&self, id: ID) -> Frontiers { + let Some(node) = self.get(id) else { + return Frontiers::default(); + }; + + let offset = id.counter - node.cnt; + if offset == 0 { + node.deps.clone() + } else { + ID::new(id.peer, node.cnt + offset - 1).into() + } + } + + pub(crate) fn with_last_mut_of_peer<R>( + &mut self, + peer: PeerID, + record_if_before: Option<Counter>, + f: impl FnOnce(Option<(ID, &mut AppDagNode)>) -> R, + ) -> R { + self.lazy_load_last_of_peer(peer); + let mut binding = self.map.lock(); + let last = binding + .range_mut(..=ID::new(peer, Counter::MAX)) + .next_back() + .map(|(id, v)| { + if record_if_before.is_some_and(|old_end| id.counter < old_end) { + self.record_map_entry_before_replacement(*id, Some(v.clone())); + } + (*id, v) + }); + f(last) + } + + fn update_version_on_new_change(&mut self, change: &Change, from_local: bool) { + if from_local { + assert!(self.pending_txn_node.take().is_some()); + assert_eq!( + self.vv.get(&change.id.peer).copied().unwrap_or(0), + change.ctr_end() + ); + } else { + let id_last = change.id_last(); + self.frontiers + .update_frontiers_on_new_change(id_last, &change.deps); + assert!(self.pending_txn_node.is_none()); + assert_eq!( + self.vv.get(&change.id.peer).copied().unwrap_or(0), + change.id.counter + ); + self.vv.extend_to_include_last_id(id_last); + } + } + + pub(super) fn lazy_load_last_of_peer(&mut self, peer: u64) { + let unparsed_vv = self.unparsed_vv.lock(); + if !unparsed_vv.contains_key(&peer) || self.vv[&peer] >= unparsed_vv[&peer] { + return; + } + + let Some(nodes) = self.change_store.get_last_dag_nodes_for_peer(peer) else { + panic!("unparsed vv don't match with change store. Peer:{peer} is not in change store") + }; + + self.lazy_load_nodes_internal(nodes, peer, None); + } + + fn lazy_load_nodes_internal( + &self, + nodes: Vec<AppDagNode>, + peer: u64, + map_input: Option<&mut BTreeMap<ID, AppDagNode>>, + ) { + assert!(!nodes.is_empty()); + let mut map_guard = None; + let map = map_input.unwrap_or_else(|| { + map_guard = Some(self.map.lock()); + map_guard.as_mut().unwrap() + }); + let new_dag_start_counter_for_the_peer = nodes[0].cnt; + let nodes_cnt_end = nodes.last().unwrap().ctr_end(); + let mut unparsed_vv = self.unparsed_vv.lock(); + let end_counter = unparsed_vv[&peer]; + assert!(end_counter <= nodes_cnt_end); + let mut deps_on_others = Vec::new(); + let mut break_point_set = self.unhandled_dep_points.lock(); + for mut node in nodes { + if node.cnt >= end_counter { + // skip already parsed nodes + break; + } + + if node.cnt + node.len as Counter > end_counter { + node = node.slice(0, (end_counter - node.cnt) as usize); + // This is unlikely to happen + } + + for dep in node.deps.iter() { + if dep.peer != peer { + deps_on_others.push(dep); + } + } + + // PERF: we can try to merge the node with the previous node + let break_point_ends: Vec<_> = break_point_set + .range(node.id_start()..node.id_end()) + .map(|id| (id.counter - node.cnt) as usize + 1) + .collect(); + if break_point_ends.is_empty() { + self.record_map_entry_before_mutation(map, node.id_start()); + map.insert(node.id_start(), node); + } else { + let mut slice_start = 0; + for slice_end in break_point_ends.iter().copied() { + let mut slice_node = node.slice(slice_start, slice_end); + let inner = Arc::make_mut(&mut slice_node.inner); + inner.has_succ = true; + self.record_map_entry_before_mutation(map, slice_node.id_start()); + map.insert(slice_node.id_start(), slice_node); + slice_start = slice_end; + } + + let last_break_point = break_point_ends.last().copied().unwrap(); + if last_break_point != node.len { + let slice_node = node.slice(last_break_point, node.len); + self.record_map_entry_before_mutation(map, slice_node.id_start()); + map.insert(slice_node.id_start(), slice_node); + } + + for break_point in break_point_ends.into_iter() { + let id = node.id_start().inc(break_point as Counter - 1); + if break_point_set.remove(&id) { + self.record_unhandled_dep_point_removed(id); + } + } + } + } + + if new_dag_start_counter_for_the_peer == 0 { + unparsed_vv.remove(&peer); + } else { + unparsed_vv.insert(peer, new_dag_start_counter_for_the_peer); + } + drop(unparsed_vv); + drop(break_point_set); + self.handle_deps_break_points(deps_on_others.iter().copied(), peer, Some(map)); + } + + fn handle_deps_break_points( + &self, + ids: impl IntoIterator<Item = ID>, + skip_peer: PeerID, + map: Option<&mut BTreeMap<ID, AppDagNode>>, + ) { + let mut map_guard = None; + let map = map.unwrap_or_else(|| { + map_guard = Some(self.map.lock()); + map_guard.as_mut().unwrap() + }); + for id in ids { + if id.peer == skip_peer { + continue; + } + + let mut handled = false; + let ans = self.try_with_node_mut(map, id, |target| { + // We don't need to break the dag node if it's not loaded yet + let (target_id, target) = target?; + if target.ctr_last() == id.counter { + self.record_map_entry_before_replacement(target_id, Some(target.clone())); + let target = Arc::make_mut(&mut target.inner); + handled = true; + target.has_succ = true; + None + } else { + // We need to split the target node into two part + // so that we can ensure the new change depends on the + // last id of a dag node. + + let new_node = + target.slice(id.counter as usize - target.cnt as usize + 1, target.len); + self.record_map_entry_before_replacement(target_id, Some(target.clone())); + let target = Arc::make_mut(&mut target.inner); + target.len -= new_node.len; + Some(new_node) + } + }); + + if let Some(new_node) = ans { + self.record_map_entry_before_mutation(map, new_node.id_start()); + map.insert(new_node.id_start(), new_node); + } else if !handled { + let mut unhandled_dep_points = self.unhandled_dep_points.lock(); + if unhandled_dep_points.insert(id) { + self.record_unhandled_dep_point_added(id); + } + } + } + } + + fn ensure_lazy_load_node(&self, id: ID) -> LoroResult<()> { + if self.shallow_since_vv.includes_id(id) { + return Ok(()); + } + + loop { + // We need to load all the dag nodes that has the same peer and greater counter than the given `id` + // Because we only record the end counter of the unparsed version on `unparsed_vv` + let unparsed_end = { + let unparsed_vv = self.unparsed_vv.lock(); + unparsed_vv.get(&id.peer).copied().unwrap_or(0) + }; + if unparsed_end <= id.counter { + return Ok(()); + } + + let last_unparsed_id = ID::new(id.peer, unparsed_end - 1); + let Some(nodes) = self + .change_store + .get_dag_nodes_that_contains(last_unparsed_id) + else { + // An unreadable external block is recorded by ChangeStore; return its + // decode error. A parsable store missing an id promised by unparsed_vv + // is still an impossible internal inconsistency and must fail fast. + self.change_store.corrupt_block_error()?; + panic!("unparsed vv don't match with change store. Id:{id} is not in change store") + }; + + self.lazy_load_nodes_internal(nodes, id.peer, None); + } + } + + pub fn total_parsed_dag_node(&self) -> usize { + self.map.lock().len() + } + + pub(crate) fn set_version_by_fast_snapshot_import( + &mut self, + v: BatchDecodeInfo, + ) -> LoroResult<()> { + assert!(self.vv.is_empty()); + *self.unparsed_vv.lock() = v.vv.clone(); + self.vv = v.vv; + self.frontiers = v.frontiers; + if let Some((vv, f)) = v.start_version { + if !f.is_empty() { + assert!(f.len() == 1); + let id = f.as_single().unwrap(); + let node = self.try_get(id)?.unwrap(); + assert!(node.cnt == id.counter); + self.shallow_root_frontiers_deps = node.deps.clone(); + } + self.shallow_since_frontiers = f; + self.shallow_since_vv = ImVersionVector::from_vv(&vv); + } + Ok(()) + } + + /// This method is slow and should only be used for debugging and testing. + /// + /// It will check the following properties: + /// + /// 1. Counter is continuous + /// 2. A node always depends of the last ids of other nodes + /// 3. Lamport is correctly calculated + /// 4. VV for each node is correctly calculated + /// 5. Frontiers are correctly calculated + #[instrument(skip(self))] + pub fn check_dag_correctness(&self) { + { + // parse all nodes + let unparsed_vv = self.unparsed_vv.lock().clone(); + for (peer, cnt) in unparsed_vv.iter() { + if *cnt == 0 { + continue; + } + + let mut end_cnt = *cnt; + let init_counter = self.shallow_since_vv.get(peer).copied().unwrap_or(0); + while end_cnt > init_counter { + let cnt = end_cnt - 1; + self.ensure_lazy_load_node(ID::new(*peer, cnt)).unwrap(); + end_cnt = self.unparsed_vv.lock().get(peer).copied().unwrap_or(0); + } + } + + self.unparsed_vv.lock().clear(); + } + { + // check property 1: Counter is continuous + let map = self.map.lock(); + let mut last_end_id = ID::new(0, 0); + for (&id, node) in map.iter() { + let init_counter = self.shallow_since_vv.get(&id.peer).copied().unwrap_or(0); + if id.peer == last_end_id.peer { + assert!(id.counter == last_end_id.counter); + } else { + assert_eq!(id.counter, init_counter); + } + + last_end_id = id.inc(node.len as Counter); + } + } + { + // check property 2: A node always depends of the last ids of other nodes + let map = self.map.lock(); + check_always_dep_on_last_id(&map); + } + { + // check property 3: Lamport is correctly calculated + let map = self.map.lock(); + 'outer: for (_, node) in map.iter() { + let mut this_lamport = 0; + for dep in node.deps.iter() { + if self.shallow_since_vv.includes_id(dep) { + continue 'outer; + } + + let (_, dep_node) = map.range(..=dep).next_back().unwrap(); + this_lamport = this_lamport.max(dep_node.lamport_end()); + } + + assert_eq!(this_lamport, node.lamport); + } + } + { + // check property 4: VV for each node is correctly calculated + let map = self.map.lock().clone(); + 'outer: for (_, node) in map.iter() { + let actual_vv = self.ensure_vv_for(node); + let mut expected_vv = ImVersionVector::default(); + for dep in node.deps.iter() { + if self.shallow_since_vv.includes_id(dep) { + continue 'outer; + } + + let (_, dep_node) = map.range(..=dep).next_back().unwrap(); + self.ensure_vv_for(dep_node); + expected_vv.extend_to_include_vv(dep_node.vv.get().unwrap().iter()); + expected_vv.extend_to_include_last_id(dep); + } + + assert_eq!(actual_vv, expected_vv); + } + } + { + // check property 5: Frontiers are correctly calculated + let mut maybe_frontiers = FxHashSet::default(); + let map = self.map.lock(); + for (_, node) in map.iter() { + maybe_frontiers.insert(node.id_last()); + } + + for (_, node) in map.iter() { + for dep in node.deps.iter() { + maybe_frontiers.remove(&dep); + } + } + + let frontiers = self.frontiers.iter().collect::<FxHashSet<_>>(); + assert_eq!(maybe_frontiers, frontiers); + } + } + + pub(crate) fn can_export_shallow_snapshot_on(&self, deps: &Frontiers) -> bool { + for id in deps.iter() { + if !self.vv.includes_id(id) { + return false; + } + } + + if self.is_before_shallow_root(deps) { + return false; + } + + true + } + + pub(crate) fn is_before_shallow_root(&self, deps: &Frontiers) -> bool { + // trace!("Is on shallow history? deps={:?}", deps); + // trace!("self.shallow_since_vv {:?}", &self.shallow_since_vv); + // trace!("self.shallow_frontiers {:?}", &self.shallow_since_frontiers); + + if self.shallow_since_vv.is_empty() { + return false; + } + + if deps.is_empty() { + return true; + } + + if deps.iter().any(|x| self.shallow_since_vv.includes_id(x)) { + return true; + } + + if deps + .iter() + .any(|x| self.shallow_since_frontiers.contains(&x)) + { + return deps != &self.shallow_since_frontiers; + } + + false + } + + /// Panics when a dependency block cannot be parsed. Production callers use + /// [`Self::try_import_deps_before_shallow_root`]. + #[allow(dead_code)] + pub(crate) fn import_deps_before_shallow_root(&self, deps: &Frontiers) -> bool { + self.try_import_deps_before_shallow_root(deps).unwrap() + } + + pub(crate) fn try_import_deps_before_shallow_root(&self, deps: &Frontiers) -> LoroResult<bool> { + if self.shallow_since_vv.is_empty() { + return Ok(false); + } + + if deps.is_empty() { + return Ok(true); + } + + // Deps equal to the root's own deps describe a change CONCURRENT with + // the root frontier op: its causal past is covered by the root state, + // so the boundary shortcut in `frontiers_to_vv` would resolve it to + // the shallow vv below. But the dep ids themselves are trimmed from + // the dag, so no lamport can be computed for such a change — it would + // be parked as pending and then panic in `calc_unknown_lamport_change`. + // Reject it like any other pre-root update. + if deps == &self.shallow_root_frontiers_deps { + return Ok(true); + } + + let shallow_vv = VersionVector::from_im_vv(&self.shallow_since_vv); + if let Some(vv) = self.try_frontiers_to_vv(deps)? { + return Ok(!vv.includes_vv(&shallow_vv)); + } + + // Import only needs to reject updates whose causal source is older than + // the shallow root. A dependency set that touches the retained boundary + // can still be a valid post-root update, even when the rest of the deps + // are imported later in the same batch. + if deps + .iter() + .any(|id| self.shallow_since_frontiers.contains(&id)) + { + return Ok(false); + } + + Ok(deps.iter().any(|id| self.shallow_since_vv.includes_id(id))) + } + + /// Travel the ancestors of the given id, and call the callback for each node + /// + /// It will travel the ancestors in the reverse order (from the greatest lamport to the smallest) + pub(crate) fn try_travel_ancestors( + &self, + id: ID, + f: &mut dyn FnMut(&AppDagNode) -> ControlFlow<()>, + ) -> LoroResult<()> { + struct PendingNode(AppDagNode); + impl PartialEq for PendingNode { + fn eq(&self, other: &Self) -> bool { + self.0.lamport_last() == other.0.lamport_last() && self.0.peer == other.0.peer + } + } + impl Eq for PendingNode {} + impl PartialOrd for PendingNode { + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { + Some(self.cmp(other)) + } + } + impl Ord for PendingNode { + fn cmp(&self, other: &Self) -> Ordering { + self.0 + .lamport_last() + .cmp(&other.0.lamport_last()) + .then_with(|| self.0.peer.cmp(&other.0.peer)) + } + } + + let mut visited = FxHashSet::default(); + let mut pending: BinaryHeap<PendingNode> = BinaryHeap::new(); + pending.push(PendingNode( + self.try_get(id)?.ok_or(LoroError::FrontiersNotFound(id))?, + )); + while let Some(PendingNode(node)) = pending.pop() { + if f(&node).is_break() { + break; + } + + for dep in node.deps.iter() { + let Some(dep_node) = self.try_get(dep)? else { + continue; + }; + if visited.contains(&dep_node.id_start()) { + continue; + } + + visited.insert(dep_node.id_start()); + pending.push(PendingNode(dep_node)); + } + } + Ok(()) + } + + pub(crate) fn update_version_on_new_local_op( + &mut self, + deps: &Frontiers, + start_id: ID, + start_lamport: Lamport, + len: usize, + ) { + let last_id = start_id.inc(len as Counter - 1); + // PERF: we can cache this last_id - this is a hot path + self.vv.set_last(last_id); + self.frontiers.update_frontiers_on_new_change(last_id, deps); + match &mut self.pending_txn_node { + Some(node) => { + assert!( + node.peer == start_id.peer + && node.cnt + node.len as Counter == start_id.counter + && deps.len() == 1 + && deps.as_single().unwrap().peer == start_id.peer + ); + let inner = Arc::make_mut(&mut node.inner); + inner.len += len; + } + None => { + let node = AppDagNode { + inner: Arc::new(AppDagNodeInner { + peer: start_id.peer, + cnt: start_id.counter, + lamport: start_lamport, + deps: deps.clone(), + vv: OnceCell::new(), + has_succ: false, + len, + }), + }; + self.pending_txn_node = Some(node); + } + } + } + + /// Undo [`Self::update_version_on_new_local_op`] for every op of a + /// transaction that is discarded instead of committed: `frontiers` and + /// `start_counter` are the DAG's frontiers and `peer`'s end before its + /// first op. + pub(crate) fn discard_pending_txn( + &mut self, + frontiers: Frontiers, + peer: PeerID, + start_counter: Counter, + ) { + self.pending_txn_node = None; + self.frontiers = frontiers; + // An end of 0 removes the peer. + self.vv.set_last(ID::new(peer, start_counter - 1)); + } + + pub(crate) fn latest_vv_contains_peer(&self, peer: PeerID) -> bool { + self.vv.contains_key(&peer) && *self.vv.get(&peer).unwrap() > 0 + } +} + +fn check_always_dep_on_last_id(map: &BTreeMap<ID, AppDagNode>) { + for (_, node) in map.iter() { + for dep in node.deps.iter() { + let Some((&dep_id, dep_node)) = map.range(..=dep).next_back() else { + // It's shallow + continue; + }; + assert_eq!(dep_node.id_start(), dep_id); + if dep_node.contains_id(dep) { + assert_eq!(dep_node.id_last(), dep); + } + } + } +} + +impl HasIndex for AppDagNode { + type Int = Counter; + fn get_start_index(&self) -> Self::Int { + self.cnt + } + + fn get_end_index(&self) -> Self::Int { + self.cnt + self.len as Counter + } +} + +impl Sliceable for AppDagNode { + fn slice(&self, from: usize, to: usize) -> Self { + AppDagNodeInner { + peer: self.peer, + cnt: self.cnt + from as Counter, + lamport: self.lamport + from as Lamport, + deps: if from > 0 { + Frontiers::from_id(self.id_start().inc(from as Counter - 1)) + } else { + self.deps.clone() + }, + vv: if let Some(vv) = self.vv.get() { + let mut new = vv.clone(); + new.insert(self.peer, self.cnt + from as Counter); + OnceCell::with_value(new) + } else { + OnceCell::new() + }, + has_succ: if to == self.len { self.has_succ } else { true }, + len: to - from, + } + .into() + } +} + +impl HasId for AppDagNode { + fn id_start(&self) -> ID { + ID { + peer: self.peer, + counter: self.cnt, + } + } +} + +impl HasCounter for AppDagNode { + fn ctr_start(&self) -> Counter { + self.cnt + } +} + +impl HasLength for AppDagNode { + fn atom_len(&self) -> usize { + self.len + } + + fn content_len(&self) -> usize { + self.len + } +} + +impl Mergable for AppDagNode { + fn is_mergable(&self, other: &Self, _conf: &()) -> bool + where + Self: Sized, + { + !self.has_succ + && self.peer == other.peer + && self.cnt + self.len as Counter == other.cnt + && other.deps.len() == 1 + && self.lamport + self.len as Lamport == other.lamport + && other.deps.as_single().unwrap().peer == self.peer + } + + fn merge(&mut self, other: &Self, _conf: &()) + where + Self: Sized, + { + assert_eq!( + other.deps.as_single().unwrap().counter, + self.cnt + self.len as Counter - 1 + ); + let this = Arc::make_mut(&mut self.inner); + this.len += other.len; + this.has_succ = other.has_succ; + } +} + +impl HasLamport for AppDagNode { + fn lamport(&self) -> Lamport { + self.lamport + } +} + +impl DagNode for AppDagNode { + fn deps(&self) -> &Frontiers { + &self.deps + } +} + +impl Dag for AppDag { + type Node = AppDagNode; + + fn frontier(&self) -> &Frontiers { + &self.frontiers + } + + fn get(&self, id: ID) -> Option<Self::Node> { + self.try_get(id).unwrap() + } + + fn try_get(&self, id: ID) -> LoroResult<Option<Self::Node>> { + self.ensure_lazy_load_node(id)?; + let binding = self.map.lock(); + if let Some(x) = binding.range(..=id).next_back() { + if x.1.contains_id(id) { + // PERF: do we need to optimize clone like this? + // by adding another layer of Arc? + return Ok(Some(x.1.clone())); + } + } + + if let Some(node) = &self.pending_txn_node { + if node.peer == id.peer && node.cnt <= id.counter { + assert!(node.cnt + node.len as Counter > id.counter); + return Ok(Some(node.clone())); + } + } + + Ok(None) + } + + fn vv(&self) -> &VersionVector { + &self.vv + } + + fn contains(&self, id: ID) -> bool { + self.vv.includes_id(id) + } +} + +impl AppDag { + // PERF: this may be painfully slow + /// get the version vector for a certain op. + /// It's the version when the op is applied + pub fn get_vv(&self, id: ID) -> Option<ImVersionVector> { + self.get(id).map(|x| { + let mut vv = self.ensure_vv_for(&x); + vv.insert(id.peer, id.counter + 1); + vv + }) + } + + pub(crate) fn ensure_vv_for(&self, target_node: &AppDagNode) -> ImVersionVector { + self.try_ensure_vv_for(target_node).unwrap() + } + + pub(crate) fn try_ensure_vv_for( + &self, + target_node: &AppDagNode, + ) -> LoroResult<ImVersionVector> { + if target_node.vv.get().is_none() { + // Iterative DFS. When the DAG contains a diamond, a dep can end + // up on the stack multiple times (once for each ancestor that + // re-queued the current node before its deps were ready). We + // skip nodes whose vv has already been computed — the original + // code eagerly called `OnceCell::set(..).unwrap()` on every pop + // and panicked on the second visit (see loro-dev/loro#929). + let mut stack: SmallVec<[AppDagNode; 4]> = smallvec::smallvec![target_node.clone()]; + while let Some(top_node) = stack.pop() { + if top_node.vv.get().is_some() { + continue; + } + + let mut ans_vv = ImVersionVector::default(); + if top_node.deps == self.shallow_root_frontiers_deps { + for (&p, &c) in self.shallow_since_vv.iter() { + ans_vv.insert(p, c); + } + } else { + let mut all_deps_processed = true; + for id in top_node.deps.iter() { + let Some(node) = self.try_get(id)? else { + if self.shallow_since_vv.includes_id(id) { + continue; + } + + panic!("deps should be in the dag"); + }; + if node.vv.get().is_none() { + if all_deps_processed { + stack.push(top_node.clone()); + } + all_deps_processed = false; + stack.push(node); + continue; + }; + } + + if !all_deps_processed { + continue; + } + + for id in top_node.deps.iter() { + let Some(node) = self.try_get(id)? else { + if self.shallow_since_vv.includes_id(id) { + ans_vv.extend_to_include_vv(self.shallow_since_vv.iter()); + continue; + } + + panic!("deps should be in the dag"); + }; + let dep_vv = node.vv.get().unwrap(); + if ans_vv.is_empty() { + ans_vv = dep_vv.clone(); + } else { + ans_vv.extend_to_include_vv(dep_vv.iter()); + } + + ans_vv.insert(node.peer, node.ctr_end()); + } + } + + // Tolerate a racing set from the diamond case above: if + // another path already initialized this cell, trust that + // value (it was computed from the same DAG) and move on. + let _ = top_node.vv.set(ans_vv); + } + } + + Ok(target_node.vv.get().unwrap().clone()) + } + + /// Compare the causal order of two versions. + /// If None, two versions are concurrent to each other + pub fn cmp_version(&self, a: ID, b: ID) -> Option<Ordering> { + if a.peer == b.peer { + return Some(a.counter.cmp(&b.counter)); + } + + let a = self.get_vv(a).unwrap(); + let b = self.get_vv(b).unwrap(); + a.partial_cmp(&b) + } + + pub fn get_lamport(&self, id: &ID) -> Option<Lamport> { + self.try_get_lamport(id).unwrap() + } + + pub fn try_get_lamport(&self, id: &ID) -> LoroResult<Option<Lamport>> { + Ok(self.try_get(*id)?.and_then(|node| { + assert!(id.counter >= node.cnt); + if node.cnt + node.len as Counter > id.counter { + Some(node.lamport + (id.counter - node.cnt) as Lamport) + } else { + None + } + })) + } + + pub fn get_change_lamport_from_deps(&self, deps: &Frontiers) -> Option<Lamport> { + self.try_get_change_lamport_from_deps(deps).unwrap() + } + + pub fn try_get_change_lamport_from_deps( + &self, + deps: &Frontiers, + ) -> LoroResult<Option<Lamport>> { + let mut lamport = 0; + for id in deps.iter() { + let Some(x) = self.try_get_lamport(&id)? else { + return Ok(None); + }; + lamport = lamport.max(x + 1); + } + + Ok(Some(lamport)) + } + + /// Convert a frontiers to a version vector + /// + /// If the frontiers version is not found in the dag, return None + pub fn frontiers_to_vv(&self, frontiers: &Frontiers) -> Option<VersionVector> { + self.try_frontiers_to_vv(frontiers).unwrap() + } + + pub fn try_frontiers_to_vv(&self, frontiers: &Frontiers) -> LoroResult<Option<VersionVector>> { + if frontiers == &self.shallow_root_frontiers_deps { + let vv = VersionVector::from_im_vv(&self.shallow_since_vv); + return Ok(Some(vv)); + } + + let mut vv: VersionVector = Default::default(); + for id in frontiers.iter() { + let Some(x) = self.try_get(id)? else { + return Ok(None); + }; + let target_vv = self.try_ensure_vv_for(&x)?; + vv.extend_to_include_vv(target_vv.iter()); + vv.extend_to_include_last_id(id); + } + + Ok(Some(vv)) + } + + #[allow(unused)] + pub(crate) fn frontiers_to_im_vv(&self, frontiers: &Frontiers) -> ImVersionVector { + if frontiers.is_empty() { + return Default::default(); + } + + let mut iter = frontiers.iter(); + let mut vv = { + let id = iter.next().unwrap(); + let Some(x) = self.get(id) else { + unreachable!() + }; + let mut vv = self.ensure_vv_for(&x); + vv.extend_to_include_last_id(id); + vv + }; + + for id in iter { + let Some(x) = self.get(id) else { + unreachable!() + }; + let x = self.ensure_vv_for(&x); + vv.extend_to_include_vv(x.iter()); + vv.extend_to_include_last_id(id); + } + + vv + } + + pub fn im_vv_to_frontiers(&self, vv: &ImVersionVector) -> Frontiers { + if vv.is_empty() { + return Default::default(); + } + + let this = vv; + let last_ids: Frontiers = this + .iter() + .filter_map(|(client_id, cnt)| { + if *cnt <= 0 { + return None; + } + + if self + .shallow_since_vv + .includes_id(ID::new(*client_id, *cnt - 1)) + { + return None; + } + + Some(ID::new(*client_id, cnt - 1)) + }) + .collect(); + + if last_ids.is_empty() { + return self.shallow_since_frontiers.clone(); + } + + shrink_frontiers(&last_ids, self).unwrap() + } + + pub fn vv_to_frontiers(&self, vv: &VersionVector) -> Frontiers { + self.try_vv_to_frontiers(vv).unwrap() + } + + pub fn try_vv_to_frontiers(&self, vv: &VersionVector) -> LoroResult<Frontiers> { + if vv.is_empty() { + return Ok(Default::default()); + } + + let this = vv; + let last_ids: Frontiers = this + .iter() + .filter_map(|(client_id, cnt)| { + if *cnt <= 0 { + return None; + } + + if self + .shallow_since_vv + .includes_id(ID::new(*client_id, *cnt - 1)) + { + return None; + } + + Some(ID::new(*client_id, cnt - 1)) + }) + .collect(); + + if last_ids.is_empty() { + return Ok(self.shallow_since_frontiers.clone()); + } + + crate::version::try_shrink_frontiers(&last_ids, self) + } + + pub(crate) fn frontiers_to_next_lamport(&self, frontiers: &Frontiers) -> Lamport { + if frontiers.is_empty() { + return 0; + } + + let mut iter = frontiers.iter(); + let mut lamport = { + let id = iter.next().unwrap(); + let Some(x) = self.get(id) else { + unreachable!() + }; + assert!(id.counter >= x.cnt); + (id.counter - x.cnt) as Lamport + x.lamport + 1 + }; + + for id in iter { + let Some(x) = self.get(id) else { + unreachable!() + }; + assert!(id.counter >= x.cnt); + lamport = lamport.max((id.counter - x.cnt) as Lamport + x.lamport + 1); + } + + lamport + } + + pub fn get_frontiers(&self) -> &Frontiers { + &self.frontiers + } + + /// - Ordering::Less means self is less than target or parallel + /// - Ordering::Equal means versions equal + /// - Ordering::Greater means self's version is greater than target + pub fn cmp_with_frontiers(&self, other: &Frontiers) -> Ordering { + if &self.frontiers == other { + Ordering::Equal + } else if other.iter().all(|id| self.vv.includes_id(id)) { + Ordering::Greater + } else { + Ordering::Less + } + } + + // PERF + /// Compare two [Frontiers] causally. + /// + /// If one of the [Frontiers] are not included, it will return [FrontiersNotIncluded]. + pub fn cmp_frontiers( + &self, + a: &Frontiers, + b: &Frontiers, + ) -> Result<Option<Ordering>, FrontiersNotIncluded> { + let a = self + .try_frontiers_to_vv(a) + .map_err(FrontiersNotIncluded::unreadable)? + .ok_or(FrontiersNotIncluded)?; + let b = self + .try_frontiers_to_vv(b) + .map_err(FrontiersNotIncluded::unreadable)? + .ok_or(FrontiersNotIncluded)?; + Ok(a.partial_cmp(&b)) + } +} + +/// Frontiers were not found, or comparing them had to read history that cannot +/// be parsed. +/// +/// Construct an absent-frontiers error with the [`FrontiersNotIncluded`] +/// constant. That construction still compiles, but an exhaustive `match` of +/// `Err(FrontiersNotIncluded)` does not (`E0004`): the struct has a private +/// field, so a `history_error: Some(_)` pattern cannot be written from another +/// crate (`E0451`). Downstream code must use `Err(_)`. An unreadable-history +/// error is not equal to the [`FrontiersNotIncluded`] constant. +#[derive(Debug, PartialEq, Eq)] +pub struct FrontiersNotIncluded { + history_error: Option<Box<str>>, +} + +/// Absent frontiers. Not equal to an error produced from unreadable history. +/// +/// See [`FrontiersNotIncluded`] for why an exhaustive match of this value does +/// not compile. +#[allow(non_upper_case_globals)] +pub const FrontiersNotIncluded: FrontiersNotIncluded = FrontiersNotIncluded { + history_error: None, +}; + +impl FrontiersNotIncluded { + pub(crate) fn unreadable(error: LoroError) -> Self { + Self { + history_error: Some(error.to_string().into_boxed_str()), + } + } +} + +impl Display for FrontiersNotIncluded { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str( + self.history_error + .as_deref() + .unwrap_or("The given Frontiers are not included by the doc"), + ) + } +} + +#[cfg(test)] +mod ensure_vv_for_tests { + use super::*; + use crate::arena::SharedArena; + use std::sync::atomic::AtomicI64; + + fn make_dag_node(peer: PeerID, cnt: Counter, len: usize, deps: Frontiers) -> AppDagNode { + AppDagNodeInner { + vv: OnceCell::new(), + peer, + cnt, + lamport: cnt as Lamport, + deps, + has_succ: false, + len, + } + .into() + } + + fn make_shallow_dag_for_import_deps() -> AppDag { + let change_store = ChangeStore::new_mem(&SharedArena::new(), Arc::new(AtomicI64::new(0))); + let mut dag = AppDag::new(change_store); + let root_deps = Frontiers::from_id(ID::new(1, 1)); + let boundary = make_dag_node(1, 2, 1, root_deps.clone()); + + { + let mut map = dag.map.lock(); + map.insert(boundary.id_start(), boundary); + } + + dag.shallow_since_vv.insert(1, 2); + dag.shallow_since_frontiers = Frontiers::from_id(ID::new(1, 2)); + dag.shallow_root_frontiers_deps = root_deps; + dag + } + + #[test] + #[should_panic(expected = "unparsed vv don't match with change store")] + fn a_missing_node_without_a_parse_failure_remains_an_internal_invariant() { + let store = ChangeStore::new_mem(&SharedArena::new(), Arc::new(AtomicI64::new(0))); + let dag = AppDag::new(store); + dag.unparsed_vv.lock().insert(1, 1); + let _ = dag.try_get(ID::new(1, 0)); + } + + /// Regression for loro-dev/loro#929: when computing the vv for a node + /// whose DAG fan-in contains a shared ancestor reached through multiple + /// paths, the iterative DFS used to push the shared ancestor onto the + /// stack twice. The second visit would then call `OnceCell::set(..) + /// .unwrap()` on an already-initialized cell and panic with + /// "called `Result::unwrap()` on an `Err` value: ImVersionVector(..)". + /// + /// Topology: + /// x (peer 1, counter 0) + /// | + /// y (peer 2, counter 0, deps = [x]) + /// | + /// z (peer 3, counter 0, deps = [x, y]) + /// + /// When we call `ensure_vv_for(z)`, z pushes x and y. Processing y then + /// re-pushes x (still uninitialized), so the stack ends up with two + /// copies of x; the second pop must be a no-op after the fix. + #[test] + fn diamond_dep_ensure_vv_for_does_not_double_set() { + let change_store = ChangeStore::new_mem(&SharedArena::new(), Arc::new(AtomicI64::new(0))); + let dag = AppDag::new(change_store); + + let x = make_dag_node(1, 0, 1, Frontiers::default()); + let y = make_dag_node(2, 0, 1, Frontiers::from_id(ID::new(1, 0))); + let mut z_deps = Frontiers::default(); + z_deps.push(ID::new(1, 0)); + z_deps.push(ID::new(2, 0)); + let z = make_dag_node(3, 0, 1, z_deps); + + { + let mut map = dag.map.lock(); + map.insert(x.id_start(), x); + map.insert(y.id_start(), y); + map.insert(z.id_start(), z.clone()); + } + + // Historically this panicked at the inner `vv.set(...).unwrap()`. + // `ensure_vv_for` returns the vv *at* the node: it covers every + // peer in the causal past, but not the node's own peer counter. + let vv = dag.ensure_vv_for(&z); + assert_eq!(vv.get(&1).copied(), Some(1)); + assert_eq!(vv.get(&2).copied(), Some(1)); + assert!(vv.get(&3).is_none()); + } + + #[test] + fn import_deps_before_shallow_root_rejects_trimmed_history_dep() { + let dag = make_shallow_dag_for_import_deps(); + let deps = Frontiers::from_id(ID::new(1, 0)); + + assert!(dag.frontiers_to_vv(&deps).is_none()); + assert!(dag.import_deps_before_shallow_root(&deps)); + } + + /// Deps exactly equal to the root's own deps describe a change concurrent + /// with the root frontier op. The boundary shortcut in `frontiers_to_vv` + /// resolves them to the shallow vv, but the dep ids are trimmed from the + /// dag, so the change could never get a lamport — reject it. + #[test] + fn import_deps_before_shallow_root_rejects_deps_equal_to_root_deps() { + let dag = make_shallow_dag_for_import_deps(); + let deps = Frontiers::from_id(ID::new(1, 1)); + + // The boundary shortcut resolves these deps to the shallow vv... + assert!(dag.frontiers_to_vv(&deps).is_some()); + // ...but the import check must still reject them. + assert!(dag.import_deps_before_shallow_root(&deps)); + } + + #[test] + fn import_deps_before_shallow_root_allows_boundary_with_missing_peer() { + let dag = make_shallow_dag_for_import_deps(); + let mut deps = Frontiers::default(); + deps.push(ID::new(1, 2)); + deps.push(ID::new(2, 0)); + + assert!(dag.frontiers_to_vv(&deps).is_none()); + assert!(!dag.import_deps_before_shallow_root(&deps)); + } + + #[test] + fn import_deps_before_shallow_root_allows_missing_non_trimmed_dep() { + let dag = make_shallow_dag_for_import_deps(); + let deps = Frontiers::from_id(ID::new(2, 0)); + + assert!(dag.frontiers_to_vv(&deps).is_none()); + assert!(!dag.import_deps_before_shallow_root(&deps)); + } +} diff --git a/vendor/loro-internal/src/oplog/pending_changes.rs b/vendor/loro-internal/src/oplog/pending_changes.rs new file mode 100644 index 0000000..2aff8c9 --- /dev/null +++ b/vendor/loro-internal/src/oplog/pending_changes.rs @@ -0,0 +1,942 @@ +use std::{ + collections::{hash_map::Entry, BTreeMap}, + ops::Deref, +}; + +use crate::{ + change::Change, + version::{ImVersionVector, VersionRange}, + OpLog, VersionVector, +}; +use loro_common::{ + Counter, CounterSpan, HasCounterSpan, HasIdSpan, IdSpan, LoroEncodeError, PeerID, ID, +}; +use rle::{HasLength, Sliceable}; +use rustc_hash::FxHashMap; + +#[derive(Debug, Clone)] +pub enum PendingChange { + // Retains the input's supplied Lamport, which cannot yet be resolved against + // the DAG. Resolve it when the change can be applied. + Unknown(Change), + // TODO: Refactor, remove this? + #[allow(unused)] + Known(Change), +} + +impl Deref for PendingChange { + type Target = Change; + fn deref(&self) -> &Self::Target { + match self { + Self::Unknown(a) => a, + Self::Known(a) => a, + } + } +} + +#[derive(Debug, Default)] +pub(crate) struct PendingChanges { + changes: FxHashMap<PeerID, BTreeMap<Counter, Vec<PendingChange>>>, +} + +impl PendingChanges { + /// Copy only the pending portions, excluding applied and duplicate operations. + /// Slots are indexed by the missing dependency, not by the pending change's ID. + pub(crate) fn export_changes( + &self, + vv: &VersionVector, + ) -> Result<Vec<Change>, LoroEncodeError> { + let mut pending: Vec<&Change> = self + .changes + .values() + .flat_map(|tree| tree.values()) + .flatten() + .map(|change| &**change) + .collect(); + pending.sort_by_key(|change| { + ( + change.id.peer, + change.id.counter, + std::cmp::Reverse(change.ctr_end()), + ) + }); + + let mut covered = vv.clone(); + let mut changes = Vec::new(); + for change in pending { + let start = change + .id + .counter + .max(covered.get(&change.id.peer).copied().unwrap_or(0)); + if start >= change.ctr_end() { + continue; + } + + // Unknown means the input's Lamport has not been verified against the + // DAG yet. Preserve it; ordinary import resolves it once deps arrive. + // JSON input can supply a value that cannot fit in a binary block. + if change + .lamport + .checked_add(change.atom_len() as u32) + .is_none() + { + return Err(LoroEncodeError::InternalError( + "pending change's supplied Lamport range cannot be encoded".into(), + )); + } + let offset = (start - change.id.counter) as usize; + let mut tail = change.slice(offset, change.atom_len()); + if offset > 0 { + // Change::slice normally keeps only the own-peer predecessor. + // Pending input may still need explicit cross-peer dependencies. + for dep in change.deps.iter().filter(|dep| dep.peer != change.id.peer) { + tail.deps.push(dep); + } + } + covered.set_end(ID::new(tail.id.peer, tail.ctr_end())); + changes.push(tail); + } + Ok(changes) + } + + pub(crate) fn has_import_rollback_ops(&self, detached: bool) -> bool { + self.changes.values().any(|tree| { + tree.values().any(|changes| { + changes.iter().any(|change| { + change + .ops + .iter() + .any(|op| super::import_op_can_reject(op, detached)) + }) + }) + }) + } + + pub(crate) fn is_empty(&self) -> bool { + self.changes.is_empty() + } + + /// Number of changes parked under `[peer][counter]`, or `None` if nothing is. + fn slot_len(&self, peer: PeerID, counter: Counter) -> Option<usize> { + Some(self.changes.get(&peer)?.get(&counter)?.len()) + } + + pub(crate) fn version_range(&self) -> VersionRange { + let mut range = VersionRange::default(); + for tree in self.changes.values() { + for pending_changes in tree.values() { + for pending_change in pending_changes { + range.extends_to_include_id_span(pending_change.id_span()); + } + } + } + + range + } +} + +#[cfg(test)] +#[allow(dead_code)] +impl PendingChanges { + pub(crate) fn len(&self) -> usize { + self.changes + .values() + .map(|tree| tree.values().map(Vec::len).sum::<usize>()) + .sum() + } +} + +/// What every `PendingChanges` slot this import-rollback scope touched held when the +/// scope began, recorded on first touch and restored wholesale on rollback. +/// +/// Snapshot-per-slot rather than a mutation log, for two reasons. +/// +/// Correctness: one scope can park a change and later unlock it — `import_batch` +/// opens a single scope across the whole batch, where later blobs routinely unlock +/// what earlier blobs parked. Undoing individual mutations then depends on getting +/// their relative order right, while restoring each slot to its pre-scope content is +/// order-independent by construction. +/// +/// Size: a slot created inside the scope only needs [`PendingSlot::Absent`], and a +/// slot merely appended to only needs its original length. Cloning is limited to +/// content that predates the scope, which is exactly what rollback cannot otherwise +/// reconstruct — an out-of-order batch parks everything it later unlocks, so it +/// clones nothing. +#[derive(Debug, Default)] +pub(crate) struct PendingChangesRollback { + slots: FxHashMap<(PeerID, Counter), PendingSlot>, +} + +#[derive(Debug)] +enum PendingSlot { + /// The slot did not exist when the scope began; rollback drops it. + Absent, + /// The slot held this many changes when the scope began and has only been + /// appended to since; rollback truncates it back. + Truncate(usize), + /// What the slot held when the scope began, kept because the slot was removed + /// wholesale and cannot be recovered from the live map. + Restore(Vec<PendingChange>), +} + +impl PendingChangesRollback { + /// Record the slot before a change is pushed onto `[id.peer][id.counter]`. + /// `pre_len` is the slot's current length, or `None` if it does not exist yet. + fn record_added(&mut self, id: ID, pre_len: Option<usize>) { + self.slots + .entry((id.peer, id.counter)) + .or_insert(match pre_len { + Some(len) => PendingSlot::Truncate(len), + None => PendingSlot::Absent, + }); + } + + /// Record the slot while `[peer][counter]` is removed wholesale. + fn record_removed(&mut self, peer: PeerID, counter: Counter, removed: &[PendingChange]) { + match self.slots.entry((peer, counter)) { + Entry::Vacant(e) => { + e.insert(PendingSlot::Restore(removed.to_vec())); + } + Entry::Occupied(mut e) => { + // `Absent` stays absent (nothing here predates the scope) and + // `Restore` already holds the pre-scope content. Only `Truncate` + // has to materialize, and just the prefix it was pointing at: + // everything past it was pushed inside the scope, so rollback + // drops it either way. + if let PendingSlot::Truncate(pre_len) = *e.get() { + debug_assert!(pre_len <= removed.len(), "slot shrank inside the scope"); + e.insert(PendingSlot::Restore(removed[..pre_len].to_vec())); + } + } + } + } + + pub(crate) fn rollback(self, pending_changes: &mut PendingChanges) { + for ((peer, counter), slot) in self.slots { + match slot { + PendingSlot::Absent => { + if let Some(tree) = pending_changes.changes.get_mut(&peer) { + tree.remove(&counter); + } + } + PendingSlot::Truncate(pre_len) => { + // The slot was never removed (that would have upgraded it to + // `Restore`), so it is still here with `pre_len` or more entries. + if let Some(changes) = pending_changes + .changes + .get_mut(&peer) + .and_then(|tree| tree.get_mut(&counter)) + { + changes.truncate(pre_len); + } + } + PendingSlot::Restore(changes) => { + debug_assert!(!changes.is_empty(), "empty slots are never stored"); + pending_changes + .changes + .entry(peer) + .or_default() + .insert(counter, changes); + } + } + } + + pending_changes.changes.retain(|_, tree| !tree.is_empty()); + } +} + +impl OpLog { + fn push_pending_change(&mut self, missing_dep: ID, change: PendingChange) { + let Self { + pending_changes, + import_rollback, + .. + } = self; + if let Some(rollback) = import_rollback.as_mut() { + let pre_len = pending_changes.slot_len(missing_dep.peer, missing_dep.counter); + rollback.pending.record_added(missing_dep, pre_len); + } + + pending_changes + .changes + .entry(missing_dep.peer) + .or_default() + .entry(missing_dep.counter) + .or_default() + .push(change); + } + + /// Store or apply changes that could not get a lamport during the main import pass. + /// + /// These changes were deferred because some deps were missing from the DAG when + /// first seen. By the time this runs, `try_apply_pending` may already have unlocked + /// those deps (e.g. applying peer B unlocked previously pending peer A ops that a + /// later B change depended on). Treat that as normal: apply when possible, skip if + /// already present, and only park changes that are still waiting on a missing dep. + /// + /// Returns the version range of changes from `remote_changes` that remain pending. + pub(super) fn extend_pending_changes_with_unknown_lamport( + &mut self, + remote_changes: Vec<Change>, + mut would_affect: Option<&mut VersionRange>, + ) -> VersionRange { + let mut parked = Vec::new(); + let mut newly_applied_ids = Vec::new(); + + for change in remote_changes { + let local_change = PendingChange::Unknown(change); + match remote_change_apply_state(self.vv(), self.shallow_since_vv(), &local_change) { + ChangeState::AwaitingMissingDependency(miss_dep) => { + parked.push(local_change.id_span()); + self.push_pending_change(miss_dep, local_change); + } + ChangeState::Applied => {} + ChangeState::CanApplyDirectly => { + newly_applied_ids.push(local_change.id_last()); + self.apply_change_from_remote(local_change, would_affect.as_deref_mut()); + } + } + } + + if !newly_applied_ids.is_empty() { + self.try_apply_pending(newly_applied_ids, would_affect); + } + + // A parked change can already be partially covered by the oplog VV: a change whose + // span straddles the VV head is not `Applied`, and it still gets parked when one of + // its cross-peer deps is missing. Only the uncovered tail of such a span is pending. + // + // Trim each span on its own rather than merging first. `VersionRange` keeps a single + // (start, end) per peer, so trimming a merged range would attribute the gap between + // two disjoint parked spans to the covered one. That is defensive here — the input + // is lamport-ordered, so a parked change is unlikely to be unblocked by the + // `try_apply_pending` above — but it keeps the reported range honest regardless. + let mut still_pending = VersionRange::default(); + for span in parked { + let vv_end = self.vv().get(&span.peer).copied().unwrap_or(0); + if vv_end < span.ctr_end() { + let start = span.counter.start.max(vv_end); + still_pending.extends_to_include_id_span(IdSpan::new( + span.peer, + start, + span.ctr_end(), + )); + } + } + + still_pending + } +} + +impl OpLog { + /// Try to apply pending changes. + /// + /// `new_ids` are the ID of the op that is just applied. + pub(crate) fn try_apply_pending( + &mut self, + mut new_ids: Vec<ID>, + mut would_affect: Option<&mut VersionRange>, + ) { + while let Some(id) = new_ids.pop() { + let Some(tree) = self.pending_changes.changes.get_mut(&id.peer) else { + continue; + }; + + let mut to_remove = Vec::new(); + for (cnt, _) in tree.range_mut(0..=id.counter) { + to_remove.push(*cnt); + } + + let mut pending_set = Vec::with_capacity(to_remove.len()); + for cnt in to_remove { + let pending_changes = tree.remove(&cnt).unwrap(); + if let Some(rollback) = self.import_rollback.as_mut() { + rollback + .pending + .record_removed(id.peer, cnt, &pending_changes); + } + pending_set.push(pending_changes); + } + + if tree.is_empty() { + self.pending_changes.changes.remove(&id.peer); + } + + for pending_changes in pending_set { + for pending_change in pending_changes { + match remote_change_apply_state( + self.dag.vv(), + self.dag.shallow_since_vv(), + &pending_change, + ) { + ChangeState::CanApplyDirectly => { + new_ids.push(pending_change.id_last()); + self.apply_change_from_remote( + pending_change, + would_affect.as_deref_mut(), + ); + } + ChangeState::Applied => {} + ChangeState::AwaitingMissingDependency(miss_dep) => { + self.push_pending_change(miss_dep, pending_change) + } + } + } + } + } + } + + pub(super) fn apply_change_from_remote( + &mut self, + change: PendingChange, + would_affect: Option<&mut VersionRange>, + ) { + let change = match change { + PendingChange::Known(mut c) => { + self.dag.calc_unknown_lamport_change(&mut c).unwrap(); + c + } + PendingChange::Unknown(mut c) => { + self.dag.calc_unknown_lamport_change(&mut c).unwrap(); + c + } + }; + + let Some(change) = self.trim_the_known_part_of_change(change) else { + return; + }; + + if let Some(w) = would_affect { + w.extends_to_include_id_span(change.id_span()); + } + self.insert_new_change(change, false); + } +} + +enum ChangeState { + Applied, + CanApplyDirectly, + // The id of first missing dep + AwaitingMissingDependency(ID), +} + +fn remote_change_apply_state( + vv: &VersionVector, + _shallow_vv: &ImVersionVector, + change: &Change, +) -> ChangeState { + let peer = change.id.peer; + let CounterSpan { start, end } = change.ctr_span(); + let vv_latest_ctr = vv.get(&peer).copied().unwrap_or(0); + if vv_latest_ctr >= end { + return ChangeState::Applied; + } + + if vv_latest_ctr < start { + return ChangeState::AwaitingMissingDependency(change.id.inc(-1)); + } + + for dep in change.deps.iter() { + let dep_vv_latest_ctr = vv.get(&dep.peer).copied().unwrap_or(0); + if dep_vv_latest_ctr - 1 < dep.counter { + return ChangeState::AwaitingMissingDependency(dep); + } + } + + ChangeState::CanApplyDirectly +} + +#[cfg(test)] +mod test { + use crate::handler::HandlerTrait; + use crate::{cursor::PosType, loro::ExportMode, LoroDoc, ToJson, VersionVector}; + + #[test] + fn pending_export_deduplicates_overlapping_slots_in_every_import_order() { + use loro_common::{HasCounterSpan, IdSpan}; + + let source = LoroDoc::new_auto_commit(); + source.set_peer_id(1).unwrap(); + source + .get_text("text") + .insert(0, "ABCDEFG", PosType::Unicode) + .unwrap(); + let _ = source.export(ExportMode::all_updates()).unwrap(); + assert_eq!(source.oplog().lock().len_changes(), 1); + let range = |start, end| { + source + .export(ExportMode::updates_in_range(vec![IdSpan::new( + 1, start, end, + )])) + .unwrap() + }; + let inputs = [range(1, 4), range(2, 5), range(6, 7)]; + let a = range(0, 1); + let f = range(5, 6); + + for order in [ + [0, 1, 2], + [0, 2, 1], + [1, 0, 2], + [1, 2, 0], + [2, 0, 1], + [2, 1, 0], + ] { + let doc = LoroDoc::new_auto_commit(); + for _ in 0..3 { + for index in order { + let status = doc.import(&inputs[index]).unwrap(); + assert!(status.success.is_empty()); + assert!(status.pending.is_some()); + } + } + // Real repeated imports leave several copies under each missing-dep + // slot. Export must deduplicate across all of those slot vectors. + let pending_len = doc.oplog().lock().pending_changes_len(); + assert_eq!(pending_len, 9); + let vv = doc.oplog_vv(); + let frontiers = doc.oplog_frontiers(); + let pending = doc.export_pending_updates().unwrap().unwrap(); + assert!(doc.export_pending_updates().unwrap().is_some()); + assert_eq!(doc.oplog().lock().pending_changes_len(), pending_len); + assert_eq!(doc.oplog_vv(), vv); + assert_eq!(doc.oplog_frontiers(), frontiers); + assert!(doc.get_text("text").to_string().is_empty()); + + let inspector = LoroDoc::new_auto_commit(); + let parsed = crate::encoding::parse_header_and_body(&pending, true).unwrap(); + let decoded = crate::encoding::fast_snapshot::decode_updates( + &mut inspector.oplog().lock(), + bytes::Bytes::copy_from_slice(parsed.body), + ) + .unwrap(); + let spans: Vec<_> = decoded + .iter() + .map(|change| (change.id.counter, change.ctr_end())) + .collect(); + assert_eq!(spans, [(1, 4), (4, 5), (6, 7)], "{order:?}"); + let counters: Vec<_> = decoded + .iter() + .flat_map(|change| change.id.counter..change.ctr_end()) + .collect(); + assert_eq!(counters, [1, 2, 3, 4, 6], "{order:?}"); + // Check actual FastUpdates framing, not just a merged range summary: + // each disjoint/trimmed change has its own current-format block. + let mut body = parsed.body; + let mut block_count = 0; + while !body.is_empty() { + let len = leb128::read::unsigned(&mut body).unwrap() as usize; + body = &body[len..]; + block_count += 1; + } + assert_eq!(block_count, 3); + + let restored = LoroDoc::new_auto_commit(); + restored + .import(&doc.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + let status = restored.import(&pending).unwrap(); + assert!(status.success.is_empty()); + assert!(status.pending.is_some()); + for target in [&doc, &restored] { + target.import(&a).unwrap(); + assert_eq!(target.get_text("text").to_string(), "ABCDE"); + assert_eq!(target.oplog_vv().get(&1), Some(&5)); + assert!(target.export_pending_updates().unwrap().is_some()); + target.import(&f).unwrap(); + assert_eq!(target.get_text("text").to_string(), "ABCDEFG"); + assert!(target.export_pending_updates().unwrap().is_none()); + } + } + } + + #[test] + fn pending_export_does_not_bypass_conflicting_history_rejection() { + use loro_common::{IdSpan, LoroError, ID}; + + let source = LoroDoc::new_auto_commit(); + source.set_peer_id(1).unwrap(); + for key in ["a", "b", "c"] { + source.get_map("map").insert(key, true).unwrap(); + } + let prefix = source + .export(ExportMode::updates_in_range(vec![IdSpan::new(1, 0, 1)])) + .unwrap(); + let mut json = source + .export_json_updates(&VersionVector::default(), &source.oplog_vv(), false) + .unwrap(); + assert_eq!(json.changes.len(), 1); + // This rewrites the dependency of an already applied operation. Current + // import validation rejects the conflicting prefix instead of parking + // the tail as if it were a valid out-of-order change. + json.changes[0].deps = vec![ID::new(2, 0)]; + json.changes[0].lamport = 0; + let doc = LoroDoc::new_auto_commit(); + doc.import(&prefix).unwrap(); + let before = doc.oplog_vv(); + let state = doc.get_deep_value(); + let err = doc.import_json_updates(json).unwrap_err(); + assert!(matches!(err, LoroError::UsedOpID { id } if id == ID::new(1, 0))); + assert_eq!(doc.oplog_vv(), before); + assert_eq!(doc.get_deep_value(), state); + assert!(doc.export_pending_updates().unwrap().is_none()); + // The rejected data did not poison the document or leave a sidecar; + // valid history with the same operation IDs still imports normally. + doc.import(&source.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + assert_eq!(doc.get_deep_value(), source.get_deep_value()); + assert!(doc.export_pending_updates().unwrap().is_none()); + } + + #[test] + fn pending_export_preserves_unresolved_input_lamport() { + let source = LoroDoc::new_auto_commit(); + source.set_peer_id(1).unwrap(); + source.get_map("map").insert("a", true).unwrap(); + let a = source.export(ExportMode::all_updates()).unwrap(); + let before_b = source.oplog_vv(); + source.get_map("map").insert("b", true).unwrap(); + let _ = source.export(ExportMode::all_updates()).unwrap(); + let mut json = source + .export_json_updates(&before_b, &source.oplog_vv(), false) + .unwrap(); + json.changes[0].lamport = 0; + let doc = LoroDoc::new_auto_commit(); + assert!(doc.import_json_updates(json).unwrap().pending.is_some()); + let bytes = doc.export_pending_updates().unwrap().unwrap(); + let restored = LoroDoc::new_auto_commit(); + restored + .import(&doc.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + assert!(restored.import(&bytes).unwrap().pending.is_some()); + doc.import(&a).unwrap(); + restored.import(&a).unwrap(); + assert!(restored.export_pending_updates().unwrap().is_none()); + assert_eq!(restored.get_deep_value(), source.get_deep_value()); + assert_eq!(restored.get_deep_value(), doc.get_deep_value()); + assert_eq!(restored.oplog_vv(), doc.oplog_vv()); + } + + #[test] + fn pending_export_returns_error_for_unrepresentable_input_lamport() { + use loro_common::IdSpan; + + let source = LoroDoc::new_auto_commit(); + source.set_peer_id(1).unwrap(); + source.get_map("map").insert("a", true).unwrap(); + let a = source.export(ExportMode::all_updates()).unwrap(); + let before_b = source.oplog_vv(); + source.get_map("map").insert("b", true).unwrap(); + let _ = source.export(ExportMode::all_updates()).unwrap(); + let mut json = source + .export_json_updates(&before_b, &source.oplog_vv(), false) + .unwrap(); + json.changes[0].lamport = u32::MAX; + let doc = LoroDoc::new_auto_commit(); + assert!(doc.import_json_updates(json).unwrap().pending.is_some()); + let before = doc.oplog_vv(); + assert!(doc.export_pending_updates().is_err()); + assert_eq!(doc.oplog_vv(), before); + // A failed export leaves the exact pending input in place. + assert_eq!( + doc.oplog().lock().pending_changes.version_range().get(&1), + Some(&(1, 2)) + ); + // Do not apply this deliberately unrepresentable input; a fresh valid + // import remains usable and does not inherit any exporter changes. + let clean = LoroDoc::new_auto_commit(); + clean.import(&a).unwrap(); + clean + .import( + &source + .export(ExportMode::updates_in_range(vec![IdSpan::new(1, 1, 2)])) + .unwrap(), + ) + .unwrap(); + assert_eq!(clean.get_deep_value(), source.get_deep_value()); + } + + #[test] + fn import_pending() { + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(2).unwrap(); + let text_a = a.get_text("text"); + text_a.insert(0, "a", PosType::Unicode).unwrap(); + let update1 = a + .export(ExportMode::updates(&VersionVector::default())) + .unwrap(); + let version1 = a.oplog_vv(); + text_a.insert(0, "b", PosType::Unicode).unwrap(); + let update2 = a.export(ExportMode::updates(&version1)).unwrap(); + let version2 = a.oplog_vv(); + text_a.insert(0, "c", PosType::Unicode).unwrap(); + let update3 = a.export(ExportMode::updates(&version2)).unwrap(); + let version3 = a.oplog_vv(); + text_a.insert(0, "d", PosType::Unicode).unwrap(); + let update4 = a.export(ExportMode::updates(&version3)).unwrap(); + // let version4 = a.oplog_vv(); + text_a.insert(0, "e", PosType::Unicode).unwrap(); + let update3_5 = a.export(ExportMode::updates(&version2)).unwrap(); + b.import(&update3_5).unwrap(); + b.import(&update4).unwrap(); + b.import(&update2).unwrap(); + b.import(&update3).unwrap(); + b.import(&update1).unwrap(); + assert_eq!(a.get_deep_value(), b.get_deep_value()); + } + + #[test] + fn pending_import_snapshot() { + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(2).unwrap(); + let text_a = a.get_text("text"); + text_a.insert(0, "a", PosType::Unicode).unwrap(); + let update1 = a.export(ExportMode::Snapshot).unwrap(); + let version1 = a.oplog_vv(); + text_a.insert(0, "b", PosType::Unicode).unwrap(); + let update2 = a.export(ExportMode::updates(&version1)).unwrap(); + let _version2 = a.oplog_vv(); + b.import(&update2).unwrap(); + // snapshot will be converted to updates + b.import(&update1).unwrap(); + assert_eq!(a.get_deep_value(), b.get_deep_value()); + } + + /// A doc holding only pending changes is not empty: a snapshot import must + /// not replace its op log and drop them. Map ops leave the arena untouched, + /// which the emptiness check used to rely on. + #[test] + fn pending_map_change_survives_snapshot_import() { + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + let map = a.get_map("m"); + map.insert("x", 1).unwrap(); + let snapshot = a.export(ExportMode::Snapshot).unwrap(); + let version1 = a.oplog_vv(); + map.insert("y", 2).unwrap(); + let update = a.export(ExportMode::updates(&version1)).unwrap(); + + let b = LoroDoc::new_auto_commit(); + assert!(b.import(&update).unwrap().pending.is_some()); + let status = b.import(&snapshot).unwrap(); + assert!(status.pending.is_none()); + assert_eq!(a.get_deep_value(), b.get_deep_value()); + assert_eq!(a.oplog_vv(), b.oplog_vv()); + } + + #[test] + fn need_deps_pending_import() { + // a: a1 <--- a2 + // \ / + // b: b1 + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(2).unwrap(); + let c = LoroDoc::new_auto_commit(); + c.set_peer_id(3).unwrap(); + let d = LoroDoc::new_auto_commit(); + d.set_peer_id(4).unwrap(); + let text_a = a.get_text("text"); + let text_b = b.get_text("text"); + text_a.insert(0, "a", PosType::Unicode).unwrap(); + let version_a1 = a.oplog_vv(); + let update_a1 = a + .export(ExportMode::updates(&VersionVector::default())) + .unwrap(); + b.import(&update_a1).unwrap(); + text_b.insert(1, "b", PosType::Unicode).unwrap(); + let update_b1 = b.export(ExportMode::updates(&version_a1)).unwrap(); + a.import(&update_b1).unwrap(); + let version_a1b1 = a.oplog_vv(); + text_a.insert(2, "c", PosType::Unicode).unwrap(); + let update_a2 = a.export(ExportMode::updates(&version_a1b1)).unwrap(); + c.import(&update_a2).unwrap(); + assert_eq!(c.get_deep_value().to_json(), "{\"text\":\"\"}"); + c.import(&update_a1).unwrap(); + assert_eq!(c.get_deep_value().to_json(), "{\"text\":\"a\"}"); + c.import(&update_b1).unwrap(); + assert_eq!(a.get_deep_value(), c.get_deep_value()); + + d.import(&update_a2).unwrap(); + assert_eq!(d.get_deep_value().to_json(), "{\"text\":\"\"}"); + d.import(&update_b1).unwrap(); + assert_eq!(d.get_deep_value().to_json(), "{\"text\":\"\"}"); + d.import(&update_a1).unwrap(); + assert_eq!(a.get_deep_value(), d.get_deep_value()); + } + + #[test] + fn should_activate_pending_change_when() { + // 0@a <- 0@b + // 0@a <- 1@a, where 0@a and 1@a will be merged + // In this case, c apply b's change first, then apply all the changes from a. + // C is expected to have the same content as a, after a imported b's change + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(2).unwrap(); + let c = LoroDoc::new_auto_commit(); + c.set_peer_id(3).unwrap(); + let text_a = a.get_text("text"); + let text_b = b.get_text("text"); + text_a.insert(0, "1", PosType::Unicode).unwrap(); + b.import(&a.export(ExportMode::Snapshot).unwrap()).unwrap(); + text_b.insert(0, "1", PosType::Unicode).unwrap(); + let b_change = b.export(ExportMode::updates(&a.oplog_vv())).unwrap(); + text_a.insert(0, "1", PosType::Unicode).unwrap(); + c.import(&b_change).unwrap(); + c.import(&a.export(ExportMode::Snapshot).unwrap()).unwrap(); + a.import(&b_change).unwrap(); + assert_eq!(c.get_deep_value(), a.get_deep_value()); + } + + /// Regression: importing a blob can both apply ops that unlock previously pending + /// changes *and* contain later ops that depended on those pending changes. + /// + /// Sequence: + /// 1. D has A0. + /// 2. Import A1 (deps B0) → A1 parked as pending. + /// 3. Import a single blob with B0 (deps A0) + B1 (deps A1): + /// - B0 applies; B1 is deferred (A1 not yet in the DAG). + /// - `try_apply_pending` then applies A1 (unlocked by B0). + /// - B1 must now apply instead of hitting `unreachable!("can apply directly")`. + #[test] + fn pending_change_becomes_applicable_after_try_apply_pending() { + let (u_a0, u_a1_only, u_b0_b1, expected) = concurrent_pending_unlock_fixture(); + + let d = LoroDoc::new_auto_commit(); + d.set_peer_id(3).unwrap(); + d.import(&u_a0).unwrap(); + let status_a1 = d.import(&u_a1_only).unwrap(); + assert!( + status_a1.pending.is_some(), + "A1 should be pending without B0: {status_a1:?}" + ); + assert!(status_a1.success.is_empty(), "{status_a1:?}"); + + // This used to panic with unreachable!("can apply directly"). + let status_b = d.import(&u_b0_b1).unwrap(); + assert!(status_b.pending.is_none(), "{status_b:?}"); + assert_eq!(d.get_deep_value(), expected.get_deep_value()); + assert_eq!(d.oplog_vv(), expected.oplog_vv()); + } + + /// Same causal pattern via `import_batch` (path that hit WASM `unreachable` + /// with the lody snapshot+updates fixture). + #[test] + fn import_batch_applies_pending_unlocked_within_blob() { + let (u_a0, u_a1_only, u_b0_b1, expected) = concurrent_pending_unlock_fixture(); + + let d = LoroDoc::new_auto_commit(); + d.set_peer_id(3).unwrap(); + d.import(&u_a0).unwrap(); + d.import(&u_a1_only).unwrap(); + d.import_batch(std::slice::from_ref(&u_b0_b1)).unwrap(); + // `import_batch` force-detaches for the duration of the batch and reattaches + // after the loop; a panic inside used to unwind past the reattach and strand + // the doc detached, failing every later import and export. + assert!(!d.is_detached(), "import_batch must leave the doc attached"); + assert_eq!(d.get_deep_value(), expected.get_deep_value()); + assert_eq!(d.oplog_vv(), expected.oplog_vv()); + } + + /// Multi-blob `import_batch` (like lody drain): a large peer-A blob that + /// leaves pending ops, then a peer-B blob that both unlocks them and depends + /// on the previously pending range. + #[test] + fn import_batch_multi_blob_unlocks_and_applies_chained_pending() { + let (u_a0, u_a1_only, u_b0_b1, expected) = concurrent_pending_unlock_fixture(); + + let d = LoroDoc::new_auto_commit(); + d.set_peer_id(3).unwrap(); + d.import(&u_a0).unwrap(); + // Sorted by change_num inside import_batch; either order must work. + d.import_batch(&[u_a1_only, u_b0_b1]).unwrap(); + assert!(!d.is_detached(), "import_batch must leave the doc attached"); + assert_eq!(d.get_deep_value(), expected.get_deep_value()); + assert_eq!(d.oplog_vv(), expected.oplog_vv()); + } + + fn concurrent_pending_unlock_fixture() -> (Vec<u8>, Vec<u8>, Vec<u8>, LoroDoc) { + use loro_common::IdSpan; + + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + let text_a = a.get_text("text"); + text_a.insert(0, "A0", PosType::Unicode).unwrap(); + let u_a0 = a + .export(ExportMode::updates(&VersionVector::default())) + .unwrap(); + let vv_a0 = a.oplog_vv(); + let a_counter_after_a0 = *vv_a0.get(&1).unwrap(); + + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(2).unwrap(); + b.import(&u_a0).unwrap(); + b.get_text("text") + .insert(2, "B0", PosType::Unicode) + .unwrap(); + let u_b0 = b.export(ExportMode::updates(&vv_a0)).unwrap(); + + a.import(&u_b0).unwrap(); + text_a.insert(4, "A1", PosType::Unicode).unwrap(); + let a_counter_after_a1 = *a.oplog_vv().get(&1).unwrap(); + // Peer-A ops only (A1), not B0 — so this stays pending on a doc that only has A0. + let u_a1_only = a + .export(ExportMode::updates_in_range(vec![IdSpan::new( + 1, + a_counter_after_a0, + a_counter_after_a1, + )])) + .unwrap(); + + b.import(&u_a1_only).unwrap(); + b.get_text("text") + .insert(6, "B1", PosType::Unicode) + .unwrap(); + // Single blob containing B0 and B1. B1 depends on A1. + let u_b0_b1 = b.export(ExportMode::updates(&vv_a0)).unwrap(); + + (u_a0, u_a1_only, u_b0_b1, b) + } + + // Change cannot be merged now + // #[test] + // fn pending_changes_may_deps_merged_change() { + // // a: (a1 <-- a2 <-- a3) <-- a4 a1~a3 is a merged change + // // \ / + // // b: b1 + // let a = LoroDoc::new(); + // a.set_peer_id(1); + // let b = LoroDoc::new(); + // b.set_peer_id(2); + // let c = LoroDoc::new(); + // c.set_peer_id(3); + // let text_a = a.get_text("text"); + // let text_b = b.get_text("text"); + // a.with_txn(|txn| text_a.insert(txn, 0, "a")).unwrap(); + // a.with_txn(|txn| text_a.insert(txn, 1, "b")).unwrap(); + // let version_a12 = a.oplog_vv(); + // let updates_a12 = a.export(ExportMode::Snapshot); + // a.with_txn(|txn| text_a.insert(txn, 2, "c")).unwrap(); + // let updates_a123 = a.export(ExportMode::Snapshot); + // b.import(&updates_a12).unwrap(); + // b.with_txn(|txn| text_b.insert(txn, 2, "d")).unwrap(); + // let update_b1 = b.export(ExportMode::updates(&version_a12)).unwrap(); + // a.import(&update_b1).unwrap(); + // let version_a123_b1 = a.oplog_vv(); + // a.with_txn(|txn| text_a.insert(txn, 4, "e")).unwrap(); + // let update_a4 = a.export(ExportMode::updates(&version_a123_b1)).unwrap(); + // c.import(&update_b1).unwrap(); + // assert_eq!(c.get_deep_value().to_json(), "{\"text\":\"\"}"); + // c.import(&update_a4).unwrap(); + // assert_eq!(c.get_deep_value().to_json(), "{\"text\":\"\"}"); + // c.import(&updates_a123).unwrap(); + // assert_eq!(c.get_deep_value(), a.get_deep_value()); + // } +} diff --git a/vendor/loro-internal/src/parent.rs b/vendor/loro-internal/src/parent.rs new file mode 100644 index 0000000..3c3dd45 --- /dev/null +++ b/vendor/loro-internal/src/parent.rs @@ -0,0 +1,151 @@ +//! This file contains the methods to maintain the parent-child relationship in Loro. +//! The child-parent relationship is established when the child container is created. +//! It won't be changed. So the depth of a container is fixed. +//! +//! + +use loro_common::{ContainerID, LoroValue}; +use smallvec::SmallVec; + +use crate::{ + arena::SharedArena, + change::Change, + container::{list::list_op::ListOp, map::MapSet}, + op::{ListSlice, Op, RawOp, RawOpContent}, + DocState, OpLog, +}; + +impl OpLog { + /// Establish the link between the child container and the parent container. + /// This relationship will never be broken. + /// It's used at the entry of creating new ops to ensure all the valid containers + /// in Loro are properly linked. + pub(super) fn register_container_and_parent_link(&self, change: &Change) { + let arena = &self.arena; + register_container_and_parent_link(arena, change); + } +} + +pub(super) fn register_container_and_parent_link(arena: &SharedArena, change: &Change) { + for op in change.ops.iter() { + op.content.visit_created_children(&mut |c| { + let idx = arena.register_container(c); + arena.set_parent(idx, Some(op.container)); + }); + } +} + +/// A transaction registers the parent of every container its ops create when it applies them +/// ([`DocState::set_container_parent_by_raw_op`]), before the change is committed. Until then +/// the op log cannot tell the parent, so a container a local op path forgot to link reads as +/// deleted instead of failing (see `SharedArena::get_parent`). Check it on commit. +#[cfg(debug_assertions)] +pub(super) fn assert_local_parent_links_registered(arena: &SharedArena, change: &Change) { + for op in change.ops.iter() { + op.content.visit_created_children(&mut |c| { + let parent = arena + .id_to_idx(c) + .and_then(|idx| arena.get_registered_parent(idx)); + assert_eq!( + parent, + Some(Some(op.container)), + "InternalError: local op {} created {c} without registering its parent", + loro_common::ID::new(change.id.peer, op.counter) + ); + }); + } +} + +impl DocState { + /// This is used in txn to short cut the process of applying an op to the state. + /// So the op here has not been registered on the oplog yet. + pub(super) fn set_container_parent_by_raw_op(&self, raw_op: &RawOp) { + let container = raw_op.container; + match &raw_op.content { + RawOpContent::List(op) => { + if let ListOp::Insert { + slice: ListSlice::RawData(list), + .. + } = op + { + let list = match list { + std::borrow::Cow::Borrowed(list) => list.iter(), + std::borrow::Cow::Owned(list) => list.iter(), + }; + for value in list { + if let LoroValue::Container(c) = value { + let idx = self.arena.register_container(c); + self.arena.set_parent(idx, Some(container)); + } + } + } + if let ListOp::Set { + elem_id: _, + value: LoroValue::Container(c), + } = op + { + let idx = self.arena.register_container(c); + self.arena.set_parent(idx, Some(container)); + } + } + RawOpContent::Map(MapSet { key: _, value }) => { + if let Some(LoroValue::Container(c)) = value { + let idx = self.arena.register_container(c); + self.arena.set_parent(idx, Some(container)); + } + } + RawOpContent::Tree(tree) => { + let target = tree.target(); + // create associated metadata container + // TODO: maybe we could create map container only when setting metadata + let container_id = target.associated_meta_container(); + let child_idx = self.arena.register_container(&container_id); + self.arena.set_parent(child_idx, Some(container)); + } + #[cfg(feature = "counter")] + RawOpContent::Counter(_) => {} + RawOpContent::Unknown { .. } => {} + } + } + + /// Create store entries for the containers this local op brings alive. + /// + /// Full snapshot export no longer walks the alive-container graph, so "every referenced + /// container has a store entry" must hold by construction: an empty child inserted via + /// `insert_container` would otherwise only exist inside its parent's value and be skipped + /// by `flush`. + /// + /// Mergeable markers are deliberately NOT handled here: an ensured-but-empty mergeable + /// child has no independent existence — the parent map's marker is its single source of + /// truth, and materializing a store entry for it would keep `has_container` true after the + /// marker is removed (see `loro_get_container_for_deleted_mergeable_children`). + pub(super) fn ensure_containers_created_by_op(&mut self, op: &Op) { + let mut to_ensure: SmallVec<[ContainerID; 2]> = SmallVec::new(); + op.content + .visit_created_children(&mut |c| to_ensure.push(c.clone())); + + for id in to_ensure { + self.ensure_container(&id); + } + } +} + +#[cfg(test)] +mod test { + use loro_common::ID; + + use crate::{arena::SharedArena, LoroDoc, TreeParentId}; + + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "without registering its parent")] + fn a_local_op_must_link_the_containers_it_creates() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + doc.get_tree("tree").create(TreeParentId::Root).unwrap(); + doc.commit_then_renew(); + let change = doc.oplog().lock().get_change_at(ID::new(1, 0)).unwrap(); + // An arena that the transaction did not register the node's meta in. + super::assert_local_parent_links_registered(&SharedArena::new(), &change); + } +} diff --git a/vendor/loro-internal/src/pre_commit.rs b/vendor/loro-internal/src/pre_commit.rs new file mode 100644 index 0000000..48c32ec --- /dev/null +++ b/vendor/loro-internal/src/pre_commit.rs @@ -0,0 +1,69 @@ +use std::sync::Arc; + +use crate::sync::Mutex; +use crate::{ + change::{Change, Timestamp}, + oplog::get_timestamp_now_txn, + ChangeMeta, +}; +use loro_common::PeerID; + +/// The callback of the first commit from a peer. +pub type FirstCommitFromPeerCallback = + Box<dyn Fn(&FirstCommitFromPeerPayload) -> bool + Send + Sync + 'static>; +pub type PreCommitCallback = Box<dyn Fn(&PreCommitCallbackPayload) -> bool + Send + Sync + 'static>; + +/// The payload of the pre commit callback. +#[derive(Debug, Clone)] +pub struct PreCommitCallbackPayload { + /// The metadata of the change which will be committed. + pub change_meta: ChangeMeta, + /// The origin of the commit. + pub origin: String, + /// The modifier of the change. You can modify the change in the callback. + pub modifier: ChangeModifier, +} + +/// The payload of the first commit from a peer callback. +#[derive(Debug, Clone)] +pub struct FirstCommitFromPeerPayload { + /// The peer id of the first commit. + pub peer: PeerID, +} + +#[derive(Debug, Clone, Default)] +pub struct ChangeModifier(Arc<Mutex<ChangeModifierInner>>); + +#[derive(Debug, Default)] +struct ChangeModifierInner { + new_msg: Option<Arc<str>>, + new_timestamp: Option<Timestamp>, +} + +impl ChangeModifier { + pub fn set_message(&self, msg: &str) -> &Self { + self.0.lock().new_msg = Some(Arc::from(msg)); + self + } + + pub fn set_timestamp(&self, timestamp: Timestamp) -> &Self { + self.0.lock().new_timestamp = Some(timestamp); + self + } + + pub fn set_timestamp_now(&self) -> &Self { + self.0.lock().new_timestamp = Some(get_timestamp_now_txn()); + self + } + + pub(crate) fn modify_change(&self, change: &mut Change) { + let m = self.0.lock(); + if let Some(msg) = &m.new_msg { + change.commit_msg = Some(msg.clone()); + } + + if let Some(timestamp) = m.new_timestamp { + change.timestamp = timestamp; + } + } +} diff --git a/vendor/loro-internal/src/span.rs b/vendor/loro-internal/src/span.rs new file mode 100644 index 0000000..b111219 --- /dev/null +++ b/vendor/loro-internal/src/span.rs @@ -0,0 +1,3 @@ +pub use loro_common::{ + CounterSpan, HasCounter, HasCounterSpan, HasId, HasIdSpan, HasLamport, HasLamportSpan, IdSpan, +}; diff --git a/vendor/loro-internal/src/state.rs b/vendor/loro-internal/src/state.rs new file mode 100644 index 0000000..5c7edd2 --- /dev/null +++ b/vendor/loro-internal/src/state.rs @@ -0,0 +1,2873 @@ +pub mod container_tree; + +use crate::sync::{AtomicU64, Mutex, RwLock}; +#[cfg(test)] +use std::cell::Cell; +use std::sync::{Arc, Weak}; +use std::{borrow::Cow, io::Write, sync::atomic::Ordering}; + +use container_store::ContainerStore; +use dead_containers_cache::DeadContainersCache; +use enum_as_inner::EnumAsInner; +use enum_dispatch::enum_dispatch; +use loro_common::{ContainerID, Lamport, LoroError, LoroResult, TreeID, ID}; +use loro_delta::DeltaItem; +use rustc_hash::{FxHashMap, FxHashSet}; +use smallvec::SmallVec; +use tracing::{info_span, instrument, warn}; + +use crate::{ + configure::{Configure, DefaultRandom, SecureRandomGenerator}, + container::{idx::ContainerIdx, richtext::config::StyleConfigMap, tree::tree_op::TreeOp}, + cursor::{Cursor, PosType}, + delta::TreeExternalDiff, + diff_calc::{DiffCalculator, DiffMode}, + event::{Diff, EventTriggerKind, Index, InternalContainerDiff, InternalDiff, KeptChange}, + fx_map, + handler::ValueOrHandler, + id::PeerID, + lock::{LoroLockGroup, LoroMutex}, + op::{Op, RawOp, RawOpContent}, + version::{Frontiers, VersionVector}, + ContainerDiff, ContainerType, DocDiff, InternalString, LoroDocInner, LoroValue, OpLog, +}; + +pub(crate) mod analyzer; +pub(crate) mod container_store; +#[cfg(feature = "counter")] +mod counter_state; +mod dead_containers_cache; +mod list_state; +mod map_state; +mod mergeable; +mod movable_list_state; +mod richtext_state; +mod tree_state; +mod unknown_state; +mod value_decode; + +pub(crate) use self::movable_list_state::{IndexType, MovableListState}; +pub(crate) use container_store::GcStore; +pub(crate) use list_state::ListState; +pub(crate) use map_state::MapState; +pub(crate) use richtext_state::{redact_dead_style_values, RichtextState}; +pub(crate) use tree_state::FiIfNotConfigured; +pub(crate) use tree_state::{get_meta_value, FractionalIndexGenResult, NodePosition, TreeState}; +pub use tree_state::{TreeNode, TreeNodeWithChildren, TreeParentId}; + +use self::{container_store::ContainerWrapper, unknown_state::UnknownState}; + +#[cfg(feature = "counter")] +use self::counter_state::CounterState; + +use super::{arena::SharedArena, event::InternalDocDiff}; + +#[cfg(test)] +thread_local! { + static FAIL_NEXT_IMPORT_STATE_APPLY: Cell<bool> = Cell::new(false); +} + +#[cfg(test)] +pub(crate) fn fail_next_import_state_apply_for_test() { + FAIL_NEXT_IMPORT_STATE_APPLY.with(|fail| fail.set(true)); +} + +fn visible_container_value_is_empty(kind: ContainerType, value: &LoroValue) -> bool { + match kind { + ContainerType::Text => value.as_string().is_some_and(|value| value.is_empty()), + ContainerType::Map | ContainerType::List | ContainerType::MovableList => { + value.is_empty_collection() + } + ContainerType::Tree => value.as_list().is_some_and(|value| value.is_empty()), + #[cfg(feature = "counter")] + ContainerType::Counter => false, + ContainerType::Unknown(_) => false, + } +} + +fn deleted_root_container_value_is_cleared(kind: ContainerType, value: &LoroValue) -> bool { + match kind { + #[cfg(feature = "counter")] + ContainerType::Counter => value.as_double().is_some_and(|value| *value == 0.0), + _ => visible_container_value_is_empty(kind, value), + } +} + +fn state_decode_error(message: impl Into<Box<str>>) -> LoroError { + LoroError::DecodeError(message.into()) +} + +fn decode_peer_table(bytes: &mut &[u8], context: &str) -> LoroResult<Vec<PeerID>> { + let peer_num = leb128::read::unsigned(bytes) + .map_err(|_| state_decode_error(format!("{context}: invalid peer table length")))?; + let peer_num = usize::try_from(peer_num) + .map_err(|_| state_decode_error(format!("{context}: peer table length overflow")))?; + let peer_bytes_len = peer_num + .checked_mul(std::mem::size_of::<PeerID>()) + .ok_or_else(|| state_decode_error(format!("{context}: peer table byte length overflow")))?; + if bytes.len() < peer_bytes_len { + return Err(state_decode_error(format!( + "{context}: truncated peer table" + ))); + } + + let peer_bytes = &bytes[..peer_bytes_len]; + let peers = peer_bytes + .chunks_exact(std::mem::size_of::<PeerID>()) + .map(|chunk| { + let mut buf = [0u8; std::mem::size_of::<PeerID>()]; + buf.copy_from_slice(chunk); + PeerID::from_le_bytes(buf) + }) + .collect(); + *bytes = &bytes[peer_bytes_len..]; + Ok(peers) +} + +fn decode_peer_from_table(peers: &[PeerID], peer_idx: usize, context: &str) -> LoroResult<PeerID> { + peers + .get(peer_idx) + .copied() + .ok_or_else(|| state_decode_error(format!("{context}: peer index out of range"))) +} + +fn read_state_leb_u64(bytes: &mut &[u8], context: &str) -> LoroResult<u64> { + leb128::read::unsigned(bytes) + .map_err(|_| state_decode_error(format!("{context}: invalid integer"))) +} + +fn decode_counter(counter: i32, context: &str) -> LoroResult<i32> { + if counter < 0 { + return Err(state_decode_error(format!("{context}: negative counter"))); + } + + Ok(counter) +} + +fn decode_lamport_from_delta( + counter: i32, + lamport_sub_counter: i32, + context: &str, +) -> LoroResult<Lamport> { + decode_counter(counter, context)?; + let lamport = counter + .checked_add(lamport_sub_counter) + .ok_or_else(|| state_decode_error(format!("{context}: lamport overflow")))?; + u32::try_from(lamport).map_err(|_| state_decode_error(format!("{context}: negative lamport"))) +} + +pub struct DocState { + pub(super) peer: Arc<AtomicU64>, + + pub(super) frontiers: Frontiers, + // pub(super) states: FxHashMap<ContainerIdx, State>, + pub(super) store: ContainerStore, + pub(super) arena: SharedArena, + pub(crate) config: Configure, + // resolve event stuff + doc: Weak<LoroDocInner>, + // txn related stuff + in_txn: bool, + changed_idx_in_txn: FxHashSet<ContainerIdx>, + + // diff related stuff + event_recorder: EventRecorder, + + dead_containers_cache: DeadContainersCache, + alive_containers_cache: Option<AliveContainersCache>, + /// Set while recording for a caller that only uses actual changes + /// ([`crate::undo::DiffBatch::from_changes`]: revert, undo). Containers that keep their + /// state are then not revived at all, which skips building full states nobody reads. + record_changes_only: bool, + /// Set while a local transaction that may be rolled back runs (`apply_diff`, + /// `revert_to`). See [`Self::begin_local_rollback`]. + local_rollback: Option<LocalRollbackJournal>, +} + +/// What undoing a local transaction's ops by checkout cannot restore exactly, +/// recorded as the ops are applied. See `context/apply-diff-atomicity.md`. +struct LocalRollbackJournal { + /// The `apply_diff` scope that began it. + scope: u64, + /// The value of each counter before the transaction's first op on it: + /// subtracting the increments again may not give back the same float. + #[cfg(feature = "counter")] + counters: FxHashMap<ContainerIdx, f64>, +} + +struct AliveContainersCache { + frontiers: Frontiers, + roots: Vec<ContainerIdx>, + indices: Arc<FxHashSet<ContainerIdx>>, +} + +/// Which containers an alive-container walk follows. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum AliveWalk { + /// Containers reachable through the current value (`get_deep_value` view). + Visible, + /// `Visible` plus the meta maps of deleted tree nodes and everything they reach. + /// + /// Shallow/state-only export filters the root state with this set. A tree node deleted + /// before the root can still be revived by a retained op: a node that is only dead because + /// an ancestor was deleted can be moved out locally, and a peer's `Move` op revives even a + /// directly deleted node (the local handler refuses that, and undo/`revert_to` allocate a + /// new `TreeID`, but the tree CRDT applies such an op). The revived node keeps its old meta map, + /// so that map must stay in the root state for the latest state and every checkout in the + /// retained range. Map/list children deleted before the root cannot be re-attached (a + /// re-insert creates a new container id) and are still dropped. + Retention, +} + +const ALIVE_CONTAINERS_CACHE_MAX_BYTES: usize = 4 * 1024 * 1024; + +fn estimated_alive_containers_cache_bytes( + roots_capacity: usize, + indices: &FxHashSet<ContainerIdx>, +) -> usize { + // Hash-table control bytes and alignment are implementation details. A pointer of overhead per + // entry is deliberately conservative, so retaining the cache cannot silently become another + // form of full-state materialization on documents with very many small containers. + roots_capacity + .saturating_mul(std::mem::size_of::<ContainerIdx>()) + .saturating_add( + indices + .capacity() + .saturating_mul(std::mem::size_of::<ContainerIdx>() + std::mem::size_of::<usize>()), + ) +} + +impl std::fmt::Debug for DocState { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DocState") + .field("peer", &self.peer) + .finish() + } +} + +#[derive(Clone, Copy)] +pub(crate) struct ContainerCreationContext<'a> { + pub configure: &'a Configure, + pub peer: PeerID, +} + +pub(crate) struct DiffApplyContext<'a> { + pub mode: DiffMode, + pub doc: &'a Weak<LoroDocInner>, +} + +pub(crate) trait FastStateSnapshot { + fn encode_snapshot_fast<W: Write>(&mut self, w: W); + fn decode_value(bytes: &[u8]) -> LoroResult<(LoroValue, &[u8])>; + fn decode_snapshot_fast( + idx: ContainerIdx, + v: (LoroValue, &[u8]), + ctx: ContainerCreationContext, + ) -> LoroResult<Self> + where + Self: Sized; +} + +#[derive(Debug, Clone, Default)] +pub(crate) struct ApplyLocalOpReturn { + pub deleted_containers: Vec<ContainerID>, +} + +#[enum_dispatch] +pub(crate) trait ContainerState { + fn container_idx(&self) -> ContainerIdx; + + fn is_state_empty(&self) -> bool; + + #[must_use] + fn apply_diff_and_convert(&mut self, diff: InternalDiff, ctx: DiffApplyContext) -> Diff; + + /// Apply a state diff. Returns `Err` when the diff is malformed in a + /// way that would corrupt the container (e.g. a `Retain`/`Insert` that + /// overruns the current state). The error is propagated up to + /// `doc.import` so the caller can observe the failure without the + /// doc-state panicking inside a lock. + fn apply_diff(&mut self, diff: InternalDiff, ctx: DiffApplyContext) -> LoroResult<()>; + + /// Validate a state diff before it is applied. Implementations should keep + /// this check proportional to the diff size and must not mutate container + /// state. + fn validate_diff(&self, _diff: &InternalDiff) -> LoroResult<()> { + Ok(()) + } + + fn apply_local_op(&mut self, raw_op: &RawOp, op: &Op) -> LoroResult<ApplyLocalOpReturn>; + /// Convert a state to a diff, such that an empty state will be transformed into the same as this state when it's applied. + fn to_diff(&mut self, doc: &Weak<LoroDocInner>) -> Diff; + + fn get_value(&mut self) -> LoroValue; + + /// Get the index of the child container + #[allow(unused)] + fn get_child_index(&self, id: &ContainerID) -> Option<Index>; + + #[allow(unused)] + fn contains_child(&self, id: &ContainerID) -> bool; + + #[allow(unused)] + fn get_child_containers(&self) -> Vec<ContainerID>; + + fn fork(&self, config: &Configure) -> Self; +} + +impl<T: FastStateSnapshot> FastStateSnapshot for Box<T> { + fn encode_snapshot_fast<W: Write>(&mut self, w: W) { + self.as_mut().encode_snapshot_fast(w) + } + + fn decode_value(bytes: &[u8]) -> LoroResult<(LoroValue, &[u8])> { + T::decode_value(bytes) + } + + fn decode_snapshot_fast( + idx: ContainerIdx, + v: (LoroValue, &[u8]), + ctx: ContainerCreationContext, + ) -> LoroResult<Self> + where + Self: Sized, + { + T::decode_snapshot_fast(idx, v, ctx).map(|x| Box::new(x)) + } +} + +impl<T: ContainerState> ContainerState for Box<T> { + fn container_idx(&self) -> ContainerIdx { + self.as_ref().container_idx() + } + + fn is_state_empty(&self) -> bool { + self.as_ref().is_state_empty() + } + + fn apply_diff_and_convert(&mut self, diff: InternalDiff, ctx: DiffApplyContext) -> Diff { + self.as_mut().apply_diff_and_convert(diff, ctx) + } + + fn apply_diff(&mut self, diff: InternalDiff, ctx: DiffApplyContext) -> LoroResult<()> { + self.as_mut().apply_diff(diff, ctx) + } + + fn validate_diff(&self, diff: &InternalDiff) -> LoroResult<()> { + self.as_ref().validate_diff(diff) + } + + fn apply_local_op(&mut self, raw_op: &RawOp, op: &Op) -> LoroResult<ApplyLocalOpReturn> { + self.as_mut().apply_local_op(raw_op, op) + } + + #[doc = r" Convert a state to a diff, such that an empty state will be transformed into the same as this state when it's applied."] + fn to_diff(&mut self, doc: &Weak<LoroDocInner>) -> Diff { + self.as_mut().to_diff(doc) + } + + fn get_value(&mut self) -> LoroValue { + self.as_mut().get_value() + } + + #[doc = r" Get the index of the child container"] + #[allow(unused)] + fn get_child_index(&self, id: &ContainerID) -> Option<Index> { + self.as_ref().get_child_index(id) + } + + fn contains_child(&self, id: &ContainerID) -> bool { + self.as_ref().contains_child(id) + } + + #[allow(unused)] + fn get_child_containers(&self) -> Vec<ContainerID> { + self.as_ref().get_child_containers() + } + + fn fork(&self, config: &Configure) -> Self { + Box::new(self.as_ref().fork(config)) + } +} + +#[allow(clippy::enum_variant_names)] +#[enum_dispatch(ContainerState)] +#[derive(EnumAsInner, Debug)] +pub enum State { + ListState(Box<ListState>), + MovableListState(Box<MovableListState>), + MapState(Box<MapState>), + RichtextState(Box<RichtextState>), + TreeState(Box<TreeState>), + #[cfg(feature = "counter")] + CounterState(Box<counter_state::CounterState>), + UnknownState(UnknownState), +} + +impl From<ListState> for State { + fn from(s: ListState) -> Self { + Self::ListState(Box::new(s)) + } +} + +impl From<RichtextState> for State { + fn from(s: RichtextState) -> Self { + Self::RichtextState(Box::new(s)) + } +} + +impl From<MovableListState> for State { + fn from(s: MovableListState) -> Self { + Self::MovableListState(Box::new(s)) + } +} + +impl From<MapState> for State { + fn from(s: MapState) -> Self { + Self::MapState(Box::new(s)) + } +} + +impl From<TreeState> for State { + fn from(s: TreeState) -> Self { + Self::TreeState(Box::new(s)) + } +} + +#[cfg(feature = "counter")] +impl From<CounterState> for State { + fn from(s: CounterState) -> Self { + Self::CounterState(Box::new(s)) + } +} + +impl State { + pub fn new_list(idx: ContainerIdx) -> Self { + Self::ListState(Box::new(ListState::new(idx))) + } + + pub fn new_map(idx: ContainerIdx) -> Self { + Self::MapState(Box::new(MapState::new(idx))) + } + + pub fn new_richtext(idx: ContainerIdx, config: Arc<RwLock<StyleConfigMap>>) -> Self { + Self::RichtextState(Box::new(RichtextState::new(idx, config))) + } + + pub fn new_tree(idx: ContainerIdx, peer: PeerID) -> Self { + Self::TreeState(Box::new(TreeState::new(idx, peer))) + } + + pub fn new_unknown(idx: ContainerIdx) -> Self { + Self::UnknownState(UnknownState::new(idx)) + } + + pub fn encode_snapshot_fast<W: Write>(&mut self, mut w: W) { + match self { + State::ListState(s) => s.encode_snapshot_fast(&mut w), + State::MovableListState(s) => s.encode_snapshot_fast(&mut w), + State::MapState(s) => s.encode_snapshot_fast(&mut w), + State::RichtextState(s) => s.encode_snapshot_fast(&mut w), + State::TreeState(s) => s.encode_snapshot_fast(&mut w), + #[cfg(feature = "counter")] + State::CounterState(s) => s.encode_snapshot_fast(&mut w), + State::UnknownState(s) => s.encode_snapshot_fast(&mut w), + } + } + + pub fn fork(&self, config: &Configure) -> Self { + match self { + State::ListState(list_state) => State::ListState(list_state.fork(config)), + State::MovableListState(movable_list_state) => { + State::MovableListState(movable_list_state.fork(config)) + } + State::MapState(map_state) => State::MapState(map_state.fork(config)), + State::RichtextState(richtext_state) => { + State::RichtextState(richtext_state.fork(config)) + } + State::TreeState(tree_state) => State::TreeState(tree_state.fork(config)), + #[cfg(feature = "counter")] + State::CounterState(counter_state) => State::CounterState(counter_state.fork(config)), + State::UnknownState(unknown_state) => State::UnknownState(unknown_state.fork(config)), + } + } +} + +impl DocState { + #[inline] + pub fn new_arc( + doc: Weak<LoroDocInner>, + arena: SharedArena, + config: Configure, + lock_group: &LoroLockGroup, + ) -> Arc<LoroMutex<Self>> { + let peer = DefaultRandom.next_u64(); + // TODO: maybe we should switch to certain version in oplog? + + let peer = Arc::new(AtomicU64::new(peer)); + Arc::new(lock_group.new_lock( + Self { + store: ContainerStore::new(arena.clone(), config.clone(), peer.clone()), + peer, + arena, + frontiers: Frontiers::default(), + doc, + config, + in_txn: false, + changed_idx_in_txn: FxHashSet::default(), + event_recorder: Default::default(), + dead_containers_cache: Default::default(), + alive_containers_cache: None, + record_changes_only: false, + local_rollback: None, + }, + crate::lock::LockKind::DocState, + )) + } + + pub fn fork_with_new_peer_id( + &mut self, + doc: Weak<LoroDocInner>, + arena: SharedArena, + config: Configure, + ) -> Arc<Mutex<Self>> { + let peer = Arc::new(AtomicU64::new(DefaultRandom.next_u64())); + let store = self.store.fork(arena.clone(), peer.clone(), config.clone()); + Arc::new(Mutex::new(Self { + peer, + frontiers: self.frontiers.clone(), + store, + arena, + config, + doc, + in_txn: false, + changed_idx_in_txn: FxHashSet::default(), + event_recorder: Default::default(), + dead_containers_cache: Default::default(), + alive_containers_cache: None, + record_changes_only: false, + local_rollback: None, + })) + } + + pub fn start_recording(&mut self) { + if self.is_recording() { + return; + } + + self.event_recorder.recording_diff = true; + self.event_recorder.diff_start_version = Some(self.frontiers.clone()); + } + + #[inline(always)] + pub fn stop_and_clear_recording(&mut self) { + self.event_recorder = Default::default(); + } + + #[inline(always)] + pub fn is_recording(&self) -> bool { + self.event_recorder.recording_diff + } + + pub fn refresh_peer_id(&mut self) { + self.peer.store( + DefaultRandom.next_u64(), + std::sync::atomic::Ordering::Relaxed, + ); + } + + /// Take all the diffs that are recorded and convert them to events. + pub fn take_events(&mut self) -> Vec<DocDiff> { + if !self.is_recording() { + return vec![]; + } + + self.convert_current_batch_diff_into_event(); + std::mem::take(&mut self.event_recorder.events) + } + + /// Record the next diff. + /// Caller should call [pre_txn] before calling this. + /// + /// # Panic + /// + /// Panic when the diff cannot be merged with the previous diff. + /// Caller should call [pre_txn] before calling this to avoid panic. + fn record_diff(&mut self, diff: InternalDocDiff) { + if !self.event_recorder.recording_diff || diff.diff.is_empty() { + return; + } + + let Some(last_diff) = self.event_recorder.diffs.last_mut() else { + self.event_recorder.diffs.push(diff.into_owned()); + return; + }; + + if last_diff.can_merge(&diff) { + self.event_recorder.diffs.push(diff.into_owned()); + return; + } + + panic!("should call pre_txn before record_diff") + } + + /// This should be called when DocState is going to apply a transaction / a diff. + fn pre_txn(&mut self, next_origin: InternalString, next_trigger: EventTriggerKind) { + if !self.is_recording() { + return; + } + + let Some(last_diff) = self.event_recorder.diffs.last() else { + return; + }; + + if last_diff.origin == next_origin && last_diff.by == next_trigger { + return; + } + + // current diff batch cannot merge with the incoming diff, + // need to convert all the current diffs into event + self.convert_current_batch_diff_into_event() + } + + fn convert_current_batch_diff_into_event(&mut self) { + let recorder = &mut self.event_recorder; + if recorder.diffs.is_empty() { + return; + } + + let diffs = std::mem::take(&mut recorder.diffs); + let start = recorder.diff_start_version.take().unwrap(); + recorder.diff_start_version = Some((*diffs.last().unwrap().new_version).to_owned()); + let event = self.diffs_to_event(diffs, start); + self.event_recorder.events.push(event); + } + + /// Change the peer id of this doc state. + /// It changes the peer id for the future txn on this AppState + #[inline] + pub fn set_peer_id(&mut self, peer: PeerID) { + self.peer.store(peer, std::sync::atomic::Ordering::Relaxed); + } + + pub fn peer_id(&self) -> PeerID { + self.peer.load(std::sync::atomic::Ordering::Relaxed) + } + + /// It's expected that diff only contains [`InternalDiff`] + /// + /// Returns `Err` if any container state rejects its diff as malformed + /// (see `ContainerState::validate_diff`). Validation runs before mutating + /// any container state, so a returned error leaves the doc-state view at + /// the previous version. + #[instrument(skip_all)] + pub(crate) fn apply_diff( + &mut self, + mut diff: InternalDocDiff<'static>, + diff_mode: DiffMode, + ) -> LoroResult<()> { + if self.in_txn { + return Err(LoroError::TransactionError( + "apply_diff should not be called in a transaction" + .to_string() + .into_boxed_str(), + )); + } + + let is_recording = self.is_recording(); + let Cow::Owned(mut diffs) = std::mem::take(&mut diff.diff) else { + unreachable!() + }; + self.validate_diff_batch(&diffs)?; + #[cfg(test)] + if diff.origin.as_str() == "__loro_fail_import_state_apply" { + return Err(LoroError::internal("state apply failpoint")); + } + #[cfg(test)] + if diff.by == EventTriggerKind::Import { + let should_fail = FAIL_NEXT_IMPORT_STATE_APPLY.with(|fail| { + let should_fail = fail.get(); + if should_fail { + fail.set(false); + } + should_fail + }); + if should_fail { + return Err(LoroError::internal("state apply failpoint")); + } + } + // `diff_mode` here is the DIRECTION mode (`origin_diff_mode` from + // `calc_diff_internal`), not the mode the calculators computed with: + // Checkout means the transition may go backwards, which can revive any + // container. Any checkout also clears it, even a forward one + // (`attach`, `checkout_to_latest`): while the state was behind the + // oplog, a container created later looked cut at its map or list + // parent. Every other forward transition keeps the state at the + // oplog's latest version, where only a tree or movable-list move can + // revive a container (see `dead_containers_cache.rs`). + if diff_mode == DiffMode::Checkout || diff.by == EventTriggerKind::Checkout { + self.dead_containers_cache.clear(); + } else if diffs.iter().any(|d| { + matches!( + d.idx.get_type(), + ContainerType::Tree | ContainerType::MovableList + ) + }) { + self.dead_containers_cache.clear_revivable(); + } + self.pre_txn(diff.origin.clone(), diff.by); + + // # Revival + // + // A Container, if it is deleted from its parent Container, will still exist + // in the internal state of Loro; whereas on the user side, a tree structure + // is maintained following Events, and at this point, the corresponding state + // is considered deleted. + // + // Sometimes, this "pseudo-dead" Container may be revived (for example, through + // backtracking or parallel editing), and the user side should receive an Event + // that restores the consistency between the revived Container and the internal + // state of Loro. This Event is required to restore the pseudo-dead Container + // State to its current state on Loro, and we refer to this process as "revival". + // + // Revival occurs during the application of the internal diff, and this operation + // is necessary when it needs to be converted into an external Event. + // + // We can utilize the output of the Diff to determine which child nodes should be revived. + // + // For nodes that are to be revived, we can disregard the Events output by their + // round of apply_diff_and_convert, and instead, directly convert their state into + // an Event once their application is complete. + // + // Suppose A is revived and B is A's child, and B also needs to be revived; therefore, + // we should process each level alternately. + + self.register_meta_parents_of_created_tree_nodes(&diffs); + // We need to ensure diff is processed in order + diffs.sort_by_cached_key(|diff| self.arena.get_depth(diff.idx)); + let mut to_revive_in_next_layer: FxHashSet<ContainerIdx> = FxHashSet::default(); + let mut to_revive_in_this_layer: FxHashSet<ContainerIdx> = FxHashSet::default(); + // Revived containers that kept their id and state: a mergeable child re-activated by + // a container that is not itself revived, and what such a container holds. Their event + // still carries the full state; `KeptChange` records their actual change. + let mut kept: FxHashSet<ContainerIdx> = FxHashSet::default(); + let mut last_depth = 0; + let len = diffs.len(); + for mut diff in std::mem::replace(&mut diffs, Vec::with_capacity(len)) { + let Some(depth) = self.arena.get_depth(diff.idx) else { + warn!("{:?} is not in arena. It could be a dangling container that was deleted before the shallow start version.", self.arena.idx_to_id(diff.idx)); + continue; + }; + let this_depth = depth.get(); + while this_depth > last_depth { + // Clear `to_revive` when we are going to process a new level + // so that we can process the revival of the next level + let to_create = std::mem::take(&mut to_revive_in_this_layer); + to_revive_in_this_layer = std::mem::take(&mut to_revive_in_next_layer); + for new in to_create { + if let Some(d) = + self.revive_without_diff(new, &mut to_revive_in_this_layer, &mut kept) + { + diffs.push(d); + } + } + + last_depth += 1; + } + + let idx = diff.idx; + let internal_diff = std::mem::take(&mut diff.diff); + match &internal_diff { + crate::event::DiffVariant::None => { + if is_recording { + let state = self.store.get_or_create_mut(diff.idx); + let extern_diff = state.to_diff(&self.doc); + trigger_on_new_container( + &extern_diff, + |cid| { + to_revive_in_next_layer.insert(cid); + }, + &self.arena, + ); + diff.diff = extern_diff.into(); + } + } + crate::event::DiffVariant::Internal(inner_diff) => { + self.ensure_containers_created_by_internal_diff(inner_diff); + let cid = self.arena.idx_to_id(idx).unwrap(); + info_span!("apply diff on", container_id = ?cid).in_scope( + || -> LoroResult<()> { + if self.in_txn { + self.changed_idx_in_txn.insert(idx); + } + let state = self.store.get_or_create_mut(idx); + if is_recording { + let is_revived = + diff.bring_back || to_revive_in_this_layer.contains(&idx); + let is_kept = is_revived && kept.contains(&idx); + let ctx = DiffApplyContext { + mode: diff.diff_mode, + doc: &self.doc, + }; + let internal_diff = internal_diff.into_internal().unwrap(); + // Containers the actual change inserts are new to a doc that + // kept this container, so they are revived with full state. + let mut inserted: FxHashSet<ContainerIdx> = FxHashSet::default(); + // process bring_back before apply + let external_diff = if is_kept { + let change = state.apply_diff_and_convert(internal_diff, ctx); + trigger_on_new_container( + &change, + |cid| { + inserted.insert(cid); + }, + &self.arena, + ); + diff.kept = Some(KeptChange::from_diff(change)); + state.to_diff(&self.doc) + } else if is_revived { + state.apply_diff(internal_diff, ctx)?; + state.to_diff(&self.doc) + } else { + state.apply_diff_and_convert(internal_diff, ctx) + }; + let arena = &self.arena; + let changes_only = self.record_changes_only; + trigger_on_new_container( + &external_diff, + |cid| { + if changes_only && !is_revived && is_mergeable(arena, cid) { + // It keeps its state; its own diff (if any) is + // its change. + return; + } + to_revive_in_next_layer.insert(cid); + let keeps_state = if is_revived { + is_kept + && (!inserted.contains(&cid) + || is_mergeable(arena, cid)) + } else { + // A container that keeps its id re-activates a + // mergeable child at its deterministic cid. + is_mergeable(arena, cid) + }; + if keeps_state { + kept.insert(cid); + } + }, + arena, + ); + diff.diff = external_diff.into(); + } else { + state.apply_diff( + internal_diff.into_internal().unwrap(), + DiffApplyContext { + mode: diff.diff_mode, + doc: &self.doc, + }, + )?; + } + Ok(()) + }, + )?; + } + crate::event::DiffVariant::External(_) => unreachable!(), + } + + to_revive_in_this_layer.remove(&idx); + if !diff.diff.is_empty() || matches!(diff.kept, Some(KeptChange::Changed(_))) { + diffs.push(diff); + } + } + + // Revive the last several layers + while !to_revive_in_this_layer.is_empty() || !to_revive_in_next_layer.is_empty() { + let to_create = std::mem::take(&mut to_revive_in_this_layer); + for new in to_create { + if let Some(d) = + self.revive_without_diff(new, &mut to_revive_in_next_layer, &mut kept) + { + diffs.push(d); + } + } + + to_revive_in_this_layer = std::mem::take(&mut to_revive_in_next_layer); + } + + diff.diff = diffs.into(); + self.frontiers = diff.new_version.clone().into_owned(); + + if self.is_recording() { + self.record_diff(diff) + } + Ok(()) + } + + /// Registers the tree as the parent of the meta map of every node a tree diff in this batch + /// (re)creates, before the batch is sorted by depth. + /// + /// Normally the node's `Create` op or the snapshot state registered it already. A node + /// deleted before a shallow root and revived by a retained op has neither when the root state + /// lacks its meta (blobs from exporters before loro-dev/loro#1119). Without a parent the meta + /// has no depth: `ensure_container` panicked with "Parent is not registered", and the meta's + /// own diff in the same batch was skipped as a dangling container. + fn register_meta_parents_of_created_tree_nodes(&mut self, diffs: &[InternalContainerDiff]) { + for diff in diffs { + let crate::event::DiffVariant::Internal(InternalDiff::Tree(delta)) = &diff.diff else { + continue; + }; + for item in delta.diff.iter() { + if matches!(item.action, crate::delta::TreeInternalDiff::Create { .. }) { + let meta_idx = self + .arena + .register_container(&item.target.associated_meta_container()); + if self.arena.get_registered_parent(meta_idx).is_none() { + self.arena.set_parent(meta_idx, Some(diff.idx)); + } + } + } + } + } + + /// Create store entries for every container this diff brings alive. + /// + /// Full snapshot export no longer walks the alive-container graph to discover containers + /// that exist only as references inside another container's value (e.g. an empty child + /// created by a remote peer, whose own container has no ops and therefore no diff). Such + /// entries must be created when the reference is applied so the next flush persists them. + fn ensure_containers_created_by_internal_diff(&mut self, diff: &InternalDiff) { + let mut to_ensure: SmallVec<[ContainerID; 2]> = SmallVec::new(); + match diff { + InternalDiff::ListRaw(delta) => { + for item in delta.iter() { + if let crate::delta::DeltaItem::Insert { insert, .. } = item { + match &insert.values { + either::Either::Left(values) => { + for value in values.as_slice() { + if let LoroValue::Container(c) = value { + to_ensure.push(c.clone()); + } + } + } + either::Either::Right(LoroValue::Container(c)) => { + to_ensure.push(c.clone()) + } + either::Either::Right(_) => {} + } + } + } + } + InternalDiff::Map(delta) => { + // Mergeable markers are deliberately not materialized here: the parent map's + // marker is the single source of truth for an ensured-but-empty mergeable + // child, and it resolves lazily via `does_container_exist`/`get_reachable`. + for value in delta.updated.values() { + let Some(Some(value)) = value.as_ref().map(|v| v.value.as_ref()) else { + continue; + }; + if let LoroValue::Container(c) = value { + to_ensure.push(c.clone()); + } + } + } + InternalDiff::Tree(delta) => { + for item in delta.diff.iter() { + if matches!(item.action, crate::delta::TreeInternalDiff::Create { .. }) { + to_ensure.push(item.target.associated_meta_container()); + } + } + } + InternalDiff::MovableList(delta) => { + for elem in delta.elements.values() { + if let LoroValue::Container(c) = &elem.value { + to_ensure.push(c.clone()); + } + } + } + InternalDiff::RichtextRaw(_) => {} + #[cfg(feature = "counter")] + InternalDiff::Counter(_) => {} + InternalDiff::Unknown => {} + } + + for id in to_ensure { + self.ensure_container(&id); + } + } + + /// Whether a forward import diff has to be recomputed in Checkout mode because a + /// movable-list op targets an element this state no longer holds. + /// See [`MovableListState::references_absent_elem`]. + pub(crate) fn needs_checkout_diff(&mut self, diffs: &[InternalContainerDiff]) -> bool { + diffs.iter().any(|diff| { + let crate::event::DiffVariant::Internal(InternalDiff::MovableList(delta)) = &diff.diff + else { + return false; + }; + match self.store.get_container(diff.idx) { + Some(State::MovableListState(state)) => state.references_absent_elem(delta), + Some(_) => unreachable!("movable list diff for a non movable list container"), + None => delta + .elements + .values() + .any(|elem| elem.pos.is_none() || elem.value_id.is_none()), + } + }) + } + + fn validate_diff_batch(&mut self, diffs: &[InternalContainerDiff]) -> LoroResult<()> { + for diff in diffs { + let crate::event::DiffVariant::Internal(internal_diff) = &diff.diff else { + continue; + }; + if let Some(state) = self.store.get_container(diff.idx) { + state.validate_diff(internal_diff)?; + } else { + let state = create_state_(diff.idx, &self.config, self.peer_id()); + state.validate_diff(internal_diff)?; + } + } + + Ok(()) + } + + pub fn apply_local_op(&mut self, raw_op: &RawOp, op: &Op) -> LoroResult<()> { + // set parent first, `MapContainer` will only be created for TreeID that does not contain + self.set_container_parent_by_raw_op(raw_op); + self.ensure_containers_created_by_op(op); + let state = self.store.get_or_create_mut(op.container); + if self.in_txn { + self.changed_idx_in_txn.insert(op.container); + } + #[cfg(feature = "counter")] + if let (Some(journal), State::CounterState(counter)) = (&mut self.local_rollback, &*state) { + journal + .counters + .entry(op.container) + .or_insert_with(|| counter.value()); + } + // A local move can take a node out of a deleted subtree. Movable-list + // elements cannot be revived locally: a deleted one has no index. + if let RawOpContent::Tree(tree_op) = &raw_op.content { + if matches!(**tree_op, TreeOp::Move { .. }) { + self.dead_containers_cache.clear_revivable(); + } + } + state.apply_local_op(raw_op, op)?; + Ok(()) + } + + /// Start recording what [`Self::finish_local_rollback`] needs to undo the + /// local ops applied from now on: the containers that get new state and the + /// counters' values. + /// + /// `scope` identifies the caller. A journal of another scope is replaced: two + /// scopes never share a transaction, so that scope's transaction was + /// committed by another thread and cannot be rolled back anyway. + pub(crate) fn begin_local_rollback(&mut self, scope: u64) { + self.store.begin_created_journal(); + self.local_rollback = Some(LocalRollbackJournal { + scope, + #[cfg(feature = "counter")] + counters: Default::default(), + }); + } + + /// Stop recording for `scope`, keeping the ops. + pub(crate) fn end_local_rollback(&mut self, scope: u64) { + if self + .local_rollback + .as_ref() + .is_some_and(|j| j.scope == scope) + { + self.store.take_created_journal(); + self.local_rollback = None; + } + } + + /// Takes the event recorder out, so that a state change the caller discards + /// is not recorded; put it back with [`Self::restore_event_recorder`]. + pub(crate) fn take_event_recorder(&mut self) -> EventRecorder { + std::mem::take(&mut self.event_recorder) + } + + pub(crate) fn restore_event_recorder(&mut self, recorder: EventRecorder) { + self.event_recorder = recorder; + } + + /// Finish rolling back the local ops applied since + /// [`Self::begin_local_rollback`], after the caller undid them by checking + /// the state out at the version before them. `peer` and `start_counter` are + /// the id of the first op. Restores what the checkout cannot: + /// + /// - containers that got state since (new or never loaded before) lose it, + /// so the store is the same as before, including which roots show up; + /// - counters get their exact old values; + /// - containers the ops created lose their parent link, since the next ops + /// reuse their ids (`SharedArena::forget_parents_of_discarded_ops`); + /// - the liveness caches, which may hold answers for the state in between. + pub(crate) fn finish_local_rollback( + &mut self, + scope: u64, + peer: PeerID, + start_counter: crate::id::Counter, + ) { + let created = self.store.take_created_journal(); + let journal = self.local_rollback.take(); + assert!( + journal.as_ref().is_some_and(|j| j.scope == scope), + "the journal of a rolled back apply_diff was replaced" + ); + #[cfg(feature = "counter")] + if let Some(journal) = journal { + for (idx, value) in journal.counters { + if let Some(State::CounterState(counter)) = self.store.get_container_mut(idx) { + counter.set_value(value); + } + } + } + #[cfg(not(feature = "counter"))] + let _ = journal; + self.store.remove_created(&created); + self.arena + .forget_parents_of_discarded_ops(peer, start_counter); + self.dead_containers_cache.clear(); + self.alive_containers_cache = None; + } + + pub(crate) fn start_txn(&mut self, origin: InternalString, trigger: EventTriggerKind) { + self.pre_txn(origin, trigger); + self.in_txn = true; + } + + pub(crate) fn abort_txn(&mut self) { + self.in_txn = false; + } + + /// Undo [`Self::abort_txn`] for a transaction that goes on + /// (`LoroDoc::rollback_apply_diff_scope`). + pub(crate) fn resume_txn(&mut self) { + self.in_txn = true; + } + + pub fn iter_and_decode_all(&mut self) -> impl Iterator<Item = &mut State> { + self.store.iter_and_decode_all() + } + + pub(crate) fn iter_all_containers_mut( + &mut self, + ) -> impl Iterator<Item = (ContainerIdx, &mut ContainerWrapper)> { + self.store.iter_all_containers() + } + + pub fn does_container_exist(&mut self, id: &ContainerID) -> bool { + // A container may exist even if not yet registered in the arena. + // Check arena first, then fall back to KV presence in the store. + let is_mergeable = id.is_mergeable(); + if id.is_root() && !is_mergeable { + return true; + } + + let registered = if is_mergeable { + None + } else { + self.arena.id_to_idx(id) + }; + if let Some(idx) = registered { + if self.arena.get_depth(idx).is_some() { + return true; + } + } + + if self.store.contains_id(id) { + return true; + } + + // Decided by the first lookup: another thread (e.g. creating a handler) may register + // the container in between, without its parent. + if !is_mergeable && registered.is_none() { + // A document loaded from a snapshot parses its changes lazily, so a container that + // an op created may not be registered yet. + if let Some(idx) = self.arena.find_created_container(id) { + if self.arena.get_depth(idx).is_some() { + return true; + } + } + } + + // An ensured-but-empty mergeable child has no ops or KV state of its own yet; + // the parent map's binary child ref is the source of truth for its existence. + is_mergeable && self.get_reachable(id) + } + + pub(crate) fn commit_txn(&mut self, new_frontiers: Frontiers, diff: Option<InternalDocDiff>) { + self.in_txn = false; + self.frontiers = new_frontiers; + if let Some(diff) = diff { + if self.is_recording() { + self.record_diff(diff); + } + } + } + + /// Ensure the container is created and will be encoded in the next `encode` call + #[inline] + pub(crate) fn ensure_container(&mut self, id: &ContainerID) { + self.store.ensure_container(id); + } + + /// Ensure all alive containers are created in DocState and will be encoded in the next + /// `encode` call, and return the alive set. + /// + /// Only shallow snapshot export needs this now (its `retain_keys` filter requires the alive + /// set). The set is a *retention* set: it also contains the meta maps (and what they reach) + /// of deleted tree nodes, because a later op can revive such a node with its old meta. See + /// [`AliveWalk::Retention`]. Full snapshot export relies on the write-time invariant maintained by + /// `ensure_containers_created_by_op` / `ensure_containers_created_by_internal_diff` instead + /// of walking the graph. + /// + /// Returns arena indices rather than IDs so callers do not have to hold a second set of + /// cloned container IDs; callers that need IDs map them through the arena. + pub(crate) fn ensure_all_alive_containers( + &mut self, + ) -> LoroResult<Arc<FxHashSet<ContainerIdx>>> { + let roots = self.existing_retention_roots(); + if !self.in_txn { + if let Some(cache) = &self.alive_containers_cache { + if cache.frontiers == self.frontiers && cache.roots == roots { + return Ok(cache.indices.clone()); + } + } + } + // Do not hold the previous version's set while constructing its replacement. + self.alive_containers_cache = None; + + let indices = Arc::new( + self.get_all_alive_container_indices_from_roots(&roots, AliveWalk::Retention)?, + ); + for idx in indices.iter() { + let id = self.arena.get_container_id(*idx).unwrap(); + if !self.store.contains_id(&id) { + self.store.ensure_container(&id); + } + } + + if !self.in_txn { + // The walk can discover and ensure an empty mergeable child, which registers another + // retention root without advancing the document version. Store the post-walk roots so + // the next unchanged export can use the cache immediately. + let roots = self.existing_retention_roots(); + if estimated_alive_containers_cache_bytes(roots.capacity(), &indices) + <= ALIVE_CONTAINERS_CACHE_MAX_BYTES + { + self.alive_containers_cache = Some(AliveContainersCache { + frontiers: self.frontiers.clone(), + roots, + indices: indices.clone(), + }); + } + } + + Ok(indices) + } + + pub(crate) fn get_value_by_idx(&mut self, container_idx: ContainerIdx) -> LoroValue { + self.store + .get_value(container_idx) + .unwrap_or_else(|| container_idx.get_type().default_value()) + } + + pub(crate) fn get_map_value_by_key( + &mut self, + container_idx: ContainerIdx, + key: &str, + ) -> Option<LoroValue> { + self.store.map_get(container_idx, key) + } + + pub(crate) fn get_map_len(&mut self, container_idx: ContainerIdx) -> usize { + self.store.map_len(container_idx) + } + + pub(crate) fn get_map_keys(&mut self, container_idx: ContainerIdx) -> Vec<InternalString> { + self.store.map_keys(container_idx) + } + + pub(crate) fn get_map_entries( + &mut self, + container_idx: ContainerIdx, + ) -> Vec<(InternalString, LoroValue)> { + self.store.map_entries(container_idx) + } + + pub(crate) fn get_list_value_at( + &mut self, + container_idx: ContainerIdx, + index: usize, + ) -> Option<LoroValue> { + self.store.list_get(container_idx, index) + } + + pub(crate) fn get_list_len(&mut self, container_idx: ContainerIdx) -> usize { + self.store.list_len(container_idx) + } + + pub(crate) fn get_list_values(&mut self, container_idx: ContainerIdx) -> Vec<LoroValue> { + self.store.list_values(container_idx) + } + + pub(crate) fn get_text_unicode_len(&mut self, container_idx: ContainerIdx) -> usize { + self.store.text_unicode_len(container_idx).unwrap_or(0) + } + + pub(crate) fn get_text_utf16_len(&mut self, container_idx: ContainerIdx) -> usize { + self.store.text_utf16_len(container_idx).unwrap_or(0) + } + + pub(crate) fn get_text_utf8_len(&mut self, container_idx: ContainerIdx) -> usize { + self.store.text_utf8_len(container_idx).unwrap_or(0) + } + + pub(crate) fn has_decoded_container_state(&mut self, container_idx: ContainerIdx) -> bool { + self.store.has_decoded_state(container_idx) + } + + /// Length of a text container in the given `pos_type`, taking a single + /// `DocState` lock and a single container-store lookup. + /// + /// The per-`pos_type` store helpers already branch on decoded-vs-lazy + /// internally, and their lazy branch reads the cheap length metadata + /// without materializing the full richtext state — preserving the + /// lazy-snapshot memory behavior. Callers previously took two separate + /// locks (one to check decoded-ness, one to query), which showed up as a + /// per-op regression on the text editing hot path. Only `Entity` length has + /// no store helper and falls back to the state path. + pub(crate) fn get_text_len(&mut self, container_idx: ContainerIdx, pos_type: PosType) -> usize { + match pos_type { + PosType::Unicode => self.get_text_unicode_len(container_idx), + PosType::Utf16 => self.get_text_utf16_len(container_idx), + PosType::Event if cfg!(feature = "wasm") => self.get_text_utf16_len(container_idx), + PosType::Event => self.get_text_unicode_len(container_idx), + PosType::Bytes => self.get_text_utf8_len(container_idx), + PosType::Entity => self.with_state_mut(container_idx, |state| { + state.as_richtext_state_mut().unwrap().len(PosType::Entity) + }), + } + } + + /// Set the state of the container with the given container idx. + /// This is only used for decode. + /// + /// # Panic + /// + /// If the state is not empty. + pub(super) fn init_with_states_and_version( + &mut self, + frontiers: Frontiers, + oplog: &OpLog, + unknown_containers: Vec<ContainerIdx>, + need_to_register_parent: bool, + origin: InternalString, + ) -> LoroResult<()> { + self.pre_txn(Default::default(), EventTriggerKind::Import); + if need_to_register_parent { + for state in self.store.iter_and_decode_all() { + let idx = state.container_idx(); + let s = state; + for child_id in s.get_child_containers() { + let child_idx = self.arena.register_container(&child_id); + self.arena.set_parent(child_idx, Some(idx)); + } + } + } + + if !unknown_containers.is_empty() { + let mut diff_calc = DiffCalculator::new(false); + let stack_vv; + let vv = if oplog.frontiers() == &frontiers { + oplog.vv() + } else { + stack_vv = oplog.dag().frontiers_to_vv(&frontiers); + stack_vv.as_ref().unwrap() + }; + + let (unknown_diffs, _diff_mode) = diff_calc.calc_diff_internal( + oplog, + &Default::default(), + &Default::default(), + vv, + &frontiers, + Some(&|idx| !idx.is_unknown() && unknown_containers.contains(&idx)), + ); + self.apply_diff( + InternalDocDiff { + origin: origin.clone(), + by: EventTriggerKind::Import, + diff: unknown_diffs.into(), + new_version: Cow::Owned(frontiers.clone()), + }, + DiffMode::Checkout, + )?; + } + + if self.is_recording() { + let diff: Vec<_> = self + .store + .iter_all_containers() + .map(|(idx, state)| InternalContainerDiff { + idx, + bring_back: false, + diff: state + .get_state_mut( + idx, + ContainerCreationContext { + configure: &self.config, + peer: self.peer.load(Ordering::Relaxed), + }, + ) + .to_diff(&self.doc) + .into(), + diff_mode: DiffMode::Checkout, + kept: None, + }) + .collect(); + + self.record_diff(InternalDocDiff { + origin, + by: EventTriggerKind::Import, + diff: diff.into(), + new_version: Cow::Borrowed(&frontiers), + }); + } + + self.frontiers = frontiers; + Ok(()) + } + + #[inline(always)] + #[allow(unused)] + pub(crate) fn with_state<F, R>(&mut self, idx: ContainerIdx, f: F) -> R + where + F: FnOnce(&State) -> R, + { + let depth = self.arena.get_depth(idx).unwrap().get() as usize; + let state = self.store.get_or_create_imm(idx); + f(state) + } + + #[inline(always)] + pub(crate) fn with_state_mut<F, R>(&mut self, idx: ContainerIdx, f: F) -> R + where + F: FnOnce(&mut State) -> R, + { + let state = self.store.get_or_create_mut(idx); + f(state) + } + + pub(crate) fn set_record_changes_only(&mut self, on: bool) { + self.record_changes_only = on; + } + + /// The container's current state as a full-state diff, the shape revival events use. + pub(crate) fn container_full_diff(&mut self, idx: ContainerIdx) -> Diff { + let doc = self.doc.clone(); + self.store.get_or_create_mut(idx).to_diff(&doc) + } + + pub(crate) fn is_container_state_empty(&mut self, idx: ContainerIdx) -> bool { + self.store.get_or_create_mut(idx).is_state_empty() + } + + /// Revives a container that has no diff of its own in this batch: its event is its full + /// state. Children it holds are queued into `to_revive`; if it kept its state, they did too. + fn revive_without_diff( + &mut self, + idx: ContainerIdx, + to_revive: &mut FxHashSet<ContainerIdx>, + kept: &mut FxHashSet<ContainerIdx>, + ) -> Option<InternalContainerDiff> { + let state = self.store.get_or_create_mut(idx); + if state.is_state_empty() { + return None; + } + + let is_kept = kept.contains(&idx); + let external_diff = state.to_diff(&self.doc); + trigger_on_new_container( + &external_diff, + |cid| { + to_revive.insert(cid); + if is_kept { + kept.insert(cid); + } + }, + &self.arena, + ); + + Some(InternalContainerDiff { + idx, + bring_back: true, + diff: external_diff.into(), + diff_mode: DiffMode::Checkout, + kept: is_kept.then_some(KeptChange::Unchanged), + }) + } + + pub(super) fn is_in_txn(&self) -> bool { + self.in_txn + } + + pub fn can_import_snapshot(&self) -> bool { + !self.in_txn && self.arena.can_import_snapshot() && self.store.can_import_snapshot() + } + + pub(crate) fn reset_to_empty_for_failed_snapshot_import(&mut self) { + let was_recording = self.is_recording(); + self.frontiers = Frontiers::default(); + self.store = + ContainerStore::new(self.arena.clone(), self.config.clone(), self.peer.clone()); + self.in_txn = false; + self.changed_idx_in_txn.clear(); + self.event_recorder = Default::default(); + if was_recording { + self.start_recording(); + } + self.dead_containers_cache = Default::default(); + self.alive_containers_cache = None; + } + + pub fn get_value(&mut self) -> LoroValue { + let roots = self.preferred_root_containers(); + let ans: loro_common::LoroMapValue = roots + .into_iter() + .map(|idx| { + let id = self.arena.idx_to_id(idx).unwrap(); + let ContainerID::Root { + name, + container_type: _, + } = &id + else { + unreachable!() + }; + (name.to_string(), LoroValue::Container(id)) + }) + .collect(); + LoroValue::Map(ans) + } + + pub fn get_deep_value(&mut self) -> LoroValue { + let roots = self.preferred_root_containers(); + let mut ans = FxHashMap::with_capacity_and_hasher(roots.len(), Default::default()); + let binding = self.config.deleted_root_containers.clone(); + let deleted_root_container = binding.lock(); + let should_hide_empty_root_container = self + .config + .hide_empty_root_containers + .load(Ordering::Relaxed); + for root_idx in roots { + let id = self.arena.idx_to_id(root_idx).unwrap(); + match &id { + loro_common::ContainerID::Root { name, .. } => { + let v = self.get_container_deep_value(root_idx); + if should_hide_empty_root_container + && visible_container_value_is_empty(root_idx.get_type(), &v) + { + continue; + } + + if deleted_root_container.contains(&id) + && deleted_root_container_value_is_cleared(root_idx.get_type(), &v) + { + continue; + } + + ans.insert(name.to_string(), v); + } + loro_common::ContainerID::Normal { .. } => { + unreachable!() + } + } + } + + LoroValue::Map(ans.into()) + } + + pub fn get_deep_value_with_id(&mut self) -> LoroValue { + let roots = self.preferred_root_containers(); + let mut ans = FxHashMap::with_capacity_and_hasher(roots.len(), Default::default()); + for root_idx in roots { + let id = self.arena.idx_to_id(root_idx).unwrap(); + match id.clone() { + loro_common::ContainerID::Root { name, .. } => { + ans.insert( + name.to_string(), + self.get_container_deep_value_with_id(root_idx, Some(id)), + ); + } + loro_common::ContainerID::Normal { .. } => { + unreachable!() + } + } + } + + LoroValue::Map(ans.into()) + } + + pub(crate) fn preferred_root_containers(&mut self) -> Vec<ContainerIdx> { + let flag = self.store.load_root_containers(); + // Mergeable cids live in a private namespace and are logically children of a regular + // Map — they must not appear here. `top_level_root_containers` already excludes them, + // so this loop is O(top_level_roots) regardless of the number of mergeable cids. + let roots = self.arena.top_level_root_containers(flag); + let mut selected = FxHashMap::default(); + let mut names = Vec::new(); + + for idx in roots { + let Some(id) = self.arena.idx_to_id(idx) else { + continue; + }; + if !self.store.contains_id(&id) { + continue; + } + let Some(name) = self.root_container_name(idx) else { + continue; + }; + let is_empty = self.root_container_is_empty(idx); + match selected.entry(name.clone()) { + std::collections::hash_map::Entry::Vacant(entry) => { + names.push(name); + entry.insert((idx, is_empty)); + } + std::collections::hash_map::Entry::Occupied(mut entry) => { + let (_, selected_is_empty) = entry.get(); + // Keep the previous last-root-wins behavior, except an empty + // root should not hide a non-empty root with the same name. + if *selected_is_empty || !is_empty { + entry.insert((idx, is_empty)); + } + } + } + } + + names + .into_iter() + .filter_map(|name| selected.remove(&name).map(|(idx, _)| idx)) + .collect() + } + + pub(crate) fn preferred_root_container_idx_by_key( + &mut self, + root_index: &InternalString, + ) -> Option<ContainerIdx> { + let flag = self.store.load_root_containers(); + // Same reasoning as `preferred_root_containers`: only top-level roots are eligible. + let roots = self.arena.top_level_root_containers(flag); + let mut selected = None; + + for idx in roots { + let Some(id) = self.arena.idx_to_id(idx) else { + continue; + }; + if !self.store.contains_id(&id) { + continue; + } + let Some(name) = self.root_container_name(idx) else { + continue; + }; + if &name != root_index { + continue; + } + + let is_empty = self.root_container_is_empty(idx); + match selected { + None => selected = Some((idx, is_empty)), + Some((_, selected_is_empty)) => { + if selected_is_empty || !is_empty { + selected = Some((idx, is_empty)); + } + } + } + } + + selected.map(|(idx, _)| idx) + } + + fn root_container_name(&self, idx: ContainerIdx) -> Option<InternalString> { + match self.arena.idx_to_id(idx)? { + ContainerID::Root { name, .. } => Some(name), + ContainerID::Normal { .. } => None, + } + } + + fn root_container_is_empty(&mut self, idx: ContainerIdx) -> bool { + let value = self + .store + .get_value_ephemeral(idx) + .unwrap_or_else(|| idx.get_type().default_value()); + visible_container_value_is_empty(idx.get_type(), &value) + } + + pub fn get_all_container_value_flat(&mut self) -> LoroValue { + let mut map = FxHashMap::default(); + self.store.iter_and_decode_all().for_each(|c| { + let value = c.get_value(); + let cid = self.arena.idx_to_id(c.container_idx()).unwrap().to_string(); + map.insert(cid, value); + }); + + LoroValue::Map(map.into()) + } + + pub(crate) fn get_container_deep_value_with_id( + &mut self, + container: ContainerIdx, + id: Option<ContainerID>, + ) -> LoroValue { + let id = id.unwrap_or_else(|| self.arena.idx_to_id(container).unwrap()); + let Some(value) = self.store.get_value_ephemeral(container) else { + return container.get_type().default_value(); + }; + // The `cid` is the container id's Display string, the same form that the + // JS `container.id` getter returns (e.g. `cid:root-map:Map`, + // `cid:92@2311024965712536503:Map`). + let cid_str = LoroValue::String(id.to_string().into()); + match value { + LoroValue::Container(_) => unreachable!(), + LoroValue::List(mut list) => { + if container.get_type() == ContainerType::Tree { + get_meta_value(list.make_mut(), self); + } else { + if list.iter().all(|x| !x.is_container()) { + return LoroValue::Map( + (fx_map!( + "cid".into() => cid_str, + "value".into() => LoroValue::List(list) + )) + .into(), + ); + } + + let list_mut = list.make_mut(); + for item in list_mut.iter_mut() { + if item.is_container() { + let container = item.as_container().unwrap(); + let container_idx = self.arena.register_container(container); + let value = self.get_container_deep_value_with_id( + container_idx, + Some(container.clone()), + ); + *item = value; + } + } + } + LoroValue::Map( + (fx_map!( + "cid".into() => cid_str, + "value".into() => LoroValue::List(list) + )) + .into(), + ) + } + LoroValue::Map(mut map) => { + // A map's mergeable children are encoded as compact binary markers in the map's + // own value table (loro-dev/loro#759), so they are already present in `map` here. + // Derive the active children straight from that value — re-fetching the + // `MapState` would force the snapshot-backed container to decode and break the + // lazy-value invariant for roots. + let mergeable_children = self.mergeable_children_from_value(&id, &map); + + let map_mut = map.make_mut(); + for (_key, value) in map_mut.iter_mut() { + if value.is_container() { + let container = value.as_container().unwrap(); + let container_idx = self.arena.register_container(container); + let new_value = self.get_container_deep_value_with_id( + container_idx, + Some(container.clone()), + ); + *value = new_value; + } + } + // Replace each marker with the nested deep value of its resolved child, keyed + // under the same logical key. + for (key, cid) in mergeable_children { + let child_idx = self.arena.register_container(&cid); + let new_value = self.get_container_deep_value_with_id(child_idx, Some(cid)); + map_mut.insert(key.to_string(), new_value); + } + + LoroValue::Map( + (fx_map!( + "cid".into() => cid_str, + "value".into() => LoroValue::Map(map) + )) + .into(), + ) + } + _ => LoroValue::Map( + (fx_map!( + "cid".into() => cid_str, + "value".into() => value + )) + .into(), + ), + } + } + + pub fn get_container_deep_value(&mut self, container: ContainerIdx) -> LoroValue { + let Some(value) = self.store.get_value_ephemeral(container) else { + return container.get_type().default_value(); + }; + match value { + LoroValue::Container(_) => unreachable!(), + LoroValue::List(mut list) => { + if container.get_type() == ContainerType::Tree { + // Each tree node has an associated map container to represent + // the metadata of this node. When the user get the deep value, + // we need to add a field named `meta` to the tree node, + // whose value is deep value of map container. + get_meta_value(list.make_mut(), self); + } else { + if list.iter().all(|x| !x.is_container()) { + return LoroValue::List(list); + } + + let list_mut = list.make_mut(); + for item in list_mut.iter_mut() { + if item.is_container() { + let container = item.as_container().unwrap(); + let container_idx = self.arena.register_container(container); + let value = self.get_container_deep_value(container_idx); + *item = value; + } + } + } + LoroValue::List(list) + } + LoroValue::Map(mut map) => { + // A map's mergeable children are encoded as compact binary markers in the map's + // own value table (loro-dev/loro#759), so they are already present in `map` here. + // Derive the active children straight from that value — re-fetching the + // `MapState` would force the snapshot-backed container to decode and break the + // lazy-value invariant for roots. + let mergeable_children = self + .arena + .idx_to_id(container) + .map(|parent_id| self.mergeable_children_from_value(&parent_id, &map)) + .unwrap_or_default(); + + if mergeable_children.is_empty() && map.iter().all(|x| !x.1.is_container()) { + return LoroValue::Map(map); + } + + let map_mut = map.make_mut(); + for (_key, value) in map_mut.iter_mut() { + if value.is_container() { + let container = value.as_container().unwrap(); + let container_idx = self.arena.register_container(container); + let new_value = self.get_container_deep_value(container_idx); + *value = new_value; + } + } + // Replace each marker with the nested deep value of its resolved child, keyed + // under the same logical key. + for (key, cid) in mergeable_children { + let child_idx = self.arena.register_container(&cid); + let new_value = self.get_container_deep_value(child_idx); + map_mut.insert(key.to_string(), new_value); + } + LoroValue::Map(map) + } + _ => value, + } + } + + /// Get the deep value of a list/movable-list container's elements in the range + /// `[start, end)`. + /// + /// `start`/`end` are clamped to the list length; an empty or inverted range + /// returns an empty list. Container items inside the range are replaced by + /// their deep value: when `with_id` is true they become `{ cid, value }` nodes + /// (via [`Self::get_container_deep_value_with_id`]), otherwise their plain deep + /// value (via [`Self::get_container_deep_value`]). + pub(crate) fn get_list_range_deep_value( + &mut self, + container: ContainerIdx, + start: usize, + end: usize, + with_id: bool, + ) -> LoroValue { + let Some(value) = self.store.get_value_ephemeral(container) else { + return container.get_type().default_value(); + }; + let LoroValue::List(list) = value else { + return container.get_type().default_value(); + }; + + let len = list.len(); + let start = start.min(len); + let end = end.min(len); + if start >= end { + return LoroValue::List(Default::default()); + } + + let mut ans = Vec::with_capacity(end - start); + for item in list.iter().skip(start).take(end - start) { + if item.is_container() { + let cid = item.as_container().unwrap(); + let container_idx = self.arena.register_container(cid); + let value = if with_id { + self.get_container_deep_value_with_id(container_idx, Some(cid.clone())) + } else { + self.get_container_deep_value(container_idx) + }; + ans.push(value); + } else { + ans.push(item.clone()); + } + } + + LoroValue::List(ans.into()) + } + + pub(crate) fn get_all_alive_containers(&mut self) -> LoroResult<FxHashSet<ContainerID>> { + Ok(self + .get_all_alive_container_indices()? + .into_iter() + .map(|idx| self.arena.get_container_id(idx).unwrap()) + .collect()) + } + + fn get_all_alive_container_indices(&mut self) -> LoroResult<FxHashSet<ContainerIdx>> { + let roots = self.existing_retention_roots(); + self.get_all_alive_container_indices_from_roots(&roots, AliveWalk::Visible) + } + + /// Root containers that currently have a store entry. Uses a root-only + /// key scan (`load_roots`), so lazily imported docs stay lazy. + pub(crate) fn existing_retention_roots(&mut self) -> Vec<ContainerIdx> { + let flag = self.store.load_root_containers(); + self.arena + .root_containers(flag) + .into_iter() + .filter(|idx| { + let id = self.arena.get_container_id(*idx).unwrap(); + self.store.contains_id(&id) + }) + .collect() + } + + fn get_all_alive_container_indices_from_roots( + &mut self, + roots: &[ContainerIdx], + walk: AliveWalk, + ) -> LoroResult<FxHashSet<ContainerIdx>> { + let mut ans = FxHashSet::default(); + let mut to_visit = Vec::new(); + for &idx in roots { + let id = self.arena.get_container_id(idx).unwrap(); + let expected_parent = id + .parse_mergeable() + .map(|(parent_id, _, _)| self.arena.register_container(&parent_id)); + to_visit.push((idx, expected_parent)); + } + + while let Some((idx, expected_parent)) = to_visit.pop() { + if !ans.insert(idx) { + // The same child may be referenced by multiple parents. Even though its value was + // already traversed, every additional edge still has to agree with the encoded and + // registered parent. + self.validate_alive_parent(idx, expected_parent)?; + continue; + } + self.get_alive_children_of(idx, expected_parent, walk, &mut to_visit)?; + } + + Ok(ans) + } + + /// Keys of stored normal containers, created at or before `root_vv`, that the retention + /// walk ([`AliveWalk::Retention`] from every stored root) may not reach. A fast filter: an + /// empty result means filtering by the walk would remove nothing; otherwise the full walk + /// must decide, and only keys in both sets may be removed. + /// + /// Every stored container's parent is read from its encoded header, and only containers + /// that are the header parent of another stored container are decoded to list their + /// children; leaf containers (a big text, childless maps, tree metas) are never decoded. + /// A container counts as reached only through its header parent, so a header that lies + /// about the parent makes the container a candidate, and the full walk then rejects the + /// inconsistency instead of dropping the container. A child referenced by a container + /// other than its header parent is rejected here directly. + /// + /// Two kinds of entries are never candidates: + /// - Containers created after `root_vv`. A root state written with an overlay keeps an + /// empty entry for them, which nothing at the root references yet. + /// - Stored children of a reached container of an unknown (newer) type. Its value decodes + /// to `Null`, so neither this filter nor the full walk can list its children; they are + /// kept. An unknown type claimed only by a header parent that is not stored, or an + /// unreferenced unknown entry, gets no such protection. + pub(crate) fn unreached_stored_containers( + &mut self, + root_vv: &VersionVector, + ) -> LoroResult<Vec<bytes::Bytes>> { + let entries = self.store.get_kv_clone().scan_all_entries(); + // Stored normal containers: id -> (key, header parent). + let mut stored: FxHashMap<ContainerID, (bytes::Bytes, Option<ContainerID>)> = + FxHashMap::default(); + let mut stored_roots = Vec::new(); + let mut has_stored_children: FxHashSet<ContainerID> = FxHashSet::default(); + // Header children of unknown-type parents, whose references cannot be decoded. + let mut unknown_children: FxHashMap<ContainerID, Vec<ContainerID>> = FxHashMap::default(); + for (key, value) in entries { + let id = ContainerID::try_from_bytes(&key)?; + let (peer, counter) = match &id { + ContainerID::Root { .. } => { + stored_roots.push(id); + continue; + } + ContainerID::Normal { peer, counter, .. } => (*peer, *counter), + }; + if !root_vv.includes_id(ID::new(peer, counter)) { + continue; + } + let parent = ContainerWrapper::try_decode_parent(&value)?; + if let Some(parent) = &parent { + if parent.is_unknown() { + unknown_children + .entry(parent.clone()) + .or_default() + .push(id.clone()); + } + has_stored_children.insert(parent.clone()); + } + stored.insert(id, (key, parent)); + } + + // Roots are always retained; only those parenting a stored container need a visit. + let mut to_visit: Vec<ContainerID> = stored_roots + .into_iter() + .filter(|id| has_stored_children.contains(id)) + .collect(); + let mut retained: FxHashSet<ContainerID> = FxHashSet::default(); + while let Some(parent_id) = to_visit.pop() { + let children = if parent_id.is_unknown() { + unknown_children.remove(&parent_id).unwrap_or_default() + } else { + self.retained_child_refs(&parent_id)? + }; + for child_id in children { + let Some((_, header_parent)) = stored.get(&child_id) else { + // A root (always retained), a container created after the root, or an + // unstored, hence empty, child. + continue; + }; + if header_parent.as_ref() != Some(&parent_id) { + return Err(LoroError::DecodeError( + format!( + "container {child_id:?} is referenced by {parent_id:?}, but its snapshot state encodes parent {header_parent:?}" + ) + .into_boxed_str(), + )); + } + if has_stored_children.contains(&child_id) && !retained.contains(&child_id) { + to_visit.push(child_id.clone()); + } + retained.insert(child_id); + } + } + + Ok(stored + .into_iter() + .filter(|(id, _)| !retained.contains(id)) + .map(|(_, (key, _))| key) + .collect()) + } + + /// Normal-container children the retention walk follows from `id`: every node meta of a + /// tree (deleted nodes included, see [`AliveWalk::Retention`]) and the container values of + /// a map or list. Mergeable children are root containers, which are always retained, so + /// their markers are not resolved. Unlike `get_alive_children_of`, children are not + /// registered in the arena. + fn retained_child_refs(&mut self, id: &ContainerID) -> LoroResult<Vec<ContainerID>> { + let idx = self.arena.register_container(id); + if idx.get_type() == ContainerType::Tree { + return Ok(self + .store + .try_get_parent_and_tree_meta_ids_ephemeral(idx)? + .map(|(_, ids)| ids) + .unwrap_or_default()); + } + + let Some((_, value)) = self.store.try_get_parent_and_value_ephemeral(idx)? else { + return Ok(Vec::new()); + }; + let containers = |values: &mut dyn Iterator<Item = &LoroValue>| { + values + .filter_map(|v| v.as_container().cloned()) + .collect::<Vec<_>>() + }; + Ok(match &value { + LoroValue::Map(map) => containers(&mut map.values()), + LoroValue::List(list) => containers(&mut list.iter()), + _ => Vec::new(), + }) + } + + fn validate_alive_parent( + &mut self, + child_idx: ContainerIdx, + expected_parent: Option<ContainerIdx>, + ) -> LoroResult<()> { + let encoded_parent = self.store.get_parent_ephemeral(child_idx)?; + self.validate_alive_parent_with_encoded(child_idx, expected_parent, encoded_parent) + } + + fn validate_alive_parent_with_encoded( + &mut self, + child_idx: ContainerIdx, + expected_parent: Option<ContainerIdx>, + encoded_parent: Option<Option<ContainerID>>, + ) -> LoroResult<()> { + let child_id = self.arena.get_container_id(child_idx).unwrap(); + let expected_parent_id = expected_parent.and_then(|idx| self.arena.get_container_id(idx)); + if let Some(encoded_parent) = encoded_parent { + if encoded_parent != expected_parent_id { + return Err(LoroError::DecodeError( + format!( + "container {child_id:?} expects parent {expected_parent_id:?}, but its snapshot state encodes parent {encoded_parent:?}" + ) + .into_boxed_str(), + )); + } + } + + match self.arena.get_registered_parent(child_idx) { + Some(registered_parent) if registered_parent == expected_parent => {} + Some(registered_parent) => { + let registered_parent = + registered_parent.and_then(|idx| self.arena.get_container_id(idx)); + return Err(LoroError::DecodeError( + format!( + "container {child_id:?} expects parent {expected_parent_id:?}, but its registered parent is {registered_parent:?}" + ) + .into_boxed_str(), + )); + } + None => self.arena.set_parent(child_idx, expected_parent), + } + + Ok(()) + } + + fn register_alive_child( + &mut self, + parent_idx: ContainerIdx, + child_id: &ContainerID, + ans: &mut Vec<(ContainerIdx, Option<ContainerIdx>)>, + ) { + let child_idx = self.arena.register_container(child_id); + ans.push((child_idx, Some(parent_idx))); + } + + fn get_alive_children_of( + &mut self, + idx: ContainerIdx, + expected_parent: Option<ContainerIdx>, + walk: AliveWalk, + ans: &mut Vec<(ContainerIdx, Option<ContainerIdx>)>, + ) -> LoroResult<()> { + if walk == AliveWalk::Retention && idx.get_type() == ContainerType::Tree { + let Some((encoded_parent, meta_ids)) = + self.store.try_get_parent_and_tree_meta_ids_ephemeral(idx)? + else { + self.validate_alive_parent_with_encoded(idx, expected_parent, None)?; + return Ok(()); + }; + self.validate_alive_parent_with_encoded(idx, expected_parent, Some(encoded_parent))?; + for id in meta_ids.iter() { + self.register_alive_child(idx, id, ans); + } + return Ok(()); + } + + let Some((encoded_parent, value)) = self.store.try_get_parent_and_value_ephemeral(idx)? + else { + self.validate_alive_parent_with_encoded(idx, expected_parent, None)?; + return Ok(()); + }; + self.validate_alive_parent_with_encoded(idx, expected_parent, Some(encoded_parent))?; + + match value { + LoroValue::Container(_) => unreachable!(), + LoroValue::List(list) => { + if idx.get_type() == ContainerType::Tree { + // Each tree node has an associated map container to represent + // the metadata of this node. When the user get the deep value, + // we need to add a field named `meta` to the tree node, + // whose value is deep value of map container. + let mut list = list.unwrap(); + while let Some(node) = list.pop() { + let map = node.as_map().unwrap(); + let meta = map.get("meta").unwrap(); + let id = meta.as_container().unwrap(); + self.register_alive_child(idx, id, ans); + let children = map.get("children").unwrap(); + let children = children.as_list().unwrap(); + for child in children.iter() { + list.push(child.clone()); + } + } + } else { + for item in list.iter() { + if let LoroValue::Container(id) = item { + self.register_alive_child(idx, id, ans); + } + } + } + } + LoroValue::Map(map) => { + for (_key, value) in map.iter() { + if let LoroValue::Container(id) = value { + self.register_alive_child(idx, id, ans); + } + } + // Mergeable children are resolved from compact binary markers stored in this + // map's own value table (loro-dev/loro#759): the active child at each key is the + // deterministic cid for whichever marker the map's regular LWW resolved to. + // Derive them from the value we already fetched lazily above — re-reading the + // decoded `MapState` would force a snapshot-backed map to materialize its full + // state. Pull them in so alive-container walks (notably shallow snapshot export) + // include mergeable cids and don't filter their KV out by `retain_keys`. + let mergeable_cids: Vec<ContainerID> = self + .arena + .idx_to_id(idx) + .map(|parent_id| { + self.mergeable_children_from_value(&parent_id, &map) + .into_iter() + .map(|(_key, cid)| cid) + .collect() + }) + .unwrap_or_default(); + for cid in mergeable_cids { + self.register_alive_child(idx, &cid, ans); + } + } + _ => {} + } + + Ok(()) + } + + // Because we need to calculate path based on [DocState], so we cannot extract + // the event recorder to a separate module. + fn diffs_to_event(&mut self, diffs: Vec<InternalDocDiff<'_>>, from: Frontiers) -> DocDiff { + if diffs.is_empty() { + panic!("diffs is empty"); + } + + let triggered_by = diffs[0].by; + debug_assert!(diffs.iter().all(|x| x.by == triggered_by)); + let mut containers = FxHashMap::default(); + let to = (*diffs.last().unwrap().new_version).to_owned(); + let origin = diffs[0].origin.clone(); + for diff in diffs { + #[allow(clippy::unnecessary_to_owned)] + for container_diff in diff.diff.into_owned() { + let Some((last_container_diff, last_kept, _)) = + containers.get_mut(&container_diff.idx) + else { + if let Some(path) = self.get_path(container_diff.idx) { + containers.insert( + container_diff.idx, + (container_diff.diff, container_diff.kept, path), + ); + } else { + // if we cannot find the path to the container, the container must be overwritten afterwards. + // So we can ignore the diff from it. + let _container_id = self + .arena + .idx_to_id(container_diff.idx) + .map(|x| x.to_string()) + .unwrap_or_else(|| "unknown".to_string()); + #[cfg(feature = "logging")] + loro_common::warn!( + "⚠️ WARNING: ignore event because cannot find its path {:#?} container id:{}", + &container_diff, + _container_id + ); + } + + continue; + }; + // Compose in place. Cloning the accumulated diff here made a + // batch of N same-container fragments O(N^2) (each compose + // cloned the growing accumulator), which is hit whenever a + // subscriber is attached and many edits land on one container + // in a single event batch. + let prev = std::mem::take(last_container_diff); + if last_kept.is_some() || container_diff.kept.is_some() { + // Track the actual change next to the full-state revival. + let as_change = |kept: Option<KeptChange>, diff: &crate::event::DiffVariant| { + kept.unwrap_or_else(|| { + KeptChange::from_diff(diff.clone().into_external().unwrap()) + }) + }; + let prev_change = as_change(last_kept.take(), &prev); + let next_change = as_change(container_diff.kept.clone(), &container_diff.diff); + *last_kept = Some(prev_change.then(next_change)); + } + *last_container_diff = if container_diff.kept.is_some() { + // A full-state revival supersedes what the container showed before. + container_diff.diff + } else { + prev.compose(container_diff.diff).unwrap() + }; + } + } + let mut diff: Vec<_> = containers + .into_iter() + .map(|(container, (diff, kept, path))| { + let idx = container; + let id = self.arena.get_container_id(idx).unwrap(); + let is_unknown = id.is_unknown(); + + ContainerDiff { + id, + idx, + diff: diff.into_external().unwrap(), + is_unknown, + path, + kept, + } + }) + .collect(); + + // Sort by path length, so caller can apply the diff from the root to the leaf. + // Otherwise, the caller may use a wrong path to apply the diff. + + diff.sort_by_key(|x| { + ( + x.path.len(), + match &x.id { + ContainerID::Root { .. } => 0, + ContainerID::Normal { counter, .. } => *counter + 1, + }, + ) + }); + DocDiff { + from, + to, + origin, + by: triggered_by, + diff, + } + } + + pub(crate) fn get_reachable(&mut self, id: &ContainerID) -> bool { + if id.is_root() && !id.is_mergeable() { + return true; + } + + // If not registered yet, check KV presence for ordinary containers, then register lazily. + // Mergeable children can be active through a parent marker before they have their + // own KV state, so their reachability must be resolved by the logical edge walk below. + if self.arena.id_to_idx(id).is_none() { + if !id.is_mergeable() && !self.does_container_exist(id) { + return false; + } + self.arena.register_container(id); + } + + let mut idx = self.arena.id_to_idx(id).unwrap(); + loop { + let id = self.arena.idx_to_id(idx).unwrap(); + if let Some(parent_idx) = self.arena.get_parent(idx) { + if !self.contains_logical_child(parent_idx, &id) { + return false; + } + idx = parent_idx; + } else { + if id.is_root() && !id.is_mergeable() { + return true; + } + + return false; + } + } + } + + // the container may be override, so it may return None + pub(super) fn get_path(&mut self, idx: ContainerIdx) -> Option<Vec<(ContainerID, Index)>> { + let mut ans = Vec::new(); + let mut idx = idx; + loop { + let id = self.arena.idx_to_id(idx).unwrap(); + if let Some(parent_idx) = self.arena.get_parent(idx) { + let Some(prop) = self.get_logical_child_index(parent_idx, &id) else { + tracing::warn!("Missing in parent's children"); + return None; + }; + ans.push((id, prop)); + idx = parent_idx; + } else { + // this container may be deleted + if id.is_mergeable() { + tracing::info!(id = %id, "Missing parent - mergeable container is inactive"); + return None; + } + let Ok(prop) = id.clone().into_root() else { + let id = format!("{}", &id); + tracing::info!(?id, "Missing parent - container is deleted"); + return None; + }; + ans.push((id, Index::Key(prop.0))); + break; + } + } + + ans.reverse(); + + Some(ans) + } + + pub(crate) fn check_before_decode_snapshot(&self) -> LoroResult<()> { + if self.is_in_txn() { + return Err(LoroError::DecodeError( + "State is in txn".to_string().into_boxed_str(), + )); + } + + if !self.can_import_snapshot() { + return Err(LoroError::DecodeError( + "State is not empty, cannot import snapshot directly" + .to_string() + .into_boxed_str(), + )); + } + + Ok(()) + } + + /// Check whether two [DocState]s are the same. Panic if not. + /// + /// Compared to check equality on `get_deep_value`, this function also checks the equality on richtext + /// styles and states that are not reachable from the root. + /// + /// This is only used for test. + pub(crate) fn check_is_the_same(&mut self, other: &mut Self) { + fn get_entries_for_state( + arena: &SharedArena, + state: &mut State, + ) -> Option<(ContainerID, (ContainerIdx, LoroValue))> { + if state.is_state_empty() { + return None; + } + + let id = arena.idx_to_id(state.container_idx()).unwrap(); + let value = match state { + State::RichtextState(s) => s.get_richtext_value(), + _ => state.get_value(), + }; + if match &value { + LoroValue::List(l) => l.is_empty(), + LoroValue::Map(m) => m.is_empty(), + _ => false, + } { + return None; + } + #[cfg(feature = "counter")] + if id.container_type() == ContainerType::Counter { + if let LoroValue::Double(c) = value { + if c.abs() < f64::EPSILON { + return None; + } + } + } + + Some((id, (state.container_idx(), value))) + } + + let self_id_to_states: FxHashMap<ContainerID, (ContainerIdx, LoroValue)> = self + .store + .iter_and_decode_all() + .filter_map(|state: &mut State| { + let arena = &self.arena; + get_entries_for_state(arena, state) + }) + .collect(); + let mut other_id_to_states: FxHashMap<ContainerID, (ContainerIdx, LoroValue)> = other + .store + .iter_and_decode_all() + .filter_map(|state: &mut State| { + let arena = &other.arena; + get_entries_for_state(arena, state) + }) + .collect(); + for (id, (idx, this_value)) in self_id_to_states { + let (_, other_value) = match other_id_to_states.remove(&id) { + Some(x) => x, + None => { + panic!( + "id: {:?}, path: {:?} is missing, value={:?}", + id, + self.get_path(idx), + &this_value + ); + } + }; + + pretty_assertions::assert_eq!( + this_value, + other_value, + "[self!=other] id: {:?}, path: {:?}", + id, + self.get_path(idx) + ); + } + + if !other_id_to_states.is_empty() { + panic!("other has more states {:#?}", &other_id_to_states); + } + } + + pub fn create_state(&self, idx: ContainerIdx) -> State { + let config = &self.config; + let peer = self.peer.load(std::sync::atomic::Ordering::Relaxed); + create_state_(idx, config, peer) + } + + pub fn create_unknown_state(&self, idx: ContainerIdx) -> State { + State::UnknownState(UnknownState::new(idx)) + } + + pub fn get_relative_position(&mut self, pos: &Cursor, use_event_index: bool) -> Option<usize> { + let idx = self.arena.register_container(&pos.container); + let state = self.store.get_container_mut(idx)?; + if let Some(id) = pos.id { + match state { + State::ListState(s) => s.get_index_of_id(id), + State::RichtextState(s) => s.get_text_index_of_id(id, use_event_index), + State::MovableListState(s) => s.get_index_of_id(id), + State::MapState(_) | State::TreeState(_) | State::UnknownState(_) => unreachable!(), + #[cfg(feature = "counter")] + State::CounterState(_) => unreachable!(), + } + } else { + if matches!(pos.side, crate::cursor::Side::Left) { + return Some(0); + } + + match state { + State::ListState(s) => Some(s.len()), + State::RichtextState(s) => Some(if use_event_index { + s.len_event() + } else { + s.len_unicode() + }), + State::MovableListState(s) => Some(s.len()), + State::MapState(_) | State::TreeState(_) | State::UnknownState(_) => unreachable!(), + #[cfg(feature = "counter")] + State::CounterState(_) => unreachable!(), + } + } + } + + pub fn get_value_by_path(&mut self, path: &[Index]) -> Option<LoroValue> { + if path.is_empty() { + return None; + } + + enum CurContainer { + Container(ContainerIdx), + TreeNode { + tree: ContainerIdx, + node: Option<TreeID>, + }, + } + + let mut state_idx = { + let root_index = path[0].as_key()?; + CurContainer::Container(self.preferred_root_container_idx_by_key(root_index)?) + }; + + if path.len() == 1 { + if let CurContainer::Container(c) = state_idx { + let cid = self.arena.idx_to_id(c)?; + return Some(LoroValue::Container(cid)); + } + } + + let mut i = 1; + while i < path.len() - 1 { + let index = &path[i]; + match state_idx { + CurContainer::Container(idx) => { + let parent_id = self.arena.idx_to_id(idx); + let parent_state = self.store.get_container_mut(idx)?; + match parent_state { + State::ListState(l) => { + let Some(LoroValue::Container(c)) = l.get(*index.as_seq()?) else { + return None; + }; + state_idx = CurContainer::Container(self.arena.register_container(c)); + } + State::MovableListState(l) => { + let Some(LoroValue::Container(c)) = + l.get(*index.as_seq()?, IndexType::ForUser) + else { + return None; + }; + state_idx = CurContainer::Container(self.arena.register_container(c)); + } + State::MapState(m) => { + let key = index.as_key()?; + let value = m.get(key)?; + let c = match value { + LoroValue::Container(c) => c.clone(), + value => { + let parent_id = parent_id?; + let kind = loro_common::parse_mergeable_marker( + &parent_id, key, value, + )?; + ContainerID::new_mergeable(&parent_id, key, kind) + } + }; + state_idx = CurContainer::Container(self.arena.register_container(&c)); + } + State::RichtextState(_) => return None, + State::TreeState(_) => { + state_idx = CurContainer::TreeNode { + tree: idx, + node: None, + }; + continue; + } + #[cfg(feature = "counter")] + State::CounterState(_) => return None, + // Unknown containers are opaque to this version; the + // path simply has no match below them. + State::UnknownState(_) => return None, + } + } + CurContainer::TreeNode { tree, node } => match index { + Index::Key(internal_string) => { + let node = node?; + let idx = self + .arena + .register_container(&node.associated_meta_container()); + let map = self.store.get_container(idx)?; + let Some(LoroValue::Container(c)) = + map.as_map_state().unwrap().get(internal_string) + else { + return None; + }; + + state_idx = CurContainer::Container(self.arena.register_container(c)); + } + Index::Seq(i) => { + let tree_state = + self.store.get_container_mut(tree)?.as_tree_state().unwrap(); + let parent: TreeParentId = if let Some(node) = node { + node.into() + } else { + TreeParentId::Root + }; + let child = tree_state.get_children(&parent)?.nth(*i)?; + state_idx = CurContainer::TreeNode { + tree, + node: Some(child), + }; + } + Index::Node(tree_id) => { + let tree_state = + self.store.get_container_mut(tree)?.as_tree_state().unwrap(); + if tree_state.parent(tree_id).is_some() { + state_idx = CurContainer::TreeNode { + tree, + node: Some(*tree_id), + } + } else { + return None; + } + } + }, + } + i += 1; + } + + let parent_idx = match state_idx { + CurContainer::Container(container_idx) => container_idx, + CurContainer::TreeNode { tree, node } => { + if let Some(node) = node { + self.arena + .register_container(&node.associated_meta_container()) + } else { + tree + } + } + }; + + let index = path.last().unwrap(); + let parent_id = self.arena.idx_to_id(parent_idx); + let parent_state = self.store.get_or_create_mut(parent_idx); + let value: LoroValue = match parent_state { + State::ListState(l) => l.get(*index.as_seq()?).cloned()?, + State::MovableListState(l) => l.get(*index.as_seq()?, IndexType::ForUser).cloned()?, + State::MapState(m) => { + if let Some(key) = index.as_key() { + let value = m.get(key).cloned()?; + if let Some(parent_id) = &parent_id { + if let Some(kind) = + loro_common::parse_mergeable_marker(parent_id, key, &value) + { + let cid = ContainerID::new_mergeable(parent_id, key, kind); + LoroValue::Container(cid) + } else { + value + } + } else { + value + } + } else if let CurContainer::TreeNode { tree, node } = state_idx { + match index { + Index::Seq(index) => { + let tree_state = + self.store.get_container_mut(tree)?.as_tree_state().unwrap(); + let parent: TreeParentId = if let Some(node) = node { + node.into() + } else { + TreeParentId::Root + }; + let child = tree_state.get_children(&parent)?.nth(*index)?; + child.associated_meta_container().into() + } + Index::Node(id) => id.associated_meta_container().into(), + _ => return None, + } + } else { + return None; + } + } + State::RichtextState(s) => { + let s = s.to_string_mut(); + s.chars() + .nth(*index.as_seq()?) + .map(|c| c.to_string().into())? + } + State::TreeState(_) => { + let id = index.as_node()?; + let cid = id.associated_meta_container(); + cid.into() + } + #[cfg(feature = "counter")] + // Leaf containers have no addressable children; the path has no match. + State::CounterState(_) => return None, + State::UnknownState(_) => return None, + }; + + Some(value) + } + + pub(crate) fn shallow_root_store(&self) -> Option<&Arc<GcStore>> { + self.store.shallow_root_store() + } +} + +fn create_state_(idx: ContainerIdx, config: &Configure, peer: u64) -> State { + match idx.get_type() { + ContainerType::Map => State::MapState(Box::new(MapState::new(idx))), + ContainerType::List => State::ListState(Box::new(ListState::new(idx))), + ContainerType::Text => State::RichtextState(Box::new(RichtextState::new( + idx, + config.text_style_config.clone(), + ))), + ContainerType::Tree => State::TreeState(Box::new(TreeState::new(idx, peer))), + ContainerType::MovableList => State::MovableListState(Box::new(MovableListState::new(idx))), + #[cfg(feature = "counter")] + ContainerType::Counter => { + State::CounterState(Box::new(counter_state::CounterState::new(idx))) + } + ContainerType::Unknown(_) => State::UnknownState(UnknownState::new(idx)), + } +} + +fn is_mergeable(arena: &SharedArena, idx: ContainerIdx) -> bool { + arena.idx_to_id(idx).is_some_and(|id| id.is_mergeable()) +} + +fn trigger_on_new_container( + state_diff: &Diff, + mut listener: impl FnMut(ContainerIdx), + arena: &SharedArena, +) { + match state_diff { + Diff::List(list) => { + for delta in list.iter() { + if let DeltaItem::Replace { + value, + attr, + delete: _, + } = delta + { + if attr.from_move { + continue; + } + + for v in value.iter() { + if let ValueOrHandler::Handler(h) = v { + let idx = h.container_idx(); + listener(idx); + } + } + } + } + } + Diff::Map(map) => { + for (_, v) in map.updated.iter() { + if let Some(ValueOrHandler::Handler(h)) = &v.value { + let idx = h.container_idx(); + listener(idx); + } + } + } + Diff::Tree(tree) => { + for item in tree.iter() { + if matches!(item.action, TreeExternalDiff::Create { .. }) { + let id = item.target.associated_meta_container(); + // Ensure registration instead of assuming it's already in arena + listener(arena.register_container(&id)); + } + } + } + _ => {} + }; +} + +#[derive(Default, Clone)] +pub(crate) struct EventRecorder { + recording_diff: bool, + // A batch of diffs will be converted to a event when + // they cannot be merged with the next diff. + diffs: Vec<InternalDocDiff<'static>>, + events: Vec<DocDiff>, + diff_start_version: Option<Frontiers>, +} + +impl EventRecorder { + #[allow(unused)] + pub fn new() -> Self { + Self::default() + } +} + +#[test] +fn test_size() { + println!("Size of State = {}", std::mem::size_of::<State>()); + println!("Size of MapState = {}", std::mem::size_of::<MapState>()); + println!("Size of ListState = {}", std::mem::size_of::<ListState>()); + println!( + "Size of TextState = {}", + std::mem::size_of::<RichtextState>() + ); + println!("Size of TreeState = {}", std::mem::size_of::<TreeState>()); +} diff --git a/vendor/loro-internal/src/state/AGENTS.md b/vendor/loro-internal/src/state/AGENTS.md new file mode 100644 index 0000000..a32a8a7 --- /dev/null +++ b/vendor/loro-internal/src/state/AGENTS.md @@ -0,0 +1,68 @@ +# State Guidelines + +This module owns materialized document state, container stores, diff application, +checkout/replay behavior, deep/shallow values, and mergeable container +visibility. Read +[../../../../context/mergeable-containers.md](../../../../context/mergeable-containers.md) +before changing mergeable child behavior. + +## Local Entry Points + +- `value_decode.rs`: iterative postcard map/list value reader. Its layout, + destruction and WASM conversion contracts are in + [../../../../context/deep-value-stack-safety.md](../../../../context/deep-value-stack-safety.md). + +- `../state.rs`: `DocState`, checkout/path/deep-value traversal, state replay, + lifecycle, and alive-container discovery. +- `container_store/`: persisted KV-backed container snapshots and + `ContainerWrapper` encoding. The decoded-value cache in `InnerStore` is + bounded and evicted wrappers must stay re-creatable from KV; read + [../../../../context/container-value-cache.md](../../../../context/container-value-cache.md) + before changing read/caching paths there. +- `map_state.rs`, `list_state.rs`, `richtext_state.rs`, `tree_state.rs`, + `movable_list_state.rs`, `counter_state.rs`: per-container state and snapshot + codecs. `richtext_state.rs` also hosts `redact_dead_style_values`, used by + shallow-snapshot export; read + [../../../../context/shallow-snapshot-style-redaction.md](../../../../context/shallow-snapshot-style-redaction.md) + before changing the richtext snapshot codec or that pass. + `tree_state.rs` builds tree events two ways depending on the diff mode: + [../../../../context/tree-events.md](../../../../context/tree-events.md). + Its depth-independent traversals, snapshot order, and nested result disposal: + [../../../../context/tree-depth.md](../../../../context/tree-depth.md). + `movable_list_state.rs` import validation and the Checkout-mode fallback for + moves of deleted elements, plus the List/Text `validate_diff` bounds checks: + [../../../../context/movable-list-op-validation.md](../../../../context/movable-list-op-validation.md). +- `mergeable.rs`: logical child edge resolution for mergeable containers. +- `dead_containers_cache.rs`: dead/alive tracking. Map/list deletions are + final; tree and movable-list ones are dropped whenever a move could revive + them; mergeable ones are never cached: + [../../../../context/dead-container-cache.md](../../../../context/dead-container-cache.md). + A failed import keeps its arena indices, so store entries and caches keyed + by `ContainerIdx` stay valid; it clears this cache: + [../../../../context/failed-import-arena-indices.md](../../../../context/failed-import-arena-indices.md). +- `unknown_state.rs` and `../diff_calc/unknown.rs`: forward compatibility for + unknown container types. They are never created locally; the `apply_diff` + pre-check and undo rules are in + [../../../../context/unknown-containers.md](../../../../context/unknown-containers.md). + +## Mergeable Rules + +- `MapHandler::ensure_mergeable_*` writes a compact marker into the parent map + and returns a handler for a deterministic `ContainerID`. +- The parent map marker, not "child has ops", decides whether a mergeable child + is visible. +- Non-mergeable occupants must block `ensure_mergeable_*`; same-kind marker + writes are idempotent; different-kind marker writes are deliberate kind + changes. +- Snapshot and shallow snapshot retention must preserve hidden losing-kind + mergeable state. + +## Validation + +- `cargo test -p loro-internal --test mergeable_cid_encoding` +- `cargo test -p loro-internal --test mergeable_container` +- `cargo test -p loro-internal import_atomicity` if import or rollback is involved. + +`container_tree.rs` traverses ephemeral shallow values into a sink. Container identity +comes from CRDT edges, including mergeable markers and Tree metadata; ordinary +values remain opaque. See [bulk reads](../../../../context/wasm-container-tree.md). diff --git a/vendor/loro-internal/src/state/CLAUDE.md b/vendor/loro-internal/src/state/CLAUDE.md new file mode 100644 index 0000000..a32a8a7 --- /dev/null +++ b/vendor/loro-internal/src/state/CLAUDE.md @@ -0,0 +1,68 @@ +# State Guidelines + +This module owns materialized document state, container stores, diff application, +checkout/replay behavior, deep/shallow values, and mergeable container +visibility. Read +[../../../../context/mergeable-containers.md](../../../../context/mergeable-containers.md) +before changing mergeable child behavior. + +## Local Entry Points + +- `value_decode.rs`: iterative postcard map/list value reader. Its layout, + destruction and WASM conversion contracts are in + [../../../../context/deep-value-stack-safety.md](../../../../context/deep-value-stack-safety.md). + +- `../state.rs`: `DocState`, checkout/path/deep-value traversal, state replay, + lifecycle, and alive-container discovery. +- `container_store/`: persisted KV-backed container snapshots and + `ContainerWrapper` encoding. The decoded-value cache in `InnerStore` is + bounded and evicted wrappers must stay re-creatable from KV; read + [../../../../context/container-value-cache.md](../../../../context/container-value-cache.md) + before changing read/caching paths there. +- `map_state.rs`, `list_state.rs`, `richtext_state.rs`, `tree_state.rs`, + `movable_list_state.rs`, `counter_state.rs`: per-container state and snapshot + codecs. `richtext_state.rs` also hosts `redact_dead_style_values`, used by + shallow-snapshot export; read + [../../../../context/shallow-snapshot-style-redaction.md](../../../../context/shallow-snapshot-style-redaction.md) + before changing the richtext snapshot codec or that pass. + `tree_state.rs` builds tree events two ways depending on the diff mode: + [../../../../context/tree-events.md](../../../../context/tree-events.md). + Its depth-independent traversals, snapshot order, and nested result disposal: + [../../../../context/tree-depth.md](../../../../context/tree-depth.md). + `movable_list_state.rs` import validation and the Checkout-mode fallback for + moves of deleted elements, plus the List/Text `validate_diff` bounds checks: + [../../../../context/movable-list-op-validation.md](../../../../context/movable-list-op-validation.md). +- `mergeable.rs`: logical child edge resolution for mergeable containers. +- `dead_containers_cache.rs`: dead/alive tracking. Map/list deletions are + final; tree and movable-list ones are dropped whenever a move could revive + them; mergeable ones are never cached: + [../../../../context/dead-container-cache.md](../../../../context/dead-container-cache.md). + A failed import keeps its arena indices, so store entries and caches keyed + by `ContainerIdx` stay valid; it clears this cache: + [../../../../context/failed-import-arena-indices.md](../../../../context/failed-import-arena-indices.md). +- `unknown_state.rs` and `../diff_calc/unknown.rs`: forward compatibility for + unknown container types. They are never created locally; the `apply_diff` + pre-check and undo rules are in + [../../../../context/unknown-containers.md](../../../../context/unknown-containers.md). + +## Mergeable Rules + +- `MapHandler::ensure_mergeable_*` writes a compact marker into the parent map + and returns a handler for a deterministic `ContainerID`. +- The parent map marker, not "child has ops", decides whether a mergeable child + is visible. +- Non-mergeable occupants must block `ensure_mergeable_*`; same-kind marker + writes are idempotent; different-kind marker writes are deliberate kind + changes. +- Snapshot and shallow snapshot retention must preserve hidden losing-kind + mergeable state. + +## Validation + +- `cargo test -p loro-internal --test mergeable_cid_encoding` +- `cargo test -p loro-internal --test mergeable_container` +- `cargo test -p loro-internal import_atomicity` if import or rollback is involved. + +`container_tree.rs` traverses ephemeral shallow values into a sink. Container identity +comes from CRDT edges, including mergeable markers and Tree metadata; ordinary +values remain opaque. See [bulk reads](../../../../context/wasm-container-tree.md). diff --git a/vendor/loro-internal/src/state/analyzer.rs b/vendor/loro-internal/src/state/analyzer.rs new file mode 100644 index 0000000..6f757b1 --- /dev/null +++ b/vendor/loro-internal/src/state/analyzer.rs @@ -0,0 +1,95 @@ +use crate::{change::Timestamp, LoroDoc}; +use loro_common::ContainerID; +use rle::HasLength; +use rustc_hash::FxHashMap; + +#[derive(Debug, Clone)] +pub struct DocAnalysis { + pub containers: FxHashMap<ContainerID, ContainerAnalysisInfo>, +} + +#[derive(Debug, Clone)] +pub struct ContainerAnalysisInfo { + pub size: u32, + pub dropped: bool, + pub depth: u32, + pub ops_num: u32, + pub last_edit_time: Timestamp, +} + +impl DocAnalysis { + pub fn analyze(doc: &LoroDoc) -> Self { + let mut ops_nums = FxHashMap::default(); + let mut last_edit_time = FxHashMap::default(); + { + let oplog = doc.oplog().lock(); + oplog.change_store().visit_all_changes(&mut |c| { + for op in c.ops().iter() { + let idx = op.container; + let info = ops_nums.entry(idx).or_insert(0); + *info += op.atom_len(); + + let time = last_edit_time.entry(idx).or_insert(c.timestamp()); + if *time < c.timestamp() { + *time = c.timestamp(); + } + } + }); + } + + let mut containers = FxHashMap::default(); + let mut state = doc.app_state().lock(); + let alive_containers = state + .get_all_alive_containers() + .expect("analyzing a valid document should resolve its container hierarchy"); + for (idx, c) in state.iter_all_containers_mut() { + let ops_num = ops_nums.get(&idx).unwrap_or(&0); + let id = doc.arena().get_container_id(idx).unwrap(); + let dropped = !alive_containers.contains(&id); + containers.insert( + id, + ContainerAnalysisInfo { + depth: c.depth() as u32, + dropped, + size: c.encode().len() as u32, + ops_num: *ops_num as u32, + last_edit_time: *last_edit_time.get(&idx).unwrap_or(&0), + }, + ); + } + + Self { containers } + } + + #[allow(unused)] + pub fn len(&self) -> usize { + self.containers.len() + } + + #[allow(unused)] + #[must_use] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub fn dropped_len(&self) -> usize { + self.containers + .iter() + .filter(|(_, info)| info.dropped) + .count() + } + + pub fn tiny_container_len(&self) -> usize { + self.containers + .iter() + .filter(|(_, info)| info.size < 128) + .count() + } + + pub fn large_container_len(&self) -> usize { + self.containers + .iter() + .filter(|(_, info)| info.size >= 1024) + .count() + } +} diff --git a/vendor/loro-internal/src/state/container_store.rs b/vendor/loro-internal/src/state/container_store.rs new file mode 100644 index 0000000..f5bb517 --- /dev/null +++ b/vendor/loro-internal/src/state/container_store.rs @@ -0,0 +1,1186 @@ +use super::{ContainerCreationContext, State}; +use crate::arena::LoadAllFlag; +use crate::sync::{AtomicU64, Mutex}; +use crate::{ + arena::SharedArena, configure::Configure, container::idx::ContainerIdx, + utils::kv_wrapper::KvWrapper, version::Frontiers, +}; +use bytes::Bytes; +use inner_store::InnerStore; +use loro_common::{ContainerID, InternalString, LoroResult, LoroValue}; +use once_cell::sync::OnceCell; +use std::sync::Arc; + +pub(crate) use container_wrapper::ContainerWrapper; + +mod container_wrapper; +mod inner_store; + +/// Encoding Schema for Container Store +/// +/// KV-Store: +/// - Key: Encoded Container ID +/// - Value: Encoded Container State +/// +/// ─ ─ ─ ─ ─ ─ ─ For Each Container Type ─ ─ ─ ─ ─ ─ ─ ─ +/// +/// ┌────────────────┬──────────────────────────────────┐ +/// │ u16 Depth │ ParentID │ +/// └────────────────┴──────────────────────────────────┘ +/// ┌───────────────────────────────────────────────────┐ +/// │ ┌───────────────────────────────────────────────┐ │ +/// │ │ Into<LoroValue> │ │ +/// │ └───────────────────────────────────────────────┘ │ +/// │ │ +/// │ Container Specific Encode │ +/// │ │ +/// │ │ +/// │ │ +/// │ │ +/// └───────────────────────────────────────────────────┘ +pub(crate) struct ContainerStore { + arena: SharedArena, + store: InnerStore, + shallow_root_store: Option<Arc<GcStore>>, + conf: Configure, + peer: Arc<AtomicU64>, +} + +pub(crate) const FRONTIERS_KEY: &[u8] = b"fr"; +impl std::fmt::Debug for ContainerStore { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ContainerStore") + .field("store", &self.store) + .finish() + } +} + +#[derive(Debug)] +pub(crate) struct GcStore { + pub shallow_root_frontiers: Frontiers, + pub encoded_state_bytes: Bytes, + pub store: Mutex<InnerStore>, + /// This root with the containers the retention walk does not reach removed, + /// computed on the first export that reuses the root (see + /// `shallow_snapshot::prune_cached_root`). `None` means nothing is removed, + /// which holds unless the root came from an exporter that kept containers + /// deleted before the root. The root never changes, so neither does this. + pub pruned_root: OnceCell<Option<PrunedRootState>>, +} + +/// A cached shallow root state with unretained containers removed. +#[derive(Debug)] +pub(crate) struct PrunedRootState { + /// Encoded pruned root state, including the frontiers key. + pub state_bytes: Bytes, + /// Keys removed from the cached root. + pub removed: Vec<Bytes>, +} + +macro_rules! ctx { + ($self:expr) => { + ContainerCreationContext { + configure: &$self.conf, + peer: $self.peer.load(std::sync::atomic::Ordering::Relaxed), + } + }; +} + +impl ContainerStore { + pub fn new(arena: SharedArena, conf: Configure, peer: Arc<AtomicU64>) -> Self { + ContainerStore { + store: InnerStore::new(arena.clone(), conf.clone()), + arena, + conf, + shallow_root_store: None, + peer, + } + } + + pub fn can_import_snapshot(&self) -> bool { + if self.shallow_root_store.is_some() { + return false; + } + + self.store.can_import_snapshot() + } + + pub(crate) fn set_decoded_value_cache_limit(&mut self, limit: usize) { + self.conf.set_decoded_value_cache_limit(limit); + self.store.trim_value_cache(); + if let Some(root) = &self.shallow_root_store { + root.store.lock().trim_value_cache(); + } + } + + pub fn get_container_mut(&mut self, idx: ContainerIdx) -> Option<&mut State> { + self.store + .get_mut(idx) + .map(|x| x.get_state_mut(idx, ctx!(self))) + } + + #[allow(unused)] + pub fn get_container(&mut self, idx: ContainerIdx) -> Option<&State> { + self.store + .get_mut(idx) + .map(|x| x.get_state(idx, ctx!(self))) + } + + pub fn shallow_root_store(&self) -> Option<&Arc<GcStore>> { + self.shallow_root_store.as_ref() + } + + pub fn get_value(&mut self, idx: ContainerIdx) -> Option<LoroValue> { + self.store + .with_container_for_read(idx, |c| c.get_value(idx, ctx!(self))) + } + + pub(crate) fn get_value_ephemeral(&mut self, idx: ContainerIdx) -> Option<LoroValue> { + self.try_get_value_ephemeral(idx) + .expect("snapshot-backed container should decode") + } + + pub(crate) fn try_get_value_ephemeral( + &mut self, + idx: ContainerIdx, + ) -> LoroResult<Option<LoroValue>> { + self.store.try_get_value_ephemeral(idx, ctx!(self)) + } + + pub(crate) fn try_get_parent_and_value_ephemeral( + &mut self, + idx: ContainerIdx, + ) -> LoroResult<Option<(Option<ContainerID>, LoroValue)>> { + self.store + .try_get_parent_and_value_ephemeral(idx, ctx!(self)) + } + + pub(crate) fn try_get_parent_and_tree_meta_ids_ephemeral( + &mut self, + idx: ContainerIdx, + ) -> LoroResult<Option<(Option<ContainerID>, Vec<ContainerID>)>> { + self.store + .try_get_parent_and_tree_meta_ids_ephemeral(idx, ctx!(self)) + } + + pub(crate) fn get_parent_ephemeral( + &mut self, + idx: ContainerIdx, + ) -> LoroResult<Option<Option<ContainerID>>> { + self.store.get_parent_ephemeral(idx) + } + + pub fn map_get(&mut self, idx: ContainerIdx, key: &str) -> Option<LoroValue> { + self.store + .with_container_for_read(idx, |c| c.map_get(idx, ctx!(self), key))? + } + + pub fn map_len(&mut self, idx: ContainerIdx) -> usize { + self.store + .with_container_for_read(idx, |c| c.map_len(idx, ctx!(self))) + .unwrap_or(0) + } + + pub fn map_keys(&mut self, idx: ContainerIdx) -> Vec<InternalString> { + self.store + .with_container_for_read(idx, |c| c.map_keys(idx, ctx!(self))) + .unwrap_or_default() + } + + pub fn map_entries(&mut self, idx: ContainerIdx) -> Vec<(InternalString, LoroValue)> { + self.store + .with_container_for_read(idx, |c| c.map_entries(idx, ctx!(self))) + .unwrap_or_default() + } + + pub fn list_get(&mut self, idx: ContainerIdx, index: usize) -> Option<LoroValue> { + self.store + .with_container_for_read(idx, |c| c.list_get(idx, ctx!(self), index))? + } + + pub fn list_len(&mut self, idx: ContainerIdx) -> usize { + self.store + .with_container_for_read(idx, |c| c.list_len(idx, ctx!(self))) + .unwrap_or(0) + } + + pub fn list_values(&mut self, idx: ContainerIdx) -> Vec<LoroValue> { + self.store + .with_container_for_read(idx, |c| c.list_values(idx, ctx!(self))) + .unwrap_or_default() + } + + pub fn text_unicode_len(&mut self, idx: ContainerIdx) -> Option<usize> { + self.store + .with_container_for_read(idx, |c| c.text_unicode_len(idx, ctx!(self)))? + } + + pub fn text_utf16_len(&mut self, idx: ContainerIdx) -> Option<usize> { + self.store + .with_container_for_read(idx, |c| c.text_utf16_len(idx, ctx!(self)))? + } + + pub fn text_utf8_len(&mut self, idx: ContainerIdx) -> Option<usize> { + self.store + .with_container_for_read(idx, |c| c.text_utf8_len(idx, ctx!(self)))? + } + + pub fn has_decoded_state(&mut self, idx: ContainerIdx) -> bool { + self.store.has_decoded_state(idx) + } + + pub fn encode(&mut self) -> Bytes { + self.store.encode() + } + + pub(crate) fn flush(&mut self) { + self.store.flush() + } + + pub fn shallow_root_frontiers(&self) -> Option<&Frontiers> { + self.shallow_root_store + .as_ref() + .map(|x| &x.shallow_root_frontiers) + } + + pub(crate) fn shallow_root_state_for_export(&self) -> Option<(Bytes, KvWrapper)> { + let shallow_root = self.shallow_root_store.as_ref()?; + let shallow_root_kv = shallow_root.store.lock().get_kv_clone(); + Some((shallow_root.encoded_state_bytes.clone(), shallow_root_kv)) + } + + pub(crate) fn decode(&mut self, bytes: Bytes) -> LoroResult<Option<Frontiers>> { + self.store.decode(bytes) + } + + pub(crate) fn decode_gc( + &mut self, + shallow_bytes: Bytes, + start_frontiers: Frontiers, + config: Configure, + ) -> LoroResult<Option<Frontiers>> { + assert!(self.shallow_root_store.is_none()); + let mut inner = InnerStore::new(self.arena.clone(), config); + let encoded_state_bytes = shallow_bytes.clone(); + let f = inner.decode(shallow_bytes)?; + let encoded_state_bytes = if f.as_ref() == Some(&start_frontiers) { + encoded_state_bytes + } else { + let kv = inner.get_kv_clone(); + kv.insert(FRONTIERS_KEY, start_frontiers.encode().into()); + kv.export() + }; + self.shallow_root_store = Some(Arc::new(GcStore { + shallow_root_frontiers: start_frontiers, + encoded_state_bytes, + store: Mutex::new(inner), + pruned_root: OnceCell::new(), + })); + Ok(f) + } + + pub(crate) fn decode_state_by_two_bytes( + &mut self, + shallow_bytes: Bytes, + state_bytes: Bytes, + ) -> LoroResult<()> { + self.store + .decode_twice(shallow_bytes.clone(), state_bytes)?; + Ok(()) + } + + pub fn iter_and_decode_all(&mut self) -> impl Iterator<Item = &mut State> { + self.store.iter_all_containers_mut().map(|(idx, v)| { + v.get_state_mut( + idx, + ContainerCreationContext { + configure: &self.conf, + peer: self.peer.load(std::sync::atomic::Ordering::Relaxed), + }, + ) + }) + } + + pub fn get_kv_clone(&self) -> KvWrapper { + self.store.get_kv_clone() + } + + pub fn contains_id(&mut self, id: &ContainerID) -> bool { + self.store.contains_id(id) + } + + pub fn iter_all_containers( + &mut self, + ) -> impl Iterator<Item = (ContainerIdx, &mut ContainerWrapper)> { + self.store.iter_all_containers_mut() + } + + pub fn iter_all_container_ids(&mut self) -> impl Iterator<Item = ContainerID> + '_ { + self.store.iter_all_container_ids() + } + + pub fn load_root_containers(&mut self) -> LoadAllFlag { + self.store.load_roots(); + LoadAllFlag + } + + pub(super) fn begin_created_journal(&mut self) { + self.store.begin_created_journal(); + } + + pub(super) fn take_created_journal(&mut self) -> Vec<ContainerIdx> { + self.store.take_created_journal() + } + + pub(super) fn remove_created(&mut self, created: &[ContainerIdx]) { + self.store.remove_created(created); + } + + pub(super) fn get_or_create_mut(&mut self, idx: ContainerIdx) -> &mut State { + self.store + .get_or_insert_with(idx, || { + let state = super::create_state_( + idx, + &self.conf, + self.peer.load(std::sync::atomic::Ordering::Relaxed), + ); + ContainerWrapper::new(state, &self.arena) + }) + .get_state_mut(idx, ctx!(self)) + } + + pub(crate) fn ensure_container(&mut self, id: &loro_common::ContainerID) { + let idx = self.arena.register_container(id); + self.store.ensure_container(idx, || { + let state = super::create_state_( + idx, + &self.conf, + self.peer.load(std::sync::atomic::Ordering::Relaxed), + ); + ContainerWrapper::new(state, &self.arena) + }); + } + + pub(super) fn get_or_create_imm(&mut self, idx: ContainerIdx) -> &State { + self.store + .get_or_insert_with(idx, || { + let state = super::create_state_( + idx, + &self.conf, + self.peer.load(std::sync::atomic::Ordering::Relaxed), + ); + ContainerWrapper::new(state, &self.arena) + }) + .get_state(idx, ctx!(self)) + } + + pub(crate) fn fork( + &mut self, + arena: SharedArena, + peer: Arc<AtomicU64>, + config: Configure, + ) -> ContainerStore { + ContainerStore { + store: self.store.fork(arena.clone(), &config), + arena, + conf: config, + peer, + shallow_root_store: None, + } + } + + #[allow(unused)] + fn check_eq_after_parsing(&mut self, other: &mut ContainerStore) { + for (idx, container) in self.store.iter_all_containers_mut() { + let id = self.arena.get_container_id(idx).unwrap(); + let other_idx = other.arena.register_container(&id); + let other_container = other + .store + .get_mut(other_idx) + .expect("container not found on other store"); + let other_id = other.arena.get_container_id(other_idx).unwrap(); + assert_eq!( + id, other_id, + "container id mismatch {:?} {:?}", + id, other_id + ); + assert_eq!( + container.get_value(idx, ctx!(self)), + other_container.get_value(other_idx, ctx!(other)), + "value mismatch" + ); + + if container.encode() != other_container.encode() { + panic!( + "container mismatch Origin: {:#?}, New: {:#?}", + &container, &other_container + ); + } + + other_container + .decode_state(other_idx, ctx!(other)) + .unwrap(); + other_container.clear_bytes(); + if container.encode() != other_container.encode() { + panic!( + "container mismatch Origin: {:#?}, New: {:#?}", + &container, &other_container + ); + } + } + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::{ + configure::DEFAULT_DECODED_VALUE_CACHE_LIMIT, cursor::PosType, handler::HandlerTrait, + state::TreeParentId, ContainerType, ListHandler, LoroDoc, MapHandler, MovableListHandler, + }; + + fn decode_container_store(bytes: Bytes) -> ContainerStore { + let mut new_store = ContainerStore::new( + SharedArena::new(), + Configure::default(), + Arc::new(AtomicU64::new(233)), + ); + + new_store.decode(bytes).unwrap(); + new_store + } + + fn init_doc() -> LoroDoc { + let doc = LoroDoc::new(); + doc.start_auto_commit(); + let text = doc.get_text("text"); + text.insert(0, "hello", PosType::Unicode).unwrap(); + let map = doc.get_map("map"); + map.insert("key", "value").unwrap(); + + let list = doc.get_list("list"); + list.push("item1").unwrap(); + + let tree = doc.get_tree("tree"); + let root = tree.create(TreeParentId::Root).unwrap(); + tree.create_at(TreeParentId::Node(root), 0).unwrap(); + + let movable_list = doc.get_movable_list("movable_list"); + movable_list.insert(0, "movable_item").unwrap(); + + // Create child containers + let child_map = map + .insert_container("child_map", MapHandler::new_detached()) + .unwrap(); + child_map.insert("child_key", "child_value").unwrap(); + + let child_list = list + .insert_container(0, ListHandler::new_detached()) + .unwrap(); + child_list.push("child_item").unwrap(); + let child_movable_list = movable_list + .insert_container(0, MovableListHandler::new_detached()) + .unwrap(); + child_movable_list.insert(0, "child_movable_item").unwrap(); + doc + } + + fn export_container_store(doc: &LoroDoc) -> Bytes { + let mut state = doc.app_state().lock(); + state.ensure_all_alive_containers().unwrap(); + state.store.encode() + } + + #[test] + fn test_container_store_exports_imports() { + let doc = init_doc(); + let bytes = export_container_store(&doc); + let mut new_store = decode_container_store(bytes); + let mut s = doc.app_state().lock(); + s.store.check_eq_after_parsing(&mut new_store); + } + + #[test] + fn first_lazy_read_caches_value() { + let doc = init_doc(); + let bytes = export_container_store(&doc); + let mut store = decode_container_store(bytes); + let map_id = ContainerID::new_root("map", ContainerType::Map); + let map_idx = store.arena.register_container(&map_id); + + assert!(!store.store.has_cached_value_for_test(map_idx)); + assert_eq!(store.map_len(map_idx), 2); + assert!(store.store.has_cached_value_for_test(map_idx)); + + // The cache is bounded (loro-dev/loro#1092): reading more containers + // than the bound evicts older cached values, and re-reading an evicted + // container transparently re-decodes it from the KV store. + let n = DEFAULT_DECODED_VALUE_CACHE_LIMIT * 2; + let source = doc_with_many_child_maps(n); + let bytes = export_container_store(&source); + let mut store = decode_container_store(bytes); + let list_idx = store + .arena + .register_container(&ContainerID::new_root("list", ContainerType::List)); + let mut child_ids = Vec::new(); + for i in 0..n { + let value = store.list_get(list_idx, i).unwrap(); + child_ids.push(value.as_container().unwrap().clone()); + let child_idx = store.arena.register_container(child_ids.last().unwrap()); + assert_eq!(store.map_get(child_idx, "key"), Some((i as i64).into())); + } + + assert!( + store.store.cached_value_count_for_test() <= DEFAULT_DECODED_VALUE_CACHE_LIMIT, + "cached decoded values must stay bounded, got {}", + store.store.cached_value_count_for_test() + ); + // The first children were evicted; re-reading must fall back to KV. + let first_idx = store.arena.register_container(&child_ids[0]); + assert_eq!(store.map_get(first_idx, "key"), Some(0i64.into())); + } + + #[test] + fn ephemeral_lazy_read_does_not_cache_value() { + let doc = init_doc(); + let bytes = export_container_store(&doc); + let mut store = decode_container_store(bytes); + let map_id = ContainerID::new_root("map", ContainerType::Map); + let map_idx = store.arena.register_container(&map_id); + + assert!(!store.store.has_cached_value_for_test(map_idx)); + assert_eq!( + store + .get_value_ephemeral(map_idx) + .and_then(|value| value.as_map().map(|map| map.len())), + Some(2) + ); + assert!(!store.store.has_cached_value_for_test(map_idx)); + } + + #[test] + fn combined_ephemeral_parent_and_value_read_does_not_cache_value() { + let doc = init_doc(); + let bytes = export_container_store(&doc); + let mut store = decode_container_store(bytes); + let map_id = ContainerID::new_root("map", ContainerType::Map); + let map_idx = store.arena.register_container(&map_id); + + assert!(!store.store.has_cached_value_for_test(map_idx)); + let (parent, value) = store + .try_get_parent_and_value_ephemeral(map_idx) + .unwrap() + .unwrap(); + assert_eq!(parent, None); + assert_eq!(value.as_map().map(|map| map.len()), Some(2)); + assert!(!store.store.has_cached_value_for_test(map_idx)); + } + + #[test] + fn snapshot_export_does_not_materialize_map_value_after_key_read() { + let source = init_doc(); + let snapshot = source + .export(crate::encoding::ExportMode::Snapshot) + .unwrap(); + let imported = LoroDoc::new(); + imported.import(&snapshot).unwrap(); + let map_id = ContainerID::new_root("map", ContainerType::Map); + + assert_eq!(imported.get_map("map").get("key"), Some("value".into())); + { + let mut state = imported.app_state().lock(); + let map_idx = state.store.arena.register_container(&map_id); + assert!(state.store.store.has_cached_value_for_test(map_idx)); + assert!(!state + .store + .store + .has_materialized_map_value_for_test(map_idx)); + } + + imported + .export(crate::encoding::ExportMode::Snapshot) + .unwrap(); + + let mut state = imported.app_state().lock(); + let map_idx = state.store.arena.register_container(&map_id); + assert!(!state + .store + .store + .has_materialized_map_value_for_test(map_idx)); + } + + #[test] + fn snapshot_export_keeps_imported_state_lazy() { + let source = init_doc(); + let snapshot = source + .export(crate::encoding::ExportMode::Snapshot) + .unwrap(); + let imported = LoroDoc::new(); + imported.import(&snapshot).unwrap(); + let map_id = ContainerID::new_root("map", ContainerType::Map); + + { + let mut state = imported.app_state().lock(); + let map_idx = state.store.arena.register_container(&map_id); + assert!(!state.store.store.has_cached_value_for_test(map_idx)); + } + + let exported = imported + .export(crate::encoding::ExportMode::Snapshot) + .unwrap(); + assert!(!exported.is_empty()); + let exported_again = imported + .export(crate::encoding::ExportMode::Snapshot) + .unwrap(); + assert_eq!(exported_again, exported); + + let mut state = imported.app_state().lock(); + let map_idx = state.store.arena.register_container(&map_id); + assert!(!state.store.store.has_cached_value_for_test(map_idx)); + } + + #[test] + fn snapshot_export_includes_empty_root_without_version_change() { + let doc = LoroDoc::new_auto_commit(); + doc.get_map("first"); + doc.export(crate::encoding::ExportMode::Snapshot).unwrap(); + let version_before = doc.state_frontiers(); + + let second_id = ContainerID::new_root("second", ContainerType::Map); + doc.get_map("second"); + assert_eq!(doc.state_frontiers(), version_before); + + let snapshot = doc.export(crate::encoding::ExportMode::Snapshot).unwrap(); + let round_tripped = LoroDoc::new(); + round_tripped.import(&snapshot).unwrap(); + let mut state = round_tripped.app_state().lock(); + assert!(state.store.contains_id(&second_id)); + } + + #[test] + fn snapshot_export_includes_new_empty_child() { + let doc = LoroDoc::new_auto_commit(); + let root = doc.get_map("root"); + root.insert("value", 1).unwrap(); + doc.export(crate::encoding::ExportMode::Snapshot).unwrap(); + + let child = root + .insert_container("child", MapHandler::new_detached()) + .unwrap(); + let child_id = child.id(); + let snapshot = doc.export(crate::encoding::ExportMode::Snapshot).unwrap(); + let round_tripped = LoroDoc::new(); + round_tripped.import(&snapshot).unwrap(); + let mut state = round_tripped.app_state().lock(); + assert!(state.store.contains_id(&child_id)); + } + + /// An empty child created by a remote peer has no ops of its own, so the importer only + /// applies the parent's diff. The diff-apply hook must still create a store entry for the + /// child, or the importer's own full snapshot would silently drop it. + #[test] + fn snapshot_export_includes_remote_empty_child() { + let a = LoroDoc::new_auto_commit(); + let map_child_id = a + .get_map("map") + .insert_container("child", MapHandler::new_detached()) + .unwrap() + .id(); + let list_child_id = a + .get_list("list") + .insert_container(0, ListHandler::new_detached()) + .unwrap() + .id(); + let movable_child_id = a + .get_movable_list("movable") + .insert_container(0, MovableListHandler::new_detached()) + .unwrap() + .id(); + let updates = a + .export(crate::encoding::ExportMode::all_updates()) + .unwrap(); + + let b = LoroDoc::new_auto_commit(); + b.import(&updates).unwrap(); + let snapshot = b.export(crate::encoding::ExportMode::Snapshot).unwrap(); + + let c = LoroDoc::new(); + c.import(&snapshot).unwrap(); + assert_eq!(a.get_deep_value(), c.get_deep_value()); + let mut state = c.app_state().lock(); + for id in [&map_child_id, &list_child_id, &movable_child_id] { + assert!(state.store.contains_id(id), "missing {id:?}"); + } + } + + /// A remote tree node's associated meta map has no ops until someone writes metadata; the + /// tree diff's `Create` action must ensure its store entry on the importer. + #[test] + fn snapshot_export_includes_remote_tree_meta() { + let a = LoroDoc::new_auto_commit(); + let node = a.get_tree("tree").create(TreeParentId::Root).unwrap(); + let meta_id = node.associated_meta_container(); + let updates = a + .export(crate::encoding::ExportMode::all_updates()) + .unwrap(); + + let b = LoroDoc::new_auto_commit(); + b.import(&updates).unwrap(); + let snapshot = b.export(crate::encoding::ExportMode::Snapshot).unwrap(); + + let c = LoroDoc::new(); + c.import(&snapshot).unwrap(); + let mut state = c.app_state().lock(); + assert!(state.store.contains_id(&meta_id)); + } + + /// An ensured-but-empty mergeable child has no store entry anywhere — the parent map's + /// marker is its single source of truth. A full snapshot round-trip through an importer + /// must keep the child resolvable by id without materializing an entry for it. + #[test] + fn snapshot_export_keeps_empty_marker_child_resolvable_without_entry() { + let a = LoroDoc::new_auto_commit(); + let child_id = a + .get_map("state") + .ensure_mergeable_text("notes") + .unwrap() + .id(); + let updates = a + .export(crate::encoding::ExportMode::all_updates()) + .unwrap(); + + let b = LoroDoc::new_auto_commit(); + b.import(&updates).unwrap(); + let snapshot = b.export(crate::encoding::ExportMode::Snapshot).unwrap(); + + let c = LoroDoc::new(); + c.import(&snapshot).unwrap(); + let mut state = c.app_state().lock(); + assert!(!state.store.contains_id(&child_id)); + assert!( + state.does_container_exist(&child_id), + "empty mergeable child must resolve from the marker after round-trip" + ); + } + + #[test] + fn deep_value_read_keeps_imported_state_lazy() { + let source = init_doc(); + let expected = source.get_deep_value(); + let child_map_id = source + .get_map("map") + .get("child_map") + .and_then(|value| value.as_container().cloned()) + .unwrap(); + let snapshot = source + .export(crate::encoding::ExportMode::Snapshot) + .unwrap(); + let imported = LoroDoc::new(); + imported.import(&snapshot).unwrap(); + let map_id = ContainerID::new_root("map", ContainerType::Map); + + assert_eq!(imported.get_deep_value(), expected); + assert_eq!(imported.get_deep_value(), expected); + + let mut state = imported.app_state().lock(); + let map_idx = state.store.arena.register_container(&map_id); + let child_map_idx = state.store.arena.register_container(&child_map_id); + assert!(!state.store.store.has_cached_value_for_test(map_idx)); + assert!(!state.store.store.has_cached_value_for_test(child_map_idx)); + } + + #[test] + fn snapshot_export_persists_empty_alive_child() { + let source = LoroDoc::new_auto_commit(); + let child = source + .get_map("root") + .insert_container("empty", MapHandler::new_detached()) + .unwrap(); + let child_id = child.id(); + let updates = source + .export(crate::encoding::ExportMode::all_updates()) + .unwrap(); + let target = LoroDoc::new(); + target.import(&updates).unwrap(); + { + // The diff-apply hook creates the empty child's store entry at import time; full + // snapshot export relies on this invariant instead of walking the alive graph. + let mut state = target.app_state().lock(); + assert!(state.store.contains_id(&child_id)); + } + + let snapshot = target + .export(crate::encoding::ExportMode::Snapshot) + .unwrap(); + let round_tripped = LoroDoc::new(); + round_tripped.import(&snapshot).unwrap(); + + let mut state = round_tripped.app_state().lock(); + assert!(state.store.contains_id(&child_id)); + } + + fn doc_with_many_child_maps(n: usize) -> LoroDoc { + let doc = LoroDoc::new_auto_commit(); + let list = doc.get_list("list"); + for i in 0..n { + let map = list + .insert_container(i, MapHandler::new_detached()) + .unwrap(); + map.insert("key", i as i64).unwrap(); + } + doc + } + + /// Count the actual lazy-value misses before each handler read, rather than + /// relying on timings. A full walk above the limit otherwise decodes every + /// child again on the next walk (loro-dev/loro#1191). + fn walk_child_maps_and_count_decodes(doc: &LoroDoc, n: usize) -> usize { + let list = doc.get_list("list"); + let mut decodes = 0; + for i in 0..n { + let id = list.get(i).unwrap().as_container().unwrap().clone(); + let idx = doc.arena().register_container(&id); + if !doc + .app_state() + .lock() + .store + .store + .has_cached_value_for_test(idx) + { + decodes += 1; + } + assert_eq!(doc.get_map(id).get("key"), Some((i as i64).into())); + } + decodes + } + + fn cached_value_count(doc: &LoroDoc) -> usize { + doc.app_state() + .lock() + .store + .store + .cached_value_count_for_test() + } + + #[test] + fn repeated_handle_walks_respect_decoded_value_cache_limit() { + // Exercise the production-sized budget even in the unit-test build. + let limit = 2048; + for n in [limit / 2, limit * 2] { + let source = doc_with_many_child_maps(n); + let snapshot = source + .export(crate::encoding::ExportMode::Snapshot) + .unwrap(); + let doc = LoroDoc::new_auto_commit(); + doc.set_decoded_value_cache_limit(limit); + doc.import(&snapshot).unwrap(); + + assert_eq!(walk_child_maps_and_count_decodes(&doc, n), n); + let warm_decodes = if n > limit { n } else { 0 }; + assert_eq!(walk_child_maps_and_count_decodes(&doc, n), warm_decodes); + assert_eq!(walk_child_maps_and_count_decodes(&doc, n), warm_decodes); + + // Include the root list in the budget. After one warm-up walk, no + // child needs decoding, even when the document exceeds the default. + doc.set_decoded_value_cache_limit(n + 1); + walk_child_maps_and_count_decodes(&doc, n); + assert_eq!(walk_child_maps_and_count_decodes(&doc, n), 0); + assert_eq!(walk_child_maps_and_count_decodes(&doc, n), 0); + + // A short window is enough to check tiny limits; repeatedly + // decoding the large root list is deliberately expensive at zero. + let n = n.min(32); + doc.set_decoded_value_cache_limit(1); + assert!(cached_value_count(&doc) <= 1); + assert_eq!(walk_child_maps_and_count_decodes(&doc, n), n); + assert!(cached_value_count(&doc) <= 1); + + doc.set_decoded_value_cache_limit(0); + assert_eq!(cached_value_count(&doc), 0); + assert_eq!(walk_child_maps_and_count_decodes(&doc, n), n); + assert_eq!(walk_child_maps_and_count_decodes(&doc, n), n); + assert_eq!(cached_value_count(&doc), 0); + } + } + + #[test] + fn lowering_decoded_value_cache_limit_preserves_local_edits() { + let n = DEFAULT_DECODED_VALUE_CACHE_LIMIT * 2; + let source = doc_with_many_child_maps(n); + let snapshot = source + .export(crate::encoding::ExportMode::Snapshot) + .unwrap(); + let doc = LoroDoc::new_auto_commit(); + // Setting the limit before import must also work. + doc.set_decoded_value_cache_limit(n + 1); + doc.import(&snapshot).unwrap(); + walk_child_maps_and_count_decodes(&doc, n); + + let id = doc + .get_list("list") + .get(0) + .unwrap() + .as_container() + .unwrap() + .clone(); + let first = doc.get_map(id); + first.insert("edited", true).unwrap(); + // This also exercises the stale queue entry left by lazy -> State. + doc.set_decoded_value_cache_limit(0); + assert_eq!(cached_value_count(&doc), 0); + assert_eq!(first.get("edited"), Some(true.into())); + walk_child_maps_and_count_decodes(&doc, n); + + let restored = LoroDoc::new(); + restored + .import(&doc.export(crate::encoding::ExportMode::Snapshot).unwrap()) + .unwrap(); + assert_eq!(restored.get_deep_value(), doc.get_deep_value()); + } + + /// Regression test for loro-dev/loro#1092: walking an imported document + /// container by container must not pin every decoded value in memory. + #[test] + fn handle_reads_bound_cached_container_values() { + let n = DEFAULT_DECODED_VALUE_CACHE_LIMIT * 4; + let source = doc_with_many_child_maps(n); + let bytes = export_container_store(&source); + let mut store = decode_container_store(bytes); + + let list_idx = store + .arena + .register_container(&ContainerID::new_root("list", ContainerType::List)); + assert_eq!(store.list_len(list_idx), n); + for i in 0..n { + let value = store.list_get(list_idx, i).unwrap(); + let child_id = value.as_container().unwrap().clone(); + let child_idx = store.arena.register_container(&child_id); + assert_eq!(store.map_get(child_idx, "key"), Some((i as i64).into())); + } + + assert!( + store.store.cached_value_count_for_test() <= DEFAULT_DECODED_VALUE_CACHE_LIMIT, + "cached decoded values must stay bounded, got {}", + store.store.cached_value_count_for_test() + ); + } + + /// Evicted containers are pure KV caches: re-reading and editing them after + /// eviction must return and preserve the correct values. + #[test] + fn evicted_containers_stay_readable_and_editable() { + let n = DEFAULT_DECODED_VALUE_CACHE_LIMIT * 4; + let source = doc_with_many_child_maps(n); + let snapshot = source + .export(crate::encoding::ExportMode::Snapshot) + .unwrap(); + let imported = LoroDoc::new_auto_commit(); + imported.import(&snapshot).unwrap(); + + let read_all = |doc: &LoroDoc| { + let list = doc.get_list("list"); + for i in 0..n { + let value = list.get(i).unwrap(); + let child_id = value.as_container().unwrap().clone(); + let child = doc.get_map(child_id); + assert_eq!(child.get("key"), Some((i as i64).into())); + } + }; + + // The first walk evicts the early children; the second walk re-reads + // them through the KV fallback. + read_all(&imported); + read_all(&imported); + + // Mutating an evicted-then-reloaded container must persist. + let first_id = imported + .get_list("list") + .get(0) + .unwrap() + .as_container() + .unwrap() + .clone(); + imported.get_map(first_id).insert("edited", true).unwrap(); + + let snapshot = imported + .export(crate::encoding::ExportMode::Snapshot) + .unwrap(); + let round_tripped = LoroDoc::new(); + round_tripped.import(&snapshot).unwrap(); + assert_eq!(round_tripped.get_deep_value(), imported.get_deep_value()); + } + + /// `load_all` (and GC snapshot imports) put the store in `AllLoaded` mode; + /// evicted entries must still be re-created from the KV store there. + #[test] + fn evicted_entries_stay_readable_when_all_loaded() { + let n = DEFAULT_DECODED_VALUE_CACHE_LIMIT * 4; + let source = doc_with_many_child_maps(n); + let bytes = export_container_store(&source); + let mut store = decode_container_store(bytes); + + let list_idx = store + .arena + .register_container(&ContainerID::new_root("list", ContainerType::List)); + store.store.load_all(); + + for i in 0..n { + let value = store.list_get(list_idx, i).unwrap(); + let child_id = value.as_container().unwrap().clone(); + let child_idx = store.arena.register_container(&child_id); + assert_eq!(store.map_get(child_idx, "key"), Some((i as i64).into())); + } + + assert!( + store.store.cached_value_count_for_test() <= DEFAULT_DECODED_VALUE_CACHE_LIMIT, + "cached decoded values must stay bounded, got {}", + store.store.cached_value_count_for_test() + ); + + // `AllLoaded` must not blind full enumeration to evicted entries: once + // an eviction has happened, `load_all` re-scans the KV store instead of + // short-circuiting on `load_state`. + assert_eq!(store.store.iter_all_container_ids().count(), n + 1); + + // The first children were evicted during the walk; re-reading them must + // fall back to the KV store even in AllLoaded mode. + for i in 0..n { + let value = store.list_get(list_idx, i).unwrap(); + let child_id = value.as_container().unwrap().clone(); + let child_idx = store.arena.register_container(&child_id); + assert_eq!(store.map_get(child_idx, "key"), Some((i as i64).into())); + } + } + + /// Mergeable children and tree meta maps are reachable through a parent + /// marker / a tree node rather than a plain value slot. Evicting their + /// cached values must not lose them: re-read through the parent/path, + /// mutate, and snapshot round-trip. + #[test] + fn evicted_mergeable_child_and_tree_meta_survive_round_trip() { + let filler = DEFAULT_DECODED_VALUE_CACHE_LIMIT * 2; + let source = LoroDoc::new_auto_commit(); + source + .get_map("state") + .ensure_mergeable_text("notes") + .unwrap() + .insert(0, "hello", PosType::Unicode) + .unwrap(); + let node = source.get_tree("tree").create(TreeParentId::Root).unwrap(); + source + .get_tree("tree") + .get_meta(node) + .unwrap() + .insert("k", "v") + .unwrap(); + let list = source.get_list("list"); + for i in 0..filler { + let map = list + .insert_container(i, MapHandler::new_detached()) + .unwrap(); + map.insert("key", i as i64).unwrap(); + } + let snapshot = source + .export(crate::encoding::ExportMode::Snapshot) + .unwrap(); + + let doc = LoroDoc::new_auto_commit(); + doc.import(&snapshot).unwrap(); + + // Cache the mergeable child and the tree meta values, then evict them + // by reading more containers than the cache bound. + let notes = doc.get_map("state").ensure_mergeable_text("notes").unwrap(); + assert_eq!(notes.to_string(), "hello"); + let meta = doc.get_tree("tree").get_meta(node).unwrap(); + assert_eq!(meta.get("k"), Some("v".into())); + let list = doc.get_list("list"); + for i in 0..filler { + let child_id = list.get(i).unwrap().as_container().unwrap().clone(); + assert_eq!(doc.get_map(child_id).get("key"), Some((i as i64).into())); + } + { + let mut state = doc.app_state().lock(); + assert!( + state.store.store.cached_value_count_for_test() + <= DEFAULT_DECODED_VALUE_CACHE_LIMIT, + "the walk must have evicted cached values, got {}", + state.store.store.cached_value_count_for_test() + ); + } + + // Re-read through the parent marker / tree path after eviction, then + // mutate both. + let notes = doc.get_map("state").ensure_mergeable_text("notes").unwrap(); + assert_eq!(notes.to_string(), "hello"); + notes.insert(5, "!", PosType::Unicode).unwrap(); + let meta = doc.get_tree("tree").get_meta(node).unwrap(); + assert_eq!(meta.get("k"), Some("v".into())); + meta.insert("k2", "v2").unwrap(); + + let snapshot = doc.export(crate::encoding::ExportMode::Snapshot).unwrap(); + let round_tripped = LoroDoc::new(); + round_tripped.import(&snapshot).unwrap(); + assert_eq!(round_tripped.get_deep_value(), doc.get_deep_value()); + assert_eq!( + round_tripped + .get_map("state") + .ensure_mergeable_text("notes") + .unwrap() + .to_string(), + "hello!" + ); + assert_eq!( + round_tripped + .get_tree("tree") + .get_meta(node) + .unwrap() + .get("k2"), + Some("v2".into()) + ); + } + + /// A wrapper that is mutated while enqueued in the value-cache queue + /// materializes into a full state, leaving a stale queue entry behind. + /// Eviction must skip the stale entry without losing the mutation or + /// wedging the queue. + #[test] + fn stale_queue_entry_after_lazy_to_state_conversion() { + let n = DEFAULT_DECODED_VALUE_CACHE_LIMIT * 2; + let source = doc_with_many_child_maps(n); + let snapshot = source + .export(crate::encoding::ExportMode::Snapshot) + .unwrap(); + let doc = LoroDoc::new_auto_commit(); + doc.import(&snapshot).unwrap(); + + // Read child 0 (cached + enqueued), then mutate it: the lazy wrapper + // materializes into a full state and its queue entry becomes stale. + let list = doc.get_list("list"); + let first_id = list.get(0).unwrap().as_container().unwrap().clone(); + let first_map = doc.get_map(first_id); + assert_eq!(first_map.get("key"), Some(0i64.into())); + first_map.insert("edited", true).unwrap(); + + // Keep reading past the bound so eviction pops the stale entry. + for i in 0..n { + let child_id = list.get(i).unwrap().as_container().unwrap().clone(); + assert_eq!(doc.get_map(child_id).get("key"), Some((i as i64).into())); + } + { + let mut state = doc.app_state().lock(); + assert!( + state.store.store.cached_value_count_for_test() + <= DEFAULT_DECODED_VALUE_CACHE_LIMIT, + "cached decoded values must stay bounded, got {}", + state.store.store.cached_value_count_for_test() + ); + } + + assert_eq!(first_map.get("edited"), Some(true.into())); + let round_tripped = LoroDoc::new(); + round_tripped + .import(&doc.export(crate::encoding::ExportMode::Snapshot).unwrap()) + .unwrap(); + assert_eq!(round_tripped.get_deep_value(), doc.get_deep_value()); + } +} diff --git a/vendor/loro-internal/src/state/container_store/container_wrapper.rs b/vendor/loro-internal/src/state/container_store/container_wrapper.rs new file mode 100644 index 0000000..3abfcb4 --- /dev/null +++ b/vendor/loro-internal/src/state/container_store/container_wrapper.rs @@ -0,0 +1,843 @@ +use std::collections::BTreeMap; + +use bytes::Bytes; +use loro_common::{ContainerID, ContainerType, InternalString, LoroError, LoroResult, LoroValue}; +use once_cell::sync::OnceCell; +use tracing::trace; + +#[cfg(feature = "counter")] +use crate::state::counter_state::CounterState; +use crate::{ + arena::SharedArena, + container::idx::ContainerIdx, + state::{ + unknown_state::UnknownState, ContainerCreationContext, ContainerState, FastStateSnapshot, + IndexType, ListState, MapState, MovableListState, RichtextState, State, TreeState, + }, + utils::utf16::{count_unicode_chars, count_utf16_len}, +}; + +#[derive(Debug)] +pub(crate) struct ContainerWrapper { + depth: usize, + kind: ContainerType, + parent: Option<ContainerID>, + data: ContainerData, + flushed: bool, + /// Whether this wrapper is currently enqueued in the store's bounded + /// decoded-value cache (`InnerStore::value_cache_queue`). + in_value_cache_queue: bool, + /// Second-chance bit for the value-cache eviction clock: set on every read + /// that uses the cached value, cleared when the eviction pass considers + /// this wrapper. + value_cache_referenced: bool, +} + +#[derive(Debug)] +enum ContainerData { + State(State), + Lazy(Box<LazyContainerData>), +} + +#[derive(Debug)] +struct LazyContainerData { + /// Lazily decoded snapshot bytes and optional decoded value. + bytes: Option<Bytes>, + value: Option<LazyDecodedValue>, + bytes_offset_for_value: Option<usize>, + bytes_offset_for_state: Option<usize>, +} + +struct DecodedHeader { + kind: ContainerType, + depth: usize, + parent: Option<ContainerID>, + payload_offset: usize, +} + +#[derive(Debug)] +enum LazyDecodedValue { + Value(LoroValue), + Text { + value: LoroValue, + unicode_len: usize, + utf16_len: usize, + }, + Map { + ordered: BTreeMap<String, LoroValue>, + value: OnceCell<LoroValue>, + }, +} + +impl LazyDecodedValue { + fn text(value: LoroValue) -> Self { + let text = value + .as_string() + .expect("decoded text value should be a string"); + Self::Text { + unicode_len: count_unicode_chars(text.as_bytes()), + utf16_len: count_utf16_len(text.as_bytes()), + value, + } + } + + fn to_loro_value(&self) -> LoroValue { + match self { + Self::Value(value) | Self::Text { value, .. } => value.clone(), + Self::Map { ordered, value } => value + .get_or_init(|| { + LoroValue::Map( + ordered + .iter() + .map(|(key, value)| (key.clone(), value.clone())) + .collect::<loro_common::LoroMapValue>(), + ) + }) + .clone(), + } + } + + fn to_loro_value_ephemeral(&self) -> LoroValue { + match self { + Self::Value(value) | Self::Text { value, .. } => value.clone(), + Self::Map { ordered, value } => value.get().cloned().unwrap_or_else(|| { + LoroValue::Map( + ordered + .iter() + .map(|(key, value)| (key.clone(), value.clone())) + .collect::<loro_common::LoroMapValue>(), + ) + }), + } + } + + fn as_map(&self) -> Option<&BTreeMap<String, LoroValue>> { + match self { + Self::Map { ordered, .. } => Some(ordered), + _ => None, + } + } + + fn unicode_len(&self) -> Option<usize> { + match self { + Self::Text { unicode_len, .. } => Some(*unicode_len), + _ => None, + } + } + + fn utf16_len(&self) -> Option<usize> { + match self { + Self::Text { utf16_len, .. } => Some(*utf16_len), + _ => None, + } + } + + fn utf8_len(&self) -> Option<usize> { + match self { + // The decoded text value is the string itself, so its byte length + // is a cheap `str::len` — no need to cache a separate field. + Self::Text { value, .. } => value.as_string().map(|s| s.len()), + _ => None, + } + } +} + +impl ContainerWrapper { + pub fn new(state: State, arena: &SharedArena) -> Self { + let idx = state.container_idx(); + let parent = arena + .get_parent(idx) + .and_then(|p| arena.get_container_id(p)); + let depth = arena + .get_depth(idx) + .expect("InternalError: a container gets state only once its parent is known") + .get() as usize; + Self { + depth, + parent, + kind: idx.get_type(), + data: ContainerData::State(state), + flushed: false, + in_value_cache_queue: false, + value_cache_referenced: false, + } + } + + pub fn depth(&self) -> usize { + self.depth + } + + pub(crate) fn kind(&self) -> ContainerType { + self.kind + } + + /// It will not decode the state if it is not decoded + #[allow(unused)] + pub fn try_get_state(&self) -> Option<&State> { + match &self.data { + ContainerData::State(state) => Some(state), + ContainerData::Lazy(_) => None, + } + } + + /// It will decode the state if it is not decoded + pub fn get_state(&mut self, idx: ContainerIdx, ctx: ContainerCreationContext) -> &State { + self.decode_state(idx, ctx).unwrap(); + match &self.data { + ContainerData::State(state) => state, + ContainerData::Lazy(_) => unreachable!("ContainerWrapper state should be decoded"), + } + } + + /// It will decode the state if it is not decoded + pub fn get_state_mut( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext, + ) -> &mut State { + self.decode_state(idx, ctx).unwrap(); + self.flushed = false; + match &mut self.data { + ContainerData::State(state) => state, + ContainerData::Lazy(_) => unreachable!("ContainerWrapper state should be decoded"), + } + } + + pub(crate) fn try_get_value( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext, + ) -> LoroResult<LoroValue> { + match &mut self.data { + ContainerData::State(state) => { + trace!("state"); + Ok(state.get_value()) + } + ContainerData::Lazy(lazy) if lazy.value.is_some() => { + trace!("value"); + Ok(lazy.value.as_ref().unwrap().to_loro_value()) + } + ContainerData::Lazy(_) => { + trace!("decode value"); + self.decode_value(idx, ctx)?; + match &mut self.data { + ContainerData::State(state) => Ok(state.get_value()), + ContainerData::Lazy(lazy) => Ok(lazy.value.as_ref().unwrap().to_loro_value()), + } + } + } + } + + pub fn get_value(&mut self, idx: ContainerIdx, ctx: ContainerCreationContext) -> LoroValue { + self.try_get_value(idx, ctx).unwrap() + } + + /// Read the current value without populating the lazy-value cache. + /// + /// Snapshot export uses this while walking reachable containers. Keeping the decoded value + /// on every lazy wrapper would turn that walk into full state materialization. + pub(crate) fn try_get_value_ephemeral( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext, + ) -> LoroResult<LoroValue> { + match &mut self.data { + ContainerData::State(state) => Ok(state.get_value()), + ContainerData::Lazy(lazy) if lazy.value.is_some() => { + Ok(lazy.value.as_ref().unwrap().to_loro_value_ephemeral()) + } + ContainerData::Lazy(lazy) => { + let Some(bytes) = lazy.bytes.clone() else { + return Ok(self.kind.default_value()); + }; + let mut temporary = Self::try_new_from_bytes(bytes)?; + temporary.try_get_value(idx, ctx) + } + } + } + + /// Meta map ids of every node in a tree container, including deleted nodes, without caching + /// a decoded state that was not already resident. + /// + /// The tree's `LoroValue` only lists alive nodes, but a deleted node can be revived by a later + /// op (a move out of a deleted ancestor, or a peer's `Move` of a directly deleted node) and + /// then its meta map is live again. Retention walks use this instead of the value. + pub(crate) fn try_get_tree_meta_ids_ephemeral( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext, + ) -> LoroResult<Vec<ContainerID>> { + debug_assert_eq!(self.kind, ContainerType::Tree); + match &self.data { + ContainerData::State(state) => Ok(state.get_child_containers()), + ContainerData::Lazy(lazy) => { + let Some(bytes) = lazy.bytes.clone() else { + return Ok(Vec::new()); + }; + let mut temporary = Self::try_new_from_bytes(bytes)?; + temporary.decode_state(idx, ctx)?; + Ok(temporary.try_get_state().unwrap().get_child_containers()) + } + } + } + + pub fn map_get( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext, + key: &str, + ) -> Option<LoroValue> { + match &mut self.data { + ContainerData::State(state) => state.as_map_state().unwrap().get(key).cloned(), + ContainerData::Lazy(_) => { + self.decode_value(idx, ctx).unwrap(); + match &self.data { + ContainerData::Lazy(lazy) => lazy.value.as_ref()?.as_map()?.get(key).cloned(), + ContainerData::State(state) => state.as_map_state().unwrap().get(key).cloned(), + } + } + } + } + + pub fn map_len(&mut self, idx: ContainerIdx, ctx: ContainerCreationContext) -> usize { + match &mut self.data { + ContainerData::State(state) => state.as_map_state().unwrap().len(), + ContainerData::Lazy(_) => { + self.decode_value(idx, ctx).unwrap(); + match &self.data { + ContainerData::Lazy(lazy) => lazy + .value + .as_ref() + .and_then(|value| value.as_map()) + .map_or(0, BTreeMap::len), + ContainerData::State(state) => state.as_map_state().unwrap().len(), + } + } + } + } + + pub fn map_keys( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext, + ) -> Vec<InternalString> { + match &mut self.data { + ContainerData::State(state) => state + .as_map_state() + .unwrap() + .iter() + .filter(|(_, value)| value.value.is_some()) + .map(|(key, _)| key.clone()) + .collect(), + ContainerData::Lazy(_) => { + self.decode_value(idx, ctx).unwrap(); + match &self.data { + ContainerData::Lazy(lazy) => lazy + .value + .as_ref() + .and_then(|value| value.as_map()) + .map(|map| map.keys().map(|key| key.as_str().into()).collect()) + .unwrap_or_default(), + ContainerData::State(state) => state + .as_map_state() + .unwrap() + .iter() + .filter(|(_, value)| value.value.is_some()) + .map(|(key, _)| key.clone()) + .collect(), + } + } + } + } + + pub fn map_entries( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext, + ) -> Vec<(InternalString, LoroValue)> { + match &mut self.data { + ContainerData::State(state) => state + .as_map_state() + .unwrap() + .iter() + .filter_map(|(key, value)| value.value.clone().map(|value| (key.clone(), value))) + .collect(), + ContainerData::Lazy(_) => { + self.decode_value(idx, ctx).unwrap(); + match &self.data { + ContainerData::Lazy(lazy) => lazy + .value + .as_ref() + .and_then(|value| value.as_map()) + .map(|map| { + map.iter() + .map(|(key, value)| (key.as_str().into(), value.clone())) + .collect() + }) + .unwrap_or_default(), + ContainerData::State(state) => state + .as_map_state() + .unwrap() + .iter() + .filter_map(|(key, value)| { + value.value.clone().map(|value| (key.clone(), value)) + }) + .collect(), + } + } + } + } + + pub fn text_unicode_len( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext, + ) -> Option<usize> { + match &mut self.data { + ContainerData::State(state) => { + Some(state.as_richtext_state_mut().unwrap().len_unicode()) + } + ContainerData::Lazy(_) => { + self.decode_value(idx, ctx).unwrap(); + match &mut self.data { + ContainerData::State(state) => { + Some(state.as_richtext_state_mut().unwrap().len_unicode()) + } + ContainerData::Lazy(lazy) => lazy.value.as_ref()?.unicode_len(), + } + } + } + } + + pub fn text_utf16_len( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext, + ) -> Option<usize> { + match &mut self.data { + ContainerData::State(state) => Some(state.as_richtext_state_mut().unwrap().len_utf16()), + ContainerData::Lazy(_) => { + self.decode_value(idx, ctx).unwrap(); + match &mut self.data { + ContainerData::State(state) => { + Some(state.as_richtext_state_mut().unwrap().len_utf16()) + } + ContainerData::Lazy(lazy) => lazy.value.as_ref()?.utf16_len(), + } + } + } + } + + pub fn text_utf8_len( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext, + ) -> Option<usize> { + match &mut self.data { + ContainerData::State(state) => Some(state.as_richtext_state_mut().unwrap().len_utf8()), + ContainerData::Lazy(_) => { + self.decode_value(idx, ctx).unwrap(); + match &mut self.data { + ContainerData::State(state) => { + Some(state.as_richtext_state_mut().unwrap().len_utf8()) + } + ContainerData::Lazy(lazy) => lazy.value.as_ref()?.utf8_len(), + } + } + } + } + + pub fn list_get( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext, + index: usize, + ) -> Option<LoroValue> { + match &mut self.data { + ContainerData::State(state) => match self.kind { + ContainerType::List => state.as_list_state().unwrap().get(index).cloned(), + ContainerType::MovableList => state + .as_movable_list_state() + .unwrap() + .get(index, IndexType::ForUser) + .cloned(), + _ => None, + }, + ContainerData::Lazy(_) => match self.get_value(idx, ctx) { + LoroValue::List(list) => list.get(index).cloned(), + _ => None, + }, + } + } + + pub fn list_len(&mut self, idx: ContainerIdx, ctx: ContainerCreationContext) -> usize { + match &mut self.data { + ContainerData::State(state) => match self.kind { + ContainerType::List => state.as_list_state().unwrap().len(), + ContainerType::MovableList => state.as_movable_list_state().unwrap().len(), + _ => 0, + }, + ContainerData::Lazy(_) => match self.get_value(idx, ctx) { + LoroValue::List(list) => list.len(), + _ => 0, + }, + } + } + + pub fn list_values( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext, + ) -> Vec<LoroValue> { + match &mut self.data { + ContainerData::State(state) => match self.kind { + ContainerType::List => state.as_list_state().unwrap().iter().cloned().collect(), + ContainerType::MovableList => state + .as_movable_list_state() + .unwrap() + .iter() + .cloned() + .collect(), + _ => Vec::new(), + }, + ContainerData::Lazy(_) => match self.get_value(idx, ctx) { + LoroValue::List(list) => list.iter().cloned().collect(), + _ => Vec::new(), + }, + } + } + + pub fn encode(&mut self) -> Bytes { + let ContainerData::State(state) = &mut self.data else { + let lazy = match &self.data { + ContainerData::Lazy(lazy) => lazy, + ContainerData::State(_) => unreachable!(), + }; + assert!(self.flushed, "lazy container should be flushed"); + return lazy.bytes.as_ref().unwrap().clone(); + }; + + // ContainerType + // Depth + // ParentID + // StateSnapshot + let mut output = Vec::new(); + output.push(self.kind.to_u8()); + leb128::write::unsigned(&mut output, self.depth as u64).unwrap(); + postcard::to_io(&self.parent, &mut output).unwrap(); + state.encode_snapshot_fast(&mut output); + output.into() + } + + /// Decode the wrapper header (kind, depth, parent id) and locate where the + /// container state payload starts. Single source of truth for the header + /// layout written by [`Self::encode`]. + fn decode_header(bytes: &[u8]) -> LoroResult<DecodedHeader> { + fn err() -> LoroError { + LoroError::DecodeError("Decode container state failed".to_string().into_boxed_str()) + } + + if bytes.is_empty() { + return Err(err()); + } + let kind = ContainerType::try_from_u8(bytes[0])?; + let mut reader = &bytes[1..]; + let depth = leb128::read::unsigned(&mut reader).map_err(|_| err())?; + let (parent, reader) = + postcard::take_from_bytes::<Option<ContainerID>>(reader).map_err(|_| err())?; + Ok(DecodedHeader { + kind, + depth: depth as usize, + parent, + payload_offset: bytes.len() - reader.len(), + }) + } + + /// Byte offset where the container state payload starts inside an encoded + /// [`ContainerWrapper`] value (after the kind byte, depth, and parent id). + pub(crate) fn payload_offset(bytes: &[u8]) -> LoroResult<usize> { + Ok(Self::decode_header(bytes)?.payload_offset) + } + + /// Parent id encoded in the header of a stored container wrapper, read + /// without touching the state payload. + pub(crate) fn try_decode_parent(bytes: &[u8]) -> LoroResult<Option<ContainerID>> { + Ok(Self::decode_header(bytes)?.parent) + } + + #[allow(unused)] + pub fn decode_parent(b: &[u8]) -> Option<ContainerID> { + Self::decode_header(b).unwrap().parent + } + + pub fn new_from_bytes(bytes: Bytes) -> Self { + Self::try_new_from_bytes(bytes).unwrap() + } + + pub fn try_new_from_bytes(bytes: Bytes) -> LoroResult<Self> { + let header = Self::decode_header(&bytes)?; + Ok(Self { + depth: header.depth, + kind: header.kind, + parent: header.parent, + data: ContainerData::Lazy(Box::new(LazyContainerData { + value: None, + bytes: Some(bytes.clone()), + bytes_offset_for_value: Some(header.payload_offset), + bytes_offset_for_state: None, + })), + flushed: true, + in_value_cache_queue: false, + value_cache_referenced: false, + }) + } + + fn decode_value(&mut self, idx: ContainerIdx, ctx: ContainerCreationContext) -> LoroResult<()> { + if matches!(self.data, ContainerData::State(_)) { + return Ok(()); + } + + if matches!(&self.data, ContainerData::Lazy(lazy) if lazy.value.is_some()) { + return Ok(()); + } + + let (v, state_offset, decoded_state) = self.decode_value_from_bytes(idx, ctx)?; + if let Some(state) = decoded_state { + self.data = ContainerData::State(state); + return Ok(()); + } + + let ContainerData::Lazy(lazy) = &mut self.data else { + unreachable!(); + }; + lazy.value = Some(v); + lazy.bytes_offset_for_state = Some(state_offset); + Ok(()) + } + + pub(super) fn has_cached_value(&self) -> bool { + match &self.data { + ContainerData::State(_) => true, + ContainerData::Lazy(lazy) => lazy.value.is_some(), + } + } + + /// Whether this wrapper holds an evictable cached decoded value: a flushed + /// lazy wrapper is a pure cache over the KV bytes, so dropping it loses + /// nothing (a later read re-creates it from the KV store). + pub(super) fn is_evictable_cached_value(&self) -> bool { + self.flushed && matches!(&self.data, ContainerData::Lazy(lazy) if lazy.value.is_some()) + } + + pub(super) fn is_in_value_cache_queue(&self) -> bool { + self.in_value_cache_queue + } + + pub(super) fn set_in_value_cache_queue(&mut self, value: bool) { + self.in_value_cache_queue = value; + } + + pub(super) fn mark_value_cache_referenced(&mut self) { + self.value_cache_referenced = true; + } + + /// Returns and clears the second-chance bit. + pub(super) fn take_value_cache_referenced(&mut self) -> bool { + std::mem::take(&mut self.value_cache_referenced) + } + + #[cfg(test)] + pub(super) fn has_cached_value_for_test(&self) -> bool { + self.has_cached_value() + } + + #[cfg(test)] + pub(super) fn has_materialized_map_value_for_test(&self) -> bool { + let ContainerData::Lazy(lazy) = &self.data else { + return false; + }; + matches!( + lazy.value.as_ref(), + Some(LazyDecodedValue::Map { value, .. }) if value.get().is_some() + ) + } + + fn value_bytes_and_offset(&mut self) -> Option<(Bytes, usize)> { + let ContainerData::Lazy(lazy) = &mut self.data else { + return None; + }; + + let bytes = lazy.bytes.as_ref()?.clone(); + if lazy.bytes_offset_for_value.is_none() { + lazy.bytes_offset_for_value = Some(Self::decode_header(&bytes).unwrap().payload_offset); + } + + Some((bytes, lazy.bytes_offset_for_value.unwrap())) + } + + fn decode_value_from_bytes( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext, + ) -> LoroResult<(LazyDecodedValue, usize, Option<State>)> { + let Some((bytes, value_offset)) = self.value_bytes_and_offset() else { + return Ok((LazyDecodedValue::Value(self.kind.default_value()), 0, None)); + }; + let b = &bytes[value_offset..]; + + let mut decoded_state = None; + let (v, state_offset) = match self.kind { + ContainerType::Text => { + let (v, rest) = RichtextState::decode_value(b)?; + ( + LazyDecodedValue::text(v), + b.len() - rest.len() + value_offset, + ) + } + ContainerType::Map => { + let (v, rest) = MapState::decode_value_as_btree_map(b)?; + ( + LazyDecodedValue::Map { + ordered: v, + value: OnceCell::new(), + }, + b.len() - rest.len() + value_offset, + ) + } + ContainerType::List => { + let (v, rest) = ListState::decode_value(b)?; + ( + LazyDecodedValue::Value(v), + b.len() - rest.len() + value_offset, + ) + } + ContainerType::MovableList => { + let (v, rest) = MovableListState::decode_value(b)?; + ( + LazyDecodedValue::Value(v), + b.len() - rest.len() + value_offset, + ) + } + ContainerType::Tree => { + let mut state = TreeState::decode_snapshot_fast(idx, (LoroValue::Null, b), ctx)?; + let value = state.get_value(); + decoded_state = Some(State::TreeState(Box::new(state))); + (LazyDecodedValue::Value(value), value_offset) + } + #[cfg(feature = "counter")] + ContainerType::Counter => { + let (v, rest) = CounterState::decode_value(b)?; + ( + LazyDecodedValue::Value(v), + b.len() - rest.len() + value_offset, + ) + } + ContainerType::Unknown(_) => { + let (v, rest) = UnknownState::decode_value(b)?; + ( + LazyDecodedValue::Value(v), + b.len() - rest.len() + value_offset, + ) + } + }; + + Ok((v, state_offset, decoded_state)) + } + + pub(super) fn decode_state( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext, + ) -> LoroResult<()> { + if matches!(self.data, ContainerData::State(_)) { + return Ok(()); + } + + let need_value = match &self.data { + ContainerData::Lazy(lazy) => lazy.value.is_none(), + ContainerData::State(_) => false, + }; + if need_value { + self.decode_value(idx, ctx)?; + } + + if matches!(self.data, ContainerData::State(_)) { + return Ok(()); + } + + let ContainerData::Lazy(lazy) = &self.data else { + unreachable!(); + }; + let bytes = lazy.bytes.as_ref().unwrap(); + let offset = lazy.bytes_offset_for_state.unwrap(); + let b = &bytes[offset..]; + let v = lazy.value.as_ref().unwrap().to_loro_value(); + let state: State = match self.kind { + ContainerType::Text => RichtextState::decode_snapshot_fast(idx, (v, b), ctx)?.into(), + ContainerType::Map => MapState::decode_snapshot_fast(idx, (v, b), ctx)?.into(), + ContainerType::List => ListState::decode_snapshot_fast(idx, (v, b), ctx)?.into(), + ContainerType::MovableList => { + MovableListState::decode_snapshot_fast(idx, (v, b), ctx)?.into() + } + ContainerType::Tree => TreeState::decode_snapshot_fast(idx, (v, b), ctx)?.into(), + #[cfg(feature = "counter")] + ContainerType::Counter => CounterState::decode_snapshot_fast(idx, (v, b), ctx)?.into(), + ContainerType::Unknown(_) => { + UnknownState::decode_snapshot_fast(idx, (v, b), ctx)?.into() + } + }; + self.data = ContainerData::State(state); + Ok(()) + } + + #[allow(unused)] + pub(crate) fn is_state_empty(&self) -> bool { + match &self.data { + ContainerData::State(state) => state.is_state_empty(), + ContainerData::Lazy(lazy) => { + // FIXME: it's not very accurate... + lazy.bytes.as_ref().unwrap().len() > 10 + } + } + } + + pub(crate) fn is_deleted_root_value_cleared(&mut self) -> bool { + fn value_is_cleared(kind: ContainerType, value: &LoroValue) -> bool { + match kind { + ContainerType::Text => value.as_string().is_some_and(|value| value.is_empty()), + ContainerType::Map | ContainerType::List | ContainerType::MovableList => { + value.is_empty_collection() + } + ContainerType::Tree => value.as_list().is_some_and(|value| value.is_empty()), + #[cfg(feature = "counter")] + ContainerType::Counter => value.as_double().is_some_and(|value| *value == 0.0), + ContainerType::Unknown(_) => false, + } + } + + match &mut self.data { + ContainerData::State(state) => value_is_cleared(self.kind, &state.get_value()), + ContainerData::Lazy(lazy) => lazy + .value + .as_ref() + .is_some_and(|value| value_is_cleared(self.kind, &value.to_loro_value())), + } + } + + pub(crate) fn clear_bytes(&mut self) { + assert!(matches!(self.data, ContainerData::State(_))); + } + + pub(crate) fn is_flushed(&self) -> bool { + self.flushed + } + + pub(crate) fn set_flushed(&mut self, flushed: bool) { + self.flushed = flushed; + } + + #[allow(unused)] + pub(crate) fn parent(&self) -> Option<&ContainerID> { + self.parent.as_ref() + } +} diff --git a/vendor/loro-internal/src/state/container_store/inner_store.rs b/vendor/loro-internal/src/state/container_store/inner_store.rs new file mode 100644 index 0000000..e33a747 --- /dev/null +++ b/vendor/loro-internal/src/state/container_store/inner_store.rs @@ -0,0 +1,821 @@ +use crate::{ + arena::SharedArena, + configure::Configure, + container::idx::ContainerIdx, + state::{container_store::FRONTIERS_KEY, ContainerCreationContext, ContainerState}, + utils::kv_wrapper::KvWrapper, + version::Frontiers, +}; +use bytes::Bytes; +use loro_common::{ContainerID, ContainerType, LoroResult, LoroValue}; +use rustc_hash::FxHashSet; +use std::collections::VecDeque; + +use super::ContainerWrapper; + +/// The invariants about this struct: +/// +/// - `kv` is either the same or older than `store`. +/// - `store` is a cache over `kv`: every container in `kv` is either present in +/// `store` or was evicted from it by the bounded decoded-value cache +/// (see `Configure::decoded_value_cache_limit`). Evicted entries are re-created from +/// `kv` on the next access, so lookups must always fall back to `kv` on a +/// `store` miss, regardless of `load_state`. +/// - `load_state == AllLoaded` means every `kv` entry was materialized into +/// `store` at some point; it does NOT mean `store` is still complete. Once +/// `evicted_since_full_load` is set, `load_all()` must re-scan `kv`. +/// +/// Invariants: it should be agnostic to the users of this struct whether a container is stored in `kv` or `store` +pub(crate) struct InnerStore { + arena: SharedArena, + store: Vec<Option<ContainerWrapper>>, + kv: KvWrapper, + load_state: LoadState, + config: Configure, + /// FIFO (with a second-chance bit on each wrapper) of containers whose + /// decoded value is currently cached in `store`. Bounded by + /// `Configure::decoded_value_cache_limit()`. Entries may be stale (the wrapper was + /// dropped or materialized into a full state); eviction skips those. + value_cache_queue: VecDeque<ContainerIdx>, + /// True once the value cache has evicted at least one wrapper since the + /// last full KV scan. While this is set, `load_state == AllLoaded` no + /// longer implies `store` contains every entry in `kv`, so `load_all()` + /// must re-scan `kv` instead of short-circuiting. + evicted_since_full_load: bool, + /// While `Some`, the containers given new (not loaded) state are recorded, so + /// a rolled back local transaction can remove them again + /// (`DocState::begin_local_rollback`). + created_journal: Option<Vec<ContainerIdx>>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum LoadState { + Lazy, + RootsLoaded, + AllLoaded, +} + +impl std::fmt::Debug for InnerStore { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("InnerStore").finish() + } +} + +/// This impl block contains all the mutation code that may break the invariants of this struct +impl InnerStore { + #[inline] + fn slot(idx: ContainerIdx) -> usize { + idx.to_index() as usize + } + + #[inline] + fn get_entry_mut_in( + store: &mut [Option<ContainerWrapper>], + idx: ContainerIdx, + ) -> Option<&mut ContainerWrapper> { + let entry = store.get_mut(Self::slot(idx))?.as_mut()?; + debug_assert_eq!(entry.kind(), idx.get_type()); + Some(entry) + } + + #[inline] + fn get_entry_mut(&mut self, idx: ContainerIdx) -> Option<&mut ContainerWrapper> { + Self::get_entry_mut_in(&mut self.store, idx) + } + + #[inline] + fn contains_idx_in(store: &[Option<ContainerWrapper>], idx: ContainerIdx) -> bool { + store + .get(Self::slot(idx)) + .and_then(|entry| entry.as_ref()) + .is_some_and(|entry| entry.kind() == idx.get_type()) + } + + #[inline] + fn contains_idx(&self, idx: ContainerIdx) -> bool { + Self::contains_idx_in(&self.store, idx) + } + + fn insert_entry( + store: &mut Vec<Option<ContainerWrapper>>, + idx: ContainerIdx, + container: ContainerWrapper, + ) -> Option<ContainerWrapper> { + let slot = Self::slot(idx); + if store.len() <= slot { + store.resize_with(slot + 1, || None); + } + + store[slot].replace(container) + } + + pub(super) fn get_or_insert_with( + &mut self, + idx: ContainerIdx, + f: impl FnOnce() -> ContainerWrapper, + ) -> &mut ContainerWrapper { + if self.get_entry_mut(idx).is_none() { + let id = self.arena.get_container_id(idx).unwrap(); + let key = id.to_bytes(); + let container = match self.kv.get(&key) { + Some(bytes) => ContainerWrapper::new_from_bytes(bytes), + None => { + if let Some(journal) = &mut self.created_journal { + journal.push(idx); + } + f() + } + }; + Self::insert_entry(&mut self.store, idx, container); + } + + self.get_entry_mut(idx).unwrap() + } + + pub(super) fn ensure_container( + &mut self, + idx: ContainerIdx, + f: impl FnOnce() -> ContainerWrapper, + ) { + if self.contains_idx(idx) { + return; + } + + let id = self.arena.get_container_id(idx).unwrap(); + let key = id.to_bytes(); + if let Some(v) = self.kv.get(&key) { + let c = ContainerWrapper::new_from_bytes(v); + Self::insert_entry(&mut self.store, idx, c); + return; + } + + if let Some(journal) = &mut self.created_journal { + journal.push(idx); + } + let c = f(); + Self::insert_entry(&mut self.store, idx, c); + } + + /// Start recording the containers that get new state. See `created_journal`. + pub(crate) fn begin_created_journal(&mut self) { + self.created_journal = Some(Vec::new()); + } + + /// Stop recording and return the containers that got new state since + /// [`Self::begin_created_journal`]. + pub(crate) fn take_created_journal(&mut self) -> Vec<ContainerIdx> { + self.created_journal.take().unwrap_or_default() + } + + /// Drop the state of containers that got new state while a rolled back + /// local transaction ran. They had no state and no KV entry before it (the + /// KV store is only written by `flush`), so this restores the store. + pub(crate) fn remove_created(&mut self, created: &[ContainerIdx]) { + for &idx in created { + debug_assert!(self + .arena + .get_container_id(idx) + .is_none_or(|id| self.kv.get(&id.to_bytes()).is_none())); + if let Some(slot) = self.store.get_mut(Self::slot(idx)) { + *slot = None; + } + } + } + + pub(crate) fn get_mut(&mut self, idx: ContainerIdx) -> Option<&mut ContainerWrapper> { + if self.get_entry_mut(idx).is_none() { + let id = self.arena.get_container_id(idx).unwrap(); + let key = id.to_bytes(); + if let Some(v) = self.kv.get(&key) { + let c = ContainerWrapper::new_from_bytes(v); + Self::insert_entry(&mut self.store, idx, c); + } + } + + self.get_entry_mut(idx) + } + + pub(crate) fn with_container_for_read<R>( + &mut self, + idx: ContainerIdx, + f: impl FnOnce(&mut ContainerWrapper) -> R, + ) -> Option<R> { + if let Some(entry) = self.get_entry_mut(idx) { + let ans = f(entry); + self.track_value_cache(idx); + return Some(ans); + } + + let id = self.arena.get_container_id(idx).unwrap(); + let key = id.to_bytes(); + if let Some(v) = self.kv.get(&key) { + let mut container = ContainerWrapper::new_from_bytes(v); + let ans = f(&mut container); + if container.has_cached_value() { + Self::insert_entry(&mut self.store, idx, container); + self.track_value_cache(idx); + } + return Some(ans); + } + + None + } + + /// Track a wrapper whose read may have populated the decoded-value cache, + /// and evict the oldest cached values once the cache exceeds + /// the configured limit (2048 by default). + /// + /// Eviction drops the whole wrapper from `store`; the wrapper is a pure + /// cache over the KV bytes (`ContainerWrapper::is_evictable_cached_value` + /// requires a flushed lazy wrapper), so the next read re-creates it from + /// the KV store. + fn track_value_cache(&mut self, idx: ContainerIdx) { + let Some(entry) = self.get_entry_mut(idx) else { + return; + }; + if !entry.is_evictable_cached_value() { + return; + } + if !entry.is_in_value_cache_queue() { + entry.set_in_value_cache_queue(true); + self.value_cache_queue.push_back(idx); + } + self.get_entry_mut(idx) + .unwrap() + .mark_value_cache_referenced(); + + self.trim_value_cache(); + } + + /// Second-chance FIFO: hot ancestors survive an eviction pass during deep + /// walks. Only flushed lazy wrappers are evictable; dirty state stays pinned. + pub(super) fn trim_value_cache(&mut self) { + let limit = self.config.decoded_value_cache_limit(); + while self.value_cache_queue.len() > limit { + let Some(victim) = self.value_cache_queue.pop_front() else { + break; + }; + enum Action { + Skip, + Requeue, + Evict, + } + let action = match self.get_entry_mut(victim) { + Some(entry) if entry.is_evictable_cached_value() => { + if entry.take_value_cache_referenced() { + Action::Requeue + } else { + entry.set_in_value_cache_queue(false); + Action::Evict + } + } + // Stale entry: the wrapper was dropped or materialized into a + // full state since it was enqueued. + _ => Action::Skip, + }; + match action { + Action::Skip => {} + Action::Requeue => self.value_cache_queue.push_back(victim), + Action::Evict => { + let slot = Self::slot(victim); + if let Some(entry) = self.store.get_mut(slot) { + *entry = None; + } + // `store` may no longer mirror `kv`: a full enumeration has + // to re-scan `kv` even in `AllLoaded` mode. + self.evicted_since_full_load = true; + } + } + } + } + + /// Read a container without retaining a wrapper loaded only for this read. + pub(crate) fn try_with_container_for_ephemeral_read<R>( + &mut self, + idx: ContainerIdx, + f: impl FnOnce(&mut ContainerWrapper) -> R, + ) -> LoroResult<Option<R>> { + if let Some(entry) = self.get_entry_mut(idx) { + return Ok(Some(f(entry))); + } + + let id = self.arena.get_container_id(idx).unwrap(); + let key = id.to_bytes(); + if let Some(v) = self.kv.get(&key) { + let mut container = ContainerWrapper::try_new_from_bytes(v)?; + return Ok(Some(f(&mut container))); + } + + Ok(None) + } + + /// Read a container's current value without retaining a wrapper loaded only for this read. + /// + /// Mirrors [`Self::try_get_parent_and_value_ephemeral`]: routing the kv branch through + /// `ContainerWrapper::try_get_value_ephemeral` would clone the bytes into a second temporary + /// wrapper, so decode the already-temporary wrapper in place instead. + pub(crate) fn try_get_value_ephemeral( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext<'_>, + ) -> LoroResult<Option<LoroValue>> { + if let Some(entry) = self.get_entry_mut(idx) { + return entry.try_get_value_ephemeral(idx, ctx).map(Some); + } + + let id = self.arena.get_container_id(idx).unwrap(); + let key = id.to_bytes(); + if let Some(bytes) = self.kv.get(&key) { + let mut container = ContainerWrapper::try_new_from_bytes(bytes)?; + return container.try_get_value(idx, ctx).map(Some); + } + + Ok(None) + } + + /// Read a container's encoded parent and current value together without retaining a wrapper + /// loaded only for this read. + /// + /// The alive-container walk needs both fields. Reading them through two independent probes can + /// evict the first SSTable block before the value is requested, and it constructs the same lazy + /// wrapper twice. Decode an uncached wrapper in place here and drop it after returning the value. + pub(crate) fn try_get_parent_and_value_ephemeral( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext<'_>, + ) -> LoroResult<Option<(Option<ContainerID>, LoroValue)>> { + if let Some(entry) = self.get_entry_mut(idx) { + let parent = entry.parent().cloned(); + let value = entry.try_get_value_ephemeral(idx, ctx)?; + return Ok(Some((parent, value))); + } + + let id = self.arena.get_container_id(idx).unwrap(); + let key = id.to_bytes(); + if let Some(value) = self.kv.get(&key) { + let mut container = ContainerWrapper::try_new_from_bytes(value)?; + let parent = container.parent().cloned(); + // This wrapper is already temporary, so decoding into it does not retain state in + // the document and avoids constructing another temporary wrapper internally. + let value = container.try_get_value(idx, ctx)?; + return Ok(Some((parent, value))); + } + + Ok(None) + } + + /// Tree counterpart of [`Self::try_get_parent_and_value_ephemeral`]: the encoded parent and + /// the meta map ids of every node, deleted nodes included. + pub(crate) fn try_get_parent_and_tree_meta_ids_ephemeral( + &mut self, + idx: ContainerIdx, + ctx: ContainerCreationContext<'_>, + ) -> LoroResult<Option<(Option<ContainerID>, Vec<ContainerID>)>> { + if let Some(entry) = self.get_entry_mut(idx) { + let parent = entry.parent().cloned(); + let ids = entry.try_get_tree_meta_ids_ephemeral(idx, ctx)?; + return Ok(Some((parent, ids))); + } + + let id = self.arena.get_container_id(idx).unwrap(); + let key = id.to_bytes(); + if let Some(value) = self.kv.get(&key) { + let mut container = ContainerWrapper::try_new_from_bytes(value)?; + let parent = container.parent().cloned(); + container.decode_state(idx, ctx)?; + let ids = container.try_get_state().unwrap().get_child_containers(); + return Ok(Some((parent, ids))); + } + + Ok(None) + } + + /// Read the parent encoded in a container wrapper without retaining a wrapper loaded only + /// for this probe. + /// + /// The outer `Option` distinguishes a missing wrapper from a wrapper whose encoded parent is + /// `None`. + pub(crate) fn get_parent_ephemeral( + &mut self, + idx: ContainerIdx, + ) -> LoroResult<Option<Option<ContainerID>>> { + self.try_with_container_for_ephemeral_read(idx, |container| container.parent().cloned()) + } + + pub(crate) fn has_decoded_state(&mut self, idx: ContainerIdx) -> bool { + self.get_entry_mut(idx) + .is_some_and(|entry| entry.try_get_state().is_some()) + } + + pub(crate) fn contains_id(&mut self, id: &ContainerID) -> bool { + if let Some(idx) = self.arena.id_to_idx(id) { + if self.contains_idx(idx) { + return true; + } + } + + let key = id.to_bytes(); + self.kv.contains_key(&key) + } + + /// Tree and MovableList containers, found without decoding any other + /// container. A kv key starts with the container type byte, with the high + /// bit set for root ids (see `ContainerID::encode`), so each type is a key range. + pub(crate) fn tree_and_movable_list_idxs(&mut self) -> Vec<ContainerIdx> { + let mut keys: Vec<Bytes> = Vec::new(); + for ty in [ContainerType::Tree, ContainerType::MovableList] { + for root_bit in [0u8, 0b1000_0000] { + let lo = ty.to_u8() | root_bit; + keys.extend( + self.kv + .scan_range_entries(&[lo], &[lo + 1]) + .into_iter() + .map(|(k, _)| k), + ); + } + } + let mut out: FxHashSet<ContainerIdx> = FxHashSet::default(); + self.arena.with_guards(|guards| { + for k in keys { + out.insert(guards.register_container(&ContainerID::from_bytes(&k))); + } + }); + // Loaded entries can be newer than kv or absent from it. + for (slot, entry) in self.store.iter().enumerate() { + if let Some(c) = entry { + if matches!(c.kind(), ContainerType::Tree | ContainerType::MovableList) { + out.insert(ContainerIdx::from_index_and_type(slot as u32, c.kind())); + } + } + } + out.into_iter().collect() + } + + pub(crate) fn iter_all_containers_mut( + &mut self, + ) -> impl Iterator<Item = (ContainerIdx, &mut ContainerWrapper)> { + self.load_all(); + self.store + .iter_mut() + .enumerate() + .filter_map(|(slot, entry)| { + entry.as_mut().map(|container| { + ( + ContainerIdx::from_index_and_type(slot as u32, container.kind()), + container, + ) + }) + }) + } + + pub(crate) fn iter_all_container_ids(&mut self) -> impl Iterator<Item = ContainerID> + '_ { + // PERF: we don't need to load all the containers here + self.load_all(); + self.store.iter().enumerate().filter_map(|(slot, entry)| { + entry.as_ref().map(|container| { + let idx = ContainerIdx::from_index_and_type(slot as u32, container.kind()); + self.arena.get_container_id(idx).unwrap() + }) + }) + } + + pub(crate) fn encode(&mut self) -> Bytes { + self.flush(); + self.kv.export() + } + + pub(crate) fn flush(&mut self) { + let deleted = self.config.deleted_root_containers.lock(); + let mut updates = Vec::new(); + let mut deleted_roots = Vec::new(); + + for (slot, entry) in self.store.iter_mut().enumerate() { + let Some(c) = entry.as_mut() else { + continue; + }; + let idx = ContainerIdx::from_index_and_type(slot as u32, c.kind()); + let cid = self.arena.get_container_id(idx).unwrap(); + if cid.is_root() && deleted.contains(&cid) && c.is_deleted_root_value_cleared() { + deleted_roots.push(cid.to_bytes()); + c.set_flushed(true); + continue; + } + + if c.is_flushed() { + continue; + } + + let cid: Bytes = cid.to_bytes().into(); + let value = c.encode(); + c.set_flushed(true); + updates.push((cid, value)); + } + + drop(deleted); + for cid in deleted_roots { + self.kv.remove(&cid); + } + self.kv.set_all(updates); + } + + pub(crate) fn get_kv_clone(&self) -> KvWrapper { + self.kv.clone() + } + + pub(crate) fn decode( + &mut self, + bytes: bytes::Bytes, + ) -> Result<Option<Frontiers>, loro_common::LoroError> { + assert!(self.kv.is_empty()); + let mut fr = None; + self.kv + .import(bytes) + .map_err(|e| loro_common::LoroError::DecodeError(e.into_boxed_str()))?; + if let Some(f) = self.kv.remove(FRONTIERS_KEY) { + fr = Some(Frontiers::decode(&f)?); + } + + let kv = self.kv.arc_clone(); + self.arena + .set_parent_resolver(Some(move |child_id: ContainerID| { + let k = child_id.to_bytes(); + let v = kv.get(&k)?; + let c = ContainerWrapper::new_from_bytes(v); + c.parent().cloned() + })); + + self.store.clear(); + self.value_cache_queue.clear(); + self.evicted_since_full_load = false; + self.load_state = LoadState::Lazy; + Ok(fr) + } + + pub(crate) fn decode_twice( + &mut self, + bytes_a: bytes::Bytes, + bytes_b: bytes::Bytes, + ) -> Result<(), loro_common::LoroError> { + assert!(self.kv.is_empty()); + // TODO: add assert that all containers in the store should be empty right now + self.kv + .import(bytes_a) + .map_err(|e| loro_common::LoroError::DecodeError(e.into_boxed_str()))?; + self.kv + .import(bytes_b) + .map_err(|e| loro_common::LoroError::DecodeError(e.into_boxed_str()))?; + self.kv.remove(FRONTIERS_KEY); + let entries = self.kv.scan_all_entries(); + let store = &mut self.store; + let arena = &self.arena; + arena.with_guards(|guards| { + for (k, v) in entries { + let cid = ContainerID::from_bytes(&k); + let c = ContainerWrapper::new_from_bytes(v); + let parent = c.parent(); + let idx = guards.register_container(&cid); + let p = parent.as_ref().map(|p| guards.register_container(p)); + guards.set_parent(idx, p); + if Self::insert_entry(store, idx, c).is_some() {} + } + }); + + // Entries were rebuilt from the KV store; drop any queue entries that + // refer to replaced wrappers so the queue only names wrappers that are + // actually enqueued. + self.value_cache_queue.clear(); + for entry in self.store.iter_mut().flatten() { + entry.set_in_value_cache_queue(false); + } + + self.evicted_since_full_load = false; + self.load_state = LoadState::AllLoaded; + Ok(()) + } + + pub fn load_all(&mut self) { + if self.load_state == LoadState::AllLoaded && !self.evicted_since_full_load { + return; + } + + let entries = self.kv.scan_all_entries(); + let store = &mut self.store; + let arena = &self.arena; + arena.with_guards(|guards| { + for (k, v) in entries { + let cid = ContainerID::from_bytes(&k); + let idx = guards.register_container(&cid); + if Self::contains_idx_in(store, idx) { + // the container is already loaded + // the content in `store` is guaranteed to be newer than the content in `kv` + continue; + } + + let container = ContainerWrapper::new_from_bytes(v); + Self::insert_entry(store, idx, container); + } + }); + + self.evicted_since_full_load = false; + self.load_state = LoadState::AllLoaded; + } + + pub fn load_roots(&mut self) { + if self.load_state != LoadState::Lazy { + return; + } + + let arena = &self.arena; + let keys = self.kv.scan_all_keys(); + arena.with_guards(|guards| { + for k in keys { + let cid = ContainerID::from_bytes(&k); + if cid.is_root() { + guards.register_container(&cid); + } + } + }); + self.load_state = LoadState::RootsLoaded; + } + + pub(crate) fn can_import_snapshot(&self) -> bool { + if !self.kv.is_empty() { + return false; + } + + self.store + .iter() + .filter_map(|entry| entry.as_ref()) + .all(|c| c.is_state_empty()) + } + + #[cfg(test)] + pub(super) fn has_cached_value_for_test(&mut self, idx: ContainerIdx) -> bool { + self.get_entry_mut(idx) + .is_some_and(|entry| entry.has_cached_value_for_test()) + } + + /// Number of wrappers currently holding an evictable cached decoded value. + /// Must stay bounded by the configured limit no matter how many + /// containers have been read (loro-dev/loro#1092). + #[cfg(test)] + pub(super) fn cached_value_count_for_test(&self) -> usize { + self.store + .iter() + .flatten() + .filter(|entry| entry.is_evictable_cached_value()) + .count() + } + + #[cfg(test)] + pub(super) fn has_materialized_map_value_for_test(&mut self, idx: ContainerIdx) -> bool { + self.get_entry_mut(idx) + .is_some_and(|entry| entry.has_materialized_map_value_for_test()) + } +} + +impl InnerStore { + pub(crate) fn new(arena: SharedArena, config: Configure) -> Self { + Self { + arena, + store: Vec::new(), + kv: KvWrapper::new_mem(), + load_state: LoadState::AllLoaded, + config, + value_cache_queue: VecDeque::new(), + evicted_since_full_load: false, + created_journal: None, + } + } + + pub(crate) fn fork(&mut self, arena: SharedArena, config: &Configure) -> InnerStore { + // PERF: we can try to reuse + let bytes = self.encode(); + let mut new_store = Self::new(arena, config.clone()); + new_store.decode(bytes).unwrap(); + new_store + } +} + +#[cfg(test)] +mod tests { + use super::*; + use loro_common::{ContainerType, ID}; + use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }; + + fn encoded_container_header(kind: ContainerType, parent: Option<ContainerID>) -> Bytes { + let mut output = Vec::new(); + output.push(kind.to_u8()); + leb128::write::unsigned(&mut output, 2).unwrap(); + postcard::to_io(&parent, &mut output).unwrap(); + output.into() + } + + fn mergeable_child_entry() -> (ContainerID, Bytes) { + let parent_id = ContainerID::new_normal(ID::new(1, 0), ContainerType::Map); + let child_id = ContainerID::new_mergeable(&parent_id, "field", ContainerType::Text); + let value = encoded_container_header(ContainerType::Text, Some(parent_id)); + (child_id, value) + } + + fn install_parent_resolver_guard( + arena: &SharedArena, + loading: Arc<AtomicBool>, + ) -> Arc<AtomicBool> { + let resolver_called = Arc::new(AtomicBool::new(false)); + let called = resolver_called.clone(); + arena.set_parent_resolver(Some(move |_child_id: ContainerID| { + assert!( + !loading.load(Ordering::SeqCst), + "lazy parent resolver must not run while loading from KV" + ); + called.store(true, Ordering::SeqCst); + None + })); + resolver_called + } + + fn kv_bytes_with_entry(cid: ContainerID, value: Bytes) -> Bytes { + let kv = KvWrapper::new_mem(); + kv.set_all(vec![(Bytes::from(cid.to_bytes()), value)]); + kv.export() + } + + #[test] + fn load_all_does_not_resolve_parent_while_loading_from_kv() { + let arena = SharedArena::new(); + let mut store = InnerStore::new(arena.clone(), Configure::default()); + let loading = Arc::new(AtomicBool::new(false)); + let resolver_called = install_parent_resolver_guard(&arena, loading.clone()); + let (child_id, value) = mergeable_child_entry(); + let child_id_for_depth = child_id.clone(); + store.load_state = LoadState::Lazy; + store + .kv + .set_all(vec![(Bytes::from(child_id.to_bytes()), value)]); + + loading.store(true, Ordering::SeqCst); + store.load_all(); + loading.store(false, Ordering::SeqCst); + assert!(!resolver_called.load(Ordering::SeqCst)); + + let child_idx = arena.id_to_idx(&child_id_for_depth).unwrap(); + let _ = arena.get_depth(child_idx); + assert!( + resolver_called.load(Ordering::SeqCst), + "lazy parent resolver should still work after load_all returns" + ); + } + + #[test] + fn load_roots_does_not_resolve_parent_while_loading_from_kv() { + let arena = SharedArena::new(); + let mut store = InnerStore::new(arena.clone(), Configure::default()); + let loading = Arc::new(AtomicBool::new(false)); + let resolver_called = install_parent_resolver_guard(&arena, loading.clone()); + let (child_id, value) = mergeable_child_entry(); + let child_id_for_depth = child_id.clone(); + store.load_state = LoadState::Lazy; + store + .kv + .set_all(vec![(Bytes::from(child_id.to_bytes()), value)]); + + loading.store(true, Ordering::SeqCst); + store.load_roots(); + loading.store(false, Ordering::SeqCst); + assert!(!resolver_called.load(Ordering::SeqCst)); + + let child_idx = arena.id_to_idx(&child_id_for_depth).unwrap(); + let _ = arena.get_depth(child_idx); + assert!( + resolver_called.load(Ordering::SeqCst), + "lazy parent resolver should still work after load_roots returns" + ); + } + + #[test] + fn decode_twice_does_not_resolve_parent_while_loading_from_kv() { + let arena = SharedArena::new(); + let mut store = InnerStore::new(arena.clone(), Configure::default()); + let loading = Arc::new(AtomicBool::new(false)); + let resolver_called = install_parent_resolver_guard(&arena, loading.clone()); + let (child_id, value) = mergeable_child_entry(); + let child_id_for_depth = child_id.clone(); + let bytes = kv_bytes_with_entry(child_id, value); + + loading.store(true, Ordering::SeqCst); + store.decode_twice(bytes, Bytes::new()).unwrap(); + loading.store(false, Ordering::SeqCst); + assert!(!resolver_called.load(Ordering::SeqCst)); + + let child_idx = arena.id_to_idx(&child_id_for_depth).unwrap(); + let _ = arena.get_depth(child_idx); + assert!( + resolver_called.load(Ordering::SeqCst), + "lazy parent resolver should still work after decode_twice returns" + ); + } +} diff --git a/vendor/loro-internal/src/state/container_tree.rs b/vendor/loro-internal/src/state/container_tree.rs new file mode 100644 index 0000000..2c771dc --- /dev/null +++ b/vendor/loro-internal/src/state/container_tree.rs @@ -0,0 +1,269 @@ +//! Structured state traversal. Container identity comes from CRDT edges, never value shape. +//! A sink constructs the target representation without a whole-document intermediate tree. +use super::{deleted_root_container_value_is_cleared, visible_container_value_is_empty, DocState}; +use crate::{container::idx::ContainerIdx, ContainerType, LoroValue}; +use loro_common::{ContainerID, LoroError, LoroResult}; +use std::sync::atomic::Ordering; +#[derive(Debug)] +pub enum Event<'a> { + Object(usize), + Array(usize), + End, + Key(&'a str), + String(&'a str), + Number(f64), + Bool(bool), + Null, + Binary(&'a [u8]), +} +pub trait Sink { + fn emit(&mut self, e: Event<'_>) -> LoroResult<()>; + fn container(&mut self, id: &ContainerID) -> LoroResult<()>; + fn container_end(&mut self) -> LoroResult<()> { + self.emit(Event::End) + } + fn value_start(&mut self) -> LoroResult<()>; + fn value_end(&mut self) -> LoroResult<()>; +} +impl DocState { + pub fn read_container_tree<S: Sink>( + &mut self, + s: &mut S, + cid: Option<&ContainerID>, + rich: bool, + selected_roots: Option<&[String]>, + ) -> LoroResult<()> { + if let Some(id) = cid { + let idx = self.arena.register_container(id); + return self.read_container_node(s, idx, rich, None, None, 0); + } + let roots = self.preferred_root_containers(); + let mut visible = Vec::new(); + let selected: Option<std::collections::HashSet<&str>> = + selected_roots.map(|names| names.iter().map(String::as_str).collect()); + for idx in roots { + if let Some(names) = &selected { + let name = self + .root_container_name(idx) + .ok_or_else(|| err("Missing root name"))?; + if !names.contains(name.as_str()) { + continue; + } + } + if matches!(idx.get_type(), ContainerType::Unknown(_)) { + return Err(err("Unsupported container type")); + } + let id = self + .arena + .idx_to_id(idx) + .ok_or_else(|| err("Missing container ID"))?; + let hidden = self + .config + .hide_empty_root_containers + .load(Ordering::Relaxed); + let deleted = self.config.deleted_root_containers.lock().contains(&id); + let v = if hidden || deleted { + self.store + .try_get_value_ephemeral(idx)? + .or_else(|| Some(idx.get_type().default_value())) + } else { + None + }; + if v.as_ref().is_some_and(|v| { + (hidden && visible_container_value_is_empty(idx.get_type(), v)) + || (deleted && deleted_root_container_value_is_cleared(idx.get_type(), v)) + }) { + continue; + } + visible.push(( + self.root_container_name(idx) + .ok_or_else(|| err("Missing root name"))?, + idx, + v, + )); + } + s.emit(Event::Object(visible.len()))?; + for (key, idx, value) in visible { + s.emit(Event::Key(&key))?; + self.read_container_node(s, idx, rich, None, value, 0)?; + } + s.emit(Event::End) + } + /// Read a list window and its coordinates under the same state lock. + pub fn read_container_tree_slice<S: Sink>( + &mut self, + sink: &mut S, + cid: &ContainerID, + rich: bool, + start: usize, + end: usize, + ) -> LoroResult<(usize, usize)> { + let idx = self.arena.register_container(cid); + let kind = idx.get_type(); + if !matches!(kind, ContainerType::List | ContainerType::MovableList) { + return Err(err("Expected list container")); + } + let value = self + .store + .try_get_value_ephemeral(idx)? + .unwrap_or_else(|| kind.default_value()); + let total = value + .as_list() + .ok_or_else(|| err("Expected list value"))? + .len(); + let start = start.min(total); + self.read_container_node(sink, idx, rich, Some((start, end)), Some(value), 0)?; + Ok((start, total)) + } + fn read_container_node<S: Sink>( + &mut self, + s: &mut S, + idx: ContainerIdx, + rich: bool, + range: Option<(usize, usize)>, + value: Option<LoroValue>, + depth: usize, + ) -> LoroResult<()> { + check_depth(depth)?; + let id = self + .arena + .idx_to_id(idx) + .ok_or_else(|| err("Missing container ID"))?; + let kind = idx.get_type(); + if matches!(kind, ContainerType::Unknown(_)) { + return Err(err("Unsupported container type")); + } + let v = if rich && kind == ContainerType::Text { + self.store + .get_or_create_mut(idx) + .as_richtext_state_mut() + .ok_or_else(|| err("Missing text state"))? + .get_richtext_value() + } else { + match value { + Some(value) => value, + None => self + .store + .try_get_value_ephemeral(idx)? + .unwrap_or_else(|| kind.default_value()), + } + }; + s.container(&id)?; + + match (&v, kind) { + (LoroValue::Map(m), ContainerType::Map) => { + s.emit(Event::Object(m.len()))?; + for (k, v) in m.iter() { + s.emit(Event::Key(k))?; + let merge = loro_common::parse_mergeable_marker(&id, k, v) + .map(|t| ContainerID::new_mergeable(&id, k, t)); + if let Some(c) = merge { + let i = self.arena.register_container(&c); + self.read_container_node(s, i, rich, None, None, depth + 1)?; + } else { + self.read_container_edge(s, v, rich, depth + 1)?; + } + } + s.emit(Event::End)?; + } + (LoroValue::List(l), ContainerType::List | ContainerType::MovableList) => { + let (start, end) = range.unwrap_or((0, l.len())); + let start = start.min(l.len()); + let end = end.min(l.len()).max(start); + s.emit(Event::Array(end - start))?; + for v in &l[start..end] { + self.read_container_edge(s, v, rich, depth + 1)?; + } + s.emit(Event::End)?; + } + (_, ContainerType::Tree) => self.read_tree_nodes(s, &v, rich, depth + 1)?, + _ => raw(s, &v, depth + 1)?, + }; + s.container_end() + } + fn read_container_edge<S: Sink>( + &mut self, + s: &mut S, + v: &LoroValue, + rich: bool, + depth: usize, + ) -> LoroResult<()> { + if let LoroValue::Container(cid) = v { + let idx = self.arena.register_container(cid); + return self.read_container_node(s, idx, rich, None, None, depth); + } + s.value_start()?; + raw(s, v, depth + 1)?; + s.value_end() + } + fn read_tree_nodes<S: Sink>( + &mut self, + s: &mut S, + v: &LoroValue, + rich: bool, + depth: usize, + ) -> LoroResult<()> { + check_depth(depth)?; + match v { + LoroValue::List(l) => { + s.emit(Event::Array(l.len()))?; + for node in l.iter() { + let m = node.as_map().ok_or_else(|| err("Invalid tree node"))?; + s.emit(Event::Object(m.len()))?; + for (k, v) in m.iter() { + s.emit(Event::Key(k))?; + if k == "meta" { + self.read_container_edge(s, v, rich, depth + 1)?; + } else if k == "children" { + self.read_tree_nodes(s, v, rich, depth + 1)?; + } else { + raw(s, v, depth + 1)?; + } + } + s.emit(Event::End)?; + } + s.emit(Event::End) + } + _ => Err(err("Invalid tree value")), + } + } +} +pub fn err(s: &str) -> LoroError { + LoroError::JsError(s.to_string().into_boxed_str()) +} +fn raw<S: Sink>(s: &mut S, v: &LoroValue, depth: usize) -> LoroResult<()> { + check_depth(depth)?; + match v { + LoroValue::Null => s.emit(Event::Null), + LoroValue::Bool(b) => s.emit(Event::Bool(*b)), + // Match the existing JavaScript value conversion, including i64 -> number. + LoroValue::I64(n) => s.emit(Event::Number(*n as f64)), + LoroValue::Double(n) => s.emit(Event::Number(*n)), + LoroValue::Binary(v) => s.emit(Event::Binary(v)), + LoroValue::Container(id) => s.emit(Event::String(&id.to_string())), + LoroValue::String(v) => s.emit(Event::String(v)), + LoroValue::List(l) => { + s.emit(Event::Array(l.len()))?; + for v in l.iter() { + raw(s, v, depth + 1)?; + } + s.emit(Event::End) + } + LoroValue::Map(m) => { + s.emit(Event::Object(m.len()))?; + for (k, v) in m.iter() { + s.emit(Event::Key(k))?; + raw(s, v, depth + 1)?; + } + s.emit(Event::End) + } + } +} + +fn check_depth(depth: usize) -> LoroResult<()> { + if depth > 256 { + Err(err("toContainerTree nesting exceeds 256 levels")) + } else { + Ok(()) + } +} diff --git a/vendor/loro-internal/src/state/counter_state.rs b/vendor/loro-internal/src/state/counter_state.rs new file mode 100644 index 0000000..861f390 --- /dev/null +++ b/vendor/loro-internal/src/state/counter_state.rs @@ -0,0 +1,145 @@ +use std::sync::Weak; + +use loro_common::{ContainerID, LoroResult, LoroValue}; + +use crate::{ + configure::Configure, + container::idx::ContainerIdx, + event::{Diff, Index, InternalDiff}, + op::{Op, RawOp, RawOpContent}, + LoroDocInner, +}; + +use super::{ApplyLocalOpReturn, ContainerState, DiffApplyContext}; + +#[derive(Debug, Clone)] +pub struct CounterState { + idx: ContainerIdx, + value: f64, +} + +impl CounterState { + pub(crate) fn value(&self) -> f64 { + self.value + } + + /// For rolling back local ops (`DocState::finish_local_rollback`). + pub(crate) fn set_value(&mut self, value: f64) { + self.value = value; + } +} + +impl CounterState { + pub(crate) fn new(idx: ContainerIdx) -> Self { + Self { idx, value: 0. } + } +} + +impl ContainerState for CounterState { + fn container_idx(&self) -> ContainerIdx { + self.idx + } + + fn is_state_empty(&self) -> bool { + false + } + + fn apply_diff_and_convert(&mut self, diff: InternalDiff, _ctx: DiffApplyContext) -> Diff { + if let InternalDiff::Counter(diff) = diff { + self.value += diff; + Diff::Counter(diff) + } else { + unreachable!() + } + } + + fn apply_diff(&mut self, diff: InternalDiff, ctx: DiffApplyContext) -> LoroResult<()> { + let _ = self.apply_diff_and_convert(diff, ctx); + Ok(()) + } + + fn apply_local_op(&mut self, raw_op: &RawOp, _op: &Op) -> LoroResult<ApplyLocalOpReturn> { + if let RawOpContent::Counter(diff) = raw_op.content { + self.value += diff; + Ok(Default::default()) + } else { + unreachable!() + } + } + + #[doc = " Convert a state to a diff, such that an empty state will be transformed into the same as this state when it\'s applied."] + fn to_diff(&mut self, _doc: &Weak<LoroDocInner>) -> Diff { + Diff::Counter(self.value) + } + + fn get_value(&mut self) -> LoroValue { + LoroValue::Double(self.value) + } + + #[doc = " Get the index of the child container"] + #[allow(unused)] + fn get_child_index(&self, id: &ContainerID) -> Option<Index> { + None + } + + #[allow(unused)] + fn get_child_containers(&self) -> Vec<ContainerID> { + vec![] + } + + fn contains_child(&self, _id: &ContainerID) -> bool { + false + } + + fn fork(&self, _config: &Configure) -> Self { + self.clone() + } +} + +mod snapshot { + use crate::state::FastStateSnapshot; + + use super::*; + + impl FastStateSnapshot for CounterState { + fn encode_snapshot_fast<W: std::io::Write>(&mut self, mut w: W) { + let bytes = self.value.to_le_bytes(); + w.write_all(&bytes).unwrap(); + } + + fn decode_value(bytes: &[u8]) -> LoroResult<(LoroValue, &[u8])> { + // Builds without the counter feature can re-export an untouched counter as header only. + if bytes.is_empty() { + return Ok((LoroValue::Double(0.0), bytes)); + } + + if bytes.len() != 8 { + return Err(loro_common::LoroError::DecodeError( + "Decode counter value failed".to_string().into_boxed_str(), + )); + } + + let value = f64::from_le_bytes(bytes[..8].try_into().unwrap()); + Ok((LoroValue::Double(value), &bytes[8..])) + } + + fn decode_snapshot_fast( + idx: ContainerIdx, + v: (LoroValue, &[u8]), + _ctx: crate::state::ContainerCreationContext, + ) -> LoroResult<Self> + where + Self: Sized, + { + if !v.1.is_empty() { + return Err(loro_common::LoroError::DecodeError( + "Decode counter state failed".to_string().into_boxed_str(), + )); + } + + let mut counter = CounterState::new(idx); + counter.value = *v.0.as_double().unwrap(); + Ok(counter) + } + } +} diff --git a/vendor/loro-internal/src/state/dead_containers_cache.rs b/vendor/loro-internal/src/state/dead_containers_cache.rs new file mode 100644 index 0000000..33976d6 --- /dev/null +++ b/vendor/loro-internal/src/state/dead_containers_cache.rs @@ -0,0 +1,391 @@ +use super::DocState; +use crate::container::idx::ContainerIdx; +use loro_common::ContainerType; +use rustc_hash::FxHashSet; +use smallvec::SmallVec; + +/// Containers known to be deleted. See `context/dead-container-cache.md`. +#[derive(Default, Debug, Clone)] +pub(super) struct DeadContainersCache { + /// Removed from a Map or List: no later version gives them back. + final_deletions: FxHashSet<ContainerIdx>, + /// Cut off at a Tree or MovableList edge: a later move can revive them. + revivable: FxHashSet<ContainerIdx>, +} + +impl DeadContainersCache { + /// Must be called whenever the state may move to a version that is not a + /// descendant of the current one (checkout, reset), because that can + /// revive any container. + pub fn clear(&mut self) { + self.final_deletions.clear(); + self.clear_revivable(); + } + + /// Must be called whenever a tree or movable-list change is applied going + /// forward, because it may move a deleted node or element back. + pub fn clear_revivable(&mut self) { + // Reusing a large table makes interleaved deletion queries and moves + // repeatedly clear its peak capacity, even with only one live entry. + self.revivable = FxHashSet::default(); + } + + fn contains(&self, idx: &ContainerIdx) -> bool { + self.final_deletions.contains(idx) || self.revivable.contains(idx) + } +} + +impl DocState { + /// Called when a failed import is rolled back. The import may have registered parent links + /// that the arena rollback drops, and a deletion found through one of them while it ran + /// (e.g. by a query on another thread) is not true of the kept history. + /// See `context/failed-import-arena-indices.md`. + pub(crate) fn forget_parent_link_caches_after_failed_import(&mut self) { + self.dead_containers_cache.clear(); + } + + pub(crate) fn is_deleted(&mut self, idx: ContainerIdx) -> bool { + #[cfg(not(debug_assertions))] + { + if self.dead_containers_cache.contains(&idx) { + return true; + } + } + + // Parent chains are shallow (depth 1 for a root container), so inline + // storage avoids a heap allocation on this per-op check. + let mut visited: SmallVec<[ContainerIdx; 4]> = SmallVec::new(); + visited.push(idx); + let mut idx = idx; + let mut depends_on_mergeable_edge = false; + // The parent that no longer holds the chain, if any. + let (is_deleted, cut_at) = loop { + let id = self.arena.idx_to_id(idx).unwrap(); + if id.is_mergeable() { + depends_on_mergeable_edge = true; + } + if let Some(parent_idx) = self.arena.get_parent(idx) { + if !self.contains_logical_child(parent_idx, &id) { + break (true, Some(parent_idx)); + } + + idx = parent_idx; + visited.push(idx); + } else { + // No parent in the arena: top-level Roots are always alive; anything else + // (including a mergeable Root whose parent edge was never wired) is treated + // as deleted. A later op can still attach it, so this is never cached. + break (!id.is_root() || id.is_mergeable(), None); + } + }; + + // Every container on the walked chain shares the answer: below the + // missing edge all of them are deleted, otherwise all are alive. + #[cfg(debug_assertions)] + for idx in visited.iter() { + assert!( + is_deleted || !self.dead_containers_cache.contains(idx), + "stale dead-container cache entry for {:?}", + self.arena.idx_to_id(*idx) + ); + } + + // A mergeable ancestor can be deleted and later reactivated by changing the parent map's + // marker. Do not cache deletion for any descendant whose liveness depends on that + // logical edge, including ordinary children nested inside a mergeable map. + if is_deleted && !depends_on_mergeable_edge { + match cut_at.map(|parent| parent.get_type()) { + Some(ContainerType::Map | ContainerType::List) => { + self.dead_containers_cache.final_deletions.extend(visited) + } + Some(ContainerType::Tree | ContainerType::MovableList) => { + self.dead_containers_cache.revivable.extend(visited) + } + _ => {} + } + } + + is_deleted + } + + #[cfg(test)] + pub(crate) fn dead_cache_entry(&self, idx: ContainerIdx) -> Option<bool> { + self.dead_containers_cache.contains(&idx).then_some(true) + } +} + +#[cfg(test)] +#[cfg(feature = "counter")] +mod tests { + use loro_common::ContainerID; + + use crate::{cursor::PosType, HandlerTrait, LoroDoc, TextHandler}; + + /// A mergeable child can be deleted and then reactivated: `delete(key)` clears its + /// marker (child unreachable), and a later `ensure_mergeable_<kind>(key)` writes the + /// marker back (child reachable again). While the child is unreachable, querying its + /// liveness must not cache a `deleted` entry because that answer depends on the mutable + /// mergeable marker edge. + /// + /// The scenario: + /// 1. Create the mergeable counter and capture its container idx. + /// 2. Delete the key, then query `is_deleted()`. + /// 3. Re-get the counter to rewrite the marker and reactivate the child. + /// 4. Assert the cache never held a `deleted` entry for that idx. + /// + /// It asserts the cache contents directly because `is_deleted()` only trusts the cache via a + /// release-only early return; inspecting the cache makes stale-cache regressions fail in both + /// debug and release builds. + #[test] + fn reactivated_mergeable_child_has_no_stale_dead_cache_entry() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let root = doc.get_map("state"); + let counter = root.ensure_mergeable_counter("revision").unwrap(); + counter.increment(1.0).unwrap(); + doc.commit_then_renew(); + + let cid: ContainerID = counter.id(); + let idx = doc.state.lock().arena.id_to_idx(&cid).unwrap(); + + root.delete("revision").unwrap(); + doc.commit_then_renew(); + assert!(counter.is_deleted()); + assert_eq!( + doc.state.lock().dead_cache_entry(idx), + None, + "mergeable-dependent deletion must not be cached" + ); + + root.ensure_mergeable_counter("revision").unwrap(); + doc.commit_then_renew(); + assert_eq!( + doc.state.lock().dead_cache_entry(idx), + None, + "reactivation must drop the stale deleted-cache entry" + ); + } + + /// The no-cache rule also applies to ordinary descendants under a mergeable ancestor. A + /// regular child container can look cache-safe by cid shape, but its liveness still depends on + /// the ancestor's marker edge. + #[test] + fn ordinary_child_under_reactivated_mergeable_map_has_no_stale_dead_cache_entry() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let root = doc.get_map("state"); + let profile = root.ensure_mergeable_map("profile").unwrap(); + let text = profile + .insert_container("bio", TextHandler::new_detached()) + .unwrap(); + text.insert(0, "Ada", PosType::Unicode).unwrap(); + doc.commit_then_renew(); + + let text_id: ContainerID = text.id(); + let text_idx = doc.state.lock().arena.id_to_idx(&text_id).unwrap(); + + root.delete("profile").unwrap(); + doc.commit_then_renew(); + assert!(text.is_deleted()); + assert_eq!( + doc.state.lock().dead_cache_entry(text_idx), + None, + "ordinary descendants behind a mergeable edge must not be cached as deleted" + ); + + root.ensure_mergeable_map("profile").unwrap(); + doc.commit_then_renew(); + assert!(!text.is_deleted()); + assert_eq!( + doc.state.lock().dead_cache_entry(text_idx), + None, + "reactivated ordinary descendant must not leave a stale cache entry" + ); + } + + /// The same stale-cache hazard exists when reactivation arrives from a *peer* via import, + /// not just from a local `ensure_mergeable_*` call. The importing peer must not cache the + /// mergeable-dependent deleted result before the reactivation update arrives. + /// + /// The scenario, with two peers A (author) and B (importer): + /// 1. A creates the mergeable counter and deletes the key, then exports. + /// 2. B imports A's updates so the child exists but is unreachable, and queries + /// `is_deleted()`. + /// 3. A re-gets the counter (rewriting the marker, reactivating the child) and + /// exports just that new update. + /// 4. B imports the reactivation update. + /// 5. Assert B's cache never held a `deleted` entry for that idx. + /// + /// Like the local-reactivation test, this asserts cache contents directly rather than + /// through `is_deleted()`, because `is_deleted()` only trusts the cache via a release-only + /// early return; a public-API assertion would pass in debug even with the bug present. + #[test] + fn imported_mergeable_child_reactivation_clears_dead_cache() { + use crate::loro::ExportMode; + + let doc_a = LoroDoc::new_auto_commit(); + doc_a.set_peer_id(1).unwrap(); + let root_a = doc_a.get_map("state"); + let counter_a = root_a.ensure_mergeable_counter("revision").unwrap(); + counter_a.increment(1.0).unwrap(); + doc_a.commit_then_renew(); + root_a.delete("revision").unwrap(); + doc_a.commit_then_renew(); + + let cid: ContainerID = counter_a.id(); + + // B imports A's history: the child exists but is unreachable (marker cleared). + let doc_b = LoroDoc::new_auto_commit(); + doc_b.set_peer_id(2).unwrap(); + doc_b + .import(&doc_a.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + + let idx = doc_b.state.lock().arena.id_to_idx(&cid).unwrap(); + assert!(doc_b.state.lock().is_deleted(idx)); + assert_eq!( + doc_b.state.lock().dead_cache_entry(idx), + None, + "imported mergeable-dependent deletion must not be cached" + ); + + // A reactivates the child locally and exports just the new update. + let vv_before = doc_a.oplog_vv(); + root_a.ensure_mergeable_counter("revision").unwrap(); + doc_a.commit_then_renew(); + let reactivation = doc_a.export(ExportMode::updates(&vv_before)).unwrap(); + + // B imports the reactivation. There must be no stale deleted-cache entry left to mask it. + doc_b.import(&reactivation).unwrap(); + assert_eq!( + doc_b.state.lock().dead_cache_entry(idx), + None, + "imported reactivation must drop the stale deleted-cache entry" + ); + } + + /// A tree node under a deleted ancestor is revived by moving it out, so a + /// local move must drop the cached deletion of its metadata. + #[test] + fn local_tree_move_drops_revivable_deletions() { + use crate::state::TreeParentId; + + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let tree = doc.get_tree("tree"); + let parent = tree.create(TreeParentId::Root).unwrap(); + let child = tree.create(TreeParentId::Node(parent)).unwrap(); + let meta = tree.get_meta(child).unwrap(); + doc.commit_then_renew(); + tree.delete(parent).unwrap(); + doc.commit_then_renew(); + + let idx = doc.state.lock().arena.id_to_idx(&meta.id()).unwrap(); + assert!(meta.is_deleted()); + assert_eq!(doc.state.lock().dead_cache_entry(idx), Some(true)); + + tree.mov(child, TreeParentId::Root).unwrap(); + assert_eq!(doc.state.lock().dead_cache_entry(idx), None); + doc.commit_then_renew(); + assert!(!meta.is_deleted()); + } + + /// A movable-list element deleted locally is revived by a concurrent move + /// with a greater lamport, so importing movable-list changes must drop the + /// cached deletion. + #[test] + fn movable_list_import_drops_revivable_deletions() { + use crate::{loro::ExportMode, MapHandler}; + + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let list = doc.get_movable_list("list"); + list.insert(0, 0).unwrap(); + let child = list + .insert_container(1, MapHandler::new_detached()) + .unwrap(); + doc.commit_then_renew(); + let other = LoroDoc::new_auto_commit(); + other.set_peer_id(2).unwrap(); + other + .import(&doc.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + other.get_map("pad").insert("k", 1).unwrap(); + other.commit_then_renew(); + other.get_movable_list("list").mov(1, 0).unwrap(); + other.commit_then_renew(); + + list.delete(1, 1).unwrap(); + doc.commit_then_renew(); + let idx = doc.state.lock().arena.id_to_idx(&child.id()).unwrap(); + assert!(child.is_deleted()); + assert_eq!(doc.state.lock().dead_cache_entry(idx), Some(true)); + + doc.import(&other.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + assert_eq!(doc.state.lock().dead_cache_entry(idx), None); + assert!(!child.is_deleted()); + } + + /// Map and list removals are final for every later version, so they are + /// cached for the child and everything below it. + #[test] + fn map_and_list_child_deletions_are_cached() { + use crate::{ListHandler, MapHandler}; + + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let map = doc.get_map("map"); + let in_map = map + .insert_container("k", MapHandler::new_detached()) + .unwrap(); + let nested = in_map + .insert_container("t", TextHandler::new_detached()) + .unwrap(); + let list = doc.get_list("list"); + let in_list = list + .insert_container(0, ListHandler::new_detached()) + .unwrap(); + doc.commit_then_renew(); + map.delete("k").unwrap(); + list.delete(0, 1).unwrap(); + doc.commit_then_renew(); + + assert!(nested.is_deleted()); + assert!(in_list.is_deleted()); + let state = doc.state.lock(); + for id in [in_map.id(), nested.id(), in_list.id()] { + let idx = state.arena.id_to_idx(&id).unwrap(); + assert_eq!(state.dead_cache_entry(idx), Some(true), "{id:?}"); + } + } + + /// While checked out to an older version, a map child created later is + /// cut at its map parent and cached as a final deletion. A forward + /// checkout is not a `DiffMode::Checkout` transition, but it must still + /// drop that entry. + #[test] + fn forward_checkout_drops_deletions_cached_behind_the_oplog() { + use crate::MapHandler; + + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let map = doc.get_map("m"); + map.insert("a", 1).unwrap(); + doc.commit_then_renew(); + let v1 = doc.oplog_frontiers(); + let child = map + .insert_container("c", MapHandler::new_detached()) + .unwrap(); + doc.commit_then_renew(); + + doc.checkout(&v1).unwrap(); + let idx = doc.state.lock().arena.id_to_idx(&child.id()).unwrap(); + assert!(child.is_deleted()); + assert_eq!(doc.state.lock().dead_cache_entry(idx), Some(true)); + + doc.checkout_to_latest(); + assert_eq!(doc.state.lock().dead_cache_entry(idx), None); + assert!(!child.is_deleted()); + } +} diff --git a/vendor/loro-internal/src/state/list_state.rs b/vendor/loro-internal/src/state/list_state.rs new file mode 100644 index 0000000..bd4ff50 --- /dev/null +++ b/vendor/loro-internal/src/state/list_state.rs @@ -0,0 +1,972 @@ +use std::{io::Write, ops::RangeBounds, sync::Weak}; + +use super::{ApplyLocalOpReturn, ContainerState, DiffApplyContext, FastStateSnapshot}; +use crate::{ + configure::Configure, + container::{idx::ContainerIdx, list::list_op::ListOp, ContainerID}, + event::{Diff, Index, InternalDiff, ListDiff}, + handler::ValueOrHandler, + op::{ListSlice, Op, RawOp, RawOpContent}, + LoroDocInner, LoroValue, +}; + +use generic_btree::{ + iter, + rle::{CanRemove, HasLength, Mergeable, Sliceable, TryInsert}, + BTree, BTreeTrait, Cursor, LeafIndex, LengthFinder, UseLengthFinder, +}; +use loro_common::{IdFull, LoroError, LoroResult, ID}; +use loro_delta::array_vec::ArrayVec; +use rustc_hash::FxHashMap; +use smallvec::SmallVec; + +const TINY_LIST_MAX: usize = 4; + +#[derive(Debug)] +pub struct ListState { + idx: ContainerIdx, + list: ListEntries, +} + +impl Clone for ListState { + fn clone(&self) -> Self { + Self { + idx: self.idx, + list: self.list.clone(), + } + } +} + +#[derive(Debug, Clone)] +pub(crate) struct Elem { + pub v: LoroValue, + pub id: IdFull, +} + +impl HasLength for Elem { + fn rle_len(&self) -> usize { + 1 + } +} + +impl Sliceable for Elem { + fn _slice(&self, range: std::ops::Range<usize>) -> Self { + assert_eq!(range.start, 0); + assert_eq!(range.end, 1); + self.clone() + } + + fn split(&mut self, _pos: usize) -> Self { + unreachable!() + } +} + +impl Mergeable for Elem { + fn can_merge(&self, _rhs: &Self) -> bool { + false + } + + fn merge_right(&mut self, _rhs: &Self) { + unreachable!() + } + + fn merge_left(&mut self, _left: &Self) { + unreachable!() + } +} + +impl TryInsert for Elem { + fn try_insert(&mut self, _pos: usize, _elem: Self) -> Result<(), Self> { + Err(_elem) + } +} + +impl CanRemove for Elem { + fn can_remove(&self) -> bool { + false + } +} + +struct ListImpl; +impl BTreeTrait for ListImpl { + type Elem = Elem; + type Cache = isize; + type CacheDiff = isize; + const USE_DIFF: bool = true; + + #[inline(always)] + fn calc_cache_internal( + cache: &mut Self::Cache, + caches: &[generic_btree::Child<Self>], + ) -> Self::CacheDiff { + let mut new_cache = 0; + for child in caches { + new_cache += child.cache; + } + + let diff = new_cache - *cache; + *cache = new_cache; + diff + } + + #[inline(always)] + fn apply_cache_diff(cache: &mut Self::Cache, diff: &Self::CacheDiff) { + *cache += diff; + } + + #[inline(always)] + fn merge_cache_diff(diff1: &mut Self::CacheDiff, diff2: &Self::CacheDiff) { + *diff1 += diff2 + } + + #[inline(always)] + fn get_elem_cache(_elem: &Self::Elem) -> Self::Cache { + 1 + } + + #[inline(always)] + fn new_cache_to_diff(cache: &Self::Cache) -> Self::CacheDiff { + *cache + } + + fn sub_cache(cache_lhs: &Self::Cache, cache_rhs: &Self::Cache) -> Self::CacheDiff { + cache_lhs - cache_rhs + } +} + +impl UseLengthFinder<ListImpl> for ListImpl { + fn get_len(cache: &isize) -> usize { + *cache as usize + } +} + +#[derive(Debug, Clone)] +enum ListEntries { + Tiny { + entries: SmallVec<[Elem; 1]>, + child_container_to_index: FxHashMap<ContainerID, usize>, + }, + Tree { + tree: BTree<ListImpl>, + child_container_to_index: FxHashMap<ContainerID, LeafIndex>, + }, +} + +impl ListEntries { + fn new_tiny() -> Self { + Self::Tiny { + entries: SmallVec::new(), + child_container_to_index: Default::default(), + } + } + + fn is_empty(&self) -> bool { + match self { + Self::Tiny { entries, .. } => entries.is_empty(), + Self::Tree { tree, .. } => tree.is_empty(), + } + } + + fn len(&self) -> usize { + match self { + Self::Tiny { entries, .. } => entries.len(), + Self::Tree { tree, .. } => *tree.root_cache() as usize, + } + } + + fn iter(&self) -> Box<dyn Iterator<Item = &Elem> + '_> { + match self { + Self::Tiny { entries, .. } => Box::new(entries.iter()), + Self::Tree { tree, .. } => Box::new(tree.iter()), + } + } +} + +impl ListState { + pub fn new(idx: ContainerIdx) -> Self { + Self { + idx, + list: ListEntries::new_tiny(), + } + } + + fn rebuild_tiny_child_index(&mut self) { + let ListEntries::Tiny { + entries, + child_container_to_index, + } = &mut self.list + else { + return; + }; + + child_container_to_index.clear(); + for (index, elem) in entries.iter().enumerate() { + if let LoroValue::Container(id) = &elem.v { + child_container_to_index.insert(id.clone(), index); + } + } + } + + fn upgrade_to_tree(&mut self) { + let ListEntries::Tiny { entries, .. } = + std::mem::replace(&mut self.list, ListEntries::new_tiny()) + else { + return; + }; + + let mut tree = BTree::new(); + let mut child_container_to_index = FxHashMap::default(); + for elem in entries { + let container = elem.v.as_container().cloned(); + let leaf = tree.push(elem); + if let Some(container) = container { + child_container_to_index.insert(container, leaf.leaf); + } + } + + self.list = ListEntries::Tree { + tree, + child_container_to_index, + }; + } + + fn downgrade_tree_if_tiny(&mut self) { + let ListEntries::Tree { tree, .. } = &self.list else { + return; + }; + + if *tree.root_cache() as usize > TINY_LIST_MAX { + return; + } + + let entries = tree.iter().cloned().collect(); + self.list = ListEntries::Tiny { + entries, + child_container_to_index: Default::default(), + }; + self.rebuild_tiny_child_index(); + } + + pub fn contains_child_container(&self, id: &ContainerID) -> bool { + match &self.list { + ListEntries::Tiny { + entries, + child_container_to_index, + } => child_container_to_index.get(id).is_some_and(|index| { + entries + .get(*index) + .is_some_and(|elem| elem.v.as_container() == Some(id)) + }), + ListEntries::Tree { + tree, + child_container_to_index, + } => child_container_to_index + .get(id) + .is_some_and(|leaf| tree.get_elem(*leaf).is_some()), + } + } + + pub fn get_child_container_index(&self, id: &ContainerID) -> Option<usize> { + let (leaf, list) = match &self.list { + ListEntries::Tiny { + entries, + child_container_to_index, + } => { + let index = *child_container_to_index.get(id)?; + entries.get(index)?; + return Some(index); + } + ListEntries::Tree { + tree, + child_container_to_index, + } => (*child_container_to_index.get(id)?, tree), + }; + + list.get_elem(leaf)?; + let mut index = 0; + list.visit_previous_caches(Cursor { leaf, offset: 0 }, |cache| match cache { + generic_btree::PreviousCache::NodeCache(cache) => { + index += *cache; + } + generic_btree::PreviousCache::PrevSiblingElem(..) => { + index += 1; + } + generic_btree::PreviousCache::ThisElemAndOffset { .. } => {} + }); + + Some(index as usize) + } + + pub fn insert(&mut self, index: usize, value: LoroValue, id: IdFull) { + if index > self.len() { + panic!("Index {index} out of range. The length is {}", self.len()); + } + + if let ListEntries::Tiny { entries, .. } = &mut self.list { + if entries.len() < TINY_LIST_MAX { + entries.insert( + index, + Elem { + v: value.clone(), + id, + }, + ); + self.rebuild_tiny_child_index(); + return; + } + + self.upgrade_to_tree(); + } + + let ListEntries::Tree { + tree, + child_container_to_index, + } = &mut self.list + else { + unreachable!() + }; + let (leaf, data) = tree.insert::<LengthFinder>( + &index, + Elem { + v: value.clone(), + id, + }, + ); + + if value.is_container() { + child_container_to_index.insert(value.into_container().unwrap(), leaf.leaf); + } + + assert!(data.arr.is_empty()); + } + + pub fn push(&mut self, value: LoroValue, id: IdFull) { + if let ListEntries::Tiny { entries, .. } = &mut self.list { + if entries.len() < TINY_LIST_MAX { + entries.push(Elem { + v: value.clone(), + id, + }); + self.rebuild_tiny_child_index(); + return; + } + + self.upgrade_to_tree(); + } + + let ListEntries::Tree { + tree, + child_container_to_index, + } = &mut self.list + else { + unreachable!() + }; + let leaf = tree.push(Elem { + v: value.clone(), + id, + }); + + if value.is_container() { + child_container_to_index.insert(value.into_container().unwrap(), leaf.leaf); + } + } + + pub fn delete(&mut self, index: usize) -> LoroValue { + if let ListEntries::Tiny { entries, .. } = &mut self.list { + let elem = entries.remove(index); + self.rebuild_tiny_child_index(); + return elem.v; + } + + let ListEntries::Tree { + tree, + child_container_to_index, + } = &mut self.list + else { + unreachable!() + }; + let leaf = tree.query::<LengthFinder>(&index); + let leaf = tree.remove_leaf(leaf.unwrap().cursor).unwrap(); + if leaf.v.is_container() { + child_container_to_index.remove(leaf.v.as_container().unwrap()); + } + self.downgrade_tree_if_tiny(); + leaf.v + } + + pub fn delete_range( + &mut self, + range: impl RangeBounds<usize>, + mut notify_deletion: Option<&mut Vec<ContainerID>>, + ) { + let start: usize = match range.start_bound() { + std::ops::Bound::Included(x) => *x, + std::ops::Bound::Excluded(x) => *x + 1, + std::ops::Bound::Unbounded => 0, + }; + let end: usize = match range.end_bound() { + std::ops::Bound::Included(x) => *x + 1, + std::ops::Bound::Excluded(x) => *x, + std::ops::Bound::Unbounded => self.len(), + }; + + if let ListEntries::Tiny { entries, .. } = &mut self.list { + for elem in entries.drain(start..end) { + if let LoroValue::Container(c) = elem.v { + if let Some(notify_deletion) = &mut notify_deletion { + notify_deletion.push(c); + } + } + } + self.rebuild_tiny_child_index(); + return; + } + + if end - start == 1 { + if let LoroValue::Container(c) = self.delete(start) { + if let Some(notify_deletion) = &mut notify_deletion { + notify_deletion.push(c); + } + } + return; + } + + let ListEntries::Tree { + tree, + child_container_to_index, + } = &mut self.list + else { + unreachable!() + }; + let q = start..end; + let start1 = tree.query::<LengthFinder>(&q.start); + let end1 = tree.query::<LengthFinder>(&q.end); + for v in iter::Drain::new(tree, start1, end1) { + if v.v.is_container() { + child_container_to_index.remove(v.v.as_container().unwrap()); + if let Some(notify_deletion) = &mut notify_deletion { + notify_deletion.push(v.v.into_container().unwrap()); + } + } + } + self.downgrade_tree_if_tiny(); + } + + // PERF: use &[LoroValue] + // PERF: batch + pub fn insert_batch(&mut self, index: usize, values: Vec<LoroValue>, start_id: IdFull) { + let mut id = start_id; + for (i, value) in values.into_iter().enumerate() { + self.insert(index + i, value, id); + id = id.inc(1); + } + } + + pub fn iter(&self) -> impl Iterator<Item = &LoroValue> { + self.iter_with_id().map(|x| &x.v) + } + + #[allow(unused)] + pub(crate) fn iter_with_id(&self) -> Box<dyn Iterator<Item = &Elem> + '_> { + self.list.iter() + } + + pub fn len(&self) -> usize { + self.list.len() + } + + fn to_vec(&self) -> Vec<LoroValue> { + let mut ans = Vec::with_capacity(self.len()); + for value in self.list.iter() { + ans.push(value.v.clone()); + } + ans + } + + pub fn get(&self, index: usize) -> Option<&LoroValue> { + match &self.list { + ListEntries::Tiny { entries, .. } => entries.get(index).map(|elem| &elem.v), + ListEntries::Tree { tree, .. } => { + let result = tree.query::<LengthFinder>(&index)?; + if result.found { + Some(&result.elem(tree).unwrap().v) + } else { + None + } + } + } + } + + pub fn get_id_at(&self, index: usize) -> Option<IdFull> { + match &self.list { + ListEntries::Tiny { entries, .. } => entries.get(index).map(|elem| elem.id), + ListEntries::Tree { tree, .. } => { + let result = tree.query::<LengthFinder>(&index)?; + if result.found { + Some(result.elem(tree).unwrap().id) + } else { + None + } + } + } + } + + #[allow(unused)] + pub(crate) fn check(&self) { + for value in self.iter() { + if let LoroValue::Container(c) = value { + self.get_child_index(c).unwrap(); + } + } + } + + pub fn get_index_of_id(&self, id: ID) -> Option<usize> { + for (i, elem) in self.iter_with_id().enumerate() { + if elem.id.id() == id { + return Some(i); + } + } + None + } +} + +impl ContainerState for ListState { + fn container_idx(&self) -> ContainerIdx { + self.idx + } + + fn is_state_empty(&self) -> bool { + self.list.is_empty() + } + + fn apply_diff_and_convert( + &mut self, + diff: InternalDiff, + DiffApplyContext { doc, .. }: DiffApplyContext, + ) -> Diff { + let InternalDiff::ListRaw(delta) = diff else { + unreachable!() + }; + let mut ans: ListDiff = ListDiff::default(); + let mut index = 0; + let doc = &doc.upgrade().unwrap(); + for span in delta.iter() { + match span { + crate::delta::DeltaItem::Retain { retain: len, .. } => { + index += len; + ans.push_retain(*len, Default::default()); + } + crate::delta::DeltaItem::Insert { insert: value, .. } => { + let mut arr = Vec::new(); + match &value.values { + either::Either::Left(values) => arr.extend_from_slice(values.as_slice()), + either::Either::Right(v) => arr.push(v.clone()), + } + for arr in ArrayVec::from_many( + arr.iter() + .map(|v| ValueOrHandler::from_value(v.clone(), doc)), + ) { + ans.push_insert(arr, Default::default()); + } + let len = arr.len(); + self.insert_batch(index, arr, value.id); + index += len; + } + crate::delta::DeltaItem::Delete { delete: len, .. } => { + self.delete_range(index..index + len, None); + ans.push_delete(*len); + } + } + } + + Diff::List(ans) + } + + fn validate_diff(&self, diff: &InternalDiff) -> LoroResult<()> { + let InternalDiff::ListRaw(delta) = diff else { + unreachable!() + }; + + let mut cursor = 0usize; + let mut projected = self.len(); + for span in delta.iter() { + match span { + crate::delta::DeltaItem::Retain { retain: len, .. } => { + cursor += len; + if cursor > projected { + return Err(LoroError::internal(format!( + "list diff retains {cursor} items but state only has {projected}", + ))); + } + } + crate::delta::DeltaItem::Insert { insert: value, .. } => { + let len = match &value.values { + either::Either::Left(values) => values.len(), + either::Either::Right(_) => 1, + }; + if cursor > projected { + return Err(LoroError::internal(format!( + "list diff inserts at {cursor} but state only has {projected}", + ))); + } + cursor += len; + projected += len; + } + crate::delta::DeltaItem::Delete { delete: len, .. } => { + if cursor + len > projected { + return Err(LoroError::internal(format!( + "list diff deletes {len} at {cursor} but state only has {projected}", + ))); + } + projected -= len; + } + } + } + + Ok(()) + } + + fn apply_diff(&mut self, diff: InternalDiff, _: DiffApplyContext) -> LoroResult<()> { + match diff { + InternalDiff::ListRaw(delta) => { + let mut index = 0; + for span in delta.iter() { + match span { + crate::delta::DeltaItem::Retain { retain: len, .. } => { + index += len; + } + crate::delta::DeltaItem::Insert { insert: value, .. } => { + let mut arr = Vec::new(); + match &value.values { + either::Either::Left(values) => { + arr.extend_from_slice(values.as_slice()) + } + either::Either::Right(v) => arr.push(v.clone()), + } + + let len = arr.len(); + self.insert_batch(index, arr, value.id); + index += len; + } + crate::delta::DeltaItem::Delete { delete: len, .. } => { + self.delete_range(index..index + len, None); + } + } + } + } + _ => unreachable!(), + } + Ok(()) + } + + fn apply_local_op(&mut self, op: &RawOp, _: &Op) -> LoroResult<ApplyLocalOpReturn> { + let mut ans: ApplyLocalOpReturn = Default::default(); + match &op.content { + RawOpContent::List(list) => match list { + ListOp::Insert { slice, pos } => match slice { + ListSlice::RawData(list) => match list { + std::borrow::Cow::Borrowed(list) => { + self.insert_batch(*pos, list.to_vec(), op.id_full()); + } + std::borrow::Cow::Owned(list) => { + self.insert_batch(*pos, list.clone(), op.id_full()); + } + }, + _ => unreachable!(), + }, + ListOp::Delete(del) => { + self.delete_range(del.span.to_urange(), Some(&mut ans.deleted_containers)); + } + ListOp::Move { .. } => { + unreachable!() + } + ListOp::StyleStart { .. } => unreachable!(), + ListOp::StyleEnd { .. } => unreachable!(), + ListOp::Set { .. } => { + unreachable!() + } + }, + _ => unreachable!(), + } + Ok(ans) + } + + #[doc = " Convert a state to a diff that when apply this diff on a empty state,"] + #[doc = " the state will be the same as this state."] + fn to_diff(&mut self, doc: &Weak<LoroDocInner>) -> Diff { + let doc = &doc.upgrade().unwrap(); + Diff::List(ListDiff::from_many( + self.to_vec() + .into_iter() + .map(|v| ValueOrHandler::from_value(v, doc)), + )) + } + + fn get_value(&mut self) -> LoroValue { + let ans = self.to_vec(); + LoroValue::List(ans.into()) + } + + fn get_child_index(&self, id: &ContainerID) -> Option<Index> { + self.get_child_container_index(id).map(Index::Seq) + } + + fn contains_child(&self, id: &ContainerID) -> bool { + self.contains_child_container(id) + } + + fn get_child_containers(&self) -> Vec<ContainerID> { + let mut ans = Vec::new(); + for elem in self.iter_with_id() { + if elem.v.is_container() { + ans.push(elem.v.as_container().unwrap().clone()); + } + } + ans + } + + fn fork(&self, _config: &Configure) -> Self { + self.clone() + } +} + +mod snapshot { + use loro_common::PeerID; + use serde_columnar::columnar; + + use crate::{ + encoding::value_register::ValueRegister, + state::{ + decode_lamport_from_delta, decode_peer_from_table, decode_peer_table, + state_decode_error, ContainerCreationContext, + }, + }; + + use super::*; + #[columnar(vec, ser, de, iterable)] + #[derive(Debug, Clone)] + struct EncodedListId { + #[columnar(strategy = "DeltaRle")] + peer_idx: usize, + #[columnar(strategy = "DeltaRle")] + counter: i32, + #[columnar(strategy = "DeltaRle")] + lamport_sub_counter: i32, + } + + #[columnar(ser, de)] + struct EncodedListIds { + #[columnar(class = "vec", iter = "EncodedListId")] + ids: Vec<EncodedListId>, + } + + impl FastStateSnapshot for ListState { + /// Encodes the ListState snapshot in a compact binary format: + /// 1. Encodes the list values using postcard serialization + /// 2. Encodes a table of unique peer IDs + /// 3. For each element, encodes its ID as: + /// - Index of the peer ID in the table (LEB128) + /// - Counter (LEB128) + /// - Lamport timestamp (LEB128) + fn encode_snapshot_fast<W: Write>(&mut self, mut w: W) { + let value = self.get_value().into_list().unwrap(); + postcard::to_io(&*value, &mut w).unwrap(); + let mut peers: ValueRegister<PeerID> = ValueRegister::new(); + let mut ids = Vec::with_capacity(self.len()); + for elem in self.iter_with_id() { + let id = elem.id; + let peer_idx = peers.register(&id.peer); + ids.push(EncodedListId { + peer_idx, + counter: id.counter, + lamport_sub_counter: (id.lamport as i32 - id.counter), + }); + } + + let peers = peers.unwrap_vec(); + leb128::write::unsigned(&mut w, peers.len() as u64).unwrap(); + for peer in peers { + w.write_all(&peer.to_le_bytes()).unwrap(); + } + + let id_bytes = serde_columnar::to_vec(&EncodedListIds { ids }).unwrap(); + w.write_all(&id_bytes).unwrap(); + } + fn decode_value(bytes: &[u8]) -> LoroResult<(LoroValue, &[u8])> { + crate::state::value_decode::decode_collection(bytes, false) + } + + fn decode_snapshot_fast( + idx: ContainerIdx, + (v, mut bytes): (LoroValue, &[u8]), + _ctx: ContainerCreationContext, + ) -> LoroResult<Self> + where + Self: Sized, + { + let peers = decode_peer_table(&mut bytes, "Decode list state failed")?; + + let EncodedListIds { ids } = serde_columnar::from_bytes(bytes).map_err(|err| { + state_decode_error(format!("Decode list state failed: invalid id table: {err}")) + })?; + + let list = v.as_list().unwrap(); + if ids.len() != list.len() { + return Err(state_decode_error( + "Decode list state failed: id/value length mismatch", + )); + } + + let mut ans = Self::new(idx); + for (i, id) in ids.into_iter().enumerate() { + let peer = decode_peer_from_table(&peers, id.peer_idx, "Decode list state failed")?; + ans.insert( + i, + list[i].clone(), + IdFull::new( + peer, + id.counter, + decode_lamport_from_delta( + id.counter, + id.lamport_sub_counter, + "Decode list state failed", + )?, + ), + ); + } + + Ok(ans) + } + } + + #[cfg(test)] + mod tests { + use loro_common::LoroValue; + + use crate::{container::idx::ContainerIdx, state::ContainerCreationContext}; + + use super::*; + + #[test] + fn list_fast_snapshot_rejects_negative_counter() { + let mut bytes = Vec::new(); + postcard::to_io(&vec![LoroValue::I64(1)], &mut bytes).unwrap(); + leb128::write::unsigned(&mut bytes, 1).unwrap(); + bytes.extend_from_slice(&1_u64.to_le_bytes()); + bytes.extend_from_slice( + &serde_columnar::to_vec(&EncodedListIds { + ids: vec![EncodedListId { + peer_idx: 0, + counter: -1, + lamport_sub_counter: 1, + }], + }) + .unwrap(), + ); + + let idx = ContainerIdx::from_index_and_type(0, loro_common::ContainerType::List); + let (value, state_bytes) = ListState::decode_value(&bytes).unwrap(); + assert!(ListState::decode_snapshot_fast( + idx, + (value, state_bytes), + ContainerCreationContext { + configure: &Default::default(), + peer: 0, + }, + ) + .is_err()); + } + } +} + +#[cfg(test)] +mod test { + use itertools::Itertools; + use loro_common::{Counter, Lamport}; + + use crate::state::ContainerCreationContext; + + use super::*; + + #[test] + fn test() { + let mut list = ListState::new(ContainerIdx::from_index_and_type( + 0, + loro_common::ContainerType::List, + )); + fn id(name: &str) -> ContainerID { + ContainerID::new_root(name, crate::ContainerType::List) + } + list.insert(0, LoroValue::Container(id("abc")), IdFull::new(0, 0, 0)); + list.insert(0, LoroValue::Container(id("x")), IdFull::new(0, 0, 0)); + assert_eq!(list.get_child_container_index(&id("x")), Some(0)); + assert_eq!(list.get_child_container_index(&id("abc")), Some(1)); + list.insert(1, LoroValue::Bool(false), IdFull::new(0, 0, 0)); + assert_eq!(list.get_child_container_index(&id("x")), Some(0)); + assert_eq!(list.get_child_container_index(&id("abc")), Some(2)); + } + + #[test] + fn test_list_fast_snapshot() { + let mut list = ListState::new(ContainerIdx::from_index_and_type( + 0, + loro_common::ContainerType::List, + )); + let mut w = Vec::new(); + list.encode_snapshot_fast(&mut w); + println!("Empty: {}", w.len()); + + list.insert(0, LoroValue::I64(0), IdFull::new(0, 0, 0)); + list.insert(1, LoroValue::I64(2), IdFull::new(1, 1, 1)); + list.insert(2, LoroValue::I64(4), IdFull::new(1, 2, 2)); + let mut w = Vec::new(); + list.encode_snapshot_fast(&mut w); + assert!(w.len() <= 39, "w.len() = {}", w.len()); + let (v, left) = ListState::decode_value(&w).unwrap(); + let mut new_list = ListState::decode_snapshot_fast( + ContainerIdx::from_index_and_type(0, loro_common::ContainerType::List), + (v.clone(), left), + ContainerCreationContext { + configure: &Default::default(), + peer: 0, + }, + ) + .unwrap(); + new_list.check(); + assert_eq!( + new_list.get_value(), + vec![LoroValue::I64(0), LoroValue::I64(2), LoroValue::I64(4)].into() + ); + assert_eq!(new_list.get_value(), v); + let v = new_list.list.iter().collect_vec(); + assert_eq!(v[0].id.peer, 0); + assert_eq!(v[0].id.counter, 0 as Counter); + assert_eq!(v[0].id.lamport, 0 as Lamport); + + assert_eq!(v[1].id.peer, 1); + assert_eq!(v[1].id.counter, 1 as Counter); + assert_eq!(v[1].id.lamport, 1 as Lamport); + + assert_eq!(v[2].id.peer, 1); + assert_eq!(v[2].id.counter, 2 as Counter); + assert_eq!(v[2].id.lamport, 2 as Lamport); + } + + #[test] + fn list_fast_snapshot_rejects_corrupt_state_metadata() { + let idx = ContainerIdx::from_index_and_type(0, loro_common::ContainerType::List); + let ctx = ContainerCreationContext { + configure: &Default::default(), + peer: 0, + }; + + let value = LoroValue::from(vec![LoroValue::I64(1)]); + assert!(ListState::decode_snapshot_fast(idx, (value.clone(), &[1]), ctx).is_err()); + + let mut empty = ListState::new(idx); + let mut bytes = Vec::new(); + empty.encode_snapshot_fast(&mut bytes); + let (_, state_bytes) = ListState::decode_value(&bytes).unwrap(); + assert!(ListState::decode_snapshot_fast(idx, (value, state_bytes), ctx).is_err()); + } +} diff --git a/vendor/loro-internal/src/state/map_state.rs b/vendor/loro-internal/src/state/map_state.rs new file mode 100644 index 0000000..737ecd9 --- /dev/null +++ b/vendor/loro-internal/src/state/map_state.rs @@ -0,0 +1,721 @@ +use std::{collections::BTreeMap, sync::Weak}; + +use loro_common::{ContainerID, IdLp, LoroResult, PeerID}; +use rustc_hash::FxHashMap; +use smallvec::SmallVec; + +use crate::{ + configure::Configure, + container::{idx::ContainerIdx, map::MapSet}, + delta::{MapValue, ResolvedMapDelta, ResolvedMapValue}, + diff_calc::DiffMode, + event::{Diff, Index, InternalDiff}, + handler::ValueOrHandler, + op::{Op, RawOp, RawOpContent}, + InternalString, LoroDocInner, LoroValue, +}; + +use super::{ApplyLocalOpReturn, ContainerState, DiffApplyContext}; + +const TINY_MAP_MAX: usize = 4; + +/// Apply the mergeable marker → `Container` boundary translation when a parent cid is known. +/// +/// `MapState` is used both with and without a registered parent cid (e.g. during decode), so the +/// translation no-ops when the parent is missing — markers stay as their stored `Binary` form. +fn translate_with_parent( + parent_id: Option<&ContainerID>, + key: &InternalString, + value: LoroValue, +) -> LoroValue { + match parent_id { + Some(parent) => loro_common::translate_mergeable_marker_value(parent, key.as_ref(), value), + None => value, + } +} + +#[derive(Debug, Clone)] +enum MapEntries { + SortedTiny(SmallVec<[(InternalString, MapValue); 1]>), + Tree(BTreeMap<InternalString, MapValue>), +} + +impl Default for MapEntries { + fn default() -> Self { + Self::SortedTiny(SmallVec::new()) + } +} + +enum MapEntriesIter<'a> { + SortedTiny(std::slice::Iter<'a, (InternalString, MapValue)>), + Tree(std::collections::btree_map::Iter<'a, InternalString, MapValue>), +} + +impl<'a> Iterator for MapEntriesIter<'a> { + type Item = (&'a InternalString, &'a MapValue); + + fn next(&mut self) -> Option<Self::Item> { + match self { + Self::SortedTiny(iter) => iter.next().map(|(key, value)| (key, value)), + Self::Tree(iter) => iter.next(), + } + } +} + +impl MapEntries { + fn debug_assert_sorted_tiny(entries: &[(InternalString, MapValue)]) { + debug_assert!(entries.windows(2).all(|pair| { + let left = &pair[0].0; + let right = &pair[1].0; + left < right + })); + } + + fn is_empty(&self) -> bool { + match self { + Self::SortedTiny(entries) => entries.is_empty(), + Self::Tree(map) => map.is_empty(), + } + } + + fn get(&self, key: &InternalString) -> Option<&MapValue> { + match self { + Self::SortedTiny(entries) => { + Self::debug_assert_sorted_tiny(entries); + entries + .binary_search_by(|(entry_key, _)| entry_key.cmp(key)) + .ok() + .map(|index| &entries[index].1) + } + Self::Tree(map) => map.get(key), + } + } + + fn insert(&mut self, key: InternalString, value: MapValue) -> Option<MapValue> { + match self { + Self::SortedTiny(entries) => { + Self::debug_assert_sorted_tiny(entries); + match entries.binary_search_by(|(entry_key, _)| entry_key.cmp(&key)) { + Ok(index) => return Some(std::mem::replace(&mut entries[index].1, value)), + Err(index) if entries.len() < TINY_MAP_MAX => { + entries.insert(index, (key, value)); + Self::debug_assert_sorted_tiny(entries); + return None; + } + Err(_) => {} + } + + let mut map = BTreeMap::new(); + for (key, value) in entries.drain(..) { + map.insert(key, value); + } + let result = map.insert(key, value); + *self = Self::Tree(map); + result + } + Self::Tree(map) => map.insert(key, value), + } + } + + fn remove(&mut self, key: &InternalString) -> Option<MapValue> { + match self { + Self::SortedTiny(entries) => { + Self::debug_assert_sorted_tiny(entries); + entries + .binary_search_by(|(entry_key, _)| entry_key.cmp(key)) + .ok() + .map(|index| entries.remove(index).1) + } + Self::Tree(map) => { + let result = map.remove(key); + if result.is_some() && map.len() <= TINY_MAP_MAX { + let entries = std::mem::take(map).into_iter().collect(); + *self = Self::SortedTiny(entries); + } + result + } + } + } + + fn iter(&self) -> MapEntriesIter<'_> { + match self { + Self::SortedTiny(entries) => { + Self::debug_assert_sorted_tiny(entries); + MapEntriesIter::SortedTiny(entries.iter()) + } + Self::Tree(map) => MapEntriesIter::Tree(map.iter()), + } + } +} + +#[derive(Debug, Clone)] +enum ChildContainers { + Tiny(SmallVec<[(ContainerID, InternalString); 1]>), + Map(FxHashMap<ContainerID, InternalString>), +} + +impl Default for ChildContainers { + fn default() -> Self { + Self::Tiny(SmallVec::new()) + } +} + +impl ChildContainers { + fn get(&self, id: &ContainerID) -> Option<&InternalString> { + match self { + Self::Tiny(entries) => entries + .iter() + .find_map(|(entry_id, key)| (entry_id == id).then_some(key)), + Self::Map(map) => map.get(id), + } + } + + fn contains_key(&self, id: &ContainerID) -> bool { + self.get(id).is_some() + } + + fn insert(&mut self, id: ContainerID, key: InternalString) -> Option<InternalString> { + match self { + Self::Tiny(entries) => { + if let Some((_, old_key)) = entries.iter_mut().find(|(entry_id, _)| entry_id == &id) + { + return Some(std::mem::replace(old_key, key)); + } + + if entries.len() < TINY_MAP_MAX { + entries.push((id, key)); + return None; + } + + let mut map = FxHashMap::default(); + for (id, key) in entries.drain(..) { + map.insert(id, key); + } + let result = map.insert(id, key); + *self = Self::Map(map); + result + } + Self::Map(map) => map.insert(id, key), + } + } + + fn remove(&mut self, id: &ContainerID) -> Option<InternalString> { + match self { + Self::Tiny(entries) => entries + .iter() + .position(|(entry_id, _)| entry_id == id) + .map(|index| entries.swap_remove(index).1), + Self::Map(map) => { + let result = map.remove(id); + if result.is_some() && map.len() <= TINY_MAP_MAX { + let entries = std::mem::take(map).into_iter().collect(); + *self = Self::Tiny(entries); + } + result + } + } + } +} + +#[derive(Debug, Clone)] +pub struct MapState { + idx: ContainerIdx, + map: MapEntries, + /// Parent-edge index for regular child containers (`MapValue::Container`). Mergeable child + /// edges are resolved by `DocState` from their deterministic cid and this map's marker + /// value, not stored here. + child_containers: ChildContainers, + size: usize, +} + +impl ContainerState for MapState { + fn container_idx(&self) -> ContainerIdx { + self.idx + } + + fn is_state_empty(&self) -> bool { + self.map.is_empty() + } + + fn apply_diff_and_convert( + &mut self, + diff: InternalDiff, + DiffApplyContext { doc, mode }: DiffApplyContext, + ) -> Diff { + let InternalDiff::Map(delta) = diff else { + unreachable!() + }; + let doc = &doc.upgrade().unwrap(); + // The parent cid is the binding side of a mergeable child marker. Cached here so we + // translate marker values into Container values once per delta apply instead of per entry. + let parent_id = doc.arena.idx_to_id(self.idx); + let force = matches!(mode, DiffMode::Checkout | DiffMode::Linear); + let mut resolved_delta = ResolvedMapDelta::new(); + for (key, value) in delta.updated.into_iter() { + let Some(value) = value else { + // uncreate op + assert_eq!(mode, DiffMode::Checkout); + self.remove(&key); + resolved_delta = resolved_delta.with_entry(key, ResolvedMapValue::new_unset()); + continue; + }; + + let mut changed = false; + if force { + let prev = self.insert(key.clone(), value.clone()); + // A checkout diff carries every key whose winning op changed, + // including ones whose value did not (see `MapDiffCalculator`): + // those only refresh the lamport/peer and report no change. + changed = mode != DiffMode::Checkout + || !matches!(prev, Some(prev) if prev.value == value.value); + } else { + match self.map.get(&key) { + Some(old_value) if old_value > &value => {} + _ => { + self.insert(key.clone(), value.clone()); + changed = true; + } + } + } + + if changed { + resolved_delta = resolved_delta.with_entry( + key.clone(), + ResolvedMapValue { + idlp: IdLp::new(value.peer, value.lamp), + value: value + .value + .map(|v| translate_with_parent(parent_id.as_ref(), &key, v)) + .map(|v| ValueOrHandler::from_value(v, doc)), + }, + ) + } + } + + Diff::Map(resolved_delta) + } + + fn apply_diff(&mut self, diff: InternalDiff, ctx: DiffApplyContext) -> LoroResult<()> { + let _ = self.apply_diff_and_convert(diff, ctx); + Ok(()) + } + + fn apply_local_op(&mut self, op: &RawOp, _: &Op) -> LoroResult<ApplyLocalOpReturn> { + let mut ans: ApplyLocalOpReturn = Default::default(); + match &op.content { + RawOpContent::Map(MapSet { key, value }) => { + let prev = self.insert( + key.clone(), + MapValue { + lamp: op.lamport, + peer: op.id.peer, + value: value.clone(), + }, + ); + + if let Some(MapValue { + value: Some(LoroValue::Container(c)), + .. + }) = prev + { + ans.deleted_containers.push(c); + } + } + _ => unreachable!(), + } + + Ok(ans) + } + + #[doc = " Convert a state to a diff that when apply this diff on a empty state,"] + #[doc = " the state will be the same as this state."] + fn to_diff(&mut self, doc: &Weak<LoroDocInner>) -> Diff { + let doc_strong = doc.upgrade().unwrap(); + let parent_id = doc_strong.arena.idx_to_id(self.idx); + // Build resolved values directly instead of going through + // `ResolvedMapValue::from_map_value`: that path forced a full `MapValue` clone per entry + // just to overwrite `.value` with the translated form. Cloning only the inner + // `Option<LoroValue>` is enough and saves an alloc per entry on every state-to-diff. + Diff::Map(ResolvedMapDelta { + updated: self + .map + .iter() + .map(|(k, v)| { + let value = v + .value + .clone() + .map(|val| translate_with_parent(parent_id.as_ref(), k, val)) + .map(|val| ValueOrHandler::from_value(val, &doc_strong)); + ( + k.clone(), + ResolvedMapValue { + idlp: IdLp::new(v.peer, v.lamp), + value, + }, + ) + }) + .collect::<FxHashMap<_, _>>(), + }) + } + + fn get_value(&mut self) -> LoroValue { + let ans = self.to_map(); + LoroValue::Map(ans.into()) + } + + fn get_child_index(&self, id: &ContainerID) -> Option<Index> { + self.child_containers.get(id).map(|x| Index::Key(x.clone())) + } + + fn contains_child(&self, id: &ContainerID) -> bool { + self.child_containers.contains_key(id) + } + + fn get_child_containers(&self) -> Vec<ContainerID> { + let mut ans = Vec::new(); + for (_, value) in self.map.iter() { + if let Some(LoroValue::Container(x)) = &value.value { + ans.push(x.clone()); + } + } + ans + } + + fn fork(&self, _config: &Configure) -> Self { + self.clone() + } +} + +impl MapState { + pub fn new(idx: ContainerIdx) -> Self { + Self { + idx, + map: Default::default(), + child_containers: Default::default(), + size: 0, + } + } + + pub fn insert(&mut self, key: InternalString, value: MapValue) -> Option<MapValue> { + let value_yes = value.value.is_some(); + let new_child = match &value.value { + Some(LoroValue::Container(id)) => { + self.child_containers.insert(id.clone(), key.clone()); + Some(id.clone()) + } + _ => None, + }; + + let result = self.map.insert(key.clone(), value); + if let Some(Some(LoroValue::Container(c))) = result.as_ref().map(|x| &x.value) { + // Re-inserting the same child (e.g. a metadata-only checkout update) + // must keep its parent edge. + if new_child.as_ref() != Some(c) { + self.child_containers.remove(c); + } + } + + match (&result, value_yes) { + (Some(x), true) if x.value.is_none() => { + self.size += 1; + } + (None, true) => { + self.size += 1; + } + (Some(x), false) if x.value.is_some() => { + self.size -= 1; + } + _ => {} + }; + + result + } + + pub fn remove(&mut self, key: &InternalString) { + let result = self.map.remove(key); + if let Some(x) = result { + if x.value.is_some() { + self.size -= 1; + } + if let Some(LoroValue::Container(id)) = x.value { + self.child_containers.remove(&id); + } + }; + } + + pub fn iter(&self) -> impl Iterator<Item = (&InternalString, &MapValue)> { + self.map.iter() + } + + fn to_map(&self) -> FxHashMap<String, LoroValue> { + let mut ans = FxHashMap::with_capacity_and_hasher(self.len(), Default::default()); + for (key, value) in self.map.iter() { + if value.value.is_none() { + continue; + } + + ans.insert(key.to_string(), value.value.as_ref().cloned().unwrap()); + } + + ans + } + + pub fn get(&self, k: &str) -> Option<&LoroValue> { + match self.map.get(&k.into()) { + Some(value) => match &value.value { + Some(v) => Some(v), + None => None, + }, + None => None, + } + } + + pub fn len(&self) -> usize { + self.size + } + + pub fn get_last_edit_peer(&self, key: &str) -> Option<PeerID> { + self.map.get(&key.into()).map(|v| v.peer) + } +} + +mod snapshot { + + use std::collections::BTreeMap; + + use loro_common::{InternalString, LoroValue}; + use rustc_hash::FxHashSet; + use serde_columnar::Itertools; + + use crate::{ + delta::MapValue, + encoding::value_register::ValueRegister, + state::{ + decode_peer_from_table, decode_peer_table, read_state_leb_u64, state_decode_error, + ContainerCreationContext, ContainerState, FastStateSnapshot, + }, + }; + + use super::MapState; + + impl FastStateSnapshot for MapState { + fn encode_snapshot_fast<W: std::io::prelude::Write>(&mut self, mut w: W) { + // 1. LoroValue + // 2. Vec<String> keys_with_none_value + // 3. leb128 peer_num + peers (in u64) + // 3. Groups of (leb128 peer_idx, leb128 lamport), each has a respective map entry + // from either 1 or 2 when they all sorted by the key strings + let value = self.get_value().into_map().unwrap(); + postcard::to_io(&*value, &mut w).unwrap(); + + let keys_with_none_value = self + .map + .iter() + .filter_map(|(k, v)| if v.value.is_some() { None } else { Some(k) }) + .collect_vec(); + postcard::to_io(&keys_with_none_value, &mut w).unwrap(); + let mut peer_register = ValueRegister::new(); + for (_, v) in self.map.iter() { + peer_register.register(&v.peer); + } + + leb128::write::unsigned(&mut w, peer_register.vec().len() as u64).unwrap(); + for p in peer_register.vec() { + w.write_all(&p.to_le_bytes()).unwrap(); + } + let mut keys: Vec<&InternalString> = self.map.iter().map(|(key, _)| key).collect(); + keys.sort_unstable(); + for key in keys.into_iter() { + let value = self.map.get(key).unwrap(); + let peer_idx = peer_register.register(&value.peer); + leb128::write::unsigned(&mut w, peer_idx as u64).unwrap(); + leb128::write::unsigned(&mut w, value.lamp as u64).unwrap(); + } + } + + fn decode_value(bytes: &[u8]) -> loro_common::LoroResult<(loro_common::LoroValue, &[u8])> { + crate::state::value_decode::decode_collection(bytes, true) + } + + fn decode_snapshot_fast( + idx: crate::container::idx::ContainerIdx, + (value, bytes): (loro_common::LoroValue, &[u8]), + _ctx: ContainerCreationContext, + ) -> loro_common::LoroResult<Self> + where + Self: Sized, + { + let value = value.into_map().unwrap(); + // keys_with_none_value + let (keys_with_none_value, mut bytes) = + postcard::take_from_bytes::<Vec<InternalString>>(bytes).map_err(|_| { + loro_common::LoroError::DecodeError( + "Decode map keys_with_none_value failed" + .to_string() + .into_boxed_str(), + ) + })?; + let keys_with_none_value: FxHashSet<_> = keys_with_none_value.into_iter().collect(); + + // peers + let peers = decode_peer_table(&mut bytes, "Decode map state failed")?; + + // + let mut ans = MapState::new(idx); + let mut keys: Vec<_> = value.keys().map(|x| x.as_str().into()).collect(); + keys.extend(keys_with_none_value.iter().cloned()); + keys.sort_unstable(); + + for key in keys { + let peer_idx = + usize::try_from(read_state_leb_u64(&mut bytes, "Decode map state failed")?) + .map_err(|_| { + state_decode_error("Decode map state failed: peer index overflow") + })?; + let lamp = + u32::try_from(read_state_leb_u64(&mut bytes, "Decode map state failed")?) + .map_err(|_| { + state_decode_error("Decode map state failed: lamport overflow") + })?; + let peer = decode_peer_from_table(&peers, peer_idx, "Decode map state failed")?; + + if keys_with_none_value.contains(&key) { + ans.insert( + key, + MapValue { + value: None, + lamp, + peer, + }, + ); + } else { + let value = value.get(&*key).unwrap(); + ans.insert( + key, + MapValue { + value: Some(value.clone()), + lamp, + peer, + }, + ); + } + } + + if !bytes.is_empty() { + return Err(loro_common::LoroError::DecodeError( + "Decode map state failed".to_string().into_boxed_str(), + )); + } + + Ok(ans) + } + } + + impl MapState { + pub(crate) fn decode_value_as_btree_map( + bytes: &[u8], + ) -> loro_common::LoroResult<(BTreeMap<String, LoroValue>, &[u8])> { + crate::state::value_decode::decode_btree_map(bytes) + } + } + + #[cfg(test)] + mod map_snapshot_test { + use loro_common::LoroValue; + + use crate::container::idx::ContainerIdx; + + use super::*; + + #[test] + fn map_fast_snapshot() { + let mut map = MapState::new(ContainerIdx::from_index_and_type( + 0, + loro_common::ContainerType::Map, + )); + map.insert( + "1".into(), + MapValue { + value: None, + lamp: 1, + peer: 1, + }, + ); + map.insert( + "2".into(), + MapValue { + value: Some(LoroValue::I64(0)), + lamp: 2, + peer: 2, + }, + ); + map.insert( + "3".into(), + MapValue { + value: Some(LoroValue::Double(1.0)), + lamp: 3, + peer: 3, + }, + ); + + let mut bytes = Vec::new(); + map.encode_snapshot_fast(&mut bytes); + assert!(bytes.len() <= 50); + + let (value, bytes) = MapState::decode_value(&bytes).unwrap(); + { + let m = value.clone().into_map().unwrap(); + assert_eq!(m.len(), 2); + assert_eq!(m.get("2").unwrap(), &LoroValue::I64(0)); + assert_eq!(m.get("3").unwrap(), &LoroValue::Double(1.0)); + } + + let new_map = MapState::decode_snapshot_fast( + ContainerIdx::from_index_and_type(0, loro_common::ContainerType::Map), + (value, bytes), + ContainerCreationContext { + configure: &Default::default(), + peer: 0, + }, + ) + .unwrap(); + let v = new_map.map.get(&"2".into()).unwrap(); + assert_eq!( + v, + &MapValue { + value: Some(LoroValue::I64(0)), + lamp: 2, + peer: 2, + } + ); + let v = new_map.map.get(&"1".into()).unwrap(); + assert_eq!( + v, + &MapValue { + value: None, + lamp: 1, + peer: 1, + } + ); + } + + #[test] + fn map_fast_snapshot_rejects_corrupt_state_metadata() { + let idx = ContainerIdx::from_index_and_type(0, loro_common::ContainerType::Map); + let ctx = ContainerCreationContext { + configure: &Default::default(), + peer: 0, + }; + let value = LoroValue::from(std::collections::HashMap::from([( + "key".to_string(), + LoroValue::I64(1), + )])); + + let mut empty = MapState::new(idx); + let mut bytes = Vec::new(); + empty.encode_snapshot_fast(&mut bytes); + let (_, state_bytes) = MapState::decode_value(&bytes).unwrap(); + assert!(MapState::decode_snapshot_fast(idx, (value, state_bytes), ctx).is_err()); + } + } +} diff --git a/vendor/loro-internal/src/state/mergeable.rs b/vendor/loro-internal/src/state/mergeable.rs new file mode 100644 index 0000000..f41080c --- /dev/null +++ b/vendor/loro-internal/src/state/mergeable.rs @@ -0,0 +1,93 @@ +//! Mergeable-container edge resolution on `DocState`. +//! +//! Mergeable child containers (created via `MapHandler::ensure_mergeable_*`) use deterministic +//! `ContainerID::Root` ids in a reserved namespace. The cid encodes `(parent, key, kind)`, while +//! the parent map's compact binary child ref is the single source of truth for whether that child +//! is currently active. +//! +//! The ref is intentionally stored as a specially constructed binary marker value. This keeps +//! user-editable strings from being reinterpreted as internal container topology, and lets the +//! resolver fail closed unless the ref's digest matches the exact `(parent, key, kind)` being +//! resolved. + +use loro_common::{ContainerID, ContainerType, InternalString, LoroMapValue}; + +use crate::{container::idx::ContainerIdx, event::Index}; + +use super::{ContainerState, DocState}; + +impl DocState { + /// Resolve a child edge using the document-level logical edge model. + /// + /// Ordinary child containers use the materialized child index stored in their parent state. + /// Mergeable children are resolved lazily from their deterministic cid plus the parent map's + /// current binary child ref, so snapshot/update import does not need any eager mergeable-edge + /// rebuild. + pub(super) fn get_logical_child_index( + &mut self, + parent_idx: ContainerIdx, + child_id: &ContainerID, + ) -> Option<Index> { + if let Some((parent_id, key, kind)) = child_id.parse_mergeable() { + return self.resolve_mergeable_child_index(parent_idx, &parent_id, &key, kind); + } + + self.store + .get_container_mut(parent_idx) + .and_then(|parent_state| parent_state.get_child_index(child_id)) + } + + pub(super) fn contains_logical_child( + &mut self, + parent_idx: ContainerIdx, + child_id: &ContainerID, + ) -> bool { + self.get_logical_child_index(parent_idx, child_id).is_some() + } + + fn resolve_mergeable_child_index( + &mut self, + parent_idx: ContainerIdx, + encoded_parent_id: &ContainerID, + key: &str, + kind: ContainerType, + ) -> Option<Index> { + if parent_idx.get_type() != ContainerType::Map { + return None; + } + + let actual_parent_id = self.arena.idx_to_id(parent_idx)?; + if &actual_parent_id != encoded_parent_id { + return None; + } + + let value = self.store.map_get(parent_idx, key)?; + if loro_common::parse_mergeable_marker(&actual_parent_id, key, &value) == Some(kind) { + Some(Index::Key(key.into())) + } else { + None + } + } + + /// Derive `(key, cid)` pairs for the active mergeable children of a map directly from its + /// current value table. + /// + /// This is used by deep-value and alive-container walks. It mirrors regular map semantics: + /// the current value at a key determines which child is visible. For mergeable children, that + /// value is a compact binary child ref rather than `LoroValue::Container`. + pub(super) fn mergeable_children_from_value( + &self, + parent_id: &ContainerID, + map_value: &LoroMapValue, + ) -> Vec<(InternalString, ContainerID)> { + let mut ans = Vec::new(); + for (key, value) in map_value.iter() { + if let Some(kind) = loro_common::parse_mergeable_marker(parent_id, key, value) { + let key_istr: InternalString = key.as_str().into(); + let cid = ContainerID::new_mergeable(parent_id, key, kind); + ans.push((key_istr, cid)); + } + } + ans + } +} diff --git a/vendor/loro-internal/src/state/movable_list_state.rs b/vendor/loro-internal/src/state/movable_list_state.rs new file mode 100644 index 0000000..62d2e6b --- /dev/null +++ b/vendor/loro-internal/src/state/movable_list_state.rs @@ -0,0 +1,2110 @@ +use itertools::Itertools; +use loro_delta::{array_vec::ArrayVec, DeltaRope, DeltaRopeBuilder}; +use serde_columnar::columnar; +use std::sync::Weak; +use tracing::{instrument, warn}; + +use generic_btree::BTree; +use loro_common::{ + CompactIdLp, ContainerID, IdFull, IdLp, LoroError, LoroResult, LoroValue, PeerID, ID, +}; +use rustc_hash::FxHashMap; + +use crate::{ + configure::Configure, + container::{idx::ContainerIdx, list::list_op::ListOp}, + delta::DeltaItem, + diff_calc::DiffMode, + event::{Diff, Index, InternalDiff, ListDeltaMeta}, + handler::ValueOrHandler, + op::{ListSlice, Op, RawOp}, + ListDiff, LoroDocInner, +}; + +use self::{ + inner::{InnerState, UpdateResultFromPosChange}, + list_item_tree::{MovableListTreeTrait, OpLenQuery, UserLenQuery}, +}; + +use super::{ApplyLocalOpReturn, ContainerState, DiffApplyContext}; + +#[derive(Debug, Clone)] +pub struct MovableListState { + idx: ContainerIdx, + inner: InnerState, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ListItem { + pointed_by: Option<CompactIdLp>, + pub(crate) id: IdFull, +} + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct Element { + pub(crate) value: LoroValue, + pub(crate) value_id: IdLp, + pub(crate) pos: IdLp, +} + +impl Element { + pub(crate) fn value(&self) -> &LoroValue { + &self.value + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum IndexType { + /// This includes the ones that are not being pointed at, which may not be visible to users + ForOp, + /// This only includes the ones that are being pointed at, which means visible to users + ForUser, +} + +mod list_item_tree { + use std::{ + iter::Sum, + ops::{Add, AddAssign, Sub}, + }; + + use generic_btree::{ + rle::{CanRemove, HasLength, Mergeable, Sliceable, TryInsert}, + BTreeTrait, + }; + + use crate::utils::query_by_len::{IndexQuery, QueryByLen}; + + use super::ListItem; + + impl HasLength for ListItem { + fn rle_len(&self) -> usize { + 1 + } + } + + impl Mergeable for ListItem { + fn can_merge(&self, _rhs: &Self) -> bool { + false + } + + fn merge_right(&mut self, _rhs: &Self) { + unreachable!() + } + + fn merge_left(&mut self, _left: &Self) { + unreachable!() + } + } + + impl Sliceable for ListItem { + fn _slice(&self, range: std::ops::Range<usize>) -> Self { + assert_eq!(range.len(), 1); + self.clone() + } + } + + impl CanRemove for ListItem { + fn can_remove(&self) -> bool { + false + } + } + + impl TryInsert for ListItem { + fn try_insert(&mut self, _pos: usize, elem: Self) -> Result<(), Self> + where + Self: Sized, + { + Err(elem) + } + } + + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] + pub(super) struct Cache { + /// This length info include the ones that were deleted. + /// It's used in op and diff calculation. + pub include_dead_len: i32, + /// This length info does not include the ones that were deleted. + /// So it's facing the users. + pub user_len: i32, + } + + impl Add for Cache { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self { + include_dead_len: self.include_dead_len + rhs.include_dead_len, + user_len: self.user_len + rhs.user_len, + } + } + } + + impl AddAssign for Cache { + fn add_assign(&mut self, rhs: Self) { + *self = *self + rhs; + } + } + + impl Sub for Cache { + type Output = Self; + + fn sub(self, rhs: Self) -> Self::Output { + Self { + include_dead_len: self.include_dead_len - rhs.include_dead_len, + user_len: self.user_len - rhs.user_len, + } + } + } + + impl Sum for Cache { + fn sum<I: Iterator<Item = Self>>(iter: I) -> Self { + iter.fold(Self::default(), |acc, x| acc + x) + } + } + + impl CanRemove for Cache { + fn can_remove(&self) -> bool { + self.include_dead_len == 0 + } + } + + pub(super) struct MovableListTreeTrait; + + impl BTreeTrait for MovableListTreeTrait { + type Elem = ListItem; + + type Cache = Cache; + + type CacheDiff = Cache; + + fn calc_cache_internal( + cache: &mut Self::Cache, + caches: &[generic_btree::Child<Self>], + ) -> Self::CacheDiff { + let new: Cache = caches.iter().map(|x| *x.cache()).sum(); + let diff = new - *cache; + *cache = new; + diff + } + + fn apply_cache_diff(cache: &mut Self::Cache, diff: &Self::CacheDiff) { + *cache += *diff; + } + + fn merge_cache_diff(diff1: &mut Self::CacheDiff, diff2: &Self::CacheDiff) { + *diff1 += *diff2; + } + + fn get_elem_cache(elem: &Self::Elem) -> Self::Cache { + if elem.pointed_by.is_some() { + Cache { + include_dead_len: 1, + user_len: 1, + } + } else { + Cache { + include_dead_len: 1, + user_len: 0, + } + } + } + + fn new_cache_to_diff(cache: &Self::Cache) -> Self::CacheDiff { + *cache + } + + fn sub_cache(cache_lhs: &Self::Cache, cache_rhs: &Self::Cache) -> Self::CacheDiff { + *cache_lhs - *cache_rhs + } + } + + pub(crate) struct UserLenQueryT; + pub(crate) type UserLenQuery = IndexQuery<UserLenQueryT, MovableListTreeTrait>; + + impl QueryByLen<MovableListTreeTrait> for UserLenQueryT { + fn get_cache_len(cache: &<MovableListTreeTrait as BTreeTrait>::Cache) -> usize { + cache.user_len as usize + } + + fn get_elem_len(elem: &<MovableListTreeTrait as BTreeTrait>::Elem) -> usize { + if elem.pointed_by.is_some() { + 1 + } else { + 0 + } + } + + fn get_offset_and_found( + left: usize, + elem: &<MovableListTreeTrait as BTreeTrait>::Elem, + ) -> (usize, bool) { + if left == 0 && elem.pointed_by.is_some() { + (0, true) + } else { + (1, false) + } + } + + fn get_cache_entity_len(cache: &<MovableListTreeTrait as BTreeTrait>::Cache) -> usize { + cache.user_len as usize + } + } + + pub(crate) struct IncludeDeadLenQueryT; + pub(crate) type OpLenQuery = IndexQuery<IncludeDeadLenQueryT, MovableListTreeTrait>; + + impl QueryByLen<MovableListTreeTrait> for IncludeDeadLenQueryT { + fn get_cache_len(cache: &<MovableListTreeTrait as BTreeTrait>::Cache) -> usize { + cache.include_dead_len as usize + } + + fn get_elem_len(_elem: &<MovableListTreeTrait as BTreeTrait>::Elem) -> usize { + 1 + } + + fn get_offset_and_found( + left: usize, + _elem: &<MovableListTreeTrait as BTreeTrait>::Elem, + ) -> (usize, bool) { + if left == 0 { + return (0, true); + } + + (1, false) + } + + fn get_cache_entity_len(cache: &<MovableListTreeTrait as BTreeTrait>::Cache) -> usize { + cache.include_dead_len as usize + } + } +} + +/// The inner state of the list. +/// +/// The operations inside this mod need to ensure certain invariants. +/// +/// - list items' `pointed_by` must be consistent with the `elements`' `pos`. +/// - `id_to_list_leaf` must be consistent with the list. +/// - `child_container_to_elem` must be consistent with the element. +mod inner { + use generic_btree::{BTree, Cursor, LeafIndex, Query}; + use loro_common::{CompactIdLp, ContainerID, IdFull, IdLp, LoroValue, PeerID}; + use rustc_hash::{FxHashMap, FxHashSet}; + use tracing::error; + + use super::{ + list_item_tree::{MovableListTreeTrait, OpLenQuery, UserLenQuery}, + Element, IndexType, ListItem, + }; + + #[derive(Debug, Clone)] + pub(super) struct InnerState { + list: BTree<MovableListTreeTrait>, + id_to_list_leaf: FxHashMap<IdLp, LeafIndex>, + elements: FxHashMap<CompactIdLp, Element>, + /// This mapping may be out of date when elem is removed/updated. + /// But it's guaranteed that if there is a ContainerID in the actual list, + /// it will be mapped correctly. + child_container_to_elem: FxHashMap<ContainerID, CompactIdLp>, + } + + impl PartialEq for InnerState { + fn eq(&self, other: &Self) -> bool { + let v = self.id_to_list_leaf == other.id_to_list_leaf + && self.elements == other.elements + && self.child_container_to_elem == other.child_container_to_elem; + if !v { + false + } else { + self.list.iter().zip(other.list.iter()).all(|(a, b)| a == b) + } + } + } + + fn eq<T: PartialEq>(a: T, b: T) -> Result<(), ()> { + if a == b { + Ok(()) + } else { + Err(()) + } + } + + impl InnerState { + pub fn new() -> Self { + Self { + list: BTree::new(), + id_to_list_leaf: FxHashMap::default(), + elements: FxHashMap::default(), + child_container_to_elem: FxHashMap::default(), + } + } + + #[inline] + pub fn child_container_to_elem(&self) -> &FxHashMap<ContainerID, CompactIdLp> { + &self.child_container_to_elem + } + + #[inline] + pub fn elements(&self) -> &FxHashMap<CompactIdLp, Element> { + &self.elements + } + + #[inline] + pub fn list(&self) -> &BTree<MovableListTreeTrait> { + &self.list + } + + pub fn remove_elem_by_id(&mut self, elem_id: &CompactIdLp) { + self.elements.remove(elem_id); + } + + #[allow(dead_code)] + pub fn check_consistency(&self) { + if !cfg!(debug_assertions) { + return; + } + + let mut failed = false; + if self.check_list_item_consistency().is_err() { + error!("list item consistency check failed, self={:#?}", self); + failed = true; + } + + if self.check_child_container_to_elem_consistency().is_err() { + error!( + "child container to elem consistency check failed, self={:#?}", + self + ); + failed = true; + } + + if failed { + panic!("consistency check failed"); + } + } + + fn check_list_item_consistency(&self) -> Result<(), ()> { + let mut visited_ids = FxHashSet::default(); + for list_item in self.list.iter() { + { + if visited_ids.contains(&list_item.id.idlp()) { + error!("duplicate list item id"); + return Err(()); + } + visited_ids.insert(list_item.id.idlp()); + } + let leaf = self.id_to_list_leaf.get(&list_item.id.idlp()).unwrap(); + let list_item_found = self.list.get_elem(*leaf).unwrap(); + eq(list_item_found, list_item)?; + if let Some(pointed_by) = list_item_found.pointed_by { + let elem = self.elements.get(&pointed_by).unwrap(); + eq(elem.pos, list_item.id.idlp())?; + } + } + + for (elem_id, elem) in self.elements.iter() { + if let Some(item) = self.get_list_item_by_id(elem.pos) { + eq(item.pointed_by, Some(*elem_id))?; + } + } + + Ok(()) + } + + fn check_child_container_to_elem_consistency(&self) -> Result<(), ()> { + for (elem_id, elem) in self.elements.iter() { + if let LoroValue::Container(c) = &elem.value { + eq(self.child_container_to_elem.get(c), Some(elem_id))?; + } + } + + Ok(()) + } + + pub fn get_list_item_index(&self, id: IdLp, kind: IndexType) -> Option<usize> { + self.id_to_list_leaf + .get(&id) + .map(|leaf| self.get_index_of(*leaf, kind) as usize) + } + + pub fn get_index_of(&self, leaf: LeafIndex, kind: IndexType) -> i32 { + let mut ans = 0; + self.list + .visit_previous_caches(Cursor { leaf, offset: 0 }, |cache| match cache { + generic_btree::PreviousCache::NodeCache(c) => { + if matches!(kind, IndexType::ForUser) { + ans += c.user_len; + } else { + ans += c.include_dead_len; + } + } + generic_btree::PreviousCache::PrevSiblingElem(p) => { + if matches!(kind, IndexType::ForUser) { + ans += if p.pointed_by.is_some() { 1 } else { 0 }; + } else { + ans += 1; + } + } + generic_btree::PreviousCache::ThisElemAndOffset { .. } => {} + }); + ans + } + + #[inline] + pub fn get_list_item_at(&self, pos: usize, index_type: IndexType) -> Option<&ListItem> { + let index = match index_type { + IndexType::ForUser => self.list.query::<UserLenQuery>(&pos)?, + IndexType::ForOp => self.list.query::<OpLenQuery>(&pos)?, + }; + self.list.get_elem(index.leaf()) + } + + pub fn get_child_index(&self, id: &ContainerID, index_type: IndexType) -> Option<usize> { + let ans = self.child_container_to_elem.get(id).and_then(|eid| { + let this = &self; + let elem_id = eid.to_id().compact(); + let elem = this.elements.get(&elem_id)?; + if elem.value.as_container() != Some(id) { + // TODO: may be better to find a way clean up these invalid elements? + return None; + } + if let Some(leaf) = self.id_to_list_leaf.get(&elem.pos) { + let list_item = self.list.get_elem(*leaf)?; + assert_eq!(list_item.pointed_by, Some(elem_id)); + } else { + return None; + } + this.get_list_item_index(elem.pos, index_type) + }); + + ans + } + + pub fn contains_child_container(&self, id: &ContainerID) -> bool { + self.get_child_index(id, IndexType::ForUser).is_some() + } + + #[inline] + pub fn get_list_item_by_id(&self, id: IdLp) -> Option<&ListItem> { + self.id_to_list_leaf + .get(&id) + .map(|&leaf| self.list.get_elem(leaf).unwrap()) + } + + pub fn len_kind(&self, kind: IndexType) -> usize { + match kind { + IndexType::ForUser => self.list.root_cache().user_len as usize, + IndexType::ForOp => self.list.root_cache().include_dead_len as usize, + } + } + + /// Insert a new list item at the given position (op index). + /// Return the value if the insertion activated an element. + pub fn insert_list_item(&mut self, pos: usize, list_item_id: IdFull) { + let c = self + .list + .insert::<OpLenQuery>( + &pos, + ListItem { + pointed_by: None, + id: list_item_id, + }, + ) + .0; + self.id_to_list_leaf.insert(list_item_id.idlp(), c.leaf); + } + + /// Drain the list items in the given range (op index). + /// + /// We also remove the elements that are pointed by the list items. + pub fn list_drain( + &mut self, + range: std::ops::Range<usize>, + mut on_elem_id: impl FnMut(CompactIdLp, &Element), + ) { + for item in Self::drain_by_query::<OpLenQuery>(&mut self.list, range) { + self.id_to_list_leaf.remove(&item.id.idlp()); + if let Some(elem_id) = &item.pointed_by { + let elem = self.elements.get(elem_id).unwrap(); + on_elem_id(*elem_id, elem); + self.elements.remove(elem_id); + } + } + } + + fn drain_by_query<Q: Query<MovableListTreeTrait>>( + list: &mut BTree<MovableListTreeTrait>, + range: std::ops::Range<Q::QueryArg>, + ) -> generic_btree::iter::Drain<'_, MovableListTreeTrait> { + let start = list.query::<Q>(&range.start); + let end = list.query::<Q>(&range.end); + generic_btree::iter::Drain::new(list, start, end) + } + + /// Update the pos pointer of an element and the corresponding list items. + /// + /// The old list item will be removed if `remove_old` is true; Otherwise, + /// it will be updated with its `pointed_by` removed. + /// + #[must_use] + pub fn update_pos( + &mut self, + elem_id: CompactIdLp, + new_pos: IdLp, + remove_old: bool, + ) -> UpdateResultFromPosChange { + let mut old_item_id = None; + if let Some(element) = self.elements.get_mut(&elem_id) { + if element.pos != new_pos { + old_item_id = Some(element.pos); + element.pos = new_pos; + } else { + return UpdateResultFromPosChange { + activate_new_list_item: false, + new_list_item_leaf: None, + removed_old_list_item_leaf: None, + }; + } + } else { + self.elements.insert( + elem_id, + Element { + value: LoroValue::Null, + value_id: IdLp::NONE_ID, + pos: new_pos, + }, + ); + } + + let mut ans = UpdateResultFromPosChange { + activate_new_list_item: true, + new_list_item_leaf: None, + removed_old_list_item_leaf: None, + }; + if let Some(leaf) = self.id_to_list_leaf.get(&new_pos) { + ans.new_list_item_leaf = Some(*leaf); + self.list.update_leaf(*leaf, |list_item| { + debug_assert!( + list_item.pointed_by.is_none(), + "list_item was pointed by {:?} but need to be changed to {:?}", + list_item.pointed_by, + elem_id + ); + ans.activate_new_list_item = list_item.pointed_by.is_none(); + list_item.pointed_by = Some(elem_id); + (true, None, None) + }); + } else { + ans.activate_new_list_item = false; + } + + if let Some(old) = old_item_id { + if old.is_none() || old == new_pos { + return ans; + } + + if remove_old { + let leaf = self.id_to_list_leaf.remove(&old).unwrap(); + let elem = self.list.remove_leaf(Cursor { leaf, offset: 0 }).unwrap(); + assert_eq!(elem.pointed_by, Some(elem_id)); + } else if let Some(leaf) = self.id_to_list_leaf.get(&old) { + ans.removed_old_list_item_leaf = Some(*leaf); + let (still_valid, split) = self.list.update_leaf(*leaf, |item| { + item.pointed_by = None; + (true, None, None) + }); + assert!(still_valid); + assert!(split.arr.is_empty()); + } + } + + ans + } + + /// The update can reflected on an event exposed to users. This method calculates the + /// corresponding event position information. + pub fn convert_update_to_event_pos( + &self, + update: UpdateResultFromPosChange, + ) -> EventPosInfo { + if update.activate_new_list_item { + let new = update.new_list_item_leaf.unwrap(); + if let Some(del) = update.removed_old_list_item_leaf { + let mut insert_pos = self.get_index_of(new, IndexType::ForUser) as usize; + let del_pos = self.get_index_of(del, IndexType::ForUser) as usize; + if insert_pos > del_pos { + insert_pos += 1; + } + EventPosInfo { + activate_new_list_item: update.activate_new_list_item, + insert: Some(insert_pos), + delete: Some(del_pos), + } + } else { + EventPosInfo { + activate_new_list_item: update.activate_new_list_item, + insert: Some(self.get_index_of(new, IndexType::ForUser) as usize), + delete: None, + } + } + } else if let Some(del) = update.removed_old_list_item_leaf { + EventPosInfo { + activate_new_list_item: update.activate_new_list_item, + insert: None, + delete: Some(self.get_index_of(del, IndexType::ForUser) as usize), + } + } else { + EventPosInfo { + activate_new_list_item: update.activate_new_list_item, + insert: None, + delete: None, + } + } + } + + pub fn update_value( + &mut self, + elem_id: CompactIdLp, + new_value: LoroValue, + value_id: IdLp, + ) -> Option<LoroValue> { + debug_assert!(elem_id.peer != PeerID::MAX); + debug_assert!(!value_id.is_none()); + if let LoroValue::Container(c) = &new_value { + self.child_container_to_elem.insert(c.clone(), elem_id); + } + + if let Some(element) = self.elements.get_mut(&elem_id) { + if let LoroValue::Container(c) = &element.value { + if element.value != new_value { + self.child_container_to_elem.remove(c); + } + } + let old_value = std::mem::replace(&mut element.value, new_value); + element.value_id = value_id; + Some(old_value) + } else { + self.elements.insert( + elem_id, + Element { + value: new_value, + value_id, + pos: IdLp::NONE_ID, + }, + ); + None + } + } + + /// push a new elem into the list + pub fn push_inner(&mut self, list_item_id: IdFull, elem: Option<PushElemInfo>) { + let pointed_by = elem.as_ref().map(|x| x.elem_id); + if let Some(elem) = elem { + if let LoroValue::Container(c) = &elem.value { + self.child_container_to_elem.insert(c.clone(), elem.elem_id); + } + debug_assert!(!elem.last_set_id.is_none()); + self.elements.insert( + elem.elem_id, + Element { + value: elem.value, + value_id: elem.last_set_id, + pos: list_item_id.idlp(), + }, + ); + } + let cursor = self.list.push(ListItem { + pointed_by, + id: list_item_id, + }); + self.id_to_list_leaf + .insert(list_item_id.idlp(), cursor.leaf); + } + } + + pub(super) struct PushElemInfo { + pub elem_id: CompactIdLp, + pub value: LoroValue, + pub last_set_id: IdLp, + } + + pub(super) struct UpdateResultFromPosChange { + /// Whether the list item is activated by this change. + /// If so, the length of the list will be increased by 1 from the users' perspective. + pub activate_new_list_item: bool, + pub new_list_item_leaf: Option<LeafIndex>, + /// Remove from the users' perspective. But they are still in the state. + pub removed_old_list_item_leaf: Option<LeafIndex>, + } + + /// This struct assumes we apply insert first and then delete. + pub(super) struct EventPosInfo { + pub activate_new_list_item: bool, + pub insert: Option<usize>, + pub delete: Option<usize>, + } +} + +impl MovableListState { + pub fn new(idx: ContainerIdx) -> Self { + Self { + idx, + inner: InnerState::new(), + } + } + + #[inline] + fn list(&self) -> &BTree<MovableListTreeTrait> { + self.inner.list() + } + + #[inline] + pub(crate) fn elements(&self) -> &FxHashMap<CompactIdLp, Element> { + self.inner.elements() + } + + /// Return whether the list item is activated by this change. + /// + /// If so, the length of the list will be increased by 1 from the users' perspective. + /// + /// It's false when the list item is already activated or deleted. + #[must_use] + fn create_new_elem( + &mut self, + elem_id: CompactIdLp, + new_pos: IdLp, + new_value: LoroValue, + value_id: IdLp, + ) -> UpdateResultFromPosChange { + self.inner.update_value(elem_id, new_value, value_id); + self.inner.update_pos(elem_id, new_pos, false) + } + + /// Return the values that are activated by the insertions of the list items, and their elem ids. + /// + /// The activation means there were elements that already points to the list items + /// inserted by this op. + fn list_insert_batch(&mut self, index: usize, items: impl Iterator<Item = IdFull>) { + for (i, item) in items.enumerate() { + self.inner.insert_list_item(index + i, item); + } + } + + /// Get the length defined by op, where the length includes the ones that are not being pointed at (moved, invisible to users). + #[allow(unused)] + fn op_len(&self) -> usize { + self.inner.list().root_cache().include_dead_len as usize + } + + fn mov( + &mut self, + from_index: usize, + to_index: usize, + elem_id: IdLp, + new_pos_id: IdFull, + kind: IndexType, + ) { + // PERF: can be optimized by inlining try update + if cfg!(debug_assertions) { + let item = self.inner.get_list_item_at(from_index, kind).unwrap(); + assert_eq!(item.pointed_by, Some(elem_id.compact())); + } + + self.inner.insert_list_item( + if to_index > from_index { + to_index + 1 + } else { + to_index + }, + new_pos_id, + ); + let _ = self + .inner + .update_pos(elem_id.compact(), new_pos_id.idlp(), true); + } + + pub(crate) fn get(&self, index: usize, kind: IndexType) -> Option<&LoroValue> { + if index >= self.len() { + return None; + } + + let item = self.inner.get_list_item_at(index, kind)?; + let elem = item.pointed_by?; + self.inner.elements().get(&elem).map(|x| &x.value) + } + + pub(crate) fn get_elem_at_given_pos( + &self, + index: usize, + kind: IndexType, + ) -> Option<(CompactIdLp, &Element)> { + self.inner.get_list_item_at(index, kind).and_then(|x| { + x.pointed_by + .map(|pointed_by| (pointed_by, self.inner.elements().get(&pointed_by).unwrap())) + }) + } + + pub(crate) fn get_list_id_at(&self, index: usize, kind: IndexType) -> Option<ID> { + self.inner.get_list_item_at(index, kind).map(|x| x.id.id()) + } + + pub(crate) fn get_elem_id_at(&self, index: usize, kind: IndexType) -> Option<CompactIdLp> { + self.inner + .get_list_item_at(index, kind) + .and_then(|x| x.pointed_by) + } + + pub(crate) fn convert_index( + &self, + index: usize, + from: IndexType, + to: IndexType, + ) -> Option<usize> { + let len = self.inner.len_kind(from); + if index == len { + return Some(self.inner.len_kind(to)); + } + + if index > len { + return None; + } + + let c = match from { + IndexType::ForOp => self.inner.list().query::<OpLenQuery>(&index).unwrap(), + IndexType::ForUser => self.inner.list().query::<UserLenQuery>(&index).unwrap(), + }; + + Some(self.inner.get_index_of(c.cursor.leaf, to) as usize) + } + + pub(crate) fn get_list_item(&self, id: IdLp) -> Option<&ListItem> { + self.inner.get_list_item_by_id(id) + } + + /// Get the user index of elem + /// + /// If we cannot find the list item in the list, we will return None. + pub(crate) fn get_index_of_elem(&self, elem_id: CompactIdLp) -> Option<usize> { + let elem = self.inner.elements().get(&elem_id)?; + self.inner.get_list_item_index(elem.pos, IndexType::ForUser) + } + + /// Debug check the consistency between the list and the elements + /// + /// We need to ensure that: + /// - Every element's pos is in the list, and it has a `pointed_by` value that points + /// back to the element + /// - Every list item's `pointed_by` value points to an element in the elements, and + /// the element has the correct `pos` value + #[cfg(any(debug_assertions, test))] + #[allow(unused)] + pub(crate) fn check_consistency(&self) { + for (id, elem) in self.inner.elements().iter() { + let item = self + .get_list_item(id.to_id()) + .expect("Elem's pos should be in the list"); + assert_eq!(item.pointed_by.unwrap(), *id); + } + + for item in self.inner.list().iter() { + if let Some(elem_id) = item.pointed_by { + let elem = self.inner.elements().get(&elem_id).unwrap(); + assert_eq!(elem.pos, item.id.idlp()); + } + } + } + + pub fn iter(&self) -> impl Iterator<Item = &LoroValue> { + // PERF: can be optimized + (0..self.len()).map(move |i| self.get(i, IndexType::ForUser).unwrap()) + } + + pub fn iter_with_last_move_id_and_elem_id( + &self, + ) -> impl Iterator<Item = (IdFull, CompactIdLp, &LoroValue)> { + self.inner.list().iter().filter_map(|list_item| { + if let Some(elem_id) = list_item.pointed_by.as_ref() { + let elem = self.inner.elements().get(elem_id).unwrap(); + Some((list_item.id, *elem_id, &elem.value)) + } else { + None + } + }) + } + + pub fn len(&self) -> usize { + self.inner.list().root_cache().user_len as usize + } + + fn to_vec(&self) -> Vec<LoroValue> { + self.iter().cloned().collect_vec() + } + + pub(crate) fn get_index_of_id(&self, id: ID) -> Option<usize> { + let mut user_index = 0; + for item in self.list().iter() { + if item.id.peer == id.peer && item.id.counter == id.counter { + return Some(user_index); + } + + user_index += if item.pointed_by.is_some() { 1 } else { 0 }; + } + None + } + + fn get_value_inner(&self) -> Vec<LoroValue> { + let list = self + .inner + .list() + .iter_with_filter(|x| (x.user_len > 0, 0)) + .filter_map(|(_, item)| { + item.pointed_by + .map(|eid| self.elements()[&eid].value.clone()) + }) + .collect(); + list + } + + pub(crate) fn get_list_item_id_at(&self, pos: usize) -> Option<IdFull> { + let item = self.inner.get_list_item_at(pos, IndexType::ForUser); + item.map(|x| x.id) + } + + #[allow(unused)] + fn check_get_child_index_correctly(&mut self) { + let value = self.get_value(); + let list = value.into_list().unwrap(); + for (i, item) in list.iter().enumerate() { + if let LoroValue::Container(c) = item { + let child_index = self.get_child_index(c).expect("cannot find child index"); + assert_eq!(child_index.into_seq().unwrap(), i); + } + } + } + + pub fn get_creator_at(&self, pos: usize) -> Option<PeerID> { + self.inner + .get_list_item_at(pos, IndexType::ForUser) + .and_then(|x| x.pointed_by.map(|x| x.peer)) + } + + pub fn get_last_mover_at(&self, pos: usize) -> Option<PeerID> { + self.inner + .get_list_item_at(pos, IndexType::ForUser) + .map(|x| x.id.peer) + } + + pub fn get_last_editor_at(&self, pos: usize) -> Option<PeerID> { + self.inner + .get_list_item_at(pos, IndexType::ForUser) + .and_then(|x| { + x.pointed_by + .and_then(|x| self.inner.elements().get(&x).map(|x| x.value_id.peer)) + }) + } +} + +impl MovableListState { + /// Whether a forward (Linear/ImportGreaterUpdates) diff moves or sets an element + /// that is not in this state. + /// + /// Such diffs only carry the fields an op touched and take the rest from the + /// current element. Honest ops cannot produce this (an element absent here was + /// deleted before every op in the diff), but a forged op can; it has the same + /// meaning as a concurrent move/set of a deleted element, which only a Checkout + /// mode diff resolves. See `context/movable-list-op-validation.md`. + pub(crate) fn references_absent_elem( + &self, + diff: &crate::delta::MovableListInnerDelta, + ) -> bool { + diff.elements.iter().any(|(elem_id, elem)| { + (elem.pos.is_none() || elem.value_id.is_none()) + && !self.inner.elements().contains_key(elem_id) + }) + } +} + +impl ContainerState for MovableListState { + fn container_idx(&self) -> ContainerIdx { + self.idx + } + + fn is_state_empty(&self) -> bool { + self.list().is_empty() && self.elements().is_empty() + } + + fn validate_diff(&self, diff: &InternalDiff) -> LoroResult<()> { + let InternalDiff::MovableList(diff) = diff else { + unreachable!() + }; + + // List items are addressed by op index (dead items included). + let mut cursor = 0usize; + let mut projected = self.inner.len_kind(IndexType::ForOp); + for item in diff.list.iter() { + match item { + DeltaItem::Retain { retain, .. } => { + cursor += retain; + if cursor > projected { + return Err(LoroError::DecodeError( + format!("movable list diff retains {cursor} items but state only has {projected}") + .into_boxed_str(), + )); + } + } + DeltaItem::Insert { insert, .. } => { + if cursor > projected { + return Err(LoroError::DecodeError( + format!("movable list diff inserts at {cursor} but state only has {projected}") + .into_boxed_str(), + )); + } + cursor += insert.len(); + projected += insert.len(); + } + DeltaItem::Delete { delete, .. } => { + if cursor + delete > projected { + return Err(LoroError::DecodeError( + format!("movable list diff deletes {delete} at {cursor} but state only has {projected}") + .into_boxed_str(), + )); + } + projected -= delete; + } + } + } + + // Import callers recompute such diffs in Checkout mode first + // (`DocState::needs_checkout_diff`); reaching here means that was skipped. + if self.references_absent_elem(diff) { + return Err(LoroError::internal( + "movable list diff lacks the value or position of an element absent from state", + )); + } + + Ok(()) + } + + // How we apply the diff is coupled with the [DiffMode] we used to calculate the diff. + // So be careful when you modify this function. + #[instrument(skip_all)] + fn apply_diff_and_convert( + &mut self, + diff: InternalDiff, + DiffApplyContext { doc, mode }: DiffApplyContext, + ) -> Diff { + let InternalDiff::MovableList(mut diff) = diff else { + unreachable!() + }; + + // let start_value = self.get_value(); + if cfg!(debug_assertions) { + self.inner.check_consistency(); + } + + let mut event: ListDiff = DeltaRope::new(); + let mut maybe_moved: FxHashMap<CompactIdLp, (usize, LoroValue)> = FxHashMap::default(); + let need_compare = matches!(mode, DiffMode::Import); + + { + // apply deletions and calculate `maybe_moved` + let mut index = 0; + for delta_item in diff.list.iter() { + match delta_item { + DeltaItem::Retain { + retain, + attributes: _, + } => { + index += retain; + } + DeltaItem::Insert { .. } => {} + DeltaItem::Delete { + delete, + attributes: _, + } => { + let mut user_index = self + .convert_index(index, IndexType::ForOp, IndexType::ForUser) + .unwrap(); + let user_index_end = self + .convert_index(index + delete, IndexType::ForOp, IndexType::ForUser) + .unwrap(); + event.compose( + &DeltaRopeBuilder::new() + .retain(user_index, Default::default()) + .delete(user_index_end - user_index) + .build(), + ); + self.inner + .list_drain(index..index + delete, |elem_id, elem| { + maybe_moved.insert(elem_id, (user_index, elem.value.clone())); + if !matches!(mode, DiffMode::Checkout) { + if let Some(new_elem) = diff.elements.get_mut(&elem_id) { + if new_elem.value_id.is_none() { + new_elem.value = elem.value.clone(); + new_elem.value_id = Some(elem.value_id); + new_elem.value_updated = false; + } + + if new_elem.pos.is_none() { + new_elem.pos = Some(elem.pos); + } + } + } + + user_index += 1; + }); + assert_eq!(user_index, user_index_end); + } + } + } + } + + { + // apply list item changes + let mut index = 0; + for delta_item in diff.list.into_iter() { + match delta_item { + DeltaItem::Retain { + retain, + attributes: _, + } => { + index += retain; + } + DeltaItem::Insert { + insert, + attributes: _, + } => { + let len = insert.len(); + self.list_insert_batch(index, insert.into_iter()); + index += len; + } + DeltaItem::Delete { .. } => {} + } + } + } + + { + let doc = &doc.upgrade().unwrap(); + // Apply element changes + // + // In this block, we need to handle the events generated from the following sources: + // + // - The change of elem's pos that activated the list item. This creates an insert event. + // - The change of elem's value. This create a deletion and an insert event. + // + // It doesn't need to worry about the deletion of the list item, because it's handled by the list diff. + + for (elem_id, delta_item) in diff.elements.into_iter() { + let crate::delta::ElementDelta { + pos, + value, + value_updated, + value_id, + } = delta_item; + // Element may be dropped after snapshot encoding, + // so we need to check which kind of update we need to do + + match self.inner.elements().get(&elem_id).cloned() { + Some(elem) => { + // Update value if needed + if let Some(value_id) = + value_id.filter(|value_id| !need_compare || elem.value_id < *value_id) + { + if elem.value == value { + // Only the winning set op may have changed (e.g. a + // checkout past a later set of the same value): + // keep the value id accurate without an event, as + // for maps. + if elem.value_id != value_id { + self.inner.update_value(elem_id, value, value_id); + } + } else { + maybe_moved.remove(&elem_id); + self.inner.update_value(elem_id, value.clone(), value_id); + let index = self.get_index_of_elem(elem_id); + if let Some(index) = index { + event.compose( + &DeltaRopeBuilder::new() + .retain(index, Default::default()) + .delete(1) + .insert( + ArrayVec::from([ValueOrHandler::from_value( + value, doc, + )]), + ListDeltaMeta { from_move: false }, + ) + .build(), + ) + } + } + } + + // Update pos if needed + if let Some(pos) = pos { + if elem.pos != pos && (!need_compare || elem.pos < pos) { + // don't need to update old list item, because it's handled by list diff already + let result = self.inner.update_pos(elem_id, pos, false); + let result = self.inner.convert_update_to_event_pos(result); + if let Some(new_index) = result.insert { + let new_value = + self.elements().get(&elem_id).unwrap().value.clone(); + let from_delete = if let Some((_elem_index, elem_old_value)) = + maybe_moved.remove(&elem_id) + { + elem_old_value == new_value + } else { + false + }; + let new_delta: ListDiff = DeltaRopeBuilder::new() + .retain(new_index, Default::default()) + .insert( + ArrayVec::from([ValueOrHandler::from_value( + new_value, doc, + )]), + ListDeltaMeta { + from_move: (result.delete.is_some() + && !value_updated) + || from_delete, + }, + ) + .build(); + event.compose(&new_delta); + } + if let Some(del_index) = result.delete { + event.compose( + &DeltaRopeBuilder::new() + .retain(del_index, Default::default()) + .delete(1) + .build(), + ); + } + if !result.activate_new_list_item { + // not matched list item found, remove directly + self.inner.remove_elem_by_id(&elem_id); + } + } + } + } + None => { + // Need to create new element + let result = self.create_new_elem( + elem_id, + pos.unwrap(), + value.clone(), + value_id.unwrap(), + ); + // Composing events + let result = self.inner.convert_update_to_event_pos(result); + // Create event for pos change and value change + if let Some(index) = result.insert { + let from_delete = if let Some((_elem_index, elem_old_value)) = + maybe_moved.remove(&elem_id) + { + elem_old_value == value + } else { + false + }; + event.compose( + &DeltaRopeBuilder::new() + .retain(index, Default::default()) + .insert( + ArrayVec::from([ValueOrHandler::from_value(value, doc)]), + ListDeltaMeta { + from_move: (result.delete.is_some() && !value_updated) + || from_delete, + }, + ) + .build(), + ) + } + if let Some(index) = result.delete { + event.compose( + &DeltaRopeBuilder::new() + .retain(index, Default::default()) + .delete(1) + .build(), + ); + } + if !result.activate_new_list_item { + // not matched list item found, remove directly + self.inner.remove_elem_by_id(&elem_id); + } + } + } + } + } + + { + // Remove redundant elements + + // We now know that the elements inside `maybe_moved` are actually deleted. + // So we can safely remove them. + let redundant = maybe_moved; + for (elem_id, _) in redundant.iter() { + self.inner.remove_elem_by_id(elem_id); + } + } + + // if cfg!(debug_assertions) { + // self.inner.check_consistency(); + // let mut end_value = start_value.clone(); + // end_value.apply_diff_shallow(&[Diff::List(event.clone())]); + // let cur_value = self.get_value(); + // assert_eq!( + // end_value, cur_value, + // "start_value={:#?} event={:#?} new_state={:#?} but the end_value={:#?}", + // start_value, event, cur_value, end_value + // ); + // self.check_get_child_index_correctly(); + // } + + Diff::List(event) + } + + // How we apply the diff is coupled with the [DiffMode] we used to calculate the diff. + // So be careful when you modify this function. + fn apply_diff(&mut self, diff: InternalDiff, ctx: DiffApplyContext) -> LoroResult<()> { + let _ = self.apply_diff_and_convert(diff, ctx); + Ok(()) + } + + #[instrument(skip_all)] + fn apply_local_op(&mut self, op: &RawOp, _: &Op) -> LoroResult<ApplyLocalOpReturn> { + let mut ans: ApplyLocalOpReturn = Default::default(); + match op.content.as_list().unwrap() { + ListOp::Insert { slice, pos } => match slice { + ListSlice::RawData(list) => { + for (i, x) in list.as_ref().iter().enumerate() { + let elem_id = op.idlp().inc(i as i32).try_into().unwrap(); + let pos_id = op.id_full().inc(i as i32); + self.inner.insert_list_item(*pos + i, pos_id); + let _ = self.create_new_elem( + elem_id, + pos_id.idlp(), + x.clone(), + elem_id.to_id(), + ); + } + } + _ => unreachable!(), + }, + ListOp::Delete(span) => { + self.inner + .list_drain(span.start() as usize..span.end() as usize, |_, elem| { + if let Some(c) = elem.value.as_container() { + ans.deleted_containers.push(c.clone()); + } + }); + } + ListOp::Move { from, to, elem_id } => { + self.mov( + *from as usize, + *to as usize, + *elem_id, + op.id_full(), + IndexType::ForOp, + ); + } + ListOp::Set { elem_id, value } => { + let old_value = + self.inner + .update_value(elem_id.compact(), value.clone(), op.idlp()); + if let Some(LoroValue::Container(c)) = old_value { + ans.deleted_containers.push(c); + } + } + ListOp::StyleStart { .. } | ListOp::StyleEnd => unreachable!(), + } + + Ok(ans) + } + + fn to_diff(&mut self, doc: &Weak<LoroDocInner>) -> Diff { + let doc = &doc.upgrade().unwrap(); + Diff::List( + DeltaRopeBuilder::new() + .insert_many( + self.to_vec() + .into_iter() + .map(|v| ValueOrHandler::from_value(v, doc)), + Default::default(), + ) + .build(), + ) + } + + fn get_value(&mut self) -> LoroValue { + let list = self.get_value_inner(); + LoroValue::List(list.into()) + } + + /// Get the index of the child container + fn get_child_index(&self, id: &ContainerID) -> Option<Index> { + self.inner + .get_child_index(id, IndexType::ForUser) + .map(Index::Seq) + } + + fn contains_child(&self, id: &ContainerID) -> bool { + self.inner.contains_child_container(id) + } + + #[allow(unused)] + fn get_child_containers(&self) -> Vec<ContainerID> { + self.inner + .child_container_to_elem() + .iter() + .filter_map(|(c, elem_id)| { + let elem = self.elements().get(elem_id)?; + if elem.value.as_container() != Some(c) { + None + } else { + Some(c.clone()) + } + }) + .collect_vec() + } + + fn fork(&self, _config: &Configure) -> Self { + self.clone() + } +} + +#[columnar(vec, ser, de, iterable)] +#[derive(Debug, Clone)] +struct EncodedId { + #[columnar(strategy = "DeltaRle")] + peer_idx: usize, + #[columnar(strategy = "DeltaRle")] + lamport: u32, +} + +#[columnar(vec, ser, de, iterable)] +#[derive(Debug, Clone, Copy)] +struct EncodedItemForFastSnapshot { + #[columnar(strategy = "DeltaRle")] + invisible_list_item: usize, + #[columnar(strategy = "BoolRle")] + pos_id_eq_elem_id: bool, + #[columnar(strategy = "BoolRle")] + elem_id_eq_last_set_id: bool, +} + +#[columnar(vec, ser, de, iterable)] +#[derive(Debug, Clone)] +struct EncodedIdFull { + #[columnar(strategy = "DeltaRle")] + peer_idx: usize, + #[columnar(strategy = "DeltaRle")] + counter: i32, + #[columnar(strategy = "DeltaRle")] + lamport_sub_counter: i32, +} + +#[columnar(ser, de)] +struct EncodedFastSnapshot { + #[columnar(class = "vec", iter = "EncodedItemForFastSnapshot")] + items: Vec<EncodedItemForFastSnapshot>, + #[columnar(class = "vec", iter = "EncodedIdFull")] + list_item_ids: Vec<EncodedIdFull>, + #[columnar(class = "vec", iter = "EncodedId")] + elem_ids: Vec<EncodedId>, + #[columnar(class = "vec", iter = "EncodedId")] + last_set_ids: Vec<EncodedId>, +} + +mod snapshot { + use loro_common::{IdFull, IdLp, PeerID}; + + use crate::{ + encoding::value_register::ValueRegister, + state::{ + decode_lamport_from_delta, decode_peer_from_table, decode_peer_table, + state_decode_error, ContainerCreationContext, ContainerState, FastStateSnapshot, + }, + }; + + use super::{ + inner::PushElemInfo, EncodedFastSnapshot, EncodedId, EncodedIdFull, + EncodedItemForFastSnapshot, MovableListState, + }; + + impl FastStateSnapshot for MovableListState { + /// Encodes the MovableListState into a compact binary format for fast snapshot storage and retrieval. + /// + /// The encoding format consists of: + /// 1. The full value of the MovableListState, encoded using postcard serialization. + /// 2. A series of EncodedItemForFastSnapshot structs representing each visible list item: + /// - invisible_list_item: Count of invisible items before this item (RLE encoded) + /// - pos_id_eq_elem_id: Boolean indicating if position ID equals element ID (RLE encoded) + /// - elem_id_eq_last_set_id: Boolean indicating if element ID equals last set ID (RLE encoded) + /// 3. A series of EncodedIdFull structs for list item IDs: + /// - peer_idx: Index of the peer ID in a value register (delta-RLE encoded) + /// - counter: Operation counter (delta-RLE encoded) + /// - lamport: Lamport timestamp (delta-RLE encoded) + /// 4. EncodedId structs for element IDs (when different from position ID) + /// 5. EncodedId structs for last set IDs (when different from element ID) + /// 6. A list of unique peer IDs used in the encoding + fn encode_snapshot_fast<W: std::io::prelude::Write>(&mut self, mut w: W) { + let value = self.get_value().into_list().unwrap(); + postcard::to_io(&*value, &mut w).unwrap(); + let mut peers: ValueRegister<PeerID> = ValueRegister::new(); + let len = self.len(); + let mut items = Vec::with_capacity(len); + // starts with a sentinel value. The num of `invisible_list_item` may be updated later + items.push(EncodedItemForFastSnapshot { + pos_id_eq_elem_id: true, + invisible_list_item: 0, + elem_id_eq_last_set_id: true, + }); + + let mut list_item_ids = Vec::with_capacity(self.len()); + let mut elem_ids = Vec::new(); + let mut last_set_ids = Vec::new(); + for item in self.list().iter() { + if let Some(elem_id) = item.pointed_by { + let elem = self.elements().get(&elem_id).unwrap(); + let elem_eq_list_item = elem_id.to_id() == item.id.idlp(); + let elem_id_eq_last_set_id = elem.value_id.compact() == elem_id; + items.push(EncodedItemForFastSnapshot { + invisible_list_item: 0, + pos_id_eq_elem_id: elem_eq_list_item, + elem_id_eq_last_set_id, + }); + + list_item_ids.push(super::EncodedIdFull { + peer_idx: peers.register(&item.id.peer), + counter: item.id.counter, + lamport_sub_counter: (item.id.lamport as i32 - item.id.counter), + }); + if !elem_eq_list_item { + elem_ids.push(super::EncodedId { + peer_idx: peers.register(&elem_id.peer), + lamport: elem_id.lamport.get(), + }) + } + if !elem_id_eq_last_set_id { + last_set_ids.push(super::EncodedId { + peer_idx: peers.register(&elem.value_id.peer), + lamport: elem.value_id.lamport, + }) + } + } else { + items.last_mut().unwrap().invisible_list_item += 1; + list_item_ids.push(super::EncodedIdFull { + peer_idx: peers.register(&item.id.peer), + counter: item.id.counter, + lamport_sub_counter: (item.id.lamport as i32 - item.id.counter), + }); + } + } + + let peers = peers.unwrap_vec(); + leb128::write::unsigned(&mut w, peers.len() as u64).unwrap(); + for peer in peers { + w.write_all(&peer.to_le_bytes()).unwrap(); + } + + let v = serde_columnar::to_vec(&EncodedFastSnapshot { + items, + list_item_ids, + elem_ids, + last_set_ids, + }) + .unwrap(); + w.write_all(&v).unwrap(); + } + + fn decode_value(bytes: &[u8]) -> loro_common::LoroResult<(loro_common::LoroValue, &[u8])> { + crate::state::value_decode::decode_collection(bytes, false) + } + + fn decode_snapshot_fast( + idx: crate::container::idx::ContainerIdx, + (list_value, mut bytes): (loro_common::LoroValue, &[u8]), + _ctx: ContainerCreationContext, + ) -> loro_common::LoroResult<Self> + where + Self: Sized, + { + let peers = decode_peer_table(&mut bytes, "Decode movable list state failed")?; + + let mut ans = MovableListState::new(idx); + + let iters = + serde_columnar::iter_from_bytes::<EncodedFastSnapshot>(bytes).map_err(|err| { + state_decode_error(format!( + "Decode movable list state failed: invalid metadata: {err}" + )) + })?; + let mut elem_iter = iters.elem_ids; + let item_iter = iters.items; + let mut list_item_id_iter = iters.list_item_ids; + let mut last_set_id_iter = iters.last_set_ids; + let mut is_first = true; + + let list_value = list_value.into_list().map_err(|_| { + state_decode_error("Decode movable list state failed: value is not a list") + })?; + let mut list_value_iter = list_value.iter(); + for item in item_iter { + let EncodedItemForFastSnapshot { + invisible_list_item, + pos_id_eq_elem_id, + elem_id_eq_last_set_id, + } = item.map_err(|err| { + state_decode_error(format!( + "Decode movable list state failed: invalid item: {err}" + )) + })?; + + if !is_first { + let EncodedIdFull { + peer_idx, + counter, + lamport_sub_counter, + } = list_item_id_iter + .next() + .ok_or_else(|| { + state_decode_error( + "Decode movable list state failed: missing list item id", + ) + })? + .map_err(|err| { + state_decode_error(format!( + "Decode movable list state failed: invalid list item id: {err}" + )) + })?; + let peer = decode_peer_from_table( + &peers, + peer_idx, + "Decode movable list state failed", + )?; + let id_full = IdFull::new( + peer, + counter, + decode_lamport_from_delta( + counter, + lamport_sub_counter, + "Decode movable list state failed", + )?, + ); + let elem_id = if pos_id_eq_elem_id { + id_full.idlp() + } else { + let EncodedId { peer_idx, lamport } = elem_iter + .next() + .ok_or_else(|| { + state_decode_error( + "Decode movable list state failed: missing element id", + ) + })? + .map_err(|err| { + state_decode_error(format!( + "Decode movable list state failed: invalid element id: {err}" + )) + })?; + IdLp::new( + decode_peer_from_table( + &peers, + peer_idx, + "Decode movable list state failed", + )?, + lamport, + ) + }; + + let last_set_id = if elem_id_eq_last_set_id { + elem_id + } else { + let EncodedId { peer_idx, lamport } = last_set_id_iter + .next() + .ok_or_else(|| { + state_decode_error( + "Decode movable list state failed: missing last set id", + ) + })? + .map_err(|err| { + state_decode_error(format!( + "Decode movable list state failed: invalid last set id: {err}" + )) + })?; + IdLp::new( + decode_peer_from_table( + &peers, + peer_idx, + "Decode movable list state failed", + )?, + lamport, + ) + }; + + let value = list_value_iter.next().ok_or_else(|| { + state_decode_error("Decode movable list state failed: missing list value") + })?; + ans.inner.push_inner( + id_full, + Some(PushElemInfo { + elem_id: elem_id.compact(), + value: value.clone(), + last_set_id, + }), + ) + } + + is_first = false; + for _ in 0..invisible_list_item { + let EncodedIdFull { + peer_idx, + counter, + lamport_sub_counter, + } = list_item_id_iter + .next() + .ok_or_else(|| { + state_decode_error( + "Decode movable list state failed: missing invisible list item id", + ) + })? + .map_err(|err| { + state_decode_error(format!( + "Decode movable list state failed: invalid invisible list item id: {err}" + )) + })?; + let peer = decode_peer_from_table( + &peers, + peer_idx, + "Decode movable list state failed", + )?; + let id_full = IdFull::new( + peer, + counter, + decode_lamport_from_delta( + counter, + lamport_sub_counter, + "Decode movable list state failed", + )?, + ); + ans.inner.push_inner(id_full, None); + } + } + + if is_first { + return Err(state_decode_error( + "Decode movable list state failed: missing sentinel item", + )); + } + if elem_iter + .next() + .transpose() + .map_err(|err| { + state_decode_error(format!( + "Decode movable list state failed: invalid extra element id: {err}" + )) + })? + .is_some() + { + return Err(state_decode_error( + "Decode movable list state failed: unused element id", + )); + } + if list_item_id_iter + .next() + .transpose() + .map_err(|err| { + state_decode_error(format!( + "Decode movable list state failed: invalid extra list item id: {err}" + )) + })? + .is_some() + { + return Err(state_decode_error( + "Decode movable list state failed: unused list item id", + )); + } + if last_set_id_iter + .next() + .transpose() + .map_err(|err| { + state_decode_error(format!( + "Decode movable list state failed: invalid extra last set id: {err}" + )) + })? + .is_some() + { + return Err(state_decode_error( + "Decode movable list state failed: unused last set id", + )); + } + if list_value_iter.next().is_some() { + return Err(state_decode_error( + "Decode movable list state failed: unused list value", + )); + } + + Ok(ans) + } + } + + #[cfg(test)] + mod test { + + use loro_common::{CompactIdLp, ContainerID, LoroValue, ID}; + + use crate::container::idx::ContainerIdx; + + use super::*; + + #[test] + fn test_movable_list_snapshot() { + let mut list = MovableListState::new(ContainerIdx::from_index_and_type( + 0, + loro_common::ContainerType::MovableList, + )); + + list.inner.insert_list_item(0, IdFull::new(9, 9, 9)); + list.inner.insert_list_item(1, IdFull::new(0, 0, 0)); + let _ = list.create_new_elem( + CompactIdLp::new(10, 10), + IdLp { + lamport: 0, + peer: 0, + }, + LoroValue::Container(ContainerID::new_normal( + ID::new(10, 10), + loro_common::ContainerType::Text, + )), + IdLp { + lamport: 1, + peer: 2, + }, + ); + list.inner.insert_list_item(2, IdFull::new(1, 1, 1)); + list.inner.insert_list_item(3, IdFull::new(2, 2, 2)); + list.inner.insert_list_item(4, IdFull::new(3, 3, 3)); + let _ = list.create_new_elem( + CompactIdLp::new(3, 8), + IdLp { + lamport: 3, + peer: 3, + }, + LoroValue::String("abc".into()), + IdLp { + lamport: 4, + peer: 5, + }, + ); + + let mut bytes = Vec::new(); + list.encode_snapshot_fast(&mut bytes); + assert!(bytes.len() <= 117, "{}", bytes.len()); + + let (v, bytes) = MovableListState::decode_value(&bytes).unwrap(); + assert_eq!( + v, + vec![ + LoroValue::Container(ContainerID::new_normal( + ID::new(10, 10), + loro_common::ContainerType::Text, + )), + LoroValue::String("abc".into()), + ] + .into() + ); + let mut list2 = MovableListState::decode_snapshot_fast( + ContainerIdx::from_index_and_type(0, loro_common::ContainerType::MovableList), + (v.clone(), bytes), + ContainerCreationContext { + configure: &Default::default(), + peer: 0, + }, + ) + .unwrap(); + assert_eq!(&list2.get_value(), &v); + assert_eq!(&list.inner, &list2.inner); + } + + #[test] + fn test_movable_list_snapshot_size() { + let mut list = MovableListState::new(ContainerIdx::from_index_and_type( + 0, + loro_common::ContainerType::MovableList, + )); + + list.inner.insert_list_item(0, IdFull::new(0, 0, 0)); + let _ = list.create_new_elem( + CompactIdLp::new(0, 0), + IdLp { + lamport: 0, + peer: 0, + }, + LoroValue::I64(0), + IdLp { + lamport: 0, + peer: 0, + }, + ); + + list.inner.insert_list_item(1, IdFull::new(0, 1, 1)); + let _ = list.create_new_elem( + CompactIdLp::new(0, 1), + IdLp { + peer: 0, + lamport: 1, + }, + LoroValue::I64(0), + IdLp { + peer: 0, + lamport: 1, + }, + ); + + let mut bytes = Vec::new(); + list.encode_snapshot_fast(&mut bytes); + assert!(bytes.len() <= 42, "{}", bytes.len()); + + list.inner.insert_list_item(2, IdFull::new(0, 1, 2)); + let _ = list.create_new_elem( + CompactIdLp::new(0, 2), + IdLp { + peer: 0, + lamport: 2, + }, + LoroValue::I64(0), + IdLp { + peer: 0, + lamport: 2, + }, + ); + let mut bytes = Vec::new(); + list.encode_snapshot_fast(&mut bytes); + assert!(bytes.len() <= 47, "{}", bytes.len()); + } + + #[test] + fn movable_list_fast_snapshot_rejects_corrupt_state_metadata() { + let idx = ContainerIdx::from_index_and_type(0, loro_common::ContainerType::MovableList); + let configure = Default::default(); + let ctx = ContainerCreationContext { + configure: &configure, + peer: 0, + }; + + assert!(MovableListState::decode_snapshot_fast( + idx, + (Vec::<LoroValue>::new().into(), &[1]), + ctx, + ) + .is_err()); + + let mut list = MovableListState::new(idx); + let mut bytes = Vec::new(); + list.encode_snapshot_fast(&mut bytes); + let (_, state_bytes) = MovableListState::decode_value(&bytes).unwrap(); + assert!(MovableListState::decode_snapshot_fast( + idx, + (vec![LoroValue::I64(1)].into(), state_bytes), + ctx, + ) + .is_err()); + } + } +} + +#[cfg(test)] +mod test { + use crate::{loro::ExportMode, HandlerTrait, LoroDoc, ToJson}; + use serde_json::json; + + #[test] + fn basic_handler_ops() { + let doc = LoroDoc::new_auto_commit(); + let list = doc.get_movable_list("list"); + list.insert(0, 0).unwrap(); + list.insert(1, 1).unwrap(); + list.insert(2, 2).unwrap(); + assert_eq!(list.get_value().to_json_value(), json!([0, 1, 2])); + list.mov(0, 1).unwrap(); + assert_eq!(list.get_value().to_json_value(), json!([1, 0, 2])); + list.mov(2, 0).unwrap(); + assert_eq!(list.get_value().to_json_value(), json!([2, 1, 0])); + list.delete(0, 2).unwrap(); + assert_eq!(list.get_value().to_json_value(), json!([0])); + list.insert(0, 9).unwrap(); + assert_eq!(list.get_value().to_json_value(), json!([9, 0])); + list.delete(0, 2).unwrap(); + assert_eq!(list.get_value().to_json_value(), json!([])); + } + + #[test] + fn basic_sync() { + let doc = LoroDoc::new_auto_commit(); + let list = doc.get_movable_list("list"); + list.insert(0, 1).unwrap(); + list.insert(1, 0).unwrap(); + list.mov(0, 1).unwrap(); + { + let doc_b = LoroDoc::new_auto_commit(); + doc_b + .import(&doc.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + assert_eq!( + doc_b.get_deep_value().to_json_value(), + json!({ + "list": [0, 1] + }) + ); + } + list.mov(1, 0).unwrap(); + assert_eq!( + doc.get_deep_value().to_json_value(), + json!({ + "list": [1, 0] + }) + ); + { + let doc_b = LoroDoc::new_auto_commit(); + doc_b + .import(&doc.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + assert_eq!( + doc_b.get_deep_value().to_json_value(), + json!({ + "list": [1, 0] + }) + ); + } + list.mov(0, 1).unwrap(); + list.insert(2, 3).unwrap(); + list.set(2, 2).unwrap(); + assert_eq!( + doc.get_deep_value().to_json_value(), + json!({ + "list": [0, 1, 2] + }) + ); + { + let doc_b = LoroDoc::new_auto_commit(); + doc_b + .import(&doc.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + assert_eq!( + doc_b.get_deep_value().to_json_value(), + json!({ + "list": [0, 1, 2] + }) + ); + } + { + let doc_b = LoroDoc::new_auto_commit(); + doc_b + .import(&doc.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + assert_eq!( + doc_b.get_deep_value().to_json_value(), + json!({ + "list": [0, 1, 2] + }) + ); + } + } +} diff --git a/vendor/loro-internal/src/state/richtext_state.rs b/vendor/loro-internal/src/state/richtext_state.rs new file mode 100644 index 0000000..394094f --- /dev/null +++ b/vendor/loro-internal/src/state/richtext_state.rs @@ -0,0 +1,1979 @@ +use generic_btree::{rle::HasLength, rle::Sliceable as _, Cursor}; +use loro_common::{ContainerID, InternalString, LoroError, LoroResult, LoroValue, ID}; +use loro_delta::{DeltaRope, DeltaRopeBuilder}; +use rustc_hash::{FxHashMap, FxHashSet}; +use smallvec::SmallVec; +use std::ops::Range; +use std::sync::{Arc, Weak}; + +use crate::{ + container::{ + idx::ContainerIdx, + list::list_op, + richtext::{ + config::StyleConfigMap, + richtext_state::{DrainInfo, EntityRanges, IterRangeItem, PosType, RichtextStateChunk}, + AnchorType, RichtextState as InnerState, StyleKey, StyleOp, Styles, + }, + }, + delta::{StyleMeta, StyleMetaItem}, + event::{Diff, Index, InternalDiff, TextDiff}, + handler::TextDelta, + op::{Op, RawOp}, + sync::RwLock, + utils::{lazy::LazyLoad, string_slice::StringSlice}, + LoroDocInner, +}; + +use super::{ApplyLocalOpReturn, ContainerState, DiffApplyContext}; + +#[derive(Debug)] +pub struct RichtextState { + idx: ContainerIdx, + config: Arc<RwLock<StyleConfigMap>>, + state: LazyLoad<RichtextStateLoader, InnerState>, + /// This is used to indicate whether the richtext state is changed, so the downstream has an easy way to cache + /// NOTE: We need to ensure the invariance that the version id is always increased when the richtext state is changed + version_id: usize, +} + +struct Pos { + entity_index: usize, + event_index: usize, +} + +impl RichtextState { + #[inline] + pub fn new(idx: ContainerIdx, config: Arc<RwLock<StyleConfigMap>>) -> Self { + Self { + idx, + config, + state: LazyLoad::Src(Default::default()), + version_id: 0, + } + } + + #[inline] + fn update_version(&mut self) { + self.version_id = self.version_id.wrapping_add(1); + } + + /// Get the version id of the richtext + /// + /// This can be used to detect whether the richtext is changed + #[inline] + pub fn get_version_id(&self) -> usize { + self.version_id + } + + /// Get the text content of the richtext + /// + /// This uses `mut` because we may need to build the state from snapshot + #[inline] + pub fn to_string_mut(&mut self) -> String { + self.state.get_mut().to_string() + } + + #[allow(unused)] + #[inline(always)] + pub(crate) fn is_empty(&self) -> bool { + match &self.state { + LazyLoad::Src(s) => s.elements.is_empty(), + LazyLoad::Dst(d) => d.is_empty(), + } + } + + pub(crate) fn diagnose(&self) { + match &self.state { + LazyLoad::Src(_) => {} + LazyLoad::Dst(d) => d.diagnose(), + } + } + + #[allow(unused)] + pub(crate) fn get_text_slice_by_event_index( + &mut self, + pos: usize, + len: usize, + ) -> LoroResult<String> { + self.state.get_mut().get_text_slice_by_event_index(pos, len) + } + + pub(crate) fn slice_delta( + &mut self, + start_index: usize, + end_index: usize, + pos_type: PosType, + ) -> LoroResult<Vec<(String, StyleMeta)>> { + self.state + .get_mut() + .slice_delta(start_index, end_index, pos_type) + } + + #[allow(unused)] + pub(crate) fn get_char_by_event_index(&mut self, pos: usize) -> Result<char, ()> { + self.state.get_mut().get_char_by_event_index(pos) + } + + pub(crate) fn iter(&mut self, mut callback: impl FnMut(&str) -> bool) { + for span in self.state.get_mut().iter_chunk() { + match span { + RichtextStateChunk::Text(text_chunk) => { + if !callback(text_chunk.as_str()) { + return; + } + } + RichtextStateChunk::Style { .. } => {} + } + } + } + + pub(crate) fn iter_raw(&self, callback: &mut dyn FnMut(&RichtextStateChunk)) { + let iter: &mut dyn Iterator<Item = &RichtextStateChunk>; + let mut a; + let mut b; + match &self.state { + LazyLoad::Src(s) => { + a = Some(s.elements.iter()); + iter = &mut *a.as_mut().unwrap(); + } + LazyLoad::Dst(s) => { + b = Some(s.iter_chunk()); + iter = &mut *b.as_mut().unwrap(); + } + } + + for c in iter { + callback(c); + } + } + + fn get_style_start( + &mut self, + style_starts: &mut FxHashMap<Arc<StyleOp>, Pos>, + style: &Arc<StyleOp>, + ) -> Pos { + self.update_version(); + match style_starts.remove(style) { + Some(x) => x, + None => { + // this should happen rarely, so it should be fine to scan + let mut pos = Pos { + entity_index: 0, + event_index: 0, + }; + + for c in self.state.get_mut().iter_chunk() { + match c { + RichtextStateChunk::Style { + style: s, + anchor_type: AnchorType::Start, + } if style == s => { + break; + } + RichtextStateChunk::Text(t) => { + pos.entity_index += t.unicode_len() as usize; + pos.event_index += t.event_len() as usize; + } + RichtextStateChunk::Style { .. } => { + pos.entity_index += 1; + } + } + } + pos + } + } + } + + pub fn get_index_of_id(&self, id: ID) -> Option<usize> { + let iter: &mut dyn Iterator<Item = &RichtextStateChunk>; + let mut a; + let mut b; + match &self.state { + LazyLoad::Src(s) => { + a = Some(s.elements.iter()); + iter = &mut *a.as_mut().unwrap(); + } + LazyLoad::Dst(s) => { + b = Some(s.iter_chunk()); + iter = &mut *b.as_mut().unwrap(); + } + } + + let mut index = 0; + for elem in iter { + let span = elem.get_id_span(); + if span.contains(id) { + return Some(index + (id.counter - span.counter.start) as usize); + } + + index += elem.rle_len(); + } + + None + } + + pub fn get_text_index_of_id(&self, id: ID, use_event_index: bool) -> Option<usize> { + let iter: &mut dyn Iterator<Item = &RichtextStateChunk>; + let mut a; + let mut b; + match &self.state { + LazyLoad::Src(s) => { + a = Some(s.elements.iter()); + iter = &mut *a.as_mut().unwrap(); + } + LazyLoad::Dst(s) => { + b = Some(s.iter_chunk()); + iter = &mut *b.as_mut().unwrap(); + } + } + + let mut index = 0; + for elem in iter { + let span = elem.get_id_span(); + if span.contains(id) { + match elem { + RichtextStateChunk::Text(t) => { + if use_event_index { + let event_offset = t.convert_unicode_offset_to_event_offset( + (id.counter - span.counter.start) as usize, + ); + return Some(index + event_offset); + } else { + return Some(index + (id.counter - span.counter.start) as usize); + } + } + RichtextStateChunk::Style { .. } => { + return Some(index); + } + } + } + + index += match elem { + RichtextStateChunk::Text(t) => { + if use_event_index { + t.event_len() as usize + } else { + t.unicode_len() as usize + } + } + RichtextStateChunk::Style { .. } => 0, + }; + } + + None + } + + pub(crate) fn get_delta(&mut self) -> Vec<TextDelta> { + let mut delta = Vec::new(); + for span in self.state.get_mut().iter() { + let next_attr = span.attributes.to_option_map(); + match delta.last_mut() { + Some(TextDelta::Insert { insert, attributes }) if &next_attr == attributes => { + insert.push_str(span.text.as_str()); + continue; + } + _ => {} + } + delta.push(TextDelta::Insert { + insert: span.text.as_str().to_string(), + attributes: next_attr, + }) + } + delta + } +} + +#[cfg(test)] +mod tests { + use crate::{container::richtext::StyleKey, cursor::PosType, handler::HandlerTrait, LoroDoc}; + + #[test] + fn has_style_key_in_entity_range_basic() { + let loro = LoroDoc::new_auto_commit(); + let text = loro.get_text("text"); + text.insert(0, "abcdef", PosType::Unicode).unwrap(); + text.mark(1, 3, "bold", true.into(), PosType::Unicode) + .unwrap(); + + let bold_key = StyleKey::Key("bold".into()); + let has_style = text + .with_state(|state| { + let st = state.as_richtext_state_mut().unwrap(); + let (entity_range, _) = + st.get_entity_range_and_styles_at_range(1..3, PosType::Unicode); + Ok(st.has_style_key_in_entity_range(entity_range, &bold_key)) + }) + .unwrap(); + assert!(has_style); + + let missing = text + .with_state(|state| { + let st = state.as_richtext_state_mut().unwrap(); + let (entity_range, _) = + st.get_entity_range_and_styles_at_range(4..5, PosType::Unicode); + Ok(st.has_style_key_in_entity_range(entity_range, &bold_key)) + }) + .unwrap(); + assert!(!missing); + } + + #[test] + fn has_style_key_in_entity_range_spans_elements() { + let loro = LoroDoc::new_auto_commit(); + let text = loro.get_text("text"); + text.insert(0, "abcdefgh", PosType::Unicode).unwrap(); + text.mark(0, 2, "bold", true.into(), PosType::Unicode) + .unwrap(); + text.mark(3, 5, "bold", true.into(), PosType::Unicode) + .unwrap(); + + let bold_key = StyleKey::Key("bold".into()); + + let has_style_across_segments = text + .with_state(|state| { + let st = state.as_richtext_state_mut().unwrap(); + let (entity_range, _) = + st.get_entity_range_and_styles_at_range(0..5, PosType::Unicode); + Ok(st.has_style_key_in_entity_range(entity_range, &bold_key)) + }) + .unwrap(); + assert!(has_style_across_segments); + + let gap_has_style = text + .with_state(|state| { + let st = state.as_richtext_state_mut().unwrap(); + let (entity_range, _) = + st.get_entity_range_and_styles_at_range(6..7, PosType::Unicode); + Ok(st.has_style_key_in_entity_range(entity_range, &bold_key)) + }) + .unwrap(); + assert!(!gap_has_style); + } +} + +impl Clone for RichtextState { + fn clone(&self) -> Self { + Self { + idx: self.idx, + config: self.config.clone(), + state: self.state.clone(), + version_id: self.version_id, + } + } +} + +impl ContainerState for RichtextState { + fn container_idx(&self) -> ContainerIdx { + self.idx + } + + fn is_state_empty(&self) -> bool { + match &self.state { + LazyLoad::Src(s) => s.is_empty(), + LazyLoad::Dst(s) => s.is_empty(), + } + } + + // TODO: refactor + fn apply_diff_and_convert(&mut self, diff: InternalDiff, _ctx: DiffApplyContext) -> Diff { + self.update_version(); + let InternalDiff::RichtextRaw(richtext) = diff else { + unreachable!() + }; + + // tracing::info!("Self state = {:#?}", &self); + // PERF: compose delta + let mut ans: TextDiff = TextDiff::new(); + let mut style_delta: TextDiff = TextDiff::new(); + let mut style_starts: FxHashMap<Arc<StyleOp>, Pos> = FxHashMap::default(); + let mut entity_index = 0; + let mut event_index = 0; + let mut new_style_deltas: Vec<TextDiff> = Vec::new(); + for span in richtext.iter() { + match span { + loro_delta::DeltaItem::Retain { len, .. } => { + entity_index += len; + } + loro_delta::DeltaItem::Replace { value, delete, .. } => { + if *delete > 0 { + // Deletions + let mut deleted_style_keys: FxHashSet<InternalString> = + FxHashSet::default(); + let DrainInfo { + start_event_index: start, + end_event_index: end, + affected_style_range, + } = self.state.get_mut().drain_by_entity_index( + entity_index, + *delete, + Some(&mut |c| match c { + RichtextStateChunk::Style { + style, + anchor_type: AnchorType::Start, + } => { + deleted_style_keys.insert(style.key.clone()); + } + RichtextStateChunk::Style { + style, + anchor_type: AnchorType::End, + } => { + deleted_style_keys.insert(style.key.clone()); + } + _ => {} + }), + ); + + if start > event_index { + ans.push_retain(start - event_index, Default::default()); + event_index = start; + } + + if let Some((entity_range, event_range)) = affected_style_range { + let mut delta: TextDiff = DeltaRopeBuilder::new() + .retain(event_range.start, Default::default()) + .build(); + let mut entity_len_sum = 0; + let expected_sum = entity_range.len(); + + for IterRangeItem { + event_len, + chunk, + styles, + entity_len, + .. + } in self.state.get_mut().iter_range(entity_range) + { + entity_len_sum += entity_len; + match chunk { + RichtextStateChunk::Text(_) => { + let mut style_meta: StyleMeta = styles.into(); + for key in deleted_style_keys.iter() { + if !style_meta.contains_key(key) { + style_meta.insert( + key.clone(), + StyleMetaItem { + lamport: 0, + peer: 0, + value: LoroValue::Null, + }, + ) + } + } + delta.push_retain( + event_len, + style_meta.to_option_map().unwrap_or_default().into(), + ); + } + RichtextStateChunk::Style { .. } => {} + } + } + + debug_assert_eq!(entity_len_sum, expected_sum); + delta.chop(); + style_delta.compose(&delta); + } + + ans.push_delete(end - start); + } + + if value.rle_len() > 0 { + // Insertions + match value { + RichtextStateChunk::Text(s) => { + let (pos, styles) = + self.state.get_mut().insert_elem_at_entity_index( + entity_index, + RichtextStateChunk::Text(s.clone()), + ); + // PERF: this can be optimized + let insert_styles = Into::<StyleMeta>::into(styles.clone()) + .to_option_map() + .unwrap_or_default(); + + if pos > event_index { + ans.push_retain(pos - event_index, Default::default()); + } + event_index = pos + s.event_len() as usize; + ans.push_insert( + StringSlice::from(s.bytes().clone()), + insert_styles.into(), + ); + } + RichtextStateChunk::Style { anchor_type, style } => { + let (new_event_index, _) = + self.state.get_mut().insert_elem_at_entity_index( + entity_index, + RichtextStateChunk::Style { + style: style.clone(), + anchor_type: *anchor_type, + }, + ); + + if new_event_index > event_index { + ans.push_retain( + new_event_index - event_index, + Default::default(), + ); + // inserting style anchor will not affect event_index's positions + event_index = new_event_index; + } + + match anchor_type { + AnchorType::Start => { + style_starts.insert( + style.clone(), + Pos { + entity_index, + event_index: new_event_index, + }, + ); + } + AnchorType::End => { + // get the pair of style anchor. now we can annotate the range + let Pos { + entity_index: start_entity_index, + event_index: start_event_index, + } = self.get_style_start(&mut style_starts, style); + let mut delta: TextDiff = DeltaRopeBuilder::new() + .retain(start_event_index, Default::default()) + .build(); + // we need to + 1 because we also need to annotate the end anchor + let event = + self.state.get_mut().annotate_style_range_with_event( + start_entity_index..entity_index + 1, + style.clone(), + ); + for (s, l) in event { + delta.push_retain( + l, + s.to_option_map().unwrap_or_default().into(), + ); + } + + delta.chop(); + new_style_deltas.push(delta); + } + } + } + } + + entity_index += value.rle_len(); + } + } + } + } + + for s in new_style_deltas { + style_delta.compose(&s); + } + // self.check_consistency_between_content_and_style_ranges(); + ans.compose(&style_delta); + Diff::Text(ans) + } + + fn validate_diff(&self, diff: &InternalDiff) -> LoroResult<()> { + let InternalDiff::RichtextRaw(delta) = diff else { + unreachable!() + }; + + // Text items are addressed by entity index (style anchors included). + let mut cursor = 0usize; + let mut projected = match &self.state { + LazyLoad::Src(s) => s.entity_index, + LazyLoad::Dst(s) => s.len_entity(), + }; + for span in delta.iter() { + match span { + loro_delta::DeltaItem::Retain { len, .. } => { + cursor += len; + if cursor > projected { + return Err(LoroError::DecodeError( + format!( + "text diff retains {cursor} items but state only has {projected}" + ) + .into_boxed_str(), + )); + } + } + loro_delta::DeltaItem::Replace { value, delete, .. } => { + if cursor + delete > projected { + return Err(LoroError::DecodeError( + format!("text diff deletes {delete} at {cursor} but state only has {projected}") + .into_boxed_str(), + )); + } + projected = projected - delete + value.rle_len(); + cursor += value.rle_len(); + } + } + } + + Ok(()) + } + + fn apply_diff(&mut self, diff: InternalDiff, _ctx: DiffApplyContext) -> LoroResult<()> { + self.update_version(); + let InternalDiff::RichtextRaw(richtext) = diff else { + unreachable!() + }; + + if let LazyLoad::Src(loader) = &mut self.state { + if loader.try_apply_append_delta(&richtext) { + return Ok(()); + } + } + + // Fast path for plain-text deltas (no style anchors / style ranges). + // + // Rebuilding avoids repeated BTree queries and mutations when the delta is very "choppy" + // (many small edit spans), but it allocates and clones chunks, so it can be slower for + // small deltas. Use a cheap cost model to enable it only when it's likely beneficial. + let should_fast_apply = { + #[inline] + fn ilog2_ceil(x: usize) -> usize { + debug_assert!(x > 0); + (usize::BITS - (x - 1).leading_zeros()) as usize + } + + let state = self.state.get_mut(); + if state.has_styles() { + false + } else { + // `edit_actions` approximates how many BTree mutations the incremental path will do: + // each Replace with delete>0 becomes a drain, and each Replace with value>0 becomes an insert. + let mut edit_actions: usize = 0; + let mut is_plain_text_delta = true; + for span in richtext.iter() { + match span { + loro_delta::DeltaItem::Retain { .. } => {} + loro_delta::DeltaItem::Replace { value, delete, .. } => { + if *delete > 0 { + edit_actions += 1; + } + if value.rle_len() > 0 { + if !matches!(value, RichtextStateChunk::Text(_)) { + is_plain_text_delta = false; + break; + } + edit_actions += 1; + } + } + } + } + + if !is_plain_text_delta || edit_actions == 0 { + false + } else { + let content_nodes = state.content_node_len().max(1); + let log_n = ilog2_ceil(content_nodes + 1).max(1); + let incremental_score = edit_actions.saturating_mul(log_n); + let rebuild_score = content_nodes.saturating_add(edit_actions); + + let old_len = richtext.old_len().max(1); + let avg_action_span = old_len / edit_actions; + // A very rough proxy for "choppiness": many edit actions with small average span. + // The thresholds are intentionally conservative to avoid rebuilding for small or + // localized deltas. + let is_choppy = edit_actions >= 256 && avg_action_span <= 32; + + is_choppy && incremental_score >= rebuild_score.saturating_mul(4) + } + } + }; + + if should_fast_apply { + let new_state = { + let state = self.state.get_mut(); + let mut chunks: Vec<RichtextStateChunk> = Vec::new(); + + let mut src_iter = state.iter_chunk(); + let mut cur = src_iter.next(); + let mut cur_offset: usize = 0; + + for span in richtext.iter() { + match span { + loro_delta::DeltaItem::Retain { len, .. } => { + let mut left = *len; + while left > 0 { + let chunk = cur.expect("Delta retain exceeds source length"); + let chunk_len = chunk.rle_len(); + if chunk_len == 0 { + cur = src_iter.next(); + cur_offset = 0; + continue; + } + let available = chunk_len - cur_offset; + let take = left.min(available); + if take == chunk_len && cur_offset == 0 { + chunks.push(chunk.clone()); + } else { + chunks.push(chunk.slice(cur_offset..cur_offset + take)); + } + + left -= take; + cur_offset += take; + if cur_offset == chunk_len { + cur = src_iter.next(); + cur_offset = 0; + } + } + } + loro_delta::DeltaItem::Replace { value, delete, .. } => { + let mut left = *delete; + while left > 0 { + let chunk = cur.expect("Delta delete exceeds source length"); + let chunk_len = chunk.rle_len(); + if chunk_len == 0 { + cur = src_iter.next(); + cur_offset = 0; + continue; + } + let available = chunk_len - cur_offset; + let take = left.min(available); + left -= take; + cur_offset += take; + if cur_offset == chunk_len { + cur = src_iter.next(); + cur_offset = 0; + } + } + + if value.rle_len() > 0 { + chunks.push(value.clone()); + } + } + } + } + + if let Some(chunk) = cur { + let chunk_len = chunk.rle_len(); + if cur_offset < chunk_len { + if cur_offset == 0 { + chunks.push(chunk.clone()); + } else { + chunks.push(chunk.slice(cur_offset..chunk_len)); + } + } + } + for chunk in src_iter { + chunks.push(chunk.clone()); + } + + InnerState::from_chunks(chunks.into_iter()) + }; + + *self.state.get_mut() = new_state; + return Ok(()); + } + + let mut style_starts: FxHashMap<Arc<StyleOp>, usize> = FxHashMap::default(); + let mut entity_index = 0; + for span in richtext.iter() { + match span { + loro_delta::DeltaItem::Retain { len, .. } => { + entity_index += len; + } + loro_delta::DeltaItem::Replace { value, delete, .. } => { + if *delete > 0 { + // Deletions + self.state + .get_mut() + .drain_by_entity_index(entity_index, *delete, None); + } + if value.rle_len() > 0 { + // Insertions + match value { + RichtextStateChunk::Text(s) => { + self.state.get_mut().insert_elem_at_entity_index( + entity_index, + RichtextStateChunk::Text(s.clone()), + ); + } + RichtextStateChunk::Style { style, anchor_type } => { + self.state.get_mut().insert_elem_at_entity_index( + entity_index, + RichtextStateChunk::Style { + style: style.clone(), + anchor_type: *anchor_type, + }, + ); + + if *anchor_type == AnchorType::Start { + style_starts.insert(style.clone(), entity_index); + } else { + let start_pos = match style_starts.get(style) { + Some(x) => *x, + None => { + // This should be rare, so it should be fine to scan + let mut start_entity_index = 0; + for c in self.state.get_mut().iter_chunk() { + match c { + RichtextStateChunk::Style { + style: s, + anchor_type: AnchorType::Start, + } if style == s => { + break; + } + RichtextStateChunk::Text(t) => { + start_entity_index += + t.unicode_len() as usize; + } + RichtextStateChunk::Style { .. } => { + start_entity_index += 1; + } + } + } + start_entity_index + } + }; + // we need to + 1 because we also need to annotate the end anchor + self.state.get_mut().annotate_style_range( + start_pos..entity_index + 1, + style.clone(), + ); + } + } + } + entity_index += value.rle_len(); + } + } + } + } + + // self.check_consistency_between_content_and_style_ranges() + Ok(()) + } + + fn apply_local_op(&mut self, r_op: &RawOp, op: &Op) -> LoroResult<ApplyLocalOpReturn> { + self.update_version(); + match &op.content { + crate::op::InnerContent::List(l) => match l { + list_op::InnerListOp::Insert { slice: _, pos: _ } => { + unreachable!() + } + list_op::InnerListOp::InsertText { + slice, + unicode_len: _, + pos, + } => { + self.state.get_mut().insert_at_entity_index( + *pos as usize, + slice.clone(), + r_op.id_full(), + ); + } + list_op::InnerListOp::Delete(del) => { + self.state.get_mut().drain_by_entity_index( + del.start() as usize, + rle::HasLength::atom_len(&del), + None, + ); + } + list_op::InnerListOp::StyleStart { + start, + end, + key, + value, + info, + } => { + // Behavior here is a little different from apply_diff. + // + // When apply_diff, we only do the mark when we have included both + // StyleStart and StyleEnd. + // + // When applying local op, we can do the mark when we have StyleStart. + // We can assume StyleStart and StyleEnd are always appear in a pair + // for apply_local_op. (Because for local behavior, when we mark, + // we always create a pair of style ops.) + self.state.get_mut().mark_with_entity_index( + *start as usize..*end as usize, + Arc::new(StyleOp { + lamport: r_op.lamport, + peer: r_op.id.peer, + cnt: r_op.id.counter, + key: key.clone(), + value: value.clone(), + info: *info, + }), + ); + } + list_op::InnerListOp::Set { .. } => {} + list_op::InnerListOp::StyleEnd => {} + list_op::InnerListOp::Move { .. } => unreachable!(), + }, + _ => unreachable!(), + } + + // self.check_consistency_between_content_and_style_ranges(); + Ok(Default::default()) + } + + fn to_diff(&mut self, _doc: &Weak<LoroDocInner>) -> Diff { + // Coalesce adjacent spans first: each `push_insert` re-measures the merged + // slice, so pushing many small contiguous spans is quadratic. (project_note patch) + use generic_btree::rle::Mergeable; + let mut delta = TextDiff::new(); + let mut pending: Option<(crate::utils::string_slice::StringSlice, crate::event::TextMeta)> = None; + for span in self.state.get_mut().iter() { + let meta: crate::event::TextMeta = span.attributes.to_option_map().unwrap_or_default().into(); + if let Some((text, m)) = &mut pending { + if *m == meta && text.can_merge(&span.text) { + text.merge_right(&span.text); + continue; + } + } + if let Some((text, m)) = pending.replace((span.text, meta)) { + delta.push_insert(text, m); + } + } + if let Some((text, m)) = pending { + delta.push_insert(text, m); + } + + Diff::Text(delta) + } + + // value is a list + fn get_value(&mut self) -> LoroValue { + match &self.state { + LazyLoad::Src(loader) => loader.to_plain_string().into(), + LazyLoad::Dst(_) => self.state.get_mut().to_string().into(), + } + } + + #[doc = r" Get the index of the child container"] + #[allow(unused)] + fn get_child_index(&self, id: &ContainerID) -> Option<Index> { + None + } + + #[allow(unused)] + fn get_child_containers(&self) -> Vec<ContainerID> { + Vec::new() + } + + fn contains_child(&self, _id: &ContainerID) -> bool { + false + } + + fn fork(&self, config: &crate::configure::Configure) -> Self { + Self { + idx: self.idx, + config: config.text_style_config.clone(), + state: self.state.clone(), + version_id: 0, + } + } +} + +impl RichtextState { + #[inline(always)] + pub fn len_utf8(&mut self) -> usize { + self.state.get_mut().len_utf8() + } + + #[inline(always)] + pub fn len(&mut self, pos_type: PosType) -> usize { + self.state.get_mut().len(pos_type) + } + + #[inline(always)] + pub fn len_utf16(&mut self) -> usize { + self.state.get_mut().len_utf16() + } + + #[inline(always)] + pub fn len_entity(&self) -> usize { + match &self.state { + LazyLoad::Src(s) => s.entity_index, + LazyLoad::Dst(d) => d.len_entity(), + } + } + + pub fn len_event(&mut self) -> usize { + if cfg!(feature = "wasm") { + self.len_utf16() + } else { + self.len_unicode() + } + } + + #[inline] + #[allow(dead_code)] + pub(crate) fn has_styles(&mut self) -> bool { + self.state.get_mut().has_styles() + } + + pub(crate) fn has_style_key_in_entity_range( + &mut self, + range: Range<usize>, + key: &StyleKey, + ) -> bool { + self.state.get_mut().range_has_style_key(range, key) + } + + pub(crate) fn has_style_key_value_in_entity_range( + &mut self, + range: Range<usize>, + key: &str, + value: &LoroValue, + ) -> bool { + self.state + .get_mut() + .range_has_style_key_value(range, key, value) + } + + /// Check if the content and style ranges are consistent. + /// + /// Panic if inconsistent. + #[allow(unused)] + pub(crate) fn check_consistency_between_content_and_style_ranges(&mut self) { + if !cfg!(debug_assertions) { + return; + } + + self.state + .get_mut() + .check_consistency_between_content_and_style_ranges(); + } + + #[inline] + pub fn len_unicode(&mut self) -> usize { + self.state.get_mut().len_unicode() + } + + #[cfg(test)] + pub(crate) fn inner_state_mut(&mut self) -> &mut InnerState { + self.state.get_mut() + } + + #[inline] + pub(crate) fn get_entity_index_for_text_insert( + &mut self, + index: usize, + pos_type: PosType, + ) -> Result<(usize, Option<Cursor>), LoroError> { + self.state + .get_mut() + .get_entity_index_for_text_insert(index, pos_type) + } + + #[inline] + pub(crate) fn get_event_index_by_cursor(&mut self, cursor: Cursor) -> usize { + self.state.get_mut().cursor_to_event_index_cached(cursor) + } + + pub(crate) fn get_entity_range_and_styles_at_range( + &mut self, + range: Range<usize>, + pos_type: PosType, + ) -> (Range<usize>, Option<&Styles>) { + self.state + .get_mut() + .get_entity_range_and_text_styles_at_range(range, pos_type) + } + + #[inline] + pub(crate) fn get_styles_at_entity_index(&mut self, entity_index: usize) -> StyleMeta { + self.state + .get_mut() + .get_styles_at_entity_index_for_insert(entity_index) + } + + #[inline] + pub(crate) fn get_text_entity_ranges_in_event_index_range( + &mut self, + pos: usize, + len: usize, + ) -> LoroResult<EntityRanges> { + self.state + .get_mut() + .get_text_entity_ranges(pos, len, PosType::Event) + } + + #[inline] + pub fn get_richtext_value(&mut self) -> LoroValue { + self.state.get_mut().get_richtext_value() + } + + #[inline] + pub(crate) fn get_stable_position( + &mut self, + event_index: usize, + get_by_event_index: bool, + ) -> Option<ID> { + self.state.get_mut().get_stable_position_at_event_index( + event_index, + if get_by_event_index { + PosType::Event + } else { + PosType::Unicode + }, + ) + } + + pub(crate) fn entity_index_to_event_index(&mut self, entity_index: usize) -> usize { + self.state + .get_mut() + .entity_index_to_event_index(entity_index) + } + + pub(crate) fn index_to_event_index(&mut self, index: usize, pos_type: PosType) -> usize { + self.state.get_mut().index_to_event_index(index, pos_type) + } + + pub(crate) fn event_index_to_unicode_index(&mut self, event_index: usize) -> usize { + self.state + .get_mut() + .event_index_to_unicode_index(event_index) + } + + pub(crate) fn event_index_to_index(&mut self, event_index: usize, pos_type: PosType) -> usize { + self.state + .get_mut() + .event_index_to_index(event_index, pos_type) + } +} + +#[derive(Debug, Default, Clone)] +pub(crate) struct RichtextStateLoader { + start_anchor_pos: FxHashMap<ID, usize>, + elements: SmallVec<[RichtextStateChunk; 1]>, + style_ranges: Vec<(Arc<StyleOp>, Range<usize>)>, + entity_index: usize, +} + +impl From<RichtextStateLoader> for InnerState { + fn from(value: RichtextStateLoader) -> Self { + value.into_state() + } +} + +impl RichtextStateLoader { + pub fn push(&mut self, elem: RichtextStateChunk) { + if let RichtextStateChunk::Style { style, anchor_type } = &elem { + if *anchor_type == AnchorType::Start { + self.start_anchor_pos + .insert(ID::new(style.peer, style.cnt), self.entity_index); + } else { + let start_pos = self + .start_anchor_pos + .remove(&ID::new(style.peer, style.cnt)) + .expect("Style start not found"); + + // we need to + 1 because we also need to annotate the end anchor + self.style_ranges + .push((style.clone(), start_pos..self.entity_index + 1)); + } + } + + self.entity_index += elem.rle_len(); + if matches!(&elem, RichtextStateChunk::Text(t) if t.bytes().len() > 2048) { + self.elements.extend(elem.into_pieces()); + } else { + self.elements.push(elem); + } + } + + pub fn into_state(self) -> InnerState { + let mut state = InnerState::from_chunks(self.elements.into_iter()); + for (style, range) in self.style_ranges { + state.annotate_style_range(range, style); + } + + if cfg!(debug_assertions) { + state.check(); + } + + state + } + + fn is_empty(&self) -> bool { + self.elements.is_empty() + } + + fn to_plain_string(&self) -> String { + let len = self + .elements + .iter() + .map(|elem| match elem { + RichtextStateChunk::Text(text) => text.bytes().len(), + RichtextStateChunk::Style { .. } => 0, + }) + .sum(); + let mut text = String::with_capacity(len); + for elem in &self.elements { + if let RichtextStateChunk::Text(chunk) = elem { + text.push_str(chunk.as_str()); + } + } + text + } + + fn try_apply_append_delta(&mut self, delta: &DeltaRope<RichtextStateChunk, ()>) -> bool { + // Style anchors/ranges need InnerState's range maintenance. + if !self.start_anchor_pos.is_empty() || !self.style_ranges.is_empty() { + return false; + } + + let old_len = self.entity_index; + let mut current_len = self.entity_index; + let mut entity_index = 0; + let mut appended = Vec::new(); + for span in delta.iter() { + match span { + loro_delta::DeltaItem::Retain { len, .. } => { + entity_index += len; + if entity_index > old_len { + return false; + } + } + loro_delta::DeltaItem::Replace { value, delete, .. } => { + if *delete > 0 { + return false; + } + + let insert_len = value.rle_len(); + if insert_len == 0 { + continue; + } + + if !matches!(value, RichtextStateChunk::Text(_)) { + return false; + } + + if entity_index != current_len { + return false; + } + + appended.push(value.clone()); + entity_index += insert_len; + current_len += insert_len; + } + } + } + + if appended.is_empty() { + return false; + } + + for elem in appended { + self.push(elem); + } + true + } +} + +pub(crate) use snapshot::redact_dead_style_values; + +mod snapshot { + use loro_common::{IdFull, InternalString, LoroResult, LoroValue, PeerID, ID}; + use rustc_hash::{FxHashMap, FxHashSet}; + use serde_columnar::columnar; + use std::sync::Arc; + + use crate::{ + container::richtext::{ + self, richtext_state::RichtextStateChunk, str_slice::StrSlice, StyleOp, + TextStyleInfoFlag, + }, + encoding::value_register::ValueRegister, + state::{ + decode_lamport_from_delta, decode_peer_from_table, decode_peer_table, + state_decode_error, ContainerCreationContext, ContainerState, FastStateSnapshot, + }, + utils::lazy::LazyLoad, + }; + + use super::{RichtextState, RichtextStateLoader}; + + #[columnar(vec, ser, de, iterable)] + #[derive(Debug, Clone)] + struct EncodedTextSpan { + #[columnar(strategy = "DeltaRle")] + peer_idx: usize, + #[columnar(strategy = "DeltaRle")] + counter: i32, + #[columnar(strategy = "DeltaRle")] + lamport_sub_counter: i32, + /// positive for text + /// 0 for mark start + /// -1 for mark end + #[columnar(strategy = "DeltaRle")] + len: i32, + } + + #[columnar(vec, ser, de, iterable)] + #[derive(Debug, Clone)] + struct EncodedMark { + key_idx: usize, + value: LoroValue, + info: u8, + } + + #[columnar(ser, de)] + struct EncodedText { + #[columnar(class = "vec", iter = "EncodedTextSpan")] + spans: Vec<EncodedTextSpan>, + keys: Vec<InternalString>, + marks: Vec<EncodedMark>, + } + + impl EncodedText { + // The columnar derives encode the outer struct and each mark as + // three-element postcard sequences. Only the nested value field needs + // a dedicated codec; spans still use the existing columnar strategies. + fn decode(mut bytes: &[u8]) -> LoroResult<Self> { + fn take<'a, T: serde::Deserialize<'a>>(bytes: &mut &'a [u8]) -> LoroResult<T> { + let (value, rest) = postcard::take_from_bytes(bytes).map_err(|err| { + state_decode_error(format!("Decode richtext fields failed: {err}")) + })?; + *bytes = rest; + Ok(value) + } + if take::<usize>(&mut bytes)? != 3 { + return Err(state_decode_error( + "Decode richtext fields failed: invalid field count", + )); + } + let spans: serde_columnar::ColumnarVec<'_, EncodedTextSpan, Vec<EncodedTextSpan>> = + take(&mut bytes)?; + let keys = take(&mut bytes)?; + let count = take::<usize>(&mut bytes)?; + let mut marks = Vec::new(); + for _ in 0..count { + if take::<usize>(&mut bytes)? != 3 { + return Err(state_decode_error( + "Decode richtext mark failed: invalid field count", + )); + } + let key_idx = take(&mut bytes)?; + let (value, rest) = crate::state::value_decode::decode_value(bytes)?; + bytes = rest; + let info = take(&mut bytes)?; + marks.push(EncodedMark { + key_idx, + value, + info, + }); + } + if !bytes.is_empty() { + return Err(state_decode_error( + "Decode richtext fields failed: trailing bytes", + )); + } + Ok(Self { + spans: spans.into_vec(), + keys, + marks, + }) + } + + fn encode(&self) -> Vec<u8> { + let mut bytes = Vec::new(); + postcard::to_io(&3usize, &mut bytes).unwrap(); + postcard::to_io(&serde_columnar::ColumnarVec::new(&self.spans), &mut bytes).unwrap(); + postcard::to_io(&self.keys, &mut bytes).unwrap(); + postcard::to_io(&self.marks.len(), &mut bytes).unwrap(); + for mark in &self.marks { + postcard::to_io(&3usize, &mut bytes).unwrap(); + postcard::to_io(&mark.key_idx, &mut bytes).unwrap(); + crate::state::value_decode::encode_value(&mark.value, &mut bytes).unwrap(); + postcard::to_io(&mark.info, &mut bytes).unwrap(); + } + bytes + } + } + + /// Nulls out the values of style-anchor pairs that no longer enclose any text + /// ("dead" pairs) in an encoded richtext state payload (the bytes produced by + /// `RichtextState::encode_snapshot_fast`). + /// + /// Shallow-snapshot export uses this: history before the shallow root is + /// trimmed, so a dead pair's value would otherwise ship in the export even + /// though no read API can reach it. See + /// `context/shallow-snapshot-style-redaction.md` for the invariants: + /// + /// - Anchors themselves must be preserved: op positions are entity indexes + /// that count each anchor, so removing them would corrupt replay. + /// - Pairs whose style expands on both sides are kept intact: an empty + /// both-expand pair still captures future inserts, so its value is live. + /// - When `only_pairs` is `Some`, only pairs whose `StyleStart` id is in the + /// set are touched (used to keep an exported latest state consistent with + /// the redacted shallow-root state). + /// + /// Returns `None` when nothing changed, otherwise the rewritten payload and + /// the `StyleStart` ids of the redacted pairs. + pub(crate) fn redact_dead_style_values( + payload: &[u8], + only_pairs: Option<&FxHashSet<ID>>, + ) -> LoroResult<Option<(Vec<u8>, Vec<ID>)>> { + const CTX: &str = "Redact dead style values failed"; + // Borrow the text prefix without copying it; only the columnar tail is + // ever rewritten. + let (_text, mut rest) = postcard::take_from_bytes::<&str>(payload) + .map_err(|_| state_decode_error(format!("{CTX}: invalid text value")))?; + let peers = decode_peer_table(&mut rest, CTX)?; + let prefix_len = payload.len() - rest.len(); + let encoded = EncodedText::decode(rest) + .map_err(|err| state_decode_error(format!("{CTX}: invalid spans: {err}")))?; + if encoded.marks.is_empty() { + return Ok(None); + } + + let EncodedText { + spans, + keys, + mut marks, + } = encoded; + // Open pairs keyed by the id the matching `StyleEnd` span will carry + // (`encode_snapshot_fast` writes the end span with start.counter + 1). + // The value records the pair's mark index, its start counter, and how + // many text spans had been seen when it opened: if that count is + // unchanged when the pair closes, no text lies between the anchors. + let mut open: FxHashMap<(usize, i32), (usize, i32, usize)> = FxHashMap::default(); + let mut start_count = 0usize; + let mut text_spans_seen = 0usize; + let mut redacted = Vec::new(); + for span in &spans { + match span.len { + 0 => { + let mark_idx = start_count; + start_count += 1; + if mark_idx >= marks.len() { + return Err(state_decode_error(format!("{CTX}: missing style mark"))); + } + let end_counter = span + .counter + .checked_add(1) + .ok_or_else(|| state_decode_error(format!("{CTX}: counter overflow")))?; + if open + .insert( + (span.peer_idx, end_counter), + (mark_idx, span.counter, text_spans_seen), + ) + .is_some() + { + return Err(state_decode_error(format!("{CTX}: duplicated style start"))); + } + } + -1 => { + let Some((mark_idx, start_counter, text_spans_at_open)) = + open.remove(&(span.peer_idx, span.counter)) + else { + return Err(state_decode_error(format!("{CTX}: unmatched style end"))); + }; + if text_spans_at_open != text_spans_seen { + // Text lies between the anchors; the pair is alive. + continue; + } + let mark = &mut marks[mark_idx]; + let info = TextStyleInfoFlag::from_byte(mark.info); + if info.expand_before() && info.expand_after() { + // An empty both-expand pair still styles future inserts. + continue; + } + if mark.value.is_null() { + continue; + } + let peer = decode_peer_from_table(&peers, span.peer_idx, CTX)?; + let id = ID::new(peer, start_counter); + if only_pairs.is_some_and(|allow| !allow.contains(&id)) { + continue; + } + mark.value = LoroValue::Null; + redacted.push(id); + } + len if len > 0 => text_spans_seen += 1, + _ => { + return Err(state_decode_error(format!( + "{CTX}: invalid text span length" + ))); + } + } + } + + // Pairs still open are a version that holds a mark's `StyleStart` but not its + // `StyleEnd` (loro-dev/loro#1165). They style nothing yet, but the end may + // still arrive, so leave their values alone. + if start_count != marks.len() { + return Err(state_decode_error(format!("{CTX}: unused style mark"))); + } + if redacted.is_empty() { + return Ok(None); + } + + let mut out = Vec::with_capacity(payload.len()); + out.extend_from_slice(&payload[..prefix_len]); + out.extend_from_slice(&EncodedText { spans, keys, marks }.encode()); + Ok(Some((out, redacted))) + } + + impl FastStateSnapshot for RichtextState { + /// Encodes the RichtextState into a compact binary format for fast snapshot storage and retrieval. + /// + /// The encoding format consists of: + /// 1. The full text content as a string, encoded using postcard serialization. + /// 2. A series of EncodedTextSpan structs representing text chunks and style markers: + /// - peer_idx: Index of the peer ID in a value register (delta-RLE encoded) + /// - counter: Operation counter (delta-RLE encoded) + /// - lamport_sub_counter: Lamport timestamp - counter (delta-RLE encoded) + /// - len: Length of text chunk or marker type (-1 for end, 0 for start, positive for text) + /// 3. A list of unique style keys as InternalString. + /// 4. A series of EncodedMark structs for style information: + /// - key_idx: Index of the style key in the keys list + /// - value: The style value + /// - info: Additional style information as a byte + fn encode_snapshot_fast<W: std::io::prelude::Write>(&mut self, mut w: W) { + let value = self.get_value().into_string().unwrap(); + postcard::to_io(&*value, &mut w).unwrap(); + let mut spans = Vec::new(); + let mut marks = Vec::new(); + + let mut peers: ValueRegister<PeerID> = ValueRegister::new(); + let iter: &mut dyn Iterator<Item = &RichtextStateChunk>; + let mut a; + let mut b; + match &self.state { + LazyLoad::Src(s) => { + a = Some(s.elements.iter()); + iter = &mut *a.as_mut().unwrap(); + } + LazyLoad::Dst(s) => { + b = Some(s.iter_chunk()); + iter = &mut *b.as_mut().unwrap(); + } + } + + let mut keys: ValueRegister<InternalString> = ValueRegister::new(); + + for chunk in iter { + match chunk { + RichtextStateChunk::Text(t) => { + let id = t.id_full(); + assert!(t.unicode_len() > 0); + spans.push(EncodedTextSpan { + peer_idx: peers.register(&id.peer), + counter: id.counter, + lamport_sub_counter: id.lamport as i32 - id.counter, + len: t.unicode_len(), + }) + } + RichtextStateChunk::Style { style, anchor_type } => match anchor_type { + richtext::AnchorType::Start => { + let id = style.id_full(); + spans.push(EncodedTextSpan { + peer_idx: peers.register(&id.peer), + counter: id.counter, + lamport_sub_counter: id.lamport as i32 - id.counter, + len: 0, + }); + marks.push(EncodedMark { + key_idx: keys.register(&style.key), + value: style.value.clone(), + info: style.info.to_byte(), + }) + } + richtext::AnchorType::End => { + let id = style.id_full(); + spans.push(EncodedTextSpan { + peer_idx: peers.register(&id.peer), + counter: id.counter + 1, + lamport_sub_counter: id.lamport as i32 - id.counter, + len: -1, + }) + } + }, + } + } + + let peers = peers.unwrap_vec(); + leb128::write::unsigned(&mut w, peers.len() as u64).unwrap(); + for peer in peers { + w.write_all(&peer.to_le_bytes()).unwrap(); + } + + let bytes = EncodedText { + spans, + keys: keys.unwrap_vec(), + marks, + } + .encode(); + w.write_all(&bytes).unwrap(); + } + + fn decode_value(bytes: &[u8]) -> loro_common::LoroResult<(loro_common::LoroValue, &[u8])> { + let (value, bytes) = postcard::take_from_bytes(bytes).map_err(|_| { + loro_common::LoroError::DecodeError( + "Decode list value failed".to_string().into_boxed_str(), + ) + })?; + let s: String = value; + Ok((LoroValue::String(s.into()), bytes)) + } + + fn decode_snapshot_fast( + idx: crate::container::idx::ContainerIdx, + (string, mut bytes): (loro_common::LoroValue, &[u8]), + ctx: ContainerCreationContext, + ) -> loro_common::LoroResult<Self> + where + Self: Sized, + { + let mut text = RichtextState::new(idx, ctx.configure.text_style_config.clone()); + let mut loader = RichtextStateLoader::default(); + let peers = decode_peer_table(&mut bytes, "Decode richtext state failed")?; + + let string = string.into_string().map_err(|_| { + state_decode_error("Decode richtext state failed: value is not a string") + })?; + let mut s = StrSlice::new_from_str(&string); + let iters = EncodedText::decode(bytes).map_err(|err| { + state_decode_error(format!( + "Decode richtext state failed: invalid spans: {err}" + )) + })?; + let keys = iters.keys; + let span_iter = iters.spans.into_iter(); + let mut mark_iter = iters.marks.into_iter(); + let mut id_to_style = FxHashMap::default(); + for span in span_iter { + let EncodedTextSpan { + peer_idx, + counter, + lamport_sub_counter, + len, + } = span; + let peer = + decode_peer_from_table(&peers, peer_idx, "Decode richtext state failed")?; + let lamport = decode_lamport_from_delta( + counter, + lamport_sub_counter, + "Decode richtext state failed", + )?; + let id_full = IdFull::new(peer, counter, lamport); + let chunk = match len { + 0 => { + // Style Start + let EncodedMark { + key_idx, + value, + info, + } = mark_iter.next().ok_or_else(|| { + state_decode_error("Decode richtext state failed: missing style mark") + })?; + let key = keys.get(key_idx).ok_or_else(|| { + state_decode_error( + "Decode richtext state failed: style key index out of range", + ) + })?; + let style_op = Arc::new(StyleOp { + lamport, + peer: id_full.peer, + cnt: id_full.counter, + key: key.clone(), + value, + info: TextStyleInfoFlag::from_byte(info), + }); + id_to_style.insert(id_full.id(), style_op.clone()); + RichtextStateChunk::new_style(style_op, richtext::AnchorType::Start) + } + -1 => { + // Style End + let style = id_to_style.remove(&id_full.id().inc(-1)).ok_or_else(|| { + state_decode_error("Decode richtext state failed: unmatched style end") + })?; + RichtextStateChunk::new_style(style, richtext::AnchorType::End) + } + len => { + if len < -1 { + return Err(state_decode_error( + "Decode richtext state failed: invalid text span length", + )); + } + + // Text + if s.as_str().chars().take(len as usize).count() < len as usize { + return Err(state_decode_error( + "Decode richtext state failed: text span exceeds value length", + )); + } + + let (new, rest) = s.split_at_unicode_pos(len as usize); + s = rest; + RichtextStateChunk::new_text(new.bytes().clone(), id_full) + } + }; + + loader.push(chunk); + } + if !s.as_str().is_empty() { + return Err(state_decode_error( + "Decode richtext state failed: text value not fully covered", + )); + } + if mark_iter.next().is_some() { + return Err(state_decode_error( + "Decode richtext state failed: unused style mark", + )); + } + // A `StyleStart` without its `StyleEnd` is valid: a version can include the + // start op but not the end op (their counters are consecutive), and + // `checkout` keeps the lone start anchor the same way. The style applies + // to nothing until the end anchor arrives (loro-dev/loro#1165). + text.state = LazyLoad::Src(loader); + // NOTE: We need to ensure the invariance that the version id is always increased when the richtext state is changed + // This is used to avoid the version_id to be the same as the previous zero version + text.version_id = 1; + Ok(text) + } + } + + #[cfg(test)] + mod tests { + use loro_common::{ContainerType, LoroValue}; + + use crate::container::idx::ContainerIdx; + + use super::*; + + #[test] + fn iterative_mark_codec_matches_the_original_columnar_bytes() { + let encoded = EncodedText { + spans: vec![span(0, 0), span(2, 5), span(1, -1)], + keys: vec!["hl".into(), "x".into()], + marks: vec![ + mark(LoroValue::Null, richtext::ExpandType::After), + mark( + LoroValue::List( + vec![ + LoroValue::Binary(vec![0, 255].into()), + LoroValue::Map(vec![("a".into(), 42.into())].into()), + ] + .into(), + ), + richtext::ExpandType::Before, + ), + ], + }; + let old = serde_columnar::to_vec(&encoded).unwrap(); + assert_eq!(encoded.encode(), old); + let decoded = EncodedText::decode(&old).unwrap(); + assert_eq!(decoded.encode(), old); + assert_eq!(decoded.marks[1].value, encoded.marks[1].value); + for len in 0..old.len() { + assert!(EncodedText::decode(&old[..len]).is_err()); + } + } + + #[test] + fn richtext_fast_snapshot_rejects_corrupt_state_metadata() { + let idx = ContainerIdx::from_index_and_type(0, ContainerType::Text); + let configure = Default::default(); + let ctx = ContainerCreationContext { + configure: &configure, + peer: 0, + }; + + assert!(RichtextState::decode_snapshot_fast( + idx, + (LoroValue::String("a".into()), &[1]), + ctx, + ) + .is_err()); + + let mut text = RichtextState::new(idx, configure.text_style_config.clone()); + let mut bytes = Vec::new(); + text.encode_snapshot_fast(&mut bytes); + let (_, state_bytes) = RichtextState::decode_value(&bytes).unwrap(); + assert!(RichtextState::decode_snapshot_fast( + idx, + (LoroValue::String("a".into()), state_bytes), + ctx, + ) + .is_err()); + } + + const PEER: PeerID = 7; + + fn payload(text: &str, spans: Vec<EncodedTextSpan>, marks: Vec<EncodedMark>) -> Vec<u8> { + let mut out = Vec::new(); + postcard::to_io(text, &mut out).unwrap(); + leb128::write::unsigned(&mut out, 1).unwrap(); + out.extend_from_slice(&PEER.to_le_bytes()); + out.extend_from_slice( + &serde_columnar::to_vec(&EncodedText { + spans, + keys: vec!["hl".into(), "x".into()], + marks, + }) + .unwrap(), + ); + out + } + + fn span(counter: i32, len: i32) -> EncodedTextSpan { + EncodedTextSpan { + peer_idx: 0, + counter, + lamport_sub_counter: 0, + len, + } + } + + fn mark(value: LoroValue, expand: richtext::ExpandType) -> EncodedMark { + EncodedMark { + key_idx: 0, + value, + info: TextStyleInfoFlag::new(expand).to_byte(), + } + } + + fn decoded_mark_values(payload: &[u8]) -> Vec<LoroValue> { + let (_, mut rest) = postcard::take_from_bytes::<&str>(payload).unwrap(); + decode_peer_table(&mut rest, "test").unwrap(); + serde_columnar::from_bytes::<EncodedText>(rest) + .unwrap() + .marks + .into_iter() + .map(|m| m.value) + .collect() + } + + /// "a" [S] [E] "d" — a dead pair between two text chunks. + fn dead_pair_payload(expand: richtext::ExpandType) -> Vec<u8> { + payload( + "ad", + vec![span(0, 1), span(10, 0), span(11, -1), span(1, 1)], + vec![mark(LoroValue::String("SECRET".into()), expand)], + ) + } + + #[test] + fn redacts_dead_pair_and_is_idempotent() { + let p = dead_pair_payload(richtext::ExpandType::After); + let (new_payload, ids) = redact_dead_style_values(&p, None).unwrap().unwrap(); + assert_eq!(ids, vec![ID::new(PEER, 10)]); + assert_eq!(decoded_mark_values(&new_payload), vec![LoroValue::Null]); + + // The redacted payload still decodes into a valid state. + let idx = ContainerIdx::from_index_and_type(0, ContainerType::Text); + let configure = crate::configure::Configure::default(); + let ctx = ContainerCreationContext { + configure: &configure, + peer: 0, + }; + let (value, rest) = RichtextState::decode_value(&new_payload).unwrap(); + let mut state = RichtextState::decode_snapshot_fast(idx, (value, rest), ctx).unwrap(); + assert_eq!(state.get_value().into_string().unwrap().to_string(), "ad"); + + // Idempotent: a second pass reports nothing to do. + assert!(redact_dead_style_values(&new_payload, None) + .unwrap() + .is_none()); + } + + #[test] + fn keeps_alive_and_both_expand_pairs() { + // Text between the anchors: alive, untouched. + let alive = payload( + "a", + vec![span(10, 0), span(0, 1), span(11, -1)], + vec![mark( + LoroValue::String("SECRET".into()), + richtext::ExpandType::After, + )], + ); + assert!(redact_dead_style_values(&alive, None).unwrap().is_none()); + + // Dead but both-expand: still styles future inserts, untouched. + let both = dead_pair_payload(richtext::ExpandType::Both); + assert!(redact_dead_style_values(&both, None).unwrap().is_none()); + } + + #[test] + fn respects_only_pairs_whitelist() { + let p = dead_pair_payload(richtext::ExpandType::None); + let mut allow = FxHashSet::default(); + allow.insert(ID::new(PEER, 999)); + assert!(redact_dead_style_values(&p, Some(&allow)) + .unwrap() + .is_none()); + + allow.insert(ID::new(PEER, 10)); + let (_, ids) = redact_dead_style_values(&p, Some(&allow)).unwrap().unwrap(); + assert_eq!(ids, vec![ID::new(PEER, 10)]); + } + + #[test] + fn handles_interleaved_pairs() { + // "ab" [S1 "a"..] [S2] [E1] [E2]: pair 1 encloses text via its start + // before "b"? Layout: [S1] "b" [S2] [E1] [E2] over text "ab" with a + // leading "a": S1 opens before "b" so it is alive; S2 opens after all + // text and closes empty, so it is dead. + let p = payload( + "ab", + vec![ + span(0, 1), // "a" + span(10, 0), // S1 + span(1, 1), // "b" + span(20, 0), // S2 + span(11, -1), // E1 + span(21, -1), // E2 + ], + vec![ + mark( + LoroValue::String("ALIVE".into()), + richtext::ExpandType::After, + ), + mark( + LoroValue::String("DEAD".into()), + richtext::ExpandType::After, + ), + ], + ); + let (new_payload, ids) = redact_dead_style_values(&p, None).unwrap().unwrap(); + assert_eq!(ids, vec![ID::new(PEER, 20)]); + assert_eq!( + decoded_mark_values(&new_payload), + vec![LoroValue::String("ALIVE".into()), LoroValue::Null] + ); + } + + #[test] + fn rejects_malformed_span_structures() { + // Start without a matching end is valid (loro-dev/loro#1165): a version can + // hold a mark's StyleStart but not its StyleEnd. It is left untouched. + let unclosed = payload( + "", + vec![span(10, 0)], + vec![mark(LoroValue::Bool(true), richtext::ExpandType::After)], + ); + assert!(redact_dead_style_values(&unclosed, None).unwrap().is_none()); + + // End without a start. (An empty mark list short-circuits before + // validation, so give it one mark to reach the scan.) + let unmatched = payload( + "", + vec![span(11, -1)], + vec![mark(LoroValue::Bool(true), richtext::ExpandType::After)], + ); + assert!(redact_dead_style_values(&unmatched, None).is_err()); + + // More starts than marks. + let missing_mark = payload( + "", + vec![span(10, 0), span(11, -1), span(20, 0), span(21, -1)], + vec![mark(LoroValue::Bool(true), richtext::ExpandType::After)], + ); + assert!(redact_dead_style_values(&missing_mark, None).is_err()); + } + + #[test] + fn skips_payload_without_marks() { + let p = payload("ab", vec![span(0, 2)], vec![]); + assert!(redact_dead_style_values(&p, None).unwrap().is_none()); + } + } +} diff --git a/vendor/loro-internal/src/state/tree_state.rs b/vendor/loro-internal/src/state/tree_state.rs new file mode 100644 index 0000000..0b9d04c --- /dev/null +++ b/vendor/loro-internal/src/state/tree_state.rs @@ -0,0 +1,2274 @@ +use either::Either; +use enum_as_inner::EnumAsInner; +use fractional_index::FractionalIndex; +use itertools::Itertools; +use loro_common::{ + ContainerID, IdFull, IdLp, LoroError, LoroResult, LoroTreeError, LoroValue, PeerID, TreeID, + DELETED_TREE_ROOT, ID, +}; +use rand::SeedableRng; +use rustc_hash::{FxHashMap, FxHashSet}; +use serde::Serialize; +use std::collections::VecDeque; +use std::fmt::Debug; +use std::ops::{Deref, DerefMut}; +use std::sync::Weak; + +use super::{ApplyLocalOpReturn, ContainerState, DiffApplyContext}; +use crate::configure::Configure; +use crate::container::idx::ContainerIdx; +use crate::delta::{TreeDiff, TreeDiffItem, TreeExternalDiff}; +use crate::diff_calc::DiffMode; +use crate::event::InternalDiff; +use crate::op::Op; +use crate::{ + container::tree::tree_op::TreeOp, + delta::TreeInternalDiff, + event::{Diff, Index}, + op::RawOp, +}; +use crate::{DocState, LoroDocInner}; + +#[derive(Clone, Debug, EnumAsInner)] +pub enum TreeFractionalIndexConfigInner { + GenerateFractionalIndex { + jitter: u8, + rng: Box<rand::rngs::StdRng>, + }, + MoveDisabled, +} + +/// The state of movable tree. +/// +/// using flat representation +#[derive(Debug, Clone)] +pub struct TreeState { + idx: ContainerIdx, + trees: FxHashMap<TreeID, TreeStateNode>, + children: TreeChildrenCache, + fractional_index_config: TreeFractionalIndexConfigInner, + peer_id: PeerID, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct TreeStateNode { + pub parent: TreeParentId, + pub position: Option<FractionalIndex>, + pub last_move_op: IdFull, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) struct NodePosition { + pub(crate) position: FractionalIndex, + // different nodes created by a peer may have the same position + // when we merge updates that cause cycles. + // for example [::fuzz::test::test_tree::same_peer_have_same_position()] + pub(crate) idlp: IdLp, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, EnumAsInner, Serialize)] +pub enum TreeParentId { + Node(TreeID), + Root, + Deleted, + // We use `Unexist` as the old parent of a new node created + // so we can infer the retreat internal diff is `Uncreate` + Unexist, +} + +impl From<Option<TreeID>> for TreeParentId { + fn from(id: Option<TreeID>) -> Self { + match id { + Some(id) => { + if TreeID::is_deleted_root(&id) { + TreeParentId::Deleted + } else { + TreeParentId::Node(id) + } + } + None => TreeParentId::Root, + } + } +} + +impl From<TreeID> for TreeParentId { + fn from(id: TreeID) -> Self { + if TreeID::is_deleted_root(&id) { + TreeParentId::Deleted + } else { + TreeParentId::Node(id) + } + } +} + +impl From<&TreeID> for TreeParentId { + fn from(id: &TreeID) -> Self { + if TreeID::is_deleted_root(id) { + TreeParentId::Deleted + } else { + TreeParentId::Node(*id) + } + } +} + +impl TreeParentId { + pub fn tree_id(&self) -> Option<TreeID> { + match self { + TreeParentId::Node(id) => Some(*id), + TreeParentId::Root => None, + TreeParentId::Deleted => Some(DELETED_TREE_ROOT), + TreeParentId::Unexist => unreachable!(), + } + } +} + +#[derive(Debug, Clone)] +enum NodeChildren { + Vec(Vec<(NodePosition, TreeID)>), + BTree(btree::ChildTree), +} + +impl Default for NodeChildren { + fn default() -> Self { + NodeChildren::Vec(vec![]) + } +} + +impl NodeChildren { + const MAX_SIZE_FOR_ARRAY: usize = 16; + fn get_index_by_child_id(&self, target: &TreeID) -> Option<usize> { + match self { + NodeChildren::Vec(v) => v.iter().position(|(_, id)| id == target), + NodeChildren::BTree(btree) => btree.id_to_index(target), + } + } + + fn get_last_insert_index_by_position( + &self, + node_position: &NodePosition, + ) -> Result<usize, usize> { + match self { + NodeChildren::Vec(v) => v.binary_search_by_key(&node_position, |x| &x.0), + NodeChildren::BTree(btree) => btree.get_index_by_node_position(node_position), + } + } + + fn get_node_position_at(&self, pos: usize) -> Option<&NodePosition> { + match self { + NodeChildren::Vec(v) => v.get(pos).map(|x| &x.0), + NodeChildren::BTree(btree) => btree.get_elem_at(pos).map(|x| x.pos.as_ref()), + } + } + + fn get_elem_at(&self, pos: usize) -> Option<(&NodePosition, &TreeID)> { + match self { + NodeChildren::Vec(v) => v.get(pos).map(|x| (&x.0, &x.1)), + NodeChildren::BTree(btree) => btree.get_elem_at(pos).map(|x| (x.pos.as_ref(), &x.id)), + } + } + + fn generate_fi_at(&self, pos: usize, target: &TreeID) -> FractionalIndexGenResult { + let mut reset_ids = vec![]; + let mut left = None; + let mut next_right = None; + { + let mut right = None; + let children_num = self.len(); + if children_num == 0 { + return FractionalIndexGenResult::Ok(FractionalIndex::default()); + } + + if pos > 0 { + left = self.get_node_position_at(pos - 1); + } + if pos < children_num { + right = self.get_elem_at(pos); + } + + let left_fi = left.map(|x| &x.position); + // if left and right have the same fractional indexes, we need to scan further to + // find all the ids that need to be reset + if let Some(left_fi) = left_fi { + if Some(left_fi) == right.map(|x| &x.0.position) { + // TODO: the min length between left and right + reset_ids.push(*right.unwrap().1); + for i in (pos + 1)..children_num { + let this_position = + self.get_node_position_at(i).map(|x| &x.position).unwrap(); + if this_position == left_fi { + reset_ids.push(*self.get_elem_at(i).unwrap().1); + } else { + next_right = Some(this_position.clone()); + break; + } + } + } + } + + if reset_ids.is_empty() { + return FractionalIndexGenResult::Ok( + FractionalIndex::new(left.map(|x| &x.position), right.map(|x| &x.0.position)) + .unwrap(), + ); + } + } + let positions = FractionalIndex::generate_n_evenly( + left.map(|x| &x.position), + next_right.as_ref(), + reset_ids.len() + 1, + ) + .unwrap(); + FractionalIndexGenResult::Rearrange( + Some(*target) + .into_iter() + .chain(reset_ids) + .zip(positions) + .collect(), + ) + } + + fn get_id_at(&self, pos: usize) -> Option<TreeID> { + match self { + NodeChildren::Vec(v) => v.get(pos).map(|x| x.1), + NodeChildren::BTree(btree) => btree.get_elem_at(pos).map(|x| x.id), + } + } + + fn delete_child(&mut self, target: &TreeID) { + match self { + NodeChildren::Vec(v) => { + v.retain(|(_, id)| id != target); + } + NodeChildren::BTree(v) => { + v.delete_child(target); + } + } + } + + fn upgrade(&mut self) { + match self { + NodeChildren::Vec(v) => { + let mut btree = btree::ChildTree::new(); + for (pos, id) in v.drain(..) { + btree.insert_child(pos, id); + } + + *self = NodeChildren::BTree(btree); + } + NodeChildren::BTree(_) => unreachable!(), + } + } + + fn insert_child(&mut self, pos: NodePosition, id: TreeID) { + match self { + NodeChildren::Vec(v) => { + if v.len() >= Self::MAX_SIZE_FOR_ARRAY { + self.upgrade(); + return self.insert_child(pos, id); + } + + let r = v.binary_search_by(|(target, _)| target.cmp(&pos)); + match r { + Ok(_) => unreachable!(), + Err(i) => { + v.insert(i, (pos, id)); + } + } + } + NodeChildren::BTree(v) => { + v.insert_child(pos, id); + } + } + } + + fn push_child_in_order(&mut self, pos: NodePosition, id: TreeID) { + match self { + NodeChildren::Vec(v) => { + if v.len() >= Self::MAX_SIZE_FOR_ARRAY { + self.upgrade(); + return self.push_child_in_order(pos, id); + } + + if let Some(last) = v.last() { + assert!(last.0 < pos); + } + v.push((pos, id)); + } + NodeChildren::BTree(v) => { + v.push_child_in_order(pos, id); + } + } + } + + fn len(&self) -> usize { + match self { + NodeChildren::Vec(v) => v.len(), + NodeChildren::BTree(v) => v.len(), + } + } + + fn has_child(&self, node_position: &NodePosition) -> bool { + match self { + NodeChildren::Vec(v) => v + .binary_search_by(|(target, _)| target.cmp(node_position)) + .is_ok(), + NodeChildren::BTree(v) => v.has_child(node_position), + } + } + + fn iter(&self) -> impl Iterator<Item = (&NodePosition, &TreeID)> { + match self { + NodeChildren::Vec(v) => Either::Left(v.iter().map(|x| (&x.0, &x.1))), + NodeChildren::BTree(t) => Either::Right(t.iter()), + } + } +} + +#[derive(Clone, Default)] +struct TreeChildrenCache(FxHashMap<TreeParentId, NodeChildren>); + +mod btree { + use std::{cmp::Ordering, ops::Range, sync::Arc}; + + use generic_btree::{ + rle::{CanRemove, HasLength, Mergeable, Sliceable, TryInsert}, + BTree, BTreeTrait, Cursor, FindResult, LeafIndex, LengthFinder, Query, UseLengthFinder, + }; + use loro_common::TreeID; + use rustc_hash::FxHashMap; + + use super::NodePosition; + + struct ChildTreeTrait; + #[derive(Debug, Clone)] + pub(super) struct ChildTree { + tree: BTree<ChildTreeTrait>, + id_to_leaf_index: FxHashMap<TreeID, LeafIndex>, + } + + impl ChildTree { + pub(super) fn new() -> Self { + Self { + tree: BTree::new(), + id_to_leaf_index: FxHashMap::default(), + } + } + + pub(super) fn insert_child(&mut self, pos: NodePosition, id: TreeID) { + let (c, _) = self.tree.insert::<KeyQuery>( + &pos, + Elem { + pos: Arc::new(pos.clone()), + id, + }, + ); + + self.id_to_leaf_index.insert(id, c.leaf); + } + + pub(super) fn push_child_in_order(&mut self, pos: NodePosition, id: TreeID) { + let c = self.tree.push(Elem { + pos: Arc::new(pos.clone()), + id, + }); + self.id_to_leaf_index.insert(id, c.leaf); + } + + pub(super) fn delete_child(&mut self, id: &TreeID) { + if let Some(leaf) = self.id_to_leaf_index.remove(id) { + self.tree.remove_leaf(Cursor { leaf, offset: 0 }); + } + } + + pub(super) fn has_child(&self, pos: &NodePosition) -> bool { + match self.tree.query::<KeyQuery>(pos) { + Some(r) => r.found, + None => false, + } + } + + pub(super) fn iter(&self) -> impl Iterator<Item = (&NodePosition, &TreeID)> { + self.tree.iter().map(|x| (&*x.pos, &x.id)) + } + + pub(super) fn len(&self) -> usize { + self.tree.root_cache().len + } + + pub(super) fn get_elem_at(&self, pos: usize) -> Option<&Elem> { + let result = self.tree.query::<LengthFinder>(&pos)?; + if !result.found { + return None; + } + self.tree.get_elem(result.leaf()) + } + + pub(super) fn id_to_index(&self, id: &TreeID) -> Option<usize> { + let leaf_index = self.id_to_leaf_index.get(id)?; + let mut ans = 0; + self.tree.visit_previous_caches( + Cursor { + leaf: *leaf_index, + offset: 0, + }, + |prev| match prev { + generic_btree::PreviousCache::NodeCache(c) => { + ans += c.len; + } + generic_btree::PreviousCache::PrevSiblingElem(_) => { + ans += 1; + } + generic_btree::PreviousCache::ThisElemAndOffset { .. } => {} + }, + ); + + Some(ans) + } + + pub(super) fn get_index_by_node_position( + &self, + node_position: &NodePosition, + ) -> Result<usize, usize> { + let Some(res) = self.tree.query::<KeyQuery>(node_position) else { + return Ok(0); + }; + let mut ans = 0; + self.tree + .visit_previous_caches(res.cursor, |prev| match prev { + generic_btree::PreviousCache::NodeCache(c) => { + ans += c.len; + } + generic_btree::PreviousCache::PrevSiblingElem(_) => { + ans += 1; + } + generic_btree::PreviousCache::ThisElemAndOffset { elem: _, offset } => { + ans += offset; + } + }); + if res.found { + Ok(ans) + } else { + Err(ans) + } + } + } + + #[derive(Clone, Debug)] + pub(super) struct Elem { + pub(super) pos: Arc<NodePosition>, + pub(super) id: TreeID, + } + + impl Mergeable for Elem { + fn can_merge(&self, _rhs: &Self) -> bool { + false + } + + fn merge_right(&mut self, _rhs: &Self) { + unreachable!() + } + + fn merge_left(&mut self, _left: &Self) { + unreachable!() + } + } + + impl HasLength for Elem { + fn rle_len(&self) -> usize { + 1 + } + } + + impl Sliceable for Elem { + fn _slice(&self, range: std::ops::Range<usize>) -> Self { + assert!(range.len() == 1); + self.clone() + } + } + + impl CanRemove for Elem { + fn can_remove(&self) -> bool { + false + } + } + + impl TryInsert for Elem { + fn try_insert(&mut self, _pos: usize, elem: Self) -> Result<(), Self> + where + Self: Sized, + { + Err(elem) + } + } + + #[derive(Clone, Debug, Default, PartialEq, Eq)] + struct Cache { + range: Option<Range<Arc<NodePosition>>>, + len: usize, + } + + impl BTreeTrait for ChildTreeTrait { + type Elem = Elem; + type Cache = Cache; + type CacheDiff = (); + const USE_DIFF: bool = false; + + fn calc_cache_internal( + cache: &mut Self::Cache, + caches: &[generic_btree::Child<Self>], + ) -> Self::CacheDiff { + if caches.is_empty() { + *cache = Default::default(); + return; + } + + *cache = Cache { + range: Some( + caches[0].cache.range.as_ref().unwrap().start.clone() + ..caches + .last() + .unwrap() + .cache + .range + .as_ref() + .unwrap() + .end + .clone(), + ), + len: caches.iter().map(|x| x.cache.len).sum(), + }; + } + + fn apply_cache_diff(_cache: &mut Self::Cache, _diff: &Self::CacheDiff) { + unreachable!() + } + + fn merge_cache_diff(_diff1: &mut Self::CacheDiff, _diff2: &Self::CacheDiff) {} + + fn get_elem_cache(elem: &Self::Elem) -> Self::Cache { + Cache { + range: Some(elem.pos.clone()..elem.pos.clone()), + len: 1, + } + } + + fn new_cache_to_diff(_cache: &Self::Cache) -> Self::CacheDiff {} + + fn sub_cache(_cache_lhs: &Self::Cache, _cache_rhs: &Self::Cache) -> Self::CacheDiff {} + } + + struct KeyQuery; + + impl Query<ChildTreeTrait> for KeyQuery { + type QueryArg = NodePosition; + + #[inline(always)] + fn init(_target: &Self::QueryArg) -> Self { + KeyQuery + } + + #[inline] + fn find_node( + &mut self, + target: &Self::QueryArg, + caches: &[generic_btree::Child<ChildTreeTrait>], + ) -> FindResult { + let result = caches.binary_search_by(|x| { + let range = x.cache.range.as_ref().unwrap(); + if target < &range.start { + core::cmp::Ordering::Greater + } else if target > &range.end { + core::cmp::Ordering::Less + } else { + core::cmp::Ordering::Equal + } + }); + + match result { + Ok(i) => FindResult::new_found(i, 0), + Err(i) => FindResult::new_missing( + i.min(caches.len() - 1), + if i == caches.len() { 1 } else { 0 }, + ), + } + } + + #[inline(always)] + fn confirm_elem( + &mut self, + q: &Self::QueryArg, + elem: &<ChildTreeTrait as BTreeTrait>::Elem, + ) -> (usize, bool) { + match q.cmp(&elem.pos) { + Ordering::Less => (0, false), + Ordering::Equal => (0, true), + Ordering::Greater => (1, false), + } + } + } + + impl UseLengthFinder<ChildTreeTrait> for ChildTreeTrait { + fn get_len(cache: &<ChildTreeTrait as BTreeTrait>::Cache) -> usize { + cache.len + } + } +} + +impl Debug for TreeChildrenCache { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + writeln!(f, "TreeChildrenCache {{")?; + for (parent, children) in self.0.iter() { + writeln!(f, " {:?}:{{", parent)?; + for (position, id) in children.iter() { + writeln!(f, " {:?} -> {:?}", position, id)?; + } + writeln!(f, " }}")?; + } + writeln!(f, "}}") + } +} + +impl Deref for TreeChildrenCache { + type Target = FxHashMap<TreeParentId, NodeChildren>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for TreeChildrenCache { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl NodePosition { + fn new(position: FractionalIndex, idlp: IdLp) -> Self { + Self { position, idlp } + } +} + +pub(crate) enum FiIfNotConfigured { + UseJitterZero, + #[allow(unused)] + Throw, + #[allow(unused)] + Zero, +} + +impl TreeState { + pub fn new(idx: ContainerIdx, peer_id: PeerID) -> Self { + Self { + idx, + trees: FxHashMap::default(), + children: Default::default(), + fractional_index_config: TreeFractionalIndexConfigInner::GenerateFractionalIndex { + jitter: 0, + rng: Box::new(rand::rngs::StdRng::seed_from_u64(0)), + }, + peer_id, + } + } + + pub fn mov( + &mut self, + target: TreeID, + parent: TreeParentId, + id: IdFull, + position: Option<FractionalIndex>, + with_check: bool, + ) -> Result<(), LoroError> { + if with_check { + if let TreeParentId::Node(parent) = parent { + if !self.trees.contains_key(&parent) { + return Err(LoroTreeError::TreeNodeParentNotFound(parent).into()); + } + } + if self.is_ancestor_of(&target, &parent) { + return Err(LoroTreeError::CyclicMoveError.into()); + } + } + if let Some(old_parent) = self.trees.get(&target).map(|x| x.parent) { + // remove old position + self.try_delete_position_cache(&old_parent, &target); + } + + let entry = self.children.entry(parent).or_default(); + let node_position = NodePosition::new(position.clone().unwrap_or_default(), id.idlp()); + debug_assert!(!entry.has_child(&node_position)); + entry.insert_child(node_position, target); + + self.trees.insert( + target, + TreeStateNode { + parent, + position, + last_move_op: id, + }, + ); + + Ok(()) + } + + fn _init_push_tree_node_in_order( + &mut self, + target: TreeID, + parent: TreeParentId, + last_move_op: IdFull, + position: Option<FractionalIndex>, + ) -> Result<(), LoroError> { + debug_assert!(!self.trees.contains_key(&target)); + let entry = self.children.entry(parent).or_default(); + let node_position = + NodePosition::new(position.clone().unwrap_or_default(), last_move_op.idlp()); + debug_assert!(!entry.has_child(&node_position)); + entry.push_child_in_order(node_position, target); + self.trees.insert( + target, + TreeStateNode { + parent, + position, + last_move_op, + }, + ); + + Ok(()) + } + + #[inline(never)] + fn is_ancestor_of(&self, maybe_ancestor: &TreeID, node_id: &TreeParentId) -> bool { + if !self.trees.contains_key(maybe_ancestor) { + return false; + } + let mut node = *node_id; + let mut remaining = self.trees.len(); + loop { + match node { + TreeParentId::Node(id) => { + assert!(remaining > 0, "tree parent cycle"); + remaining -= 1; + if &id == maybe_ancestor { + return true; + } + let parent = self.trees.get(&id).unwrap().parent; + assert_ne!(parent, node, "is_ancestor_of loop"); + node = parent; + } + TreeParentId::Deleted | TreeParentId::Root => return false, + TreeParentId::Unexist => unreachable!(), + } + } + } + + /// Get the parent of the node, if the node does not exist, return None + pub fn parent(&self, target: &TreeID) -> Option<TreeParentId> { + self.trees.get(target).map(|x| x.parent) + } + + /// If the node is unexist, return None. If the node is deleted, return true. + pub(crate) fn is_node_deleted(&self, target: &TreeID) -> Option<bool> { + let mut node = *target; + let mut remaining = self.trees.len(); + loop { + let parent = self.trees.get(&node)?.parent; + assert!(remaining > 0, "tree parent cycle"); + remaining -= 1; + match parent { + TreeParentId::Deleted => return Some(true), + TreeParentId::Root => return Some(false), + TreeParentId::Node(parent) => node = parent, + TreeParentId::Unexist => unreachable!(), + } + } + } + + pub(crate) fn is_node_unexist(&self, target: &TreeID) -> bool { + !self.trees.contains_key(target) + } + + // Get all flat tree nodes, excluding deleted nodes. + pub(crate) fn tree_nodes(&self) -> Vec<TreeNode> { + self.get_all_tree_nodes_under(TreeParentId::Root) + } + + // Get all flat deleted nodes: directly deleted ones (parent `Deleted`) and their descendants. + pub(crate) fn deleted_tree_nodes(&self) -> Vec<TreeNode> { + self.get_all_tree_nodes_under(TreeParentId::Deleted) + } + + // Get all flat tree nodes under the parent + pub(crate) fn get_all_tree_nodes_under(&self, root: TreeParentId) -> Vec<TreeNode> { + let mut ans = vec![]; + let children = self.children.get(&root); + let mut q = children + .map(|x| VecDeque::from_iter(x.iter().enumerate().zip(std::iter::repeat(root)))) + .unwrap_or_default(); + + while let Some(((index, (position, &target)), parent)) = q.pop_front() { + ans.push(TreeNode { + id: target, + parent, + fractional_index: position.position.clone(), + index, + last_move_op: self.trees.get(&target).map(|x| x.last_move_op).unwrap(), + }); + if let Some(children) = self.children.get(&TreeParentId::Node(target)) { + q.extend( + children + .iter() + .enumerate() + .map(|(index, (position, this_target))| { + ((index, (position, this_target)), TreeParentId::Node(target)) + }), + ); + } + } + ans + } + + pub(crate) fn get_all_hierarchy_nodes_under( + &self, + root: TreeParentId, + ) -> Vec<TreeNodeWithChildren> { + let mut ans = vec![]; + let mut pending = vec![(root, &mut ans)]; + while let Some((parent, output)) = pending.pop() { + if let Some(children) = self.children.get(&parent) { + output.extend(children.iter().enumerate().map(|(index, (position, &id))| { + TreeNodeWithChildren { + id, + parent, + fractional_index: position.position.clone(), + index, + children: Vec::new(), + } + })); + for node in output.iter_mut().rev() { + pending.push((TreeParentId::Node(node.id), &mut node.children)); + } + } + } + ans + } + + fn bfs_all_alive_nodes_for_fast_snapshot(&self) -> Vec<TreeNode> { + let mut ans = vec![]; + self._bfs_all_nodes(TreeParentId::Root, &mut ans); + ans + } + + fn bfs_all_deleted_nodes_for_fast_snapshot(&self) -> Vec<TreeNode> { + let mut ans = vec![]; + self._bfs_all_nodes(TreeParentId::Deleted, &mut ans); + ans + } + + fn _bfs_all_nodes(&self, root: TreeParentId, ans: &mut Vec<TreeNode>) { + let mut pending = vec![root]; + while let Some(parent) = pending.pop() { + let Some(children) = self.children.get(&parent) else { + continue; + }; + for (index, (position, target)) in children.iter().enumerate() { + ans.push(TreeNode { + id: *target, + parent, + fractional_index: position.position.clone(), + index, + last_move_op: self.trees.get(target).map(|x| x.last_move_op).unwrap(), + }); + } + + // Preserve the snapshot's existing order: siblings first, followed + // by each sibling's subtree in sibling order. + let start = pending.len(); + pending.extend(children.iter().map(|(_, id)| TreeParentId::Node(*id))); + pending[start..].reverse(); + } + } + + pub fn nodes(&self) -> Vec<TreeID> { + self.trees.keys().copied().collect::<Vec<_>>() + } + + #[cfg(feature = "test_utils")] + pub fn max_counter(&self) -> i32 { + self.trees + .keys() + .filter(|&k| !self.is_node_deleted(k).unwrap()) + .map(|k| k.counter) + .max() + .unwrap_or(0) + } + + pub fn get_children<'a>( + &'a self, + parent: &TreeParentId, + ) -> Option<impl Iterator<Item = TreeID> + 'a> { + self.children.get(parent).map(|x| x.iter().map(|x| *x.1)) + } + + pub fn children_num(&self, parent: &TreeParentId) -> Option<usize> { + self.children.get(parent).map(|x| x.len()) + } + + /// Determine whether the target is the child of the node + /// + /// O(1) + pub fn is_parent(&self, target: &TreeID, parent: &TreeParentId) -> bool { + self.trees.get(target).is_some_and(|x| x.parent == *parent) + } + + /// Delete the position cache of the node + pub(crate) fn try_delete_position_cache(&mut self, parent: &TreeParentId, target: &TreeID) { + if let Some(x) = self.children.get_mut(parent) { + x.delete_child(target); + } + } + + pub(crate) fn generate_position_at( + &mut self, + target: &TreeID, + parent: &TreeParentId, + index: usize, + cfg: FiIfNotConfigured, + ) -> FractionalIndexGenResult { + match &mut self.fractional_index_config { + TreeFractionalIndexConfigInner::GenerateFractionalIndex { jitter, rng } => { + if *jitter == 0 { + self.children + .entry(*parent) + .or_default() + .generate_fi_at(index, target) + } else { + self.children + .entry(*parent) + .or_default() + .generate_fi_at_jitter(index, target, rng.as_mut(), *jitter) + } + } + TreeFractionalIndexConfigInner::MoveDisabled => match cfg { + FiIfNotConfigured::Throw => FractionalIndexGenResult::NotConfigured, + FiIfNotConfigured::UseJitterZero => self + .children + .entry(*parent) + .or_default() + .generate_fi_at(index, target), + FiIfNotConfigured::Zero => FractionalIndexGenResult::Ok(FractionalIndex::default()), + }, + } + } + + pub(crate) fn is_fractional_index_enabled(&self) -> bool { + !matches!( + self.fractional_index_config, + TreeFractionalIndexConfigInner::MoveDisabled + ) + } + + pub(crate) fn enable_generate_fractional_index(&mut self, jitter: u8) { + if let TreeFractionalIndexConfigInner::GenerateFractionalIndex { + jitter: old_jitter, .. + } = &mut self.fractional_index_config + { + *old_jitter = jitter; + return; + } + self.fractional_index_config = TreeFractionalIndexConfigInner::GenerateFractionalIndex { + jitter, + rng: Box::new(rand::rngs::StdRng::seed_from_u64(self.peer_id)), + }; + } + + pub(crate) fn disable_generate_fractional_index(&mut self) { + self.fractional_index_config = TreeFractionalIndexConfigInner::MoveDisabled; + } + + pub(crate) fn get_position(&self, target: &TreeID) -> Option<FractionalIndex> { + self.trees.get(target).and_then(|x| x.position.clone()) + } + + pub(crate) fn get_index_by_tree_id(&self, target: &TreeID) -> Option<usize> { + let parent = self.parent(target)?; + (!parent.is_deleted()) + .then(|| { + self.children + .get(&parent) + .and_then(|x| x.get_index_by_child_id(target)) + }) + .flatten() + } + + pub(crate) fn get_index_by_position( + &self, + parent: &TreeParentId, + node_position: &NodePosition, + ) -> Option<usize> { + self.children.get(parent).map(|c| { + match c.get_last_insert_index_by_position(node_position) { + Ok(i) => i, + Err(i) => i, + } + }) + } + + pub(crate) fn get_id_by_index(&self, parent: &TreeParentId, index: usize) -> Option<TreeID> { + (!parent.is_deleted()) + .then(|| self.children.get(parent).and_then(|x| x.get_id_at(index))) + .flatten() + } + + /// Check the consistency between `self.trees` and `self.children` + /// + /// It's used for debug and test + #[allow(unused)] + pub(crate) fn check_tree_integrity(&self) { + let mut parent_children_map: FxHashMap<TreeParentId, FxHashSet<TreeID>> = + FxHashMap::default(); + for (id, node) in self.trees.iter() { + let parent = node.parent; + parent_children_map.entry(parent).or_default().insert(*id); + } + + for (parent, children) in parent_children_map.iter() { + let cached_children = self.get_children(parent).expect("parent not found"); + let cached_children = cached_children.collect::<FxHashSet<_>>(); + if &cached_children != children { + panic!( + "tree integrity broken: children set of node {:?} is not consistent", + parent + ); + } + } + } + + pub fn is_empty(&self) -> bool { + match self.children.get(&TreeParentId::Root) { + Some(c) => c.len() == 0, + None => true, + } + } + + pub fn get_last_move_id(&self, id: &TreeID) -> Option<ID> { + self.trees.get(id).map(|x| x.last_move_op.id()) + } +} + +pub(crate) enum FractionalIndexGenResult { + Ok(FractionalIndex), + Rearrange(Vec<(TreeID, FractionalIndex)>), + NotConfigured, +} + +impl TreeState { + /// Applies a raw `Create` or `Move` op (`Linear` and `ImportGreaterUpdates` + /// modes) and pushes the events that turn the alive tree before it into + /// the alive tree after it: + /// + /// - alive before and after: `Move`, unless nothing visible changed (e.g. a + /// `Create` op for a child that the revival of its parent already + /// brought back where it is); + /// - alive before only: `Delete`, which covers the subtree; + /// - alive after only: `Create` for the node and for every node below it, + /// because a node that leaves a deleted subtree brings its subtree back; + /// - neither: nothing. + /// + /// With `with_check`, an op that would create a cycle is skipped, as in + /// `apply_diff`. + fn apply_raw_move_and_convert( + &mut self, + target: TreeID, + parent: TreeParentId, + last_move_op: IdFull, + position: &FractionalIndex, + with_check: bool, + ans: &mut Vec<TreeDiffItem>, + ) { + let old = self + .trees + .get(&target) + .map(|node| (node.parent, node.position.as_ref() == Some(position))); + let old_index = match &old { + Some(_) if !self.is_node_deleted(&target).unwrap() => { + Some(self.get_index_by_tree_id(&target).unwrap()) + } + _ => None, + }; + let result = self.mov( + target, + parent, + last_move_op, + Some(position.clone()), + with_check, + ); + if with_check { + if result.is_err() { + return; + } + } else { + result.unwrap(); + } + + let alive = !self.is_node_deleted(&target).unwrap(); + match (old, old_index) { + (Some((old_parent, same_position)), Some(old_index)) => { + if !alive { + ans.push(TreeDiffItem { + target, + action: TreeExternalDiff::Delete { + old_parent, + old_index, + }, + }); + return; + } + let index = self.get_index_by_tree_id(&target).unwrap(); + if old_parent == parent && old_index == index && same_position { + return; + } + ans.push(TreeDiffItem { + target, + action: TreeExternalDiff::Move { + parent, + index, + position: position.clone(), + old_parent, + old_index, + }, + }); + } + (old, _) => { + if !alive { + return; + } + ans.push(TreeDiffItem { + target, + action: TreeExternalDiff::Create { + parent, + index: self.get_index_by_tree_id(&target).unwrap(), + position: position.clone(), + }, + }); + // A node that did not exist has no children yet. + if old.is_some() { + self.push_subtree_creation(target, ans); + } + } + } + } + + /// Pushes a `Create` for every node below `root`: parents before their + /// children and siblings in order, so each `index` is valid when the + /// events are applied in sequence. + fn push_subtree_creation(&self, root: TreeID, ans: &mut Vec<TreeDiffItem>) { + let mut stack = vec![root]; + while let Some(node) = stack.pop() { + let parent = TreeParentId::Node(node); + let Some(children) = self.children.get(&parent) else { + continue; + }; + for (index, (position, &child)) in children.iter().enumerate() { + ans.push(TreeDiffItem { + target: child, + action: TreeExternalDiff::Create { + parent, + index, + position: position.position.clone(), + }, + }); + stack.push(child); + } + } + } +} + +impl ContainerState for TreeState { + fn container_idx(&self) -> crate::container::idx::ContainerIdx { + self.idx + } + + fn is_state_empty(&self) -> bool { + self.nodes().is_empty() + } + + // How we apply the diff is coupled with the [DiffMode] we used to calculate the diff. + // So be careful when you modify this function. + fn apply_diff_and_convert( + &mut self, + diff: crate::event::InternalDiff, + ctx: DiffApplyContext, + ) -> Diff { + let need_check = !matches!(ctx.mode, DiffMode::Checkout | DiffMode::Linear); + // In `Checkout` mode the items come from `TreeDiffCalculator`, which + // has already classified them against its cache and follows every + // `Create` with the node's subtree. In `Linear` and + // `ImportGreaterUpdates` modes they are the raw ops, so the events are + // derived from the state. See `context/tree-events.md`. + let raw_ops = !matches!(ctx.mode, DiffMode::Checkout); + let mut ans = vec![]; + if let InternalDiff::Tree(tree) = &diff { + // assert never cause cycle move + for diff in tree.diff.iter() { + let last_move_op = diff.last_effective_move_op_id; + let target = diff.target; + // create associated metadata container + match &diff.action { + TreeInternalDiff::Create { parent, position } + | TreeInternalDiff::Move { parent, position } + if raw_ops => + { + self.apply_raw_move_and_convert( + target, + *parent, + last_move_op, + position, + need_check, + &mut ans, + ); + } + TreeInternalDiff::Create { parent, position } => { + self.mov(target, *parent, last_move_op, Some(position.clone()), false) + .unwrap(); + + if let TreeParentId::Node(p) = parent { + // reuse diff cache, at this time,it's "move in deleted" + if self.is_node_deleted(p).unwrap() { + continue; + } + } + + let index = self.get_index_by_tree_id(&target).unwrap(); + ans.push(TreeDiffItem { + target, + action: TreeExternalDiff::Create { + parent: *parent, + index, + position: position.clone(), + }, + }); + } + TreeInternalDiff::Move { parent, position } => { + let old_parent = self.trees.get(&target).unwrap().parent; + // If this is some, the node is still alive at the moment + let old_index = self.get_index_by_tree_id(&target); + let was_alive = !self.is_node_deleted(&target).unwrap(); + self.mov(target, *parent, last_move_op, Some(position.clone()), false) + .unwrap(); + + if let TreeParentId::Node(p) = parent { + // reuse diff cache, at this time,it's "move in deleted" + if self.is_node_deleted(p).unwrap() { + continue; + } + } + + let index = self.get_index_by_tree_id(&target).unwrap(); + match was_alive { + true => { + ans.push(TreeDiffItem { + target, + action: TreeExternalDiff::Move { + parent: *parent, + index, + position: position.clone(), + old_parent, + old_index: old_index.unwrap(), + }, + }); + } + false => { + ans.push(TreeDiffItem { + target, + action: TreeExternalDiff::Create { + parent: *parent, + index, + position: position.clone(), + }, + }); + } + } + } + TreeInternalDiff::Delete { parent, position } => { + let mut send_event = true; + if self.is_node_deleted(&target).unwrap() { + send_event = false; + } + if send_event { + ans.push(TreeDiffItem { + target, + action: TreeExternalDiff::Delete { + old_parent: self.trees.get(&target).unwrap().parent, + old_index: self.get_index_by_tree_id(&target).unwrap(), + }, + }); + } + self.mov(target, *parent, last_move_op, position.clone(), false) + .unwrap(); + } + TreeInternalDiff::MoveInDelete { parent, position } => { + self.mov(target, *parent, last_move_op, position.clone(), false) + .unwrap(); + } + TreeInternalDiff::UnCreate => { + // maybe the node created and moved to the parent deleted + if !self.is_node_deleted(&target).unwrap() { + ans.push(TreeDiffItem { + target, + action: TreeExternalDiff::Delete { + old_parent: self.trees.get(&target).unwrap().parent, + old_index: self.get_index_by_tree_id(&target).unwrap(), + }, + }); + } + // delete it from state + let node = self.trees.remove(&target); + if let Some(node) = node { + if !node.parent.is_deleted() { + self.children + .get_mut(&node.parent) + .unwrap() + .delete_child(&target); + } + } + continue; + } + }; + } + } + + // self.check_tree_integrity(); + Diff::Tree(TreeDiff { diff: ans }) + } + + // How we apply the diff is coupled with the [DiffMode] we used to calculate the diff. + // So be careful when you modify this function. + fn apply_diff(&mut self, diff: InternalDiff, ctx: DiffApplyContext) -> LoroResult<()> { + if let InternalDiff::Tree(tree) = &diff { + let need_check = !matches!(ctx.mode, DiffMode::Checkout | DiffMode::Linear); + // assert never cause cycle move + for diff in tree.diff.iter() { + let last_move_op = diff.last_effective_move_op_id; + let target = diff.target; + // create associated metadata container + match &diff.action { + TreeInternalDiff::Create { parent, position } + | TreeInternalDiff::Move { + parent, position, .. + } => { + if need_check { + self.mov(target, *parent, last_move_op, Some(position.clone()), true) + .unwrap_or_default(); + } else { + self.mov(target, *parent, last_move_op, Some(position.clone()), false)?; + } + } + TreeInternalDiff::Delete { parent, position } => { + self.mov(target, *parent, last_move_op, position.clone(), false)?; + } + TreeInternalDiff::MoveInDelete { parent, position } => { + self.mov(target, *parent, last_move_op, position.clone(), false)?; + } + TreeInternalDiff::UnCreate => { + // delete it from state + let parent = self.trees.remove(&target); + if let Some(parent) = parent { + if !parent.parent.is_deleted() { + self.children + .get_mut(&parent.parent) + .unwrap() + .delete_child(&target); + } + } + continue; + } + }; + } + } + // self.check_tree_integrity(); + Ok(()) + } + + fn apply_local_op(&mut self, raw_op: &RawOp, _op: &Op) -> LoroResult<ApplyLocalOpReturn> { + let mut deleted_containers = vec![]; + match &raw_op.content { + crate::op::RawOpContent::Tree(tree) => match &**tree { + TreeOp::Create { + target, + parent, + position, + } + | TreeOp::Move { + target, + parent, + position, + } => { + let parent = TreeParentId::from(*parent); + self.mov( + *target, + parent, + raw_op.id_full(), + Some(position.clone()), + true, + )?; + } + TreeOp::Delete { target } => { + let parent = TreeParentId::Deleted; + deleted_containers.push(ContainerID::new_normal( + target.id(), + loro_common::ContainerType::Map, + )); + self.mov(*target, parent, raw_op.id_full(), None, true)?; + } + }, + _ => unreachable!(), + } + // self.check_tree_integrity(); + Ok(ApplyLocalOpReturn { deleted_containers }) + } + + fn to_diff(&mut self, _doc: &Weak<LoroDocInner>) -> Diff { + let mut diffs = vec![]; + let Some(roots) = self.children.get(&TreeParentId::Root) else { + return Diff::Tree(TreeDiff { diff: vec![] }); + }; + + let mut q = VecDeque::from_iter(roots.iter()); + let mut index = 0; + let mut parent = TreeParentId::Root; + while let Some((position, node)) = q.pop_front() { + let node_parent = self.trees.get(node).unwrap().parent; + if node_parent != parent { + index = 0; + parent = node_parent; + } + let diff = TreeDiffItem { + target: *node, + action: TreeExternalDiff::Create { + parent: node_parent, + index, + position: position.position.clone(), + }, + }; + index += 1; + diffs.push(diff); + if let Some(children) = self.children.get(&TreeParentId::Node(*node)) { + // TODO: Refactor: you can include the index and parent in the q + // The code will be more robust and easy to understand + q.extend(children.iter()); + } + } + + Diff::Tree(TreeDiff { diff: diffs }) + } + + fn get_value(&mut self) -> LoroValue { + self.get_all_hierarchy_nodes_under(TreeParentId::Root) + .into_iter() + .map(|x| x.into_value()) + .collect::<Vec<_>>() + .into() + } + + /// Get the index of the child container + fn get_child_index(&self, id: &ContainerID) -> Option<Index> { + let id = id.as_normal().unwrap(); + let tree_id = TreeID { + peer: *id.0, + counter: *id.1, + }; + if !self.trees.contains_key(&tree_id) || self.is_node_deleted(&tree_id).unwrap() { + None + } else { + Some(Index::Node(tree_id)) + } + } + + fn contains_child(&self, id: &ContainerID) -> bool { + let id = id.as_normal().unwrap(); + let tree_id = TreeID { + peer: *id.0, + counter: *id.1, + }; + self.trees.contains_key(&tree_id) && !self.is_node_deleted(&tree_id).unwrap() + } + + fn get_child_containers(&self) -> Vec<ContainerID> { + self.trees + .keys() + .map(|n| n.associated_meta_container()) + .collect_vec() + } + + fn fork(&self, _config: &Configure) -> Self { + self.clone() + } +} + +// convert map container to LoroValue +#[allow(clippy::ptr_arg)] +pub(crate) fn get_meta_value(nodes: &mut Vec<LoroValue>, state: &mut DocState) { + let mut pending = nodes.iter_mut().rev().collect::<Vec<_>>(); + while let Some(node) = pending.pop() { + let map = node.as_map_mut().unwrap().make_mut(); + let meta = map.get_mut("meta").unwrap(); + let id = meta.as_container().unwrap(); + *meta = state.get_container_deep_value(state.arena.register_container(id)); + let children = map.get_mut("children").unwrap().as_list_mut().unwrap(); + pending.extend(children.make_mut().iter_mut().rev()); + } +} + +#[derive(Debug, Clone)] +pub struct TreeNode { + pub id: TreeID, + pub parent: TreeParentId, + pub fractional_index: FractionalIndex, + pub index: usize, + pub last_move_op: IdFull, +} + +#[derive(Debug, Clone)] +pub struct TreeNodeWithChildren { + pub id: TreeID, + pub parent: TreeParentId, + pub fractional_index: FractionalIndex, + pub index: usize, + pub children: Vec<TreeNodeWithChildren>, +} + +impl TreeNodeWithChildren { + fn into_value(self) -> LoroValue { + // Finish a node only after its children, without using the call stack. + let mut pending = vec![(self, None)]; + let mut values = Vec::new(); + while let Some((mut node, child_count)) = pending.pop() { + if let Some(child_count) = child_count { + let children = values.split_off(values.len() - child_count); + values.push(node.into_value_with_children(children)); + } else { + let children = std::mem::take(&mut node.children); + pending.push((node, Some(children.len()))); + pending.extend(children.into_iter().rev().map(|node| (node, None))); + } + } + values.pop().unwrap() + } + + fn into_value_with_children(self, children: Vec<LoroValue>) -> LoroValue { + let mut t = FxHashMap::default(); + t.insert("id".to_string(), self.id.to_string().into()); + let p = self + .parent + .tree_id() + .map(|p| p.to_string().into()) + .unwrap_or(LoroValue::Null); + t.insert("parent".to_string(), p); + t.insert( + "meta".to_string(), + self.id.associated_meta_container().into(), + ); + t.insert("index".to_string(), (self.index as i64).into()); + t.insert( + "fractional_index".to_string(), + self.fractional_index.to_string().into(), + ); + t.insert("children".to_string(), children.into()); + t.into() + } +} + +impl Drop for TreeNodeWithChildren { + fn drop(&mut self) { + let mut pending = std::mem::take(&mut self.children); + while let Some(mut node) = pending.pop() { + pending.append(&mut node.children); + } + } +} + +#[cfg(test)] +mod traversal_tests { + use super::*; + use loro_common::ContainerType; + + fn cyclic_parents() -> TreeState { + let idx = ContainerIdx::from_index_and_type(0, ContainerType::Tree); + let mut tree = TreeState::new(idx, 1); + for counter in 0..3 { + tree._init_push_tree_node_in_order( + TreeID::new(1, counter), + TreeParentId::Root, + IdFull::new(1, counter, counter as u32), + Some(FractionalIndex::default()), + ) + .unwrap(); + } + tree.trees.get_mut(&TreeID::new(1, 0)).unwrap().parent = TreeID::new(1, 1).into(); + tree.trees.get_mut(&TreeID::new(1, 1)).unwrap().parent = TreeID::new(1, 0).into(); + tree + } + + #[test] + #[should_panic(expected = "tree parent cycle")] + fn ancestor_walk_fails_fast_on_an_internal_cycle() { + cyclic_parents().is_ancestor_of(&TreeID::new(1, 2), &TreeID::new(1, 0).into()); + } + + #[test] + #[should_panic(expected = "tree parent cycle")] + fn deletion_walk_fails_fast_on_an_internal_cycle() { + cyclic_parents().is_node_deleted(&TreeID::new(1, 0)); + } + + #[test] + fn iterative_walks_keep_hierarchy_and_snapshot_order() { + let idx = ContainerIdx::from_index_and_type(0, ContainerType::Tree); + let mut tree = TreeState::new(idx, 1); + // Two roots, with a branching subtree under each root. + for (counter, parent) in [ + (0, None), + (1, None), + (2, Some(0)), + (3, Some(0)), + (4, Some(2)), + (5, Some(1)), + ] { + tree._init_push_tree_node_in_order( + TreeID::new(1, counter), + parent.map(|counter| TreeID::new(1, counter)).into(), + IdFull::new(1, counter, counter as u32), + Some(FractionalIndex::default()), + ) + .unwrap(); + } + let hierarchy = tree.get_all_hierarchy_nodes_under(TreeParentId::Root); + let mut pending = hierarchy.iter().rev().collect::<Vec<_>>(); + let mut preorder = Vec::new(); + while let Some(node) = pending.pop() { + assert_eq!(tree.parent(&node.id), Some(node.parent)); + assert_eq!(tree.get_index_by_tree_id(&node.id), Some(node.index)); + assert_eq!( + tree.get_position(&node.id), + Some(node.fractional_index.clone()) + ); + preorder.push(node.id.counter); + pending.extend(node.children.iter().rev()); + } + assert_eq!(preorder, vec![0, 2, 4, 3, 1, 5]); + let snapshot_order = tree.bfs_all_alive_nodes_for_fast_snapshot(); + assert_eq!( + snapshot_order + .iter() + .map(|node| node.id.counter) + .collect::<Vec<_>>(), + vec![0, 1, 2, 3, 4, 5] + ); + let root = TreeID::new(1, 0); + tree.mov( + root, + TreeParentId::Deleted, + IdFull::new(1, 6, 6), + None, + true, + ) + .unwrap(); + assert_eq!( + tree.bfs_all_deleted_nodes_for_fast_snapshot() + .iter() + .map(|node| node.id.counter) + .collect::<Vec<_>>(), + vec![0, 2, 3, 4] + ); + } + + #[test] + fn deep_hierarchy_can_be_dropped_on_a_small_stack() { + std::thread::Builder::new() + .stack_size(1 << 20) + .spawn(|| { + let idx = ContainerIdx::from_index_and_type(0, ContainerType::Tree); + let mut tree = TreeState::new(idx, 1); + for counter in 0..4_000 { + let parent = (counter > 0).then(|| TreeID::new(1, counter - 1)); + tree._init_push_tree_node_in_order( + TreeID::new(1, counter), + parent.into(), + IdFull::new(1, counter, counter as u32), + Some(FractionalIndex::default()), + ) + .unwrap(); + } + let hierarchy = tree.get_all_hierarchy_nodes_under(TreeParentId::Root); + let mut nodes = &hierarchy; + let mut depth = 0; + while let Some(node) = nodes.first() { + depth += 1; + nodes = &node.children; + } + assert_eq!(depth, 4_000); + drop(hierarchy); + }) + .unwrap() + .join() + .unwrap(); + } +} + +mod jitter { + use super::{FractionalIndexGenResult, NodeChildren}; + use fractional_index::FractionalIndex; + use loro_common::TreeID; + use rand::Rng; + + impl NodeChildren { + pub(super) fn generate_fi_at_jitter( + &self, + pos: usize, + target: &TreeID, + rng: &mut impl Rng, + jitter: u8, + ) -> FractionalIndexGenResult { + let mut reset_ids = vec![]; + let mut left = None; + let mut next_right = None; + { + let mut right = None; + let children_num = self.len(); + if children_num == 0 { + return FractionalIndexGenResult::Ok(FractionalIndex::jitter_default( + rng, jitter, + )); + } + + if pos > 0 { + left = self.get_node_position_at(pos - 1); + } + if pos < children_num { + right = self.get_elem_at(pos); + } + + let left_fi = left.map(|x| &x.position); + // if left and right have the same fractional indexes, we need to scan further to + // find all the ids that need to be reset + if let Some(left_fi) = left_fi { + if Some(left_fi) == right.map(|x| &x.0.position) { + // TODO: the min length between left and right + reset_ids.push(*right.unwrap().1); + for i in (pos + 1)..children_num { + let this_position = &self.get_node_position_at(i).unwrap().position; + if this_position == left_fi { + reset_ids.push(*self.get_elem_at(i).unwrap().1); + } else { + next_right = Some(this_position.clone()); + break; + } + } + } + } + + if reset_ids.is_empty() { + return FractionalIndexGenResult::Ok( + FractionalIndex::new_jitter( + left.map(|x| &x.position), + right.map(|x| &x.0.position), + rng, + jitter, + ) + .unwrap(), + ); + } + } + let positions = FractionalIndex::generate_n_evenly_jitter( + left.map(|x| &x.position), + next_right.as_ref(), + reset_ids.len() + 1, + rng, + jitter, + ) + .unwrap(); + FractionalIndexGenResult::Rearrange( + Some(*target) + .into_iter() + .chain(reset_ids) + .zip(positions) + .collect(), + ) + } + } +} + +mod snapshot { + use std::{borrow::Cow, collections::BTreeSet}; + + use fractional_index::FractionalIndex; + use loro_common::{IdFull, PeerID, TreeID}; + use rustc_hash::{FxHashMap, FxHashSet}; + + use serde_columnar::columnar; + + use crate::{ + encoding::{arena::PositionArena, value_register::ValueRegister}, + state::{ + decode_counter, decode_lamport_from_delta, decode_peer_from_table, decode_peer_table, + state_decode_error, FastStateSnapshot, + }, + }; + + use super::{NodePosition, TreeNode, TreeParentId, TreeState}; + #[columnar(vec, ser, de, iterable)] + #[derive(Debug, Clone)] + struct EncodedTreeNodeId { + #[columnar(strategy = "DeltaRle")] + peer_idx: usize, + #[columnar(strategy = "DeltaRle")] + counter: i32, + } + + #[columnar(vec, ser, de, iterable)] + #[derive(Debug, Clone)] + struct EncodedTreeNode { + /// If this field is 0, it means none, its parent is root + /// If this field is 1, its parent is the deleted root + #[columnar(strategy = "DeltaRle")] + parent_idx_plus_two: usize, + #[columnar(strategy = "DeltaRle")] + last_set_peer_idx: usize, + #[columnar(strategy = "DeltaRle")] + last_set_counter: i32, + #[columnar(strategy = "DeltaRle")] + last_set_lamport_sub_counter: i32, + fractional_index_idx: usize, + } + + #[columnar(ser, de)] + struct EncodedTree<'a> { + #[columnar(class = "vec", iter = "EncodedTreeNodeId")] + node_ids: Vec<EncodedTreeNodeId>, + #[columnar(class = "vec", iter = "EncodedTreeNode")] + nodes: Vec<EncodedTreeNode>, + #[columnar(borrow)] + fractional_indexes: Cow<'a, [u8]>, + #[columnar(borrow)] + reserved_has_effect_bool_rle: Cow<'a, [u8]>, + } + + fn encode( + state: &TreeState, + input: Vec<TreeNode>, + deleted_nodes: Vec<TreeNode>, + ) -> (ValueRegister<PeerID>, EncodedTree<'_>) { + let mut peers: ValueRegister<PeerID> = ValueRegister::new(); + let mut position_set = BTreeSet::default(); + let mut nodes = Vec::with_capacity(input.len()); + let mut node_ids = Vec::with_capacity(input.len()); + let mut position_register = ValueRegister::new(); + let mut id_to_idx = FxHashMap::default(); + for node in input.iter().chain(deleted_nodes.iter()) { + position_set.insert(node.fractional_index.clone()); + let idx = node_ids.len(); + node_ids.push(EncodedTreeNodeId { + peer_idx: peers.register(&node.id.peer), + counter: node.id.counter, + }); + id_to_idx.insert(node.id, idx); + } + + for p in position_set { + position_register.register(&p); + } + + for node in input { + let n = state.trees.get(&node.id).unwrap(); + let last_set_id = n.last_move_op; + nodes.push(EncodedTreeNode { + parent_idx_plus_two: match node.parent { + TreeParentId::Deleted => 1, + TreeParentId::Root => 0, + TreeParentId::Node(id) => id_to_idx.get(&id).unwrap() + 2, + TreeParentId::Unexist => unreachable!(), + }, + last_set_peer_idx: peers.register(&last_set_id.peer), + last_set_counter: last_set_id.counter, + last_set_lamport_sub_counter: last_set_id.lamport as i32 - last_set_id.counter, + fractional_index_idx: position_register.register(&node.fractional_index), + }) + } + + for node in deleted_nodes { + let n = state.trees.get(&node.id).unwrap(); + let last_set_id = n.last_move_op; + nodes.push(EncodedTreeNode { + parent_idx_plus_two: match node.parent { + TreeParentId::Deleted => 1, + TreeParentId::Root => 0, + TreeParentId::Node(id) => id_to_idx.get(&id).unwrap() + 2, + TreeParentId::Unexist => unreachable!(), + }, + last_set_peer_idx: peers.register(&last_set_id.peer), + last_set_counter: last_set_id.counter, + last_set_lamport_sub_counter: last_set_id.lamport as i32 - last_set_id.counter, + fractional_index_idx: position_register.register(&node.fractional_index), + }) + } + + let position_vec = position_register.unwrap_vec(); + let positions = PositionArena::from_positions(position_vec.iter().map(|p| p.as_bytes())); + ( + peers, + EncodedTree { + node_ids, + nodes, + fractional_indexes: positions.encode().into(), + reserved_has_effect_bool_rle: vec![].into(), + }, + ) + } + + struct DecodedTreeNode { + id: TreeID, + parent: TreeParentId, + last_move_op: IdFull, + node_position: NodePosition, + } + + /// Returns whether every parent's children appear in strictly increasing + /// [`NodePosition`] order. Two siblings with the same position and idlp cannot + /// be produced by any valid history, so they are rejected. + fn siblings_in_order(nodes: &[DecodedTreeNode]) -> loro_common::LoroResult<bool> { + let mut last_child: FxHashMap<TreeParentId, &NodePosition> = FxHashMap::default(); + let mut in_order = true; + for node in nodes { + if let Some(prev) = last_child.insert(node.parent, &node.node_position) { + match prev.cmp(&node.node_position) { + std::cmp::Ordering::Less => {} + std::cmp::Ordering::Equal => { + return Err(state_decode_error( + "Decode tree state failed: duplicate sibling position", + )); + } + std::cmp::Ordering::Greater => in_order = false, + } + } + } + Ok(in_order) + } + + impl FastStateSnapshot for TreeState { + /// Encodes the TreeState into a compact binary format for efficient serialization. + /// + /// The encoding schema: + /// 1. Encodes all nodes using a breadth-first search traversal, ensuring a consistent order. + /// 2. Uses a ValueRegister to deduplicate and index PeerIDs and TreeIDs, reducing redundancy. + /// - PeerIDs are stored once and referenced by index. + /// - TreeIDs are decomposed into peer index and counter for compact representation. + /// 3. Encodes fractional indexes using a PositionArena for space efficiency + /// 4. Utilizes delta encoding and run-length encoding for further size reduction: + /// - Delta encoding stores differences between consecutive values. + /// - Run-length encoding compresses sequences of repeated values. + /// 5. Stores parent relationships using indices, with special values for root and deleted nodes. + /// 6. Encodes last move operation details (peer_idx, counter[Delta], lamport clock[Delta]) for each node. + fn encode_snapshot_fast<W: std::io::prelude::Write>(&mut self, mut w: W) { + let all_alive_nodes = self.bfs_all_alive_nodes_for_fast_snapshot(); + let all_deleted_nodes = self.bfs_all_deleted_nodes_for_fast_snapshot(); + let (peers, encoded) = encode(self, all_alive_nodes, all_deleted_nodes); + let peers = peers.unwrap_vec(); + leb128::write::unsigned(&mut w, peers.len() as u64).unwrap(); + for peer in peers { + w.write_all(&peer.to_le_bytes()).unwrap(); + } + + let vec = serde_columnar::to_vec(&encoded).unwrap(); + w.write_all(&vec).unwrap(); + } + + fn decode_value(_: &[u8]) -> loro_common::LoroResult<(loro_common::LoroValue, &[u8])> { + unreachable!() + } + + fn decode_snapshot_fast( + idx: crate::container::idx::ContainerIdx, + (_, mut bytes): (loro_common::LoroValue, &[u8]), + ctx: crate::state::ContainerCreationContext, + ) -> loro_common::LoroResult<Self> + where + Self: Sized, + { + let peers = decode_peer_table(&mut bytes, "Decode tree state failed")?; + + let mut tree = TreeState::new(idx, ctx.peer); + let encoded: EncodedTree = serde_columnar::from_bytes(bytes).map_err(|err| { + state_decode_error(format!("Decode tree state failed: invalid metadata: {err}")) + })?; + let fractional_indexes = + PositionArena::decode(&encoded.fractional_indexes)?.try_parse_to_positions()?; + if encoded.node_ids.len() != encoded.nodes.len() { + return Err(state_decode_error( + "Decode tree state failed: node id/node length mismatch", + )); + } + let node_ids = encoded + .node_ids + .iter() + .map(|x| { + Ok(TreeID::new( + decode_peer_from_table(&peers, x.peer_idx, "Decode tree state failed")?, + decode_counter(x.counter, "Decode tree state failed")?, + )) + }) + .collect::<loro_common::LoroResult<Vec<_>>>()?; + let mut decoded = Vec::with_capacity(node_ids.len()); + let mut seen_ids = + FxHashSet::with_capacity_and_hasher(node_ids.len(), Default::default()); + for (node_id, node) in node_ids.iter().zip(encoded.nodes) { + if !seen_ids.insert(*node_id) { + return Err(state_decode_error( + "Decode tree state failed: duplicate node id", + )); + } + let parent = match node.parent_idx_plus_two { + 0 => TreeParentId::Root, + 1 => TreeParentId::Deleted, + n => { + let id = *node_ids.get(n - 2).ok_or_else(|| { + state_decode_error( + "Decode tree state failed: parent index out of range", + ) + })?; + TreeParentId::from(Some(id)) + } + }; + let last_move_op = IdFull::new( + decode_peer_from_table( + &peers, + node.last_set_peer_idx, + "Decode tree state failed", + )?, + node.last_set_counter, + decode_lamport_from_delta( + node.last_set_counter, + node.last_set_lamport_sub_counter, + "Decode tree state failed", + )?, + ); + let position = FractionalIndex::from_bytes( + fractional_indexes + .get(node.fractional_index_idx) + .ok_or_else(|| { + state_decode_error( + "Decode tree state failed: fractional index out of range", + ) + })? + .clone(), + ); + decoded.push(DecodedTreeNode { + id: *node_id, + parent, + last_move_op, + node_position: NodePosition::new(position, last_move_op.idlp()), + }); + } + + // Sibling order is fully determined by each node's (fractional index, idlp), + // so the encoded order carries no information. Rust always writes siblings in + // that order, but other encoders (loro.js <= 0.2.0, loro-dev/loro#1088) may + // not; sort instead of tripping `push_child_in_order` on the first read. + if !siblings_in_order(&decoded)? { + decoded.sort_by(|a, b| a.node_position.cmp(&b.node_position)); + // Out-of-order duplicates only become adjacent after sorting. + let sorted = siblings_in_order(&decoded)?; + debug_assert!(sorted); + } + + for node in decoded { + let DecodedTreeNode { + id, + parent, + last_move_op, + node_position, + } = node; + // PERF: we don't need to mov the deleted node, instead we can cache them + tree._init_push_tree_node_in_order( + id, + parent, + last_move_op, + Some(node_position.position), + ) + .map_err(|err| { + state_decode_error(format!("Decode tree state failed: invalid node: {err}")) + })?; + } + Ok(tree) + } + } + + #[cfg(test)] + mod tests { + use loro_common::{ContainerType, LoroValue}; + + use crate::{container::idx::ContainerIdx, state::ContainerCreationContext}; + + use super::*; + + #[test] + fn tree_fast_snapshot_rejects_corrupt_state_metadata() { + let idx = ContainerIdx::from_index_and_type(0, ContainerType::Tree); + let configure = Default::default(); + let ctx = ContainerCreationContext { + configure: &configure, + peer: 0, + }; + + assert!(TreeState::decode_snapshot_fast(idx, (LoroValue::Null, &[1]), ctx).is_err()); + } + + #[test] + fn tree_fast_snapshot_rejects_negative_node_counter() { + let idx = ContainerIdx::from_index_and_type(0, ContainerType::Tree); + let configure = Default::default(); + let ctx = ContainerCreationContext { + configure: &configure, + peer: 0, + }; + + let position = fractional_index::FractionalIndex::default(); + let positions = PositionArena::from_positions([position.as_bytes()]); + let encoded = EncodedTree { + node_ids: vec![EncodedTreeNodeId { + peer_idx: 0, + counter: -1, + }], + nodes: vec![EncodedTreeNode { + parent_idx_plus_two: 0, + last_set_peer_idx: 0, + last_set_counter: 0, + last_set_lamport_sub_counter: 0, + fractional_index_idx: 0, + }], + fractional_indexes: positions.encode().into(), + reserved_has_effect_bool_rle: vec![].into(), + }; + + let mut bytes = Vec::new(); + leb128::write::unsigned(&mut bytes, 1).unwrap(); + bytes.extend_from_slice(&1_u64.to_le_bytes()); + bytes.extend_from_slice(&serde_columnar::to_vec(&encoded).unwrap()); + + assert!(TreeState::decode_snapshot_fast(idx, (LoroValue::Null, &bytes), ctx).is_err()); + } + + /// Encodes `(counter, parent_idx_plus_two, last_set_counter, position_idx)` nodes of + /// peer 1, with lamport == counter for every last-set op. + fn encode_nodes( + nodes: &[(i32, usize, i32, usize)], + positions: &[FractionalIndex], + ) -> Vec<u8> { + let arena = PositionArena::from_positions(positions.iter().map(|p| p.as_bytes())); + let encoded = EncodedTree { + node_ids: nodes + .iter() + .map(|&(counter, ..)| EncodedTreeNodeId { + peer_idx: 0, + counter, + }) + .collect(), + nodes: nodes + .iter() + .map( + |&(_, parent_idx_plus_two, last_set_counter, fractional_index_idx)| { + EncodedTreeNode { + parent_idx_plus_two, + last_set_peer_idx: 0, + last_set_counter, + last_set_lamport_sub_counter: 0, + fractional_index_idx, + } + }, + ) + .collect(), + fractional_indexes: arena.encode().into(), + reserved_has_effect_bool_rle: vec![].into(), + }; + let mut bytes = Vec::new(); + leb128::write::unsigned(&mut bytes, 1).unwrap(); + bytes.extend_from_slice(&1_u64.to_le_bytes()); + bytes.extend_from_slice(&serde_columnar::to_vec(&encoded).unwrap()); + bytes + } + + fn decode(bytes: &[u8]) -> loro_common::LoroResult<TreeState> { + let idx = ContainerIdx::from_index_and_type(0, ContainerType::Tree); + let configure = Default::default(); + let ctx = ContainerCreationContext { + configure: &configure, + peer: 0, + }; + TreeState::decode_snapshot_fast(idx, (LoroValue::Null, bytes), ctx) + } + + fn children_of(tree: &TreeState, parent: TreeParentId) -> Vec<i32> { + tree.get_children(&parent) + .unwrap() + .map(|id| id.counter) + .collect() + } + + /// loro-dev/loro#1088: loro.js <= 0.2.0 wrote siblings in creation order. + #[test] + fn tree_fast_snapshot_sorts_unordered_siblings() { + // Cover both the Vec and the BTree representation of `NodeChildren`. + for n in [3, super::super::NodeChildren::MAX_SIZE_FOR_ARRAY as i32 + 5] { + let positions = FractionalIndex::generate_n_evenly(None, None, n as usize).unwrap(); + // Root node 0 has children 1..=n. Child i takes the (n - i)th position, so + // the encoded order is exactly the reverse of the sibling order. Node n + 1 + // is a child of node 1, and the deleted node n + 2 is encoded between alive + // nodes instead of after them. + let mut nodes = vec![(0, 0, 0, 0)]; + nodes.push((n + 2, 1, n + 2, 0)); + for i in 1..=n { + nodes.push((i, 2, i, (n - i) as usize)); + } + nodes.push((n + 1, 4, n + 1, 0)); + let tree = decode(&encode_nodes(&nodes, &positions)).unwrap(); + + assert_eq!(children_of(&tree, TreeParentId::Root), vec![0]); + let root = TreeID::new(1, 0); + assert_eq!( + children_of(&tree, TreeParentId::Node(root)), + (1..=n).rev().collect::<Vec<_>>() + ); + assert_eq!( + children_of(&tree, TreeParentId::Node(TreeID::new(1, 1))), + vec![n + 1] + ); + assert_eq!(children_of(&tree, TreeParentId::Deleted), vec![n + 2]); + assert_eq!(tree.is_node_deleted(&TreeID::new(1, n + 2)), Some(true)); + } + } + + #[test] + fn tree_fast_snapshot_orders_same_position_siblings_by_idlp() { + let positions = vec![FractionalIndex::default()]; + // Same fractional index: lamport (== last-set counter here) breaks the tie. + let nodes = [(0, 0, 0, 0), (1, 2, 5, 0), (2, 2, 3, 0), (3, 2, 4, 0)]; + let tree = decode(&encode_nodes(&nodes, &positions)).unwrap(); + assert_eq!( + children_of(&tree, TreeParentId::Node(TreeID::new(1, 0))), + vec![2, 3, 1] + ); + } + + #[test] + fn tree_fast_snapshot_rejects_duplicate_nodes_and_sibling_positions() { + let positions = FractionalIndex::generate_n_evenly(None, None, 2).unwrap(); + // The same node id twice. + let duplicate_id = [(0, 0, 0, 0), (0, 0, 1, 1)]; + assert!(decode(&encode_nodes(&duplicate_id, &positions)).is_err()); + // Two siblings with the same position and last-set idlp, adjacent in the input. + let adjacent = [(0, 0, 0, 0), (1, 0, 0, 0)]; + assert!(decode(&encode_nodes(&adjacent, &positions)).is_err()); + // ... and only adjacent once the out-of-order input is sorted. + let unordered = [(0, 0, 0, 1), (1, 0, 3, 0), (2, 0, 0, 1)]; + assert!(decode(&encode_nodes(&unordered, &positions)).is_err()); + } + } +} diff --git a/vendor/loro-internal/src/state/unknown_state.rs b/vendor/loro-internal/src/state/unknown_state.rs new file mode 100644 index 0000000..1b4a472 --- /dev/null +++ b/vendor/loro-internal/src/state/unknown_state.rs @@ -0,0 +1,184 @@ +use std::sync::Weak; + +use loro_common::{ContainerID, LoroResult, LoroValue}; + +use crate::{ + configure::Configure, + container::idx::ContainerIdx, + event::{Diff, Index, InternalDiff}, + op::{Op, RawOp}, + LoroDocInner, +}; + +use super::{ApplyLocalOpReturn, ContainerState, DiffApplyContext}; + +#[derive(Debug, Clone)] +pub struct UnknownState { + idx: ContainerIdx, +} + +impl UnknownState { + pub fn new(idx: ContainerIdx) -> Self { + Self { idx } + } +} + +impl ContainerState for UnknownState { + fn container_idx(&self) -> ContainerIdx { + self.idx + } + + fn is_state_empty(&self) -> bool { + false + } + + // An unknown container created and edited within one import/checkout still + // receives its (empty) diff; there is nothing to apply. + fn apply_diff_and_convert(&mut self, diff: InternalDiff, _ctx: DiffApplyContext) -> Diff { + assert!(matches!(diff, InternalDiff::Unknown), "{diff:?}"); + Diff::Unknown + } + + fn apply_diff(&mut self, diff: InternalDiff, _ctx: DiffApplyContext) -> LoroResult<()> { + assert!(matches!(diff, InternalDiff::Unknown), "{diff:?}"); + Ok(()) + } + + fn apply_local_op(&mut self, _raw_op: &RawOp, _op: &Op) -> LoroResult<ApplyLocalOpReturn> { + unreachable!() + } + + #[doc = r" Convert a state to a diff, such that an empty state will be transformed into the same as this state when it's applied."] + fn to_diff(&mut self, _doc: &Weak<LoroDocInner>) -> Diff { + Diff::Unknown + } + + fn get_value(&mut self) -> LoroValue { + // The payload of an unknown container is opaque to this version of + // Loro; expose it as `Null`, matching the public API convention in + // `ValueOrContainer::get_deep_value` (crates/loro/src/lib.rs) and + // `decode_value` below. + LoroValue::Null + } + + #[doc = r" Get the index of the child container"] + #[allow(unused)] + fn get_child_index(&self, id: &ContainerID) -> Option<Index> { + None + } + + fn contains_child(&self, _id: &ContainerID) -> bool { + false + } + + #[allow(unused)] + fn get_child_containers(&self) -> Vec<ContainerID> { + vec![] + } + + fn fork(&self, _config: &Configure) -> Self { + self.clone() + } +} + +mod snapshot { + use loro_common::LoroValue; + + use crate::state::FastStateSnapshot; + + use super::UnknownState; + + impl FastStateSnapshot for UnknownState { + fn encode_snapshot_fast<W: std::io::prelude::Write>(&mut self, _w: W) {} + + fn decode_value(bytes: &[u8]) -> loro_common::LoroResult<(loro_common::LoroValue, &[u8])> { + Ok((LoroValue::Null, bytes)) + } + + fn decode_snapshot_fast( + idx: crate::container::idx::ContainerIdx, + _v: (loro_common::LoroValue, &[u8]), + _ctx: crate::state::ContainerCreationContext, + ) -> loro_common::LoroResult<Self> + where + Self: Sized, + { + Ok(UnknownState::new(idx)) + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::Weak; + + use loro_common::{ContainerID, ContainerType}; + + use crate::{ + configure::Configure, + container::idx::ContainerIdx, + event::Diff, + state::{ContainerCreationContext, ContainerState, FastStateSnapshot}, + InternalString, + }; + + use super::UnknownState; + + fn unknown_idx() -> ContainerIdx { + ContainerIdx::from_index_and_type(7, ContainerType::Unknown(3)) + } + + #[test] + fn unknown_state_reports_identity_without_material_value() { + let mut state = UnknownState::new(unknown_idx()); + assert_eq!(state.container_idx(), unknown_idx()); + assert!(!state.is_state_empty()); + + assert!(matches!(state.to_diff(&Weak::new()), Diff::Unknown)); + assert_eq!(state.get_child_containers(), Vec::<ContainerID>::new()); + assert!(!state.contains_child(&ContainerID::Root { + name: InternalString::from("child"), + container_type: ContainerType::Text, + })); + assert_eq!( + state.get_child_index(&ContainerID::Root { + name: InternalString::from("child"), + container_type: ContainerType::Text, + }), + None + ); + } + + #[test] + fn unknown_state_fork_keeps_container_identity() { + let state = UnknownState::new(unknown_idx()); + let forked = state.fork(&Configure::default()); + + assert_eq!(forked.container_idx(), unknown_idx()); + assert!(!forked.is_state_empty()); + } + + #[test] + fn unknown_snapshot_roundtrip_preserves_bytes_and_index() { + let mut state = UnknownState::new(unknown_idx()); + let mut encoded = Vec::new(); + state.encode_snapshot_fast(&mut encoded); + assert!(encoded.is_empty()); + + let input = b"opaque-unknown-payload"; + let (value, rest) = UnknownState::decode_value(input).unwrap(); + assert_eq!(value, loro_common::LoroValue::Null); + assert_eq!(rest, input); + + let decoded = UnknownState::decode_snapshot_fast( + unknown_idx(), + (value, rest), + ContainerCreationContext { + configure: &Configure::default(), + peer: 0, + }, + ) + .unwrap(); + assert_eq!(decoded.container_idx(), unknown_idx()); + } +} diff --git a/vendor/loro-internal/src/state/value_decode.rs b/vendor/loro-internal/src/state/value_decode.rs new file mode 100644 index 0000000..4aa7a7f --- /dev/null +++ b/vendor/loro-internal/src/state/value_decode.rs @@ -0,0 +1,437 @@ +//! The postcard value layout is recursive, but reading it must not use the call +//! stack. Keep the shallow header variants in the same order as LoroValue's +//! binary Serialize implementation in loro-common/src/value.rs. + +use loro_common::{ContainerID, LoroError, LoroResult, LoroValue}; +use rustc_hash::FxHashMap; +use serde::Deserialize; +use std::collections::BTreeMap; + +#[derive(Deserialize)] +enum Header { + Null, + Bool(bool), + Double(f64), + I32(i64), + String(String), + List(usize), + Map(usize), + Container(ContainerID), + Binary(Vec<u8>), +} + +type Decoder<'a> = postcard::Deserializer<'a, postcard::de_flavors::Slice<'a>>; + +fn decode_error(err: postcard::Error) -> LoroError { + LoroError::DecodeError(format!("Decode snapshot value failed: {err}").into_boxed_str()) +} + +fn read<'a, T: Deserialize<'a>>(decoder: &mut Decoder<'a>) -> LoroResult<T> { + T::deserialize(decoder).map_err(decode_error) +} + +enum Collection { + List(Vec<LoroValue>), + Map(FxHashMap<String, LoroValue>), +} + +struct Frame { + left: usize, + collection: Collection, + key: Option<String>, +} + +impl Frame { + fn new(left: usize, is_map: bool) -> Self { + Self { + left, + // Do not reserve an untrusted length before reading any elements. + collection: if is_map { + Collection::Map(FxHashMap::default()) + } else { + Collection::List(Vec::new()) + }, + key: None, + } + } + + fn push(&mut self, value: LoroValue) { + match &mut self.collection { + Collection::List(list) => list.push(value), + Collection::Map(map) => { + map.insert(self.key.take().unwrap(), value); + } + } + self.left -= 1; + } + + fn into_value(self) -> LoroValue { + match self.collection { + Collection::List(list) => LoroValue::List(list.into()), + Collection::Map(map) => LoroValue::Map(map.into()), + } + } +} + +/// Read a bare postcard map/list followed by the remaining state metadata. +pub(super) fn decode_collection(bytes: &[u8], is_map: bool) -> LoroResult<(LoroValue, &[u8])> { + let mut decoder = Decoder::from_bytes(bytes); + let root = Frame::new(read(&mut decoder)?, is_map); + let value = decode(&mut decoder, Some(root))?; + Ok((value, decoder.finalize().map_err(decode_error)?)) +} + +/// Read a bare postcard map directly into the ordered lazy-value cache. +/// Nested values still use heap frames; never reserve an untrusted map length. +pub(super) fn decode_btree_map(bytes: &[u8]) -> LoroResult<(BTreeMap<String, LoroValue>, &[u8])> { + let mut decoder = Decoder::from_bytes(bytes); + let len: usize = read(&mut decoder)?; + let mut map = BTreeMap::new(); + for _ in 0..len { + let key = read(&mut decoder)?; + let value = decode_value_inner(&mut decoder)?; + map.insert(key, value); + } + Ok((map, decoder.finalize().map_err(decode_error)?)) +} + +/// Read one enum-tagged value embedded in an internal binary field. +pub(super) fn decode_value(bytes: &[u8]) -> LoroResult<(LoroValue, &[u8])> { + let mut decoder = Decoder::from_bytes(bytes); + let value = decode_value_inner(&mut decoder)?; + Ok((value, decoder.finalize().map_err(decode_error)?)) +} + +fn decode_value_inner(decoder: &mut Decoder<'_>) -> LoroResult<LoroValue> { + let value = match read::<Header>(decoder)? { + Header::Null => LoroValue::Null, + Header::Bool(v) => LoroValue::Bool(v), + Header::Double(v) => LoroValue::Double(v), + Header::I32(v) => LoroValue::I64(v), + Header::String(v) => LoroValue::String(v.into()), + Header::Container(v) => LoroValue::Container(v), + Header::Binary(v) => LoroValue::Binary(v.into()), + Header::List(len) => return decode(decoder, Some(Frame::new(len, false))), + Header::Map(len) => return decode(decoder, Some(Frame::new(len, true))), + }; + Ok(value) +} + +fn decode(decoder: &mut Decoder<'_>, root: Option<Frame>) -> LoroResult<LoroValue> { + let mut stack: Vec<_> = root.into_iter().collect(); + loop { + if let Some(frame) = stack.pop_if(|frame| frame.left == 0) { + let value = frame.into_value(); + if let Some(parent) = stack.last_mut() { + parent.push(value); + continue; + } + return Ok(value); + } + + if let Some(frame) = stack.last_mut() { + if matches!(frame.collection, Collection::Map(_)) { + frame.key = Some(read(decoder)?); + } + } + let value = match read::<Header>(decoder)? { + Header::Null => LoroValue::Null, + Header::Bool(v) => LoroValue::Bool(v), + Header::Double(v) => LoroValue::Double(v), + Header::I32(v) => LoroValue::I64(v), + Header::String(v) => LoroValue::String(v.into()), + Header::Container(v) => LoroValue::Container(v), + Header::Binary(v) => LoroValue::Binary(v.into()), + Header::List(len) => { + stack.push(Frame::new(len, false)); + continue; + } + Header::Map(len) => { + stack.push(Frame::new(len, true)); + continue; + } + }; + if let Some(frame) = stack.last_mut() { + frame.push(value); + } else { + return Ok(value); + } + } +} + +/// Write the same postcard enum layout without recursing through child values. +pub(super) fn encode_value<W: std::io::Write>( + value: &LoroValue, + mut writer: W, +) -> postcard::Result<()> { + enum Task<'a> { + Value(&'a LoroValue), + Key(&'a str), + } + let mut pending = vec![Task::Value(value)]; + while let Some(task) = pending.pop() { + let value = match task { + Task::Value(value) => value, + Task::Key(key) => { + postcard::to_io(key, &mut writer)?; + continue; + } + }; + let tag: u32 = match value { + LoroValue::Null => 0, + LoroValue::Bool(_) => 1, + LoroValue::Double(_) => 2, + LoroValue::I64(_) => 3, + LoroValue::String(_) => 4, + LoroValue::List(_) => 5, + LoroValue::Map(_) => 6, + LoroValue::Container(_) => 7, + LoroValue::Binary(_) => 8, + }; + postcard::to_io(&tag, &mut writer)?; + match value { + LoroValue::Null => {} + LoroValue::Bool(v) => { + postcard::to_io(v, &mut writer)?; + } + LoroValue::Double(v) => { + postcard::to_io(v, &mut writer)?; + } + LoroValue::I64(v) => { + postcard::to_io(v, &mut writer)?; + } + LoroValue::String(v) => { + postcard::to_io(&**v, &mut writer)?; + } + LoroValue::Container(v) => { + postcard::to_io(v, &mut writer)?; + } + LoroValue::Binary(v) => { + postcard::to_io(&**v, &mut writer)?; + } + LoroValue::List(v) => { + postcard::to_io(&v.len(), &mut writer)?; + pending.extend(v.iter().rev().map(Task::Value)); + } + LoroValue::Map(v) => { + postcard::to_io(&v.len(), &mut writer)?; + let start = pending.len(); + for (key, value) in v.iter() { + pending.push(Task::Key(key)); + pending.push(Task::Value(value)); + } + pending[start..].reverse(); + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use loro_common::{ContainerType, ID}; + + #[test] + fn postcard_layout_and_remaining_metadata() { + let values = vec![ + LoroValue::Null, + true.into(), + 1.25.into(), + i64::MIN.into(), + "a string".into(), + LoroValue::Binary(vec![0, 128, 255].into()), + ContainerID::new_root("text", ContainerType::Text).into(), + ContainerID::new_normal(ID::new(42, 5), ContainerType::Map).into(), + LoroValue::List(vec![1.into(), LoroValue::List(vec![].into())].into()), + LoroValue::Map(vec![("key".into(), "value".into())].into()), + ]; + for value in &values { + let mut encoded = Vec::new(); + encode_value(value, &mut encoded).unwrap(); + assert_eq!(encoded, postcard::to_stdvec(value).unwrap()); + encoded.extend([99, 100]); + let (decoded, rest) = decode_value(&encoded).unwrap(); + assert_eq!(&decoded, value); + assert_eq!(rest, &[99, 100]); + } + let mut bytes = postcard::to_stdvec(&values).unwrap(); + bytes.extend([99, 100]); + let (decoded, rest) = decode_collection(&bytes, false).unwrap(); + assert_eq!(decoded, LoroValue::List(values.clone().into())); + assert_eq!(rest, &[99, 100]); + let map: FxHashMap<_, _> = values + .into_iter() + .enumerate() + .map(|(i, value)| (i.to_string(), value)) + .collect(); + let bytes = postcard::to_stdvec(&map).unwrap(); + let (decoded, rest) = decode_collection(&bytes, true).unwrap(); + assert_eq!(decoded, LoroValue::Map(map.into())); + assert!(rest.is_empty()); + } + + #[test] + fn ordered_map_layout_duplicate_keys_and_remaining_metadata() { + let values = vec![ + LoroValue::Null, + true.into(), + 1.25.into(), + i64::MIN.into(), + "a string".into(), + LoroValue::Binary(vec![0, 128, 255].into()), + ContainerID::new_root("text", ContainerType::Text).into(), + ContainerID::new_normal(ID::new(42, 5), ContainerType::Map).into(), + LoroValue::List(vec![1.into(), LoroValue::List(vec![].into())].into()), + LoroValue::Map(vec![("nested".into(), "value".into())].into()), + LoroValue::Map(vec![].into()), + LoroValue::List(vec![].into()), + ]; + let expected: BTreeMap<_, _> = values + .into_iter() + .enumerate() + .map(|(i, value)| (format!("key{i}"), value)) + .collect(); + let mut bytes = postcard::to_stdvec(&expected).unwrap(); + bytes.extend([99, 100]); + let (decoded, rest) = decode_btree_map(&bytes).unwrap(); + assert_eq!(decoded, expected); + assert_eq!(rest, &[99, 100]); + let (old, old_rest): (BTreeMap<String, LoroValue>, _) = + postcard::take_from_bytes(&bytes).unwrap(); + assert_eq!(decoded, old); + assert_eq!(rest, old_rest); + + let mut duplicate = postcard::to_stdvec(&2usize).unwrap(); + for value in [1, 2] { + duplicate.extend(postcard::to_stdvec("same").unwrap()); + encode_value(&LoroValue::I64(value), &mut duplicate).unwrap(); + } + let (decoded, rest) = decode_btree_map(&duplicate).unwrap(); + assert_eq!(decoded, BTreeMap::from([("same".into(), 2.into())])); + assert!(rest.is_empty()); + let old: BTreeMap<String, LoroValue> = postcard::from_bytes(&duplicate).unwrap(); + assert_eq!(decoded, old); + let (empty, rest) = decode_btree_map(&[0, 99]).unwrap(); + assert!(empty.is_empty()); + assert_eq!(rest, &[99]); + } + + #[test] + fn ordered_map_rejects_truncated_values_and_untrusted_lengths() { + let map = BTreeMap::from([ + ("first".to_string(), LoroValue::from("a complete string")), + ( + "second".to_string(), + LoroValue::List(vec![1.into(), true.into()].into()), + ), + ]); + let bytes = postcard::to_stdvec(&map).unwrap(); + for end in 0..bytes.len() { + assert!(decode_btree_map(&bytes[..end]).is_err(), "prefix {end}"); + } + assert_eq!(decode_btree_map(&bytes).unwrap().0, map); + // A huge declared size with no entries must fail on input, without an + // allocation proportional to that size or a loop over absent entries. + let huge_len = postcard::to_stdvec(&usize::MAX).unwrap(); + assert!(decode_btree_map(&huge_len).is_err()); + assert!(decode_btree_map(&[255; 20]).is_err()); + // One valid key followed by an invalid enum tag must return an error. + let mut invalid = postcard::to_stdvec(&1usize).unwrap(); + invalid.extend(postcard::to_stdvec("key").unwrap()); + invalid.push(255); + assert!(decode_btree_map(&invalid).is_err()); + } + + #[test] + fn ordered_map_deep_values_and_error_cleanup_use_bounded_stack() { + std::thread::Builder::new() + .stack_size(1 << 20) + .spawn(|| { + let mut bytes = postcard::to_stdvec(&1usize).unwrap(); + bytes.extend(postcard::to_stdvec("value").unwrap()); + bytes.extend_from_slice(&deep_bytes(20_000)[1..]); + let (map, rest) = decode_btree_map(&bytes).unwrap(); + assert!(rest.is_empty()); + assert_eq!(map["value"].get_depth(), 20_000); + drop(map); + // Keep a fully decoded deep sibling alive until the next entry + // fails, exercising both returned-map and partial-map cleanup. + bytes[0] = 2; + let complete_entry_len = bytes.len(); + bytes.extend(postcard::to_stdvec("broken").unwrap()); + bytes.extend([6, 1, 1, b'a', 255]); + assert!(decode_btree_map(&bytes).is_err()); + // Replacing a duplicate key must also drop its previous deep + // value without recursing, before a later entry can fail. + bytes.truncate(complete_entry_len); + bytes.extend(postcard::to_stdvec("value").unwrap()); + encode_value(&LoroValue::I64(7), &mut bytes).unwrap(); + let (map, rest) = decode_btree_map(&bytes).unwrap(); + assert_eq!(map, BTreeMap::from([("value".into(), 7.into())])); + assert!(rest.is_empty()); + bytes[0] = 3; + bytes.extend(postcard::to_stdvec("broken").unwrap()); + bytes.push(255); + assert!(decode_btree_map(&bytes).is_err()); + }) + .unwrap() + .join() + .unwrap(); + } + + fn deep_bytes(depth: usize) -> Vec<u8> { + let mut bytes = vec![1]; // a bare one-element list + for i in 0..depth { + if i % 2 == 0 { + bytes.extend([6, 1, 1, b'a']); + } else { + bytes.extend([5, 1]); + } + } + bytes.extend([3, 0]); // I64(0) + bytes + } + + #[test] + fn deeply_nested_values_and_error_cleanup_use_bounded_stack() { + std::thread::Builder::new() + .stack_size(1 << 20) + .spawn(|| { + let mut bytes = deep_bytes(20_000); + let (value, rest) = decode_collection(&bytes, false).unwrap(); + assert!(rest.is_empty()); + assert_eq!(value.get_depth(), 20_001); + drop(value); + // A completed deep sibling must also be safely dropped on failure. + bytes[0] = 2; + bytes.push(255); + assert!(decode_collection(&bytes, false).is_err()); + assert!(decode_collection(&[255], true).is_err()); + }) + .unwrap() + .join() + .unwrap(); + } + + #[test] + fn generic_serde_depth_is_bounded_without_resetting_at_each_child() { + for tag in [5, 6] { + for depth in [128, 129, 20_000] { + let mut bytes = Vec::new(); + for _ in 0..depth { + bytes.extend([tag, 1]); + if tag == 6 { + bytes.extend([1, b'a']); + } + } + bytes.extend([3, 0]); + let result = postcard::from_bytes::<LoroValue>(&bytes); + assert_eq!(result.is_ok(), depth <= 128); + } + } + let siblings = vec![LoroValue::List(vec![].into()); 300]; + let bytes = postcard::to_stdvec(&LoroValue::List(siblings.into())).unwrap(); + assert!(postcard::from_bytes::<LoroValue>(&bytes).is_ok()); + } +} diff --git a/vendor/loro-internal/src/subscription.rs b/vendor/loro-internal/src/subscription.rs new file mode 100644 index 0000000..724f822 --- /dev/null +++ b/vendor/loro-internal/src/subscription.rs @@ -0,0 +1,232 @@ +use super::{ + arena::SharedArena, + event::{DiffEvent, DocDiff}, +}; +use crate::{ + container::idx::ContainerIdx, + utils::subscription::{DeferredPanic, SubscriberSet}, + ContainerDiff, LoroDoc, Subscription, +}; +use loro_common::{ContainerID, ID}; +use rustc_hash::FxHashMap; +use smallvec::SmallVec; +use std::{collections::VecDeque, sync::Arc}; + +use crate::sync::Mutex; +/// The callback of the local update. +pub type LocalUpdateCallback = Box<dyn Fn(&Vec<u8>) -> bool + Send + Sync + 'static>; +/// The callback of the peer id change. The second argument is the next counter for the peer. +pub type PeerIdUpdateCallback = Box<dyn Fn(&ID) -> bool + Send + Sync + 'static>; +#[allow(clippy::unused_unit)] +pub type Subscriber = Arc<dyn for<'a> Fn(DiffEvent<'a>) + Send + Sync>; + +impl LoroDoc { + /// Subscribe to the changes of the peer id. + pub fn subscribe_peer_id_change(&self, callback: PeerIdUpdateCallback) -> Subscription { + let (s, enable) = self.peer_id_change_subs.inner().insert((), callback); + enable(); + s + } +} + +struct ObserverInner { + subscriber_set: SubscriberSet<Option<ContainerIdx>, Subscriber>, + queue: Arc<Mutex<VecDeque<DocDiff>>>, +} + +impl Default for ObserverInner { + fn default() -> Self { + Self { + subscriber_set: SubscriberSet::new(), + queue: Arc::new(Mutex::new(VecDeque::new())), + } + } +} + +pub struct Observer { + inner: ObserverInner, + arena: SharedArena, +} + +impl std::fmt::Debug for Observer { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Observer").finish() + } +} + +impl Observer { + pub fn new(arena: SharedArena) -> Self { + Self { + arena, + inner: ObserverInner::default(), + } + } + + pub fn subscribe(&self, id: &ContainerID, callback: Subscriber) -> Subscription { + let idx = self.arena.register_container(id); + let inner = &self.inner; + let (sub, enable) = inner.subscriber_set.insert(Some(idx), callback); + enable(); + sub + } + + pub fn subscribe_root(&self, callback: Subscriber) -> Subscription { + let inner = &self.inner; + let (sub, enable) = inner.subscriber_set.insert(None, callback); + enable(); + sub + } + + pub(crate) fn emit(&self, doc_diff: DocDiff) { + let mut panic = DeferredPanic::default(); + let success = self.emit_inner(doc_diff, &mut panic); + if success { + let mut e = self.inner.queue.lock().pop_front(); + while let Some(event) = e { + self.emit_inner(event, &mut panic); + e = self.inner.queue.lock().pop_front(); + } + } + panic.resume(); + } + + // When emitting changes, we need to make sure that the observer is not locked. + /// A subscriber that panics does not stop the others; its panic is put in `panic`. + fn emit_inner(&self, doc_diff: DocDiff, panic: &mut DeferredPanic) -> bool { + let inner = &self.inner; + let mut container_events_map: FxHashMap<ContainerIdx, SmallVec<[&ContainerDiff; 1]>> = + Default::default(); + for container_diff in doc_diff.diff.iter() { + self.arena + .with_ancestors(container_diff.idx, |ancestor, _| { + if inner.subscriber_set.may_include(&Some(ancestor)) { + container_events_map + .entry(ancestor) + .or_default() + .push(container_diff); + } + }); + } + + { + // Check whether we are calling events recursively. + // If so, push the event to the queue + if inner.subscriber_set.is_recursive_calling(&None) + || container_events_map + .keys() + .any(|x| inner.subscriber_set.is_recursive_calling(&Some(*x))) + { + drop(container_events_map); + inner.queue.lock().push_back(doc_diff); + return false; + } + } + + for (container_idx, container_diffs) in container_events_map { + panic.run(|| { + inner + .subscriber_set + .retain(&Some(container_idx), &mut |callback| { + (callback)(DiffEvent { + current_target: Some( + self.arena.get_container_id(container_idx).unwrap(), + ), + events: &container_diffs, + event_meta: &doc_diff, + }); + true + }) + .unwrap() + }); + } + + let events: Vec<_> = doc_diff.diff.iter().collect(); + panic.run(|| { + inner + .subscriber_set + .retain(&None, &mut |callback| { + (callback)(DiffEvent { + current_target: None, + events: &events, + event_meta: &doc_diff, + }); + true + }) + .unwrap() + }); + + true + } +} + +#[cfg(test)] +mod test { + use std::sync::atomic::{AtomicUsize, Ordering}; + + use super::*; + use crate::{cursor::PosType, handler::HandlerTrait, LoroDoc}; + + #[test] + fn test_recursive_events() { + let loro = Arc::new(LoroDoc::new()); + let loro_cp = loro.clone(); + let count = Arc::new(AtomicUsize::new(0)); + let count_cp = Arc::clone(&count); + let _g = loro_cp.subscribe_root(Arc::new(move |_| { + count_cp.fetch_add(1, Ordering::SeqCst); + let mut txn = loro.txn().unwrap(); + let text = loro.get_text("id"); + if text.get_value().as_string().unwrap().len() > 10 { + return; + } + text.insert_with_txn(&mut txn, 0, "123", PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + })); + + let loro = loro_cp; + let mut txn = loro.txn().unwrap(); + let text = loro.get_text("id"); + text.insert_with_txn(&mut txn, 0, "123", PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + let count = count.load(Ordering::SeqCst); + assert!(count > 2, "{}", count); + } + + #[test] + fn unsubscribe() { + let loro = Arc::new(LoroDoc::new()); + let count = Arc::new(AtomicUsize::new(0)); + let count_cp = Arc::clone(&count); + let sub = loro.subscribe_root(Arc::new(move |_| { + count_cp.fetch_add(1, Ordering::SeqCst); + })); + + let text = loro.get_text("id"); + + assert_eq!(count.load(Ordering::SeqCst), 0); + { + let mut txn = loro.txn().unwrap(); + text.insert_with_txn(&mut txn, 0, "123", PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + } + assert_eq!(count.load(Ordering::SeqCst), 1); + { + let mut txn = loro.txn().unwrap(); + text.insert_with_txn(&mut txn, 0, "123", PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + } + assert_eq!(count.load(Ordering::SeqCst), 2); + sub.unsubscribe(); + { + let mut txn = loro.txn().unwrap(); + text.insert_with_txn(&mut txn, 0, "123", PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + } + assert_eq!(count.load(Ordering::SeqCst), 2); + } +} diff --git a/vendor/loro-internal/src/sync.rs b/vendor/loro-internal/src/sync.rs new file mode 100644 index 0000000..713ec8f --- /dev/null +++ b/vendor/loro-internal/src/sync.rs @@ -0,0 +1,178 @@ +#[cfg(loom)] +pub use loom::thread; +#[cfg(not(loom))] +pub use std::thread; + +#[cfg(loom)] +mod raw { + pub use loom::sync::{ + LockResult, Mutex as RawMutex, MutexGuard, RwLock as RawRwLock, RwLockReadGuard, + RwLockWriteGuard, + }; +} +#[cfg(not(loom))] +mod raw { + pub use std::sync::{ + LockResult, Mutex as RawMutex, MutexGuard, RwLock as RawRwLock, RwLockReadGuard, + RwLockWriteGuard, + }; +} + +pub use raw::{MutexGuard, RwLockReadGuard, RwLockWriteGuard}; + +#[cfg(loom)] +pub use loom::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicU8, AtomicUsize}; +#[cfg(not(loom))] +pub use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicU8, AtomicUsize}; + +#[cfg(loom)] +pub(crate) use my_thread_local::ThreadLocal; +#[cfg(not(loom))] +pub(crate) use thread_local::ThreadLocal; + +fn expect_not_poisoned<T>(result: raw::LockResult<T>, lock_kind: &str) -> T { + result.unwrap_or_else(|_| panic!("poisoned {lock_kind}")) +} + +#[derive(Debug)] +pub struct Mutex<T: ?Sized> { + inner: raw::RawMutex<T>, +} + +impl<T> Mutex<T> { + pub fn new(value: T) -> Self { + Self { + inner: raw::RawMutex::new(value), + } + } +} + +impl<T: ?Sized> Mutex<T> { + pub fn lock(&self) -> MutexGuard<'_, T> { + self.lock_with_kind("mutex") + } + + pub(crate) fn lock_with_kind(&self, lock_kind: &str) -> MutexGuard<'_, T> { + expect_not_poisoned(self.inner.lock(), lock_kind) + } + + /// For locks whose protected state stays valid across a panic (it is + /// restored by RAII during unwinding), so one panic does not block every + /// later caller. + pub(crate) fn lock_ignoring_poison(&self) -> MutexGuard<'_, T> { + self.inner + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + pub(crate) fn is_locked(&self) -> bool { + self.inner.try_lock().is_err() + } +} + +impl<T: Default> Default for Mutex<T> { + fn default() -> Self { + Self::new(T::default()) + } +} + +#[derive(Debug)] +pub struct RwLock<T> { + inner: raw::RawRwLock<T>, +} + +impl<T> RwLock<T> { + pub fn new(value: T) -> Self { + Self { + inner: raw::RawRwLock::new(value), + } + } + + pub fn into_inner(self) -> T { + expect_not_poisoned(self.inner.into_inner(), "rwlock") + } +} + +impl<T> RwLock<T> { + pub fn read(&self) -> RwLockReadGuard<'_, T> { + expect_not_poisoned(self.inner.read(), "rwlock") + } + + pub fn write(&self) -> RwLockWriteGuard<'_, T> { + expect_not_poisoned(self.inner.write(), "rwlock") + } +} + +impl<T: Default> Default for RwLock<T> { + fn default() -> Self { + Self::new(T::default()) + } +} + +#[cfg(loom)] +mod my_thread_local { + use std::sync::Arc; + + use super::thread; + use super::Mutex; + use rustc_hash::FxHashMap; + + #[derive(Debug)] + pub(crate) struct ThreadLocal<T> { + content: Arc<Mutex<FxHashMap<thread::ThreadId, Arc<T>>>>, + } + + impl<T: Default> ThreadLocal<T> { + pub fn new() -> Self { + Self { + content: Arc::new(Mutex::new(FxHashMap::default())), + } + } + + pub fn get_or_default(&self) -> Arc<T> { + let mut content = self.content.lock(); + let v = content + .entry(thread::current().id()) + .or_insert_with(|| Arc::new(T::default())); + v.clone() + } + } + + impl<T> Clone for ThreadLocal<T> { + fn clone(&self) -> Self { + Self { + content: self.content.clone(), + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[should_panic(expected = "poisoned mutex")] + fn mutex_lock_panics_after_poison() { + let lock = Mutex::new(7); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _guard = lock.lock(); + panic!("poison mutex"); + })); + + drop(lock.lock()); + } + + #[test] + #[should_panic(expected = "poisoned rwlock")] + fn rwlock_read_panics_after_poison() { + let lock = RwLock::new(7); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let mut guard = lock.write(); + *guard = 9; + panic!("poison rwlock"); + })); + + drop(lock.read()); + } +} diff --git a/vendor/loro-internal/src/tests/import_atomicity.rs b/vendor/loro-internal/src/tests/import_atomicity.rs new file mode 100644 index 0000000..66cfa75 --- /dev/null +++ b/vendor/loro-internal/src/tests/import_atomicity.rs @@ -0,0 +1,1091 @@ +use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, +}; + +use crate::{ + cursor::PosType, + encoding::json_schema::json::{JsonOpContent, JsonSchema, ListOp}, + loro::ExportMode, + state::fail_next_import_state_apply_for_test, + version::{Frontiers, VersionVector}, + LoroDoc, LoroError, TreeParentId, +}; + +fn pending_len(doc: &LoroDoc) -> usize { + doc.oplog().lock().pending_changes_len() +} + +#[test] +fn import_batch_snapshot_keeps_untouched_state_lazy() { + use crate::HandlerTrait; + let source = LoroDoc::new_auto_commit(); + source.set_peer_id(1).unwrap(); + for i in 0..64 { + source + .get_text(format!("text-{i}")) + .insert_unicode(0, "snapshot text") + .unwrap(); + } + let snapshot = source.export(ExportMode::Snapshot).unwrap(); + let vv = source.oplog_vv(); + source + .get_text("text-0") + .insert_unicode(0, "edit ") + .unwrap(); + let update = source.export(ExportMode::updates(&vv)).unwrap(); + + let split = LoroDoc::new(); + split.import(&snapshot).unwrap(); + split.import(&update).unwrap(); + let batch = LoroDoc::new(); + // Sorting must still put the full snapshot first. + let status = batch.import_batch(&[update, snapshot]).unwrap(); + assert!(status.pending.is_none()); + assert_eq!( + status.success, + crate::version::VersionRange::from_vv(&source.oplog_vv()) + ); + for doc in [&split, &batch] { + let untouched = doc.get_text("text-63").idx(); + assert!( + !doc.app_state().lock().store.has_decoded_state(untouched), + "snapshot bootstrap must not replay untouched container state" + ); + } + assert_eq!(batch.oplog_vv(), split.oplog_vv()); + assert_eq!(batch.state_frontiers(), split.state_frontiers()); + assert_eq!(batch.get_deep_value(), split.get_deep_value()); +} + +#[test] +fn import_batch_snapshot_checkout_failure_resets_state_and_history() { + let source = LoroDoc::new_auto_commit(); + source + .get_text("text") + .insert_unicode(0, "snapshot") + .unwrap(); + let snapshot = source.export(ExportMode::Snapshot).unwrap(); + let target = LoroDoc::new_auto_commit(); + // Existing handles and subscriptions must remain usable after rollback. + let text = target.get_text("text"); + let before = target.get_deep_value(); + let events = Arc::new(AtomicUsize::new(0)); + let counter = events.clone(); + let _sub = target.subscribe_root(Arc::new(move |_| { + counter.fetch_add(1, Ordering::SeqCst); + })); + let err = target + .import_batch(&[snapshot.clone(), malformed_binary_update(91)]) + .unwrap_err(); + assert!(err.to_string().contains("list diff"), "{err:?}"); + assert!(!target.is_detached()); + assert!(!target.oplog().lock().batch_importing); + assert_eq!(target.oplog_vv(), VersionVector::default()); + assert_eq!(target.state_frontiers(), Frontiers::default()); + assert_eq!(target.get_deep_value(), before); + assert_eq!(pending_len(&target), 0); + assert_eq!(events.load(Ordering::SeqCst), 0); + assert!(target.drop_pending_events().is_empty()); + text.insert_unicode(0, "still usable").unwrap(); + target.commit_then_renew(); + assert_eq!(text.to_string(), "still usable"); + target.import(&snapshot).unwrap(); + assert_eq!(target.state_frontiers(), target.oplog_frontiers()); +} + +#[test] +fn import_batch_snapshot_preserves_preexisting_pending_changes() { + let remote = LoroDoc::new_auto_commit(); + remote.set_peer_id(72).unwrap(); + remote.get_map("remote").insert("first", 1).unwrap(); + let base = remote.export(ExportMode::all_updates()).unwrap(); + let vv = remote.oplog_vv(); + remote.get_map("remote").insert("later", 2).unwrap(); + let pending = remote.export(ExportMode::updates(&vv)).unwrap(); + + let source = LoroDoc::new_auto_commit(); + source.set_peer_id(73).unwrap(); + source.get_map("source").insert("snapshot", 1).unwrap(); + let snapshot = source.export(ExportMode::Snapshot).unwrap(); + let vv = source.oplog_vv(); + source.get_map("source").insert("update", 2).unwrap(); + let update = source.export(ExportMode::updates(&vv)).unwrap(); + + let target = LoroDoc::new(); + target.import(&pending).unwrap(); + assert_eq!(pending_len(&target), 1); + let status = target.import_batch(&[snapshot, update]).unwrap(); + assert!(status.pending.is_some()); + assert_eq!(pending_len(&target), 1); + target.import(&base).unwrap(); + source.import(&base).unwrap(); + source.import(&pending).unwrap(); + assert_eq!(pending_len(&target), 0); + assert_eq!(target.get_deep_value(), source.get_deep_value()); + assert_eq!(target.oplog_vv(), source.oplog_vv()); +} + +#[test] +fn import_batch_snapshot_panic_keeps_prefix_attached() { + let source = LoroDoc::new_auto_commit(); + source.get_map("map").insert("snapshot", 1).unwrap(); + let snapshot = source.export(ExportMode::Snapshot).unwrap(); + let vv = source.oplog_vv(); + source.get_map("map").insert("update", 2).unwrap(); + let update = source.export(ExportMode::updates(&vv)).unwrap(); + let blobs = [snapshot.clone(), update]; + let target = LoroDoc::new_auto_commit(); + crate::loro::panic_at_batch_import_blob_for_test(1); + assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = target.import_batch(&blobs); + })) + .is_err()); + assert!(!target.is_detached()); + assert!(!target.oplog().lock().batch_importing); + assert_eq!(target.oplog_vv(), vv); + assert_eq!(target.state_frontiers(), target.oplog_frontiers()); + let expected = LoroDoc::new(); + expected.import(&snapshot).unwrap(); + assert_eq!(target.get_deep_value(), expected.get_deep_value()); + target.import_batch(&blobs).unwrap(); + assert_eq!(target.get_deep_value(), source.get_deep_value()); + target.get_map("map").insert("local", 3).unwrap(); +} + +#[test] +fn import_batch_snapshot_into_detached_empty_doc_only_updates_history() { + let source = LoroDoc::new_auto_commit(); + source + .get_text("text") + .insert_unicode(0, "snapshot") + .unwrap(); + let snapshot = source.export(ExportMode::Snapshot).unwrap(); + let vv = source.oplog_vv(); + source.get_text("text").insert_unicode(0, "update").unwrap(); + let update = source.export(ExportMode::updates(&vv)).unwrap(); + let target = LoroDoc::new(); + target.detach(); + target.import_batch(&[snapshot, update]).unwrap(); + assert!(target.is_detached()); + assert_eq!(target.state_frontiers(), Frontiers::default()); + assert_eq!(target.oplog_vv(), source.oplog_vv()); + assert_eq!(target.get_text("text").to_string(), ""); + target.attach(); + assert_eq!(target.get_deep_value(), source.get_deep_value()); +} + +fn corrupt_snapshot_state_bytes(snapshot: &mut [u8]) { + let body_start = 22; + let oplog_len = + u32::from_le_bytes(snapshot[body_start..body_start + 4].try_into().unwrap()) as usize; + let state_len_pos = body_start + 4 + oplog_len; + let state_len = u32::from_le_bytes( + snapshot[state_len_pos..state_len_pos + 4] + .try_into() + .unwrap(), + ) as usize; + assert!(state_len > 0); + let state_start = state_len_pos + 4; + snapshot[state_start] ^= 0xff; + + refresh_snapshot_checksum(snapshot); +} + +#[derive(Clone, Copy, Debug)] +enum SnapshotKvSection { + OpLog, + State, +} + +fn corrupt_snapshot_sstable_block(snapshot: &mut [u8], section: SnapshotKvSection) { + let body_start = 22; + let oplog_len = + u32::from_le_bytes(snapshot[body_start..body_start + 4].try_into().unwrap()) as usize; + let oplog_start = body_start + 4; + let state_len_pos = oplog_start + oplog_len; + let state_len = u32::from_le_bytes( + snapshot[state_len_pos..state_len_pos + 4] + .try_into() + .unwrap(), + ) as usize; + let state_start = state_len_pos + 4; + let (section_start, section_len) = match section { + SnapshotKvSection::OpLog => (oplog_start, oplog_len), + SnapshotKvSection::State => (state_start, state_len), + }; + + // SSTable layout starts with four magic bytes and one schema byte. Corrupt the first block + // payload while leaving its embedded checksum stale, then refresh only the outer envelope. + assert!(section_len > 9); + snapshot[section_start + 5] ^= 0xff; + refresh_snapshot_checksum(snapshot); +} + +fn refresh_snapshot_checksum(snapshot: &mut [u8]) { + let checksum = xxhash_rust::xxh32::xxh32(&snapshot[20..], u32::from_le_bytes(*b"LORO")); + snapshot[16..20].copy_from_slice(&checksum.to_le_bytes()); +} + +fn make_json_list_update_with_four_ops(peer: u64) -> (LoroDoc, JsonSchema) { + let doc = LoroDoc::new(); + doc.set_peer_id(peer).unwrap(); + let map = doc.get_map("map"); + let list = doc.get_list("list"); + let text = doc.get_text("text"); + + let mut txn = doc.txn().unwrap(); + map.insert_with_txn(&mut txn, "prefix", "map-value".into()) + .unwrap(); + list.insert_with_txn(&mut txn, 0, "seed".into()).unwrap(); + text.insert_with_txn(&mut txn, 0, "text-value", PosType::Unicode) + .unwrap(); + list.insert_with_txn(&mut txn, 1, "tail".into()).unwrap(); + txn.commit().unwrap(); + + let json = doc + .export_json_updates(&Default::default(), &doc.oplog_vv(), false) + .unwrap(); + assert_eq!(json.changes.len(), 1); + assert_eq!(json.changes[0].ops.len(), 4); + (doc, json) +} + +fn move_last_list_insert_far_out_of_bounds(json: &mut JsonSchema) { + let last_change = json.changes.last_mut().unwrap(); + let last_op = last_change.ops.last_mut().unwrap(); + match &mut last_op.content { + JsonOpContent::List(ListOp::Insert { pos, .. }) => { + *pos = 1_000; + } + other => panic!("expected list insert op, got {other:?}"), + } +} + +fn make_multi_peer_frontier_doc() -> LoroDoc { + let base = LoroDoc::new_auto_commit(); + base.set_peer_id(1).unwrap(); + base.get_map("map").insert("base", 0).unwrap(); + base.get_text("text").insert_unicode(0, "base").unwrap(); + let tree = base.get_tree("tree"); + let root = tree.create(TreeParentId::Root).unwrap(); + tree.get_meta(root).unwrap().insert("base", 0).unwrap(); + + let base_updates = base.export(ExportMode::all_updates()).unwrap(); + + let peer2 = base.fork(); + peer2.set_peer_id(2).unwrap(); + peer2.get_map("map").insert("p2", 2).unwrap(); + peer2.get_text("text").insert_unicode(0, "p2").unwrap(); + peer2.commit_then_renew(); + let peer2_updates = peer2.export(ExportMode::updates(&base.oplog_vv())).unwrap(); + + let peer3 = base.fork(); + peer3.set_peer_id(3).unwrap(); + peer3.get_map("map").insert("p3", 3).unwrap(); + let peer3_tree = peer3.get_tree("tree"); + let node = peer3_tree.create(TreeParentId::Root).unwrap(); + peer3_tree.get_meta(node).unwrap().insert("p3", 3).unwrap(); + peer3.commit_then_renew(); + let peer3_updates = peer3.export(ExportMode::updates(&base.oplog_vv())).unwrap(); + + let target = LoroDoc::new(); + target.import(&base_updates).unwrap(); + target.import(&peer2_updates).unwrap(); + target.import(&peer3_updates).unwrap(); + target +} + +fn assert_doc_unchanged( + doc: &LoroDoc, + vv: &VersionVector, + frontiers: &Frontiers, + state: &crate::LoroValue, +) { + assert_eq!(&doc.oplog_vv(), vv); + assert_eq!(&doc.oplog_frontiers(), frontiers); + assert_eq!(&doc.get_deep_value(), state); +} + +#[test] +fn failed_dependency_import_rolls_back_single_pending_change() { + let src = LoroDoc::new_auto_commit(); + src.set_peer_id(1).unwrap(); + let map = src.get_map("map"); + map.insert("seed", "base").unwrap(); + let update_base = src + .export(ExportMode::updates(&VersionVector::default())) + .unwrap(); + let version_base = src.oplog_vv(); + + map.insert("later", "value").unwrap(); + let update_later = src.export(ExportMode::updates(&version_base)).unwrap(); + + let dst = LoroDoc::new(); + dst.import(&update_later).unwrap(); + assert_eq!(pending_len(&dst), 1); + let vv_before_import = dst.oplog_vv(); + let frontiers_before_import = dst.oplog_frontiers(); + let state_before_import = dst.get_deep_value(); + + fail_next_import_state_apply_for_test(); + let err = dst.import(&update_base).unwrap_err(); + assert!( + err.to_string().contains("state apply failpoint"), + "unexpected error: {err:?}" + ); + assert_eq!(pending_len(&dst), 1); + assert_eq!(dst.oplog_vv(), vv_before_import); + assert_eq!(dst.oplog_frontiers(), frontiers_before_import); + assert_eq!(dst.get_deep_value(), state_before_import); + + dst.import(&update_base).unwrap(); + assert_eq!(pending_len(&dst), 0); + assert_eq!(dst.oplog_vv(), src.oplog_vv()); + assert_eq!(dst.oplog_frontiers(), src.oplog_frontiers()); + assert_eq!(dst.get_deep_value(), src.get_deep_value()); +} + +#[test] +fn failed_dependency_import_rolls_back_multiple_pending_changes() { + let base = LoroDoc::new_auto_commit(); + base.set_peer_id(1).unwrap(); + let map = base.get_map("map"); + map.insert("seed", "base").unwrap(); + let update_base = base + .export(ExportMode::updates(&VersionVector::default())) + .unwrap(); + let version_base = base.oplog_vv(); + + let peer2 = LoroDoc::new_auto_commit(); + peer2.set_peer_id(2).unwrap(); + peer2.import(&update_base).unwrap(); + peer2.get_map("map").insert("p2", "B").unwrap(); + let update_peer2 = peer2.export(ExportMode::updates(&version_base)).unwrap(); + + let peer3 = LoroDoc::new_auto_commit(); + peer3.set_peer_id(3).unwrap(); + peer3.import(&update_base).unwrap(); + peer3.get_map("map").insert("p3", "C").unwrap(); + let update_peer3 = peer3.export(ExportMode::updates(&version_base)).unwrap(); + + let expected = LoroDoc::new(); + expected.import(&update_base).unwrap(); + expected.import(&update_peer2).unwrap(); + expected.import(&update_peer3).unwrap(); + + let dst = LoroDoc::new(); + dst.import(&update_peer2).unwrap(); + dst.import(&update_peer3).unwrap(); + assert_eq!(pending_len(&dst), 2); + + let vv_before_import = dst.oplog_vv(); + let frontiers_before_import: Frontiers = dst.oplog_frontiers(); + let state_before_import = dst.get_deep_value(); + + fail_next_import_state_apply_for_test(); + let err = dst.import(&update_base).unwrap_err(); + assert!( + err.to_string().contains("state apply failpoint"), + "unexpected error: {err:?}" + ); + assert_eq!(pending_len(&dst), 2); + assert_eq!(dst.oplog_vv(), vv_before_import); + assert_eq!(dst.oplog_frontiers(), frontiers_before_import); + assert_eq!(dst.get_deep_value(), state_before_import); + + dst.import(&update_base).unwrap(); + assert_eq!(pending_len(&dst), 0); + assert_eq!(dst.oplog_vv(), expected.oplog_vv()); + assert_eq!(dst.oplog_frontiers(), expected.oplog_frontiers()); + assert_eq!(dst.get_deep_value(), expected.get_deep_value()); +} + +#[test] +fn failed_import_keeps_multi_peer_frontiers_intact() { + let target = make_multi_peer_frontier_doc(); + let vv_before_import = target.oplog_vv(); + assert!(vv_before_import.iter().count() >= 3); + let frontiers_before_import = target.oplog_frontiers(); + let state_before_import = target.get_deep_value(); + + let (_, mut bad_json) = make_json_list_update_with_four_ops(4); + move_last_list_insert_far_out_of_bounds(&mut bad_json); + let bad_json = serde_json::to_string(&bad_json).unwrap(); + + let err = target.import_json_updates(&bad_json).unwrap_err(); + assert!( + err.to_string().contains("list diff"), + "expected state list bounds validation, got {err:?}" + ); + assert_eq!(target.oplog_vv(), vv_before_import); + assert_eq!(target.oplog_frontiers(), frontiers_before_import); + assert_eq!(target.get_deep_value(), state_before_import); +} + +#[test] +fn malformed_json_import_returns_error_without_mutating_doc() { + let doc = make_multi_peer_frontier_doc(); + let vv_before_import = doc.oplog_vv(); + let frontiers_before_import = doc.oplog_frontiers(); + let state_before_import = doc.get_deep_value(); + + let err = doc + .import_json_updates("[3,{ \"(' k\" :\n\n42222 }]") + .unwrap_err(); + assert_eq!(err, LoroError::InvalidJsonSchema); + assert_doc_unchanged( + &doc, + &vv_before_import, + &frontiers_before_import, + &state_before_import, + ); +} + +#[test] +fn failed_import_does_not_emit_events() { + let doc = LoroDoc::new(); + let hit = Arc::new(AtomicUsize::new(0)); + let hit_cloned = hit.clone(); + let _sub = doc.subscribe_root(Arc::new(move |_event| { + hit_cloned.fetch_add(1, Ordering::SeqCst); + })); + + let (_, mut bad_json) = make_json_list_update_with_four_ops(7); + move_last_list_insert_far_out_of_bounds(&mut bad_json); + let bad_json = serde_json::to_string(&bad_json).unwrap(); + let err = doc.import_json_updates(&bad_json).unwrap_err(); + assert!( + err.to_string().contains("list diff"), + "expected state list bounds validation, got {err:?}" + ); + assert_eq!(hit.load(Ordering::SeqCst), 0); + assert!(doc.drop_pending_events().is_empty()); + + let (_, good_json) = make_json_list_update_with_four_ops(8); + let good_json = serde_json::to_string(&good_json).unwrap(); + doc.import_json_updates(&good_json).unwrap(); + assert!(hit.load(Ordering::SeqCst) > 0); +} + +/// Build a binary update blob that decodes into the `OpLog` fine but whose ops are +/// rejected by `DocState` validation (list insert far out of bounds). +fn malformed_binary_update(peer: u64) -> Vec<u8> { + let (_, mut bad_json) = make_json_list_update_with_four_ops(peer); + move_last_list_insert_far_out_of_bounds(&mut bad_json); + + // A detached doc records changes into the OpLog without applying them to state, + // so the malformed op survives into the exported binary updates. + let carrier = LoroDoc::new(); + carrier.detach(); + carrier + .import_json_updates(serde_json::to_string(&bad_json).unwrap()) + .unwrap(); + carrier.export(ExportMode::all_updates()).unwrap() +} + +fn doc_with_snapshot_and_pending_updates() -> (LoroDoc, Vec<Vec<u8>>, LoroDoc) { + let base = LoroDoc::new_auto_commit(); + base.set_peer_id(1).unwrap(); + base.get_text("text").insert_unicode(0, "base").unwrap(); + base.get_list("list").push("base").unwrap(); + base.commit_then_renew(); + let snapshot = base.export(ExportMode::Snapshot).unwrap(); + let base_vv = base.oplog_vv(); + + // A chain of updates from a second peer. Imported out of order, all but the + // first land in `pending_changes` until their deps arrive. + let peer2 = base.fork(); + peer2.set_peer_id(2).unwrap(); + let mut chain = Vec::new(); + let mut from = base_vv.clone(); + for i in 0..5 { + peer2.get_map("map").insert(&format!("k{i}"), i).unwrap(); + peer2.commit_then_renew(); + chain.push(peer2.export(ExportMode::updates(&from)).unwrap()); + from = peer2.oplog_vv(); + } + // Latest first: everything but the last blob stays pending while the batch runs. + chain.reverse(); + + let dst = LoroDoc::new_auto_commit(); + dst.set_peer_id(3).unwrap(); + dst.import(&snapshot).unwrap(); + (dst, chain, peer2) +} + +/// A blob whose ops only fail when they reach `DocState` used to panic inside the +/// batch reattach (`checkout to oplog frontiers should succeed`), unwinding past the +/// reattach and leaving the document detached — and every later import/export broken. +#[test] +fn import_batch_with_unappliable_update_stays_attached_and_rolls_back() { + let (dst, mut blobs, _) = doc_with_snapshot_and_pending_updates(); + blobs.insert(0, malformed_binary_update(21)); + + let vv_before = dst.oplog_vv(); + let frontiers_before = dst.oplog_frontiers(); + let state_before = dst.get_deep_value(); + + let err = dst + .import_batch(&blobs) + .expect_err("a state-rejected op must fail the batch"); + assert!( + err.to_string().contains("list diff"), + "expected state list bounds validation, got {err:?}" + ); + + assert!( + !dst.is_detached(), + "import_batch must leave the doc attached" + ); + assert!(!dst.oplog().lock().batch_importing); + assert_doc_unchanged(&dst, &vv_before, &frontiers_before, &state_before); + // The chain blobs were parked and then unlocked *within* the batch; its rollback + // must not resurrect them. A resurrected entry would carry `ContainerIdx` + // registrations the arena rollback just truncated. + assert_eq!( + pending_len(&dst), + 0, + "changes the batch itself parked must not survive its rollback" + ); + + // Still fully usable afterwards. + dst.get_text("text").insert_unicode(0, "after").unwrap(); + dst.commit_then_renew(); + assert_eq!(dst.state_frontiers(), dst.oplog_frontiers()); +} + +/// A batch can unlock changes that were parked *before* it started. If the batch is +/// rolled back, those changes must be re-parked, or the document would silently drop +/// them and diverge once their deps finally arrive. +#[test] +fn failed_import_batch_reparks_prebatch_pending_changes() { + let src = LoroDoc::new_auto_commit(); + src.set_peer_id(1).unwrap(); + src.get_map("map").insert("seed", "base").unwrap(); + let update_base = src + .export(ExportMode::updates(&VersionVector::default())) + .unwrap(); + let version_base = src.oplog_vv(); + src.get_map("map").insert("later", "value").unwrap(); + let update_later = src.export(ExportMode::updates(&version_base)).unwrap(); + + let dst = LoroDoc::new(); + dst.import(&update_later).unwrap(); + assert_eq!(pending_len(&dst), 1); + let vv_before = dst.oplog_vv(); + let frontiers_before = dst.oplog_frontiers(); + let state_before = dst.get_deep_value(); + + // `update_base` unlocks the pre-batch pending change mid-batch; the malformed + // blob then makes the closing reattach fail and rolls the whole batch back. + let err = dst + .import_batch(&[update_base.clone(), malformed_binary_update(31)]) + .expect_err("the malformed blob must fail the whole batch"); + assert!(err.to_string().contains("list diff"), "{err:?}"); + assert!(!dst.is_detached()); + assert_eq!( + pending_len(&dst), + 1, + "the pending change the batch unlocked must be re-parked" + ); + assert_doc_unchanged(&dst, &vv_before, &frontiers_before, &state_before); + + // Retrying without the bad blob applies base and unlocks the re-parked change. + dst.import(&update_base).unwrap(); + assert_eq!(pending_len(&dst), 0); + assert_eq!(dst.oplog_vv(), src.oplog_vv()); + assert_eq!(dst.get_deep_value(), src.get_deep_value()); +} + +/// Changes are parked under the ID of the dep they are missing, so two peers waiting +/// on the same change share one pending slot. When a batch appends to a slot that +/// already held a pre-batch change, rollback has to trim its own entry off and keep +/// the older one — dropping the slot loses a change the document still needs, and +/// keeping both resurrects a change whose arena registrations were just truncated. +#[test] +fn failed_import_batch_trims_only_its_own_entry_from_a_shared_pending_slot() { + let p1 = LoroDoc::new_auto_commit(); + p1.set_peer_id(1).unwrap(); + p1.get_map("map").insert("seed", "v").unwrap(); + p1.commit_then_renew(); + // Never shipped to `dst`, so everything below stays parked on it. + let u_seed = p1 + .export(ExportMode::updates(&VersionVector::default())) + .unwrap(); + let vv_seed = p1.oplog_vv(); + + let waiter = |peer: u64, key: &str| { + let d = LoroDoc::new_auto_commit(); + d.set_peer_id(peer).unwrap(); + d.import(&u_seed).unwrap(); + d.get_map("map").insert(key, "v").unwrap(); + d.commit_then_renew(); + d.export(ExportMode::updates(&vv_seed)).unwrap() + }; + let u_p2 = waiter(2, "p2"); + let u_p3 = waiter(3, "p3"); + + let dst = LoroDoc::new_auto_commit(); + dst.set_peer_id(9).unwrap(); + dst.import(&u_p2).unwrap(); + assert_eq!(pending_len(&dst), 1, "p2 waits on the seed change"); + let vv_before = dst.oplog_vv(); + let frontiers_before = dst.oplog_frontiers(); + let state_before = dst.get_deep_value(); + + // `u_p3` parks in the same slot as `u_p2`; the malformed blob then fails the + // closing reattach and rolls the whole batch back. + let err = dst + .import_batch(&[u_p3.clone(), malformed_binary_update(41)]) + .expect_err("the malformed blob must fail the whole batch"); + assert!(err.to_string().contains("list diff"), "{err:?}"); + assert!(!dst.is_detached()); + assert_eq!( + pending_len(&dst), + 1, + "rollback must keep the pre-batch change and drop only the batch's own" + ); + assert_doc_unchanged(&dst, &vv_before, &frontiers_before, &state_before); + + // The kept change is still the right one, and the doc converges on a retry. + dst.import(&u_seed).unwrap(); + assert_eq!(pending_len(&dst), 0, "the seed unlocks the kept p2 change"); + dst.import(&u_p3).unwrap(); + + let expected = LoroDoc::new_auto_commit(); + expected.set_peer_id(8).unwrap(); + expected.import(&u_seed).unwrap(); + expected.import(&u_p2).unwrap(); + expected.import(&u_p3).unwrap(); + assert_eq!(dst.oplog_vv(), expected.oplog_vv()); + assert_eq!(dst.get_deep_value(), expected.get_deep_value()); +} + +/// One blob can both park a change and unlock it in the same import: B1 parks while +/// A1 is missing, B0 unlocks A1, and the cascade then applies B1. If that import's +/// state apply fails, rollback must re-park only what was pending *before* the +/// import — resurrecting the import's own parked changes would leave pending entries +/// whose arena registrations were just rolled back. +#[test] +fn failed_import_reparks_only_preexisting_pending_changes() { + use loro_common::IdSpan; + + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + a.get_text("text").insert_unicode(0, "A0").unwrap(); + let u_a0 = a + .export(ExportMode::updates(&VersionVector::default())) + .unwrap(); + let vv_a0 = a.oplog_vv(); + let a_counter_after_a0 = *vv_a0.get(&1).unwrap(); + + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(2).unwrap(); + b.import(&u_a0).unwrap(); + b.get_text("text").insert_unicode(2, "B0").unwrap(); + let u_b0 = b.export(ExportMode::updates(&vv_a0)).unwrap(); + + a.import(&u_b0).unwrap(); + a.get_text("text").insert_unicode(4, "A1").unwrap(); + let a_counter_after_a1 = *a.oplog_vv().get(&1).unwrap(); + // Peer-A ops only (A1), without B0 — pending on a doc that only has A0. + let u_a1_only = a + .export(ExportMode::updates_in_range(vec![IdSpan::new( + 1, + a_counter_after_a0, + a_counter_after_a1, + )])) + .unwrap(); + + b.import(&u_a1_only).unwrap(); + b.get_text("text").insert_unicode(6, "B1").unwrap(); + // Single blob with B0 and B1; B1 depends on A1. + let u_b0_b1 = b.export(ExportMode::updates(&vv_a0)).unwrap(); + + let d = LoroDoc::new_auto_commit(); + d.set_peer_id(3).unwrap(); + d.import(&u_a0).unwrap(); + d.import(&u_a1_only).unwrap(); + assert_eq!(pending_len(&d), 1); + let vv_before = d.oplog_vv(); + let frontiers_before = d.oplog_frontiers(); + let state_before = d.get_deep_value(); + + fail_next_import_state_apply_for_test(); + let err = d.import(&u_b0_b1).unwrap_err(); + assert!(err.to_string().contains("state apply failpoint"), "{err:?}"); + assert_eq!( + pending_len(&d), + 1, + "only the pre-import pending change may be re-parked" + ); + assert_doc_unchanged(&d, &vv_before, &frontiers_before, &state_before); + + // Retrying converges. + d.import(&u_b0_b1).unwrap(); + assert_eq!(pending_len(&d), 0); + assert_eq!(d.oplog_vv(), b.oplog_vv()); + assert_eq!(d.get_deep_value(), b.get_deep_value()); +} + +/// The same guarantee for a panic (malformed remote data reaching an `unreachable!` +/// in decode/apply is the shape that originally stranded the document). The blobs +/// imported before the panic must still be applied to `DocState`. +#[test] +fn import_batch_panic_leaves_doc_attached() { + let (dst, blobs, expected) = doc_with_snapshot_and_pending_updates(); + assert!(blobs.len() > 2); + + crate::loro::panic_at_batch_import_blob_for_test(2); + let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = dst.import_batch(&blobs); + })); + assert!(panicked.is_err(), "the failpoint should have panicked"); + + assert!( + !dst.is_detached(), + "import_batch must leave the doc attached" + ); + assert!(!dst.oplog().lock().batch_importing); + assert_eq!(dst.state_frontiers(), dst.oplog_frontiers()); + + // The document still accepts the updates it missed. + dst.import_batch(&blobs).unwrap(); + assert!(!dst.is_detached()); + assert_eq!(dst.oplog_vv(), expected.oplog_vv()); + assert_eq!(dst.get_deep_value(), expected.get_deep_value()); +} + +/// A doc that was already detached must stay detached: the batch is only allowed to +/// restore the pre-batch mode, not to silently attach. +#[test] +fn import_batch_keeps_explicitly_detached_doc_detached() { + let (dst, blobs, _) = doc_with_snapshot_and_pending_updates(); + dst.detach(); + let state_frontiers = dst.state_frontiers(); + + dst.import_batch(&blobs).unwrap(); + assert!(dst.is_detached()); + assert_eq!(dst.state_frontiers(), state_frontiers); + assert!(!dst.oplog().lock().batch_importing); +} + +#[test] +fn corrupt_snapshot_import_rolls_back_empty_doc() { + let src = LoroDoc::new_auto_commit(); + src.set_peer_id(9).unwrap(); + src.get_text("text").insert_unicode(0, "snapshot").unwrap(); + src.get_list("list").push("value").unwrap(); + let snapshot = src.export(ExportMode::Snapshot).unwrap(); + let mut corrupt_snapshot = snapshot.clone(); + corrupt_snapshot_state_bytes(&mut corrupt_snapshot); + + let dst = LoroDoc::new(); + let vv_before_import = dst.oplog_vv(); + let frontiers_before_import = dst.oplog_frontiers(); + let state_before_import = dst.get_deep_value(); + let err = dst.import(&corrupt_snapshot).unwrap_err(); + assert!( + err.to_string().contains("decode_snapshot") + || err.to_string().contains("Decode") + || err.to_string().contains("snapshot"), + "unexpected error: {err:?}" + ); + assert_eq!(dst.oplog_vv(), vv_before_import); + assert_eq!(dst.oplog_frontiers(), frontiers_before_import); + assert_eq!(dst.get_deep_value(), state_before_import); + assert!(dst.oplog().lock().is_empty()); + + dst.import(&snapshot).unwrap(); + assert_eq!(dst.get_deep_value(), src.get_deep_value()); +} + +#[test] +fn corrupt_snapshot_batch_preserves_empty_handles() { + let source = LoroDoc::new_auto_commit(); + source + .get_text("text") + .insert_unicode(0, "snapshot") + .unwrap(); + let mut snapshot = source.export(ExportMode::Snapshot).unwrap(); + corrupt_snapshot_state_bytes(&mut snapshot); + let empty_update = LoroDoc::new().export(ExportMode::all_updates()).unwrap(); + let target = LoroDoc::new_auto_commit(); + let text = target.get_text("existing"); + let before = target.get_deep_value(); + assert!(target.import_batch(&[snapshot, empty_update]).is_err()); + assert!(!target.is_detached()); + assert_eq!(target.get_deep_value(), before); + assert_eq!(target.oplog_vv(), VersionVector::default()); + text.insert_unicode(0, "usable").unwrap(); + assert_eq!(text.to_string(), "usable"); +} + +#[test] +fn snapshot_import_rejects_corrupt_inner_sstable_with_valid_envelope_checksum() { + let src = LoroDoc::new_auto_commit(); + src.set_peer_id(9).unwrap(); + src.get_map("map").insert("key", "value").unwrap(); + let snapshot = src.export(ExportMode::Snapshot).unwrap(); + + for section in [SnapshotKvSection::OpLog, SnapshotKvSection::State] { + let mut corrupted = snapshot.clone(); + corrupt_snapshot_sstable_block(&mut corrupted, section); + + let dst = LoroDoc::new(); + let err = dst + .import(&corrupted) + .expect_err("invalid inner SSTable checksum must fail during import"); + assert!( + err.to_string().contains("checksum") || err.to_string().contains("Checksum"), + "unexpected {section:?} import error: {err:?}" + ); + assert!(dst.oplog().lock().is_empty()); + assert!(dst + .get_deep_value() + .as_map() + .is_some_and(|value| value.is_empty())); + } +} + +/// A change whose deps are before the shallow root is rejected AND dropped: +/// it must not linger in the pending store, where it could never be unlocked. +/// Locks in the "dropped, not pending" guarantee documented by +/// `loro/tests/shallow_snapshot_concurrency.rs`. +#[test] +fn outdated_update_on_shallow_doc_is_dropped_not_pending() { + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + a.get_map("m").insert("a", 1).unwrap(); + a.commit_then_renew(); + let v_vv = a.oplog_vv(); + let v_frontiers = a.oplog_frontiers(); + a.get_map("m").insert("b", 2).unwrap(); + a.commit_then_renew(); + let f = a.oplog_frontiers(); + a.get_map("m").insert("c", 3).unwrap(); + a.commit_then_renew(); + + // B is bootstrapped from the shallow snapshot at F. + let b = LoroDoc::new(); + b.import(&a.export(ExportMode::shallow_snapshot(&f)).unwrap()) + .unwrap(); + assert_eq!(pending_len(&b), 0); + + // C holds full history up to V and edits on top of it, concurrent with F. + let c = LoroDoc::new(); + c.import(&a.export(ExportMode::snapshot_at(&v_frontiers)).unwrap()) + .unwrap(); + c.set_peer_id(2).unwrap(); + c.get_map("m").insert("from_c", true).unwrap(); + c.commit_then_renew(); + let updates = c.export(ExportMode::updates(&v_vv)).unwrap(); + + let err = b.import(&updates).unwrap_err(); + assert!(matches!( + err, + LoroError::ImportUpdatesThatDependsOnOutdatedVersion + )); + assert_eq!( + pending_len(&b), + 0, + "outdated changes must be dropped, not parked as pending" + ); +} + +/// Binary update whose movable-list move targets an element that never existed. +/// The public import paths reject it, so the carrier inserts the decoded change +/// straight into its oplog to obtain the bytes. +fn binary_update_moving_unknown_movable_list_elem() -> (LoroDoc, Vec<u8>) { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let list = doc.get_movable_list("list"); + list.insert(0, "a").unwrap(); + list.insert(1, "b").unwrap(); + doc.commit_then_renew(); + + let json = serde_json::json!({ + "schema_version": 1, + "start_version": {}, + "peers": ["1"], + "changes": [{ + "id": "2@0", "timestamp": 0, "deps": ["1@0"], "lamport": 2, "msg": null, + "ops": [{ + "container": "cid:root-list:MovableList", + "content": {"type": "move", "from": 0, "to": 1, "elem_id": "L99@0"}, + "counter": 2 + }] + }] + }); + let bytes = binary_update_bypassing_validation(&doc, json); + (doc, bytes) +} + +/// Encode the JSON `changes` on top of `doc` as a binary update. The carrier inserts +/// the decoded changes straight into its oplog, so no import validation runs. +fn binary_update_bypassing_validation(doc: &LoroDoc, json: serde_json::Value) -> Vec<u8> { + let carrier = LoroDoc::new(); + carrier + .import(&doc.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + let json: JsonSchema = serde_json::from_value(json).unwrap(); + { + let mut oplog = carrier.oplog().lock(); + let changes = + crate::encoding::json_schema::decode_json_changes(json, &oplog.arena).unwrap(); + crate::encoding::apply_decoded_changes_to_oplog(&mut oplog, changes).unwrap(); + } + carrier + .export(ExportMode::updates(&doc.oplog_vv())) + .unwrap() +} + +/// Peer 2 edits a map, and peer 3 moves an unknown element in a change that depends on +/// peer 2's. The import preflight used to skip peer 3's ops because its deps were not +/// in the DAG yet, so the blob was imported without a rollback scope or validation. +#[test] +fn binary_forged_move_behind_same_blob_dependency_is_rejected() { + let (doc, _) = binary_update_moving_unknown_movable_list_elem(); + let json = serde_json::json!({ + "schema_version": 1, + "start_version": {}, + "peers": ["1", "2", "3"], + "changes": [ + { + "id": "0@1", "timestamp": 0, "deps": ["1@0"], "lamport": 2, "msg": null, + "ops": [{ + "container": "cid:root-meta:Map", + "content": {"type": "insert", "key": "k", "value": 1}, + "counter": 0 + }] + }, + { + "id": "0@2", "timestamp": 0, "deps": ["0@1"], "lamport": 3, "msg": null, + "ops": [{ + "container": "cid:root-list:MovableList", + "content": {"type": "move", "from": 0, "to": 1, "elem_id": "L99@0"}, + "counter": 0 + }] + } + ] + }); + let bad = binary_update_bypassing_validation(&doc, json); + let vv_before = doc.oplog_vv(); + let frontiers_before = doc.oplog_frontiers(); + let state_before = doc.get_deep_value(); + + let err = doc.import(&bad).unwrap_err(); + assert!(matches!(err, LoroError::DecodeError(_)), "{err:?}"); + assert_doc_unchanged(&doc, &vv_before, &frontiers_before, &state_before); + + let err = doc.import_batch(std::slice::from_ref(&bad)).unwrap_err(); + assert!(matches!(err, LoroError::DecodeError(_)), "{err:?}"); + assert!(!doc.is_detached()); + assert_doc_unchanged(&doc, &vv_before, &frontiers_before, &state_before); + + doc.detach(); + let err = doc.import(&bad).unwrap_err(); + assert!(matches!(err, LoroError::DecodeError(_)), "{err:?}"); + doc.attach(); + assert_doc_unchanged(&doc, &vv_before, &frontiers_before, &state_before); + + doc.get_movable_list("list").mov(0, 1).unwrap(); + doc.commit_then_renew(); + assert_eq!(doc.state_frontiers(), doc.oplog_frontiers()); +} + +#[test] +fn binary_move_of_unknown_movable_list_elem_is_rejected_atomically() { + let (doc, bad) = binary_update_moving_unknown_movable_list_elem(); + let vv_before = doc.oplog_vv(); + let frontiers_before = doc.oplog_frontiers(); + let state_before = doc.get_deep_value(); + + let err = doc.import(&bad).unwrap_err(); + assert!(matches!(err, LoroError::DecodeError(_)), "{err:?}"); + assert_doc_unchanged(&doc, &vv_before, &frontiers_before, &state_before); + + doc.detach(); + let err = doc.import(&bad).unwrap_err(); + assert!(matches!(err, LoroError::DecodeError(_)), "{err:?}"); + doc.attach(); + assert_doc_unchanged(&doc, &vv_before, &frontiers_before, &state_before); + + doc.get_movable_list("list").mov(0, 1).unwrap(); + doc.commit_then_renew(); + assert_eq!(doc.state_frontiers(), doc.oplog_frontiers()); +} + +/// Blobs inside an attached `import_batch` are imported detached, so their element +/// references are validated once in `BatchImportGuard::finish`. +#[test] +fn import_batch_with_move_of_unknown_movable_list_elem_rolls_back() { + let (doc, bad) = binary_update_moving_unknown_movable_list_elem(); + let valid = LoroDoc::new_auto_commit(); + valid.set_peer_id(2).unwrap(); + valid + .import(&doc.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + valid.get_movable_list("list").push("v".into()).unwrap(); + valid.commit_then_renew(); + let valid_update = valid.export(ExportMode::updates(&doc.oplog_vv())).unwrap(); + + let vv_before = doc.oplog_vv(); + let frontiers_before = doc.oplog_frontiers(); + let state_before = doc.get_deep_value(); + + let err = doc.import_batch(&[valid_update, bad]).unwrap_err(); + assert!(matches!(err, LoroError::DecodeError(_)), "{err:?}"); + assert!(!doc.is_detached()); + assert!(!doc.oplog().lock().batch_importing); + assert_doc_unchanged(&doc, &vv_before, &frontiers_before, &state_before); + + doc.get_movable_list("list").mov(0, 1).unwrap(); + doc.commit_then_renew(); + assert_eq!(doc.state_frontiers(), doc.oplog_frontiers()); +} + +#[test] +fn detached_text_import_that_unlocks_invalid_movable_list_ops_rolls_back() { + let (doc, _) = binary_update_moving_unknown_movable_list_elem(); + let text_peer = LoroDoc::new_auto_commit(); + text_peer.set_peer_id(2).unwrap(); + text_peer + .import(&doc.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + text_peer + .get_text("t") + .insert(0, "unlock", PosType::Unicode) + .unwrap(); + text_peer.commit_then_renew(); + let text_update = text_peer + .export(ExportMode::updates(&doc.oplog_vv())) + .unwrap(); + let bad = binary_update_bypassing_validation( + &text_peer, + serde_json::json!({ + "schema_version": 1, "start_version": {}, "peers": ["2", "3"], + "changes": [{ + "id": "0@1", "timestamp": 0, "deps": ["0@0"], "lamport": 8, "msg": null, + "ops": [{ + "container": "cid:root-list:MovableList", "counter": 0, + "content": {"type": "move", "from": 0, "to": 1, "elem_id": "L99@0"} + }] + }] + }), + ); + let vv = doc.oplog_vv(); + let frontiers = doc.oplog_frontiers(); + let state = doc.get_deep_value(); + doc.detach(); + doc.import(&bad).unwrap(); + let pending_before = doc.oplog().lock().pending_changes_len(); + assert!(pending_before > 0); + let err = doc.import(&text_update).unwrap_err(); + assert!(matches!(err, LoroError::DecodeError(_)), "{err:?}"); + assert!(doc.is_detached()); + assert_eq!(doc.oplog().lock().pending_changes_len(), pending_before); + doc.attach(); + assert_doc_unchanged(&doc, &vv, &frontiers, &state); +} diff --git a/vendor/loro-internal/src/tests/mod.rs b/vendor/loro-internal/src/tests/mod.rs new file mode 100644 index 0000000..201ede2 --- /dev/null +++ b/vendor/loro-internal/src/tests/mod.rs @@ -0,0 +1,51 @@ +#[ctor::ctor] +fn init() { + dev_utils::setup_test_log(); +} + +mod import_atomicity; +mod op_count; +mod replay_base; +mod text_arena_growth; + +use crate::{op::ListSlice, LoroValue}; + +/// Two-way sync of two docs. +pub(crate) fn exchange(a: &crate::LoroDoc, b: &crate::LoroDoc) { + let ua = a + .export(crate::loro::ExportMode::updates(&b.oplog_vv())) + .unwrap(); + let ub = b + .export(crate::loro::ExportMode::updates(&a.oplog_vv())) + .unwrap(); + a.import(&ub).unwrap(); + b.import(&ua).unwrap(); +} + +pub const PROPTEST_FACTOR_10: usize = 1; +pub const PROPTEST_FACTOR_1: usize = 0; + +#[test] +fn size_of() { + use crate::change::Change; + use crate::{ + container::{map::MapSet, ContainerID}, + id::ID, + op::{Op, RawOpContent}, + span::IdSpan, + InternalString, + }; + + println!("Change {}", std::mem::size_of::<Change>()); + println!("Op {}", std::mem::size_of::<Op>()); + println!("InsertContent {}", std::mem::size_of::<RawOpContent>()); + println!("MapSet {}", std::mem::size_of::<MapSet>()); + println!("ListSlice {}", std::mem::size_of::<ListSlice>()); + println!("LoroValue {}", std::mem::size_of::<LoroValue>()); + println!("ID {}", std::mem::size_of::<ID>()); + println!("Vec {}", std::mem::size_of::<Vec<ID>>()); + println!("IdSpan {}", std::mem::size_of::<IdSpan>()); + println!("ContainerID {}", std::mem::size_of::<ContainerID>()); + println!("InternalString {}", std::mem::size_of::<InternalString>()); +} +mod undo_atomicity; diff --git a/vendor/loro-internal/src/tests/op_count.rs b/vendor/loro-internal/src/tests/op_count.rs new file mode 100644 index 0000000..1980d30 --- /dev/null +++ b/vendor/loro-internal/src/tests/op_count.rs @@ -0,0 +1,107 @@ +use crate::{ + loro::ExportMode, state::fail_next_import_state_apply_for_test, version::VersionVector, LoroDoc, +}; +use std::sync::atomic::Ordering::{Acquire, Release}; + +fn assert_visible_op_count_cache_matches_exact(doc: &LoroDoc) { + let exact = doc.oplog().lock().visible_op_count_exact(); + assert_eq!(doc.visible_op_count.load(Acquire), exact); + + let _state = doc.app_state().lock(); + assert_eq!(doc.len_ops(), exact); +} + +#[test] +fn len_ops_is_available_while_state_is_locked_with_local_ops() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + doc.get_map("map").insert("k", 1).unwrap(); + + let _state = doc.app_state().lock(); + assert_eq!(doc.len_ops(), 1); +} + +#[test] +fn len_ops_tracks_snapshot_import_while_state_is_locked() { + let src = LoroDoc::new_auto_commit(); + src.set_peer_id(2).unwrap(); + src.get_map("map").insert("k", 1).unwrap(); + src.commit_then_renew(); + let expected = src.len_ops(); + let snapshot = src.export(ExportMode::Snapshot).unwrap(); + + let dst = LoroDoc::new(); + dst.import(&snapshot).unwrap(); + + let _state = dst.app_state().lock(); + assert_eq!(dst.len_ops(), expected); +} + +#[test] +fn len_ops_prefers_exact_oplog_value_when_lock_order_allows() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(3).unwrap(); + doc.get_map("map").insert("k", 1).unwrap(); + + doc.visible_op_count.store(0, Release); + assert_eq!(doc.len_ops(), 1); +} + +#[test] +fn visible_op_count_cache_tracks_pending_activation() { + let src = LoroDoc::new_auto_commit(); + src.set_peer_id(4).unwrap(); + let map = src.get_map("map"); + map.insert("base", "base").unwrap(); + let update_base = src + .export(ExportMode::updates(&VersionVector::default())) + .unwrap(); + let version_base = src.oplog_vv(); + + map.insert("later", "later").unwrap(); + let update_later = src.export(ExportMode::updates(&version_base)).unwrap(); + + let dst = LoroDoc::new(); + let status = dst.import(&update_later).unwrap(); + assert!(status.pending.is_some()); + assert_visible_op_count_cache_matches_exact(&dst); + assert_eq!(dst.len_ops(), 0); + + let status = dst.import(&update_base).unwrap(); + assert!(status.pending.is_none()); + assert_eq!(dst.len_ops(), src.len_ops()); + assert_visible_op_count_cache_matches_exact(&dst); +} + +#[test] +fn visible_op_count_cache_rolls_back_after_failed_pending_activation() { + let src = LoroDoc::new_auto_commit(); + src.set_peer_id(5).unwrap(); + let map = src.get_map("map"); + map.insert("base", "base").unwrap(); + let update_base = src + .export(ExportMode::updates(&VersionVector::default())) + .unwrap(); + let version_base = src.oplog_vv(); + + map.insert("later", "later").unwrap(); + let update_later = src.export(ExportMode::updates(&version_base)).unwrap(); + + let dst = LoroDoc::new(); + dst.import(&update_later).unwrap(); + assert_eq!(dst.len_ops(), 0); + assert_visible_op_count_cache_matches_exact(&dst); + + fail_next_import_state_apply_for_test(); + let err = dst.import(&update_base).unwrap_err(); + assert!( + err.to_string().contains("state apply failpoint"), + "unexpected error: {err:?}" + ); + assert_eq!(dst.len_ops(), 0); + assert_visible_op_count_cache_matches_exact(&dst); + + dst.import(&update_base).unwrap(); + assert_eq!(dst.len_ops(), src.len_ops()); + assert_visible_op_count_cache_matches_exact(&dst); +} diff --git a/vendor/loro-internal/src/tests/replay_base.rs b/vendor/loro-internal/src/tests/replay_base.rs new file mode 100644 index 0000000..c9b62f2 --- /dev/null +++ b/vendor/loro-internal/src/tests/replay_base.rs @@ -0,0 +1,723 @@ +//! Replay-base selection: the bounded multi-head critical version search +//! (`OpLog::latest_critical_version_below_meet`) and its wiring in +//! `iter_from_replay_base_causally`. +//! +//! The DAG shape under test is the criss-cross that continuous two-peer sync +//! produces: every merge point has two heads, so the single-head descent +//! (`latest_single_head_critical_version`) stays stuck at the initial fork +//! point while the multi-head fixpoint finds the last fully synced version. + +use crate::dag::DagUtils; +use crate::diff_calc::DiffMode; +use crate::loro::ExportMode; +use crate::oplog::CriticalVersionSearch; +use crate::{LoroDoc, VersionVector}; + +use super::exchange; + +/// Two peers that edit concurrently and fully sync after every round. +fn criss_cross(rounds: usize) -> (LoroDoc, LoroDoc) { + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + a.get_text("t").insert_unicode(0, "base").unwrap(); + a.commit_then_renew(); + let b = a.fork(); + b.set_peer_id(2).unwrap(); + for _ in 0..rounds { + a.get_text("t").insert_unicode(0, "a").unwrap(); + a.commit_then_renew(); + b.get_text("t").insert_unicode(0, "b").unwrap(); + b.commit_then_renew(); + exchange(&a, &b); + } + (a, b) +} + +/// One more unsynced concurrent pair on top of a synced criss-cross, with +/// `b`'s side imported into `a`. Returns `(a, sync_vv, before, after)`. +fn one_concurrent_import(rounds: usize) -> (LoroDoc, VersionVector, VersionVector, VersionVector) { + let (a, b) = criss_cross(rounds); + let sync_vv = a.oplog_vv(); + assert_eq!(sync_vv, b.oplog_vv()); + + a.get_text("t").insert_unicode(0, "a").unwrap(); + a.commit_then_renew(); + b.get_text("t").insert_unicode(0, "b").unwrap(); + b.commit_then_renew(); + + let before = a.oplog_vv(); + let update = b.export(ExportMode::updates(&before)).unwrap(); + a.import(&update).unwrap(); + let after = a.oplog_vv(); + (a, sync_vv, before, after) +} + +/// Randomized multi-peer edit/sync workload: on ordinary concurrent +/// histories the search must always find a critical base — never fall back +/// to the single-head descent. (An earlier rounds-style cap on the fixpoint +/// caused a silent fallback on roughly a third of such imports.) +#[test] +fn randomized_sync_never_exhausts_the_search_budget() { + use crate::oplog::CRITICAL_BASE_FALLBACK_COUNT; + + struct Lcg(u64); + impl Lcg { + fn below(&mut self, n: usize) -> usize { + self.0 = self + .0 + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + ((self.0 >> 33) as usize) % n + } + } + let mut rng = Lcg(0xC0FFEE); + + let docs: Vec<LoroDoc> = (1..=3) + .map(|p| { + let d = LoroDoc::new_auto_commit(); + d.set_peer_id(p).unwrap(); + d + }) + .collect(); + docs[0].get_text("t").insert_unicode(0, "seed").unwrap(); + docs[0].commit_then_renew(); + let all = docs[0].export(ExportMode::all_updates()).unwrap(); + docs[1].import(&all).unwrap(); + docs[2].import(&all).unwrap(); + + let fallbacks_before = CRITICAL_BASE_FALLBACK_COUNT.with(|c| c.get()); + let rebuilds_before = crate::diff_calc::FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()); + for _ in 0..600 { + let i = rng.below(3); + if rng.below(3) == 0 { + let j = (i + 1 + rng.below(2)) % 3; + let u = docs[i] + .export(ExportMode::updates(&docs[j].oplog_vv())) + .unwrap(); + docs[j].import(&u).unwrap(); + } else { + let t = docs[i].get_text("t"); + let pos = rng.below(t.len_unicode() + 1); + t.insert_unicode(pos, "x").unwrap(); + docs[i].commit_then_renew(); + } + } + for _ in 0..2 { + for i in 0..3 { + for j in 0..3 { + if i != j { + let u = docs[i] + .export(ExportMode::updates(&docs[j].oplog_vv())) + .unwrap(); + docs[j].import(&u).unwrap(); + } + } + } + } + assert_eq!( + docs[0].get_text("t").to_string(), + docs[1].get_text("t").to_string() + ); + assert_eq!( + docs[0].get_text("t").to_string(), + docs[2].get_text("t").to_string() + ); + let fallbacks = CRITICAL_BASE_FALLBACK_COUNT.with(|c| c.get()) - fallbacks_before; + assert_eq!( + fallbacks, 0, + "the bounded search fell back to the single-head descent" + ); + let rebuilds = crate::diff_calc::FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) - rebuilds_before; + assert_eq!( + rebuilds, 0, + "randomized concurrent imports must not rebuild the tracker" + ); +} + +#[test] +fn multi_head_critical_base_on_criss_cross_sync() { + let (a, sync_vv, before, after) = one_concurrent_import(4); + let before_frontiers = a.oplog().lock().dag.vv_to_frontiers(&before); + let after_frontiers = a.oplog_frontiers(); + + let oplog = a.oplog().lock(); + // On this DAG shape every synced version has two heads, so the single-head + // descent stays stuck at the initial fork point (before peer 2's first op) + // no matter how many rounds have passed… + let single_head = oplog + .dag + .latest_single_head_critical_version(&before_frontiers, &after_frontiers); + let single_head_vv = oplog.dag.frontiers_to_vv(&single_head).unwrap(); + assert!(!single_head_vv.includes_id(loro_common::ID::new(2, 0))); + // …while the multi-head search retreats only to the last synced version. + let (base, _) = + oplog.iter_from_replay_base_causally(&before, &before_frontiers, &after, &after_frontiers); + assert_eq!(base.vv, sync_vv); + assert!(base.is_critical); + assert_eq!(base.diff_mode, DiffMode::Import); +} + +#[test] +fn fixpoint_returns_the_greatest_cut() { + let (a, sync_vv, before, after) = one_concurrent_import(3); + let mut merged = before.clone(); + merged.merge(&after); + + let oplog = a.oplog().lock(); + let res = oplog.latest_critical_version_below_meet(&before, &after, &merged); + assert_eq!(res, CriticalVersionSearch::Found(sync_vv)); +} + +#[test] +fn disjoint_histories_have_no_cut_below_the_meet() { + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + a.get_text("t").insert_unicode(0, "aaa").unwrap(); + a.commit_then_renew(); + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(2).unwrap(); + b.get_text("t").insert_unicode(0, "bbb").unwrap(); + b.commit_then_renew(); + + let before = a.oplog_vv(); + let before_frontiers = a.oplog_frontiers(); + a.import(&b.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + let after = a.oplog_vv(); + let after_frontiers = a.oplog_frontiers(); + + let oplog = a.oplog().lock(); + let mut merged = before.clone(); + merged.merge(&after); + assert_eq!( + oplog.latest_critical_version_below_meet(&before, &after, &merged), + CriticalVersionSearch::NoneBelowMeet + ); + // ∅ is trivially critical; the wiring reports it as such. + let (base, _) = + oplog.iter_from_replay_base_causally(&before, &before_frontiers, &after, &after_frontiers); + assert!(base.vv.is_empty()); + assert!(base.is_critical); +} + +// ---- Trusting a critical replay base (richtext) ---- + +/// peer 1 commits `insert + mark` in ONE change, so `StyleStart` and +/// `StyleEnd` are adjacent counters inside a single change. Peers 2 and 3 +/// then fork *between* those two counters (detached editing on a mid-change +/// frontier), which is the only way a doc version can sit inside a style +/// pair. The greatest critical cut then lands between the two ops of one +/// mark, exercising the unpaired-end recovery path +/// (`style_for_end_anchor`) of the non-rebuilt tracker. +fn style_straddle_forks() -> (LoroDoc, LoroDoc, LoroDoc) { + use crate::cursor::PosType; + use crate::version::Frontiers; + use loro_common::ID; + + let doc1 = LoroDoc::new_auto_commit(); + doc1.set_peer_id(1).unwrap(); + doc1.get_text("r") + .insert(0, "hello world", PosType::Unicode) + .unwrap(); + doc1.get_text("r") + .mark(0, 5, "bold", true.into(), PosType::Unicode) + .unwrap(); + doc1.commit_then_renew(); + let snapshot = doc1.export(ExportMode::Snapshot).unwrap(); + + let mut forks = Vec::new(); + for (peer, s) in [(2u64, "AAA"), (3u64, "BBB")] { + let d = LoroDoc::new_auto_commit(); + d.set_detached_editing(true); + d.import(&snapshot).unwrap(); + d.set_peer_id(peer).unwrap(); + // Mid-change frontier: after StyleStart (counter 11), before + // StyleEnd (counter 12). + d.checkout(&Frontiers::from(ID::new(1, 11))).unwrap(); + d.set_peer_id(peer).unwrap(); + d.get_text("r").insert(2, s, PosType::Unicode).unwrap(); + d.commit_then_renew(); + forks.push(d); + } + + let doc3 = forks.pop().unwrap(); + let doc2 = forks.pop().unwrap(); + (doc1, doc2, doc3) +} + +#[test] +fn critical_base_may_cut_between_style_start_and_end() { + let (doc1, doc2, doc3) = style_straddle_forks(); + let target = LoroDoc::new_auto_commit(); + target + .import(&doc1.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + target + .import( + &doc2 + .export(ExportMode::updates(&target.oplog_vv())) + .unwrap(), + ) + .unwrap(); + + let before = target.oplog_vv(); + let before_frontiers = target.oplog_frontiers(); + target + .import( + &doc3 + .export(ExportMode::updates(&target.oplog_vv())) + .unwrap(), + ) + .unwrap(); + let after = target.oplog_vv(); + let after_frontiers = target.oplog_frontiers(); + + let oplog = target.oplog().lock(); + let (base, _) = + oplog.iter_from_replay_base_causally(&before, &before_frontiers, &after, &after_frontiers); + // A later change to the base search that rounds cuts to change (or style + // pair) boundaries would silently drop this coverage — keep it pinned. + assert_eq!( + base.vv.get(&1).copied(), + Some(12), + "base must cut between StyleStart(11) and StyleEnd(12); got {:?}", + base.vv + ); + assert!( + base.is_critical, + "the mid-mark cut must be reported critical" + ); + assert_ne!(base.vv, before, "must be a conservative base"); +} + +#[test] +fn style_straddling_base_converges_in_every_import_order() { + use crate::diff_calc::FULL_TRACKER_REBUILD_COUNT; + use crate::version::Frontiers; + + let (doc1, doc2, doc3) = style_straddle_forks(); + let rebuilds_before = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()); + // a: import 2 then 3. b: import 3 then 2. c: everything in one batch. + let a = LoroDoc::new_auto_commit(); + a.import(&doc1.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + a.import(&doc2.export(ExportMode::updates(&a.oplog_vv())).unwrap()) + .unwrap(); + a.import(&doc3.export(ExportMode::updates(&a.oplog_vv())).unwrap()) + .unwrap(); + + let b = LoroDoc::new_auto_commit(); + b.import(&doc1.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + b.import(&doc3.export(ExportMode::updates(&b.oplog_vv())).unwrap()) + .unwrap(); + b.import(&doc2.export(ExportMode::updates(&b.oplog_vv())).unwrap()) + .unwrap(); + + let rebuilds = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) - rebuilds_before; + assert_eq!( + rebuilds, 0, + "the straddle imports must take the trusted path" + ); + + let c = LoroDoc::new_auto_commit(); + c.import(&doc1.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + let all = vec![ + doc2.export(ExportMode::updates(&c.oplog_vv())).unwrap(), + doc3.export(ExportMode::updates(&c.oplog_vv())).unwrap(), + ]; + c.import_batch(&all).unwrap(); + + assert_eq!(a.get_text("r").to_string(), b.get_text("r").to_string()); + assert_eq!(a.get_text("r").to_string(), c.get_text("r").to_string()); + assert_eq!( + a.get_text("r").get_richtext_value(), + b.get_text("r").get_richtext_value() + ); + assert_eq!( + a.get_text("r").get_richtext_value(), + c.get_text("r").get_richtext_value() + ); + + // Independent oracle: a checkout round-trip through the empty frontiers + // forces a full-history rebuild, so the trusted incremental result is + // compared against the rebuild path — not just against itself. + let incremental = a.get_text("r").get_richtext_value(); + let head = a.oplog_frontiers(); + let oracle_before = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()); + a.checkout(&Frontiers::default()).unwrap(); + a.checkout(&head).unwrap(); + assert!( + FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) > oracle_before, + "the oracle round-trip must take the rebuild path" + ); + assert_eq!(a.get_text("r").get_richtext_value(), incremental); +} + +/// Continuous two-peer sync with marks: text and styles converge, and the +/// full-history tracker rebuild never fires — every concurrent import is +/// served from a tracker seeded at the (multi-head critical) replay base. +#[test] +fn criss_cross_sync_never_rebuilds_the_text_tracker() { + use crate::cursor::PosType; + use crate::diff_calc::FULL_TRACKER_REBUILD_COUNT; + + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(2).unwrap(); + a.get_text("r") + .insert(0, "seed text here", PosType::Unicode) + .unwrap(); + a.commit_then_renew(); + b.import(&a.export(ExportMode::updates(&b.oplog_vv())).unwrap()) + .unwrap(); + + let rebuilds_before = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()); + for round in 0..40 { + for (d, s) in [(&a, "x"), (&b, "y")] { + let t = d.get_text("r"); + t.insert(1, s, PosType::Unicode).unwrap(); + let len = t.len_unicode(); + t.mark( + 0, + (len / 2).max(1), + "bold", + (round % 2 == 0).into(), + PosType::Unicode, + ) + .unwrap(); + d.commit_then_renew(); + } + exchange(&a, &b); + } + assert_eq!(a.get_text("r").to_string(), b.get_text("r").to_string()); + assert_eq!( + a.get_text("r").get_richtext_value(), + b.get_text("r").get_richtext_value() + ); + let rebuilds = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) - rebuilds_before; + assert_eq!( + rebuilds, 0, + "concurrent imports must not rebuild the tracker" + ); + + // Independent oracle: force one rebuild via a checkout round-trip and + // compare it against the incrementally maintained state. + let incremental = a.get_text("r").get_richtext_value(); + let head = a.oplog_frontiers(); + a.checkout(&crate::version::Frontiers::default()).unwrap(); + a.checkout(&head).unwrap(); + assert!( + FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) > rebuilds_before, + "the oracle round-trip must take the rebuild path" + ); + assert_eq!(a.get_text("r").get_richtext_value(), incremental); +} + +/// A persisted calculator replays ops the tracker has already applied +/// whenever the replay base sits below the version the tracker reached on +/// an earlier round (the shape `LoroDoc::checkout` produces — driven here +/// directly through one persisted `DiffCalculator`). The tracker skips +/// them (`skip_applied`), and the style table must not grow a duplicate +/// entry per re-replayed StyleStart: trusting the base turns what was a +/// once-per-retreat re-replay into one on every step. +#[test] +fn persisted_walks_do_not_duplicate_style_entries() { + use crate::cursor::PosType; + use crate::diff_calc::{ContainerDiffCalculator, DiffCalculator, FULL_TRACKER_REBUILD_COUNT}; + use crate::handler::HandlerTrait; + + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + a.get_text("t") + .insert(0, "seed text", PosType::Unicode) + .unwrap(); + a.commit_then_renew(); + let b = a.fork(); + b.set_peer_id(2).unwrap(); + + // A forward checkout path through half-synced frontiers: `{A_i}` is not + // critical (B_i is concurrent), so the step to `{A_i, B_i}` replays from + // the previous sync point and re-applies A_i's ops. + let rounds = 6; + let mut stops = vec![a.oplog_frontiers()]; + for round in 0..rounds { + for (d, s) in [(&a, "x"), (&b, "y")] { + let t = d.get_text("t"); + t.insert(0, s, PosType::Unicode).unwrap(); + t.mark(0, 4, "bold", (round % 2 == 0).into(), PosType::Unicode) + .unwrap(); + d.commit_then_renew(); + } + stops.push(a.oplog_frontiers()); + exchange(&a, &b); + stops.push(a.oplog_frontiers()); + } + + let oplog = a.oplog().lock(); + let idx = a.get_text("t").idx(); + let mut calc = DiffCalculator::new(true); + let rebuilds_before = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()); + for w in stops.windows(2) { + let before = oplog.dag.frontiers_to_vv(&w[0]).unwrap(); + let after = oplog.dag.frontiers_to_vv(&w[1]).unwrap(); + calc.calc_diff_internal(&oplog, &before, &w[0], &after, &w[1], None); + } + assert_eq!( + FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) - rebuilds_before, + 0, + "a forward walk over critical bases must not rebuild (a rebuild would reset the style table and mask the leak)" + ); + + let depth = oplog.arena.get_depth(idx); + let (_, c) = calc.get_or_create_calc(idx, depth); + let ContainerDiffCalculator::Richtext(text) = c else { + panic!("expected a richtext calculator"); + }; + assert_eq!( + text.tracked_style_ids().len(), + 2 * rounds, + "each StyleStart must appear exactly once in the style table" + ); +} + +/// The StyleEnd fallback (`style_for_end_anchor`) pushes a style entry when +/// its StyleStart lies below the tracker's seed. Re-replaying that StyleEnd +/// must reuse the entry, not push another; likewise a rebuild-created entry +/// must be reused by a later re-replay. +#[test] +fn straddling_walks_never_duplicate_style_entries() { + use crate::diff_calc::{ContainerDiffCalculator, DiffCalculator, FULL_TRACKER_REBUILD_COUNT}; + use crate::handler::HandlerTrait; + + let (doc1, doc2, doc3) = style_straddle_forks(); + // A second mark on one fork puts a StyleStart into the region the later + // steps re-replay (the straddling mark's own StyleStart sits below every + // base and only its StyleEnd is replayed, via the fallback). + doc2.get_text("r") + .mark(0, 3, "italic", true.into(), crate::cursor::PosType::Unicode) + .unwrap(); + doc2.commit_then_renew(); + let target = LoroDoc::new_auto_commit(); + for d in [&doc1, &doc2, &doc3] { + target + .import(&d.export(ExportMode::updates(&target.oplog_vv())).unwrap()) + .unwrap(); + } + let f0 = doc1.oplog_frontiers(); + let f1 = { + let t = doc1.fork(); + t.import(&doc2.export(ExportMode::updates(&t.oplog_vv())).unwrap()) + .unwrap(); + t.oplog_frontiers() + }; + let f2 = target.oplog_frontiers(); + + let oplog = target.oplog().lock(); + let idx = target.get_text("r").idx(); + let mut calc = DiffCalculator::new(true); + let rebuilds_before = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()); + // Forward over a base that cuts between StyleStart and StyleEnd (the + // fallback pushes), forward again (the fallback must reuse), retreat + // (rebuild replaces the table), forward again (reuse after a rebuild). + for w in [[&f0, &f1], [&f1, &f2], [&f2, &f1], [&f1, &f2]] { + let before = oplog.dag.frontiers_to_vv(w[0]).unwrap(); + let after = oplog.dag.frontiers_to_vv(w[1]).unwrap(); + calc.calc_diff_internal(&oplog, &before, w[0], &after, w[1], None); + + let depth = oplog.arena.get_depth(idx); + let (_, c) = calc.get_or_create_calc(idx, depth); + let ContainerDiffCalculator::Richtext(text) = c else { + panic!("expected a richtext calculator"); + }; + let mut ids = text.tracked_style_ids(); + let len = ids.len(); + ids.sort(); + ids.dedup(); + assert_eq!(ids.len(), len, "duplicate style entry for one op id"); + assert_eq!(len, 2, "one entry per mark: the fallback's and the fork's"); + } + assert_eq!( + FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) - rebuilds_before, + 1, + "only the retreating step may rebuild" + ); +} + +/// Same criss-cross shape on a plain list container: the list tracker also +/// stops rebuilding once the replay base is certified critical. +#[test] +fn criss_cross_sync_never_rebuilds_the_list_tracker() { + use crate::diff_calc::FULL_TRACKER_REBUILD_COUNT; + + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(2).unwrap(); + a.get_list("l").insert(0, "seed").unwrap(); + a.commit_then_renew(); + b.import(&a.export(ExportMode::updates(&b.oplog_vv())).unwrap()) + .unwrap(); + + let rebuilds_before = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()); + for round in 0..40 { + for (d, v) in [(&a, "x"), (&b, "y")] { + d.get_list("l").insert(0, format!("{v}{round}")).unwrap(); + d.commit_then_renew(); + } + exchange(&a, &b); + } + assert_eq!(a.get_deep_value(), b.get_deep_value()); + let rebuilds = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) - rebuilds_before; + assert_eq!( + rebuilds, 0, + "concurrent list imports must not rebuild the tracker" + ); +} + +/// What a forward walk through half-synced versions of two concurrent +/// branches does to one container's diff calculator: the stops, and the doc. +fn half_synced_walk( + rounds: usize, + edit: impl Fn(&LoroDoc, usize), +) -> (LoroDoc, Vec<crate::version::Frontiers>) { + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(2).unwrap(); + let mut stops = vec![a.oplog_frontiers()]; + for round in 0..rounds { + for d in [&a, &b] { + edit(d, round); + d.commit_then_renew(); + } + // `{A_i}` is not critical (B_i is concurrent), so the step to + // `{A_i, B_i}` replays from the previous sync point and re-applies + // A_i's ops to a tracker that already has them. + stops.push(a.oplog_frontiers()); + exchange(&a, &b); + stops.push(a.oplog_frontiers()); + } + (a, stops) +} + +/// Walks `stops` with one persisted calculator, returns the calculator's +/// table size for `idx`, and checks the doc's checkouts against forks. +fn walk_and_measure( + doc: &LoroDoc, + stops: &[crate::version::Frontiers], + idx: crate::container::idx::ContainerIdx, + table_len: impl Fn(&crate::diff_calc::ContainerDiffCalculator) -> usize, +) -> usize { + use crate::diff_calc::{DiffCalculator, FULL_TRACKER_REBUILD_COUNT}; + + let len = { + let oplog = doc.oplog().lock(); + let mut calc = DiffCalculator::new(true); + let rebuilds_before = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()); + for w in stops.windows(2) { + let before = oplog.dag.frontiers_to_vv(&w[0]).unwrap(); + let after = oplog.dag.frontiers_to_vv(&w[1]).unwrap(); + calc.calc_diff_internal(&oplog, &before, &w[0], &after, &w[1], None); + } + assert_eq!( + FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) - rebuilds_before, + 0, + "a rebuild would reset the table and mask the growth" + ); + let depth = oplog.arena.get_depth(idx); + let (_, c) = calc.get_or_create_calc(idx, depth); + table_len(c) + }; + + for stop in stops { + doc.checkout(stop).unwrap(); + assert_eq!( + doc.get_deep_value(), + doc.fork_at(stop).unwrap().get_deep_value() + ); + } + doc.checkout_to_latest(); + len +} + +/// The diff calculators' text and value tables record what the tracker +/// applies. A re-replayed insert, which the tracker skips, must not be +/// recorded again (it kept growing the tables and using up their `u32` +/// index space on every forward checkout). The applied prefix of a partly +/// re-replayed op is covered by `insert_with_builds_content_only_for_the_unapplied_suffix`. +/// See `context/text-arena-growth.md`. +#[test] +fn persisted_walks_record_each_text_char_once() { + use crate::cursor::PosType; + use crate::diff_calc::ContainerDiffCalculator; + use crate::handler::HandlerTrait; + + let rounds = 50; + let (doc, stops) = half_synced_walk(rounds, |d, round| { + let t = d.get_text("t"); + t.insert( + 0, + if round % 2 == 0 { "ab" } else { "文😀" }, + PosType::Unicode, + ) + .unwrap(); + }); + let idx = doc.get_text("t").idx(); + let len = walk_and_measure(&doc, &stops, idx, |c| { + let ContainerDiffCalculator::Richtext(text) = c else { + panic!("expected a richtext calculator"); + }; + text.tracked_text_len() + }); + assert_eq!(len, 2 * 2 * rounds); +} + +#[test] +fn persisted_walks_record_each_list_value_once() { + use crate::diff_calc::ContainerDiffCalculator; + use crate::handler::HandlerTrait; + + let rounds = 50; + let (doc, stops) = half_synced_walk(rounds, |d, round| { + let l = d.get_list("l"); + l.insert(0, round as i64).unwrap(); + l.insert(0, format!("v{round}")).unwrap(); + }); + let idx = doc.get_list("l").idx(); + let len = walk_and_measure(&doc, &stops, idx, |c| { + let ContainerDiffCalculator::List(list) = c else { + panic!("expected a list calculator"); + }; + list.tracked_values_len() + }); + assert_eq!(len, 2 * 2 * rounds); +} + +/// The movable-list calculator rebuilds its tracker on these steps (base != +/// from), which replaces the table; this pins that it still holds one copy. +#[test] +fn persisted_walks_record_each_movable_list_value_once() { + use crate::diff_calc::ContainerDiffCalculator; + use crate::handler::HandlerTrait; + + let rounds = 50; + let (doc, stops) = half_synced_walk(rounds, |d, round| { + let l = d.get_movable_list("m"); + l.insert(0, round as i64).unwrap(); + l.insert(0, format!("v{round}")).unwrap(); + if l.len() > 2 { + l.mov(0, l.len() - 1).unwrap(); + } + }); + let idx = doc.get_movable_list("m").idx(); + let len = walk_and_measure(&doc, &stops, idx, |c| { + let ContainerDiffCalculator::MovableList(list) = c else { + panic!("expected a movable list calculator"); + }; + list.tracked_values_len() + }); + assert_eq!(len, 2 * 2 * rounds); +} diff --git a/vendor/loro-internal/src/tests/text_arena_growth.rs b/vendor/loro-internal/src/tests/text_arena_growth.rs new file mode 100644 index 0000000..d918111 --- /dev/null +++ b/vendor/loro-internal/src/tests/text_arena_growth.rs @@ -0,0 +1,184 @@ +//! Re-parsing a change block must not copy its text or list values into a +//! doc-wide store again (zeronsh/zeron#905). See `context/text-arena-growth.md`. + +use super::exchange; +use crate::{ + cursor::PosType, loro::ExportMode, op::InnerContent, version::Frontiers, LoroDoc, LoroValue, + ToJson, +}; + +#[test] +fn exporting_while_streaming_text_does_not_grow_the_string_arena() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let text = doc.get_text("text"); + let token = "token "; + let ticks = 2000; + for _ in 0..ticks { + text.insert(text.len_unicode(), token, PosType::Unicode) + .unwrap(); + doc.commit_then_renew(); + // Turns the block back into bytes; the next commit parses it again. + doc.export(ExportMode::Snapshot).unwrap(); + } + + let written = token.len() * ticks; + let arena = doc.oplog().lock().arena.str_len_bytes(); + // Before the fix the arena held every re-parse of the block: ~1000x here. + assert!( + arena <= 2 * written, + "string arena holds {arena} bytes for {written} bytes of text" + ); + assert_eq!(text.to_string(), token.repeat(ticks)); +} + +/// Tracker diffs take text from the ops, which now live in block-local +/// buffers: check concurrent, non-ASCII and long inserts across re-parsed +/// blocks against a fresh replay at every version. +#[test] +fn checkout_text_from_reparsed_blocks_matches_replay() { + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(2).unwrap(); + let long = "长文本😀".repeat(120); + let mut versions: Vec<Frontiers> = Vec::new(); + for i in 0..40 { + let (doc, s) = if i % 3 == 0 { + (&b, long.as_str()) + } else { + (&a, if i % 2 == 0 { "ab" } else { "文字😀" }) + }; + let text = doc.get_text("text"); + let pos = (i * 7) % (text.len_unicode() + 1); + text.insert(pos, s, PosType::Unicode).unwrap(); + if i % 5 == 4 { + let len = text.len_unicode(); + text.delete(len / 3, (len / 4).min(9), PosType::Unicode) + .unwrap(); + } + doc.commit_then_renew(); + doc.export(ExportMode::Snapshot).unwrap(); + if i % 4 == 3 { + exchange(&a, &b); + } + versions.push(doc.oplog_frontiers()); + } + a.import(&b.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + + let snapshot = a.export(ExportMode::Snapshot).unwrap(); + for f in versions.iter().rev().chain(versions.iter()) { + a.checkout(f).unwrap(); + let expected = LoroDoc::new(); + expected.import(&snapshot).unwrap(); + expected.checkout(f).unwrap(); + assert_eq!( + a.get_text("text").to_string(), + expected.get_text("text").to_string() + ); + a.export(ExportMode::Snapshot).unwrap(); + } + a.checkout_to_latest(); + let replay = LoroDoc::new(); + replay + .import(&a.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + assert_eq!( + a.get_text("text").to_string(), + replay.get_text("text").to_string() + ); +} + +/// List values are owned by their ops. Streaming pushes with an export after +/// each commit keeps one copy per value, and a local push still merges into the +/// re-parsed op that precedes it. +#[test] +fn exporting_while_pushing_list_values_keeps_one_copy() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let list = doc.get_list("list"); + let ticks = 500; + for i in 0..ticks { + list.push(i as i64).unwrap(); + doc.commit_then_renew(); + doc.export(ExportMode::Snapshot).unwrap(); + } + + let mut stored = 0; + let mut ops = 0; + doc.oplog() + .lock() + .change_store() + .visit_all_changes(&mut |change| { + for op in change.ops().iter() { + if let InnerContent::List(crate::container::list::list_op::InnerListOp::Insert { + slice, + .. + }) = &op.content + { + stored += slice.len(); + ops += 1; + } + } + }); + assert_eq!(stored, ticks); + assert!( + ops < ticks / 4, + "{ops} insert ops for {ticks} consecutive pushes" + ); + let expected: Vec<LoroValue> = (0..ticks as i64).map(LoroValue::from).collect(); + assert_eq!( + doc.get_deep_value().to_json_value()["list"], + LoroValue::from(expected).to_json_value() + ); +} + +/// Checkouts of concurrent list and movable-list inserts from re-parsed +/// blocks match a fresh replay. +#[test] +fn checkout_list_values_from_reparsed_blocks_matches_replay() { + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(1).unwrap(); + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(2).unwrap(); + let mut versions: Vec<Frontiers> = Vec::new(); + for i in 0..60i64 { + let doc = if i % 3 == 0 { &b } else { &a }; + let list = doc.get_list("list"); + let movable = doc.get_movable_list("movable"); + let pos = (i as usize * 7) % (list.len() + 1); + list.insert(pos, i).unwrap(); + list.insert(pos, format!("v{i}")).unwrap(); + let mpos = (i as usize * 5) % (movable.len() + 1); + movable.insert(mpos, i).unwrap(); + if i % 5 == 4 { + list.delete(list.len() / 3, 2.min(list.len() / 3)).unwrap(); + if movable.len() > 2 { + movable.mov(0, movable.len() - 1).unwrap(); + movable.set(1, i * 100).unwrap(); + } + } + doc.commit_then_renew(); + doc.export(ExportMode::Snapshot).unwrap(); + if i % 4 == 3 { + exchange(&a, &b); + } + versions.push(doc.oplog_frontiers()); + } + a.import(&b.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + + let snapshot = a.export(ExportMode::Snapshot).unwrap(); + for f in versions.iter().rev().chain(versions.iter()) { + a.checkout(f).unwrap(); + let expected = LoroDoc::new(); + expected.import(&snapshot).unwrap(); + expected.checkout(f).unwrap(); + assert_eq!( + a.get_deep_value().to_json_value(), + expected.get_deep_value().to_json_value() + ); + a.export(ExportMode::Snapshot).unwrap(); + } +} diff --git a/vendor/loro-internal/src/tests/undo_atomicity.rs b/vendor/loro-internal/src/tests/undo_atomicity.rs new file mode 100644 index 0000000..059d813 --- /dev/null +++ b/vendor/loro-internal/src/tests/undo_atomicity.rs @@ -0,0 +1,123 @@ +use crate::{ + loro::{AFTER_APPLY_DIFF_HANDLER, FAIL_APPLY_DIFF_AFTER_HANDLER}, + undo::UndoManager, + LoroDoc, +}; +use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, +}; + +#[test] +fn failed_undo_and_redo_restore_text_history_and_events() { + for mixed in [false, true] { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let text = doc.get_text("text"); + text.insert(0, "a😀bc", crate::cursor::PosType::Unicode) + .unwrap(); + doc.commit_then_renew(); + let undo = UndoManager::new(&doc); + undo.set_merge_interval(0); + text.delete(1, 1, crate::cursor::PosType::Unicode).unwrap(); + text.mark(0, 2, "bold", true.into(), crate::cursor::PosType::Unicode) + .unwrap(); + if mixed { + doc.get_map("map").insert("changed", 42).unwrap(); + doc.get_list("list").push(42).unwrap(); + doc.get_movable_list("movable").push(42.into()).unwrap(); + doc.get_tree("tree") + .create(crate::state::TreeParentId::Root) + .unwrap(); + #[cfg(feature = "counter")] + doc.get_counter("counter").increment(0.1).unwrap(); + } + doc.commit_then_renew(); + let events = Arc::new(AtomicUsize::new(0)); + let captured = events.clone(); + let _sub = doc.subscribe_root(Arc::new(move |_| { + captured.fetch_add(1, Ordering::Relaxed); + })); + + for redo in [false, true] { + let value = doc.get_deep_value(); + let delta = text.get_delta(); + let frontiers = doc.state_frontiers(); + let vv = doc.oplog_vv(); + let count = doc.oplog().lock().cached_visible_op_count(); + let stacks = (undo.undo_count(), undo.redo_count()); + for _ in 0..2 { + let seen = events.load(Ordering::Relaxed); + FAIL_APPLY_DIFF_AFTER_HANDLER.with(|flag| flag.set(true)); + let result = if redo { undo.redo() } else { undo.undo() }; + assert!(matches!( + result, + Err(crate::LoroError::OutOfBound { + pos: usize::MAX, + .. + }) + )); + assert_eq!(doc.get_deep_value(), value); + assert_eq!(text.get_delta(), delta); + assert_eq!(doc.state_frontiers(), frontiers); + assert_eq!(doc.oplog_vv(), vv); + assert_eq!(doc.oplog().lock().cached_visible_op_count(), count); + assert_eq!(doc.get_pending_txn_len(), 0); + assert_eq!((undo.undo_count(), undo.redo_count()), stacks); + assert_eq!(events.load(Ordering::Relaxed), seen); + } + assert!(if redo { undo.redo() } else { undo.undo() }.unwrap()); + } + assert_eq!(text.get_delta(), { + let restored = LoroDoc::new_auto_commit(); + restored + .import(&doc.export(crate::encoding::ExportMode::Snapshot).unwrap()) + .unwrap(); + restored.get_text("text").get_delta() + }); + } +} + +#[test] +fn failed_undo_does_not_discard_a_concurrent_writers_edit() { + use std::{sync::mpsc, thread, time::Duration}; + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let text = doc.get_text("text"); + text.insert(0, "abc", crate::cursor::PosType::Unicode) + .unwrap(); + doc.commit_then_renew(); + let undo = UndoManager::new(&doc); + text.delete(0, 1, crate::cursor::PosType::Unicode).unwrap(); + doc.commit_then_renew(); + let other = doc.clone(); + let (go, begin) = mpsc::channel(); + let (ready, attempted) = mpsc::channel(); + let (done, finished) = mpsc::channel(); + let writer = thread::spawn(move || { + begin.recv().unwrap(); + ready.send(()).unwrap(); + other + .get_text("text") + .insert(2, "X", crate::cursor::PosType::Unicode) + .unwrap(); + other.commit_then_renew(); + let _ = done.send(()); + }); + AFTER_APPLY_DIFF_HANDLER.with(|hook| { + *hook.borrow_mut() = Some(Box::new(move || { + go.send(()).unwrap(); + attempted.recv().unwrap(); + assert!(matches!( + finished.recv_timeout(Duration::from_millis(50)), + Err(mpsc::RecvTimeoutError::Timeout) + )); + })); + }); + FAIL_APPLY_DIFF_AFTER_HANDLER.with(|flag| flag.set(true)); + assert!(undo.undo().is_err()); + writer.join().unwrap(); + assert_eq!(text.to_string(), "bcX"); + assert_eq!(undo.undo_count(), 2); + assert_eq!(undo.redo_count(), 0); +} diff --git a/vendor/loro-internal/src/txn.rs b/vendor/loro-internal/src/txn.rs new file mode 100644 index 0000000..f5d673f --- /dev/null +++ b/vendor/loro-internal/src/txn.rs @@ -0,0 +1,1221 @@ +use std::{ + borrow::Cow, + mem::take, + sync::{Arc, Weak}, +}; + +use enum_as_inner::EnumAsInner; +use generic_btree::rle::{HasLength as RleHasLength, Mergeable as GBSliceable}; +use loro_common::{ContainerType, IdLp, IdSpan, LoroResult}; +use loro_delta::{array_vec::ArrayVec, DeltaRopeBuilder}; +use rle::{HasLength, Mergable, RleVec, Sliceable}; +use rustc_hash::FxHashMap; +use smallvec::SmallVec; + +use crate::utils::subscription::DeferredPanic; +use crate::{ + change::{Change, Lamport, Timestamp}, + container::{ + idx::ContainerIdx, + list::list_op::{DeleteSpan, InnerListOp}, + richtext::Style, + IntoContainerId, + }, + delta::{ResolvedMapDelta, ResolvedMapValue, StyleMeta, StyleMetaItem, TreeDiff, TreeDiffItem}, + encoding::export_fast_updates_in_range, + event::{Diff, ListDeltaMeta, TextDiff}, + handler::{Handler, ValueOrHandler}, + id::{Counter, PeerID, ID}, + lock::{LoroMutex, LoroMutexGuard}, + loro::CommitOptions, + op::{InnerContent, Op, RawOp, RawOpContent}, + pre_commit::{ChangeModifier, PreCommitCallbackPayload}, + span::HasIdSpan, + version::Frontiers, + ChangeMeta, InternalString, LoroDoc, LoroDocInner, LoroError, LoroValue, +}; + +use super::{ + arena::SharedArena, + event::{InternalContainerDiff, InternalDocDiff}, + handler::{ListHandler, MapHandler, TextHandler, TreeHandler}, + oplog::OpLog, + state::DocState, +}; + +impl crate::LoroDoc { + /// Create a new transaction. + /// Every ops created inside one transaction will be packed into a single + /// [Change]. + /// + /// There can only be one active transaction at a time for a [LoroDoc]. + #[inline(always)] + pub fn txn(&self) -> Result<Transaction, LoroError> { + self.txn_with_origin("") + } + + /// Create a new transaction with specified origin. + /// + /// The origin will be propagated to the events. + /// There can only be one active transaction at a time for a [LoroDoc]. + pub fn txn_with_origin(&self, origin: &str) -> Result<Transaction, LoroError> { + if !self.can_edit() { + return Err(LoroError::TransactionError( + String::from("LoroDoc is in readonly detached mode. To make it writable in detached mode, call `set_detached_editing(true)`.").into_boxed_str(), + )); + } + + let mut txn = Transaction::new_with_origin(self.inner.clone(), origin.into())?; + + let obs = self.observer.clone(); + let local_update_subs_weak = self.local_update_subs.downgrade(); + txn.set_on_commit(Box::new(move |state, oplog, id_span| { + let mut state = state.lock(); + let events = state.take_events(); + drop(state); + // A panicking subscriber must not drop the other events, nor the + // local update of this commit, which apps send to their peers. + let mut panic = DeferredPanic::default(); + for event in events { + panic.run(|| obs.emit(event)); + } + + if id_span.atom_len() != 0 { + if let Some(local_update_subs) = local_update_subs_weak.upgrade() { + if !local_update_subs.inner().is_empty() { + let bytes = { export_fast_updates_in_range(&oplog.lock(), &[id_span]) }; + panic.run(|| local_update_subs.emit(&(), bytes)); + } + } + } + panic.resume(); + })); + + Ok(txn) + } + + pub fn start_auto_commit(&self) { + self.auto_commit + .store(true, std::sync::atomic::Ordering::Release); + let mut self_txn = self.txn.lock(); + if self_txn.is_some() || !self.can_edit() { + return; + } + + let txn = self + .txn() + .expect("auto-commit should be able to create a transaction"); + self_txn.replace(txn); + } + + #[inline] + pub fn renew_txn_if_auto_commit(&self, options: Option<CommitOptions>) { + if self.auto_commit.load(std::sync::atomic::Ordering::Acquire) && self.can_edit() { + let mut self_txn = self.txn.lock(); + if self_txn.is_some() { + return; + } + + let mut txn = self + .txn() + .expect("auto-commit should be able to renew a transaction"); + if let Some(options) = options { + txn.set_options(options); + } + self_txn.replace(txn); + } + } + + #[inline] + pub(crate) fn _renew_txn_if_auto_commit_with_guard( + &self, + options: Option<CommitOptions>, + mut guard: LoroMutexGuard<Option<Transaction>>, + ) { + if self.auto_commit.load(std::sync::atomic::Ordering::Acquire) && self.can_edit() { + if guard.is_some() { + return; + } + + let mut txn = self + .txn() + .expect("auto-commit should be able to renew a transaction"); + if let Some(options) = options { + txn.set_options(options); + } + guard.replace(txn); + } + } +} + +pub(crate) type OnCommitFn = + Box<dyn FnOnce(&Arc<LoroMutex<DocState>>, &Arc<LoroMutex<OpLog>>, IdSpan) + Sync + Send>; + +pub struct Transaction { + peer: PeerID, + origin: InternalString, + start_counter: Counter, + next_counter: Counter, + start_lamport: Lamport, + next_lamport: Lamport, + doc: Weak<LoroDocInner>, + frontiers: Frontiers, + local_ops: RleVec<[Op; 1]>, // TODO: use a more efficient data structure + event_hints: FxHashMap<ContainerIdx, Vec<EventHint>>, + pub(super) arena: SharedArena, + finished: bool, + on_commit: Option<OnCommitFn>, + timestamp: Option<Timestamp>, + msg: Option<Arc<str>>, + latest_timestamp: Timestamp, + pub(super) is_peer_first_appearance: bool, + /// The DAG's frontiers when the txn began, before its first op. + dag_frontiers_at_start: Frontiers, + /// Set while `LoroDoc::apply_diff` or `revert_to` runs a batch in this txn, + /// which is rolled back if the batch fails (context/apply-diff-atomicity.md). + rollback_scope: Option<RollbackScope>, +} + +/// See [`Transaction::begin_rollback_scope`]. +#[derive(Debug)] +struct RollbackScope { + id: u64, + thread: usize, + /// Another thread applied an op in this txn while the batch ran. + foreign_ops: bool, + /// The txn's next counter and lamport when the batch began. + counter: Counter, + lamport: Lamport, + is_peer_first_appearance: bool, + /// For each container the batch gave an event hint to: how many hints it + /// had before, and the last one, which the batch's first hint may have been + /// merged into. + event_hints: FxHashMap<ContainerIdx, (usize, Option<EventHint>)>, +} + +/// Identifies the current thread for [`RollbackScope`]: the address of a +/// thread local is unique among the live threads. +fn current_thread_mark() -> usize { + thread_local!(static MARK: u8 = const { 0 }); + MARK.with(|m| m as *const u8 as usize) +} + +/// What [`Transaction::roll_back_scope`] took out of a txn. +pub(crate) struct RolledBackBatch { + pub(crate) peer: PeerID, + /// The txn's first op, its lamport, and the version it was applied on. + pub(crate) txn_start_counter: Counter, + pub(crate) txn_start_lamport: Lamport, + pub(crate) deps: Frontiers, + /// The DAG's frontiers before the txn's first op. + pub(crate) dag_frontiers_at_start: Frontiers, + /// The batch's ops are `batch_start..batch_end`; the txn keeps the ops before. + pub(crate) batch_start: Counter, + pub(crate) batch_end: Counter, + /// Every op of the txn, including the batch's. + pub(crate) ops: RleVec<[Op; 1]>, + pub(crate) timestamp: Timestamp, +} + +impl std::fmt::Debug for Transaction { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Transaction") + .field("peer", &self.peer) + .field("origin", &self.origin) + .field("start_counter", &self.start_counter) + .field("next_counter", &self.next_counter) + .field("start_lamport", &self.start_lamport) + .field("next_lamport", &self.next_lamport) + .field("frontiers", &self.frontiers) + .field("local_ops", &self.local_ops) + .field("event_hints", &self.event_hints) + .field("arena", &self.arena) + .field("finished", &self.finished) + .field("on_commit", &self.on_commit.is_some()) + .field("timestamp", &self.timestamp) + .finish() + } +} + +/// We can infer local events directly from the local behavior. This enum is used to +/// record them, so that we can avoid recalculate them when we commit the transaction. +/// +/// For example, when we insert a text in wasm, users use the utf16 index to send the +/// command. However, internally loro will convert it to unicode index. But the users +/// still need events that are in utf16 index. To avoid the round trip, we record the +/// events here. +#[derive(Debug, Clone, EnumAsInner)] +pub(super) enum EventHint { + Mark { + start: u32, + end: u32, + style: Style, + }, + InsertText { + /// pos is a Unicode index. If wasm, it's a UTF-16 index. + pos: u32, + event_len: u32, + unicode_len: u32, + styles: StyleMeta, + }, + /// pos is a Unicode index. If wasm, it's a UTF-16 index. + DeleteText { + span: DeleteSpan, + unicode_len: usize, + }, + InsertList { + len: u32, + pos: usize, + }, + SetList { + index: usize, + value: LoroValue, + }, + Move { + value: LoroValue, + from: u32, + to: u32, + }, + DeleteList(DeleteSpan), + Map { + key: InternalString, + value: Option<LoroValue>, + }, + // use vec because we could bring back some node that has children + Tree(SmallVec<[TreeDiffItem; 1]>), + MarkEnd, + #[cfg(feature = "counter")] + Counter(f64), +} + +impl generic_btree::rle::HasLength for EventHint { + fn rle_len(&self) -> usize { + match self { + EventHint::Mark { .. } => 1, + EventHint::InsertText { + unicode_len: len, .. + } => *len as usize, + EventHint::DeleteText { unicode_len, .. } => *unicode_len, + EventHint::InsertList { len, .. } => *len as usize, + EventHint::DeleteList(d) => d.len(), + EventHint::Map { .. } => 1, + EventHint::Tree(_) => 1, + EventHint::MarkEnd => 1, + EventHint::Move { .. } => 1, + EventHint::SetList { .. } => 1, + #[cfg(feature = "counter")] + EventHint::Counter(_) => 1, + } + } +} + +impl generic_btree::rle::Mergeable for EventHint { + fn can_merge(&self, rhs: &Self) -> bool { + match (self, rhs) { + ( + EventHint::InsertText { + pos, + unicode_len: _, + event_len, + styles, + }, + EventHint::InsertText { + pos: r_pos, + styles: r_styles, + .. + }, + ) => *pos + *event_len == *r_pos && styles == r_styles, + (EventHint::InsertList { pos, len }, EventHint::InsertList { pos: pos_right, .. }) => { + pos + *len as usize == *pos_right + } + // We don't merge delete text because it's hard to infer the correct pos to split: + // `range` param is in unicode range, but the delete text event is in UTF-16 range. + // Without the original text, it's impossible to convert the range. + (EventHint::DeleteText { span, .. }, EventHint::DeleteText { span: r, .. }) => { + span.is_mergable(r, &()) + } + (EventHint::DeleteList(l), EventHint::DeleteList(r)) => l.is_mergable(r, &()), + _ => false, + } + } + + fn merge_right(&mut self, rhs: &Self) { + match (self, rhs) { + ( + EventHint::InsertText { + event_len, + unicode_len: len, + .. + }, + EventHint::InsertText { + event_len: r_event_len, + unicode_len: r_len, + .. + }, + ) => { + *len += *r_len; + *event_len += *r_event_len; + } + ( + EventHint::InsertList { len, pos: _ }, + EventHint::InsertList { len: r_len, pos: _ }, + ) => *len += *r_len, + (EventHint::DeleteList(l), EventHint::DeleteList(r)) => l.merge(r, &()), + ( + EventHint::DeleteText { span, unicode_len }, + EventHint::DeleteText { + span: r_span, + unicode_len: r_len, + }, + ) => { + *unicode_len += *r_len; + span.merge(r_span, &()); + } + _ => unreachable!(), + } + } + + fn merge_left(&mut self, _: &Self) { + unreachable!() + } +} + +impl Transaction { + #[inline] + pub fn new(doc: Arc<LoroDocInner>) -> LoroResult<Self> { + Self::new_with_origin(doc.clone(), "".into()) + } + + pub fn new_with_origin(doc: Arc<LoroDocInner>, origin: InternalString) -> LoroResult<Self> { + let oplog_lock = doc.oplog.lock(); + let mut state_lock = doc.state.lock(); + if state_lock.is_in_txn() { + return Err(LoroError::DuplicatedTransactionError); + } + + state_lock.start_txn(origin, crate::event::EventTriggerKind::Local); + let arena = state_lock.arena.clone(); + let frontiers = state_lock.frontiers.clone(); + let peer = state_lock.peer.load(std::sync::atomic::Ordering::Relaxed); + let next_counter = oplog_lock.next_id(peer).counter; + let next_lamport = oplog_lock.dag.frontiers_to_next_lamport(&frontiers); + let dag_frontiers_at_start = oplog_lock.dag.frontiers().clone(); + let latest_timestamp = oplog_lock.get_greatest_timestamp(&frontiers); + if let Err(err) = + oplog_lock.check_change_greater_than_last_peer_id(peer, next_counter, &frontiers) + { + state_lock.abort_txn(); + return Err(err); + } + drop(state_lock); + drop(oplog_lock); + Ok(Self { + peer, + doc: Arc::downgrade(&doc), + arena, + frontiers, + timestamp: None, + next_counter, + next_lamport, + origin: Default::default(), + start_counter: next_counter, + start_lamport: next_lamport, + event_hints: Default::default(), + local_ops: RleVec::new(), + finished: false, + on_commit: None, + msg: None, + latest_timestamp, + is_peer_first_appearance: false, + dag_frontiers_at_start, + rollback_scope: None, + }) + } + + pub fn set_origin(&mut self, origin: InternalString) { + self.origin = origin; + } + + pub fn set_timestamp(&mut self, time: Timestamp) { + self.timestamp = Some(time); + } + + pub fn set_msg(&mut self, msg: Option<Arc<str>>) { + self.msg = msg; + } + + pub fn local_ops(&self) -> &RleVec<[Op; 1]> { + &self.local_ops + } + + pub fn peer(&self) -> &PeerID { + &self.peer + } + + pub fn timestamp(&self) -> &Option<Timestamp> { + &self.timestamp + } + + pub fn frontiers(&self) -> &Frontiers { + &self.frontiers + } + pub fn msg(&self) -> &Option<Arc<str>> { + &self.msg + } + + pub fn lamport(&self) -> &Lamport { + &self.start_lamport + } + + pub(crate) fn set_on_commit(&mut self, f: OnCommitFn) { + self.on_commit = Some(f); + } + + pub(crate) fn take_on_commit(&mut self) -> Option<OnCommitFn> { + self.on_commit.take() + } + + pub fn commit(mut self) -> Result<Option<CommitOptions>, LoroError> { + let mut panic = DeferredPanic::default(); + let ans = self._commit(&mut panic); + panic.resume(); + ans + } + + /// [`Self::commit`] for a caller that holds the doc's txn lock: a panic of a + /// pre-commit callback is put in `panic`, to be raised after the lock is + /// released. + pub(crate) fn commit_deferring_panic( + mut self, + panic: &mut DeferredPanic, + ) -> Result<Option<CommitOptions>, LoroError> { + self._commit(panic) + } + + /// A pre-commit callback that panics is user code panicking in the middle + /// of a commit: the change is already applied to the state and the op log + /// holds it as uncommitted. The commit is finished as if the callback had + /// returned, and its panic is put in `panic` to be raised once no doc lock + /// is held. + #[tracing::instrument(level = "debug", skip(self, panic))] + fn _commit(&mut self, panic: &mut DeferredPanic) -> Result<Option<CommitOptions>, LoroError> { + if self.finished { + return Ok(None); + } + + let Some(doc) = self.doc.upgrade() else { + return Ok(None); + }; + self.finished = true; + if self.local_ops.is_empty() { + let mut state = doc.state.lock(); + state.abort_txn(); + return Ok(Some(self.take_options())); + } + + let ops = std::mem::take(&mut self.local_ops); + let deps = take(&mut self.frontiers); + let change = Change { + lamport: self.start_lamport, + ops, + deps, + id: ID::new(self.peer, self.start_counter), + timestamp: self.latest_timestamp.max( + self.timestamp + .unwrap_or_else(|| doc.oplog.lock().get_timestamp_for_next_txn()), + ), + commit_msg: take(&mut self.msg), + }; + + let change_meta = ChangeMeta::from_change(&change); + { + // add change to uncommit field of oplog + let mut oplog = doc.oplog.lock(); + oplog.set_uncommitted_change(change); + } + + let modifier = ChangeModifier::default(); + panic.run(|| { + doc.pre_commit_subs.emit( + &(), + PreCommitCallbackPayload { + change_meta, + origin: self.origin.to_string(), + modifier: modifier.clone(), + }, + ) + }); + + let mut oplog = doc.oplog.lock(); + let mut state = doc.state.lock(); + + let Some(mut change) = oplog.uncommitted_change.take() else { + state.abort_txn(); + drop(state); + drop(oplog); + return Err(LoroError::internal( + "missing uncommitted change while committing transaction", + )); + }; + modifier.modify_change(&mut change); + let diff = if state.is_recording() { + Some(change_to_diff( + &change, + doc.clone(), + std::mem::take(&mut self.event_hints), + )) + } else { + None + }; + + let last_id = change.id_last(); + if let Err(err) = oplog.import_local_change(change) { + state.abort_txn(); + drop(state); + drop(oplog); + return Err(err); + } + + state.commit_txn( + Frontiers::from_id(last_id), + diff.map(|arr| InternalDocDiff { + by: crate::event::EventTriggerKind::Local, + origin: self.origin.clone(), + diff: Cow::Owned( + arr.into_iter() + .map(|x| InternalContainerDiff { + idx: x.idx, + bring_back: false, + diff: (x.diff.into()), + diff_mode: crate::diff_calc::DiffMode::Linear, + kept: None, + }) + .collect(), + ), + new_version: Cow::Borrowed(oplog.frontiers()), + }), + ); + drop(state); + drop(oplog); + if let Some(on_commit) = self.on_commit.take() { + assert!(!doc.txn.is_locked()); + on_commit(&doc.state.clone(), &doc.oplog.clone(), self.id_span()); + } + Ok(None) + } + + /// Mark the start of a batch that `LoroDoc` rolls back if it fails + /// ([`Self::roll_back_scope`]). The txn may already hold ops; they are kept. + pub(crate) fn begin_rollback_scope(&mut self, id: u64) { + debug_assert!(self.rollback_scope.is_none()); + self.rollback_scope = Some(RollbackScope { + id, + thread: current_thread_mark(), + foreign_ops: false, + counter: self.next_counter, + lamport: self.next_lamport, + is_peer_first_appearance: self.is_peer_first_appearance, + event_hints: FxHashMap::default(), + }); + } + + pub(crate) fn has_rollback_scope(&self) -> bool { + self.rollback_scope.is_some() + } + + pub(crate) fn end_rollback_scope(&mut self, id: u64) { + if self.rollback_scope.as_ref().is_some_and(|s| s.id == id) { + self.rollback_scope = None; + } + } + + /// Whether this is the txn scope `id` began in and every op in it came from + /// the thread that began it. + pub(crate) fn rollback_scope_is_intact(&self, id: u64) -> bool { + self.rollback_scope + .as_ref() + .is_some_and(|s| s.id == id && !s.foreign_ops) + } + + /// Take the ops of scope `id` (which must be intact) out of the txn: it + /// keeps its ops from before the scope, and its counters and event hints are + /// as they were then. The ops stay applied to the state and the DAG's + /// version; the caller undoes them. + pub(crate) fn roll_back_scope(&mut self, id: u64) -> RolledBackBatch { + assert!(self.rollback_scope_is_intact(id)); + let scope = self.rollback_scope.take().unwrap(); + let ops = take(&mut self.local_ops); + for op in ops.iter() { + let end = op.counter + op.atom_len() as Counter; + if end <= scope.counter { + self.local_ops.push(op.clone()); + } else if op.counter < scope.counter { + self.local_ops + .push(op.slice(0, (scope.counter - op.counter) as usize)); + } + } + for (container, (len, last)) in scope.event_hints { + if len == 0 { + self.event_hints.remove(&container); + continue; + } + let hints = self.event_hints.get_mut(&container).unwrap(); + hints.truncate(len); + *hints.last_mut().unwrap() = last.unwrap(); + } + let batch_end = self.next_counter; + self.next_counter = scope.counter; + self.next_lamport = scope.lamport; + self.is_peer_first_appearance = scope.is_peer_first_appearance; + RolledBackBatch { + peer: self.peer, + txn_start_counter: self.start_counter, + txn_start_lamport: self.start_lamport, + deps: self.frontiers.clone(), + dag_frontiers_at_start: self.dag_frontiers_at_start.clone(), + batch_start: scope.counter, + batch_end, + ops, + timestamp: self.latest_timestamp, + } + } + + fn take_options(&self) -> CommitOptions { + let mut options = CommitOptions::new(); + if !self.origin.is_empty() { + options = options.origin(self.origin.as_str()); + } + if let Some(msg) = self.msg.as_ref() { + options = options.commit_msg(msg); + } + if let Some(timestamp) = self.timestamp { + options = options.timestamp(timestamp); + } + options + } + + pub(super) fn apply_local_op( + &mut self, + container: ContainerIdx, + content: RawOpContent, + event: EventHint, + // check whether context and txn are referring to the same state context + doc: &LoroDoc, + ) -> LoroResult<()> { + // A transaction must be applied to the document it was created for. + // `insert_with_txn`/`delete_with_txn` are public API, so this guards + // against misuse (passing one doc's txn to another doc's handler), which + // would otherwise stamp the target doc's state/oplog with the wrong + // peer+counter. Compare doc identity via the `Weak` pointer (no atomic + // upgrade) on the hot path; only upgrade to fill in the error on the + // rare mismatch. + if self.doc.as_ptr() != Arc::as_ptr(&doc.inner) { + let found = doc + .state + .lock() + .peer + .load(std::sync::atomic::Ordering::Relaxed); + let expected = self + .doc + .upgrade() + .map(|d| { + d.state + .lock() + .peer + .load(std::sync::atomic::Ordering::Relaxed) + }) + .unwrap_or(found); + return Err(LoroError::UnmatchedContext { expected, found }); + } + + if let Some(scope) = &mut self.rollback_scope { + if scope.thread != current_thread_mark() { + scope.foreign_ops = true; + } + } + + let len = content.content_len(); + assert!(len > 0); + let raw_op = RawOp { + id: ID { + peer: self.peer, + counter: self.next_counter, + }, + lamport: self.next_lamport, + container, + content, + }; + + let mut oplog = doc.oplog.lock(); + let mut state = doc.state.lock(); + if state.is_deleted(container) { + return Err(LoroError::ContainerDeleted { + container: Box::new(state.arena.idx_to_id(container).unwrap()), + }); + } + + let op = self.arena.convert_raw_op(&raw_op); + state.apply_local_op(&raw_op, &op)?; + { + if !self.is_peer_first_appearance && !oplog.dag.latest_vv_contains_peer(self.peer) { + self.is_peer_first_appearance = true; + } + // update version info + let dep_id = Frontiers::from_id(ID::new(self.peer, self.next_counter - 1)); + let start_id = ID::new(self.peer, self.next_counter); + self.next_counter += len as Counter; + oplog.dag.update_version_on_new_local_op( + if self.local_ops.is_empty() { + &self.frontiers + } else { + &dep_id + }, + start_id, + self.next_lamport, + len, + ); + // Local ops are always visible; bump the cached count incrementally + // instead of recomputing it from the version vectors every op. + oplog.inc_visible_op_count(len); + self.next_lamport += len as Lamport; + // set frontiers to the last op id + let last_id = start_id.inc(len as Counter - 1); + state.frontiers = Frontiers::from_id(last_id); + }; + drop(state); + drop(oplog); + debug_assert_eq!( + event.rle_len(), + op.atom_len(), + "event:{:#?} \nop:{:#?}", + &event, + &op + ); + + let container_hints = self.event_hints.entry(container).or_default(); + if let Some(scope) = &mut self.rollback_scope { + scope + .event_hints + .entry(container) + .or_insert_with(|| (container_hints.len(), container_hints.last().cloned())); + } + + match container_hints.last_mut() { + Some(last) if last.can_merge(&event) => { + last.merge_right(&event); + } + _ => { + container_hints.push(event); + } + } + self.local_ops.push(op); + Ok(()) + } + + /// id can be a str, ContainerID, or ContainerIdRaw. + /// if it's str it will use Root container, which will not be None + pub fn get_text<I: IntoContainerId>(&self, id: I) -> TextHandler { + let id = id.into_container_id(&self.arena, ContainerType::Text); + Handler::new_attached(id, LoroDoc::from_inner(self.doc.upgrade().unwrap())) + .into_text() + .unwrap() + } + + /// id can be a str, ContainerID, or ContainerIdRaw. + /// if it's str it will use Root container, which will not be None + pub fn get_list<I: IntoContainerId>(&self, id: I) -> ListHandler { + let id = id.into_container_id(&self.arena, ContainerType::List); + Handler::new_attached(id, LoroDoc::from_inner(self.doc.upgrade().unwrap())) + .into_list() + .unwrap() + } + + /// id can be a str, ContainerID, or ContainerIdRaw. + /// if it's str it will use Root container, which will not be None + pub fn get_map<I: IntoContainerId>(&self, id: I) -> MapHandler { + let id = id.into_container_id(&self.arena, ContainerType::Map); + Handler::new_attached(id, LoroDoc::from_inner(self.doc.upgrade().unwrap())) + .into_map() + .unwrap() + } + + /// id can be a str, ContainerID, or ContainerIdRaw. + /// if it's str it will use Root container, which will not be None + pub fn get_tree<I: IntoContainerId>(&self, id: I) -> TreeHandler { + let id = id.into_container_id(&self.arena, ContainerType::Tree); + Handler::new_attached(id, LoroDoc::from_inner(self.doc.upgrade().unwrap())) + .into_tree() + .unwrap() + } + pub fn next_id(&self) -> ID { + ID { + peer: self.peer, + counter: self.next_counter, + } + } + + #[inline] + pub fn id_span(&self) -> IdSpan { + IdSpan::new(self.peer, self.start_counter, self.next_counter) + } + + pub fn next_idlp(&self) -> IdLp { + IdLp { + peer: self.peer, + lamport: self.next_lamport, + } + } + + pub fn is_empty(&self) -> bool { + self.local_ops.is_empty() + } + + pub(crate) fn len(&self) -> usize { + (self.next_counter - self.start_counter) as usize + } + + pub(crate) fn set_options(&mut self, options: CommitOptions) { + self.origin = options.origin.unwrap_or_default(); + self.msg = options.commit_msg; + self.timestamp = options.timestamp; + } + + pub(crate) fn set_default_options(&mut self, default_options: crate::loro::CommitOptions) { + if self.origin.is_empty() { + self.origin = default_options.origin.unwrap_or_default(); + } + if self.msg.is_none() { + self.msg = default_options.commit_msg; + } + if self.timestamp.is_none() { + self.timestamp = default_options.timestamp; + } + } +} + +impl Drop for Transaction { + #[tracing::instrument(level = "debug", skip(self))] + fn drop(&mut self) { + if !self.finished { + // TODO: should we abort here or commit here? + // what if commit fails? + let mut panic = DeferredPanic::default(); + let ans = self._commit(&mut panic); + // Raising it while already unwinding would abort the process. + if !std::thread::panicking() { + panic.resume(); + } + ans.unwrap(); + } + } +} + +#[derive(Debug, Clone)] +pub(crate) struct TxnContainerDiff { + pub(crate) idx: ContainerIdx, + pub(crate) diff: Diff, +} + +// PERF: could be compacter +fn change_to_diff( + change: &Change, + doc: Arc<LoroDocInner>, + event_hints: FxHashMap<ContainerIdx, Vec<EventHint>>, +) -> Vec<TxnContainerDiff> { + let mut ans: Vec<TxnContainerDiff> = Vec::with_capacity(change.ops.len()); + let peer = change.id.peer; + let mut lamport = change.lamport; + + // Group ops by container first to match our new structure + let mut ops_by_container: FxHashMap<ContainerIdx, Vec<Op>> = FxHashMap::default(); + for op in change.ops.iter() { + ops_by_container + .entry(op.container) + .or_default() + .push(op.clone()); + } + + // Process each container's hints and ops together + for (container_idx, hints) in event_hints { + let Some(container_ops) = ops_by_container.get_mut(&container_idx) else { + continue; + }; + + let mut op_index = 0; + let mut hint_iter = hints.into_iter(); + let mut current_hint = hint_iter.next(); + + while op_index < container_ops.len() { + let Some(hint) = current_hint.take() else { + unreachable!("Missing hint for op"); + }; + + // Collect the ops that belong to this hint. Ops and hints merge by + // different rules (text delete hints use UTF-16 spans in WASM), so a + // hint can cover several ops and an op can cover several hints. + let mut ops_for_hint: SmallVec<[Op; 1]> = SmallVec::new(); + let mut total_len = 0; + while total_len < hint.rle_len() { + let Some(op) = container_ops.get_mut(op_index) else { + unreachable!("Op/hint length mismatch: {hint:?}"); + }; + let op_len = op.atom_len(); + let needed = hint.rle_len() - total_len; + if op_len > needed { + ops_for_hint.push(op.slice(0, needed)); + *op = op.slice(needed, op_len); + total_len += needed; + } else { + total_len += op_len; + ops_for_hint.push(op.clone()); + op_index += 1; + } + } + + debug_assert!( + ops_for_hint.iter().all(|op| op_matches_hint(op, &hint)), + "Op/hint kind mismatch: {hint:?} {ops_for_hint:?}" + ); + + // Move to next hint + current_hint = hint_iter.next(); + + // Generate diff based on hint type + match hint { + EventHint::Mark { start, end, style } => { + let mut meta = StyleMeta::default(); + meta.insert( + style.key.clone(), + StyleMetaItem { + lamport, + peer: change.id.peer, + value: style.data, + }, + ); + let diff = DeltaRopeBuilder::new() + .retain(start as usize, Default::default()) + .retain( + (end - start) as usize, + meta.to_option_map().unwrap_or_default().into(), + ) + .build(); + ans.push(TxnContainerDiff { + idx: container_idx, + diff: Diff::Text(diff), + }); + } + EventHint::InsertText { styles, pos, .. } => { + let mut delta: TextDiff = DeltaRopeBuilder::new() + .retain(pos as usize, Default::default()) + .build(); + for op in ops_for_hint.iter() { + let InnerListOp::InsertText { slice, .. } = op.content.as_list().unwrap() + else { + unreachable!() + }; + + delta.push_insert( + slice.clone().into(), + styles.to_option_map().unwrap_or_default().into(), + ); + } + ans.push(TxnContainerDiff { + idx: container_idx, + diff: Diff::Text(delta), + }) + } + EventHint::DeleteText { + span, + unicode_len: _, + // we don't need to iter over ops here, because we already + // know what the events should be + } => ans.push(TxnContainerDiff { + idx: container_idx, + diff: Diff::Text( + DeltaRopeBuilder::new() + .retain(span.start() as usize, Default::default()) + .delete(span.len()) + .build(), + ), + }), + EventHint::InsertList { pos, .. } => { + // We should use pos from event hint because index in op may + // be using op index for the MovableList + let mut index = pos; + for op in ops_for_hint.iter() { + let (range, _) = op.content.as_list().unwrap().as_insert().unwrap(); + let values = range + .as_slice() + .iter() + .map(|v| ValueOrHandler::from_value(v.clone(), &doc)); + let len = values.len(); + ans.push(TxnContainerDiff { + idx: container_idx, + diff: Diff::List( + DeltaRopeBuilder::new() + .retain(index, Default::default()) + .insert_many(values, Default::default()) + .build(), + ), + }); + index += len; + } + } + EventHint::DeleteList(s) => { + ans.push(TxnContainerDiff { + idx: container_idx, + diff: Diff::List( + DeltaRopeBuilder::new() + .retain(s.start() as usize, Default::default()) + .delete(s.len()) + .build(), + ), + }); + } + EventHint::Map { key, value } => { + // Mirror `MapState::apply_diff_and_convert`: a marker write surfaces to + // subscribers as the deterministic Container, not the raw binary value. + let parent_id = doc.arena.idx_to_id(container_idx); + let value = value.map(|v| match parent_id.as_ref() { + Some(pid) => { + loro_common::translate_mergeable_marker_value(pid, key.as_ref(), v) + } + None => v, + }); + ans.push(TxnContainerDiff { + idx: container_idx, + diff: Diff::Map(ResolvedMapDelta::new().with_entry( + key, + ResolvedMapValue { + value: value.map(|v| ValueOrHandler::from_value(v, &doc)), + idlp: IdLp::new(peer, lamport), + }, + )), + }); + } + EventHint::Tree(tree_diff) => { + let mut diff = TreeDiff::default(); + diff.diff.extend(tree_diff); + ans.push(TxnContainerDiff { + idx: container_idx, + diff: Diff::Tree(diff), + }); + } + EventHint::Move { from, to, value } => { + let mut a = DeltaRopeBuilder::new() + .retain(from as usize, Default::default()) + .delete(1) + .build(); + a.compose( + &DeltaRopeBuilder::new() + .retain(to as usize, Default::default()) + .insert( + ArrayVec::from([ValueOrHandler::from_value(value, &doc)]), + ListDeltaMeta { from_move: true }, + ) + .build(), + ); + ans.push(TxnContainerDiff { + idx: container_idx, + diff: Diff::List(a), + }); + } + EventHint::SetList { index, value } => { + ans.push(TxnContainerDiff { + idx: container_idx, + diff: Diff::List( + DeltaRopeBuilder::new() + .retain(index, Default::default()) + .delete(1) + .insert( + ArrayVec::from([ValueOrHandler::from_value(value, &doc)]), + Default::default(), + ) + .build(), + ), + }); + } + EventHint::MarkEnd => { + // do nothing + } + #[cfg(feature = "counter")] + EventHint::Counter(diff) => { + ans.push(TxnContainerDiff { + idx: container_idx, + diff: Diff::Counter(diff), + }); + } + } + + // Update lamport for this hint's operations + lamport += ops_for_hint + .iter() + .map(|x| x.content_len() as Lamport) + .sum::<Lamport>(); + } + + debug_assert!( + current_hint.is_none(), + "Unused event hint: {current_hint:?}" + ); + } + + ans +} + +/// Whether `op` is the kind of op `hint` was recorded for. +fn op_matches_hint(op: &Op, hint: &EventHint) -> bool { + match &op.content { + InnerContent::List(list_op) => matches!( + (list_op, hint), + (InnerListOp::StyleStart { .. }, EventHint::Mark { .. }) + | (InnerListOp::StyleEnd, EventHint::MarkEnd) + | (InnerListOp::InsertText { .. }, EventHint::InsertText { .. }) + | ( + InnerListOp::Delete(_), + EventHint::DeleteText { .. } | EventHint::DeleteList(_) + ) + | (InnerListOp::Insert { .. }, EventHint::InsertList { .. }) + | (InnerListOp::Move { .. }, EventHint::Move { .. }) + | (InnerListOp::Set { .. }, EventHint::SetList { .. }) + ), + InnerContent::Map(_) => matches!(hint, EventHint::Map { .. }), + InnerContent::Tree(_) => matches!(hint, EventHint::Tree(_)), + #[cfg(feature = "counter")] + InnerContent::Future(crate::op::FutureInnerContent::Counter(_)) => { + matches!(hint, EventHint::Counter(_)) + } + InnerContent::Future(_) => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{cursor::PosType, version::Frontiers}; + + #[test] + fn txn_creation_rolls_back_in_txn_after_peer_conflict() { + let doc = LoroDoc::new(); + doc.set_detached_editing(true); + doc.set_peer_id(7).unwrap(); + + let text = doc.get_text("text"); + let mut txn = doc.txn().unwrap(); + text.insert_with_txn(&mut txn, 0, "a", PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + + doc.checkout(&Frontiers::default()).unwrap(); + doc.set_peer_id(7).unwrap(); + + let err = doc + .txn() + .expect_err("stale detached frontiers should reject reusing the same peer"); + assert!(matches!( + err, + LoroError::ConcurrentOpsWithSamePeerID { peer: 7, .. } + )); + assert!(!doc.app_state().lock().is_in_txn()); + } +} diff --git a/vendor/loro-internal/src/undo.rs b/vendor/loro-internal/src/undo.rs new file mode 100644 index 0000000..f3ce20c --- /dev/null +++ b/vendor/loro-internal/src/undo.rs @@ -0,0 +1,1243 @@ +use std::{cell::RefCell, collections::VecDeque, sync::Arc}; + +use crate::sync::{AtomicU64, Mutex}; +use either::Either; +use loro_common::{ + ContainerID, Counter, CounterSpan, HasIdSpan, IdSpan, LoroError, LoroResult, LoroValue, PeerID, +}; +use parking_lot::lock_api::ReentrantMutex; +use rustc_hash::{FxHashMap, FxHashSet}; +use tracing::{debug_span, info_span, instrument}; + +use crate::{ + change::{get_sys_timestamp, Timestamp}, + cursor::{AbsolutePosition, Cursor}, + delta::TreeExternalDiff, + event::{Diff, EventTriggerKind, KeptChange}, + version::Frontiers, + ContainerDiff, DiffEvent, DocDiff, LoroDoc, Subscription, +}; + +#[cfg(test)] +mod atomicity_tests; +pub(crate) mod movable_list; + +/// A batch of diffs. +/// +/// You can use `loroDoc.apply_diff(diff)` to apply the diff to the document. +#[derive(Debug, Clone, Default)] +pub struct DiffBatch { + pub cid_to_events: FxHashMap<ContainerID, Diff>, + pub order: Vec<ContainerID>, + /// Set on batches from [`LoroDoc::diff`]: a mergeable child the batch re-activates carries + /// its full state (no entry means empty), which `apply_diff` aligns with whatever hidden + /// state the target doc keeps at that deterministic cid. Unset batches (local events, + /// hand-built ones) are applied incrementally, as a doc that shares the source's hidden + /// state needs. Local events must stay unset: a plain re-ensure has no child entry because + /// the child is unchanged, which a full-state batch would read as "empty". Import and + /// checkout events do carry full states for revived children, so they may be set. See + /// context/mergeable-containers.md. + pub full_state: bool, +} + +impl DiffBatch { + pub fn new(diff: Vec<DocDiff>) -> Self { + let mut map: FxHashMap<ContainerID, Diff> = Default::default(); + let mut order: Vec<ContainerID> = Vec::with_capacity(diff.len()); + for d in diff.into_iter() { + for item in d.diff.into_iter() { + let old = map.insert(item.id.clone(), item.diff); + assert!(old.is_none(), "Duplicate container ID in diff events"); + order.push(item.id.clone()); + } + } + + Self { + cid_to_events: map, + order, + full_state: false, + } + } + + /// Like [`DiffBatch::new`], but a container that kept its state while its event reports a + /// full-state revival contributes its actual change. Use it for a batch applied to the doc + /// it was computed on (revert, undo). See [`crate::event::KeptChange`]. + pub(crate) fn from_changes(diff: Vec<DocDiff>) -> Self { + let mut map: FxHashMap<ContainerID, Diff> = Default::default(); + let mut order: Vec<ContainerID> = Vec::with_capacity(diff.len()); + for d in diff.into_iter() { + for item in d.diff.into_iter() { + let change = match item.kept { + None => item.diff, + Some(KeptChange::Unchanged) => continue, + Some(KeptChange::Changed(change)) => change, + }; + let old = map.insert(item.id.clone(), change); + assert!(old.is_none(), "Duplicate container ID in diff events"); + order.push(item.id); + } + } + + Self { + cid_to_events: map, + order, + full_state: false, + } + } + + /// Composes `other` after `self`. + /// + /// [`DiffBatch::full_state`] composes as follows. An empty batch is the identity, so + /// composing into one adopts `other`'s flag. Two full-state batches stay full-state: a + /// mergeable child that `other` re-activates was hidden at the version where the batches + /// meet, so `self` has no entry for it, and a child `self` re-activated followed by + /// increments is still a full state. Two incremental batches stay incremental. A + /// full-state batch and an incremental one cannot be composed: re-activated children would + /// mix full states and increments on hidden state, which neither mode can apply. + /// + /// # Panics + /// + /// If both batches are non-empty and exactly one of them is full-state. + pub fn compose(&mut self, other: &Self) { + if other.cid_to_events.is_empty() { + return; + } + if self.cid_to_events.is_empty() { + self.full_state = other.full_state; + } + assert_eq!( + self.full_state, other.full_state, + "cannot compose a full-state DiffBatch with an incremental one" + ); + + for (id, diff) in other.iter() { + if let Some(this_diff) = self.cid_to_events.get_mut(id) { + this_diff.compose_ref(diff); + } else { + self.cid_to_events.insert(id.clone(), diff.clone()); + self.order.push(id.clone()); + } + } + } + + pub fn transform(&mut self, other: &Self, left_priority: bool) { + if other.cid_to_events.is_empty() || self.cid_to_events.is_empty() { + return; + } + + for (idx, diff) in self.cid_to_events.iter_mut() { + if let Some(b_diff) = other.cid_to_events.get(idx) { + diff.transform(b_diff, left_priority); + } + } + } + + pub fn clear(&mut self) { + self.cid_to_events.clear(); + self.order.clear(); + self.full_state = false; + } + + pub fn iter(&self) -> impl Iterator<Item = (&ContainerID, &Diff)> + '_ { + self.order + .iter() + .map(|cid| (cid, self.cid_to_events.get(cid).unwrap())) + } + + #[allow(clippy::should_implement_trait)] + pub fn into_iter(self) -> impl Iterator<Item = (ContainerID, Diff)> { + let mut cid_to_events = self.cid_to_events; + self.order.into_iter().map(move |cid| { + let d = cid_to_events.remove(&cid).unwrap(); + (cid, d) + }) + } +} + +fn transform_cursor( + cursor_with_pos: &mut CursorWithPos, + remote_diff: &DiffBatch, + doc: &LoroDoc, + container_remap: &FxHashMap<ContainerID, ContainerID>, +) { + let mut container_changed = false; + let mut cid = &cursor_with_pos.cursor.container; + while let Some(new_cid) = container_remap.get(cid) { + cid = new_cid; + container_changed = true; + } + + if cursor_with_pos.cursor.id.is_none() { + // We don't need to transform a cursor that always points to the leftmost or rightmost position + if container_changed { + cursor_with_pos.cursor.container = cid.clone(); + } + return; + } + + if let Some(diff) = remote_diff.cid_to_events.get(cid) { + let new_pos = diff.transform_cursor(cursor_with_pos.pos.pos, false); + cursor_with_pos.pos.pos = new_pos; + }; + + let new_pos = cursor_with_pos.pos.pos; + // Cursors come from the user's `on_push` and may name a missing container + let Some(handler) = doc.get_handler(cid.clone()) else { + return; + }; + match handler { + crate::handler::Handler::Text(h) => { + let Some(new_cursor) = h.get_cursor_internal(new_pos, cursor_with_pos.pos.side, false) + else { + return; + }; + + cursor_with_pos.cursor = new_cursor; + } + crate::handler::Handler::List(h) => { + let Some(new_cursor) = h.get_cursor(new_pos, cursor_with_pos.pos.side) else { + return; + }; + + cursor_with_pos.cursor = new_cursor; + } + crate::handler::Handler::MovableList(h) => { + let Some(new_cursor) = h.get_cursor(new_pos, cursor_with_pos.pos.side) else { + return; + }; + + cursor_with_pos.cursor = new_cursor; + } + crate::handler::Handler::Map(_) => {} + crate::handler::Handler::Tree(_) => {} + crate::handler::Handler::Unknown(_) => {} + #[cfg(feature = "counter")] + crate::handler::Handler::Counter(_) => {} + } +} + +/// UndoManager is responsible for managing undo/redo from the current peer's perspective. +/// +/// Undo/local is local: it cannot be used to undone the changes made by other peers. +/// If you want to undo changes made by other peers, you may need to use the time travel feature. +/// +/// PeerID cannot be changed during the lifetime of the UndoManager +pub struct UndoManager { + peer: Arc<AtomicU64>, + container_remap: Arc<Mutex<FxHashMap<ContainerID, ContainerID>>>, + element_remap: Mutex<movable_list::ElementRemap>, + inner: Arc<parking_lot::ReentrantMutex<RefCell<UndoManagerInner>>>, + _peer_id_change_sub: Subscription, + _undo_sub: Subscription, + doc: LoroDoc, +} + +impl std::fmt::Debug for UndoManager { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("UndoManager") + .field("peer", &self.peer) + .field("container_remap", &self.container_remap) + .field("inner", &self.inner) + .finish() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UndoOrRedo { + Undo, + Redo, +} + +impl UndoOrRedo { + fn opposite(&self) -> UndoOrRedo { + match self { + Self::Undo => Self::Redo, + Self::Redo => Self::Undo, + } + } +} + +/// When a undo/redo item is pushed, the undo manager will call the on_push callback to get the meta data of the undo item. +/// The returned cursors will be recorded for a new pushed undo item. +pub type OnPush = Box< + dyn for<'a> Fn(UndoOrRedo, CounterSpan, Option<DiffEvent<'a>>) -> UndoItemMeta + Send + Sync, +>; +pub type OnPop = Box<dyn Fn(UndoOrRedo, CounterSpan, UndoItemMeta) + Send + Sync>; + +struct UndoManagerInner { + next_counter: Option<Counter>, + undo_stack: Stack, + redo_stack: Stack, + processing_undo: bool, + paused: bool, + last_undo_time: i64, + merge_interval_in_ms: i64, + max_stack_size: usize, + exclude_origin_prefixes: Vec<Box<str>>, + last_popped_selection: Option<Vec<CursorWithPos>>, + on_push: Option<OnPush>, + on_pop: Option<OnPop>, + group: Option<UndoGroup>, +} + +impl std::fmt::Debug for UndoManagerInner { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("UndoManagerInner") + .field("latest_counter", &self.next_counter) + .field("undo_stack", &self.undo_stack) + .field("redo_stack", &self.redo_stack) + .field("processing_undo", &self.processing_undo) + .field("last_undo_time", &self.last_undo_time) + .field("merge_interval", &self.merge_interval_in_ms) + .field("max_stack_size", &self.max_stack_size) + .field("exclude_origin_prefixes", &self.exclude_origin_prefixes) + .field("group", &self.group) + .finish() + } +} + +#[derive(Debug, Clone, Default)] +struct UndoGroup { + start_counter: Counter, + affected_cids: FxHashSet<ContainerID>, +} + +impl UndoGroup { + pub fn new(start_counter: Counter) -> Self { + Self { + start_counter, + affected_cids: Default::default(), + } + } +} + +struct ProcessingUndoGuard { + inner: Arc<parking_lot::ReentrantMutex<RefCell<UndoManagerInner>>>, +} + +impl Drop for ProcessingUndoGuard { + fn drop(&mut self) { + self.inner.lock().borrow_mut().processing_undo = false; + } +} + +#[derive(Debug)] +struct Stack { + stack: VecDeque<(VecDeque<StackItem>, Arc<Mutex<DiffBatch>>)>, + size: usize, +} + +#[derive(Debug, Clone)] +struct StackItem { + span: CounterSpan, + meta: UndoItemMeta, +} + +/// The metadata of an undo item. +/// +/// The cursors inside the metadata will be transformed by remote operations as well. +/// So that when the item is popped, users can restore the cursors position correctly. +#[derive(Debug, Default, Clone)] +pub struct UndoItemMeta { + pub value: LoroValue, + pub cursors: Vec<CursorWithPos>, +} + +#[derive(Debug, Clone)] +pub struct CursorWithPos { + pub cursor: Cursor, + pub pos: AbsolutePosition, +} + +impl UndoItemMeta { + pub fn new() -> Self { + Self { + value: LoroValue::Null, + cursors: Default::default(), + } + } + + /// It's assumed that the cursor is just acquired before the ops that + /// need to be undo/redo. + /// + /// We need to rely on the validity of the original pos value + pub fn add_cursor(&mut self, cursor: &Cursor) { + self.cursors.push(CursorWithPos { + cursor: cursor.clone(), + pos: AbsolutePosition { + pos: cursor.origin_pos, + side: cursor.side, + }, + }); + } + + pub fn set_value(&mut self, value: LoroValue) { + self.value = value; + } +} + +impl Stack { + pub fn new() -> Self { + let mut stack = VecDeque::new(); + stack.push_back((VecDeque::new(), Arc::new(Mutex::new(Default::default())))); + Stack { stack, size: 0 } + } + + /// Peek the top-most StackItem's metadata without modifying the stack. + /// + /// Returns None if the stack is empty. + fn peek_top_meta(&self) -> Option<UndoItemMeta> { + if self.is_empty() { + return None; + } + + for (items, _) in self.stack.iter().rev() { + if let Some(item) = items.back() { + return Some(item.meta.clone()); + } + } + + None + } + + pub fn pop(&mut self) -> Option<(StackItem, Arc<Mutex<DiffBatch>>)> { + while self.stack.back().unwrap().0.is_empty() && self.stack.len() > 1 { + let (_, diff) = self.stack.pop_back().unwrap(); + let diff = diff.lock(); + if !diff.cid_to_events.is_empty() { + self.stack.back_mut().unwrap().1.lock().compose(&diff); + } + } + + if self.stack.len() == 1 && self.stack.back().unwrap().0.is_empty() { + // If the stack is empty, we need to clear the remote diff + self.stack.back_mut().unwrap().1.lock().clear(); + return None; + } + + self.size -= 1; + let last = self.stack.back_mut().unwrap(); + last.0.pop_back().map(|x| (x, last.1.clone())) + // If this row in stack is empty, we don't pop it right away + // Because we still need the remote diff to be available. + // Cursor position transformation relies on the remote diff in the same row. + } + + pub fn push(&mut self, span: CounterSpan, meta: UndoItemMeta) { + self.push_with_merge(span, meta, false, None) + } + + fn restore_popped(&mut self, item: StackItem, remote_diff: &Arc<Mutex<DiffBatch>>) { + let last = self.stack.back_mut().unwrap(); + assert!( + Arc::ptr_eq(&last.1, remote_diff), + "failed undo lost its remote-diff row" + ); + last.0.push_back(item); + self.size += 1; + } + + pub fn push_with_merge( + &mut self, + span: CounterSpan, + meta: UndoItemMeta, + can_merge: bool, + group: Option<&UndoGroup>, + ) { + let last = self.stack.back_mut().unwrap(); + let last_remote_diff = last.1.lock(); + + // Check if the remote diff is disjoint with the current undo group + let is_disjoint_group = group.is_some_and(|g| { + g.affected_cids.iter().all(|cid| { + last_remote_diff + .cid_to_events + .get(cid) + .is_none_or(|diff| diff.is_empty()) + }) + }); + + // Can't merge if remote diffs exist and it's not disjoint with the current undo group + let should_create_new_entry = + !last_remote_diff.cid_to_events.is_empty() && !is_disjoint_group; + + if should_create_new_entry { + // Create a new entry in the stack + drop(last_remote_diff); + let mut v = VecDeque::new(); + v.push_back(StackItem { span, meta }); + self.stack + .push_back((v, Arc::new(Mutex::new(DiffBatch::default())))); + self.size += 1; + return; + } + + // Try to merge with the previous entry if allowed + if can_merge { + if let Some(last_span) = last.0.back_mut() { + if last_span.span.end == span.start { + // Merge spans by extending the end of the last span + last_span.span.end = span.end; + return; + } + } + } + + // Add as a new item to the existing entry + self.size += 1; + last.0.push_back(StackItem { span, meta }); + } + + pub fn compose_remote_event(&mut self, diff: &[&ContainerDiff]) { + if self.is_empty() { + return; + } + + let remote_diff = &mut self.stack.back_mut().unwrap().1; + let mut remote_diff = remote_diff.lock(); + for e in diff { + // Transform against what actually changed. A re-activated mergeable child's event + // is its full state, but its content (and the undo items' positions in it) stayed. + let Some(change) = e.change() else { + continue; + }; + if let Some(d) = remote_diff.cid_to_events.get_mut(&e.id) { + d.compose_ref(change); + } else { + remote_diff + .cid_to_events + .insert(e.id.clone(), change.clone()); + remote_diff.order.push(e.id.clone()); + } + } + } + + pub fn transform_based_on_this_delta(&mut self, diff: &DiffBatch) { + if self.is_empty() { + return; + } + let remote_diff = &mut self.stack.back_mut().unwrap().1; + remote_diff.lock().transform(diff, false); + } + + pub fn clear(&mut self) { + self.stack = VecDeque::new(); + self.stack.push_back((VecDeque::new(), Default::default())); + self.size = 0; + } + + pub fn is_empty(&self) -> bool { + self.size == 0 + } + + pub fn len(&self) -> usize { + self.size + } + + fn discard_empty_front_rows(&mut self) { + // Undo pop can leave an empty front row that only carries remote diffs. + // There is no older stack item for that diff to transform during trimming. + while self + .stack + .front() + .is_some_and(|(items, _)| items.is_empty()) + { + self.stack.pop_front(); + } + } + + fn ensure_trailing_empty_row(&mut self) { + if self.stack.is_empty() { + self.stack + .push_back((VecDeque::new(), Arc::new(Mutex::new(Default::default())))); + } + } + + fn pop_front(&mut self) { + if self.is_empty() { + return; + } + + self.discard_empty_front_rows(); + self.size -= 1; + let first = self.stack.front_mut().unwrap(); + let f = first.0.pop_front(); + assert!(f.is_some()); + if first.0.is_empty() { + self.stack.pop_front(); + } + + self.ensure_trailing_empty_row(); + } + + fn set_top_meta(&mut self, meta: UndoItemMeta) { + let Some(top) = self.stack.back_mut() else { + return; + }; + let Some(last) = top.0.back_mut() else { + return; + }; + last.meta = meta; + } +} + +impl Default for Stack { + fn default() -> Self { + Stack::new() + } +} + +impl UndoManagerInner { + fn new(last_counter: Counter) -> Self { + Self { + next_counter: Some(last_counter), + undo_stack: Default::default(), + redo_stack: Default::default(), + processing_undo: false, + paused: false, + merge_interval_in_ms: 0, + last_undo_time: 0, + max_stack_size: usize::MAX, + exclude_origin_prefixes: vec![], + last_popped_selection: None, + on_pop: None, + on_push: None, + group: None, + } + } + + /// Returns true if a given container diff is disjoint with the current group. + /// They are disjoint if they have no overlap in changed container ids. + fn is_disjoint_with_group(&self, diff: &[&ContainerDiff]) -> bool { + let Some(group) = &self.group else { + return false; + }; + + diff.iter().all(|d| !group.affected_cids.contains(&d.id)) + } + + fn record_checkpoint(this: &RefCell<Self>, latest_counter: Counter, event: Option<DiffEvent>) { + let previous_counter = this.borrow().next_counter; + + if Some(latest_counter) == this.borrow().next_counter { + return; + } + + if this.borrow().next_counter.is_none() { + this.borrow_mut().next_counter = Some(latest_counter); + return; + } + + if let Some(group) = &mut this.borrow_mut().group { + event.iter().for_each(|e| { + e.events.iter().for_each(|e| { + group.affected_cids.insert(e.id.clone()); + }) + }); + } + + let now = get_sys_timestamp() as Timestamp; + let span = CounterSpan::new(this.borrow().next_counter.unwrap(), latest_counter); + let meta = this + .borrow() + .on_push + .as_ref() + .map(|x| x(UndoOrRedo::Undo, span, event)) + .unwrap_or_default(); + + let mut this = this.borrow_mut(); + let this: &mut Self = &mut this; + // Wether the change is within the accepted merge interval + let in_merge_interval = now - this.last_undo_time < this.merge_interval_in_ms; + + // If group is active, but there is nothing in the group, don't merge + // If the group is active and it's not the first push in the group, merge + let group_should_merge = this.group.is_some() + && match ( + previous_counter, + this.group.as_ref().map(|g| g.start_counter), + ) { + (Some(previous), Some(active)) => previous != active, + _ => true, + }; + + let should_merge = !this.undo_stack.is_empty() && (in_merge_interval || group_should_merge); + + if should_merge { + this.undo_stack + .push_with_merge(span, meta, true, this.group.as_ref()); + } else { + this.last_undo_time = now; + this.undo_stack.push(span, meta); + } + + this.next_counter = Some(latest_counter); + this.redo_stack.clear(); + while this.undo_stack.len() > this.max_stack_size { + this.undo_stack.pop_front(); + } + } +} + +fn get_counter_end(doc: &LoroDoc, peer: PeerID) -> Counter { + doc.oplog().lock().vv().get(&peer).cloned().unwrap_or(0) +} + +impl UndoManager { + pub fn new(doc: &LoroDoc) -> Self { + let peer = Arc::new(AtomicU64::new(doc.peer_id())); + let peer_clone = peer.clone(); + let peer_clone2 = peer.clone(); + let inner = Arc::new(ReentrantMutex::new(RefCell::new(UndoManagerInner::new( + get_counter_end(doc, doc.peer_id()), + )))); + let inner_clone = inner.clone(); + let inner_clone2 = inner.clone(); + let remap_containers = Arc::new(Mutex::new(FxHashMap::default())); + let remap_containers_clone = remap_containers.clone(); + let undo_sub = doc.subscribe_root(Arc::new(move |event| match event.event_meta.by { + EventTriggerKind::Local => { + // TODO: PERF undo can be significantly faster if we can get + // the DiffBatch for undo here + let lock = inner_clone.lock(); + if lock.borrow().processing_undo { + return; + } + if let Some(id) = event + .event_meta + .to + .iter() + .find(|x| x.peer == peer_clone.load(std::sync::atomic::Ordering::Relaxed)) + { + let is_paused = lock.borrow().paused; + let should_exclude = lock + .borrow() + .exclude_origin_prefixes + .iter() + .any(|x| event.event_meta.origin.starts_with(&**x)); + if is_paused || should_exclude { + // Paused and excluded-origin edits are not recorded as + // undo steps, but their effects must be composed into + // both stacks so transforms stay correct, and + // next_counter must advance so the next recorded item + // does not fold these edits into its span. + let mut inner = lock.borrow_mut(); + inner.undo_stack.compose_remote_event(event.events); + inner.redo_stack.compose_remote_event(event.events); + inner.next_counter = Some(id.counter + 1); + } else { + UndoManagerInner::record_checkpoint(&lock, id.counter + 1, Some(event)); + } + } + } + EventTriggerKind::Import => { + let lock = inner_clone.lock(); + let mut inner = lock.borrow_mut(); + + for e in event.events { + if let Diff::Tree(tree) = &e.diff { + for item in &tree.diff { + let target = item.target; + if let TreeExternalDiff::Create { .. } = &item.action { + // If the concurrent event is a create event, it may bring the deleted tree node back, + // so we need to remove it from the remap of the container. + remap_containers_clone + .lock() + .remove(&target.associated_meta_container()); + } + } + } + } + + let is_import_disjoint = inner.is_disjoint_with_group(event.events); + + inner.undo_stack.compose_remote_event(event.events); + inner.redo_stack.compose_remote_event(event.events); + + // If the import is not disjoint, we end the active group + // all subsequent changes will be new undo items + if !is_import_disjoint { + inner.group = None; + } + } + EventTriggerKind::Checkout => { + let lock = inner_clone.lock(); + if lock.borrow().paused { + return; + } + let mut inner = lock.borrow_mut(); + inner.undo_stack.clear(); + inner.redo_stack.clear(); + inner.next_counter = None; + } + })); + + let sub = doc.subscribe_peer_id_change(Box::new(move |id| { + let lock = inner_clone2.lock(); + let mut inner = lock.borrow_mut(); + inner.undo_stack.clear(); + inner.redo_stack.clear(); + inner.next_counter = Some(id.counter); + peer_clone2.store(id.peer, std::sync::atomic::Ordering::Relaxed); + true + })); + + UndoManager { + peer, + container_remap: remap_containers, + element_remap: Mutex::new(FxHashMap::default()), + inner, + _peer_id_change_sub: sub, + _undo_sub: undo_sub, + doc: doc.clone(), + } + } + + pub fn group_start(&self) -> LoroResult<()> { + let lock = self.inner.lock(); + let mut inner = lock.borrow_mut(); + + if inner.group.is_some() { + return Err(LoroError::UndoGroupAlreadyStarted); + } + + inner.group = + Some(UndoGroup::new(inner.next_counter.ok_or_else(|| { + LoroError::Unknown("UndoManager is not ready".into()) + })?)); + + Ok(()) + } + + pub fn group_end(&self) { + self.inner.lock().borrow_mut().group = None; + } + + pub fn peer(&self) -> PeerID { + self.peer.load(std::sync::atomic::Ordering::Relaxed) + } + + pub fn set_merge_interval(&self, interval: i64) { + self.inner.lock().borrow_mut().merge_interval_in_ms = interval; + } + + pub fn set_max_undo_steps(&self, size: usize) { + self.inner.lock().borrow_mut().max_stack_size = size; + } + + pub fn add_exclude_origin_prefix(&self, prefix: &str) { + self.inner + .lock() + .borrow_mut() + .exclude_origin_prefixes + .push(prefix.into()); + } + + pub fn record_new_checkpoint(&self) -> LoroResult<()> { + // Use implicit-style barrier to preserve next-commit options across + // an empty commit before undo/redo processing. + self.doc.with_barrier(|| {}); + let counter = get_counter_end(&self.doc, self.peer()); + UndoManagerInner::record_checkpoint(&self.inner.lock(), counter, None); + Ok(()) + } + + /// Consume at most one undo item, even if its transformed inverse is a no-op. + /// Returns whether local operations were generated; use `can_undo` to check + /// whether history remains after a `false` result. + #[instrument(skip_all)] + pub fn undo(&self) -> LoroResult<bool> { + self.perform( + |x| &mut x.undo_stack, + |x| &mut x.redo_stack, + UndoOrRedo::Undo, + ) + } + + /// Consume at most one redo item, including a no-op. A `false` result means + /// no local operations were generated, not necessarily an empty redo stack. + #[instrument(skip_all)] + pub fn redo(&self) -> LoroResult<bool> { + self.perform( + |x| &mut x.redo_stack, + |x| &mut x.undo_stack, + UndoOrRedo::Redo, + ) + } + + fn perform( + &self, + get_stack: impl Fn(&mut UndoManagerInner) -> &mut Stack, + get_opposite: impl Fn(&mut UndoManagerInner) -> &mut Stack, + kind: UndoOrRedo, + ) -> LoroResult<bool> { + if self.inner.lock().borrow().paused { + return Ok(false); + } + let doc = &self.doc.clone(); + let _exclusive = doc.txn.lock_exclusive(); + // When in the undo/redo loop, the new undo/redo stack item should restore the selection + // to the state it was in before the item that was popped two steps ago from the stack. + // + // ┌────────────┐ + // │Selection 1 │ + // └─────┬──────┘ + // │ Some + // ▼ ops + // ┌────────────┐ + // │Selection 2 │ + // └─────┬──────┘ + // │ Some + // ▼ ops + // ┌────────────┐ + // │Selection 3 │◁ ─ ─ ─ ─ ─ ─ ─ Restore ─ ─ ─ + // └─────┬──────┘ │ + // │ + // │ │ + // │ ┌ ─ ─ ─ ─ ─ ─ ─ + // Enter the │ Undo ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─▶ Push Redo │ + // undo/redo ─ ─ ─ ▶ ▼ └ ─ ─ ─ ─ ─ ─ ─ + // loop ┌────────────┐ │ + // │Selection 2 │◁─ ─ ─ Restore ─ + // └─────┬──────┘ │ │ + // │ + // │ │ │ + // │ ┌ ─ ─ ─ ─ ─ ─ ─ + // │ Undo ─ ─ ─ ─ ▶ Push Redo │ │ + // ▼ └ ─ ─ ─ ─ ─ ─ ─ + // ┌────────────┐ │ │ + // │Selection 1 │ + // └─────┬──────┘ │ │ + // │ Redo ◀ ─ ─ ─ ─ ─ ─ ─ ─ + // ▼ │ + // ┌────────────┐ + // ┌ Restore ─ ▷│Selection 2 │ │ + // └─────┬──────┘ + // │ │ │ + // ┌ ─ ─ ─ ─ ─ ─ ─ │ + // Push Undo │◀─ ─ ─ ─ ─ ─ ─ │ Redo ◀ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ + // └ ─ ─ ─ ─ ─ ─ ─ ▼ + // │ ┌────────────┐ + // │Selection 3 │ + // │ └─────┬──────┘ + // ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ▶ │ Undo + // ▼ + // ┌────────────┐ + // │Selection 2 │ + // └────────────┘ + // + // Because users may change the selections during the undo/redo loop, it's + // more stable to keep the selection stored in the last stack item + // rather than using the current selection directly. + self.record_new_checkpoint()?; + let end_counter = get_counter_end(doc, self.peer()); + let top = { + let lock = self.inner.lock(); + let mut inner = lock.borrow_mut(); + inner.processing_undo = true; + get_stack(&mut inner).pop() + }; + let _guard = ProcessingUndoGuard { + inner: self.inner.clone(), + }; + + let mut executed = false; + // A no-op still consumes this item. Never cross its history boundary + // to undo/redo an unrelated edit in the same call. + if let Some((mut span, remote_diff)) = top { + let mut next_push_selection = None; + { + let inner = self.inner.clone(); + // We need to clone this because otherwise <transform_delta> will be applied to the same remote diff + let remote_change_clone = remote_diff.lock().clone(); + let mut rejected_step = None; + let commit = match doc.undo_internal_with( + IdSpan { + peer: self.peer(), + counter: span.span, + }, + &mut self.container_remap.lock(), + Some(&remote_change_clone), + &mut |diff| { + info_span!("transform remote diff").in_scope(|| { + let inner = inner.lock(); + // <transform_delta> + get_stack(&mut inner.borrow_mut()).transform_based_on_this_delta(diff); + }); + }, + &mut rejected_step, + &mut self.element_remap.lock(), + ) { + Ok(c) => c, + // Keep the documented unknown-container policy: consume a + // prechecked unsupported step and rebase older history. + // Application errors, including other ArgErrs, are retried. + Err(e @ LoroError::ArgErr(_)) if rejected_step.is_some() => { + // Its changes stay in the doc: rebase the steps before + // it over them, like over remote changes + if let Some(mut changes) = rejected_step { + let mut remote = remote_diff.lock(); + changes.compose(&remote); + *remote = changes; + } + return Err(e); + } + Err(e) => { + get_stack(&mut self.inner.lock().borrow_mut()) + .restore_popped(span, &remote_diff); + return Err(e); + } + }; + drop(commit); + let inner = self.inner.lock(); + let mut is_some = false; + + if let Some(on_pop) = inner.borrow().on_pop.as_ref() { + is_some = true; + for cursor in span.meta.cursors.iter_mut() { + // <cursor_transform> We need to transform cursor here. + // Note that right now <transform_delta> is already done, + // remote_diff is also transformed by it now (that's what we need). + transform_cursor( + cursor, + &remote_diff.lock(), + doc, + &self.container_remap.lock(), + ); + } + + on_pop(kind, span.span, span.meta.clone()); + } + if is_some { + let take = inner.borrow_mut().last_popped_selection.take(); + next_push_selection = take; + inner.borrow_mut().last_popped_selection = Some(span.meta.cursors); + } + } + let new_counter = get_counter_end(doc, self.peer()); + if end_counter != new_counter { + let inner = self.inner.lock(); + let mut meta = inner + .borrow() + .on_push + .as_ref() + .map(|x| { + x( + kind.opposite(), + CounterSpan::new(end_counter, new_counter), + None, + ) + }) + .unwrap_or_default(); + + if matches!(kind, UndoOrRedo::Undo) + && get_opposite(&mut inner.borrow_mut()).is_empty() + { + // If it's the first undo, we use the cursors from the users + } else if let Some(inner) = next_push_selection.take() { + // Otherwise, we use the cursors from the undo/redo loop + meta.cursors = inner; + } + + get_opposite(&mut inner.borrow_mut()) + .push(CounterSpan::new(end_counter, new_counter), meta); + inner.borrow_mut().next_counter = Some(new_counter); + executed = true; + } + } + + Ok(executed) + } + + pub fn can_undo(&self) -> bool { + !self.inner.lock().borrow().undo_stack.is_empty() + } + + pub fn can_redo(&self) -> bool { + !self.inner.lock().borrow().redo_stack.is_empty() + } + + pub fn undo_count(&self) -> usize { + self.inner.lock().borrow().undo_stack.len() + } + + pub fn redo_count(&self) -> usize { + self.inner.lock().borrow().redo_stack.len() + } + + /// Get the metadata of the top undo stack item, if any. + pub fn top_undo_meta(&self) -> Option<UndoItemMeta> { + self.inner.lock().borrow().undo_stack.peek_top_meta() + } + + /// Get the metadata of the top redo stack item, if any. + pub fn top_redo_meta(&self) -> Option<UndoItemMeta> { + self.inner.lock().borrow().redo_stack.peek_top_meta() + } + + /// Get the value associated with the top undo stack item, if any. + pub fn top_undo_value(&self) -> Option<LoroValue> { + self.top_undo_meta().map(|m| m.value) + } + + /// Get the value associated with the top redo stack item, if any. + pub fn top_redo_value(&self) -> Option<LoroValue> { + self.top_redo_meta().map(|m| m.value) + } + + pub fn set_on_push(&self, on_push: Option<OnPush>) { + self.inner.lock().borrow_mut().on_push = on_push; + } + + pub fn set_on_pop(&self, on_pop: Option<OnPop>) { + self.inner.lock().borrow_mut().on_pop = on_pop; + } + + pub fn clear(&self) { + self.inner.lock().borrow_mut().undo_stack.clear(); + self.inner.lock().borrow_mut().redo_stack.clear(); + } + + /// Clear only the redo stack, preserving the undo stack. + pub fn clear_redo(&self) { + self.inner.lock().borrow_mut().redo_stack.clear(); + } + + /// Clear only the undo stack, preserving the redo stack. + pub fn clear_undo(&self) { + self.inner.lock().borrow_mut().undo_stack.clear(); + } + + /// Pause the UndoManager so that local edits and checkout events are ignored. + /// + /// While paused, local edits are not recorded as undo steps and checkout + /// events do not clear the stacks. Import events (remote changes) are still + /// processed so that the stacks remain correctly transformed against + /// concurrent edits. + /// + /// Use this before temporary checkouts (e.g. read-only history preview) that + /// should not disturb the undo/redo history. Close any open group (via + /// [`Self::group_end`]) before pausing. + /// + /// Call [`Self::resume`] after returning the document to its original state. + pub fn pause(&self) { + self.inner.lock().borrow_mut().paused = true; + } + + /// Resume the UndoManager after a [`Self::pause`]. + pub fn resume(&self) { + self.inner.lock().borrow_mut().paused = false; + } + + /// Returns whether the UndoManager is currently paused. + pub fn is_paused(&self) -> bool { + self.inner.lock().borrow().paused + } + + pub fn set_top_undo_meta(&self, meta: UndoItemMeta) { + self.inner.lock().borrow_mut().undo_stack.set_top_meta(meta); + } + + pub fn set_top_redo_meta(&self, meta: UndoItemMeta) { + self.inner.lock().borrow_mut().redo_stack.set_top_meta(meta); + } +} + +/// Undo the given spans of operations. +/// +/// # Parameters +/// +/// - `spans`: A vector of tuples where each tuple contains an `IdSpan` and its associated `Frontiers`. +/// - `IdSpan`: Represents a span of operations identified by an ID. +/// - `Frontiers`: Represents the deps of the given id_span +/// - `latest_frontiers`: The latest frontiers of the document +/// - `calc_diff`: A closure that takes two `Frontiers` and calculates the difference between them, returning a `DiffBatch`. +/// +/// # Returns +/// +/// - `DiffBatch`: Applying this batch on the `latest_frontiers` will undo the ops in the given spans. +pub(crate) fn undo( + spans: Vec<(IdSpan, Frontiers)>, + last_frontiers_or_last_bi: Either<&Frontiers, &DiffBatch>, + calc_diff: impl Fn(&Frontiers, &Frontiers) -> DiffBatch, + on_last_event_a: &mut dyn FnMut(&DiffBatch), +) -> DiffBatch { + // The process of performing undo is: + // + // 0. Split the span into a series of continuous spans. There is no external dep within each continuous span. + // + // For each continuous span_i: + // + // 1. a. Calculate the event of checkout from id_span.last to id_span.deps, call it Ai. It undo the ops in the current span. + // b. Calculate A'i = Ai + T(Ci-1, Ai) if i > 0, otherwise A'i = Ai. + // NOTE: A'i can undo the ops in the current span and the previous spans, if it's applied on the id_span.last version. + // 2. Calculate the event of checkout from id_span.last to [the next span's last id] or [the latest version], call it Bi. + // 3. Transform event A'i based on Bi, call it Ci + // 4. If span_i is the last span, apply Ci to the current state. + + // ------------------------------------------------------- + // 0. Split the span into a series of continuous spans + // ------------------------------------------------------- + + let mut last_ci: Option<DiffBatch> = None; + for i in 0..spans.len() { + debug_span!("Undo", ?i, "Undo span {:?}", &spans[i]).in_scope(|| { + let (this_id_span, this_deps) = &spans[i]; + // --------------------------------------- + // 1.a Calc event A_i + // --------------------------------------- + let mut event_a_i = debug_span!("1. Calc event A_i").in_scope(|| { + // Checkout to the last id of the id_span + calc_diff(&this_id_span.id_last().into(), this_deps) + }); + + // println!("event_a_i: {:?}", event_a_i); + + // --------------------------------------- + // 2. Calc event B_i + // --------------------------------------- + let stack_diff_batch; + let event_b_i = 'block: { + let next = if i + 1 < spans.len() { + spans[i + 1].0.id_last().into() + } else { + match last_frontiers_or_last_bi { + Either::Left(last_frontiers) => last_frontiers.clone(), + Either::Right(right) => break 'block right, + } + }; + stack_diff_batch = Some(calc_diff(&this_id_span.id_last().into(), &next)); + stack_diff_batch.as_ref().unwrap() + }; + + // println!("event_b_i: {:?}", event_b_i); + + // event_a_prime can undo the ops in the current span and the previous spans + let mut event_a_prime = if let Some(mut last_ci) = last_ci.take() { + // ------------------------------------------------------------------------------ + // 1.b Transform and apply Ci-1 based on Ai, call it A'i + // ------------------------------------------------------------------------------ + last_ci.transform(&event_a_i, true); + + event_a_i.compose(&last_ci); + event_a_i + } else { + event_a_i + }; + if i == spans.len() - 1 { + on_last_event_a(&event_a_prime); + } + // -------------------------------------------------- + // 3. Transform event A'_i based on B_i, call it C_i + // -------------------------------------------------- + event_a_prime.transform(event_b_i, true); + + // println!("event_a_prime: {:?}", event_a_prime); + + let c_i = event_a_prime; + last_ci = Some(c_i); + }); + } + + last_ci.unwrap() +} diff --git a/vendor/loro-internal/src/undo/atomicity_tests.rs b/vendor/loro-internal/src/undo/atomicity_tests.rs new file mode 100644 index 0000000..7013253 --- /dev/null +++ b/vendor/loro-internal/src/undo/atomicity_tests.rs @@ -0,0 +1,141 @@ +use super::*; +use crate::{ + cursor::PosType, + encoding::ExportMode, + handler::MovableListHandler, + loro::{ + AFTER_APPLY_DIFF_HANDLER, FAIL_APPLY_DIFF_AFTER_HANDLER, FAIL_APPLY_DIFF_WITH_ARG_ERR, + RUN_APPLY_DIFF_HOOK_AFTER_NATIVE_PLAN, + }, +}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +#[test] +fn application_errors_preserve_remote_row_metadata_and_both_identity_maps() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let text = doc.get_text("text"); + text.insert(0, "abc", PosType::Unicode).unwrap(); + let child = doc + .get_map("holder") + .insert_container("child", MovableListHandler::new_detached()) + .unwrap(); + child.push(7.into()).unwrap(); + let list = doc.get_movable_list("list"); + list.push(7.into()).unwrap(); + list.push(8.into()).unwrap(); + doc.commit_then_renew(); + let undo = UndoManager::new(&doc); + undo.set_merge_interval(0); + doc.get_map("older").insert("keep", 42).unwrap(); + doc.commit_then_renew(); + text.delete(0, 1, PosType::Unicode).unwrap(); + list.delete(0, 1).unwrap(); + doc.get_map("holder").delete("child").unwrap(); + doc.commit_then_renew(); + let remote = doc.fork(); + remote.set_peer_id(2).unwrap(); + remote + .get_text("text") + .insert(0, "R", PosType::Unicode) + .unwrap(); + remote.commit_then_renew(); + doc.import(&remote.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + + let pops = Arc::new(AtomicUsize::new(0)); + let captured = pops.clone(); + undo.set_on_pop(Some(Box::new(move |_, _, _| { + captured.fetch_add(1, Ordering::Relaxed); + }))); + let events = Arc::new(AtomicUsize::new(0)); + let captured = events.clone(); + let _sub = doc.subscribe_root(Arc::new(move |_| { + captured.fetch_add(1, Ordering::Relaxed); + })); + + for redo in [false, true] { + // A remote edit after the successful undo also gives the redo item a + // nonempty transform base. Ordinary push would put it in a new row. + if redo { + remote + .import(&doc.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + remote + .get_text("text") + .insert(0, "S", PosType::Unicode) + .unwrap(); + remote.commit_then_renew(); + doc.import(&remote.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + } + let mut meta = UndoItemMeta::new(); + meta.set_value("saved selection".into()); + if redo { + undo.set_top_redo_meta(meta); + } else { + undo.set_top_undo_meta(meta); + } + let row = { + let lock = undo.inner.lock(); + let inner = lock.borrow(); + let stack = if redo { + &inner.redo_stack + } else { + &inner.undo_stack + }; + stack.stack.back().unwrap().1.clone() + }; + assert!(!row.lock().cid_to_events.is_empty()); + let history = format!("{:?}", undo.inner.lock().borrow()); + let containers = undo.container_remap.lock().clone(); + let elements = undo.element_remap.lock().clone(); + let value = doc.get_deep_value(); + let delta = text.get_delta(); + let frontiers = doc.state_frontiers(); + let vv = doc.oplog_vv(); + let seen = events.load(Ordering::Relaxed); + let popped = pops.load(Ordering::Relaxed); + for native in [false, true] { + for arg_err in [false, true] { + let current = list.clone(); + AFTER_APPLY_DIFF_HANDLER.with(|hook| { + *hook.borrow_mut() = Some(Box::new(move || { + // Native edits have really run before either failure. + assert_eq!(current.len(), if redo { 1 } else { 2 }); + })); + }); + RUN_APPLY_DIFF_HOOK_AFTER_NATIVE_PLAN.with(|flag| flag.set(native)); + FAIL_APPLY_DIFF_WITH_ARG_ERR.with(|flag| flag.set(arg_err)); + FAIL_APPLY_DIFF_AFTER_HANDLER.with(|flag| flag.set(true)); + let err = if redo { undo.redo() } else { undo.undo() }.unwrap_err(); + assert!(matches!(err, LoroError::ArgErr(_)) == arg_err); + RUN_APPLY_DIFF_HOOK_AFTER_NATIVE_PLAN.with(|flag| assert!(!flag.get())); + assert_eq!(doc.get_deep_value(), value); + assert_eq!(text.get_delta(), delta); + assert_eq!(doc.state_frontiers(), frontiers); + assert_eq!(doc.oplog_vv(), vv); + assert_eq!(doc.get_pending_txn_len(), 0); + assert_eq!(format!("{:?}", undo.inner.lock().borrow()), history); + assert_eq!(*undo.container_remap.lock(), containers); + assert_eq!(*undo.element_remap.lock(), elements); + let lock = undo.inner.lock(); + let inner = lock.borrow(); + let stack = if redo { + &inner.redo_stack + } else { + &inner.undo_stack + }; + assert!(Arc::ptr_eq(&stack.stack.back().unwrap().1, &row)); + assert_eq!(events.load(Ordering::Relaxed), seen); + assert_eq!(pops.load(Ordering::Relaxed), popped); + } + } + assert!(if redo { undo.redo() } else { undo.undo() }.unwrap()); + assert_eq!(pops.load(Ordering::Relaxed), popped + 1); + assert_eq!(text.to_string(), if redo { "SRbc" } else { "aRbc" }); + assert_eq!(list.len(), if redo { 1 } else { 2 }); + assert_eq!(doc.get_map("holder").get("child").is_some(), !redo); + assert_eq!(doc.get_map("older").get("keep"), Some(42.into())); + } +} diff --git a/vendor/loro-internal/src/undo/movable_list.rs b/vendor/loro-internal/src/undo/movable_list.rs new file mode 100644 index 0000000..197d47a --- /dev/null +++ b/vendor/loro-internal/src/undo/movable_list.rs @@ -0,0 +1,890 @@ +//! Identity and gap anchors for MovableList undo. Public list deltas deliberately +//! carry values, so they cannot distinguish a moved scalar from a new copy. + +use std::{collections::BTreeMap, ops::Bound}; + +use fractional_index::FractionalIndex; +use loro_common::{CompactIdLp, ContainerID, IdLp, IdSpan, LoroError, LoroResult, LoroValue, ID}; +use loro_delta::DeltaRopeBuilder; +use rle::HasLength; +use rustc_hash::{FxHashMap, FxHashSet}; + +use crate::{ + container::list::list_op::InnerListOp, + event::{Diff, ListDeltaMeta}, + handler::{Handler, MovableListHandler, ValueOrHandler}, + op::InnerContent, + state::{IndexType, MovableListState}, + txn::Transaction, + version::Frontiers, + HandlerTrait, LoroDoc, +}; + +use super::DiffBatch; + +pub(crate) type ElementRemap = FxHashMap<CompactIdLp, CompactIdLp>; + +#[derive(Clone)] +struct Element { + index: usize, + id: CompactIdLp, + position: IdLp, + value_id: IdLp, + value: LoroValue, +} + +pub(crate) struct Snapshot { + alive: bool, + elements: Vec<Element>, + targets: FxHashSet<CompactIdLp>, + full: bool, + searches: Vec<AnchorSearch>, +} + +#[derive(Default)] +pub(crate) struct Scope { + ids: FxHashSet<CompactIdLp>, + // Only needed for deletes referring to positions trimmed by a shallow root. + full: bool, +} + +pub(crate) type Scopes = FxHashMap<ContainerID, Scope>; + +/// Insert/move/set name elements directly. A deletion names list positions; +/// resolve each position's insertion or move to its element, without walking +/// the live list. Trimmed positions retain the old full-state fallback. +pub(crate) fn scopes( + doc: &LoroDoc, + spans: &[(IdSpan, Frontiers)], +) -> LoroResult<(Vec<Scopes>, Scopes)> { + let oplog = doc.oplog.lock(); + let mut all: Scopes = Default::default(); + let scopes = spans + .iter() + .map(|(span, _)| { + let mut scopes: Scopes = Default::default(); + for op in oplog.iter_ops(*span) { + if op.container().get_type() != loro_common::ContainerType::MovableList { + continue; + } + let cid = doc.arena.get_container_id(op.container()).ok_or_else(|| { + LoroError::NotFoundError("MovableList undo history container is missing".into()) + })?; + let scope = scopes.entry(cid).or_default(); + match &op.op().content { + InnerContent::List( + InnerListOp::Move { elem_id, .. } | InnerListOp::Set { elem_id, .. }, + ) => { + scope.ids.insert(elem_id.compact()); + } + InnerContent::List(InnerListOp::Insert { .. }) => { + for i in 0..op.atom_len() { + scope + .ids + .insert(IdLp::new(op.peer, op.idlp().lamport + i as u32).compact()); + } + } + InnerContent::List(InnerListOp::Delete(deletion)) => { + for i in 0..deletion.atom_len() { + let id = ID::new( + deletion.id_start.peer, + deletion.id_start.counter + i as i32, + ); + let Some(position) = oplog.get_op_that_includes(id) else { + scope.full = true; + continue; + }; + let element = match &position.content { + InnerContent::List(InnerListOp::Move { elem_id, .. }) => *elem_id, + _ => { + let Some(lamport) = oplog.get_lamport_at(id) else { + scope.full = true; + continue; + }; + IdLp::new(id.peer, lamport) + } + }; + scope.ids.insert(element.compact()); + } + } + _ => {} + } + } + for (cid, scope) in &scopes { + let union = all.entry(cid.clone()).or_default(); + union.ids.extend(scope.ids.iter().copied()); + union.full |= scope.full; + } + Ok(scopes) + }) + .collect::<LoroResult<Vec<_>>>()?; + Ok((scopes, all)) +} + +struct AnchorSearch { + next: isize, + direction: isize, + width: usize, + exhausted: bool, + done: bool, + candidates: Vec<Element>, +} + +fn element_at(list: &MovableListState, index: usize) -> Option<Element> { + let (id, e) = list.get_elem_at_given_pos(index, IndexType::ForUser)?; + #[cfg(test)] + CAPTURE_STATS.with(|stats| { + let (n, model) = stats.get(); + stats.set((n + 1, model)); + }); + Some(Element { + index, + id, + position: e.pos, + value_id: e.value_id, + value: e.value.clone(), + }) +} + +fn element_by_id(list: &MovableListState, id: CompactIdLp) -> Option<Element> { + let e = element_at(list, list.get_index_of_elem(id)?)?; + (e.id == id).then_some(e) +} + +impl AnchorSearch { + fn extend(&mut self, list: &MovableListState, scope: &Scope) { + let mut found = 0; + while self.next >= 0 && self.next < list.len() as isize { + let index = self.next as usize; + self.next += self.direction; + let Some(e) = element_at(list, index) else { + continue; + }; + if scope.ids.contains(&e.id) { + continue; + } + self.candidates.push(e); + found += 1; + if found >= self.width { + break; + } + } + self.exhausted = self.next < 0 || self.next >= list.len() as isize; + self.width *= 2; + } +} + +impl Snapshot { + pub(crate) fn capture(doc: &LoroDoc, cid: &ContainerID) -> Self { + let mut state = doc.state.lock(); + let alive = state.get_reachable(cid); + let elements = doc.arena.id_to_idx(cid).map_or_else(Vec::new, |idx| { + state.with_state(idx, |s| { + let list = s.as_movable_list_state().unwrap(); + list.iter_with_last_move_id_and_elem_id() + .enumerate() + .map(|(index, (pos, id, value))| Element { + index, + id, + position: pos.idlp(), + value_id: list.elements()[&id].value_id, + value: value.clone(), + }) + .collect() + }) + }); + #[cfg(test)] + CAPTURE_STATS.with(|stats| { + let (n, model) = stats.get(); + stats.set((n + elements.len(), model)); + }); + let targets = elements.iter().map(|e| e.id).collect(); + Self { + alive, + elements, + targets, + full: true, + searches: Vec::new(), + } + } + + pub(crate) fn capture_span( + doc: &LoroDoc, + cid: &ContainerID, + scope: &Scope, + all: &Scope, + before: bool, + ) -> Self { + if scope.full || all.full { + return Self::capture(doc, cid); + } + let mut state = doc.state.lock(); + let alive = state.get_reachable(cid); + let (elements, searches) = doc + .arena + .id_to_idx(cid) + .map_or_else(Default::default, |idx| { + state.with_state(idx, |s| { + let list = s.as_movable_list_state().unwrap(); + let ids = if before { &all.ids } else { &scope.ids }; + let elements: Vec<_> = ids + .iter() + .filter_map(|id| element_by_id(list, *id)) + .collect(); + let mut searches = Vec::new(); + if before { + for e in elements.iter().filter(|e| scope.ids.contains(&e.id)) { + for direction in [-1, 1] { + let mut search = AnchorSearch { + next: e.index as isize + direction, + direction, + width: 1, + exhausted: false, + done: false, + candidates: Vec::new(), + }; + search.extend(list, all); + searches.push(search); + } + } + } + (elements, searches) + }) + }); + let mut result = Self { + alive, + elements, + searches, + targets: scope.ids.clone(), + full: false, + }; + result.elements.sort_by_key(|e| e.index); + result + } +} + +pub(crate) struct Inverse { + pub span_index: usize, + pub cid: ContainerID, + pub before: Snapshot, + pub after: Snapshot, + pub before_frontiers: Frontiers, +} + +/// Usually each immediate neighbour survives, so no additional checkout is +/// needed. If remote deletes removed it, expand just that search geometrically +/// in the original view until the nearest surviving neighbour is found. Never +/// copy a live-id table or the unrelated values of a large list. +pub(crate) fn complete_anchors( + doc: &LoroDoc, + inverses: &mut [Inverse], + latest: &Frontiers, + scopes: &Scopes, + remapped: &ElementRemap, + containers: &FxHashMap<ContainerID, ContainerID>, +) -> LoroResult<()> { + for inverse in inverses { + loop { + { + let mut state = doc.state.lock(); + if let Some(idx) = doc.arena.id_to_idx(&remap(&inverse.cid, containers)) { + state.with_state(idx, |s| { + let list = s.as_movable_list_state().unwrap(); + for search in inverse.before.searches.iter_mut().filter(|s| !s.done) { + if let Some(e) = search + .candidates + .iter() + .find(|e| element_by_id(list, remap(&e.id, remapped)).is_some()) + { + inverse.before.elements.push(e.clone()); + search.done = true; + } else if search.exhausted { + search.done = true; + } + } + }); + } + } + if inverse.before.searches.iter().all(|s| s.done) { + break; + } + doc._checkout_without_emitting(&inverse.before_frontiers, false, false)?; + { + let mut state = doc.state.lock(); + if let Some(idx) = doc.arena.id_to_idx(&inverse.cid) { + state.with_state(idx, |s| { + let list = s.as_movable_list_state().unwrap(); + for search in inverse.before.searches.iter_mut().filter(|s| !s.done) { + search.extend(list, &scopes[&inverse.cid]); + } + }); + } + } + doc._checkout_without_emitting(latest, false, false)?; + } + inverse.before.elements.sort_by_key(|e| e.index); + inverse.before.elements.dedup_by_key(|e| e.id); + inverse.before.searches.clear(); + } + doc.set_detached(false); + Ok(()) +} + +enum Edit { + Delete(CompactIdLp), + Place { + id: CompactIdLp, + // Some only for a removal undo; moves must never recreate a deleted element. + insert: Option<LoroValue>, + left: Option<CompactIdLp>, + right: Option<CompactIdLp>, + }, + Set(CompactIdLp, LoroValue), +} + +pub(crate) struct Plan { + kind: PlanKind, +} + +enum PlanKind { + Native { + edits: Vec<Edit>, + preflight: NativePreflight, + }, + Recreated(Vec<Element>), +} + +/// The batch preflight needs actual child lifetimes, not a full value delta +/// of the sparse model. Native moves never create a child; only restore/set +/// can do so. This metadata is private to identity undo. +#[derive(Default)] +pub(crate) struct NativePreflight { + pub creates: FxHashSet<ContainerID>, + pub removes: FxHashSet<ContainerID>, +} + +pub(crate) type Revivals = FxHashMap<ContainerID, (usize, Snapshot)>; + +/// Keep the identity source of a full-state child revival. The positional +/// delta keeps the values but cannot supply these ids after cloning its parent. +pub(crate) fn capture_revivals( + doc: &LoroDoc, + diff: &DiffBatch, + span_index: usize, + revivals: &mut Revivals, +) { + for (cid, diff) in diff.iter() { + if cid.container_type() != loro_common::ContainerType::MovableList { + continue; + } + let Diff::List(delta) = diff else { + unreachable!() + }; + if delta + .iter() + .all(|item| matches!(item, loro_delta::DeltaItem::Replace { delete: 0, .. })) + { + let inserted: usize = delta + .iter() + .map(|item| match item { + loro_delta::DeltaItem::Replace { value, .. } => value.len(), + _ => unreachable!(), + }) + .sum(); + // An insert-only delta can also restore just the first element + // of a large live list. Check its length before taking a full + // child-revival snapshot, not after cloning unrelated values. + let matches_full_state = { + let mut state = doc.state.lock(); + doc.arena.id_to_idx(cid).is_some_and(|idx| { + state.with_state(idx, |s| { + s.as_movable_list_state().unwrap().len() == inserted + }) + }) + }; + if matches_full_state { + revivals.insert(cid.clone(), (span_index, Snapshot::capture(doc, cid))); + } + } + } +} + +fn remap<T: Clone + Eq + std::hash::Hash>(id: &T, map: &FxHashMap<T, T>) -> T { + let mut id = id.clone(); + while let Some(next) = map.get(&id) { + id = next.clone(); + } + id +} + +fn remap_value(value: &LoroValue, containers: &FxHashMap<ContainerID, ContainerID>) -> LoroValue { + match value { + LoroValue::Container(cid) => LoroValue::Container(remap(cid, containers)), + value => value.clone(), + } +} + +// The ordered model contains only affected elements and their anchors. Relative +// keys avoid shifting the rest of the list while planning each identity edit. +struct Model { + order: BTreeMap<FractionalIndex, Element>, + keys: FxHashMap<CompactIdLp, FractionalIndex>, +} + +impl Model { + fn new(elements: &[Element]) -> Self { + #[cfg(test)] + CAPTURE_STATS.with(|stats| { + let (n, model) = stats.get(); + stats.set((n, model.max(elements.len()))); + }); + let keys = FractionalIndex::generate_n_evenly(None, None, elements.len()).unwrap(); + let order: BTreeMap<_, _> = keys.into_iter().zip(elements.iter().cloned()).collect(); + let keys = order.iter().map(|(key, e)| (e.id, key.clone())).collect(); + Self { order, keys } + } + + fn remove(&mut self, id: CompactIdLp) -> Option<Element> { + let key = self.keys.remove(&id)?; + Some(self.order.remove(&key).expect("undo model element missing")) + } + + fn place(&mut self, element: Element, left: Option<CompactIdLp>, right: Option<CompactIdLp>) { + let (lower, upper) = if let Some(key) = left.and_then(|id| self.keys.get(&id)) { + let next = self + .order + .range((Bound::Excluded(key), Bound::Unbounded)) + .next(); + (Some(key), next.map(|(key, _)| key)) + } else if let Some(key) = right.and_then(|id| self.keys.get(&id)) { + let prev = self.order.range(..key).next_back(); + (prev.map(|(key, _)| key), Some(key)) + } else { + (None, self.order.first_key_value().map(|(key, _)| key)) + }; + let key = FractionalIndex::new(lower, upper).unwrap(); + assert!(self.keys.insert(element.id, key.clone()).is_none()); + assert!(self.order.insert(key, element).is_none()); + } + + fn undo( + &mut self, + inverse: &Inverse, + remapped: &ElementRemap, + containers: &FxHashMap<ContainerID, ContainerID>, + edits: &mut Vec<Edit>, + preflight: &mut NativePreflight, + ) { + let before: FxHashMap<_, _> = inverse.before.elements.iter().map(|e| (e.id, e)).collect(); + let after: FxHashMap<_, _> = inverse.after.elements.iter().map(|e| (e.id, e)).collect(); + for e in &inverse.after.elements { + if inverse.after.targets.contains(&e.id) && !before.contains_key(&e.id) { + let id = remap(&e.id, remapped); + if let Some(removed) = self.remove(id) { + if let LoroValue::Container(cid) = removed.value { + preflight.removes.insert(cid); + } + edits.push(Edit::Delete(id)); + } + } + } + + let repositioned: FxHashSet<_> = inverse + .before + .elements + .iter() + .filter(|e| inverse.before.targets.contains(&e.id)) + .filter_map(|e| { + let id = remap(&e.id, remapped); + match after.get(&e.id) { + None if !self.keys.contains_key(&id) => Some(id), + Some(other) if e.position != other.position && self.keys.contains_key(&id) => { + Some(id) + } + _ => None, + } + }) + .collect(); + // A future move is not a stable right anchor. Already placed elements + // can anchor the next edit on the left, including restored runs. + let mut right = vec![None; inverse.before.elements.len()]; + let mut next = None; + for (i, e) in inverse.before.elements.iter().enumerate().rev() { + right[i] = next; + let id = remap(&e.id, remapped); + if !repositioned.contains(&id) && self.keys.contains_key(&id) { + next = Some(id); + } + } + let mut left = None; + for (i, e) in inverse.before.elements.iter().enumerate() { + let id = remap(&e.id, remapped); + if !inverse.before.targets.contains(&e.id) { + if self.keys.contains_key(&id) { + left = Some(id); + } + continue; + } + // Classify this original identity independently: several old ids + // may now resolve to one replacement. Another entry's placement + // must not turn a missing move into a restoration. + let place = match after.get(&e.id) { + None => !self.keys.contains_key(&id), + Some(other) => e.position != other.position && self.keys.contains_key(&id), + }; + if place { + let insert = + (!after.contains_key(&e.id)).then(|| remap_value(&e.value, containers)); + let element = match (self.remove(id), insert.as_ref()) { + (Some(element), _) => element, + (None, Some(value)) => Element { + id, + value: value.clone(), + ..e.clone() + }, + // An original id and its undo-created replacement can + // coexist after a concurrent move revives the original. + // Their aliases may coincide; an absent move/set target + // still must not be recreated. + (None, None) => continue, + }; + if let Some(LoroValue::Container(cid)) = &insert { + preflight.creates.insert(cid.clone()); + } + self.place(element, left, right[i]); + edits.push(Edit::Place { + id, + insert, + left, + right: right[i], + }); + } + if let Some(other) = after.get(&e.id) { + if e.value_id != other.value_id { + if let Some(key) = self.keys.get(&id) { + let element = self.order.get_mut(key).unwrap(); + let value = remap_value(&e.value, containers); + if value != element.value { + if let LoroValue::Container(cid) = &element.value { + preflight.removes.insert(cid.clone()); + } + if let LoroValue::Container(cid) = &value { + preflight.creates.insert(cid.clone()); + } + } + element.value = value; + element.value_id = e.value_id; + edits.push(Edit::Set(id, element.value.clone())); + } + } + } + if self.keys.contains_key(&id) { + left = Some(id); + } + } + } +} + +/// Replace only lists that keep the same container lifetime. Parent-driven +/// recreation still uses the existing full-child diff and container remapping. +pub(crate) fn prepare( + doc: &LoroDoc, + diff: &mut DiffBatch, + inverses: Vec<Inverse>, + revivals: Revivals, + containers: &FxHashMap<ContainerID, ContainerID>, + remapped: &ElementRemap, +) -> FxHashMap<ContainerID, Plan> { + let mut grouped: FxHashMap<ContainerID, Vec<Inverse>> = FxHashMap::default(); + for inverse in inverses.into_iter().rev() { + grouped + .entry(inverse.cid.clone()) + .or_default() + .push(inverse); + } + let mut plans = FxHashMap::default(); + for (cid, (span_index, source)) in revivals { + let mut elements = source.elements; + for e in &mut elements { + e.id = remap(&e.id, remapped); + e.value = remap_value(&e.value, containers); + } + let mut model = Model::new(&elements); + if let Some(inverses) = grouped.get(&cid) { + for inverse in inverses.iter().filter(|i| i.span_index < span_index) { + model.undo( + inverse, + remapped, + containers, + &mut Vec::new(), + &mut NativePreflight::default(), + ); + } + } + plans.insert( + cid, + Plan { + kind: PlanKind::Recreated(model.order.into_values().collect()), + }, + ); + } + for (cid, inverses) in grouped { + let current_id = remap(&cid, containers); + let current = if inverses.iter().any(|i| i.before.full || i.after.full) { + Snapshot::capture(doc, ¤t_id) + } else { + let scope = Scope { + ids: inverses + .iter() + .flat_map(|i| i.before.elements.iter().chain(&i.after.elements)) + .map(|e| remap(&e.id, remapped)) + .collect(), + full: false, + }; + Snapshot::capture_span(doc, ¤t_id, &scope, &scope, false) + }; + if !current.alive || inverses.iter().any(|i| !i.before.alive || !i.after.alive) { + continue; + } + // A parent clone normally installs aliases from its full-state source. + // If that source could not be aligned, retain the previous positional + // path rather than treating every recreated element as remotely deleted. + if remap(&cid, containers) != cid { + let current_ids: FxHashSet<_> = current.elements.iter().map(|e| e.id).collect(); + if inverses + .iter() + .flat_map(|i| &i.after.elements) + .any(|e| remap(&e.id, remapped) == e.id && !current_ids.contains(&e.id)) + { + continue; + } + } + let mut model = Model::new(¤t.elements); + let mut edits = Vec::new(); + let mut preflight = NativePreflight::default(); + for inverse in &inverses { + model.undo(inverse, remapped, containers, &mut edits, &mut preflight); + } + // This private entry advertises possible child creations to the batch + // preflight. Positions/removals come from NativePreflight, and actual + // application uses only the identity edits under the transaction lock. + let delta = DeltaRopeBuilder::new().insert_many( + preflight + .creates + .iter() + .cloned() + .map(|cid| ValueOrHandler::Value(LoroValue::Container(cid))), + ListDeltaMeta::default(), + ); + if !diff.cid_to_events.contains_key(&cid) { + diff.order.push(cid.clone()); + } + diff.cid_to_events + .insert(cid.clone(), Diff::List(delta.build())); + plans.insert( + cid, + Plan { + kind: PlanKind::Native { edits, preflight }, + }, + ); + } + plans +} + +impl Plan { + pub(crate) fn is_native(&self) -> bool { + matches!(self.kind, PlanKind::Native { .. }) + } + + pub(crate) fn preflight(&self) -> Option<&NativePreflight> { + match &self.kind { + PlanKind::Native { preflight, .. } => Some(preflight), + _ => None, + } + } + + pub(crate) fn apply_with_txn( + self, + list: &MovableListHandler, + txn: &mut Transaction, + containers: &mut FxHashMap<ContainerID, ContainerID>, + remapped: &mut ElementRemap, + ) -> LoroResult<()> { + let PlanKind::Native { edits, .. } = self.kind else { + return Err(LoroError::TransactionError( + "expected native MovableList undo plan".into(), + )); + }; + Self::apply_native(edits, list, txn, containers, remapped) + } + + pub(crate) fn apply( + self, + list: &MovableListHandler, + diff: Diff, + containers: &mut FxHashMap<ContainerID, ContainerID>, + remapped: &mut ElementRemap, + ) -> LoroResult<()> { + match self.kind { + PlanKind::Recreated(target) => { + Handler::MovableList(list.clone()).apply_diff( + diff, + containers, + &mut Default::default(), + )?; + let current = list.with_state(|s| { + Ok(s.as_movable_list_state() + .unwrap() + .iter_with_last_move_id_and_elem_id() + .map(|(_, id, value)| (id, value.clone())) + .collect::<Vec<_>>()) + })?; + if current.len() == target.len() + && current + .iter() + .zip(&target) + .all(|((_, value), e)| *value == remap_value(&e.value, containers)) + { + for ((new_id, _), e) in current.into_iter().zip(target) { + let old_id = remap(&e.id, remapped); + if old_id != new_id { + remapped.insert(old_id, new_id); + } + } + } + Ok(()) + } + PlanKind::Native { .. } => Err(LoroError::TransactionError( + "MovableList identity undo requires the transaction guard".into(), + )), + } + } + + fn apply_native( + edits: Vec<Edit>, + list: &MovableListHandler, + txn: &mut Transaction, + containers: &mut FxHashMap<ContainerID, ContainerID>, + remapped: &mut ElementRemap, + ) -> LoroResult<()> { + let index = |id: CompactIdLp, remapped: &ElementRemap| { + let id = remap(&id, remapped); + list.with_state(|s| { + let state = s.as_movable_list_state().unwrap(); + Ok(state + .get_index_of_elem(id) + .filter(|i| state.get_elem_id_at(*i, IndexType::ForUser) == Some(id))) + }) + }; + let missing = + || LoroError::NotFoundError("MovableList undo element or anchor disappeared".into()); + for edit in edits { + match edit { + Edit::Delete(id) => { + list.delete_with_txn(txn, index(id, remapped)?.ok_or_else(missing)?, 1)? + } + Edit::Place { + id, + insert, + left, + right, + } => { + let gap = if let Some(left) = left { + index(left, remapped)?.ok_or_else(missing)? + 1 + } else if let Some(right) = right { + index(right, remapped)?.ok_or_else(missing)? + } else { + 0 + }; + if let Some(value) = insert { + if index(id, remapped)?.is_some() { + return Err(LoroError::TransactionError( + "MovableList undo element already restored".into(), + )); + } + match remap_value(&value, containers) { + LoroValue::Container(cid) => { + let child = list.insert_container_with_txn( + txn, + gap, + Handler::new_unattached(cid.container_type())?, + )?; + containers.insert(cid, child.id()); + } + value => list.insert_with_txn(txn, gap, value)?, + } + let new_id = list.with_state(|s| { + s.as_movable_list_state() + .unwrap() + .get_elem_id_at(gap, IndexType::ForUser) + .ok_or_else(missing) + })?; + remapped.insert(remap(&id, remapped), new_id); + } else { + let from = index(id, remapped)?.ok_or_else(missing)?; + list.move_with_txn(txn, from, gap - usize::from(from < gap))?; + } + } + Edit::Set(id, value) => { + let index = index(id, remapped)?.ok_or_else(missing)?; + match remap_value(&value, containers) { + LoroValue::Container(cid) => { + if list.get(index) != Some(LoroValue::Container(cid.clone())) { + let child = list.set_container_with_txn( + txn, + index, + Handler::new_unattached(cid.container_type())?, + )?; + containers.insert(cid, child.id()); + } + } + value => list.set_with_txn(txn, index, value)?, + } + } + } + } + Ok(()) + } +} + +#[cfg(test)] +thread_local! { + static CAPTURE_STATS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) }; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn small_edits_keep_snapshot_and_model_sizes_bounded() { + for (n, remove) in [ + (1_000, false), + (10_000, false), + (1_000, true), + (10_000, true), + ] { + let doc = LoroDoc::new_auto_commit(); + let list = doc.get_movable_list("list"); + for i in 0..n { + list.push(i.into()).unwrap(); + } + doc.commit_then_renew(); + let undo = crate::UndoManager::new(&doc); + if remove { + list.delete(0, 1).unwrap(); + } else { + list.mov(0, n as usize - 1).unwrap(); + } + doc.commit_then_renew(); + CAPTURE_STATS.with(|stats| stats.set((0, 0))); + assert!(undo.undo().unwrap()); + let (captured, model) = CAPTURE_STATS.with(|stats| stats.get()); + assert!( + captured <= 12, + "captured {captured} elements for list length {n}" + ); + assert!(model <= 3, "model has {model} elements for list length {n}"); + } + } +} diff --git a/vendor/loro-internal/src/utils/kv_wrapper.rs b/vendor/loro-internal/src/utils/kv_wrapper.rs new file mode 100644 index 0000000..c207eda --- /dev/null +++ b/vendor/loro-internal/src/utils/kv_wrapper.rs @@ -0,0 +1,181 @@ +use crate::sync::Mutex; +use bytes::Bytes; +use loro_kv_store::{mem_store::MemKvConfig, MemKvStore}; +use std::{collections::BTreeSet, ops::Bound, sync::Arc}; + +use crate::kv_store::KvStore; + +/// This thin wrapper aims to limit the ability to modify the kv store and make +/// it easy to find all the modifications. +pub(crate) struct KvWrapper { + kv: Arc<Mutex<dyn KvStore>>, +} + +impl Clone for KvWrapper { + /// Deep clone the inner kv store. + fn clone(&self) -> Self { + Self { + kv: self.kv.lock().clone_store(), + } + } +} + +impl KvWrapper { + pub fn new_mem() -> Self { + Self { + // kv: Arc::new(Mutex::new(BTreeMap::new())), + kv: Arc::new(Mutex::new(MemKvStore::new( + // set false because it's depended by GC snapshot's import & export + MemKvConfig::default().should_encode_none(false), + ))), + } + } + + pub fn arc_clone(&self) -> Self { + Self { + kv: self.kv.clone(), + } + } + + pub fn import(&self, bytes: Bytes) -> Result<(), String> { + let mut kv = self.kv.lock(); + // Snapshot bytes are external input. The document-level checksum does not replace + // validation of the checksums embedded in each SSTable block: a producer can emit a + // self-consistent outer envelope containing an invalid inner table. + kv.import_all(bytes) + } + + pub fn export(&self) -> Bytes { + let mut kv = self.kv.lock(); + kv.export_all() + } + + pub fn get(&self, key: &[u8]) -> Option<Bytes> { + let kv = self.kv.lock(); + kv.get(key) + } + + pub(crate) fn keys(&self) -> BTreeSet<Vec<u8>> { + let kv = self.kv.lock(); + kv.scan(Bound::Unbounded, Bound::Unbounded) + .map(|(k, _)| k.to_vec()) + .collect() + } + + /// Snapshot all entries while holding only the KV lock. + /// + /// Callers that also need the arena lock must use this instead of entering arena code from + /// inside a KV-locked closure. Lazy arena parent resolution can acquire this same KV lock. + pub(crate) fn scan_all_entries(&self) -> Vec<(Bytes, Bytes)> { + let kv = self.kv.lock(); + kv.scan(Bound::Unbounded, Bound::Unbounded).collect() + } + + /// Snapshot the entries whose keys are in `[lower, upper)` while holding + /// only the KV lock. See [`Self::scan_all_entries`] for the lock-ordering + /// rationale. + pub(crate) fn scan_range_entries(&self, lower: &[u8], upper: &[u8]) -> Vec<(Bytes, Bytes)> { + let kv = self.kv.lock(); + kv.scan(Bound::Included(lower), Bound::Excluded(upper)) + .collect() + } + + pub(crate) fn scan_all_keys(&self) -> Vec<Bytes> { + let kv = self.kv.lock(); + kv.scan(Bound::Unbounded, Bound::Unbounded) + .map(|(k, _)| k) + .collect() + } + + pub fn set_all(&self, updates: Vec<(Bytes, Bytes)>) { + let mut kv = self.kv.lock(); + for (k, v) in updates { + kv.set(&k, v); + } + } + + #[allow(unused)] + pub(crate) fn contains_key(&self, key: &[u8]) -> bool { + self.kv.lock().contains_key(key) + } + + pub(crate) fn remove_same(&self, old_kv: &KvWrapper) { + if Arc::ptr_eq(&self.kv, &old_kv.kv) { + let mut this = self.kv.lock(); + let keys = this + .scan(Bound::Unbounded, Bound::Unbounded) + .map(|(k, _)| k) + .collect::<Vec<_>>(); + for k in keys { + this.remove(&k); + } + return; + } + + let other = old_kv.kv.lock(); + let mut this = self.kv.lock(); + for (k, v) in other.scan(Bound::Unbounded, Bound::Unbounded) { + if this.get(&k) == Some(v) { + this.remove(&k); + } + } + } + + pub(crate) fn remove(&self, k: &[u8]) -> Option<Bytes> { + self.kv.lock().remove(k) + } + + /// Remove all keys not in the given set + pub(crate) fn retain_keys(&self, keys: &BTreeSet<Vec<u8>>) { + let mut kv = self.kv.lock(); + let mut to_remove = BTreeSet::new(); + for (k, _) in kv.scan(Bound::Unbounded, Bound::Unbounded) { + if !keys.contains(&*k) { + to_remove.insert(k); + } + } + + for k in to_remove { + kv.remove(&k); + } + } + + pub(crate) fn insert(&self, k: &[u8], v: Bytes) { + self.kv.lock().set(k, v); + } + + pub(crate) fn is_empty(&self) -> bool { + self.kv.lock().is_empty() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn set_all_applies_precollected_updates() { + let kv = KvWrapper::new_mem(); + + kv.set_all(vec![( + Bytes::from_static(b"key"), + Bytes::from_static(b"value"), + )]); + assert_eq!(kv.get(b"key"), Some(Bytes::from_static(b"value"))); + } + + #[test] + fn remove_same_streams_different_stores() { + let kv = KvWrapper::new_mem(); + let old_kv = KvWrapper::new_mem(); + kv.insert(b"same", Bytes::from_static(b"value")); + kv.insert(b"changed", Bytes::from_static(b"new")); + old_kv.insert(b"same", Bytes::from_static(b"value")); + old_kv.insert(b"changed", Bytes::from_static(b"old")); + + kv.remove_same(&old_kv); + + assert_eq!(kv.get(b"same"), None); + assert_eq!(kv.get(b"changed"), Some(Bytes::from_static(b"new"))); + } +} diff --git a/vendor/loro-internal/src/utils/lazy.rs b/vendor/loro-internal/src/utils/lazy.rs new file mode 100644 index 0000000..175e0d2 --- /dev/null +++ b/vendor/loro-internal/src/utils/lazy.rs @@ -0,0 +1,21 @@ +#[derive(Debug, Clone)] +pub enum LazyLoad<Src, Dst: From<Src>> { + Src(Src), + Dst(Dst), +} + +impl<Src: Default, Dst: From<Src>> LazyLoad<Src, Dst> { + pub fn get_mut(&mut self) -> &mut Dst { + match self { + LazyLoad::Src(src) => { + let dst = Dst::from(std::mem::take(src)); + *self = LazyLoad::Dst(dst); + match self { + LazyLoad::Dst(dst) => dst, + _ => unreachable!(), + } + } + LazyLoad::Dst(dst) => dst, + } + } +} diff --git a/vendor/loro-internal/src/utils/mod.rs b/vendor/loro-internal/src/utils/mod.rs new file mode 100644 index 0000000..9feef9b --- /dev/null +++ b/vendor/loro-internal/src/utils/mod.rs @@ -0,0 +1,6 @@ +pub(crate) mod kv_wrapper; +pub(crate) mod lazy; +pub(crate) mod query_by_len; +pub mod string_slice; +pub(crate) mod subscription; +pub(crate) mod utf16; diff --git a/vendor/loro-internal/src/utils/query_by_len.rs b/vendor/loro-internal/src/utils/query_by_len.rs new file mode 100644 index 0000000..b9ef8c4 --- /dev/null +++ b/vendor/loro-internal/src/utils/query_by_len.rs @@ -0,0 +1,200 @@ +use std::marker::PhantomData; + +use generic_btree::{BTreeTrait, FindResult, Query}; + +use crate::container::richtext::richtext_state::{RichtextStateChunk, RichtextTreeTrait}; + +/// An easy way to implement [Query] by using key index +/// +/// By default this query implementation will +/// - prefer next element when this element has zero length. +/// - prefer next element rather than previous element when the left is at the middle of two elements. +/// With `LEFT_BOUNDARY`, it instead prefers the preceding nonempty element at +/// an exact boundary, which excludes zero-length elements from a range end. +pub struct IndexQuery<T: QueryByLen<B>, B: BTreeTrait, const LEFT_BOUNDARY: bool = false> { + pub left: usize, + _data: PhantomData<(T, B)>, +} + +/// An easy way to implement [Query] by using key index +/// +/// This query implementation will +/// - prefer next element when this element has zero length. +/// - prefer next element rather than previous element when the left is at the middle of two elements. +pub struct IndexQueryWithEntityIndex<T: QueryByLen<B>, B: BTreeTrait> { + pub left: usize, + pub entity_index: usize, + _data: PhantomData<(T, B)>, +} + +/// An easy way to implement [Query] by using key index +/// +/// This query implementation will +/// - prefer next element when this element has zero length. +/// - prefer next element rather than previous element when the left is at the middle of two elements. +pub struct EntityIndexQueryWithEventIndex { + pub left: usize, + pub event_index: usize, +} + +impl<T: QueryByLen<B>, B: BTreeTrait> IndexQueryWithEntityIndex<T, B> { + pub fn entity_index(&self) -> usize { + self.entity_index + } +} + +/// The default query implementation will +/// +/// - prefer next element when this element has zero length. +/// - prefer next element rather than previous element when the left is at the middle of two elements. +pub trait QueryByLen<B: BTreeTrait> { + fn get_cache_entity_len(cache: &B::Cache) -> usize; + fn get_cache_len(cache: &B::Cache) -> usize; + fn get_elem_len(elem: &B::Elem) -> usize; + fn get_offset_and_found(left: usize, elem: &B::Elem) -> (usize, bool); +} + +impl<T: QueryByLen<B>, B: BTreeTrait, const LEFT_BOUNDARY: bool> Query<B> + for IndexQuery<T, B, LEFT_BOUNDARY> +{ + type QueryArg = usize; + + fn init(target: &Self::QueryArg) -> Self { + Self { + left: *target, + _data: PhantomData, + } + } + + fn find_node( + &mut self, + _: &Self::QueryArg, + child_caches: &[generic_btree::Child<B>], + ) -> generic_btree::FindResult { + let mut last_left = self.left; + for (i, cache) in child_caches.iter().enumerate() { + let len = T::get_cache_len(&cache.cache); + // Range ends should stop at the preceding nonempty element. A + // right-biased endpoint may include arbitrarily many zero-length + // style anchors at this position, making a tiny slice linear in + // the number of marks outside its visible content. + if len == 0 || self.left > len || (!LEFT_BOUNDARY && self.left == len) { + last_left = self.left; + self.left -= len; + } else { + return FindResult::new_found(i, self.left); + } + } + + self.left = last_left; + FindResult::new_missing(child_caches.len() - 1, last_left) + } + + fn confirm_elem( + &mut self, + _q: &Self::QueryArg, + elem: &<B as BTreeTrait>::Elem, + ) -> (usize, bool) { + T::get_offset_and_found(self.left, elem) + } +} + +impl<T: QueryByLen<B>, B: BTreeTrait> Query<B> for IndexQueryWithEntityIndex<T, B> { + type QueryArg = usize; + + fn init(target: &Self::QueryArg) -> Self { + Self { + left: *target, + entity_index: 0, + _data: PhantomData, + } + } + + fn find_node( + &mut self, + _: &Self::QueryArg, + child_caches: &[generic_btree::Child<B>], + ) -> generic_btree::FindResult { + let mut last_left = self.left; + for (i, cache) in child_caches.iter().enumerate() { + let len = T::get_cache_len(&cache.cache); + if self.left >= len { + self.entity_index += T::get_cache_entity_len(&cache.cache); + last_left = self.left; + self.left -= len; + } else { + return FindResult::new_found(i, self.left); + } + } + + self.left = last_left; + FindResult::new_missing(child_caches.len() - 1, last_left) + } + + fn confirm_elem( + &mut self, + _q: &Self::QueryArg, + elem: &<B as BTreeTrait>::Elem, + ) -> (usize, bool) { + let (offset, found) = T::get_offset_and_found(self.left, elem); + self.entity_index += offset; + (offset, found) + } +} + +impl Query<RichtextTreeTrait> for EntityIndexQueryWithEventIndex { + type QueryArg = usize; + + fn init(target: &Self::QueryArg) -> Self { + Self { + left: *target, + event_index: 0, + } + } + + fn find_node( + &mut self, + _: &Self::QueryArg, + child_caches: &[generic_btree::Child<RichtextTreeTrait>], + ) -> generic_btree::FindResult { + let mut last_left = self.left; + let mut last_event_left = self.left; + for (i, cache) in child_caches.iter().enumerate() { + let len = cache.cache.entity_len as usize; + if self.left >= len { + last_event_left = self.event_index; + self.event_index += cache.cache.event_len() as usize; + last_left = self.left; + self.left -= len; + } else { + return FindResult::new_found(i, self.left); + } + } + + self.left = last_left; + self.event_index = last_event_left; + FindResult::new_missing(child_caches.len() - 1, last_left) + } + + fn confirm_elem(&mut self, _q: &Self::QueryArg, elem: &RichtextStateChunk) -> (usize, bool) { + let left = self.left; + match elem { + RichtextStateChunk::Text(s) => { + if s.len() as usize >= left { + self.event_index += s.convert_unicode_offset_to_event_offset(left); + return (left, true); + } + + self.event_index += s.event_len() as usize; + (left, false) + } + RichtextStateChunk::Style { .. } => { + if left == 0 { + return (0, true); + } + + (left, false) + } + } + } +} diff --git a/vendor/loro-internal/src/utils/string_slice.rs b/vendor/loro-internal/src/utils/string_slice.rs new file mode 100644 index 0000000..8038717 --- /dev/null +++ b/vendor/loro-internal/src/utils/string_slice.rs @@ -0,0 +1,466 @@ +use std::{fmt::Debug, ops::Deref}; + +use append_only_bytes::BytesSlice; +use generic_btree::rle::{HasLength, Mergeable, Sliceable, TryInsert}; +use rle::Mergable; +use serde::{Deserialize, Deserializer, Serialize}; + +use crate::{ + container::richtext::richtext_state::{unicode_to_utf8_index, utf16_to_utf8_index}, + delta::DeltaValue, +}; + +use super::utf16::{count_unicode_chars, count_utf16_len}; + +#[derive(Clone)] +pub struct StringSlice { + bytes: Variant, +} + +impl PartialEq for StringSlice { + fn eq(&self, other: &Self) -> bool { + self.as_str() == other.as_str() + } +} + +impl Eq for StringSlice {} + +#[derive(Clone, PartialEq, Eq)] +enum Variant { + BytesSlice(BytesSlice), + Owned(String), +} + +impl From<String> for StringSlice { + fn from(s: String) -> Self { + Self { + bytes: Variant::Owned(s), + } + } +} + +impl From<BytesSlice> for StringSlice { + fn from(s: BytesSlice) -> Self { + Self::new(s) + } +} + +impl From<&str> for StringSlice { + fn from(s: &str) -> Self { + Self { + bytes: Variant::Owned(s.to_string()), + } + } +} + +impl Debug for StringSlice { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("StringSlice") + .field("bytes", &self.as_str()) + .finish() + } +} + +impl StringSlice { + pub fn new(s: BytesSlice) -> Self { + std::str::from_utf8(&s).unwrap(); + Self { + bytes: Variant::BytesSlice(s), + } + } + + pub fn as_str(&self) -> &str { + match &self.bytes { + // SAFETY: `bytes` is always valid utf8 + Variant::BytesSlice(s) => unsafe { std::str::from_utf8_unchecked(s) }, + Variant::Owned(s) => s, + } + } + + pub fn len_bytes(&self) -> usize { + match &self.bytes { + Variant::BytesSlice(s) => s.len(), + Variant::Owned(s) => s.len(), + } + } + + fn bytes(&self) -> &[u8] { + match &self.bytes { + Variant::BytesSlice(s) => s.deref(), + Variant::Owned(s) => s.as_bytes(), + } + } + + pub fn len_unicode(&self) -> usize { + count_unicode_chars(self.bytes()) + } + + pub fn len_utf16(&self) -> usize { + count_utf16_len(self.bytes()) + } + + pub fn is_empty(&self) -> bool { + self.bytes().is_empty() + } + + pub fn extend(&mut self, s: &str) { + match &mut self.bytes { + Variant::BytesSlice(_) => { + *self = Self { + bytes: Variant::Owned(format!("{}{}", self.as_str(), s)), + } + } + Variant::Owned(v) => { + v.push_str(s); + } + } + } +} + +impl std::fmt::Display for StringSlice { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for StringSlice { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + Ok(s.into()) + } +} + +impl Serialize for StringSlice { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + serializer.serialize_str(self.as_str()) + } +} + +impl DeltaValue for StringSlice { + fn value_extend(&mut self, other: Self) -> Result<(), Self> { + match (&mut self.bytes, &other.bytes) { + (Variant::BytesSlice(s), Variant::BytesSlice(o)) => match s.try_merge(o) { + Ok(_) => Ok(()), + Err(_) => Err(other), + }, + (Variant::Owned(s), _) => { + s.push_str(other.as_str()); + Ok(()) + } + _ => Err(other), + } + } + + fn take(&mut self, length: usize) -> Self { + let length = if cfg!(feature = "wasm") { + utf16_to_utf8_index(self.as_str(), length).unwrap() + } else { + unicode_to_utf8_index(self.as_str(), length).unwrap() + }; + + match &mut self.bytes { + Variant::BytesSlice(s) => { + let mut other = s.slice_clone(length..); + s.slice_(..length); + std::mem::swap(s, &mut other); + Self { + bytes: Variant::BytesSlice(other), + } + } + Variant::Owned(s) => { + let mut other = s.split_off(length); + std::mem::swap(s, &mut other); + Self { + bytes: Variant::Owned(other), + } + } + } + } + + /// Unicode length of the string + /// Utf16 length when in WASM + fn length(&self) -> usize { + if cfg!(feature = "wasm") { + count_utf16_len(self.bytes()) + } else { + count_unicode_chars(self.bytes()) + } + } +} + +impl HasLength for StringSlice { + fn rle_len(&self) -> usize { + if cfg!(feature = "wasm") { + count_utf16_len(self.bytes()) + } else { + count_unicode_chars(self.bytes()) + } + } +} + +impl TryInsert for StringSlice { + fn try_insert(&mut self, pos: usize, elem: Self) -> Result<(), Self> + where + Self: Sized, + { + match &mut self.bytes { + Variant::BytesSlice(_) => Err(elem), + Variant::Owned(s) => { + if s.capacity() >= s.len() + elem.len_bytes() { + let pos = if cfg!(feature = "wasm") { + utf16_to_utf8_index(s.as_str(), pos).unwrap() + } else { + unicode_to_utf8_index(s.as_str(), pos).unwrap() + }; + s.insert_str(pos, elem.as_str()); + Ok(()) + } else { + Err(elem) + } + } + } + + // match (&mut self.bytes, &elem.bytes) { + // (Variant::Owned(a), Variant::Owned(b)) + // // TODO: Extract magic num + // if a.capacity() >= a.len() + b.len() && a.capacity() < 128 => + // { + // a.insert_str(pos, b.as_str()); + // Ok(()) + // } + // _ => Err(elem), + // } + } +} + +impl Mergeable for StringSlice { + fn can_merge(&self, rhs: &Self) -> bool { + match (&self.bytes, &rhs.bytes) { + (Variant::BytesSlice(a), Variant::BytesSlice(b)) => a.can_merge(b), + (Variant::Owned(a), Variant::Owned(b)) => a.len() + b.len() <= a.capacity(), + _ => false, + } + } + + fn merge_right(&mut self, rhs: &Self) { + match (&mut self.bytes, &rhs.bytes) { + (Variant::BytesSlice(a), Variant::BytesSlice(b)) => a.merge(b, &()), + (Variant::Owned(a), Variant::Owned(b)) => a.push_str(b.as_str()), + _ => {} + } + } + + fn merge_left(&mut self, left: &Self) { + match (&mut self.bytes, &left.bytes) { + (Variant::BytesSlice(a), Variant::BytesSlice(b)) => { + let mut new = b.clone(); + new.merge(a, &()); + *a = new; + } + (Variant::Owned(a), Variant::Owned(b)) => { + a.insert_str(0, b.as_str()); + } + _ => {} + } + } +} + +impl Sliceable for StringSlice { + fn _slice(&self, range: std::ops::Range<usize>) -> Self { + let range = if cfg!(feature = "wasm") { + let start = utf16_to_utf8_index(self.as_str(), range.start).unwrap(); + let end = utf16_to_utf8_index(self.as_str(), range.end).unwrap(); + start..end + } else { + let start = unicode_to_utf8_index(self.as_str(), range.start).unwrap(); + let end = unicode_to_utf8_index(self.as_str(), range.end).unwrap(); + start..end + }; + + let bytes = match &self.bytes { + Variant::BytesSlice(s) => Variant::BytesSlice(s.slice_clone(range)), + Variant::Owned(s) => Variant::Owned(s[range].to_string()), + }; + + Self { bytes } + } + + fn split(&mut self, pos: usize) -> Self { + let pos = if cfg!(feature = "wasm") { + utf16_to_utf8_index(self.as_str(), pos).unwrap() + } else { + unicode_to_utf8_index(self.as_str(), pos).unwrap() + }; + + let bytes = match &mut self.bytes { + Variant::BytesSlice(s) => { + let other = s.slice_clone(pos..); + s.slice_(..pos); + Variant::BytesSlice(other) + } + Variant::Owned(s) => { + let other = s.split_off(pos); + Variant::Owned(other) + } + }; + + Self { bytes } + } +} + +impl Default for StringSlice { + fn default() -> Self { + StringSlice { + bytes: Variant::Owned(String::with_capacity(32)), + } + } +} + +impl loro_delta::delta_trait::DeltaValue for StringSlice {} +pub fn unicode_range_to_byte_range(s: &str, start: usize, end: usize) -> (usize, usize) { + debug_assert!(start <= end); + if end <= s.len() && s.as_bytes()[..end].is_ascii() { + return (start, end); + } + let start_unicode_index = start; + let end_unicode_index = end; + let mut current_utf8_index = 0; + let mut start_byte = 0; + let mut end_byte = s.len(); + for (current_unicode_index, c) in s.chars().enumerate() { + if current_unicode_index == start_unicode_index { + start_byte = current_utf8_index; + } + + if current_unicode_index == end_unicode_index { + end_byte = current_utf8_index; + break; + } + + current_utf8_index += c.len_utf8(); + } + + (start_byte, end_byte) +} + +#[cfg(test)] +mod tests { + use append_only_bytes::AppendOnlyBytes; + use generic_btree::rle::{HasLength, Mergeable, Sliceable, TryInsert}; + + use crate::delta::DeltaValue; + + use super::*; + + #[test] + fn owned_slice_lengths_and_unicode_boundaries_use_logical_char_indices() { + let mut slice = StringSlice::from("aé😀b"); + assert_eq!(slice.as_str(), "aé😀b"); + assert_eq!(slice.len_bytes(), 8); + assert_eq!(slice.len_unicode(), 4); + assert_eq!(slice.len_utf16(), 5); + let event_len = if cfg!(feature = "wasm") { 5 } else { 4 }; + assert_eq!(slice.length(), event_len); + assert_eq!(slice.rle_len(), event_len); + + let middle_range = if cfg!(feature = "wasm") { 1..4 } else { 1..3 }; + let middle = slice._slice(middle_range); + assert_eq!(middle.as_str(), "é😀"); + + let right = slice.split(2); + assert_eq!(slice.as_str(), "aé"); + assert_eq!(right.as_str(), "😀b"); + + let prefix = slice.take(1); + assert_eq!(prefix.as_str(), "a"); + assert_eq!(slice.as_str(), "é"); + } + + #[test] + fn owned_slice_insert_and_merge_respect_capacity_contracts() { + let mut backing = String::with_capacity(16); + backing.push_str("a😀"); + let mut slice = StringSlice::from(backing); + slice.try_insert(1, StringSlice::from("é")).unwrap(); + assert_eq!(slice.as_str(), "aé😀"); + + let mut tight = StringSlice::from(String::from("ab")); + let rejected = tight.try_insert(1, StringSlice::from("c")).unwrap_err(); + assert_eq!(tight.as_str(), "ab"); + assert_eq!(rejected.as_str(), "c"); + + let mut left_text = String::with_capacity(8); + left_text.push_str("ab"); + let mut left = StringSlice::from(left_text); + let right = StringSlice::from("cd"); + assert!(left.can_merge(&right)); + left.merge_right(&right); + assert_eq!(left.as_str(), "abcd"); + + let mut suffix = StringSlice::from("cd"); + suffix.merge_left(&StringSlice::from("ab")); + assert_eq!(suffix.as_str(), "abcd"); + } + + #[test] + fn bytes_slice_variant_keeps_append_only_slice_semantics() { + let mut bytes = AppendOnlyBytes::new(); + bytes.push_str("left"); + let left_bytes = bytes.slice(..); + bytes.push_str("right"); + let right_bytes = bytes.slice(4..); + + let mut left = StringSlice::from(left_bytes.clone()); + let right = StringSlice::from(right_bytes.clone()); + assert_eq!(left.as_str(), "left"); + assert_eq!(right.as_str(), "right"); + assert!(left.can_merge(&right)); + left.value_extend(right).unwrap(); + assert_eq!(left.as_str(), "leftright"); + + let mut whole = StringSlice::from(bytes.slice(..)); + let tail = whole.split(4); + assert_eq!(whole.as_str(), "left"); + assert_eq!(tail.as_str(), "right"); + assert_eq!( + StringSlice::from(bytes.slice(..))._slice(1..5).as_str(), + "eftr" + ); + + let mut converted_to_owned = StringSlice::from(left_bytes); + converted_to_owned.extend("!"); + assert_eq!(converted_to_owned.as_str(), "left!"); + + let mut byte_slice = StringSlice::from(right_bytes); + let rejected = byte_slice + .try_insert(1, StringSlice::from("!")) + .unwrap_err(); + assert_eq!(byte_slice.as_str(), "right"); + assert_eq!(rejected.as_str(), "!"); + } + + #[test] + fn serde_display_default_and_range_conversion_are_string_like() { + let empty = StringSlice::default(); + assert!(empty.is_empty()); + + let slice = StringSlice::from("aé😀b"); + assert_eq!(slice.to_string(), "aé😀b"); + assert_eq!(format!("{slice:?}"), r#"StringSlice { bytes: "aé😀b" }"#); + + let encoded = serde_json::to_string(&slice).unwrap(); + assert_eq!(encoded, r#""aé😀b""#); + let decoded: StringSlice = serde_json::from_str(&encoded).unwrap(); + assert_eq!(decoded, slice); + + let (start, end) = unicode_range_to_byte_range("aé😀b", 1, 3); + assert_eq!(&"aé😀b"[start..end], "é😀"); + assert_eq!(unicode_range_to_byte_range("aé😀b", 2, 4), (3, 8)); + } +} diff --git a/vendor/loro-internal/src/utils/subscription.rs b/vendor/loro-internal/src/utils/subscription.rs new file mode 100644 index 0000000..4fc11ac --- /dev/null +++ b/vendor/loro-internal/src/utils/subscription.rs @@ -0,0 +1,857 @@ +use either::Either; +/* +This file is modified from the original file in the following repo: +https://github.com/zed-industries/zed + + +Copyright 2022 - 2024 Zed Industries, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + + http://www.apache.org/licenses/LICENSE-2.0 + + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + + 1. Definitions. + + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + + END OF TERMS AND CONDITIONS + +*/ +use crate::sync::{thread, AtomicBool, Mutex}; +use smallvec::SmallVec; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::atomic::Ordering; +use std::sync::{Arc, Weak}; +use std::{fmt::Debug, mem}; +use thread::ThreadId; + +#[derive(Debug)] +pub enum SubscriptionError { + CannotEmitEventDueToRecursiveCall, +} + +impl std::fmt::Display for Subscription { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "SubscriptionError") + } +} + +pub struct SubscriberSet<EmitterKey, Callback>( + Arc<Mutex<SubscriberSetState<EmitterKey, Callback>>>, +); + +impl<EmitterKey, Callback> Clone for SubscriberSet<EmitterKey, Callback> { + fn clone(&self) -> Self { + SubscriberSet(self.0.clone()) + } +} + +struct SubscriberSetState<EmitterKey, Callback> { + subscribers: BTreeMap<EmitterKey, Either<BTreeMap<usize, Subscriber<Callback>>, ThreadId>>, + /// Subscribers added while their emitter was mid-emit. + /// + /// `retain` swaps an emitter's map out for a `ThreadId` marker + /// while it invokes callbacks, so during that window there is no + /// map to insert into. The marker cannot simply be replaced: it is + /// what makes a concurrent `retain` wait instead of emitting the + /// same emitter twice, and what lets `is_recursive_calling` spot a + /// re-entrant emit. Parking the new subscriber here keeps the + /// marker intact, and `retain` folds these back in when it + /// restores the map. + pending_subscribers: BTreeMap<EmitterKey, BTreeMap<usize, Subscriber<Callback>>>, + dropped_subscribers: BTreeSet<(EmitterKey, usize)>, + next_subscriber_id: usize, +} + +struct Subscriber<Callback> { + active: Arc<AtomicBool>, + callback: Callback, + /// This field is used to drop the subscription when the subscriber is dropped. + _sub: InnerSubscription, +} + +impl<EmitterKey, Callback> SubscriberSet<EmitterKey, Callback> +where + EmitterKey: 'static + Ord + Clone + Debug + Send + Sync, + Callback: 'static + Send + Sync, +{ + pub fn new() -> Self { + Self(Arc::new(Mutex::new(SubscriberSetState { + subscribers: Default::default(), + pending_subscribers: Default::default(), + dropped_subscribers: Default::default(), + next_subscriber_id: 0, + }))) + } + + /// Inserts a new [`Subscription`] for the given `emitter_key`. + /// + /// By default, subscriptions are inert, meaning that they won't be listed when calling + /// `[SubscriberSet::remove]` or `[SubscriberSet::retain]`. This method returns a tuple + /// of a [`Subscription`] and an `impl FnOnce`, and you can use the latter to activate + /// the [`Subscription`]. + pub fn insert( + &self, + emitter_key: EmitterKey, + callback: Callback, + ) -> (Subscription, impl FnOnce()) { + let active = Arc::new(AtomicBool::new(false)); + let mut lock = self.0.lock(); + let subscriber_id = post_inc(&mut lock.next_subscriber_id); + let this = Arc::downgrade(&self.0); + let emitter_key_1 = emitter_key.clone(); + let inner_sub = InnerSubscription { + unsubscribe: Arc::new(Mutex::new(Some(Box::new(move || { + let Some(this) = this.upgrade() else { + return; + }; + + let mut lock = this.lock(); + let Some(subscribers) = lock.subscribers.get_mut(&emitter_key) else { + // remove was called with this emitter_key + return; + }; + + if let Either::Left(subscribers) = subscribers { + let removed = subscribers.remove(&subscriber_id); + if subscribers.is_empty() { + lock.subscribers.remove(&emitter_key); + } + // Drop the subscriber only after releasing the lock: its callback + // may own another `Subscription` (or an `UndoManager`) on this set, + // whose drop takes this lock again (loro-dev/loro#1162). + drop(lock); + drop(removed); + return; + } + + // We didn't manage to remove the subscription, which means it was dropped + // while invoking the callback. Mark it as dropped so that we can remove it + // later. + lock.dropped_subscribers + .insert((emitter_key, subscriber_id)); + })))), + }; + let subscription = Subscription { + unsubscribe: Arc::downgrade(&inner_sub.unsubscribe), + }; + + let subscriber = Subscriber { + active: active.clone(), + callback, + _sub: inner_sub, + }; + // Subscribing to an emitter that is mid-emit is legal and + // happens whenever one thread adds a listener while another is + // delivering events for the same key (or a callback subscribes + // re-entrantly). The map is checked out by `retain` in that + // window, so park the subscriber instead of unwrapping a + // `Left` that is not there. + if matches!(lock.subscribers.get(&emitter_key_1), Some(Either::Right(_))) { + lock.pending_subscribers + .entry(emitter_key_1) + .or_default() + .insert(subscriber_id, subscriber); + } else { + lock.subscribers + .entry(emitter_key_1) + .or_insert_with(|| Either::Left(BTreeMap::new())) + .as_mut() + .unwrap_left() + .insert(subscriber_id, subscriber); + } + (subscription, move || active.store(true, Ordering::Relaxed)) + } + + #[allow(unused)] + pub fn remove(&self, emitter: &EmitterKey) -> impl IntoIterator<Item = Callback> { + let mut lock = self.0.lock(); + let subscribers = lock.subscribers.remove(emitter); + // A subscriber parked mid-emit belongs to the emitter being + // removed; it never became visible, so it goes with it. + let parked = lock.pending_subscribers.remove(emitter); + // Drop callbacks outside the lock; see the unsubscribe closure in `insert`. + drop(lock); + drop(parked); + subscribers + .and_then(|x| x.left().map(|s| s.into_values())) + .into_iter() + .flatten() + .filter_map(|subscriber| { + if subscriber.active.load(Ordering::Relaxed) { + Some(subscriber.callback) + } else { + None + } + }) + } + + pub fn is_recursive_calling(&self, emitter: &EmitterKey) -> bool { + if let Some(Either::Right(thread_id)) = self.0.lock().subscribers.get(emitter) { + *thread_id == thread::current().id() + } else { + false + } + } + + /// Call the given callback for each subscriber to the given emitter. + /// If the callback returns false, the subscriber is removed. + pub fn retain( + &self, + emitter: &EmitterKey, + f: &mut dyn FnMut(&mut Callback) -> bool, + ) -> Result<(), SubscriptionError> { + let mut subscribers = { + let inner = loop { + let mut subscriber_set_state = self.0.lock(); + let Some(set) = subscriber_set_state.subscribers.get_mut(emitter) else { + return Ok(()); + }; + match set { + Either::Left(_) => { + break std::mem::replace(set, Either::Right(thread::current().id())) + .unwrap_left(); + } + Either::Right(lock_thread) => { + if thread::current().id() == *lock_thread { + return Err(SubscriptionError::CannotEmitEventDueToRecursiveCall); + } else { + // return Ok(()); + drop(subscriber_set_state); + #[cfg(loom)] + loom::thread::yield_now(); + #[cfg(not(loom))] + std::thread::sleep(std::time::Duration::from_millis(10)); + } + } + } + }; + inner + }; + + // A panicking callback must not take the checked-out subscribers with + // it: the marker left in their place would make later emits on this + // thread queue forever and emits on other threads wait forever. The + // other subscribers still get the event, the map is put back, and the + // first panic is raised again at the end. + let mut panic = DeferredPanic::default(); + subscribers.retain(|_, subscriber| { + if !subscriber.active.load(Ordering::Relaxed) { + return true; + } + panic.run(|| f(&mut subscriber.callback)).unwrap_or(true) + }); + + let mut lock = self.0.lock(); + + // Add any new subscribers that were added while invoking the callback. + if let Some(Either::Left(new_subscribers)) = lock.subscribers.remove(emitter) { + subscribers.extend(new_subscribers); + } + // …including those parked because this emitter was checked + // out. Folded in BEFORE the dropped sweep below, so one that + // was unsubscribed again mid-emit is still dropped. + if let Some(parked) = lock.pending_subscribers.remove(emitter) { + subscribers.extend(parked); + } + + // Remove any dropped subscriptions that were dropped while invoking the callback. + let mut removed = Vec::new(); + for (dropped_emitter, dropped_subscription_id) in mem::take(&mut lock.dropped_subscribers) { + if *emitter == dropped_emitter { + removed.extend(subscribers.remove(&dropped_subscription_id)); + } else { + lock.dropped_subscribers + .insert((dropped_emitter, dropped_subscription_id)); + } + } + + lock.subscribers + .insert(emitter.clone(), Either::Left(subscribers)); + // Drop callbacks outside the lock; see the unsubscribe closure in `insert`. + drop(lock); + drop(removed); + panic.resume(); + Ok(()) + } + + pub fn is_empty(&self) -> bool { + self.0.lock().subscribers.is_empty() + } + + pub fn may_include(&self, emitter: &EmitterKey) -> bool { + self.0.lock().subscribers.contains_key(emitter) + } +} + +impl<EmitterKey, Callback> Default for SubscriberSet<EmitterKey, Callback> +where + EmitterKey: 'static + Ord + Clone + Debug + Send + Sync, + Callback: 'static + Send + Sync, +{ + fn default() -> Self { + Self::new() + } +} + +impl<EmitterKey, Callback> std::fmt::Debug for SubscriberSet<EmitterKey, Callback> +where + EmitterKey: 'static + Ord + Clone + Debug + Send + Sync, + Callback: 'static + Send + Sync, +{ + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let lock = self.0.lock(); + f.debug_struct("SubscriberSet") + .field("subscriber_count", &lock.subscribers.len()) + .field("dropped_subscribers_count", &lock.dropped_subscribers.len()) + .field("next_subscriber_id", &lock.next_subscriber_id) + .finish() + } +} + +fn post_inc(next_subscriber_id: &mut usize) -> usize { + let ans = *next_subscriber_id; + *next_subscriber_id += 1; + ans +} +type Callback = Box<dyn FnOnce() + 'static + Send + Sync>; + +/// A handle to a subscription created by GPUI. When dropped, the subscription +/// is cancelled and the callback will no longer be invoked. +#[must_use] +pub struct Subscription { + unsubscribe: Weak<Mutex<Option<Callback>>>, +} + +impl std::fmt::Debug for Subscription { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Subscription").finish() + } +} + +impl Subscription { + /// Detaches the subscription from this handle. The callback will + /// continue to be invoked until the doc has been subscribed to + /// are dropped + pub fn detach(self) { + if let Some(unsubscribe) = self.unsubscribe.upgrade() { + unsubscribe.lock().take(); + } + } + + /// Unsubscribes the subscription. + #[inline] + pub fn unsubscribe(self) { + drop(self) + } +} + +impl Drop for Subscription { + fn drop(&mut self) { + if let Some(unsubscribe) = self.unsubscribe.upgrade() { + let unsubscribe = unsubscribe.lock().take(); + if let Some(unsubscribe) = unsubscribe { + unsubscribe(); + } + } + } +} + +struct InnerSubscription { + unsubscribe: Arc<Mutex<Option<Callback>>>, +} + +impl Drop for InnerSubscription { + fn drop(&mut self) { + self.unsubscribe.lock().take(); + } +} + +/// A wrapper around `SubscriberSet` that automatically handles recursive event emission. +/// +/// This struct differs from `SubscriberSet` in the following ways: +/// 1. It automatically handles the `CannotEmitEventDueToRecursiveCall` error that can occur in `SubscriberSet`. +/// 2. When a recursive event emission is detected, it queues the event instead of throwing an error. +/// 3. After the current event processing is complete, it automatically processes the queued events. +/// +/// This behavior ensures that all events are processed in the order they were emitted, even in cases +/// where recursive event emission would normally cause an error. +#[derive(Clone)] +pub struct SubscriberSetWithQueue<EmitterKey, Callback, Payload> { + subscriber_set: SubscriberSet<EmitterKey, Callback>, + queue: Arc<Mutex<BTreeMap<EmitterKey, Vec<Payload>>>>, +} + +impl<EmitterKey, Callback, Payload> Debug + for SubscriberSetWithQueue<EmitterKey, Callback, Payload> +{ + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SubscriberSetWithQueue").finish() + } +} + +impl<EmitterKey, Callback, Payload> Default + for SubscriberSetWithQueue<EmitterKey, Callback, Payload> +where + EmitterKey: 'static + Ord + Clone + Debug + Send + Sync, + Callback: 'static + Send + Sync + for<'a> FnMut(&'a Payload) -> bool, + Payload: Send + Sync + Debug, +{ + fn default() -> Self { + Self::new() + } +} + +pub struct WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload> { + subscriber_set: Weak<Mutex<SubscriberSetState<EmitterKey, Callback>>>, + queue: Weak<Mutex<BTreeMap<EmitterKey, Vec<Payload>>>>, +} + +impl<EmitterKey, Callback, Payload> Debug + for WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload> +{ + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WeakSubscriberSetWithQueue").finish() + } +} + +impl<EmitterKey, Callback, Payload> Clone + for WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload> +{ + fn clone(&self) -> Self { + Self { + subscriber_set: self.subscriber_set.clone(), + queue: self.queue.clone(), + } + } +} + +impl<EmitterKey, Callback, Payload> WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload> { + pub fn upgrade(self) -> Option<SubscriberSetWithQueue<EmitterKey, Callback, Payload>> { + Some(SubscriberSetWithQueue { + subscriber_set: SubscriberSet(self.subscriber_set.upgrade()?), + queue: self.queue.upgrade()?, + }) + } +} + +/// Runs steps that must all happen even if one of them panics, such as calling +/// every subscriber and delivering every event, and raises the first panic +/// once they are done. A subscriber is user code; its panic must not drop +/// events or local updates meant for others. +#[derive(Default)] +pub(crate) struct DeferredPanic(Option<Box<dyn std::any::Any + Send + 'static>>); + +impl DeferredPanic { + pub fn run<R>(&mut self, f: impl FnOnce() -> R) -> Option<R> { + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) { + Ok(ans) => Some(ans), + Err(payload) => { + self.0.get_or_insert(payload); + None + } + } + } + + pub fn has_panic(&self) -> bool { + self.0.is_some() + } + + pub fn resume(self) { + if let Some(payload) = self.0 { + std::panic::resume_unwind(payload); + } + } +} + +impl<EmitterKey, Callback, Payload> SubscriberSetWithQueue<EmitterKey, Callback, Payload> +where + EmitterKey: 'static + Ord + Clone + Debug + Send + Sync, + Callback: 'static + Send + Sync + for<'a> FnMut(&'a Payload) -> bool, + Payload: Send + Sync + Debug, +{ + pub fn new() -> Self { + Self { + subscriber_set: SubscriberSet::new(), + queue: Arc::new(Mutex::new(Default::default())), + } + } + + pub fn downgrade(&self) -> WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload> { + WeakSubscriberSetWithQueue { + subscriber_set: Arc::downgrade(&self.subscriber_set.0), + queue: Arc::downgrade(&self.queue), + } + } + + pub fn inner(&self) -> &SubscriberSet<EmitterKey, Callback> { + &self.subscriber_set + } + + pub fn emit(&self, key: &EmitterKey, payload: Payload) { + let mut panic = DeferredPanic::default(); + let mut pending_events: SmallVec<[Payload; 1]> = SmallVec::new(); + pending_events.push(payload); + while let Some(payload) = pending_events.pop() { + // A subscriber that panicked still had the payload delivered to the others. + let result = panic + .run(|| { + self.subscriber_set + .retain(key, &mut |callback| (callback)(&payload)) + }) + .unwrap_or(Ok(())); + match result { + Ok(_) => { + let mut queue = self.queue.lock(); + if let Some(new_pending_events) = queue.remove(key) { + pending_events.extend(new_pending_events); + } + } + Err(SubscriptionError::CannotEmitEventDueToRecursiveCall) => { + let mut queue = self.queue.lock(); + queue.entry(key.clone()).or_default().push(payload); + } + } + } + panic.resume(); + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_inner_subscription_drop() { + let subscriber_set = SubscriberSet::<i32, Box<dyn Fn(&i32) -> bool + Send + Sync>>::new(); + let (subscription, activate) = subscriber_set.insert(1, Box::new(move |_: &i32| true)); + activate(); + drop(subscriber_set); + assert!(subscription.unsubscribe.upgrade().is_none()); + } + + /// Subscribing while the same emitter is mid-emit must not panic. + /// `retain` checks the emitter's map out and leaves a `ThreadId` + /// marker in its place, so an `insert` landing in that window used + /// to `unwrap_left()` the marker and take the process down with + /// `called Either::unwrap_left() on a Right value`. The new + /// subscriber is parked and folded in when `retain` restores the + /// map — so it is registered, but does not fire for the event + /// already being delivered. + #[test] + fn insert_during_emit_does_not_panic() { + let set = SubscriberSet::<i32, Box<dyn Fn(&i32) -> bool + Send + Sync>>::new(); + let late_fired = Arc::new(AtomicBool::new(false)); + + // The first subscriber subscribes AGAIN from inside its own + // callback: the emitter is checked out at that moment, which + // is exactly the state that used to panic. + let set_inner = set.clone(); + let flag = late_fired.clone(); + let (_sub, activate) = set.insert( + 1, + Box::new(move |_: &i32| { + let flag = flag.clone(); + let (sub, activate) = set_inner.insert( + 1, + Box::new(move |_: &i32| { + flag.store(true, Ordering::Relaxed); + true + }), + ); + activate(); + std::mem::forget(sub); + true + }), + ); + activate(); + + set.retain(&1, &mut |callback| callback(&1)).unwrap(); + assert!( + !late_fired.load(Ordering::Relaxed), + "a subscriber added mid-emit must not receive the event being delivered" + ); + + // The parked subscriber was folded back in, so the NEXT emit + // reaches it. + set.retain(&1, &mut |callback| callback(&1)).unwrap(); + assert!( + late_fired.load(Ordering::Relaxed), + "a subscriber added mid-emit must be registered for later events" + ); + } + + /// The cross-thread flavour: one thread emits while another + /// subscribes to the same emitter. + #[test] + fn concurrent_insert_and_emit_do_not_panic() { + use std::sync::{atomic::AtomicUsize, mpsc}; + let set = SubscriberSet::<i32, Box<dyn Fn(&i32) -> bool + Send + Sync>>::new(); + + // The first emit parks inside the callback until released, which + // keeps the emitter checked out for as long as the test needs. + let (entered_tx, entered_rx) = mpsc::channel::<()>(); + let (release_tx, release_rx) = mpsc::channel::<()>(); + let entered_tx = std::sync::Mutex::new(Some(entered_tx)); + let release_rx = std::sync::Mutex::new(release_rx); + let (_sub, activate) = set.insert( + 1, + Box::new(move |_: &i32| { + if let Some(tx) = entered_tx.lock().unwrap().take() { + tx.send(()).unwrap(); + release_rx.lock().unwrap().recv().unwrap(); + } + true + }), + ); + activate(); + + let emitter = set.clone(); + let t = std::thread::spawn(move || { + emitter.retain(&1, &mut |callback| callback(&1)).unwrap(); + }); + + // Only subscribe once the emitting thread is inside the callback, + // so this insert is guaranteed to land while the emitter is + // checked out. + entered_rx.recv().unwrap(); + let late_calls = Arc::new(AtomicUsize::new(0)); + let late_calls_clone = late_calls.clone(); + let (sub, activate) = set.insert( + 1, + Box::new(move |_: &i32| { + late_calls_clone.fetch_add(1, Ordering::SeqCst); + true + }), + ); + activate(); + release_tx.send(()).unwrap(); + t.join().unwrap(); + assert_eq!(late_calls.load(Ordering::SeqCst), 0); + + set.retain(&1, &mut |callback| callback(&1)).unwrap(); + assert_eq!(late_calls.load(Ordering::SeqCst), 1); + drop(sub); + } + + #[test] + fn test_inner_subscription_drop_2() { + let subscriber_set = SubscriberSet::<i32, Box<dyn Fn(&i32) -> bool + Send + Sync>>::new(); + let (subscription, activate) = subscriber_set.insert(1, Box::new(move |_: &i32| false)); + activate(); + subscriber_set + .retain(&1, &mut |callback| callback(&1)) + .unwrap(); + assert!(subscription.unsubscribe.upgrade().is_none()); + } +} diff --git a/vendor/loro-internal/src/utils/utf16.rs b/vendor/loro-internal/src/utils/utf16.rs new file mode 100644 index 0000000..3096d96 --- /dev/null +++ b/vendor/loro-internal/src/utils/utf16.rs @@ -0,0 +1,139 @@ +pub fn count_utf16_len(utf8_str: &[u8]) -> usize { + str_lens(utf8_str).1 +} + +#[allow(dead_code)] +fn count_utf16_len_slow(utf8_str: &[u8]) -> usize { + let mut utf16_count = 0; + + let mut iter = utf8_str.iter(); + + while let Some(&byte) = iter.next() { + if byte & 0b1000_0000 == 0 { + utf16_count += 1; + } else if byte & 0b1110_0000 == 0b1100_0000 { + let _ = iter.next(); + + utf16_count += 1; + } else if byte & 0b1111_0000 == 0b1110_0000 { + let _ = iter.next(); + let _ = iter.next(); + + utf16_count += 1; + } else if byte & 0b1111_1000 == 0b1111_0000 { + let u = (((byte & 0b0000_0111) as u32) << 18) + | (((iter.next().unwrap() & 0b0011_1111) as u32) << 12); + + let _ = iter.next(); + let _ = iter.next(); + if u >= 0x10000 { + utf16_count += 2; + } else { + utf16_count += 1; + } + } else { + unreachable!() + } + } + + utf16_count +} + +// TODO: FIXME: Tests +/// Count unicode chars in a utf8 string +pub fn count_unicode_chars(s: &[u8]) -> usize { + str_lens(s).0 +} + +/// (unicode, utf16) lengths of valid UTF-8 by counting lead bytes; no per-char decode. +/// (project_note patch) +pub fn str_lens(s: &[u8]) -> (usize, usize) { + // Mostly-ASCII text (say code with one separator) skips its ASCII chunks. + let (mut unicode, mut wide) = (0usize, 0usize); + for c in s.chunks(4096) { + if c.is_ascii() { + unicode += c.len(); + continue; + } + for &b in c { + unicode += ((b as i8) >= -0x40) as usize; + wide += (b >= 0xF0) as usize; + } + } + (unicode, unicode + wide) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_ascii() { + let input = "Hello, world!"; + let expected = 13; + assert_eq!(count_utf16_len(input.as_bytes()), expected); + } + + #[test] + fn test_2_byte() { + let input = "Привет, мир!"; + let expected = 12; + assert_eq!(count_utf16_len(input.as_bytes()), expected); + } + + #[test] + fn test_3_byte() { + let input = "こんにちは世界"; + let expected = 7; + assert_eq!(count_utf16_len(input.as_bytes()), expected); + } + + #[test] + fn test_4_byte() { + let input = "👋🌍"; + let expected = 4; + assert_eq!(count_utf16_len(input.as_bytes()), expected); + } + + #[test] + fn test_crazy_emoji_bytes() { + let input = "👩‍👩‍👧‍👧👨‍👨‍👧"; + let expected = 19; + assert_eq!(count_utf16_len(input.as_bytes()), expected); + } + + #[test] + fn test_empty_string() { + let input = ""; + let expected = 0; + assert_eq!(count_utf16_len(input.as_bytes()), expected); + } + + #[test] + fn test_single_char() { + let input = "a"; + let expected = 1; + assert_eq!(count_utf16_len(input.as_bytes()), expected); + } + + #[test] + fn test_utf8_with_bom() { + let input = "\u{FEFF}Hello, world!"; // UTF-8 with BOM + let expected = 14; + assert_eq!(count_utf16_len(input.as_bytes()), expected); + } + + #[test] + fn test_long_string() { + let input = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + let expected = 52; + assert_eq!(count_utf16_len(input.as_bytes()), expected); + } + + #[test] + fn test_utf8_with_null_char() { + let input = "Hello\u{0000}world!"; + let expected = 12; + assert_eq!(count_utf16_len(input.as_bytes()), expected); + } +} diff --git a/vendor/loro-internal/src/value.rs b/vendor/loro-internal/src/value.rs new file mode 100644 index 0000000..1c47e9c --- /dev/null +++ b/vendor/loro-internal/src/value.rs @@ -0,0 +1,1222 @@ +use crate::{ + container::richtext::richtext_state::{unicode_to_utf8_index, utf16_to_utf8_index}, + delta::{Delta, DeltaItem, Meta}, + event::{Diff, Index, Path, TextDiff, TextDiffItem, TextMeta}, + handler::ValueOrHandler, + utils::string_slice::StringSlice, +}; +use generic_btree::rle::HasLength; +use loro_common::ContainerType; +pub use loro_common::LoroValue; + +// TODO: rename this trait +pub trait ToJson { + fn to_json_value(&self) -> serde_json::Value; + fn to_json(&self) -> String { + self.to_json_value().to_string() + } + fn to_json_pretty(&self) -> String { + serde_json::to_string_pretty(&self.to_json_value()).unwrap() + } + fn from_json(s: &str) -> Self; +} + +impl ToJson for LoroValue { + fn to_json_value(&self) -> serde_json::Value { + serde_json::to_value(self).unwrap() + } + + fn to_json(&self) -> String { + serde_json::to_string(self).unwrap() + } + + fn to_json_pretty(&self) -> String { + serde_json::to_string_pretty(self).unwrap() + } + + #[allow(unused)] + fn from_json(s: &str) -> Self { + serde_json::from_str(s).unwrap() + } +} + +impl ToJson for DeltaItem<StringSlice, TextMeta> { + fn to_json_value(&self) -> serde_json::Value { + match self { + DeltaItem::Retain { + retain: len, + attributes: meta, + } => { + let mut map = serde_json::Map::new(); + map.insert("retain".into(), serde_json::to_value(len).unwrap()); + if !meta.is_empty() { + map.insert("attributes".into(), meta.to_json_value()); + } + serde_json::Value::Object(map) + } + DeltaItem::Insert { + insert: value, + attributes: meta, + } => { + let mut map = serde_json::Map::new(); + map.insert("insert".into(), serde_json::to_value(value).unwrap()); + if !meta.is_empty() { + map.insert("attributes".into(), meta.to_json_value()); + } + serde_json::Value::Object(map) + } + DeltaItem::Delete { + delete: len, + attributes: _, + } => { + let mut map = serde_json::Map::new(); + map.insert("delete".into(), serde_json::to_value(len).unwrap()); + serde_json::Value::Object(map) + } + } + } + + fn from_json(s: &str) -> Self { + let map: serde_json::Map<String, serde_json::Value> = serde_json::from_str(s).unwrap(); + if map.contains_key("retain") { + let len = map["retain"].as_u64().unwrap(); + let meta = if let Some(meta) = map.get("attributes") { + TextMeta::from_json(meta.to_string().as_str()) + } else { + TextMeta::default() + }; + DeltaItem::Retain { + retain: len as usize, + attributes: meta, + } + } else if map.contains_key("insert") { + let value = map["insert"].as_str().unwrap().to_string().into(); + let meta = if let Some(meta) = map.get("attributes") { + TextMeta::from_json(meta.to_string().as_str()) + } else { + TextMeta::default() + }; + DeltaItem::Insert { + insert: value, + attributes: meta, + } + } else if map.contains_key("delete") { + let len = map["delete"].as_u64().unwrap(); + DeltaItem::Delete { + delete: len as usize, + attributes: Default::default(), + } + } else { + panic!("Invalid delta item: {}", s); + } + } +} + +fn diff_item_to_json_value(item: &TextDiffItem) -> (serde_json::Value, Option<serde_json::Value>) { + match item { + loro_delta::DeltaItem::Retain { len, attr } => { + let mut map = serde_json::Map::new(); + map.insert("retain".into(), serde_json::to_value(len).unwrap()); + if !attr.is_empty() { + map.insert("attributes".into(), attr.to_json_value()); + } + (serde_json::Value::Object(map), None) + } + loro_delta::DeltaItem::Replace { + value, + attr, + delete, + } => { + let mut a = None; + let mut b = None; + if value.rle_len() > 0 { + let mut map = serde_json::Map::new(); + map.insert("insert".into(), serde_json::to_value(value).unwrap()); + if !attr.is_empty() { + map.insert("attributes".into(), attr.to_json_value()); + } + a = Some(serde_json::Value::Object(map)); + } + if *delete > 0 { + let mut map = serde_json::Map::new(); + map.insert("delete".into(), serde_json::to_value(delete).unwrap()); + b = Some(serde_json::Value::Object(map)); + } + + if a.is_none() { + a = std::mem::take(&mut b); + if a.is_none() { + let mut map = serde_json::Map::new(); + map.insert("retain".into(), serde_json::to_value(0).unwrap()); + a = Some(serde_json::Value::Object(map)); + } + } + (a.unwrap(), b) + } + } +} + +fn diff_item_from_json(v: serde_json::Value) -> TextDiffItem { + let serde_json::Value::Object(map) = v else { + panic!("Invalid delta item: {:?}", v); + }; + if map.contains_key("retain") { + let len = map["retain"].as_u64().unwrap(); + let meta = if let Some(meta) = map.get("attributes") { + TextMeta::from_json(meta.to_string().as_str()) + } else { + TextMeta::default() + }; + TextDiffItem::Retain { + len: len as usize, + attr: meta, + } + } else if map.contains_key("insert") { + let value = map["insert"].as_str().unwrap().to_string().into(); + let meta = if let Some(meta) = map.get("attributes") { + TextMeta::from_json(meta.to_string().as_str()) + } else { + TextMeta::default() + }; + TextDiffItem::Replace { + value, + attr: meta, + delete: 0, + } + } else if map.contains_key("delete") { + let len = map["delete"].as_u64().unwrap(); + TextDiffItem::new_delete(len as usize) + } else { + panic!("Invalid delta item: {:?}", map); + } +} + +impl ToJson for TextDiff { + fn to_json_value(&self) -> serde_json::Value { + let mut vec = Vec::new(); + for item in self.iter() { + let (a, b) = diff_item_to_json_value(item); + vec.push(a); + if let Some(b) = b { + vec.push(b); + } + } + serde_json::Value::Array(vec) + } + + fn from_json(s: &str) -> Self { + let vec: Vec<serde_json::Value> = serde_json::from_str(s).unwrap(); + let mut ans = TextDiff::new(); + for item in vec.into_iter() { + ans.push(diff_item_from_json(item)); + } + ans + } +} + +impl ToJson for Delta<StringSlice, TextMeta> { + fn to_json_value(&self) -> serde_json::Value { + let mut vec = Vec::new(); + for item in self.iter() { + vec.push(item.to_json_value()); + } + serde_json::Value::Array(vec) + } + + fn from_json(s: &str) -> Self { + let vec: Vec<serde_json::Value> = serde_json::from_str(s).unwrap(); + let mut ans = Delta::new(); + for item in vec.into_iter() { + ans.push(DeltaItem::from_json(item.to_string().as_str())); + } + ans + } +} + +#[derive(Debug, PartialEq, Eq)] +enum TypeHint { + Map, + Text, + List, + Tree, + #[cfg(feature = "counter")] + Counter, +} + +pub trait ApplyDiff { + fn apply_diff_shallow(&mut self, diff: &[Diff]); + fn apply_diff(&mut self, diff: &[Diff]); + fn apply(&mut self, path: &Path, diff: &[Diff]); +} + +impl ApplyDiff for LoroValue { + fn apply_diff_shallow(&mut self, diff: &[Diff]) { + match self { + LoroValue::String(value) => { + let mut s = value.to_string(); + for item in diff.iter() { + let delta = item.as_text().unwrap(); + let mut index = 0; + for delta_item in delta.iter() { + match delta_item { + loro_delta::DeltaItem::Retain { len, attr: _ } => { + index += len; + } + loro_delta::DeltaItem::Replace { + value, + attr: _, + delete, + } => { + let (start, end) = if cfg!(feature = "wasm") { + ( + utf16_to_utf8_index(&s, index).unwrap(), + utf16_to_utf8_index(&s, index + *delete).unwrap(), + ) + } else { + ( + unicode_to_utf8_index(&s, index).unwrap(), + unicode_to_utf8_index(&s, index + *delete).unwrap(), + ) + }; + s.replace_range(start..end, value.as_str()); + index += value.len_bytes(); + } + } + } + } + *value = s.into() + } + LoroValue::List(seq) => { + let is_tree = matches!(diff.first(), Some(Diff::Tree(_))); + if !is_tree { + let seq = seq.make_mut(); + for item in diff.iter() { + let delta = item.as_list().unwrap(); + let mut index = 0; + for delta_item in delta.iter() { + match delta_item { + loro_delta::DeltaItem::Retain { len, attr: _ } => { + index += len; + } + loro_delta::DeltaItem::Replace { + value, + attr: _, + delete, + } => { + let len = value.len(); + seq.splice( + index..index + delete, + value.iter().map(|x| x.to_value()), + ); + index += len; + } + } + } + } + } else { + // let seq = Arc::make_mut(seq); + // for item in diff.iter() { + // match item { + // Diff::Tree(tree) => { + // let mut v = TreeValue(seq); + // v.apply_diff(tree); + // } + // _ => unreachable!(), + // } + // } + unimplemented!() + } + } + LoroValue::Map(map) => { + for item in diff.iter() { + match item { + Diff::Map(diff) => { + let map = map.make_mut(); + for (key, value) in diff.updated.iter() { + match &value.value { + Some(value) => { + map.insert(key.to_string(), value.to_value()); + } + None => { + map.remove(&key.to_string()); + } + } + } + } + _ => unreachable!(), + } + } + } + _ => unreachable!(), + } + } + + fn apply_diff(&mut self, diff: &[Diff]) { + match self { + LoroValue::String(value) => { + let mut s = value.to_string(); + for item in diff.iter() { + let delta = item.as_text().unwrap(); + let mut index = 0; + for delta_item in delta.iter() { + match delta_item { + loro_delta::DeltaItem::Retain { len, attr: _ } => { + index += len; + } + loro_delta::DeltaItem::Replace { + value, + attr: _, + delete, + } => { + s.replace_range(index..index + *delete, value.as_str()); + index += value.len_bytes(); + } + } + } + } + *value = s.into(); + } + LoroValue::List(seq) => { + let is_tree = matches!(diff.first(), Some(Diff::Tree(_))); + if !is_tree { + let seq = seq.make_mut(); + for item in diff.iter() { + let delta = item.as_list().unwrap(); + let mut index = 0; + for delta_item in delta.iter() { + match delta_item { + loro_delta::DeltaItem::Retain { len, .. } => { + index += len; + } + loro_delta::DeltaItem::Replace { + value, + attr: _, + delete, + } => { + let value_iter = value.iter().map(unresolved_to_collection); + seq.splice(index..index + *delete, value_iter); + index += value.len(); + } + } + } + } + } else { + // let seq = Arc::make_mut(seq); + // for item in diff.iter() { + // match item { + // Diff::Tree(tree) => { + // let mut v = TreeValue(seq); + // v.apply_diff(tree); + // } + // _ => unreachable!(), + // } + // } + unimplemented!() + } + } + LoroValue::Map(map) => { + for item in diff.iter() { + match item { + Diff::Map(diff) => { + let map = map.make_mut(); + for (key, value) in diff.updated.iter() { + match &value.value { + Some(value) => { + map.insert( + key.to_string(), + unresolved_to_collection(value), + ); + } + None => { + map.remove(&key.to_string()); + } + } + } + } + _ => unreachable!(), + } + } + } + _ => unreachable!(), + } + } + + fn apply(&mut self, path: &Path, diff: &[Diff]) { + if diff.is_empty() { + return; + } + + let hint = match diff[0] { + Diff::List(_) => TypeHint::List, + Diff::Text(_) => TypeHint::Text, + Diff::Map(_) => TypeHint::Map, + Diff::Tree(_) => TypeHint::Tree, + #[cfg(feature = "counter")] + Diff::Counter(_) => TypeHint::Counter, + Diff::Unknown => unreachable!(), + }; + let value = { + let mut hints = Vec::with_capacity(path.len()); + for item in path.iter().skip(1) { + match item { + Index::Key(_) => hints.push(TypeHint::Map), + Index::Seq(_) => hints.push(TypeHint::List), + Index::Node(_) => hints.push(TypeHint::Tree), + } + } + + hints.push(hint); + let mut value: &mut LoroValue = self; + for (item, hint) in path.iter().zip(hints.iter()) { + match item { + Index::Key(key) => { + let m = value.as_map_mut().unwrap(); + let map = m.make_mut(); + value = map.entry(key.to_string()).or_insert_with(|| match hint { + TypeHint::Map => LoroValue::Map(Default::default()), + TypeHint::Text => LoroValue::String(Default::default()), + TypeHint::List => LoroValue::List(Default::default()), + TypeHint::Tree => LoroValue::List(Default::default()), + #[cfg(feature = "counter")] + TypeHint::Counter => LoroValue::Double(0.), + }) + } + Index::Seq(index) => { + let l = value.as_list_mut().unwrap(); + let list = l.make_mut(); + value = list.get_mut(*index).unwrap(); + } + Index::Node(tree_id) => { + let l = value.as_list_mut().unwrap(); + let list = l.make_mut(); + let Some(map) = list.iter_mut().find(|x| { + let id = x.as_map().unwrap().get("id").unwrap().as_string().unwrap(); + id.as_ref() == tree_id.to_string() + }) else { + // delete node first + return; + }; + let map_mut = map.as_map_mut().unwrap().make_mut(); + let meta = map_mut.get_mut("meta").unwrap(); + if meta.is_container() { + *meta = ContainerType::Map.default_value(); + } + value = meta + } + } + } + value + }; + value.apply_diff(diff); + } +} + +pub(crate) fn unresolved_to_collection(v: &ValueOrHandler) -> LoroValue { + match v { + ValueOrHandler::Value(v) => v.clone(), + ValueOrHandler::Handler(c) => c.c_type().default_value(), + } +} + +#[cfg(test)] +mod tests { + use loro_common::IdLp; + use loro_delta::{array_vec::ArrayVec, DeltaItem as EventDeltaItem}; + use rustc_hash::FxHashMap; + + use crate::{ + delta::{Delta, DeltaItem}, + event::{ListDeltaMeta, ListDiff, ListDiffInsertItem}, + handler::{Handler, HandlerTrait}, + LoroDoc, + }; + + use super::*; + + fn text_diff(items: Vec<TextDiffItem>) -> TextDiff { + let mut diff = TextDiff::new(); + for item in items { + diff.push(item); + } + diff + } + + fn list_values(values: Vec<LoroValue>) -> ListDiffInsertItem { + let mut array = ArrayVec::new(); + for value in values { + array.push(ValueOrHandler::Value(value)).unwrap(); + } + array + } + + fn list_diff(items: Vec<crate::event::ListDiffItem>) -> ListDiff { + let mut diff = ListDiff::new(); + for item in items { + diff.push(item); + } + diff + } + + fn map_value(value: Option<LoroValue>, lamport: u32) -> crate::delta::ResolvedMapValue { + crate::delta::ResolvedMapValue { + value: value.map(ValueOrHandler::Value), + idlp: IdLp::new(1, lamport), + } + } + + #[test] + fn text_delta_json_roundtrip_preserves_attributes_and_operation_order() { + let mut attributes = FxHashMap::default(); + attributes.insert("bold".to_string(), LoroValue::Bool(true)); + let meta = TextMeta(attributes); + + let item = DeltaItem::Insert { + insert: StringSlice::from("hi"), + attributes: meta.clone(), + }; + assert_eq!( + item.to_json_value(), + serde_json::json!({"insert": "hi", "attributes": {"bold": true}}) + ); + assert_eq!( + DeltaItem::<StringSlice, TextMeta>::from_json( + r#"{"insert":"hi","attributes":{"bold":true}}"# + ), + item + ); + + let mut delta = Delta::<StringSlice, TextMeta>::new(); + delta.push(DeltaItem::Retain { + retain: 2, + attributes: meta.clone(), + }); + delta.push(DeltaItem::Insert { + insert: StringSlice::from("!"), + attributes: TextMeta::default(), + }); + delta.push(DeltaItem::Delete { + delete: 1, + attributes: TextMeta::default(), + }); + + let json = delta.to_json(); + assert_eq!( + serde_json::from_str::<serde_json::Value>(&json).unwrap(), + serde_json::json!([ + {"retain": 2, "attributes": {"bold": true}}, + {"insert": "!"}, + {"delete": 1} + ]) + ); + assert_eq!(Delta::<StringSlice, TextMeta>::from_json(&json), delta); + } + + #[test] + fn text_diff_json_splits_replace_with_insert_and_delete_entries() { + let diff = text_diff(vec![TextDiffItem::Replace { + value: StringSlice::from("new"), + attr: TextMeta::default(), + delete: 2, + }]); + + assert_eq!( + diff.to_json_value(), + serde_json::json!([{"insert": "new"}, {"delete": 2}]) + ); + assert_eq!( + TextDiff::from_json(r#"[{"retain":1},{"insert":"x"},{"delete":2}]"#).to_json_value(), + serde_json::json!([{"retain": 1}, {"insert": "x"}, {"delete": 2}]) + ); + + let (empty_replace, follow_up) = diff_item_to_json_value(&TextDiffItem::Replace { + value: StringSlice::from(""), + attr: TextMeta::default(), + delete: 0, + }); + assert_eq!(empty_replace, serde_json::json!({"retain": 0})); + assert_eq!(follow_up, None); + } + + #[test] + fn apply_diff_updates_string_list_and_map_values() { + let mut text = LoroValue::String("aéz".into()); + text.apply_diff_shallow(&[Diff::Text(text_diff(vec![ + TextDiffItem::Retain { + len: 1, + attr: TextMeta::default(), + }, + TextDiffItem::Replace { + value: StringSlice::from("bc"), + attr: TextMeta::default(), + delete: 1, + }, + ]))]); + assert_eq!(text, LoroValue::String("abcz".into())); + + let mut list = + LoroValue::List(vec![LoroValue::I64(1), LoroValue::I64(2), LoroValue::I64(3)].into()); + list.apply_diff(&[Diff::List(list_diff(vec![ + EventDeltaItem::Retain { + len: 1, + attr: ListDeltaMeta::default(), + }, + EventDeltaItem::Replace { + value: list_values(vec![LoroValue::I64(20), LoroValue::I64(21)]), + attr: ListDeltaMeta::default(), + delete: 1, + }, + ]))]); + assert_eq!( + list, + LoroValue::List( + vec![ + LoroValue::I64(1), + LoroValue::I64(20), + LoroValue::I64(21), + LoroValue::I64(3), + ] + .into() + ) + ); + + let mut map = LoroValue::Map( + FxHashMap::from_iter([ + ("keep".to_string(), LoroValue::I64(1)), + ("remove".to_string(), LoroValue::I64(2)), + ]) + .into(), + ); + map.apply_diff(&[Diff::Map( + crate::delta::ResolvedMapDelta::new() + .with_entry("add".into(), map_value(Some(LoroValue::I64(3)), 1)) + .with_entry("remove".into(), map_value(None, 2)), + )]); + let map = map.as_map().unwrap(); + assert_eq!(map.get("keep"), Some(&LoroValue::I64(1))); + assert_eq!(map.get("add"), Some(&LoroValue::I64(3))); + assert_eq!(map.get("remove"), None); + } + + #[test] + fn apply_creates_missing_nested_values_from_path_and_diff_hint() { + let mut root = LoroValue::Map(Default::default()); + let mut title_path = Path::new(); + title_path.push(Index::Key("doc".into())); + title_path.push(Index::Key("title".into())); + root.apply( + &title_path, + &[Diff::Text(text_diff(vec![TextDiffItem::Replace { + value: StringSlice::from("Loro"), + attr: TextMeta::default(), + delete: 0, + }]))], + ); + + assert_eq!( + root.to_json_value(), + serde_json::json!({"doc": {"title": "Loro"}}) + ); + + let mut tags_path = Path::new(); + tags_path.push(Index::Key("doc".into())); + tags_path.push(Index::Key("tags".into())); + root.apply( + &tags_path, + &[Diff::List(list_diff(vec![EventDeltaItem::Replace { + value: list_values(vec![ + LoroValue::String("crdt".into()), + LoroValue::String("rust".into()), + ]), + attr: ListDeltaMeta::default(), + delete: 0, + }]))], + ); + assert_eq!( + root.to_json_value(), + serde_json::json!({"doc": {"title": "Loro", "tags": ["crdt", "rust"]}}) + ); + } + + #[test] + fn unresolved_container_handlers_apply_as_default_collection_values() { + let doc = LoroDoc::new_auto_commit(); + let map_handler = Handler::new_unattached(ContainerType::Map).unwrap(); + let text_handler = Handler::new_unattached(ContainerType::Text).unwrap(); + let attached_list = doc.get_list("list").to_handler(); + + assert_eq!( + unresolved_to_collection(&ValueOrHandler::Handler(map_handler)), + LoroValue::Map(Default::default()) + ); + assert_eq!( + unresolved_to_collection(&ValueOrHandler::Handler(text_handler)), + LoroValue::String(Default::default()) + ); + assert_eq!( + unresolved_to_collection(&ValueOrHandler::Handler(attached_list)), + LoroValue::List(Default::default()) + ); + assert_eq!( + unresolved_to_collection(&ValueOrHandler::Value(LoroValue::Bool(true))), + LoroValue::Bool(true) + ); + } +} + +#[cfg(feature = "wasm")] +pub mod wasm { + use crate::{ + delta::{Delta, DeltaItem, Meta, StyleMeta, TreeDiff, TreeDiffItem, TreeExternalDiff}, + event::{Index, TextDiff, TextDiffItem, TextMeta}, + utils::string_slice::StringSlice, + TreeParentId, + }; + use fractional_index::FractionalIndex; + use generic_btree::rle::HasLength; + use js_sys::{Array, Object}; + use loro_common::{LoroValue, TreeID}; + use wasm_bindgen::{__rt::IntoJsResult, JsCast, JsValue}; + + impl From<Index> for JsValue { + fn from(value: Index) -> Self { + match value { + Index::Key(key) => JsValue::from_str(&key), + Index::Seq(num) => JsValue::from_f64(num as f64), + Index::Node(node) => node.into(), + } + } + } + + impl From<&TreeDiff> for JsValue { + fn from(value: &TreeDiff) -> Self { + let array = Array::new(); + for diff in value.diff.iter() { + let obj = Object::new(); + js_sys::Reflect::set(&obj, &"target".into(), &diff.target.into()).unwrap(); + match &diff.action { + TreeExternalDiff::Create { + parent, + index, + position, + } => { + js_sys::Reflect::set(&obj, &"action".into(), &"create".into()).unwrap(); + js_sys::Reflect::set( + &obj, + &"parent".into(), + &JsValue::from(parent.tree_id()), + ) + .unwrap(); + js_sys::Reflect::set(&obj, &"index".into(), &(*index).into()).unwrap(); + js_sys::Reflect::set( + &obj, + &"fractionalIndex".into(), + &position.to_string().into(), + ) + .unwrap(); + } + TreeExternalDiff::Delete { + old_parent, + old_index, + } => { + js_sys::Reflect::set(&obj, &"action".into(), &"delete".into()).unwrap(); + js_sys::Reflect::set( + &obj, + &"oldParent".into(), + &JsValue::from(old_parent.tree_id()), + ) + .unwrap(); + js_sys::Reflect::set(&obj, &"oldIndex".into(), &(*old_index).into()) + .unwrap(); + } + TreeExternalDiff::Move { + parent, + index, + position, + old_parent, + old_index, + } => { + js_sys::Reflect::set(&obj, &"action".into(), &"move".into()).unwrap(); + js_sys::Reflect::set( + &obj, + &"parent".into(), + &JsValue::from(parent.tree_id()), + ) + .unwrap(); + js_sys::Reflect::set(&obj, &"index".into(), &(*index).into()).unwrap(); + js_sys::Reflect::set( + &obj, + &"fractionalIndex".into(), + &position.to_string().into(), + ) + .unwrap(); + js_sys::Reflect::set( + &obj, + &"oldParent".into(), + &JsValue::from(old_parent.tree_id()), + ) + .unwrap(); + js_sys::Reflect::set(&obj, &"oldIndex".into(), &(*old_index).into()) + .unwrap(); + } + } + array.push(&obj); + } + array.into_js_result().unwrap() + } + } + + impl TryFrom<&JsValue> for TreeDiff { + type Error = String; + + fn try_from(value: &JsValue) -> Result<Self, Self::Error> { + if !value.is_array() { + return Err("Expected an array".to_string()); + } + + let array = js_sys::Array::from(value); + let mut diff = Vec::new(); + + for i in 0..array.length() { + let item = array.get(i); + if !item.is_object() { + return Err(format!("Item at index {i} is not an object")); + } + + let obj = js_sys::Object::from(item); + let target = js_sys::Reflect::get(&obj, &"target".into()) + .map_err(|e| format!("Failed to get target: {:?}", e))?; + let target = TreeID::try_from(target) + .map_err(|e| format!("Failed to parse target: {:?}", e))?; + + let action = js_sys::Reflect::get(&obj, &"action".into()) + .map_err(|e| format!("Failed to get action: {:?}", e))?; + let action = action + .as_string() + .ok_or_else(|| "action is not a string".to_string())?; + + let action = match action.as_str() { + "create" => { + let parent = js_sys::Reflect::get(&obj, &"parent".into()) + .map_err(|e| format!("Failed to get parent: {:?}", e))?; + let parent_id = if parent.is_null() || parent.is_undefined() { + None + } else { + Some( + TreeID::try_from(parent) + .map_err(|e| format!("Failed to parse parent: {:?}", e))?, + ) + }; + let parent = TreeParentId::from(parent_id); + let index = js_sys::Reflect::get(&obj, &"index".into()) + .map_err(|e| format!("Failed to get index: {:?}", e))?; + let index = index + .as_f64() + .ok_or_else(|| "index is not a number".to_string())? + as usize; + + let position = js_sys::Reflect::get(&obj, &"fractionalIndex".into()) + .map_err(|e| format!("Failed to get fractionalIndex: {:?}", e))?; + let position = position + .as_string() + .ok_or_else(|| "fractionalIndex is not a string".to_string())?; + let position = FractionalIndex::from_hex_string(position); + + TreeExternalDiff::Create { + parent, + index, + position, + } + } + "move" => { + let parent = js_sys::Reflect::get(&obj, &"parent".into()) + .map_err(|e| format!("Failed to get parent: {:?}", e))?; + let parent_id = if parent.is_null() || parent.is_undefined() { + None + } else { + Some( + TreeID::try_from(parent) + .map_err(|e| format!("Failed to parse parent: {:?}", e))?, + ) + }; + let parent = TreeParentId::from(parent_id); + + let index = js_sys::Reflect::get(&obj, &"index".into()) + .map_err(|e| format!("Failed to get index: {:?}", e))?; + let index = index + .as_f64() + .ok_or_else(|| "index is not a number".to_string())? + as usize; + + let position = js_sys::Reflect::get(&obj, &"fractionalIndex".into()) + .map_err(|e| format!("Failed to get fractionalIndex: {:?}", e))?; + let position = position + .as_string() + .ok_or_else(|| "fractionalIndex is not a string".to_string())?; + let position = FractionalIndex::from_hex_string(position); + + let old_parent = js_sys::Reflect::get(&obj, &"oldParent".into()) + .map_err(|e| format!("Failed to get oldParent: {:?}", e))?; + let old_parent_id = if old_parent.is_null() || old_parent.is_undefined() { + None + } else { + Some( + TreeID::try_from(old_parent) + .map_err(|e| format!("Failed to parse oldParent: {:?}", e))?, + ) + }; + let old_parent = TreeParentId::from(old_parent_id); + + let old_index = js_sys::Reflect::get(&obj, &"oldIndex".into()) + .map_err(|e| format!("Failed to get oldIndex: {:?}", e))?; + let old_index = old_index + .as_f64() + .ok_or_else(|| "oldIndex is not a number".to_string())? + as usize; + + TreeExternalDiff::Move { + parent, + index, + position, + old_parent, + old_index, + } + } + "delete" => { + let old_parent = js_sys::Reflect::get(&obj, &"oldParent".into()) + .map_err(|e| format!("Failed to get oldParent: {:?}", e))?; + let old_parent_id = if old_parent.is_null() || old_parent.is_undefined() { + None + } else { + Some( + TreeID::try_from(old_parent) + .map_err(|e| format!("Failed to parse oldParent: {:?}", e))?, + ) + }; + let old_parent = TreeParentId::from(old_parent_id); + + let old_index = js_sys::Reflect::get(&obj, &"oldIndex".into()) + .map_err(|e| format!("Failed to get oldIndex: {:?}", e))?; + let old_index = old_index + .as_f64() + .ok_or_else(|| "oldIndex is not a number".to_string())? + as usize; + + TreeExternalDiff::Delete { + old_parent, + old_index, + } + } + action => Err(format!("Unknown tree diff action: {action}"))?, + }; + + diff.push(TreeDiffItem { target, action }); + } + + Ok(TreeDiff { diff }) + } + } + + impl From<&Delta<StringSlice, StyleMeta>> for JsValue { + fn from(value: &Delta<StringSlice, StyleMeta>) -> Self { + let arr = Array::new_with_length(value.len() as u32); + for (i, v) in value.iter().enumerate() { + arr.set(i as u32, JsValue::from(v.clone())); + } + + arr.into_js_result().unwrap() + } + } + + impl From<DeltaItem<StringSlice, StyleMeta>> for JsValue { + fn from(value: DeltaItem<StringSlice, StyleMeta>) -> Self { + let obj = Object::new(); + match value { + DeltaItem::Retain { + retain: len, + attributes: meta, + } => { + js_sys::Reflect::set( + &obj, + &JsValue::from_str("retain"), + &JsValue::from_f64(len as f64), + ) + .unwrap(); + if !meta.is_empty() { + js_sys::Reflect::set( + &obj, + &JsValue::from_str("attributes"), + &JsValue::from(&meta), + ) + .unwrap(); + } + } + DeltaItem::Insert { + insert: value, + attributes: meta, + } => { + js_sys::Reflect::set( + &obj, + &JsValue::from_str("insert"), + &JsValue::from_str(value.as_str()), + ) + .unwrap(); + if !meta.is_empty() { + js_sys::Reflect::set( + &obj, + &JsValue::from_str("attributes"), + &JsValue::from(&meta), + ) + .unwrap(); + } + } + DeltaItem::Delete { + delete: len, + attributes: _, + } => { + js_sys::Reflect::set( + &obj, + &JsValue::from_str("delete"), + &JsValue::from_f64(len as f64), + ) + .unwrap(); + } + } + + obj.into_js_result().unwrap() + } + } + + pub fn text_diff_to_js_value(diff: &TextDiff) -> JsValue { + let arr = Array::new(); + let mut i = 0; + for v in diff.iter() { + let (a, b) = text_diff_item_to_js_value(v); + arr.set(i as u32, a); + i += 1; + if let Some(b) = b { + arr.set(i as u32, b); + i += 1; + } + } + + arr.into_js_result().unwrap() + } + + fn text_diff_item_to_js_value(value: &TextDiffItem) -> (JsValue, Option<JsValue>) { + match value { + loro_delta::DeltaItem::Retain { len, attr } => { + let obj = Object::new(); + js_sys::Reflect::set( + &obj, + &JsValue::from_str("retain"), + &JsValue::from_f64(*len as f64), + ) + .unwrap(); + if !attr.is_empty() { + js_sys::Reflect::set( + &obj, + &JsValue::from_str("attributes"), + &JsValue::from(attr), + ) + .unwrap(); + } + (obj.into_js_result().unwrap(), None) + } + loro_delta::DeltaItem::Replace { + value, + attr, + delete, + } => { + let mut a = None; + let mut b = None; + if value.rle_len() > 0 { + let obj = Object::new(); + js_sys::Reflect::set( + &obj, + &JsValue::from_str("insert"), + &JsValue::from_str(value.as_str()), + ) + .unwrap(); + if !attr.is_empty() { + js_sys::Reflect::set( + &obj, + &JsValue::from_str("attributes"), + &JsValue::from(attr), + ) + .unwrap(); + } + a = Some(obj.into_js_result().unwrap()); + } + + if *delete > 0 { + let obj = Object::new(); + js_sys::Reflect::set( + &obj, + &JsValue::from_str("delete"), + &JsValue::from_f64(*delete as f64), + ) + .unwrap(); + b = Some(obj.into_js_result().unwrap()); + } + + if a.is_none() { + a = std::mem::take(&mut b); + } + + (a.unwrap(), b) + } + } + } + + impl From<&StyleMeta> for JsValue { + fn from(value: &StyleMeta) -> Self { + // TODO: refactor: should we extract the common code of ToJson and ToJsValue + let obj = Object::new(); + for (key, style) in value.iter() { + let value = JsValue::from(style.data); + js_sys::Reflect::set(&obj, &JsValue::from_str(&key), &value).unwrap(); + } + + obj.into_js_result().unwrap() + } + } + + impl From<&TextMeta> for JsValue { + fn from(value: &TextMeta) -> Self { + let obj = Object::new(); + for (key, value) in value.0.iter() { + js_sys::Reflect::set(&obj, &JsValue::from_str(key), &JsValue::from(value.clone())) + .unwrap(); + } + + obj.into_js_result().unwrap() + } + } + + impl TryFrom<&JsValue> for TextMeta { + type Error = JsValue; + + fn try_from(value: &JsValue) -> Result<Self, Self::Error> { + if value.is_null() || value.is_undefined() { + return Ok(TextMeta::default()); + } + + let obj = value.dyn_ref::<Object>().ok_or("Expected an object")?; + let mut meta = TextMeta::default(); + + let entries = Object::entries(obj); + for i in 0..entries.length() { + let entry = entries.get(i); + let entry_arr = entry.dyn_ref::<Array>().ok_or("Expected an array")?; + let key = entry_arr + .get(0) + .as_string() + .ok_or("Expected a string key")?; + let value = entry_arr.get(1); + meta.0.insert(key, LoroValue::from(value)); + } + + Ok(meta) + } + } +} diff --git a/vendor/loro-internal/src/version.rs b/vendor/loro-internal/src/version.rs new file mode 100644 index 0000000..3c3edb3 --- /dev/null +++ b/vendor/loro-internal/src/version.rs @@ -0,0 +1,1221 @@ +mod frontiers; +pub use frontiers::Frontiers; + +use crate::{ + id::{Counter, ID}, + oplog::AppDag, + span::{CounterSpan, IdSpan}, + LoroError, PeerID, +}; +use loro_common::{HasCounter, HasCounterSpan, HasIdSpan, HasLamportSpan, IdFull, IdSpanVector}; +use rustc_hash::FxHashMap; +use serde::{Deserialize, Serialize}; +use smallvec::SmallVec; +use std::{ + cmp::Ordering, + ops::{ControlFlow, Deref, DerefMut}, +}; + +/// [VersionVector](https://en.wikipedia.org/wiki/Version_vector) +/// is a map from [PeerID] to [Counter]. Its a right-open interval. +/// +/// i.e. a [VersionVector] of `{A: 1, B: 2}` means that A has 1 atomic op and B has 2 atomic ops, +/// thus ID of `{client: A, counter: 1}` is out of the range. +// +// NOTE: though normally it doesn't make sense to have an entry with counter = 0, but it can be 0 in certain cases. +// Like, when using start_vv and end_vv to mark the version range, start_vv may have an entry with counter = 0. +#[repr(transparent)] +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct VersionVector(FxHashMap<PeerID, Counter>); + +#[repr(transparent)] +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct VersionRange(pub(crate) FxHashMap<PeerID, (Counter, Counter)>); + +#[macro_export] +macro_rules! version_range { + ($($peer:expr => ($start:expr, $end:expr)),* $(,)?) => {{ + let mut map = ::rustc_hash::FxHashMap::default(); + $( + map.insert($peer, ($start, $end)); + )* + $crate::version::VersionRange::from_map(map) + }}; +} + +impl VersionRange { + pub fn new() -> Self { + Self(Default::default()) + } + + pub fn from_map(map: FxHashMap<PeerID, (Counter, Counter)>) -> Self { + Self(map) + } + + pub fn iter(&self) -> impl Iterator<Item = (&PeerID, &(Counter, Counter))> + '_ { + self.0.iter() + } + + pub fn iter_mut(&mut self) -> impl Iterator<Item = (&PeerID, &mut (Counter, Counter))> + '_ { + self.0.iter_mut() + } + + pub fn clear(&mut self) { + self.0.clear() + } + + pub fn get(&self, peer: &PeerID) -> Option<&(Counter, Counter)> { + self.0.get(peer) + } + + pub fn insert(&mut self, peer: PeerID, start: Counter, end: Counter) { + self.0.insert(peer, (start, end)); + } + + pub fn from_vv(vv: &VersionVector) -> Self { + let mut ans = Self::new(); + for (peer, counter) in vv.iter() { + let counter = normalize_vv_counter(*counter); + if counter > 0 { + ans.insert(*peer, 0, counter); + } + } + ans + } + + pub fn contains_ops_between(&self, vv_a: &VersionVector, vv_b: &VersionVector) -> bool { + for span in vv_a.sub_iter(vv_b) { + if !self.contains_id_span(IdSpan::new( + span.peer, + span.counter.start.saturating_sub(1), + span.counter.end, + )) { + return false; + } + } + + for span in vv_b.sub_iter(vv_a) { + if !self.contains_id_span(IdSpan::new( + span.peer, + span.counter.start.saturating_sub(1), + span.counter.end, + )) { + return false; + } + } + + true + } + + pub fn has_overlap_with(&self, mut span: IdSpan) -> bool { + span.normalize_(); + if let Some((start, end)) = self.get(&span.peer) { + start < &span.counter.end && end > &span.counter.start + } else { + false + } + } + + pub fn contains_id(&self, id: ID) -> bool { + if let Some((start, end)) = self.get(&id.peer) { + start <= &id.counter && end > &id.counter + } else { + false + } + } + + pub fn contains_id_span(&self, mut span: IdSpan) -> bool { + span.normalize_(); + if let Some((start, end)) = self.get(&span.peer) { + start <= &span.counter.start && end >= &span.counter.end + } else { + false + } + } + + pub fn extends_to_include_id_span(&mut self, mut span: IdSpan) { + span.normalize_(); + if let Some((start, end)) = self.0.get_mut(&span.peer) { + *start = (*start).min(span.counter.start); + *end = (*end).max(span.counter.end); + } else { + self.insert(span.peer, span.counter.start, span.counter.end); + } + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub fn inner(&self) -> &FxHashMap<PeerID, (Counter, Counter)> { + &self.0 + } +} + +/// Immutable version vector +/// +/// It has O(1) clone time and O(logN) insert/delete/lookup time. +/// +/// It's more memory efficient than [VersionVector] when the version vector +/// can be created from cloning and modifying other similar version vectors. +#[repr(transparent)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct ImVersionVector(im::HashMap<PeerID, Counter, rustc_hash::FxBuildHasher>); + +#[inline] +fn normalize_vv_counter(counter: Counter) -> Counter { + counter.max(0) +} + +#[inline] +fn last_id_to_vv_end(id: ID) -> Counter { + id.counter.saturating_add(1).max(0) +} + +impl ImVersionVector { + pub fn new() -> Self { + Self(Default::default()) + } + + pub fn clear(&mut self) { + self.0.clear() + } + + pub fn get(&self, key: &PeerID) -> Option<&Counter> { + self.0.get(key) + } + + pub fn get_mut(&mut self, key: &PeerID) -> Option<&mut Counter> { + self.0.get_mut(key) + } + + pub fn insert(&mut self, k: PeerID, v: Counter) { + self.0.insert(k, v); + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub fn iter(&self) -> im::hashmap::Iter<'_, PeerID, Counter> { + self.0.iter() + } + + pub fn remove(&mut self, k: &PeerID) -> Option<Counter> { + self.0.remove(k) + } + + pub fn len(&self) -> usize { + self.0.len() + } + + pub fn contains_key(&self, k: &PeerID) -> bool { + self.0.contains_key(k) + } + + pub fn encode(&self) -> Vec<u8> { + postcard::to_allocvec(self).unwrap() + } + + pub fn decode(bytes: &[u8]) -> Result<Self, LoroError> { + let vv = VersionVector::decode(bytes)?; + Ok(Self::from_vv(&vv)) + } + + pub fn to_vv(&self) -> VersionVector { + VersionVector(self.0.iter().map(|(&k, &v)| (k, v)).collect()) + } + + pub fn from_vv(vv: &VersionVector) -> Self { + ImVersionVector(vv.0.iter().map(|(&k, &v)| (k, v)).collect()) + } + + pub fn extend_to_include_vv<'a>( + &mut self, + vv: impl Iterator<Item = (&'a PeerID, &'a Counter)>, + ) { + for (&client_id, &counter) in vv { + let counter = normalize_vv_counter(counter); + if counter == 0 { + continue; + } + + if let Some(my_counter) = self.0.get_mut(&client_id) { + *my_counter = normalize_vv_counter(*my_counter); + if *my_counter < counter { + *my_counter = counter; + } + } else { + self.0.insert(client_id, counter); + } + } + } + + #[inline] + pub fn merge(&mut self, other: &Self) { + self.extend_to_include_vv(other.0.iter()); + } + + #[inline] + pub fn merge_vv(&mut self, other: &VersionVector) { + self.extend_to_include_vv(other.0.iter()); + } + + #[inline] + pub fn set_last(&mut self, id: ID) { + let end = last_id_to_vv_end(id); + if end == 0 { + self.0.remove(&id.peer); + } else { + self.0.insert(id.peer, end); + } + } + + pub fn extend_to_include_last_id(&mut self, id: ID) { + let end = last_id_to_vv_end(id); + if end == 0 { + return; + } + + if let Some(counter) = self.0.get_mut(&id.peer) { + *counter = normalize_vv_counter(*counter); + if *counter < end { + *counter = end; + } + } else { + self.0.insert(id.peer, end); + } + } + + pub(crate) fn includes_id(&self, x: ID) -> bool { + if self.is_empty() || x.counter < 0 { + return false; + } + + normalize_vv_counter(self.get(&x.peer).copied().unwrap_or(0)) > x.counter + } +} + +impl PartialEq for VersionVector { + fn eq(&self, other: &Self) -> bool { + self.iter().all(|(client, counter)| { + normalize_vv_counter(*other.get(client).unwrap_or(&0)) == normalize_vv_counter(*counter) + }) && other.iter().all(|(client, counter)| { + normalize_vv_counter(*self.get(client).unwrap_or(&0)) == normalize_vv_counter(*counter) + }) + } +} + +impl Eq for VersionVector {} + +impl PartialEq for ImVersionVector { + fn eq(&self, other: &Self) -> bool { + self.0.iter().all(|(client, counter)| { + normalize_vv_counter(*other.0.get(client).unwrap_or(&0)) + == normalize_vv_counter(*counter) + }) && other.0.iter().all(|(client, counter)| { + normalize_vv_counter(*self.0.get(client).unwrap_or(&0)) + == normalize_vv_counter(*counter) + }) + } +} + +impl Eq for ImVersionVector {} + +impl Deref for VersionVector { + type Target = FxHashMap<PeerID, Counter>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +#[derive(Default, Debug, PartialEq, Eq)] +pub struct VersionVectorDiff { + /// The spans that the `left` side needs to retreat to reach the `right` side + /// + /// these spans are included in the left, but not in the right + pub retreat: IdSpanVector, + /// The spans that the `left` side needs to forward to reach the `right` side + /// + /// these spans are included in the right, but not in the left + pub forward: IdSpanVector, +} + +impl VersionVectorDiff { + #[inline] + pub fn merge_left(&mut self, span: IdSpan) { + merge(&mut self.retreat, span); + } + + #[inline] + pub fn merge_right(&mut self, span: IdSpan) { + merge(&mut self.forward, span); + } + + #[inline] + pub fn subtract_start_left(&mut self, span: IdSpan) { + subtract_start(&mut self.retreat, span); + } + + #[inline] + pub fn subtract_start_right(&mut self, span: IdSpan) { + subtract_start(&mut self.forward, span); + } + + pub fn get_id_spans_left(&self) -> impl Iterator<Item = IdSpan> + '_ { + self.retreat.iter().map(|(peer, span)| IdSpan { + peer: *peer, + counter: *span, + }) + } + + pub fn get_id_spans_right(&self) -> impl Iterator<Item = IdSpan> + '_ { + self.forward.iter().map(|(peer, span)| IdSpan { + peer: *peer, + counter: *span, + }) + } +} + +fn subtract_start(m: &mut FxHashMap<PeerID, CounterSpan>, target: IdSpan) { + if let Some(span) = m.get_mut(&target.peer) { + if span.start < target.counter.end { + span.start = target.counter.end; + } + } +} + +fn merge(m: &mut FxHashMap<PeerID, CounterSpan>, mut target: IdSpan) { + target.normalize_(); + if let Some(span) = m.get_mut(&target.peer) { + span.start = span.start.min(target.counter.start); + span.end = span.end.max(target.counter.end); + } else { + m.insert(target.peer, target.counter); + } +} + +impl PartialOrd for VersionVector { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + let mut self_greater = true; + let mut other_greater = true; + let mut eq = true; + for (client_id, other_end) in other.iter() { + let other_end = normalize_vv_counter(*other_end); + if let Some(self_end) = self.get(client_id) { + let self_end = normalize_vv_counter(*self_end); + if self_end < other_end { + self_greater = false; + eq = false; + } + if self_end > other_end { + other_greater = false; + eq = false; + } + } else if other_end > 0 { + self_greater = false; + eq = false; + } + } + + for (client_id, self_end) in self.iter() { + if other.contains_key(client_id) { + continue; + } else if normalize_vv_counter(*self_end) > 0 { + other_greater = false; + eq = false; + } + } + + if eq { + Some(Ordering::Equal) + } else if self_greater { + Some(Ordering::Greater) + } else if other_greater { + Some(Ordering::Less) + } else { + None + } + } +} + +impl PartialOrd for ImVersionVector { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + let mut self_greater = true; + let mut other_greater = true; + let mut eq = true; + for (client_id, other_end) in other.iter() { + let other_end = normalize_vv_counter(*other_end); + if let Some(self_end) = self.get(client_id) { + let self_end = normalize_vv_counter(*self_end); + if self_end < other_end { + self_greater = false; + eq = false; + } + if self_end > other_end { + other_greater = false; + eq = false; + } + } else if other_end > 0 { + self_greater = false; + eq = false; + } + } + + for (client_id, self_end) in self.iter() { + if other.contains_key(client_id) { + continue; + } else if normalize_vv_counter(*self_end) > 0 { + other_greater = false; + eq = false; + } + } + + if eq { + Some(Ordering::Equal) + } else if self_greater { + Some(Ordering::Greater) + } else if other_greater { + Some(Ordering::Less) + } else { + None + } + } +} + +impl DerefMut for VersionVector { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl VersionVector { + pub fn diff(&self, rhs: &Self) -> VersionVectorDiff { + let mut ans: VersionVectorDiff = Default::default(); + for (client_id, &counter) in self.iter() { + let counter = normalize_vv_counter(counter); + if let Some(&rhs_counter) = rhs.get(client_id) { + let rhs_counter = normalize_vv_counter(rhs_counter); + match counter.cmp(&rhs_counter) { + Ordering::Less => { + ans.forward.insert( + *client_id, + CounterSpan { + start: counter, + end: rhs_counter, + }, + ); + } + Ordering::Greater => { + ans.retreat.insert( + *client_id, + CounterSpan { + start: rhs_counter, + end: counter, + }, + ); + } + Ordering::Equal => {} + } + } else if counter > 0 { + ans.retreat.insert( + *client_id, + CounterSpan { + start: 0, + end: counter, + }, + ); + } + } + for (client_id, &rhs_counter) in rhs.iter() { + let rhs_counter = normalize_vv_counter(rhs_counter); + if rhs_counter > 0 && !self.contains_key(client_id) { + ans.forward.insert( + *client_id, + CounterSpan { + start: 0, + end: rhs_counter, + }, + ); + } + } + + ans + } + + /// Returns two iterators that cover the differences between two version vectors. + /// + /// - The first iterator contains the spans that are in `self` but not in `rhs` + /// - The second iterator contains the spans that are in `rhs` but not in `self` + pub fn diff_iter<'a>( + &'a self, + rhs: &'a Self, + ) -> ( + impl Iterator<Item = IdSpan> + 'a, + impl Iterator<Item = IdSpan> + 'a, + ) { + (self.sub_iter(rhs), rhs.sub_iter(self)) + } + + /// Returns the spans that are in `self` but not in `rhs` + pub fn sub_iter<'a>(&'a self, rhs: &'a Self) -> impl Iterator<Item = IdSpan> + 'a { + self.iter().filter_map(move |(peer, &counter)| { + let counter = normalize_vv_counter(counter); + if let Some(&rhs_counter) = rhs.get(peer) { + let rhs_counter = normalize_vv_counter(rhs_counter); + if counter > rhs_counter { + Some(IdSpan { + peer: *peer, + counter: CounterSpan { + start: rhs_counter, + end: counter, + }, + }) + } else { + None + } + } else if counter > 0 { + Some(IdSpan { + peer: *peer, + counter: CounterSpan { + start: 0, + end: counter, + }, + }) + } else { + None + } + }) + } + + /// Returns the spans that are in `self` but not in `rhs` + pub fn sub_iter_im<'a>( + &'a self, + rhs: &'a ImVersionVector, + ) -> impl Iterator<Item = IdSpan> + 'a { + self.iter().filter_map(move |(peer, &counter)| { + let counter = normalize_vv_counter(counter); + if let Some(&rhs_counter) = rhs.get(peer) { + let rhs_counter = normalize_vv_counter(rhs_counter); + if counter > rhs_counter { + Some(IdSpan { + peer: *peer, + counter: CounterSpan { + start: rhs_counter, + end: counter, + }, + }) + } else { + None + } + } else if counter > 0 { + Some(IdSpan { + peer: *peer, + counter: CounterSpan { + start: 0, + end: counter, + }, + }) + } else { + None + } + }) + } + + /// Iter all span from a -> b and b -> a + pub fn iter_between<'a>(&'a self, other: &'a Self) -> impl Iterator<Item = IdSpan> + 'a { + // PERF: can be optimized a little + self.sub_iter(other).chain(other.sub_iter(self)) + } + + pub fn sub_vec(&self, rhs: &Self) -> IdSpanVector { + self.sub_iter(rhs).map(|x| (x.peer, x.counter)).collect() + } + + pub fn distance_between(&self, other: &Self) -> usize { + let mut ans = 0usize; + for (client_id, &counter) in self.iter() { + let counter = counter.max(0) as i64; + if let Some(&other_counter) = other.get(client_id) { + let other_counter = other_counter.max(0) as i64; + ans += counter.abs_diff(other_counter) as usize; + } else { + ans += counter as usize; + } + } + + for (client_id, &counter) in other.iter() { + if !self.contains_key(client_id) { + ans += counter.max(0) as usize; + } + } + + ans + } + + pub fn to_spans(&self) -> IdSpanVector { + self.iter() + .filter_map(|(client_id, &counter)| { + let counter = normalize_vv_counter(counter); + (counter > 0).then_some(( + *client_id, + CounterSpan { + start: 0, + end: counter, + }, + )) + }) + .collect() + } + + #[inline] + pub fn get_frontiers(&self) -> Frontiers { + self.iter() + .filter_map(|(client_id, &counter)| { + if counter > 0 { + Some(ID { + peer: *client_id, + counter: counter - 1, + }) + } else { + None + } + }) + .collect() + } + + #[inline] + pub fn new() -> Self { + Self(Default::default()) + } + + /// set the inclusive ending point. target id will be included by self + #[inline] + pub fn set_last(&mut self, id: ID) { + let end = last_id_to_vv_end(id); + if end == 0 { + self.0.remove(&id.peer); + } else { + self.0.insert(id.peer, end); + } + } + + #[inline] + pub fn get_last(&self, client_id: PeerID) -> Option<Counter> { + self.0.get(&client_id).and_then(|&x| { + let x = normalize_vv_counter(x); + if x == 0 { + None + } else { + Some(x - 1) + } + }) + } + + /// set the exclusive ending point. target id will NOT be included by self + #[inline] + pub fn set_end(&mut self, id: ID) { + if id.counter <= 0 { + self.0.remove(&id.peer); + } else { + self.0.insert(id.peer, id.counter); + } + } + + /// Update the end counter of the given client if the end is greater. + /// Return whether updated + #[inline] + pub fn try_update_last(&mut self, id: ID) -> bool { + let new_end = last_id_to_vv_end(id); + if new_end == 0 { + if self.0.get(&id.peer).is_some_and(|counter| *counter < 0) { + self.0.remove(&id.peer); + } + return false; + } + + if let Some(end) = self.0.get_mut(&id.peer) { + *end = normalize_vv_counter(*end); + if *end < new_end { + *end = new_end; + true + } else { + false + } + } else { + self.0.insert(id.peer, new_end); + true + } + } + + pub fn get_missing_span(&self, target: &Self) -> Vec<IdSpan> { + let mut ans = vec![]; + for (client_id, other_end) in target.iter() { + let other_end = normalize_vv_counter(*other_end); + if other_end == 0 { + continue; + } + + let my_end = self + .get(client_id) + .map(|counter| normalize_vv_counter(*counter)) + .unwrap_or(0); + if my_end < other_end { + ans.push(IdSpan::new(*client_id, my_end, other_end)); + } + } + + ans + } + + pub fn merge(&mut self, other: &Self) { + for (&client_id, &other_end) in other.iter() { + let other_end = normalize_vv_counter(other_end); + if other_end == 0 { + continue; + } + + if let Some(my_end) = self.get_mut(&client_id) { + *my_end = normalize_vv_counter(*my_end); + if *my_end < other_end { + *my_end = other_end; + } + } else { + self.0.insert(client_id, other_end); + } + } + } + + pub fn includes_vv(&self, other: &VersionVector) -> bool { + match self.partial_cmp(other) { + Some(ord) => match ord { + Ordering::Less => false, + Ordering::Equal => true, + Ordering::Greater => true, + }, + None => false, + } + } + + pub fn includes_id(&self, id: ID) -> bool { + if id.counter < 0 { + return false; + } + + if let Some(end) = self.get(&id.peer) { + if normalize_vv_counter(*end) > id.counter { + return true; + } + } + false + } + + pub fn intersect_span(&self, target: IdSpan) -> Option<CounterSpan> { + if let Some(&end) = self.get(&target.peer) { + let end = normalize_vv_counter(end); + let count_start = target.ctr_start().max(0); + let count_end = target.ctr_end().max(0); + if end > count_start && count_end > count_start { + return Some(CounterSpan { + start: count_start, + end: end.min(count_end), + }); + } + } + + None + } + + pub fn extend_to_include_vv<'a>( + &mut self, + vv: impl Iterator<Item = (&'a PeerID, &'a Counter)>, + ) { + for (&client_id, &counter) in vv { + let counter = normalize_vv_counter(counter); + if counter == 0 { + continue; + } + + if let Some(my_counter) = self.get_mut(&client_id) { + *my_counter = normalize_vv_counter(*my_counter); + if *my_counter < counter { + *my_counter = counter; + } + } else { + self.0.insert(client_id, counter); + } + } + } + + pub fn extend_to_include_last_id(&mut self, id: ID) { + let end = last_id_to_vv_end(id); + if end == 0 { + return; + } + + if let Some(counter) = self.get_mut(&id.peer) { + *counter = normalize_vv_counter(*counter); + if *counter < end { + *counter = end; + } + } else { + self.0.insert(id.peer, end); + } + } + + pub fn extend_to_include_end_id(&mut self, id: ID) { + let end = normalize_vv_counter(id.counter); + if end == 0 { + return; + } + + if let Some(counter) = self.get_mut(&id.peer) { + *counter = normalize_vv_counter(*counter); + if *counter < end { + *counter = end; + } + } else { + self.0.insert(id.peer, end); + } + } + + pub fn extend_to_include(&mut self, span: IdSpan) { + let end = normalize_vv_counter(span.counter.norm_end()); + if end == 0 { + if self.0.get(&span.peer).is_some_and(|counter| *counter < 0) { + self.0.remove(&span.peer); + } + return; + } + + if let Some(counter) = self.get_mut(&span.peer) { + *counter = normalize_vv_counter(*counter); + if *counter < end { + *counter = end; + } + } else { + self.insert(span.peer, end); + } + } + + pub fn shrink_to_exclude(&mut self, span: IdSpan) { + let start = normalize_vv_counter(span.counter.min()); + let end = normalize_vv_counter(span.counter.norm_end()); + if end <= start { + return; + } + + if start == 0 { + self.remove(&span.peer); + return; + } + + if let Some(counter) = self.get_mut(&span.peer) { + *counter = normalize_vv_counter(*counter); + if *counter > start { + *counter = start; + } + if *counter == 0 { + self.remove(&span.peer); + } + } + } + + pub fn forward(&mut self, spans: &IdSpanVector) { + for span in spans.iter() { + self.extend_to_include(IdSpan { + peer: *span.0, + counter: *span.1, + }); + } + } + + pub fn retreat(&mut self, spans: &IdSpanVector) { + for span in spans.iter() { + self.shrink_to_exclude(IdSpan { + peer: *span.0, + counter: *span.1, + }); + } + } + + pub fn intersection(&self, other: &VersionVector) -> VersionVector { + let mut ans = VersionVector::new(); + for (client_id, &counter) in self.iter() { + let counter = normalize_vv_counter(counter); + if let Some(&other_counter) = other.get(client_id) { + let other_counter = normalize_vv_counter(other_counter); + if counter < other_counter { + if counter != 0 { + ans.insert(*client_id, counter); + } + } else if other_counter != 0 { + ans.insert(*client_id, other_counter); + } + } + } + ans + } + + /// In-place [`Self::intersection`]: keeps, per peer, the smaller of the + /// two (normalized) counters, dropping peers that end at zero. + pub(crate) fn intersect_with(&mut self, other: &VersionVector) { + self.retain(|peer, counter| { + let other_counter = other + .get(peer) + .copied() + .map(normalize_vv_counter) + .unwrap_or(0); + *counter = normalize_vv_counter(*counter).min(other_counter); + *counter > 0 + }); + } + + #[inline(always)] + pub fn encode(&self) -> Vec<u8> { + postcard::to_allocvec(self).unwrap() + } + + #[inline(always)] + pub fn decode(bytes: &[u8]) -> Result<Self, LoroError> { + postcard::from_bytes(bytes).map_err(|_| LoroError::DecodeVersionVectorError) + } + + pub fn to_im_vv(&self) -> ImVersionVector { + ImVersionVector(self.0.iter().map(|(&k, &v)| (k, v)).collect()) + } + + pub fn from_im_vv(im_vv: &ImVersionVector) -> Self { + VersionVector(im_vv.0.iter().map(|(&k, &v)| (k, v)).collect()) + } +} + +/// Use minimal set of ids to represent the frontiers +#[tracing::instrument(skip(dag))] +pub fn shrink_frontiers(last_ids: &Frontiers, dag: &AppDag) -> Result<Frontiers, ID> { + try_shrink_frontiers(last_ids, dag).map_err(|err| match err { + loro_common::LoroError::FrontiersNotFound(id) => id, + err => panic!("{err}"), + }) +} + +pub(crate) fn try_shrink_frontiers( + last_ids: &Frontiers, + dag: &AppDag, +) -> loro_common::LoroResult<Frontiers> { + // it only keep the ids of ops that are concurrent to each other + + if last_ids.len() <= 1 { + return Ok(last_ids.clone()); + } + + let mut last_ids = { + let ids = filter_duplicated_peer_id(last_ids); + if last_ids.len() == 1 { + let mut frontiers = Frontiers::default(); + frontiers.push(last_ids.as_single().unwrap()); + return Ok(frontiers); + } + + let mut last_ids = Vec::with_capacity(ids.len()); + for id in ids { + let Some(lamport) = dag.try_get_lamport(&id)? else { + return Err(loro_common::LoroError::FrontiersNotFound(id)); + }; + last_ids.push(IdFull::new(id.peer, id.counter, lamport)) + } + + last_ids + }; + + let mut frontiers = Vec::new(); + // Iterate from the greatest lamport to the smallest + last_ids.sort_by_key(|x| x.lamport); + for id in last_ids.iter().rev() { + let mut should_insert = true; + let mut len = 0; + // travel backward because they have more similar lamport + for f_id in frontiers.iter().rev() { + dag.try_travel_ancestors(*f_id, &mut |x| { + len += 1; + if x.contains_id(id.id()) { + should_insert = false; + ControlFlow::Break(()) + } else if x.lamport_last() < id.lamport { + // Already travel to a node with smaller lamport, no need to continue, we are sure two ops are concurrent now + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + })?; + } + + if should_insert { + frontiers.push(id.id()); + } + } + + Ok(frontiers.into()) +} + +fn filter_duplicated_peer_id(last_ids: &Frontiers) -> Vec<ID> { + let mut peer_max_counters = FxHashMap::default(); + for id in last_ids.iter() { + let counter = peer_max_counters.entry(id.peer).or_insert(id.counter); + if id.counter > *counter { + *counter = id.counter; + } + } + + peer_max_counters + .into_iter() + .map(|(peer, counter)| ID::new(peer, counter)) + .collect() +} + +impl Default for VersionVector { + fn default() -> Self { + Self::new() + } +} + +impl From<FxHashMap<PeerID, Counter>> for VersionVector { + fn from(map: FxHashMap<PeerID, Counter>) -> Self { + let mut im_map = FxHashMap::default(); + for (client_id, counter) in map { + im_map.insert(client_id, counter); + } + Self(im_map) + } +} + +impl From<Vec<ID>> for VersionVector { + fn from(vec: Vec<ID>) -> Self { + let mut vv = VersionVector::new(); + for id in vec { + vv.set_last(id); + } + + vv + } +} + +impl FromIterator<ID> for VersionVector { + fn from_iter<T: IntoIterator<Item = ID>>(iter: T) -> Self { + let iter = iter.into_iter(); + let mut vv = VersionVector(FxHashMap::with_capacity_and_hasher( + iter.size_hint().0, + Default::default(), + )); + for id in iter { + vv.set_last(id); + } + + vv + } +} + +impl FromIterator<(PeerID, Counter)> for VersionVector { + fn from_iter<T: IntoIterator<Item = (PeerID, Counter)>>(iter: T) -> Self { + VersionVector(FxHashMap::from_iter(iter)) + } +} + +// Note: It will be encoded into binary format, so the order of its fields should not be changed. + +pub fn are_frontiers_eq(a: &[ID], b: &[ID]) -> bool { + if a.len() != b.len() { + return false; + } + + let mut a: SmallVec<[ID; 10]> = a.into(); + let mut b: SmallVec<[ID; 10]> = b.into(); + + a.sort(); + b.sort(); + + a == b +} + +#[cfg(test)] +mod tests { + #![allow(clippy::neg_cmp_op_on_partial_ord)] + use super::*; + mod cmp { + use super::*; + #[test] + fn test() { + let a: VersionVector = vec![ID::new(1, 1), ID::new(2, 2)].into(); + let b: VersionVector = vec![ID::new(1, 1), ID::new(2, 2)].into(); + assert_eq!(a.partial_cmp(&b), Some(Ordering::Equal)); + assert!(a == b); + + let a: VersionVector = vec![ID::new(1, 2), ID::new(2, 1)].into(); + let b: VersionVector = vec![ID::new(1, 1), ID::new(2, 2)].into(); + assert_eq!(a.partial_cmp(&b), None); + + assert!(!(a > b)); + assert!(!(b > a)); + assert!(!(b == a)); + + let a: VersionVector = vec![ID::new(1, 2), ID::new(2, 3)].into(); + let b: VersionVector = vec![ID::new(1, 1), ID::new(2, 2)].into(); + assert_eq!(a.partial_cmp(&b), Some(Ordering::Greater)); + assert!(a > b); + assert!(a >= b); + + let a: VersionVector = vec![ID::new(1, 0), ID::new(2, 2)].into(); + let b: VersionVector = vec![ID::new(1, 1), ID::new(2, 2)].into(); + assert_eq!(a.partial_cmp(&b), Some(Ordering::Less)); + assert!(a < b); + assert!(a <= b); + } + } + + #[test] + fn im() { + let mut a = VersionVector::new(); + a.set_last(ID::new(1, 1)); + a.set_last(ID::new(2, 1)); + let mut b = a.clone(); + b.merge(&vec![ID::new(1, 2), ID::new(2, 2)].into()); + assert!(a != b); + assert_eq!(a.get(&1), Some(&2)); + assert_eq!(a.get(&2), Some(&2)); + assert_eq!(b.get(&1), Some(&3)); + assert_eq!(b.get(&2), Some(&3)); + } + + #[test] + fn test_encode_decode_im_version_vector() { + let vv = VersionVector::from_iter([(1, 1), (2, 2), (3, 3)]); + let im_vv = vv.to_im_vv(); + let decoded_vv = VersionVector::from_im_vv(&im_vv); + assert_eq!(vv, decoded_vv); + } + + #[test] + fn test_version_vector_encoding_decoding() { + let mut vv = VersionVector::new(); + vv.insert(1, 10); + vv.insert(2, 20); + vv.insert(3, 30); + + // Encode VersionVector + let encoded = vv.encode(); + + // Decode to ImVersionVector + let decoded_im_vv = ImVersionVector::decode(&encoded).unwrap(); + + // Convert VersionVector to ImVersionVector for comparison + let im_vv = vv.to_im_vv(); + + // Compare the original ImVersionVector with the decoded one + assert_eq!(im_vv, decoded_im_vv); + + // Convert back to VersionVector and compare + let decoded_vv = VersionVector::from_im_vv(&decoded_im_vv); + assert_eq!(vv, decoded_vv); + } +} diff --git a/vendor/loro-internal/src/version/frontiers.rs b/vendor/loro-internal/src/version/frontiers.rs new file mode 100644 index 0000000..9c26268 --- /dev/null +++ b/vendor/loro-internal/src/version/frontiers.rs @@ -0,0 +1,574 @@ +use super::*; +use either::Either; + +/// Frontiers representation. +// +// Internal Invariance: +// - Frontiers::Map(map) always have at least 2 elements. +#[derive(Clone, Default)] +pub enum Frontiers { + #[default] + None, + ID(ID), + // We use internal map to avoid the module outside accidentally create or modify the map + // to make it empty or only contain 1 element + Map(InternalMap), +} + +use std::{fmt, sync::Arc}; + +impl fmt::Debug for Frontiers { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("Frontiers") + .field(&FrontiersDebugHelper(self)) + .finish() + } +} + +struct FrontiersDebugHelper<'a>(&'a Frontiers); + +impl fmt::Debug for FrontiersDebugHelper<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut list = f.debug_list(); + match self.0 { + Frontiers::None => {} + Frontiers::ID(id) => { + list.entry(id); + } + Frontiers::Map(map) => { + for id in map.iter() { + list.entry(&id); + } + } + } + list.finish() + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InternalMap(Arc<FxHashMap<PeerID, Counter>>); + +impl InternalMap { + fn new() -> Self { + Self(Arc::new(FxHashMap::default())) + } + + fn len(&self) -> usize { + self.0.len() + } + + fn iter(&self) -> impl Iterator<Item = ID> + '_ { + self.0 + .iter() + .map(|(&peer, &counter)| ID::new(peer, counter)) + } + + fn contains(&self, id: &ID) -> bool { + self.0 + .get(&id.peer) + .is_some_and(|&counter| counter == id.counter) + } + + fn insert(&mut self, id: ID) { + Arc::make_mut(&mut self.0) + .entry(id.peer) + .and_modify(|e| *e = (*e).max(id.counter)) + .or_insert(id.counter); + } + + fn remove(&mut self, id: &ID) -> bool { + let map = Arc::make_mut(&mut self.0); + if let Some(counter) = map.get_mut(&id.peer) { + if *counter == id.counter { + map.remove(&id.peer); + return true; + } + } + false + } + + fn retain<F>(&mut self, mut f: F) + where + F: FnMut(&ID) -> bool, + { + let map = Arc::make_mut(&mut self.0); + map.retain(|&peer, &mut counter| f(&ID::new(peer, counter))); + } +} + +impl Frontiers { + pub fn len(&self) -> usize { + match self { + Frontiers::None => 0, + Frontiers::ID(_) => 1, + Frontiers::Map(map) => map.len(), + } + } + + pub fn iter(&self) -> impl Iterator<Item = ID> + '_ { + match self { + Frontiers::None => Either::Left(Either::Left(std::iter::empty())), + Frontiers::ID(id) => Either::Left(Either::Right(std::iter::once(*id))), + Frontiers::Map(map) => Either::Right(map.iter()), + } + } + + pub fn contains(&self, id: &ID) -> bool { + match self { + Frontiers::None => false, + Frontiers::ID(inner_id) => inner_id == id, + Frontiers::Map(map) => map.contains(id), + } + } + + pub fn push(&mut self, id: ID) { + match self { + Frontiers::None => *self = Frontiers::ID(id), + Frontiers::ID(existing_id) => { + if existing_id.peer != id.peer { + let mut map = InternalMap::new(); + map.insert(*existing_id); + map.insert(id); + *self = Frontiers::Map(map); + } else if existing_id.counter < id.counter { + *existing_id = id; + } + } + Frontiers::Map(map) => map.insert(id), + } + } + + pub fn retain<F>(&mut self, mut f: F) + where + F: FnMut(&ID) -> bool, + { + match self { + Frontiers::None => {} + Frontiers::ID(id) => { + if !f(id) { + *self = Frontiers::None; + } + } + Frontiers::Map(map) => { + map.retain(|id| f(id)); + match map.len() { + 0 => *self = Frontiers::None, + 1 => { + let id = map.iter().next().unwrap(); + *self = Frontiers::ID(id); + } + _ => {} + } + } + } + } + + pub fn remove(&mut self, id: &ID) { + match self { + Frontiers::None => {} + Frontiers::ID(existing_id) => { + if existing_id == id { + *self = Frontiers::None; + } + } + Frontiers::Map(map) => { + if map.remove(id) { + match map.len() { + 0 => *self = Frontiers::None, + 1 => { + let id = map.iter().next().unwrap(); + *self = Frontiers::ID(id); + } + _ => {} + } + } + } + } + } +} + +impl PartialEq for Frontiers { + fn eq(&self, other: &Self) -> bool { + let len = self.len(); + if len != other.len() { + return false; + } + + match (self, other) { + (Frontiers::None, Frontiers::None) => true, + (Frontiers::ID(id1), Frontiers::ID(id2)) => id1 == id2, + (Frontiers::Map(map1), Frontiers::Map(map2)) => map1 == map2, + _ => unreachable!(), + } + } +} + +impl Eq for Frontiers {} + +impl Frontiers { + pub fn new() -> Self { + Self::None + } + + #[inline] + pub fn from_id(id: ID) -> Self { + Self::ID(id) + } + + #[inline] + pub fn encode(&self) -> Vec<u8> { + let mut vec: Vec<ID> = self.iter().collect(); + vec.sort(); + postcard::to_allocvec(&vec).unwrap() + } + + #[inline] + pub fn decode(bytes: &[u8]) -> Result<Self, LoroError> { + let vec: Vec<ID> = postcard::from_bytes(bytes).map_err(|_| { + LoroError::DecodeError("Decode Frontiers error".to_string().into_boxed_str()) + })?; + Ok(Self::from(vec)) + } + + pub fn update_frontiers_on_new_change(&mut self, id: ID, deps: &Frontiers) { + if self.len() <= 8 && self == deps { + *self = Frontiers::from_id(id); + return; + } + + // Remove all IDs in deps from self + for dep in deps.iter() { + self.remove(&dep); + } + + // Add the new ID + self.push(id); + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Returns the single ID if the Frontiers contains exactly one ID, otherwise returns None. + pub fn as_single(&self) -> Option<ID> { + match self { + Frontiers::ID(id) => Some(*id), + _ => None, + } + } + + /// Returns a reference to the internal map if the Frontiers contains multiple IDs, + /// otherwise returns None. + pub fn as_map(&self) -> Option<&InternalMap> { + match self { + Frontiers::Map(map) => Some(map), + _ => None, + } + } + + /// Merges another Frontiers into this one. + /// + /// Id from other will override the id with the same peer from self. + pub fn merge_with_greater(&mut self, other: &Frontiers) { + if self.is_empty() { + *self = other.clone(); + return; + } + + if let Some(id) = self.as_single() { + match other { + Frontiers::None => {} + Frontiers::ID(other_id) => { + if id.peer == other_id.peer { + *self = Frontiers::ID(ID::new(id.peer, id.counter.max(other_id.counter))); + } else { + self.push(*other_id); + } + return; + } + Frontiers::Map(internal_map) => { + let mut map = internal_map.clone(); + Arc::make_mut(&mut map.0) + .entry(id.peer) + .and_modify(|c| *c = (*c).max(id.counter)) + .or_insert(id.counter); + *self = Frontiers::Map(map); + } + } + + return; + } + + let Frontiers::Map(map) = self else { + unreachable!() + }; + let map = Arc::make_mut(&mut map.0); + for id in other.iter() { + map.entry(id.peer) + .and_modify(|c| *c = (*c).max(id.counter)) + .or_insert(id.counter); + } + } + + pub fn to_vec(&self) -> Vec<ID> { + match self { + Frontiers::None => Vec::new(), + Frontiers::ID(id) => vec![*id], + Frontiers::Map(map) => map.iter().collect(), + } + } + + /// Keeps only one element in the Frontiers, deleting all others. + /// If the Frontiers is empty, it remains empty. + /// If it contains multiple elements, it keeps the first one encountered. + pub fn keep_one(&mut self) { + match self { + Frontiers::None => {} + Frontiers::ID(_) => {} + Frontiers::Map(map) => { + if let Some((&peer, &counter)) = map.0.iter().next() { + *self = Frontiers::ID(ID::new(peer, counter)); + } + } + } + } +} +impl From<&[ID]> for Frontiers { + fn from(ids: &[ID]) -> Self { + match ids.len() { + 0 => Frontiers::None, + 1 => Frontiers::ID(ids[0]), + _ => { + let mut map = InternalMap::new(); + for &id in ids { + map.insert(id); + } + Frontiers::Map(map) + } + } + } +} + +impl From<Vec<ID>> for Frontiers { + fn from(ids: Vec<ID>) -> Self { + match ids.len() { + 0 => Frontiers::None, + 1 => Frontiers::ID(ids[0]), + _ => { + let mut map = InternalMap::new(); + for id in ids { + map.insert(id); + } + Frontiers::Map(map) + } + } + } +} + +impl From<ID> for Frontiers { + fn from(value: ID) -> Self { + Self::ID(value) + } +} + +impl FromIterator<ID> for Frontiers { + fn from_iter<I: IntoIterator<Item = ID>>(iter: I) -> Self { + let mut new = Self::new(); + for id in iter { + new.push(id); + } + new + } +} + +impl From<Option<ID>> for Frontiers { + fn from(value: Option<ID>) -> Self { + match value { + Some(id) => Frontiers::ID(id), + None => Frontiers::None, + } + } +} + +impl<const N: usize> From<[ID; N]> for Frontiers { + fn from(value: [ID; N]) -> Self { + match N { + 0 => Frontiers::None, + 1 => Frontiers::ID(value[0]), + _ => { + let mut map = InternalMap::new(); + for id in value { + map.insert(id); + } + Frontiers::Map(map) + } + } + } +} + +impl From<&Vec<ID>> for Frontiers { + fn from(ids: &Vec<ID>) -> Self { + match ids.len() { + 0 => Frontiers::None, + 1 => Frontiers::ID(ids[0]), + _ => { + let mut map = InternalMap::new(); + for id in ids { + map.insert(*id); + } + Frontiers::Map(map) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_frontiers_push_insert_remove() { + let mut frontiers = Frontiers::None; + + // Test push + frontiers.push(ID::new(1, 1)); + assert_eq!(frontiers, Frontiers::ID(ID::new(1, 1))); + + frontiers.push(ID::new(2, 1)); + assert!(matches!(frontiers, Frontiers::Map(_))); + assert_eq!(frontiers.len(), 2); + + frontiers.push(ID::new(1, 2)); + assert_eq!(frontiers.len(), 2); + assert!(frontiers.contains(&ID::new(1, 2))); + assert!(!frontiers.contains(&ID::new(1, 1))); + + // Test insert (via InternalMap) + if let Frontiers::Map(ref mut map) = frontiers { + map.insert(ID::new(3, 1)); + } + assert_eq!(frontiers.len(), 3); + assert!(frontiers.contains(&ID::new(3, 1))); + + // Test remove + frontiers.remove(&ID::new(2, 1)); + assert_eq!(frontiers.len(), 2); + assert!(!frontiers.contains(&ID::new(2, 1))); + + frontiers.remove(&ID::new(1, 2)); + assert_eq!(frontiers, Frontiers::ID(ID::new(3, 1))); + + frontiers.remove(&ID::new(3, 1)); + assert_eq!(frontiers, Frontiers::None); + } + + #[test] + fn test_frontiers_edge_cases() { + let mut frontiers = Frontiers::None; + + // Push to empty + frontiers.push(ID::new(1, 1)); + assert_eq!(frontiers, Frontiers::ID(ID::new(1, 1))); + + // Push same peer, higher counter + frontiers.push(ID::new(1, 2)); + assert_eq!(frontiers, Frontiers::ID(ID::new(1, 2))); + + // Push same peer, lower counter (should not change) + frontiers.push(ID::new(1, 1)); + assert_eq!(frontiers, Frontiers::ID(ID::new(1, 2))); + + // Push different peer + frontiers.push(ID::new(2, 1)); + assert!(matches!(frontiers, Frontiers::Map(_))); + assert_eq!(frontiers.len(), 2); + + // Remove non-existent + frontiers.remove(&ID::new(3, 1)); + assert_eq!(frontiers.len(), 2); + + // Remove until only one left + frontiers.remove(&ID::new(2, 1)); + assert_eq!(frontiers, Frontiers::ID(ID::new(1, 2))); + + // Remove last + frontiers.remove(&ID::new(1, 2)); + assert_eq!(frontiers, Frontiers::None); + } + + #[test] + fn test_frontiers_retain() { + let mut frontiers = Frontiers::None; + + // Test retain on empty frontiers + frontiers.retain(|_| true); + assert_eq!(frontiers, Frontiers::None); + + // Test retain on single ID + frontiers.push(ID::new(1, 1)); + frontiers.retain(|id| id.peer == 1); + assert_eq!(frontiers, Frontiers::ID(ID::new(1, 1))); + + frontiers.retain(|id| id.peer == 2); + assert_eq!(frontiers, Frontiers::None); + + // Test retain on multiple IDs + frontiers.push(ID::new(1, 1)); + frontiers.push(ID::new(2, 2)); + frontiers.push(ID::new(3, 3)); + + // Retain only even peer IDs + frontiers.retain(|id| id.peer % 2 == 0); + assert_eq!(frontiers, Frontiers::ID(ID::new(2, 2))); + + // Add more IDs and test retaining multiple + frontiers.push(ID::new(1, 1)); + frontiers.push(ID::new(3, 3)); + frontiers.push(ID::new(4, 4)); + + frontiers.retain(|id| id.peer > 2); + assert!(matches!(frontiers, Frontiers::Map(_))); + assert_eq!(frontiers.len(), 2); + assert!(frontiers.contains(&ID::new(3, 3))); + assert!(frontiers.contains(&ID::new(4, 4))); + + // Retain none + frontiers.retain(|_| false); + assert_eq!(frontiers, Frontiers::None); + } + + #[test] + fn test_frontiers_encode_decode() { + let mut frontiers = Frontiers::None; + + // Test encode/decode for empty frontiers + let encoded = frontiers.encode(); + let decoded = Frontiers::decode(&encoded).unwrap(); + assert_eq!(frontiers, decoded); + + // Test encode/decode for single ID + frontiers.push(ID::new(1, 100)); + let encoded = frontiers.encode(); + let decoded = Frontiers::decode(&encoded).unwrap(); + assert_eq!(frontiers, decoded); + + // Test encode/decode for multiple IDs + frontiers.push(ID::new(2, 200)); + frontiers.push(ID::new(3, 300)); + let encoded = frontiers.encode(); + let decoded = Frontiers::decode(&encoded).unwrap(); + assert_eq!(frontiers, decoded); + + // Test encode/decode for many IDs + for i in 4..20 { + frontiers.push(ID::new(i, i as Counter * 100)); + } + let encoded = frontiers.encode(); + let decoded = Frontiers::decode(&encoded).unwrap(); + assert_eq!(frontiers, decoded); + + // Test decode with invalid input + assert!(Frontiers::decode(&[0xFF]).is_err()); + assert!(Frontiers::decode(&[]).is_err()); + } +} diff --git a/vendor/loro-internal/tests/autocommit.rs b/vendor/loro-internal/tests/autocommit.rs new file mode 100644 index 0000000..524ed2f --- /dev/null +++ b/vendor/loro-internal/tests/autocommit.rs @@ -0,0 +1,78 @@ +use loro_common::ID; +use loro_internal::{ + cursor::PosType, loro::ExportMode, version::Frontiers, HandlerTrait, LoroDoc, TextHandler, + ToJson, +}; +use serde_json::json; + +#[test] +fn auto_commit() { + let doc_a = LoroDoc::default(); + doc_a.set_peer_id(1).unwrap(); + doc_a.start_auto_commit(); + let text_a = doc_a.get_text("text"); + text_a.insert(0, "hello", PosType::Unicode).unwrap(); + text_a.delete(2, 2, PosType::Unicode).unwrap(); + assert_eq!(&**text_a.get_value().as_string().unwrap(), "heo"); + let bytes = doc_a.export(ExportMode::all_updates()).unwrap(); + + let doc_b = LoroDoc::default(); + doc_b.start_auto_commit(); + doc_b.set_peer_id(2).unwrap(); + let text_b = doc_b.get_text("text"); + text_b.insert(0, "100", PosType::Unicode).unwrap(); + doc_b.import(&bytes).unwrap(); + doc_a + .import(&doc_b.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + assert_eq!(text_a.get_value(), text_b.get_value()); + doc_a.check_state_diff_calc_consistency_slow(); +} + +#[test] +fn auto_commit_list() { + let doc_a = LoroDoc::default(); + doc_a.start_auto_commit(); + let list_a = doc_a.get_list("list"); + list_a.insert(0, "hello").unwrap(); + assert_eq!(list_a.get_value().to_json_value(), json!(["hello"])); + let text_a = list_a + .insert_container(0, TextHandler::new_detached()) + .unwrap(); + let text = text_a; + text.insert(0, "world", PosType::Unicode).unwrap(); + let value = doc_a.get_deep_value(); + assert_eq!(value.to_json_value(), json!({"list": ["world", "hello"]})) +} + +#[ctor::ctor] +fn init() { + dev_utils::setup_test_log(); +} + +#[test] +fn auto_commit_with_checkout() { + let doc = LoroDoc::default(); + doc.set_peer_id(1).unwrap(); + doc.start_auto_commit(); + let map = doc.get_map("a"); + map.insert("0", 0).unwrap(); + map.insert("1", 1).unwrap(); + map.insert("2", 2).unwrap(); + map.insert("3", 3).unwrap(); + doc.checkout(&Frontiers::from(ID::new(1, 0))).unwrap(); + assert_eq!(map.get_value().to_json_value(), json!({"0": 0})); + // assert error if insert after checkout + map.insert("4", 4).unwrap_err(); + doc.checkout_to_latest(); + // assert ok if doc is attached + map.insert("4", 4).unwrap(); + let expected = json!({"0": 0, "1": 1, "2": 2, "3": 3, "4": 4}); + + // should include all changes + let new = LoroDoc::default(); + let a = new.get_map("a"); + new.import(&doc.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + assert_eq!(a.get_value().to_json_value(), expected,); +} diff --git a/vendor/loro-internal/tests/contracts.rs b/vendor/loro-internal/tests/contracts.rs new file mode 100644 index 0000000..7cd6daa --- /dev/null +++ b/vendor/loro-internal/tests/contracts.rs @@ -0,0 +1,14 @@ +#[path = "contracts/event_diff.rs"] +mod event_diff; +#[path = "contracts/handler.rs"] +mod handler; +#[path = "contracts/jsonpath_value.rs"] +mod jsonpath_value; +#[path = "contracts/public_doc.rs"] +mod public_doc; +#[path = "contracts/text_richtext_behavior.rs"] +mod text_richtext_behavior; +#[path = "contracts/text_richtext_handler.rs"] +mod text_richtext_handler; +#[path = "contracts/tree_handler.rs"] +mod tree_handler; diff --git a/vendor/loro-internal/tests/contracts/event_diff.rs b/vendor/loro-internal/tests/contracts/event_diff.rs new file mode 100644 index 0000000..0689821 --- /dev/null +++ b/vendor/loro-internal/tests/contracts/event_diff.rs @@ -0,0 +1,160 @@ +use fractional_index::FractionalIndex; +use loro_delta::{array_vec::ArrayVec, delta_trait::DeltaAttr}; +use loro_internal::{ + delta::{ + DeltaType, Meta, ResolvedMapDelta, ResolvedMapValue, TreeDiff, TreeDiffItem, + TreeExternalDiff, + }, + event::{ + path_to_str, str_to_path, Diff, Index, ListDeltaMeta, ListDiff, ListDiffInsertItem, + TextDiff, TextMeta, + }, + handler::ValueOrHandler, + FxHashMap, IdLp, LoroValue, StringSlice, TreeID, TreeParentId, +}; +use pretty_assertions::assert_eq; + +fn list_values(values: impl IntoIterator<Item = LoroValue>) -> ListDiffInsertItem { + let mut array = ArrayVec::new(); + for value in values { + array.push(ValueOrHandler::Value(value)).unwrap(); + } + array +} + +fn list_insert(values: impl IntoIterator<Item = LoroValue>, from_move: bool) -> ListDiff { + let mut diff = ListDiff::new(); + diff.push_insert(list_values(values), ListDeltaMeta { from_move }); + diff +} + +fn text_insert(value: &str) -> TextDiff { + let mut diff = TextDiff::new(); + diff.push_insert(StringSlice::from(value), TextMeta::default()); + diff +} + +fn map_diff(key: &str, value: Option<LoroValue>, lamport: u32) -> ResolvedMapDelta { + ResolvedMapDelta::new().with_entry( + key.into(), + ResolvedMapValue { + value: value.map(ValueOrHandler::Value), + idlp: IdLp::new(1, lamport), + }, + ) +} + +fn tree_create(target: TreeID, index: usize) -> TreeDiff { + TreeDiff { + diff: vec![TreeDiffItem { + target, + action: TreeExternalDiff::Create { + parent: TreeParentId::Root, + index, + position: FractionalIndex::default(), + }, + }], + } +} + +#[test] +fn event_diff_helpers_compose_transform_and_report_empty_by_kind() { + assert_eq!(format!("{:?}", Index::Seq(7)), "Index::Seq(7)"); + assert_eq!( + format!("{:?}", Index::Node(TreeID::new(3, 9))), + "Index::Node(9@3)" + ); + assert_eq!(Index::from(4).to_string(), "4"); + assert_eq!( + path_to_str(&[Index::Key("root".into()), Index::Seq(2)]), + "root/2" + ); + assert_eq!( + str_to_path("root/2/9@3"), + Some(vec![ + Index::Key("root".into()), + Index::Seq(2), + Index::Node(TreeID::new(3, 9)), + ]) + ); + + let mut attrs = FxHashMap::default(); + attrs.insert("bold".to_string(), LoroValue::Bool(true)); + let text_meta = TextMeta(attrs.clone()); + let roundtrip_attrs: FxHashMap<String, LoroValue> = text_meta.clone().into(); + assert_eq!(roundtrip_attrs, attrs); + assert_eq!(TextMeta::from(attrs), text_meta); + + let mut list_meta = ListDeltaMeta::default(); + assert!(<ListDeltaMeta as Meta>::is_empty(&list_meta)); + <ListDeltaMeta as Meta>::compose( + &mut list_meta, + &ListDeltaMeta { from_move: true }, + (DeltaType::Retain, DeltaType::Retain), + ); + assert!(list_meta.from_move); + assert!(<ListDeltaMeta as Meta>::is_mergeable( + &list_meta, + &ListDeltaMeta { from_move: true } + )); + <ListDeltaMeta as Meta>::merge(&mut list_meta, &ListDeltaMeta { from_move: true }); + + let mut delta_attr = ListDeltaMeta::default(); + assert!(DeltaAttr::attr_is_empty(&delta_attr)); + DeltaAttr::compose(&mut delta_attr, &ListDeltaMeta { from_move: true }); + assert!(delta_attr.from_move); + assert!(!DeltaAttr::attr_is_empty(&delta_attr)); + + let mut list = Diff::List(list_insert([LoroValue::I64(1)], false)); + list.compose_ref(&Diff::List(list_insert([LoroValue::I64(2)], true))); + assert!(!list.is_empty()); + let list_composed = Diff::List(list_insert([LoroValue::I64(3)], false)) + .compose(Diff::List(list_insert([LoroValue::I64(4)], false))) + .expect("same diff kinds should compose"); + assert!(!list_composed.is_empty()); + + let mut text = Diff::Text(text_insert("a")); + text.compose_ref(&Diff::Text(text_insert("b"))); + assert!(!text.is_empty()); + let text_composed = Diff::Text(text_insert("c")) + .compose(Diff::Text(text_insert("d"))) + .expect("text diffs should compose"); + assert!(!text_composed.is_empty()); + + let map_a = Diff::Map(map_diff("title", Some("old".into()), 1)); + let map_b = Diff::Map(map_diff("title", Some("new".into()), 2)); + let mut map_composed = map_a + .clone() + .compose(map_b.clone()) + .expect("map diffs should compose"); + assert!(!map_composed.is_empty()); + map_composed.transform(&map_b, false); + assert!(map_composed.is_empty()); + + let target = TreeID::new(1, 2); + let tree_a = Diff::Tree(tree_create(target, 0)); + let tree_b = Diff::Tree(tree_create(target, 1)); + let mut tree_composed = tree_a + .clone() + .compose(tree_b.clone()) + .expect("tree diffs should compose"); + assert!(!tree_composed.is_empty()); + tree_composed.transform(&tree_b, false); + assert!(tree_composed.is_empty()); + + assert!(Diff::Unknown.is_empty()); + let wrong_kind = Diff::Text(text_insert("x")).compose(Diff::List(list_insert([], false))); + assert!(matches!(wrong_kind, Err(Diff::Text(_)))); + + #[cfg(feature = "counter")] + { + let counter = Diff::Counter(1.0) + .compose(Diff::Counter(2.0)) + .expect("counter diffs should compose"); + assert!(matches!(counter, Diff::Counter(3.0))); + let mut transformed = Diff::Counter(1.0); + transformed.transform(&Diff::Counter(2.0), false); + assert!(matches!(transformed, Diff::Counter(1.0))); + assert!(Diff::Counter(0.0).is_empty()); + } +} diff --git a/vendor/loro-internal/tests/contracts/handler.rs b/vendor/loro-internal/tests/contracts/handler.rs new file mode 100644 index 0000000..bbd882b --- /dev/null +++ b/vendor/loro-internal/tests/contracts/handler.rs @@ -0,0 +1,179 @@ +use loro_internal::{ + handler::{Handler, ListHandler, MapHandler, MovableListHandler, TextHandler, TreeHandler}, + HandlerTrait, LoroDoc, ToJson, TreeID, TreeParentId, +}; +use pretty_assertions::assert_eq; +use serde_json::json; + +#[test] +fn detached_handlers_expose_local_values_ids_and_clear_contracts() -> loro_internal::LoroResult<()> +{ + let map = MapHandler::new_detached(); + map.insert("title", "draft")?; + let text = map.insert_container("body", TextHandler::new_detached())?; + text.insert_unicode(0, "hello")?; + + let list = ListHandler::new_detached(); + list.insert(0, "a")?; + list.insert_container(1, MapHandler::new_detached())? + .insert("kind", "nested")?; + + let movable = MovableListHandler::new_detached(); + movable.insert(0, "first")?; + movable.insert(1, "second")?; + movable.mov(1, 0)?; + + let tree = TreeHandler::new_detached(); + let root = tree.create(TreeParentId::Root)?; + tree.get_meta(root)?.insert("name", "root")?; + + assert_eq!(format!("{map:?}"), "MapHandler Detached"); + assert_eq!(format!("{list:?}"), "ListHandler Detached"); + assert_eq!( + format!("{movable:?}"), + format!("MovableListHandler {}", movable.id()) + ); + assert_eq!(format!("{text:?}"), "TextHandler(Unattached)"); + assert_eq!(format!("{tree:?}"), "TreeHandler Detached"); + + assert!(!map.is_attached()); + assert!(!list.is_attached()); + assert!(!movable.is_attached()); + assert!(!text.is_attached()); + assert!(!tree.is_attached()); + assert!(map.attached_handler().is_none()); + assert!(list.attached_handler().is_none()); + assert!(movable.attached_handler().is_none()); + assert!(text.attached_handler().is_none()); + assert!(tree.attached_handler().is_none()); + assert!(map.doc().is_none()); + assert!(list.doc().is_none()); + assert!(movable.doc().is_none()); + assert!(text.doc().is_none()); + assert!(tree.doc().is_none()); + assert!(map.parent().is_none()); + assert!(list.parent().is_none()); + assert!(movable.parent().is_none()); + assert!(text.parent().is_none()); + assert!(tree.parent().is_none()); + + assert_eq!( + map.get_deep_value().to_json_value(), + json!({"body": "hello", "title": "draft"}) + ); + assert_eq!( + list.get_deep_value().to_json_value(), + json!(["a", {"kind": "nested"}]) + ); + assert_eq!( + movable.get_deep_value().to_json_value(), + json!(["second", "first"]) + ); + assert_eq!(text.get_deep_value().to_json_value(), json!("hello")); + assert_eq!( + tree.get_deep_value().to_json_value()[0]["meta"], + json!({"name": "root"}) + ); + + for handler in [ + Handler::Map(map.clone()), + Handler::List(list.clone()), + Handler::MovableList(movable.clone()), + Handler::Text(text.clone()), + Handler::Tree(tree.clone()), + ] { + assert!(!handler.is_attached()); + assert!(handler.attached_handler().is_none()); + assert!(handler.doc().is_none()); + assert!(handler.get_attached().is_none()); + assert_eq!(handler.id().container_type(), handler.kind()); + assert_eq!(handler.c_type(), handler.kind()); + assert_eq!(handler.to_handler().kind(), handler.kind()); + assert!(!handler.get_value().is_null()); + } + + Handler::Text(text).clear()?; + Handler::List(list).clear()?; + Handler::MovableList(movable).clear()?; + Handler::Tree(tree).clear()?; + Handler::Map(map).clear()?; + + Ok(()) +} + +#[test] +fn attached_handlers_report_parent_types_and_roundtrip_through_handler_enum( +) -> loro_internal::LoroResult<()> { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(66)?; + + let root = doc.get_map("root"); + root.insert("title", "draft")?; + let text = root.insert_container("text", TextHandler::new_detached())?; + text.insert_unicode(0, "hello")?; + + let list = root.insert_container("list", ListHandler::new_detached())?; + let map_under_list = list.insert_container(0, MapHandler::new_detached())?; + map_under_list.insert("kind", "list-child")?; + + let movable = root.insert_container("movable", MovableListHandler::new_detached())?; + let text_under_movable = movable.insert_container(0, TextHandler::new_detached())?; + text_under_movable.insert_unicode(0, "move-child")?; + + let tree = root.insert_container("tree", TreeHandler::new_detached())?; + let node = tree.create(TreeParentId::Root)?; + let meta = tree.get_meta(node)?; + meta.insert("kind", "tree-meta")?; + + doc.commit_then_renew(); + + assert!(matches!(text.parent(), Some(Handler::Map(_)))); + assert!(matches!(list.parent(), Some(Handler::Map(_)))); + assert!(matches!(map_under_list.parent(), Some(Handler::List(_)))); + assert!(matches!( + text_under_movable.parent(), + Some(Handler::MovableList(_)) + )); + assert!(matches!(tree.parent(), Some(Handler::Map(_)))); + assert!(matches!(meta.parent(), Some(Handler::Tree(_)))); + + assert!(<TextHandler as HandlerTrait>::from_handler(text.to_handler()).is_some()); + assert!(<MapHandler as HandlerTrait>::from_handler(map_under_list.to_handler()).is_some()); + assert!(<ListHandler as HandlerTrait>::from_handler(list.to_handler()).is_some()); + assert!(<MovableListHandler as HandlerTrait>::from_handler(movable.to_handler()).is_some()); + assert!(<TreeHandler as HandlerTrait>::from_handler(tree.to_handler()).is_some()); + assert!(<TreeHandler as HandlerTrait>::from_handler(root.to_handler()).is_none()); + + for handler in [ + root.to_handler(), + text.to_handler(), + list.to_handler(), + map_under_list.to_handler(), + movable.to_handler(), + text_under_movable.to_handler(), + tree.to_handler(), + meta.to_handler(), + ] { + assert!(handler.is_attached()); + assert!(handler.attached_handler().is_some()); + assert!(handler.doc().is_some()); + assert!(handler.get_attached().is_some()); + assert_eq!(handler.to_handler().id(), handler.id()); + assert_eq!(handler.c_type(), handler.kind()); + assert!(!handler.get_value().is_null()); + assert!(!handler.get_deep_value().is_null()); + } + + Handler::Text(text).clear()?; + Handler::List(list).clear()?; + Handler::MovableList(movable).clear()?; + Handler::Tree(tree).clear()?; + Handler::Map(root).clear()?; + assert_eq!(doc.get_deep_value().to_json_value(), json!({"root": {}})); + + assert!(doc + .get_handler(TreeID::new(123, 0).associated_meta_container()) + .is_none()); + + Ok(()) +} diff --git a/vendor/loro-internal/tests/contracts/jsonpath_value.rs b/vendor/loro-internal/tests/contracts/jsonpath_value.rs new file mode 100644 index 0000000..438dacc --- /dev/null +++ b/vendor/loro-internal/tests/contracts/jsonpath_value.rs @@ -0,0 +1,172 @@ +#![cfg(feature = "jsonpath")] + +use loro_internal::{ + handler::ValueOrHandler, jsonpath::jsonpath_impl::evaluate_jsonpath, loro_value, HandlerTrait, + LoroValue, ToJson, +}; +use pretty_assertions::assert_eq; +use serde_json::{json, Value}; +use std::error::Error; + +fn query_json(root: &LoroValue, path: &str) -> Result<Value, Box<dyn Error>> { + Ok(Value::Array( + evaluate_jsonpath(root, path)? + .into_iter() + .map(|value| match value { + ValueOrHandler::Value(value) => value.to_json_value(), + ValueOrHandler::Handler(handler) => handler.get_deep_value().to_json_value(), + }) + .collect(), + )) +} + +fn root_value() -> LoroValue { + loro_value!({ + "store": { + "books": [ + { + "title": "1984", + "author": "George Orwell", + "price": 10, + "rating": 4.5, + "available": true, + "tags": ["classic", "dystopia"], + "meta": {"pages": 328, "edition": "paperback"}, + "note": null, + "zero": 0, + "empty": "", + "empty_list": [], + "empty_map": {} + }, + { + "title": "Animal Farm", + "author": "George Orwell", + "price": 6, + "rating": 4.0, + "available": true, + "tags": ["classic"], + "meta": {"pages": 112}, + "note": "satire", + "zero": 0, + "empty": "", + "empty_list": [], + "empty_map": {} + }, + { + "title": "Brave New World", + "author": "Aldous Huxley", + "price": 12, + "rating": 4.2, + "available": false, + "tags": [], + "meta": {}, + "note": null, + "zero": 0, + "empty": "", + "empty_list": [], + "empty_map": {} + } + ], + "featured_authors": ["George Orwell"], + "min_price": 9, + "empty": "", + "truth": true, + "nothing": null + }, + "numbers": [0, 1, 2, 3] + }) +} + +#[test] +fn jsonpath_evaluates_raw_loro_values_with_comparisons_and_truthiness() -> Result<(), Box<dyn Error>> +{ + let root = root_value(); + + assert_eq!(query_json(&root, "$")?, json!([root.to_json_value()])); + assert_eq!( + query_json(&root, "$.store.books[-1].title")?, + json!(["Brave New World"]) + ); + assert_eq!(query_json(&root, "$.store.books[-99]")?, json!([])); + + assert_eq!( + query_json(&root, "$.store.books[?(@.price != 10)].title")?, + json!(["Animal Farm", "Brave New World"]) + ); + assert_eq!( + query_json( + &root, + "$.store.books[?(@.price <= $.store.min_price)].title" + )?, + json!(["Animal Farm"]) + ); + assert_eq!( + query_json(&root, "$.store.books[?(@.price > 10)].title")?, + json!(["Brave New World"]) + ); + assert_eq!( + query_json(&root, "$.store.books[?(@.rating == 4.5)].title")?, + json!(["1984"]) + ); + assert_eq!( + query_json(&root, "$.store.books[?(@.rating >= 4.2)].title")?, + json!(["1984", "Brave New World"]) + ); + assert_eq!( + query_json( + &root, + "$.store.books[?(@.title >= 'Brave New World')].title" + )?, + json!(["Brave New World"]) + ); + assert_eq!( + query_json(&root, "$.store.books[?(@.title < 'Brave New World')].title")?, + json!(["1984", "Animal Farm"]) + ); + assert_eq!( + query_json(&root, "$.store.books[?(@.available != false)].title")?, + json!(["1984", "Animal Farm"]) + ); + assert_eq!( + query_json( + &root, + "$.store.books[?(@.author in $.store.featured_authors)].title" + )?, + json!(["1984", "Animal Farm"]) + ); + assert_eq!( + query_json(&root, "$.store.books[?(@.author in 'George Orwell')].title")?, + json!([]) + ); + + assert_eq!( + query_json(&root, "$.store.books[?(count(@.title) == 1)].title")?, + json!(["1984", "Animal Farm", "Brave New World"]) + ); + assert!(evaluate_jsonpath(&root, "$.store.books[?(count(1) == 0)].title").is_err()); + assert_eq!( + query_json(&root, "$.store.books[?(length(value(@.tags)) > 0)].title")?, + json!(["1984", "Animal Farm"]) + ); + assert_eq!( + query_json(&root, "$.store.books[?(length(value(@.meta)) >= 2)].title")?, + json!(["1984"]) + ); + assert_eq!( + query_json(&root, "$.store.books[?(length(value(@.price)) == 0)].title")?, + json!(["1984", "Animal Farm", "Brave New World"]) + ); + assert_eq!( + query_json(&root, "$.store.books[?(value(@.tags[*]) == null)].title")?, + json!(["1984", "Brave New World"]) + ); + + assert!(evaluate_jsonpath(&root, "$.store.books[?(value(@.title))].title").is_err()); + assert_eq!( + query_json(&root, "$.store.books[?(@.missing)].title")?, + json!([]) + ); + assert_eq!(query_json(&root, "$.numbers[?(@ >= 2)]")?, json!([2, 3])); + + Ok(()) +} diff --git a/vendor/loro-internal/tests/contracts/public_doc.rs b/vendor/loro-internal/tests/contracts/public_doc.rs new file mode 100644 index 0000000..856a2c2 --- /dev/null +++ b/vendor/loro-internal/tests/contracts/public_doc.rs @@ -0,0 +1,243 @@ +use std::sync::{Arc, Mutex}; + +use loro_common::{ContainerID, ContainerType, LoroResult, TreeID, ID}; +use loro_internal::{ + cursor::Side, + event::{path_to_str, str_to_path, EventTriggerKind, Index}, + handler::{Handler, ListHandler, MapHandler, MovableListHandler, TextHandler, ValueOrHandler}, + loro::ExportMode, + version::VersionVector, + HandlerTrait, LoroDoc, ToJson, TreeParentId, +}; +use pretty_assertions::assert_eq; +use serde_json::{json, Value}; + +fn deep_json(doc: &LoroDoc) -> Value { + doc.get_deep_value().to_json_value() +} + +fn value_or_handler_deep_json(value: ValueOrHandler) -> Value { + match value { + ValueOrHandler::Value(value) => value.to_json_value(), + ValueOrHandler::Handler(handler) => handler.get_deep_value().to_json_value(), + } +} + +#[test] +fn internal_doc_introspection_uses_the_same_container_path_contracts() -> LoroResult<()> { + let pristine = LoroDoc::new(); + assert!(pristine.can_reset_with_snapshot()); + + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(901)?; + + let root = doc.get_map("root"); + root.insert("title", "draft")?; + + let body = root.insert_container("body", TextHandler::new_detached())?; + body.insert_unicode(0, "hello")?; + + let list = root.insert_container("items", ListHandler::new_detached())?; + list.insert(0, "one")?; + let nested_map = list.insert_container(1, MapHandler::new_detached())?; + nested_map.insert("kind", "nested")?; + + let movable = root.insert_container("order", MovableListHandler::new_detached())?; + movable.insert(0, "first")?; + movable.insert(1, "second")?; + movable.mov(1, 0)?; + + let tree = doc.get_tree("tree"); + tree.enable_fractional_index(0); + let root_node = tree.create(TreeParentId::Root)?; + tree.get_meta(root_node)?.insert("label", "root")?; + + let uncommitted = doc + .get_uncommitted_ops_as_json() + .expect("pending local ops should be visible before commit"); + assert!(!uncommitted.changes.is_empty()); + + doc.commit_then_renew(); + assert!(doc.get_uncommitted_ops_as_json().is_none()); + assert!(!doc.can_reset_with_snapshot()); + + let value_with_ids = doc.app_state().lock().get_deep_value_with_id(); + let value_with_ids_json = value_with_ids.to_json_value(); + assert_eq!( + value_with_ids_json["root"]["value"]["title"], + json!("draft") + ); + assert!(value_with_ids_json["root"]["cid"] + .as_str() + .expect("cid should be a string") + .contains("cid:")); + + let flat = doc.app_state().lock().get_all_container_value_flat(); + let flat_json = flat.to_json_value(); + assert_eq!(flat_json[body.id().to_string()], json!("hello")); + assert_eq!( + flat_json[nested_map.id().to_string()], + json!({"kind": "nested"}) + ); + + let body_path = doc + .get_path_to_container(&body.id()) + .expect("body should have a root path"); + let indexes = body_path + .iter() + .map(|(_, index)| index.clone()) + .collect::<Vec<_>>(); + assert_eq!(path_to_str(&indexes), "root/body"); + assert_eq!(str_to_path("root/body"), Some(indexes.clone())); + assert_eq!( + value_or_handler_deep_json(doc.get_by_path(&indexes).expect("body path should resolve")), + json!("hello") + ); + assert!(doc + .get_path_to_container(&ContainerID::new_normal( + ID::new(777, 0), + ContainerType::Text + )) + .is_none()); + + assert_eq!(EventTriggerKind::Local.to_string(), "local"); + assert_eq!(EventTriggerKind::Import.to_string(), "import"); + assert_eq!(EventTriggerKind::Checkout.to_string(), "checkout"); + assert!(EventTriggerKind::Local.is_local()); + assert!(EventTriggerKind::Import.is_import()); + assert!(EventTriggerKind::Checkout.is_checkout()); + + assert_eq!(Index::try_from("").unwrap(), Index::Key("".into())); + assert_eq!(Index::try_from("12").unwrap(), Index::Seq(12)); + assert_eq!(Index::try_from("12x").unwrap(), Index::Key("12x".into())); + assert_eq!(Index::Node(TreeID::new(5, 7)).to_string(), "5@7"); + assert_eq!( + format!("{:?}", Index::Key("plain".into())), + "Index::Key(\"plain\")" + ); + assert_eq!( + str_to_path("root/1/5@7"), + Some(vec![ + Index::Key("root".into()), + Index::Seq(1), + Index::Node(TreeID::new(7, 5)), + ]) + ); + + let fork = doc.fork(); + assert_eq!(deep_json(&fork), deep_json(&doc)); + doc.detach(); + let detached_fork = doc.fork(); + assert_eq!(deep_json(&detached_fork), deep_json(&doc)); + doc.attach(); + + let text_cursor = body + .get_cursor(0, Side::Middle) + .expect("text cursor should be created"); + assert_eq!( + doc.query_pos(&text_cursor) + .expect("cursor should resolve") + .current + .pos, + 0 + ); + + Ok(()) +} + +#[test] +fn import_diff_apply_and_checkout_events_follow_doc_contracts() -> LoroResult<()> { + let source = LoroDoc::new_auto_commit(); + source.set_peer_id(902)?; + + let source_events = Arc::new(Mutex::new(Vec::<(EventTriggerKind, String, usize)>::new())); + let source_events_ref = Arc::clone(&source_events); + let _source_sub = source.subscribe_root(Arc::new(move |event| { + source_events_ref.lock().unwrap().push(( + event.event_meta.by, + event.event_meta.origin.to_string(), + event.events.len(), + )); + })); + + let text = source.get_text("text"); + text.insert_unicode(0, "a")?; + source.set_next_commit_origin("seed"); + source.commit_then_renew(); + let v1 = source.state_frontiers(); + + text.insert_unicode(1, "b")?; + let list = source.get_list("list"); + list.insert(0, "item")?; + let nested = list.insert_container(1, TextHandler::new_detached())?; + nested.insert_unicode(0, "nested")?; + source.set_next_commit_origin("second"); + source.commit_then_renew(); + let v2 = source.state_frontiers(); + + source.checkout(&v1)?; + assert_eq!(deep_json(&source), json!({"text": "a", "list": []})); + source.checkout_to_latest(); + assert_eq!( + deep_json(&source), + json!({"text": "ab", "list": ["item", "nested"]}) + ); + + let observed = source_events.lock().unwrap().clone(); + assert!(observed + .iter() + .any(|(kind, origin, _)| kind.is_local() && origin == "seed")); + assert!(observed + .iter() + .any(|(kind, origin, _)| kind.is_local() && origin == "second")); + assert!(observed.iter().any(|(kind, _, _)| kind.is_checkout())); + + let at_v1 = source.fork_at(&v1)?; + assert_eq!(deep_json(&at_v1), json!({"text": "a", "list": []})); + let diff = source.diff(&v1, &v2)?; + at_v1.apply_diff(diff)?; + assert_eq!( + deep_json(&at_v1), + json!({"text": "ab", "list": ["item", "nested"]}) + ); + + let reverse = source.diff(&v2, &v1)?; + at_v1.apply_diff(reverse)?; + assert_eq!(deep_json(&at_v1), json!({"text": "a", "list": []})); + + let snapshot = source.export(ExportMode::Snapshot)?; + let imported = LoroDoc::new_auto_commit(); + let import_events = Arc::new(Mutex::new(Vec::<(EventTriggerKind, String)>::new())); + let import_events_ref = Arc::clone(&import_events); + let _import_sub = imported.subscribe_root(Arc::new(move |event| { + import_events_ref + .lock() + .unwrap() + .push((event.event_meta.by, event.event_meta.origin.to_string())); + })); + imported.import_with(&snapshot, "sync".into())?; + assert_eq!(deep_json(&imported), deep_json(&source)); + assert_eq!( + import_events.lock().unwrap().as_slice(), + &[(EventTriggerKind::Import, "sync".to_string())] + ); + + let batch_target = LoroDoc::new_auto_commit(); + let first_vv = source + .frontiers_to_vv(&v1) + .expect("v1 should be in the source oplog"); + let first_updates = source.export(ExportMode::updates(&VersionVector::default()))?; + let second_updates = source.export(ExportMode::updates(&first_vv))?; + let status = batch_target.import_batch(&[second_updates, first_updates])?; + assert!(status.pending.is_none()); + assert_eq!(deep_json(&batch_target), deep_json(&source)); + + let handler = imported + .get_handler(text.id()) + .expect("text handler should exist"); + assert!(matches!(handler, Handler::Text(_))); + assert!(matches!(handler.to_handler(), Handler::Text(_))); + assert_eq!(handler.kind(), ContainerType::Text); + + Ok(()) +} diff --git a/vendor/loro-internal/tests/contracts/text_richtext_behavior.rs b/vendor/loro-internal/tests/contracts/text_richtext_behavior.rs new file mode 100644 index 0000000..b1415d4 --- /dev/null +++ b/vendor/loro-internal/tests/contracts/text_richtext_behavior.rs @@ -0,0 +1,213 @@ +use loro_common::{LoroError, LoroValue}; +use loro_internal::{ + cursor::PosType, + handler::{TextDelta, TextHandler, UpdateOptions}, + HandlerTrait, LoroDoc, ToJson, +}; +use pretty_assertions::assert_eq; +use rustc_hash::FxHashMap; +use serde_json::json; + +fn attrs( + pairs: impl IntoIterator<Item = (&'static str, LoroValue)>, +) -> FxHashMap<String, LoroValue> { + pairs + .into_iter() + .map(|(key, value)| (key.to_string(), value)) + .collect() +} + +#[test] +fn attached_text_versions_styles_and_coordinate_errors_follow_contract( +) -> loro_internal::LoroResult<()> { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(78)?; + let text = doc.get_text("text"); + + let initial_version = text.version_id().expect("attached text has a version id"); + text.insert_unicode(0, "A😀文")?; + assert_ne!(text.version_id(), Some(initial_version)); + assert_eq!(text.to_string(), "A😀文"); + + assert!(matches!( + text.insert_utf16(2, "x"), + Err(LoroError::UTF16InUnicodeCodePoint { pos: 2 }) + )); + assert!(matches!( + text.insert_utf8(2, "x"), + Err(LoroError::UTF8InUnicodeCodePoint { pos: 2 }) + )); + assert_eq!(text.to_string(), "A😀文"); + assert_eq!( + text.convert_pos(2, PosType::Unicode, PosType::Utf16), + Some(3) + ); + assert_eq!( + text.convert_pos(5, PosType::Bytes, PosType::Unicode), + Some(2) + ); + assert_eq!(text.convert_pos(1, PosType::Unicode, PosType::Entity), None); + assert_eq!( + text.convert_pos(100, PosType::Unicode, PosType::Bytes), + None + ); + + let before_missing_unmark = text.version_id(); + text.unmark(0, 1, "bold", PosType::Unicode)?; + assert_eq!(text.version_id(), before_missing_unmark); + + text.mark(1, 3, "bold", true.into(), PosType::Unicode)?; + let after_mark = text.version_id(); + text.mark(1, 3, "bold", true.into(), PosType::Unicode)?; + assert_eq!(text.version_id(), after_mark); + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([ + { "insert": "A" }, + { "insert": "😀文", "attributes": { "bold": true } } + ]) + ); + assert_eq!( + text.slice_delta(0, text.len_unicode(), PosType::Unicode)?, + vec![ + TextDelta::Insert { + insert: "A".to_string(), + attributes: None, + }, + TextDelta::Insert { + insert: "😀文".to_string(), + attributes: Some(attrs([("bold", true.into())])), + }, + ] + ); + + text.unmark(2, 3, "bold", PosType::Unicode)?; + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([ + { "insert": "A" }, + { "insert": "😀", "attributes": { "bold": true } }, + { "insert": "文" } + ]) + ); + + text.check(); + text.diagnose(); + Ok(()) +} + +#[test] +fn apply_delta_and_update_keep_text_and_attribute_contracts() -> loro_internal::LoroResult<()> { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(79)?; + let text = doc.get_text("patch"); + + text.apply_delta(&[TextDelta::Insert { + insert: "hello".to_string(), + attributes: Some(attrs([("bold", true.into())])), + }])?; + assert_eq!( + text.get_delta(), + vec![TextDelta::Insert { + insert: "hello".to_string(), + attributes: Some(attrs([("bold", true.into())])), + }] + ); + + text.apply_delta(&[ + TextDelta::Retain { + retain: 2, + attributes: Some(attrs([("italic", true.into())])), + }, + TextDelta::Delete { delete: 2 }, + TextDelta::Insert { + insert: "Y".to_string(), + attributes: None, + }, + ])?; + assert_eq!(text.to_string(), "heYo"); + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([ + { "insert": "he", "attributes": { "bold": true, "italic": true } }, + { "insert": "Y" }, + { "insert": "o", "attributes": { "bold": true } } + ]) + ); + + text.update("plain\nnew\ntext", UpdateOptions::default()) + .expect("character update should finish without timeout"); + assert_eq!(text.to_string(), "plain\nnew\ntext"); + text.update_by_line("plain\nline\ntext\n", UpdateOptions::default()) + .expect("line update should finish without timeout"); + assert_eq!(text.to_string(), "plain\nline\ntext\n"); + + Ok(()) +} + +#[test] +fn detached_text_richtext_state_survives_attach() -> loro_internal::LoroResult<()> { + let detached = TextHandler::new_detached(); + assert_eq!(detached.version_id(), None); + assert!(detached.is_empty()); + assert!(detached.apply_delta(&[]).is_err()); + + detached.insert_unicode(0, "abc文")?; + detached.mark(1, 3, "bold", true.into(), PosType::Unicode)?; + detached.mark(1, 3, "bold", true.into(), PosType::Unicode)?; + detached.unmark(0, 1, "bold", PosType::Unicode)?; + assert!(matches!( + detached.char_at(99, PosType::Unicode), + Err(LoroError::OutOfBound { .. }) + )); + assert!(matches!( + detached.slice(3, 2, PosType::Unicode), + Err(LoroError::EndIndexLessThanStartIndex { .. }) + )); + assert!(detached + .mark(2, 2, "bold", true.into(), PosType::Unicode) + .is_err()); + assert_eq!(detached.slice(0, 0, PosType::Unicode)?, ""); + + let expected_delta = vec![ + TextDelta::Insert { + insert: "a".to_string(), + attributes: None, + }, + TextDelta::Insert { + insert: "bc".to_string(), + attributes: Some(attrs([("bold", true.into())])), + }, + TextDelta::Insert { + insert: "文".to_string(), + attributes: None, + }, + ]; + assert_eq!(detached.get_delta(), expected_delta); + + let mut first_chunk = String::new(); + detached.iter(|chunk| { + first_chunk.push_str(chunk); + false + }); + assert_eq!(first_chunk, "a"); + detached.check(); + detached.diagnose(); + + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(80)?; + let root = doc.get_map("root"); + let attached = root.insert_container("body", detached.clone())?; + let attached_from_detached = detached + .get_attached() + .expect("detached text should resolve to attached handler after insertion"); + assert_eq!(attached.id(), attached_from_detached.id()); + assert!(attached.version_id().is_some()); + assert_eq!(attached.get_delta(), expected_delta); + assert_eq!( + root.get_deep_value().to_json_value(), + json!({ "body": "abc文" }) + ); + + Ok(()) +} diff --git a/vendor/loro-internal/tests/contracts/text_richtext_handler.rs b/vendor/loro-internal/tests/contracts/text_richtext_handler.rs new file mode 100644 index 0000000..4e7be2b --- /dev/null +++ b/vendor/loro-internal/tests/contracts/text_richtext_handler.rs @@ -0,0 +1,266 @@ +use loro_internal::{ + cursor::{PosType, Side}, + handler::Handler, + handler::TextDelta, + ContainerType, HandlerTrait, LoroDoc, LoroResult, TextHandler, ToJson, +}; +use pretty_assertions::assert_eq; +use serde_json::json; + +fn richtext_json(text: &TextHandler) -> serde_json::Value { + text.get_richtext_value().to_json_value() +} + +#[test] +fn detached_text_handler_contract_covers_local_branch() -> LoroResult<()> { + let text = TextHandler::new_detached(); + + assert!(!text.is_attached()); + assert!(text.doc().is_none()); + assert!(text.version_id().is_none()); + assert!(text.get_attached().is_none()); + assert!(text.is_empty()); + assert_eq!(format!("{:?}", text), "TextHandler(Unattached)"); + + text.insert_utf8(0, "a😀文b")?; + text.mark(1, 3, "bold", true.into(), PosType::Unicode)?; + + assert_eq!(text.len_utf8(), 9); + assert_eq!(text.len_unicode(), 4); + assert_eq!(text.len_utf16(), 5); + let event_len = if cfg!(feature = "wasm") { 5 } else { 4 }; + assert_eq!(text.len_event(), event_len); + assert_eq!(text.char_at(1, PosType::Unicode)?, '😀'); + assert_eq!(text.slice(1, 3, PosType::Unicode)?, "😀文"); + assert_eq!(text.slice_utf16(1, 4)?, "😀文"); + assert_eq!( + text.convert_pos(2, PosType::Unicode, PosType::Bytes), + Some(5) + ); + assert_eq!( + text.convert_pos(5, PosType::Bytes, PosType::Unicode), + Some(2) + ); + assert_eq!( + text.convert_pos(1, PosType::Unicode, PosType::Utf16), + Some(1) + ); + assert!(text.char_at(99, PosType::Unicode).is_err()); + assert!(text.slice(3, 2, PosType::Unicode).is_err()); + + let mut seen = Vec::new(); + text.iter(|chunk| { + seen.push(chunk.to_owned()); + false + }); + assert_eq!(seen, vec!["a".to_string()]); + + assert_eq!( + richtext_json(&text), + json!([ + {"insert": "a"}, + {"insert": "😀文", "attributes": {"bold": true}}, + {"insert": "b"} + ]) + ); + assert_eq!( + text.slice_delta(0, text.len_unicode(), PosType::Unicode)?, + vec![ + TextDelta::Insert { + insert: "a".to_string(), + attributes: None, + }, + TextDelta::Insert { + insert: "😀文".to_string(), + attributes: Some([("bold".to_string(), true.into())].into_iter().collect()), + }, + TextDelta::Insert { + insert: "b".to_string(), + attributes: None, + }, + ] + ); + + let handler = text.to_handler(); + assert_eq!(handler.c_type(), ContainerType::Text); + assert!(!handler.is_attached()); + assert!(handler.attached_handler().is_none()); + assert!(handler.doc().is_none()); + assert_eq!(handler.get_value().to_json_value(), json!("a😀文b")); + assert_eq!(handler.get_deep_value().to_json_value(), json!("a😀文b")); + assert!(<TextHandler as HandlerTrait>::from_handler(handler.clone()).is_some()); + assert!(<Handler as HandlerTrait>::from_handler(handler).is_some()); + + text.diagnose(); + + let plain = TextHandler::new_detached(); + plain.insert_utf8(0, "clear me")?; + plain.clear()?; + assert_eq!(plain.len_unicode(), 0); + assert_eq!(plain.len_utf8(), 0); + assert_eq!(richtext_json(&plain), json!([])); + + Ok(()) +} + +#[test] +fn attached_text_handler_contract_covers_document_branch_and_handler_enum() -> LoroResult<()> { + let doc = LoroDoc::new_auto_commit(); + let root = doc.get_map("root"); + + let detached = TextHandler::new_detached(); + detached.insert_utf8(0, "abcd")?; + detached.mark(1, 3, "bold", true.into(), PosType::Unicode)?; + + let attached = root.insert_container("body", detached.clone())?; + + assert!(!detached.is_attached()); + assert!(detached.doc().is_none()); + assert!(detached.get_attached().is_some()); + assert!(attached.is_attached()); + assert!(attached.doc().is_some()); + assert!(attached.version_id().is_some()); + assert_eq!(attached.len_utf8(), 4); + assert_eq!(attached.len_unicode(), 4); + assert_eq!(attached.len_utf16(), 4); + assert_eq!(attached.char_at(1, PosType::Unicode)?, 'b'); + assert_eq!(attached.slice(1, 3, PosType::Unicode)?, "bc"); + assert_eq!(attached.slice_utf16(1, 3)?, "bc"); + assert_eq!( + attached.convert_pos(2, PosType::Unicode, PosType::Bytes), + Some(2) + ); + assert_eq!( + attached.convert_pos(2, PosType::Bytes, PosType::Unicode), + Some(2) + ); + + let mut seen = Vec::new(); + attached.iter(|chunk| { + seen.push(chunk.to_owned()); + false + }); + assert_eq!(seen, vec!["a".to_string()]); + + assert_eq!( + attached.slice_delta(0, attached.len_unicode(), PosType::Unicode)?, + vec![ + TextDelta::Insert { + insert: "a".to_string(), + attributes: None, + }, + TextDelta::Insert { + insert: "bc".to_string(), + attributes: Some([("bold".to_string(), true.into())].into_iter().collect()), + }, + TextDelta::Insert { + insert: "d".to_string(), + attributes: None, + }, + ] + ); + assert_eq!( + attached.get_richtext_value().to_json_value(), + json!([ + {"insert": "a"}, + {"insert": "bc", "attributes": {"bold": true}}, + {"insert": "d"} + ]) + ); + assert_eq!( + root.get_deep_value().to_json_value(), + json!({"body": "abcd"}) + ); + + let handler = attached.to_handler(); + assert_eq!(handler.kind(), ContainerType::Text); + assert!(handler.is_attached()); + assert!(handler.attached_handler().is_some()); + assert!(handler.doc().is_some()); + assert_eq!(handler.get_value().to_json_value(), json!("abcd")); + assert_eq!(handler.get_deep_value().to_json_value(), json!("abcd")); + assert!(<TextHandler as HandlerTrait>::from_handler(handler.clone()).is_some()); + assert!(<Handler as HandlerTrait>::from_handler(handler.clone()).is_some()); + + let before = attached.version_id(); + attached.insert_utf8(attached.len_utf8(), "!")?; + attached.delete_utf16(1, 2)?; + assert_ne!(attached.version_id(), before); + assert_eq!( + attached.slice(0, attached.len_unicode(), PosType::Unicode)?, + "ad!" + ); + assert_eq!( + root.get_deep_value().to_json_value(), + json!({"body": "ad!"}) + ); + + handler.clear()?; + assert_eq!(attached.len_unicode(), 0); + assert_eq!(attached.len_utf8(), 0); + assert!(attached.version_id().is_some()); + let cursor = attached + .get_cursor(0, Side::Middle) + .expect("empty attached text"); + assert_eq!(cursor.id, None); + assert_eq!(cursor.side, Side::Left); + assert_eq!(attached.char_at(0, PosType::Unicode).is_err(), true); + assert_eq!(attached.get_richtext_value().to_json_value(), json!([])); + + attached.diagnose(); + assert!(attached.char_at(0, PosType::Unicode).is_err()); + assert!(attached.slice(1, 0, PosType::Unicode).is_err()); + + Ok(()) +} + +#[test] +fn text_handler_position_edge_cases_cover_unsupported_and_empty_ranges() -> LoroResult<()> { + let text = TextHandler::new_detached(); + text.insert_utf8(0, "ab")?; + + assert_eq!( + text.get_delta(), + vec![TextDelta::Insert { + insert: "ab".to_string(), + attributes: None, + }] + ); + assert_eq!( + text.convert_pos(0, PosType::Unicode, PosType::Unicode), + Some(0) + ); + assert_eq!(text.convert_pos(0, PosType::Entity, PosType::Unicode), None); + assert_eq!(text.convert_pos(0, PosType::Unicode, PosType::Entity), None); + assert_eq!(text.convert_pos(10, PosType::Unicode, PosType::Bytes), None); + assert_eq!(text.slice(1, 1, PosType::Unicode)?, ""); + assert_eq!(text.slice_utf16(1, 1)?, ""); + + let doc = LoroDoc::new_auto_commit(); + let root = doc.get_map("root"); + let attached = root.insert_container("body", text.clone())?; + + assert!(attached.is_attached()); + assert_eq!( + attached.get_delta(), + vec![TextDelta::Insert { + insert: "ab".to_string(), + attributes: None, + }] + ); + assert_eq!( + attached.convert_pos(0, PosType::Entity, PosType::Unicode), + None + ); + assert_eq!( + attached.convert_pos(attached.len_unicode(), PosType::Unicode, PosType::Unicode), + Some(attached.len_unicode()) + ); + assert_eq!( + attached.convert_pos(attached.len_unicode() + 1, PosType::Unicode, PosType::Bytes), + None + ); + assert_eq!(attached.slice(0, 0, PosType::Unicode)?, ""); + + Ok(()) +} diff --git a/vendor/loro-internal/tests/contracts/tree_handler.rs b/vendor/loro-internal/tests/contracts/tree_handler.rs new file mode 100644 index 0000000..5c36314 --- /dev/null +++ b/vendor/loro-internal/tests/contracts/tree_handler.rs @@ -0,0 +1,119 @@ +use loro_common::{LoroResult, PeerID}; +use loro_internal::{handler::TreeHandler, LoroDoc, ToJson, TreeID, TreeParentId}; +use pretty_assertions::assert_eq; +use serde_json::{json, Value}; + +fn deep_json(doc: &LoroDoc) -> Value { + doc.get_deep_value().to_json_value() +} + +#[test] +fn detached_tree_handler_queries_and_clear_follow_contracts() -> LoroResult<()> { + let tree = TreeHandler::new_detached(); + assert_eq!(format!("{tree:?}"), "TreeHandler Detached"); + assert!(tree.is_fractional_index_enabled()); + tree.enable_fractional_index(2); + tree.disable_fractional_index(); + assert!(!tree.is_deleted()); + assert!(tree.is_empty()); + assert_eq!(tree.__internal__next_tree_id(), TreeID::new(PeerID::MAX, 0)); + + let root = tree.create(TreeParentId::Root)?; + let first = tree.create_at(root.into(), 0)?; + let second = tree.create_at(root.into(), 1)?; + let third = tree.create_at(root.into(), 2)?; + + assert_eq!(tree.__internal__next_tree_id(), TreeID::new(PeerID::MAX, 4)); + assert_eq!(tree.get_child_at(&TreeParentId::Root, 0), Some(root)); + assert_eq!(tree.get_child_at(&root.into(), 0), Some(first)); + assert_eq!(tree.get_child_at(&root.into(), 1), Some(second)); + assert_eq!(tree.get_child_at(&root.into(), 2), Some(third)); + assert_eq!(tree.get_child_at(&root.into(), 3), None); + assert_eq!(tree.get_index_by_tree_id(&second), Some(1)); + assert!(tree.get_position_by_tree_id(&second).is_some()); + assert!(tree + .get_position_by_tree_id(&TreeID::new(PeerID::MAX, 99)) + .is_none()); + assert!(tree.is_parent(&second, &root.into())); + assert_eq!(tree.get_nodes_under(TreeParentId::Root).len(), 4); + assert_eq!(tree.get_nodes_under(root.into()).len(), 3); + assert_eq!(tree.nodes().len(), 4); + + tree.mov_before(third, first)?; + assert_eq!( + tree.children(&root.into()), + Some(vec![third, first, second]) + ); + tree.mov_after(third, second)?; + assert_eq!( + tree.children(&root.into()), + Some(vec![first, second, third]) + ); + tree.move_to(third, TreeParentId::Root, 0)?; + assert_eq!(tree.children(&TreeParentId::Root), Some(vec![third, root])); + + tree.delete(third)?; + assert!(!tree.contains(third)); + assert_eq!(tree.get_node_parent(&third), None); + + tree.clear()?; + assert!(tree.is_empty()); + assert_eq!(tree.roots(), Vec::<TreeID>::new()); + assert_eq!(tree.nodes(), Vec::<TreeID>::new()); + + Ok(()) +} + +#[test] +fn attached_tree_hierarchy_positions_and_diff_apply_follow_contracts() -> LoroResult<()> { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(77)?; + let tree = doc.get_tree("outline"); + tree.enable_fractional_index(2); + + let root = tree.create(TreeParentId::Root)?; + let first = tree.create_at(root.into(), 0)?; + let second = tree.create_at(root.into(), 1)?; + tree.get_meta(root)?.insert("name", "root")?; + tree.get_meta(first)?.insert("name", "first")?; + tree.get_meta(second)?.insert("name", "second")?; + + assert!(format!("{tree:?}").contains("TreeHandler")); + assert_eq!(tree.get_child_at(&TreeParentId::Root, 0), Some(root)); + assert_eq!(tree.get_child_at(&root.into(), 0), Some(first)); + assert_eq!(tree.get_child_at(&root.into(), 1), Some(second)); + assert_eq!(tree.get_index_by_tree_id(&second), Some(1)); + assert!(tree.get_position_by_tree_id(&second).is_some()); + assert!(tree.get_last_move_id(&root).is_some()); + + let hierarchy = tree.get_all_hierarchy_nodes_under(TreeParentId::Root); + assert_eq!(hierarchy.len(), 1); + assert_eq!(hierarchy[0].id, root); + assert_eq!(hierarchy[0].children.len(), 2); + assert_eq!(hierarchy[0].children[0].id, first); + assert_eq!(hierarchy[0].children[1].id, second); + + doc.commit_then_renew(); + let v1 = doc.state_frontiers(); + let before = deep_json(&doc); + + tree.move_to(second, TreeParentId::Root, 0)?; + tree.delete(first)?; + tree.get_meta(second)?.insert("status", "promoted")?; + doc.commit_then_renew(); + let v2 = doc.state_frontiers(); + let after = deep_json(&doc); + assert_ne!(before, after); + + let fork = doc.fork_at(&v1)?; + assert_eq!(deep_json(&fork), before); + fork.apply_diff(doc.diff(&v1, &v2)?)?; + assert_eq!(deep_json(&fork), after); + + tree.clear()?; + doc.commit_then_renew(); + assert!(tree.is_empty()); + assert_eq!(deep_json(&doc), json!({"outline": []})); + + Ok(()) +} diff --git a/vendor/loro-internal/tests/ephemeral_store.rs b/vendor/loro-internal/tests/ephemeral_store.rs new file mode 100644 index 0000000..f991ad8 --- /dev/null +++ b/vendor/loro-internal/tests/ephemeral_store.rs @@ -0,0 +1,94 @@ +use loro_internal::awareness::EphemeralStore; +use loro_internal::LoroValue; +use serde::Serialize; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +#[derive(Serialize)] +struct WireState { + key: String, + value: Option<LoroValue>, + timestamp: i64, +} + +fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() as i64 +} + +#[test] +fn import_skips_entries_past_timeout() { + let store = EphemeralStore::new(100); + let stale_timestamp = now_ms() - 500; + + let payload = postcard::to_allocvec(&vec![WireState { + key: "stale".into(), + value: Some(LoroValue::from(1)), + timestamp: stale_timestamp, + }]) + .unwrap(); + + store.apply(&payload).unwrap(); + + assert!(store.get("stale").is_none()); + assert!(store.get_all_states().is_empty()); +} + +#[test] +fn import_preserves_remote_timestamp_for_timeout() { + let timeout_ms = 100; + let store = EphemeralStore::new(timeout_ms); + let remote_timestamp = now_ms() - (timeout_ms - 20); + + let payload = postcard::to_allocvec(&vec![WireState { + key: "cursor".into(), + value: Some(LoroValue::from("v")), + timestamp: remote_timestamp, + }]) + .unwrap(); + + store.apply(&payload).unwrap(); + assert_eq!(store.get("cursor"), Some(LoroValue::from("v"))); + + std::thread::sleep(Duration::from_millis(40)); + store.remove_outdated(); + + assert!(store.get("cursor").is_none()); + assert!(store.get_all_states().is_empty()); +} + +#[test] +fn import_rejects_too_deep_loro_value() { + let mut payload = vec![0x01u8, 0x00, 0x01]; + for _ in 0..600 { + payload.push(0x05); + payload.push(0x01); + } + payload.extend_from_slice(&[0x00, 0x00]); + + let store = EphemeralStore::new(30_000); + let err = store.apply(&payload).unwrap_err(); + + assert!(err.contains("Failed to decode data")); +} + +#[test] +fn import_accepts_loro_value_at_depth_511() { + let mut value = LoroValue::Null; + for _ in 0..511 { + value = LoroValue::List(vec![value].into()); + } + + let payload = postcard::to_allocvec(&vec![WireState { + key: "deep".into(), + value: Some(value), + timestamp: now_ms(), + }]) + .unwrap(); + + let store = EphemeralStore::new(30_000); + + assert!(store.apply(&payload).is_ok()); + assert!(store.get("deep").is_some()); +} diff --git a/vendor/loro-internal/tests/fugue.rs b/vendor/loro-internal/tests/fugue.rs new file mode 100644 index 0000000..661a744 --- /dev/null +++ b/vendor/loro-internal/tests/fugue.rs @@ -0,0 +1,90 @@ +use loro_common::LoroResult; +use loro_internal::{LoroDoc, ToJson}; +use serde_json::json; + +#[test] +fn test_forward_interleaving() -> LoroResult<()> { + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(0)?; + a.get_text("text").insert_unicode(0, "Hello")?; + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(1)?; + b.get_text("text").insert_unicode(0, " World!")?; + a.merge(&b)?; + assert_eq!( + a.get_deep_value().to_json_value(), + json!({"text": "Hello World!"}) + ); + Ok(()) +} + +#[test] +fn test_backward_interleaving() -> LoroResult<()> { + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(0)?; + a.get_text("text").insert_unicode(0, "o")?; + a.get_text("text").insert_unicode(0, "l")?; + a.get_text("text").insert_unicode(0, "l")?; + a.get_text("text").insert_unicode(0, "e")?; + a.get_text("text").insert_unicode(0, "H")?; + dbg!(a.get_deep_value()); + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(1)?; + b.get_text("text").insert_unicode(0, "!")?; + b.get_text("text").insert_unicode(0, "d")?; + b.get_text("text").insert_unicode(0, "l")?; + b.get_text("text").insert_unicode(0, "r")?; + b.get_text("text").insert_unicode(0, "o")?; + b.get_text("text").insert_unicode(0, "W")?; + b.get_text("text").insert_unicode(0, " ")?; + dbg!(b.get_deep_value()); + a.merge(&b)?; + assert_eq!( + a.get_deep_value().to_json_value(), + json!({"text": "Hello World!"}) + ); + Ok(()) +} + +#[test] +fn test_forward_backward() -> LoroResult<()> { + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(0)?; + a.get_text("text").insert_unicode(0, "ll")?; + a.get_text("text").insert_unicode(0, "He")?; + a.get_text("text").insert_unicode(4, "o")?; + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(1)?; + b.get_text("text").insert_unicode(0, " !")?; + b.get_text("text").insert_unicode(1, "W")?; + b.get_text("text").insert_unicode(2, "d")?; + b.get_text("text").insert_unicode(2, "l")?; + b.get_text("text").insert_unicode(2, "r")?; + b.get_text("text").insert_unicode(2, "o")?; + a.merge(&b)?; + assert_eq!( + a.get_deep_value().to_json_value(), + json!({"text": "Hello World!"}) + ); + + Ok(()) +} + +#[test] +fn test_yjs_interleave() -> LoroResult<()> { + // As stated in the Fugue paper, Yjs has a interleaving anomaly in the following case: + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(0)?; + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(1)?; + let c = LoroDoc::new_auto_commit(); + c.set_peer_id(2)?; + c.get_text("text").insert_unicode(0, "2")?; + a.merge(&c)?; + a.get_text("text").insert_unicode(0, "1")?; + // b should not be between a and c + b.get_text("text").insert_unicode(0, "b")?; + a.merge(&b)?; + assert_eq!(a.get_deep_value().to_json_value(), json!({"text": "b12"})); + Ok(()) +} diff --git a/vendor/loro-internal/tests/handle_walk_memory.rs b/vendor/loro-internal/tests/handle_walk_memory.rs new file mode 100644 index 0000000..c283ee2 --- /dev/null +++ b/vendor/loro-internal/tests/handle_walk_memory.rs @@ -0,0 +1,141 @@ +//! Regression test for loro#1092: a container-by-container handle walk must +//! retain bounded memory. The decoded-value cache in `InnerStore` is capped +//! (2048 by default), so retained memory after a walk is +//! O(cache bound), not O(containers ever read). +//! +//! Run: cargo test -p loro-internal --test handle_walk_memory -- --nocapture + +use dev_utils::get_mem_usage; +use loro_internal::cursor::PosType; +use loro_internal::handler::{Handler, ValueOrHandler}; +use loro_internal::LoroDoc; + +fn live_bytes() -> usize { + get_mem_usage().0 +} + +const MIB: usize = 1 << 20; + +const TEXT: &str = "The quick brown fox jumps over the lazy dog. \ +The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog."; + +fn build_snapshot(turns: usize, items_per_turn: usize) -> Vec<u8> { + let doc = LoroDoc::new_auto_commit(); + let history = doc.get_list("history"); + for t in 0..turns { + let turn = history + .push_container(loro_internal::handler::MapHandler::new_detached()) + .unwrap(); + turn.insert("id", format!("turn-{t}").as_str()).unwrap(); + turn.insert("role", if t % 2 == 0 { "user" } else { "assistant" }) + .unwrap(); + let items = turn + .insert_container("items", loro_internal::handler::ListHandler::new_detached()) + .unwrap(); + let count = if t % 2 == 0 { 1 } else { items_per_turn }; + for i in 0..count { + let item = items + .push_container(loro_internal::handler::MapHandler::new_detached()) + .unwrap(); + if i % 4 == 3 { + item.insert("type", "text").unwrap(); + let text = item + .insert_container("text", loro_internal::handler::TextHandler::new_detached()) + .unwrap(); + text.insert(0, &format!("{TEXT} turn {t} item {i}"), PosType::Unicode) + .unwrap(); + } else { + item.insert("type", "tool_call").unwrap(); + item.insert("toolCallId", format!("tc-{t}-{i}").as_str()) + .unwrap(); + let raw = item + .insert_container( + "rawInput", + loro_internal::handler::MapHandler::new_detached(), + ) + .unwrap(); + raw.insert("command", "pnpm test").unwrap(); + raw.insert("cwd", "/repo").unwrap(); + let text = item + .insert_container("title", loro_internal::handler::TextHandler::new_detached()) + .unwrap(); + text.insert(0, TEXT, PosType::Unicode).unwrap(); + } + } + } + doc.export(loro_internal::encoding::ExportMode::snapshot()) + .unwrap() +} + +/// The loro-mirror-style traversal: keys()/get() per map, get(i) per list, +/// to_string() per text. +fn walk(h: &Handler, handles: &mut usize) { + *handles += 1; + match h { + Handler::Map(m) => { + let keys: Vec<_> = m.keys().collect(); + for k in keys { + if let Some(ValueOrHandler::Handler(child)) = m.get_(&k) { + walk(&child, handles); + } + } + } + Handler::List(l) => { + for i in 0..l.len() { + if let Some(ValueOrHandler::Handler(child)) = l.get_(i) { + walk(&child, handles); + } + } + } + Handler::Text(t) => { + let _ = t.to_string(); + } + _ => {} + } +} + +#[test] +fn handle_walk_retains_bounded_memory() { + let snapshot = build_snapshot(95, 100); // ≈ 63k containers + let doc = LoroDoc::new_auto_commit(); + doc.import(&snapshot).unwrap(); + let history = Handler::List(doc.get_list("history")); + + // Every walk must visit all 13,260 containers (48 even turns × 5 + // containers + 47 odd turns × 277 containers + the root list): a walk that + // silently visits fewer containers would pass the memory thresholds below + // more easily. + let expected_containers = 48 * 5 + 47 * 277 + 1; + + let after_import = live_bytes(); + let mut handles = 0; + walk(&history, &mut handles); + assert_eq!(handles, expected_containers, "first walk is incomplete"); + let after_walk1 = live_bytes(); + handles = 0; + walk(&history, &mut handles); + assert_eq!(handles, expected_containers, "second walk is incomplete"); + let after_walk2 = live_bytes(); + + let walk1_retained = after_walk1.saturating_sub(after_import); + let walk2_growth = after_walk2.saturating_sub(after_walk1); + println!( + "handles={handles} retained after walk#1: {:.1} MiB, walk#2 growth: {:.1} MiB", + walk1_retained as f64 / MIB as f64, + walk2_growth as f64 / MIB as f64, + ); + + // Unbounded, this walk pinned ~1 KB per container (~60 MB at this size). + // The bounded cache (2048 entries) must retain far less than that. + assert!( + walk1_retained < 16 * MIB, + "walk retained {:.1} MiB; the decoded-value cache is not bounded", + walk1_retained as f64 / MIB as f64 + ); + // Re-walking hits the same bounded cache: no further growth. + assert!( + walk2_growth < 4 * MIB, + "second walk grew memory by {:.1} MiB; cached values must be reused or re-decoded, not accumulated", + walk2_growth as f64 / MIB as f64 + ); +} diff --git a/vendor/loro-internal/tests/mergeable_cid_encoding.rs b/vendor/loro-internal/tests/mergeable_cid_encoding.rs new file mode 100644 index 0000000..4dd4d71 --- /dev/null +++ b/vendor/loro-internal/tests/mergeable_cid_encoding.rs @@ -0,0 +1,314 @@ +//! Encoding and decoding of mergeable container ids. + +#[test] +#[cfg(feature = "counter")] +fn mergeable_container_id_roundtrips_parent_key_and_type() { + use loro_internal::ContainerType; + + let parent = loro_common::ContainerID::new_root("state", ContainerType::Map); + let key = "field\u{1}with/slash:and:semicolon"; + let cid = loro_common::ContainerID::new_mergeable(&parent, key, ContainerType::Counter); + + assert!(cid.is_mergeable()); + let (decoded_parent, decoded_key, decoded_type) = cid.parse_mergeable().unwrap(); + assert_eq!(decoded_parent, parent); + assert_eq!(decoded_key, key); + assert_eq!(decoded_type, ContainerType::Counter); +} + +#[test] +fn user_root_names_cannot_use_mergeable_namespace() { + assert!(!loro_common::check_root_container_name( + loro_common::MERGEABLE_NAMESPACE_PREFIX + )); +} + +/// `parse_mergeable` is a pure decoder and must return `None` (not panic, not +/// silently misinterpret) for every malformed payload. This guards against +/// future drift in the encoder + decoder pair. +/// +/// The cid does NOT encode the container kind in its name — kind already lives in +/// `ContainerID::Root::container_type`. Distinct kinds at the same `(parent, key)` therefore share +/// the same name string but compare unequal at the `ContainerID` level, which is what callers see. +#[test] +#[cfg(feature = "counter")] +fn parse_mergeable_rejects_malformed_payloads() { + use loro_common::{ContainerID, ContainerType}; + + // Non-mergeable root: returns None. + let plain_root = ContainerID::new_root("ordinary", ContainerType::Map); + assert!(plain_root.parse_mergeable().is_none()); + + // Mergeable prefix but missing the required key segment. + let no_key = ContainerID::Root { + name: "🤝:$state".into(), + container_type: ContainerType::Counter, + }; + assert!( + no_key.parse_mergeable().is_none(), + "payload without a key segment must reject" + ); + + // Mergeable prefix, but empty payload. + let truncated = ContainerID::Root { + name: "🤝:".into(), + container_type: ContainerType::Counter, + }; + assert!( + truncated.parse_mergeable().is_none(), + "empty payload must reject" + ); + + // Unknown escapes, raw slash, and dangling backslash must reject. + let malformed = ContainerID::Root { + name: "🤝:$state>bad\\xescape".into(), + container_type: ContainerType::Counter, + }; + assert!( + malformed.parse_mergeable().is_none(), + "unknown escape in payload must reject" + ); + + let raw_slash = ContainerID::Root { + name: "🤝:$state>raw/slash".into(), + container_type: ContainerType::Counter, + }; + assert!(raw_slash.parse_mergeable().is_none()); + + let dangling = ContainerID::Root { + name: "🤝:$state>dangling\\".into(), + container_type: ContainerType::Counter, + }; + assert!(dangling.parse_mergeable().is_none()); + + for name in ["🤝:$root\\sname>key", "🤝:$root\\0name>key"] { + let invalid_root_name = ContainerID::Root { + name: name.into(), + container_type: ContainerType::Counter, + }; + assert!( + invalid_root_name.parse_mergeable().is_none(), + "root base parent must reject decoded slash/NUL: {name:?}" + ); + } + + for name in [ + "🤝:@Z:0>key", + "🤝:@001:0>key", + "🤝:@1:00>key", + "🤝:@1:-0>key", + ] { + let non_canonical = ContainerID::Root { + name: name.into(), + container_type: ContainerType::Counter, + }; + assert!( + non_canonical.parse_mergeable().is_none(), + "non-canonical base36 payload must reject: {name:?}" + ); + } +} + +/// `LoroDoc::get_map` must reject names in the mergeable namespace at the +/// call site, not just in `check_root_container_name`. Otherwise user code +/// could fabricate a Root cid that masquerades as a mergeable child and +/// confuse the parent-edge walks. +/// +/// This test runs `check_root_container_name` directly on a variety of +/// user-supplied strings; the runtime `get_map` / `get_text` / etc. calls +/// route through this validator (see callers in `crates/loro-internal/src/`). +/// If the validator is bypassed by a runtime path, that's a separate bug — +/// but it's not something this test can prove without intentionally writing +/// `🤝:` keys, which is what we're trying to prevent in the first place. +#[test] +fn root_name_validator_rejects_mergeable_namespace_inputs() { + use loro_common::{check_root_container_name, MERGEABLE_NAMESPACE_PREFIX}; + + // Bare prefix. + assert!(!check_root_container_name(MERGEABLE_NAMESPACE_PREFIX)); + // Prefix + arbitrary payload. + assert!(!check_root_container_name("🤝:deadbeef")); + assert!(!check_root_container_name("🤝:")); + // Prefix-as-substring is OK (not a prefix), validator still allows it. + assert!(check_root_container_name("foo🤝:bar")); + // Prefix with a leading zero-width space is NOT a prefix match, allowed. + assert!(check_root_container_name("\u{200B}🤝:abc")); + // Sanity: ordinary user names still pass. + assert!(check_root_container_name("state")); + assert!(check_root_container_name("ordinary-name_with-symbols")); + // Empty is still rejected (pre-existing behavior). + assert!(!check_root_container_name("")); + // Slash and NUL still rejected (pre-existing behavior). + assert!(!check_root_container_name("a/b")); + assert!(!check_root_container_name("a\0b")); +} + +/// For each supported container kind, `new_mergeable` produces a deterministic +/// cid that decodes back to the same `(parent, key, kind)`. Counter is gated +/// on the feature; the rest are unconditional. +#[test] +fn mergeable_cid_roundtrips_for_every_container_kind() { + use loro_common::{ContainerID, ContainerType}; + let parent = ContainerID::new_root("state", ContainerType::Map); + + for kind in ContainerType::ALL_TYPES { + let cid = ContainerID::new_mergeable(&parent, "field", kind); + assert!(cid.is_mergeable(), "kind {kind:?}: must be mergeable"); + let again = ContainerID::new_mergeable(&parent, "field", kind); + assert_eq!(cid, again, "kind {kind:?}: cid must be deterministic"); + let (decoded_parent, decoded_key, decoded_kind) = cid + .parse_mergeable() + .unwrap_or_else(|| panic!("kind {kind:?}: parse_mergeable returned None")); + assert_eq!(decoded_parent, parent, "kind {kind:?}: parent roundtrip"); + assert_eq!(decoded_key, "field", "kind {kind:?}: key roundtrip"); + assert_eq!(decoded_kind, kind, "kind {kind:?}: kind roundtrip"); + } +} + +/// Key encoding is escaped path segments, so it must round-trip cleanly for +/// degenerate inputs: empty, long, delimiters, embedded NUL, and embedded +/// mergeable prefix substring. Catches off-by-one and ad-hoc string-split +/// mistakes in any future decoder change. +#[test] +fn mergeable_cid_roundtrips_for_degenerate_keys() { + use loro_common::{ContainerID, ContainerType}; + let parent = ContainerID::new_root("state", ContainerType::Map); + + let long_key: String = std::iter::repeat('k').take(2048).collect(); + let cases: Vec<&str> = vec![ + "", + long_key.as_str(), + "with\0nul\0bytes", + "embedded 🤝: substring in the middle", + "starts_with_🤝:_prefix", + "trailing_emoji_🤝:", + "ascii/slash/looking", + "contains>separator", + "contains\\backslash", + "mixed>\\/\0chars", + ]; + + for key in cases { + let cid = ContainerID::new_mergeable(&parent, key, ContainerType::Map); + assert!(cid.is_mergeable(), "key {key:?}: must be mergeable"); + let (decoded_parent, decoded_key, decoded_kind) = cid + .parse_mergeable() + .unwrap_or_else(|| panic!("key {key:?}: parse_mergeable returned None")); + assert_eq!(decoded_parent, parent); + assert_eq!(decoded_key, key, "key {key:?}: round-trip mismatch"); + assert_eq!(decoded_kind, ContainerType::Map); + } +} + +#[test] +fn mergeable_cid_uses_flattened_path_payload() { + use loro_common::{ContainerID, ContainerType, MERGEABLE_NAMESPACE_PREFIX}; + + let parent = ContainerID::new_root("state", ContainerType::Map); + let child = ContainerID::new_mergeable(&parent, "note>1", ContainerType::Map); + let grandchild = ContainerID::new_mergeable(&child, "body/slash\\nul\0", ContainerType::Text); + + let name = match &grandchild { + ContainerID::Root { name, .. } => name.as_str(), + _ => panic!("expected Root"), + }; + assert!( + name.starts_with(MERGEABLE_NAMESPACE_PREFIX), + "mergeable cid must use the reserved namespace" + ); + assert_eq!( + name, "🤝:$state>note\\>1>body\\sslash\\\\nul\\0", + "nested mergeable ids must extend the flattened path, not embed parent cid bytes" + ); + assert!( + !name.contains('/'), + "synthetic root names must not contain raw slash" + ); + assert!( + !name.contains('\0'), + "synthetic root names must not contain raw NUL" + ); + + let (decoded_parent, decoded_key, decoded_kind) = grandchild.parse_mergeable().unwrap(); + assert_eq!(decoded_parent, child); + assert_eq!(decoded_key, "body/slash\\nul\0"); + assert_eq!(decoded_kind, ContainerType::Text); +} + +#[test] +fn mergeable_cid_roundtrips_normal_base_parent() { + use loro_common::{ContainerID, ContainerType, ID}; + + let parent = ContainerID::new_normal( + ID { + peer: u64::MAX, + counter: i32::MIN, + }, + ContainerType::Map, + ); + let cid = ContainerID::new_mergeable(&parent, "field", ContainerType::List); + let name = match &cid { + ContainerID::Root { name, .. } => name.as_str(), + _ => panic!("expected Root"), + }; + assert!( + name.starts_with("🤝:@3w5e11264sgsf:-zik0zk>"), + "normal parent ids should use compact base36 encoding; got {name:?}" + ); + + let (decoded_parent, decoded_key, decoded_kind) = cid.parse_mergeable().unwrap(); + assert_eq!(decoded_parent, parent); + assert_eq!(decoded_key, "field"); + assert_eq!(decoded_kind, ContainerType::List); +} + +#[test] +fn mergeable_cid_roundtrips_escaped_root_base_parent() { + use loro_common::{ContainerID, ContainerType}; + + let parent = ContainerID::new_root("root>\\name", ContainerType::Map); + let cid = ContainerID::new_mergeable(&parent, "field", ContainerType::Tree); + let name = match &cid { + ContainerID::Root { name, .. } => name.as_str(), + _ => panic!("expected Root"), + }; + assert_eq!(name, "🤝:$root\\>\\\\name>field"); + + let (decoded_parent, decoded_key, decoded_kind) = cid.parse_mergeable().unwrap(); + assert_eq!(decoded_parent, parent); + assert_eq!(decoded_key, "field"); + assert_eq!(decoded_kind, ContainerType::Tree); +} + +#[test] +#[should_panic(expected = "mergeable child parent must be a map")] +fn mergeable_cid_rejects_non_map_parent() { + use loro_common::{ContainerID, ContainerType}; + + let parent = ContainerID::new_root("content", ContainerType::Text); + let _ = ContainerID::new_mergeable(&parent, "field", ContainerType::Map); +} + +#[test] +fn nested_mergeable_cid_size_grows_linearly() { + use loro_common::{ContainerID, ContainerType}; + + let mut cid = ContainerID::new_root("state", ContainerType::Map); + let mut sizes = Vec::new(); + for _ in 0..=8 { + cid = ContainerID::new_mergeable(&cid, "k", ContainerType::Map); + sizes.push(cid.to_bytes().len()); + } + + for window in sizes.windows(2) { + assert_eq!( + window[1] - window[0], + 2, + "each additional one-byte key should add only separator + key bytes; sizes={sizes:?}" + ); + } + assert!( + sizes[8] < 64, + "depth 8 should stay compact with flattened encoding; sizes={sizes:?}" + ); +} diff --git a/vendor/loro-internal/tests/mergeable_container.rs b/vendor/loro-internal/tests/mergeable_container.rs new file mode 100644 index 0000000..c675abc --- /dev/null +++ b/vendor/loro-internal/tests/mergeable_container.rs @@ -0,0 +1,19 @@ +//! Integration tests for mergeable container support. The actual tests live in focused files +//! under `tests/mergeable_container/`; this harness aggregates them into a single test target. + +#[path = "mergeable_container/convergence.rs"] +mod convergence; +#[path = "mergeable_container/delete.rs"] +mod delete; +#[path = "mergeable_container/discriminator.rs"] +mod discriminator; +#[path = "mergeable_container/events_and_paths.rs"] +mod events_and_paths; +#[path = "mergeable_container/pending.rs"] +mod pending; +#[path = "mergeable_container/snapshot.rs"] +mod snapshot; +#[path = "mergeable_container/type_conflict.rs"] +mod type_conflict; +#[path = "mergeable_container/undo_redo.rs"] +mod undo_redo; diff --git a/vendor/loro-internal/tests/mergeable_container/common.rs b/vendor/loro-internal/tests/mergeable_container/common.rs new file mode 100644 index 0000000..5add377 --- /dev/null +++ b/vendor/loro-internal/tests/mergeable_container/common.rs @@ -0,0 +1,25 @@ +//! Shared helpers for the mergeable-container integration tests. +//! +//! Each split test file uses `#[path = "mergeable_container/common.rs"] mod common;` from +//! the harness in `tests/mergeable_container.rs`, so test fns can reach `common::doc` and +//! `common::sync` regardless of which sub-file they live in. + +// Each split test file imports this module via `#[path = "common.rs"]`, so each helper appears +// as a separate copy per file. Suppress the dead-code warning that fires when an individual file +// only uses a subset of the helpers. +#![allow(dead_code)] + +use loro_internal::{loro::ExportMode, LoroDoc}; + +pub fn doc(peer: u64) -> LoroDoc { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(peer).unwrap(); + doc +} + +pub fn sync(a: &LoroDoc, b: &LoroDoc) { + a.import(&b.export(ExportMode::updates(&a.oplog_vv())).unwrap()) + .unwrap(); + b.import(&a.export(ExportMode::updates(&b.oplog_vv())).unwrap()) + .unwrap(); +} diff --git a/vendor/loro-internal/tests/mergeable_container/convergence.rs b/vendor/loro-internal/tests/mergeable_container/convergence.rs new file mode 100644 index 0000000..db9a555 --- /dev/null +++ b/vendor/loro-internal/tests/mergeable_container/convergence.rs @@ -0,0 +1,285 @@ +//! Concurrent first-create convergence and basic merging. + +#[path = "common.rs"] +mod common; +use common::{doc, sync}; + +use loro_internal::{cursor::PosType, event::Index, handler::ValueOrHandler, HandlerTrait, ToJson}; +use serde_json::json; + +#[test] +#[cfg(feature = "counter")] +fn concurrent_counter_increments_show_current_lost_update_bug() { + let a = doc(1); + let b = doc(2); + + let a_root = a.get_map("state"); + let b_root = b.get_map("state"); + + let a_counter = a_root.ensure_mergeable_counter("revision").unwrap(); + let b_counter = b_root.ensure_mergeable_counter("revision").unwrap(); + + assert_eq!( + a_counter.id(), + b_counter.id(), + "both peers should produce the same deterministic cid" + ); + assert!( + a_counter.id().is_mergeable(), + "counter cid should be in the mergeable namespace" + ); + + a_counter.increment(1.0).unwrap(); + b_counter.increment(1.0).unwrap(); + + sync(&a, &b); + + assert_eq!( + a.get_deep_value().to_json_value(), + json!({ "state": { "revision": 2.0 } }), + "both concurrent increments should survive on the merged counter", + ); + assert_eq!( + b.get_deep_value().to_json_value(), + a.get_deep_value().to_json_value() + ); + + let a_cid = match a_root.get_("revision") { + Some(ValueOrHandler::Handler(handler)) => Some(handler.id()), + _ => None, + }; + let b_cid = match b_root.get_("revision") { + Some(ValueOrHandler::Handler(handler)) => Some(handler.id()), + _ => None, + }; + assert_eq!( + a_cid, b_cid, + "both peers should resolve the same logical counter cid" + ); +} + +#[test] +fn concurrent_text_updates_show_current_lost_update_bug() { + let a = doc(1); + let b = doc(2); + let a_text = a.get_map("state").ensure_mergeable_text("notes").unwrap(); + let b_text = b.get_map("state").ensure_mergeable_text("notes").unwrap(); + + assert_eq!( + a_text.id(), + b_text.id(), + "both peers should produce the same deterministic cid" + ); + assert!( + a_text.id().is_mergeable(), + "text cid should be in the mergeable namespace" + ); + + a_text.insert(0, "A", PosType::Unicode).unwrap(); + b_text.insert(0, "B", PosType::Unicode).unwrap(); + sync(&a, &b); + + let value = a.get_deep_value().to_json_value(); + assert!( + value == json!({ "state": { "notes": "AB" } }) + || value == json!({ "state": { "notes": "BA" } }), + "both concurrent text edits should survive on the merged text; got {value}", + ); +} + +#[test] +fn concurrent_list_inserts_show_current_lost_update_bug() { + let a = doc(1); + let b = doc(2); + let a_list = a.get_map("state").ensure_mergeable_list("items").unwrap(); + let b_list = b.get_map("state").ensure_mergeable_list("items").unwrap(); + + assert_eq!( + a_list.id(), + b_list.id(), + "both peers should produce the same deterministic cid" + ); + assert!( + a_list.id().is_mergeable(), + "list cid should be in the mergeable namespace" + ); + + a_list.insert(0, "A").unwrap(); + b_list.insert(0, "B").unwrap(); + sync(&a, &b); + + let value = a.get_deep_value().to_json_value(); + assert!( + value == json!({ "state": { "items": ["A", "B"] } }) + || value == json!({ "state": { "items": ["B", "A"] } }), + "both concurrent list inserts should survive on the merged list; got {value}", + ); +} + +/// Two peers each obtain the "profile" Map via `ensure_mergeable_map` and write +/// to *different* keys. With non-mergeable child Maps, each peer creates a +/// distinct peer-specific cid, so LWW drops one peer's Map entirely even +/// though the key sets are disjoint. Once child Maps are mergeable the merged +/// value should contain both keys. +#[test] +fn concurrent_map_writes_show_current_lost_update_bug() { + let a = doc(1); + let b = doc(2); + let a_map = a.get_map("state").ensure_mergeable_map("profile").unwrap(); + let b_map = b.get_map("state").ensure_mergeable_map("profile").unwrap(); + + assert_eq!( + a_map.id(), + b_map.id(), + "both peers should produce the same deterministic cid" + ); + assert!( + a_map.id().is_mergeable(), + "map cid should be in the mergeable namespace" + ); + + a_map.insert("name", "Ada").unwrap(); + b_map.insert("title", "Engineer").unwrap(); + sync(&a, &b); + + assert_eq!( + a.get_deep_value().to_json_value(), + json!({ "state": { "profile": { "name": "Ada", "title": "Engineer" } } }) + ); +} + +/// Three peers each increment the same mergeable counter once. After a full +/// round-robin sync, every peer must observe `3.0` and the same deterministic +/// cid. Two-peer tests can't catch ordering or idempotency bugs that fire +/// only when more than two histories overlap. +#[test] +#[cfg(feature = "counter")] +fn three_peer_mergeable_counter_convergence() { + let a = doc(1); + let b = doc(2); + let c = doc(3); + + let a_counter = a + .get_map("state") + .ensure_mergeable_counter("revision") + .unwrap(); + let b_counter = b + .get_map("state") + .ensure_mergeable_counter("revision") + .unwrap(); + let c_counter = c + .get_map("state") + .ensure_mergeable_counter("revision") + .unwrap(); + assert_eq!(a_counter.id(), b_counter.id()); + assert_eq!(b_counter.id(), c_counter.id()); + + a_counter.increment(1.0).unwrap(); + b_counter.increment(1.0).unwrap(); + c_counter.increment(1.0).unwrap(); + + // Full round-robin: every pair syncs. + sync(&a, &b); + sync(&b, &c); + sync(&a, &c); + sync(&a, &b); + + let expected = json!({ "state": { "revision": 3.0 } }); + assert_eq!(a.get_deep_value().to_json_value(), expected); + assert_eq!(b.get_deep_value().to_json_value(), expected); + assert_eq!(c.get_deep_value().to_json_value(), expected); +} + +/// After A and B sync once, both peers concurrently mutate the same +/// mergeable counter again, then sync. Convergence must hold on the second +/// round — the deterministic cid plus CRDT merge must keep working after +/// the logical mergeable edge has already been resolved and used. +#[test] +#[cfg(feature = "counter")] +fn post_merge_concurrent_counter_increments_converge() { + let a = doc(1); + let b = doc(2); + + let a_counter = a + .get_map("state") + .ensure_mergeable_counter("revision") + .unwrap(); + let b_counter = b + .get_map("state") + .ensure_mergeable_counter("revision") + .unwrap(); + a_counter.increment(1.0).unwrap(); + b_counter.increment(1.0).unwrap(); + sync(&a, &b); + assert_eq!( + a.get_deep_value().to_json_value(), + json!({ "state": { "revision": 2.0 } }) + ); + + // Round 2: concurrent edits on the already-merged child. + a_counter.increment(10.0).unwrap(); + b_counter.increment(100.0).unwrap(); + sync(&a, &b); + + let expected = json!({ "state": { "revision": 112.0 } }); + assert_eq!(a.get_deep_value().to_json_value(), expected); + assert_eq!(b.get_deep_value().to_json_value(), expected); +} + +/// Two peers independently navigate `state → mergeable map "profile" → +/// mergeable counter "revision"` and increment. The deterministic cid for +/// "revision" is the same on both peers (it's a function of the "profile" +/// cid, which is itself deterministic from "state"'s cid + "profile" + Map). +/// After sync, both peers see the counter at 2.0 nested correctly. +#[test] +#[cfg(feature = "counter")] +fn nested_mergeable_concurrent_counter_converges() { + let a = doc(1); + let b = doc(2); + + let a_profile = a.get_map("state").ensure_mergeable_map("profile").unwrap(); + let b_profile = b.get_map("state").ensure_mergeable_map("profile").unwrap(); + assert_eq!(a_profile.id(), b_profile.id()); + + let a_rev = a_profile.ensure_mergeable_counter("revision").unwrap(); + let b_rev = b_profile.ensure_mergeable_counter("revision").unwrap(); + assert_eq!(a_rev.id(), b_rev.id()); + + a_rev.increment(1.0).unwrap(); + b_rev.increment(1.0).unwrap(); + sync(&a, &b); + + let expected = json!({ "state": { "profile": { "revision": 2.0 } } }); + assert_eq!(a.get_deep_value().to_json_value(), expected); + assert_eq!(b.get_deep_value().to_json_value(), expected); + + // Path resolution still walks both mergeable hops. + let path = a.get_path_to_container(&a_rev.id()).expect("path"); + let indexes = path.iter().map(|(_, idx)| idx.clone()).collect::<Vec<_>>(); + assert_eq!( + indexes, + vec![ + Index::Key("state".into()), + Index::Key("profile".into()), + Index::Key("revision".into()), + ] + ); +} + +/// `ensure_mergeable_*` cannot work on a detached handler: the deterministic cid is computed from +/// the parent's cid, which a detached parent doesn't have. Falling back to a non-deterministic +/// regular child would silently break the mergeable guarantee once the handler attaches, so the +/// detached call must surface that misuse explicitly instead. +#[test] +#[cfg(feature = "counter")] +fn detached_map_ensure_mergeable_counter_rejects_misuse() { + use loro_internal::MapHandler; + let detached = MapHandler::new_detached(); + let err = detached + .ensure_mergeable_counter("revision") + .expect_err("detached ensure_mergeable_* must error"); + assert!( + matches!(err, loro_common::LoroError::MisuseDetachedContainer { .. }), + "detached error must be MisuseDetachedContainer; got {err:?}" + ); +} diff --git a/vendor/loro-internal/tests/mergeable_container/delete.rs b/vendor/loro-internal/tests/mergeable_container/delete.rs new file mode 100644 index 0000000..79b5802 --- /dev/null +++ b/vendor/loro-internal/tests/mergeable_container/delete.rs @@ -0,0 +1,383 @@ +//! Delete semantics for mergeable children. +//! +//! `delete(key)` overwrites the binary marker in the parent map's value slot with `None`, exactly +//! as deleting a regular child container clears its value-table entry. The child +//! becomes unreachable; its container state is preserved in history. Re-calling +//! `ensure_mergeable_<kind>(key)` rewrites the marker and resurfaces the preserved state, and +//! Map LWW resolves any concurrent delete-vs-recreate race — symmetric with normal Loro +//! write/delete (loro-dev/loro#759). + +#[path = "common.rs"] +mod common; +use common::{doc, sync}; + +use loro_internal::{loro::ExportMode, HandlerTrait, ToJson}; +use serde_json::json; + +/// `delete(key)` on a mergeable key clears the marker, so the child no longer appears in +/// deep value. The child's container state is preserved: re-getting it resolves to the same +/// deterministic cid and resurfaces the prior value (delete detaches, it does not reset). +#[test] +#[cfg(feature = "counter")] +fn delete_clears_marker_and_recreate_resurfaces_state() { + let doc = doc(1); + let root = doc.get_map("state"); + let counter = root.ensure_mergeable_counter("revision").unwrap(); + counter.increment(3.0).unwrap(); + doc.commit_then_renew(); + assert_eq!( + doc.get_deep_value().to_json_value(), + json!({ "state": { "revision": 3.0 } }) + ); + + root.delete("revision").unwrap(); + doc.commit_then_renew(); + + // Cleared: not in deep value, exactly like any deleted container. + assert_eq!( + doc.get_deep_value().to_json_value(), + json!({ "state": {} }), + "delete must clear the mergeable child from deep value" + ); + + // Re-get rewrites the marker. The child resurfaces with its PRESERVED value (3.0), + // not a reset to 0.0 — delete detaches, it does not destroy the container state. + let counter2 = root.ensure_mergeable_counter("revision").unwrap(); + doc.commit_then_renew(); + assert_eq!(counter2.id(), counter.id(), "deterministic cid is stable"); + assert_eq!( + doc.get_deep_value().to_json_value(), + json!({ "state": { "revision": 3.0 } }), + "re-get rewrites the marker and resurfaces the preserved state" + ); +} + +/// `delete(key)` records nothing special in side state — the slot value (`None`) is the whole +/// story. After delete, the parent map simply has no value at the key. +#[test] +#[cfg(feature = "counter")] +fn delete_leaves_no_value_at_key() { + let doc = doc(1); + let root = doc.get_map("state"); + let counter = root.ensure_mergeable_counter("revision").unwrap(); + counter.increment(1.0).unwrap(); + doc.commit_then_renew(); + assert!(root.get("revision").is_some(), "marker present"); + + root.delete("revision").unwrap(); + doc.commit_then_renew(); + + assert_eq!( + root.get("revision"), + None, + "after delete the slot holds no value" + ); +} + +/// A local `delete` clears the child from deep value immediately, without waiting for any +/// remote import cycle. +#[test] +#[cfg(feature = "counter")] +fn local_delete_immediately_clears_mergeable_child() { + let doc = doc(1); + let root = doc.get_map("state"); + let counter = root.ensure_mergeable_counter("revision").unwrap(); + counter.increment(1.0).unwrap(); + doc.commit_then_renew(); + assert_eq!( + doc.get_deep_value().to_json_value(), + json!({ "state": { "revision": 1.0 } }) + ); + + root.delete("revision").unwrap(); + doc.commit_then_renew(); + + assert_eq!( + doc.get_deep_value().to_json_value(), + json!({ "state": {} }), + "local delete must remove the mergeable child from deep value" + ); +} + +/// Recreate after seeing a delete wins: peer A deletes the key; peer B imports the delete (its +/// slot is now cleared), then re-calls `ensure_mergeable_<kind>`, which re-emits a FRESH marker +/// because the slot is empty. That marker's IdLp dominates the delete, so the child is +/// visible again and its preserved state resurfaces — symmetric with re-`set_container` after a +/// regular delete. +/// +/// (Note the symmetry: if B re-calls `ensure_mergeable_<kind>` while still holding the OLD +/// marker it imported earlier — i.e. before seeing the delete — the call is idempotent and +/// emits no op, so the concurrent delete wins, exactly as a regular concurrent delete beats a +/// stale local handle. That case is covered by `concurrent_delete_wins_against_earlier_increment`.) +#[test] +#[cfg(feature = "counter")] +fn recreate_after_seen_delete_resurfaces_preserved_state() { + let a = doc(1); + let b = doc(2); + + let a_root = a.get_map("state"); + let a_counter = a_root.ensure_mergeable_counter("revision").unwrap(); + a_counter.increment(1.0).unwrap(); + a.commit_then_renew(); + sync(&a, &b); + + // A deletes; B imports the delete so B's slot is cleared. + a_root.delete("revision").unwrap(); + a.commit_then_renew(); + sync(&a, &b); + assert_eq!( + b.get_deep_value().to_json_value(), + json!({ "state": {} }), + "B sees the cleared slot after importing the delete" + ); + + // B re-creates: the slot is empty, so this re-emits a fresh marker dominating the + // delete. The preserved counter state (1.0) resurfaces, plus B's new increment. + let b_counter = b + .get_map("state") + .ensure_mergeable_counter("revision") + .unwrap(); + b_counter.increment(100.0).unwrap(); + b.commit_then_renew(); + + sync(&a, &b); + + let va = a.get_deep_value().to_json_value(); + let vb = b.get_deep_value().to_json_value(); + assert_eq!(va, vb, "peers must converge"); + assert_eq!( + va["state"]["revision"], + json!(101.0), + "recreate after seeing the delete resurfaces preserved state (1.0) + new increment (100.0)" + ); +} + +/// Concurrent delete-wins: peer A increments, peer B deletes with a higher IdLp and never +/// recreates. The delete dominates the marker via Map LWW, so the child is gone on both +/// peers — symmetric with a concurrent delete winning over a regular write. +#[test] +#[cfg(feature = "counter")] +fn concurrent_delete_wins_against_earlier_increment() { + let a = doc(1); + let b = doc(2); + + let a_root = a.get_map("state"); + let a_counter = a_root.ensure_mergeable_counter("revision").unwrap(); + a_counter.increment(1.0).unwrap(); + a.commit_then_renew(); + sync(&a, &b); + + // B increments first (low IdLp). + let b_root = b.get_map("state"); + let b_counter = b_root.ensure_mergeable_counter("revision").unwrap(); + b_counter.increment(100.0).unwrap(); + b.commit_then_renew(); + + // A advances its clock past B's increment, then deletes. + for i in 0..5 { + a_root.insert(&format!("noise_{i}"), i).unwrap(); + a.commit_then_renew(); + } + a_root.delete("revision").unwrap(); + a.commit_then_renew(); + + sync(&a, &b); + + let va = a.get_deep_value().to_json_value(); + let vb = b.get_deep_value().to_json_value(); + assert_eq!(va, vb); + assert!( + va["state"].get("revision").is_none(), + "delete with higher IdLp must dominate the marker; got {va}" + ); +} + +/// Remote delete clears the child on the receiver: peer B has a visible mergeable counter; peer A +/// deletes the key with a higher IdLp. After sync, B's deep value drops the counter because A's +/// delete wins the Map LWW for the marker slot. +#[test] +#[cfg(feature = "counter")] +fn remote_delete_clears_mergeable_child_on_receiver() { + let a = doc(1); + let b = doc(2); + + let b_root = b.get_map("state"); + let b_counter = b_root.ensure_mergeable_counter("revision").unwrap(); + b_counter.increment(1.0).unwrap(); + b.commit_then_renew(); + sync(&a, &b); + assert_eq!( + b.get_deep_value().to_json_value(), + json!({ "state": { "revision": 1.0 } }) + ); + + let a_root = a.get_map("state"); + for i in 0..5 { + a_root.insert(&format!("noise_{i}"), i).unwrap(); + a.commit_then_renew(); + } + a_root.delete("revision").unwrap(); + a.commit_then_renew(); + + sync(&a, &b); + + let vb = b.get_deep_value().to_json_value(); + assert!( + vb["state"].get("revision").is_none(), + "remote delete must clear B's mergeable child; got {vb}" + ); +} + +/// Three-peer convergence across a delete and a competing-kind recreate: B creates a counter, A +/// deletes it with a higher IdLp, C recreates the key as a text. All peers converge on the text. +#[test] +#[cfg(feature = "counter")] +fn three_peer_delete_then_recreate_converges() { + use loro_internal::cursor::PosType; + + let a = doc(1); + let b = doc(2); + let c = doc(3); + + let b_counter = b + .get_map("state") + .ensure_mergeable_counter("revision") + .unwrap(); + b_counter.increment(1.0).unwrap(); + b.commit_then_renew(); + + sync(&a, &b); + sync(&b, &c); + + let a_root = a.get_map("state"); + for i in 0..6 { + a_root.insert(&format!("noise_{i}"), i).unwrap(); + a.commit_then_renew(); + } + a_root.delete("revision").unwrap(); + a.commit_then_renew(); + + sync(&a, &b); + sync(&a, &c); + + // C recreates "revision" as a text with a post-delete IdLp. + let c_text = c + .get_map("state") + .ensure_mergeable_text("revision") + .unwrap(); + c_text.insert(0, "after-delete", PosType::Unicode).unwrap(); + c.commit_then_renew(); + + sync(&b, &c); + sync(&a, &c); + sync(&a, &b); + + let expected = json!({ + "state": { + "noise_0": 0, + "noise_1": 1, + "noise_2": 2, + "noise_3": 3, + "noise_4": 4, + "noise_5": 5, + "revision": "after-delete", + } + }); + assert_eq!(a.get_deep_value().to_json_value(), expected, "A converges"); + assert_eq!(b.get_deep_value().to_json_value(), expected, "B converges"); + assert_eq!(c.get_deep_value().to_json_value(), expected, "C converges"); +} + +/// Snapshot round-trip preserves the delete: a peer creates and deletes a mergeable counter, then +/// exports a snapshot. The receiver sees no counter — the `None` slot rides through the snapshot +/// as ordinary map state, so no special recovery is needed. +#[test] +#[cfg(feature = "counter")] +fn snapshot_roundtrip_preserves_delete() { + let a = doc(1); + let a_root = a.get_map("state"); + let a_counter = a_root.ensure_mergeable_counter("revision").unwrap(); + a_counter.increment(5.0).unwrap(); + a_root.delete("revision").unwrap(); + a.commit_then_renew(); + assert_eq!(a.get_deep_value().to_json_value(), json!({ "state": {} })); + + let snapshot = a.export(ExportMode::Snapshot).unwrap(); + let b = doc(2); + b.import(&snapshot).unwrap(); + + assert_eq!( + b.get_deep_value().to_json_value(), + json!({ "state": {} }), + "snapshot import must preserve the cleared slot; no mergeable child appears" + ); + assert_eq!( + b.get_map("state").get("revision"), + None, + "the cleared slot has no value after snapshot import" + ); +} + +/// `delete` on a mergeable key emits exactly one op — a regular `MapSet { value: None }` — by the +/// local peer. No new op types are introduced; older peers apply it as an ordinary map-key clear. +#[test] +#[cfg(feature = "counter")] +fn delete_on_mergeable_key_emits_only_existing_op_types() { + let doc = doc(1); + let root = doc.get_map("state"); + let counter = root.ensure_mergeable_counter("revision").unwrap(); + counter.increment(1.0).unwrap(); + doc.commit_then_renew(); + let counter_before = doc.oplog_vv().get(&1).copied().unwrap_or(0); + + root.delete("revision").unwrap(); + doc.commit_then_renew(); + let counter_after = doc.oplog_vv().get(&1).copied().unwrap_or(0); + + let new_ops = counter_after - counter_before; + assert_eq!( + new_ops, 1, + "delete must emit exactly one op (the MapSet clearing the slot); got {new_ops}" + ); +} + +/// `revert_to` a version before the delete re-activates the hidden child. The diff must carry +/// the child's delta relative to its preserved hidden state, not a full-state revival that +/// would be appended to it (it used to yield "hellohello" / 14 / ["keep", "keep"]). +#[test] +fn revert_to_before_delete_restores_hidden_content_once() { + let doc = doc(1); + let root = doc.get_map("m"); + root.ensure_mergeable_text("t") + .unwrap() + .insert(0, "hello", loro_internal::cursor::PosType::Unicode) + .unwrap(); + root.ensure_mergeable_list("l") + .unwrap() + .push("keep") + .unwrap(); + #[cfg(feature = "counter")] + root.ensure_mergeable_counter("c") + .unwrap() + .increment(7.0) + .unwrap(); + doc.commit_then_renew(); + let before_delete = doc.state_frontiers(); + let expected = doc.get_deep_value().to_json_value(); + + for key in ["t", "l", "c"] { + let _ = root.delete(key); + } + doc.commit_then_renew(); + assert_eq!(doc.get_deep_value().to_json_value(), json!({ "m": {} })); + + doc.revert_to(&before_delete).unwrap(); + doc.commit_then_renew(); + assert_eq!(doc.get_deep_value().to_json_value(), expected); + + let replay = loro_internal::LoroDoc::new_auto_commit(); + replay + .import(&doc.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + assert_eq!(replay.get_deep_value().to_json_value(), expected); +} diff --git a/vendor/loro-internal/tests/mergeable_container/discriminator.rs b/vendor/loro-internal/tests/mergeable_container/discriminator.rs new file mode 100644 index 0000000..b15695e --- /dev/null +++ b/vendor/loro-internal/tests/mergeable_container/discriminator.rs @@ -0,0 +1,313 @@ +//! Marker-based mergeable type-conflict resolution. +//! +//! `ensure_mergeable_<kind>(key)` records which container kind is active at +//! `(parent, key)` by writing a compact binary marker op against the parent map. +//! The active mergeable child is whichever marker the parent map's regular LWW +//! resolves to. See loro-dev/loro#759. + +#[path = "common.rs"] +mod common; +use common::{doc, sync}; + +use loro_common::{mergeable_marker, ContainerType, LoroError, LoroValue, MERGEABLE_MARKER_MAGIC}; +use loro_internal::{HandlerTrait, ToJson}; +use serde_json::json; + +/// `ensure_mergeable_list(key)` activates a List child at the parent map's slot. From the +/// public API, `map.get(key)` reports it as a Container value carrying the deterministic +/// mergeable cid — symmetric with what an explicit `set_container` would produce. +#[test] +fn ensure_mergeable_writes_marker_into_parent_slot() { + let d = doc(1); + let root = d.get_map("state"); + + assert_eq!(root.get("tags"), None, "key starts empty"); + + let list = root.ensure_mergeable_list("tags").unwrap(); + + assert_eq!( + root.get("tags"), + Some(LoroValue::Container(list.id())), + "ensure_mergeable_list must surface the activated List child as a Container value" + ); +} + +/// `ensure_mergeable_<kind>(key)` must not silently clobber an existing non-mergeable value at the +/// key. A plain scalar or a regular child container occupying the slot makes the call an error, +/// so the marker overwrite is never a hidden side effect of a `get_`-named API. +#[test] +fn ensure_mergeable_rejects_overwriting_a_scalar_value() { + let d = doc(1); + let root = d.get_map("state"); + root.insert("field", 5).unwrap(); + + let err = root + .ensure_mergeable_list("field") + .expect_err("ensure_mergeable over a scalar must error"); + assert!( + matches!(err, LoroError::ArgErr(_)), + "expected ArgErr, got {err:?}" + ); + assert_eq!( + root.get("field"), + Some(5.into()), + "the existing scalar value must be left untouched" + ); +} + +/// The same guard applies when the slot holds a regular child container: requesting a mergeable +/// child there is an error and must not overwrite the container reference. +#[test] +fn ensure_mergeable_rejects_overwriting_a_regular_child_container() { + let d = doc(1); + let root = d.get_map("state"); + root.insert_container("field", loro_internal::handler::MapHandler::new_detached()) + .unwrap(); + + let err = root + .ensure_mergeable_list("field") + .expect_err("ensure_mergeable over a regular child container must error"); + assert!( + matches!(err, LoroError::ArgErr(_)), + "expected ArgErr, got {err:?}" + ); +} + +/// An empty slot, or a slot already holding a mergeable marker, is fair game: +/// `ensure_mergeable_<kind>` creates on empty and is idempotent / kind-changes over an existing +/// marker. Only non-mergeable occupants are rejected. +#[test] +fn ensure_mergeable_allows_empty_slot_and_existing_marker() { + let d = doc(1); + let root = d.get_map("state"); + + // Empty slot: creates. + let _list = root.ensure_mergeable_list("a").unwrap(); + // Same kind again: idempotent, still Ok. + let _list2 = root.ensure_mergeable_list("a").unwrap(); + // Different kind over an existing marker: kind change, still Ok. + let _map = root.ensure_mergeable_map("a").unwrap(); +} + +/// A user string must stay a plain scalar and block mergeable child creation. +#[test] +fn user_string_is_not_mergeable() { + let d = doc(1); + let root = d.get_map("state"); + + root.insert("field", "not-a-marker").unwrap(); + d.commit_then_renew(); + + assert_eq!( + d.get_deep_value().to_json_value(), + json!({ "state": { "field": "not-a-marker" } }) + ); + let err = root + .ensure_mergeable_map("field") + .expect_err("user string must not be treated as a mergeable marker"); + assert!( + matches!(err, LoroError::ArgErr(_)), + "expected ArgErr, got {err:?}" + ); +} + +/// A marker is bound to its exact `(parent, key, kind)` by the digest. Copying +/// the binary payload to another key leaves it as an inert user binary value. +#[test] +fn marker_for_another_key_is_not_mergeable() { + let d = doc(1); + let root = d.get_map("state"); + let marker_for_other = mergeable_marker(&root.id(), "other", ContainerType::Map); + + root.insert("field", marker_for_other.clone()).unwrap(); + d.commit_then_renew(); + + assert_eq!(root.get("field"), Some(marker_for_other)); + let err = root + .ensure_mergeable_map("field") + .expect_err("marker digest for another key must not activate this key"); + assert!( + matches!(err, LoroError::ArgErr(_)), + "expected ArgErr, got {err:?}" + ); +} + +/// A second `ensure_mergeable_<kind>(key)` with the SAME kind is idempotent: it +/// does not emit another op (the parent slot already holds the matching marker). +#[test] +fn repeated_ensure_mergeable_same_kind_is_idempotent() { + let d = doc(1); + let root = d.get_map("state"); + + let _first = root.ensure_mergeable_map("profile").unwrap(); + d.commit_then_renew(); + let ops_after_first = d.len_ops(); + + let _second = root.ensure_mergeable_map("profile").unwrap(); + d.commit_then_renew(); + let ops_after_second = d.len_ops(); + + assert_eq!( + ops_after_second, ops_after_first, + "a second same-kind ensure_mergeable must not emit another op" + ); +} + +/// The resolver substitutes the resolved child for the binary marker in deep value: the (empty) +/// child is visible immediately as its default, and the raw marker never leaks into the read view. +#[test] +fn marker_resolves_to_child_in_deep_value() { + let d = doc(1); + let root = d.get_map("state"); + let _list = root.ensure_mergeable_list("tags").unwrap(); + d.commit_then_renew(); + + assert_eq!( + d.get_deep_value().to_json_value(), + json!({ "state": { "tags": [] } }), + "the marker must resolve to the child's value, not leak as a binary value" + ); + + // Now add an item; the resolved child must reflect it. + let list = root.ensure_mergeable_list("tags").unwrap(); + list.insert(0, "hello").unwrap(); + d.commit_then_renew(); + assert_eq!( + d.get_deep_value().to_json_value(), + json!({ "state": { "tags": ["hello"] } }) + ); +} + +/// A nested chain of mergeable children resolves at every hop: the intermediate mergeable map is +/// visible (it has a marker on its parent) even though it never receives a direct content op, only +/// its nested child does. This is the case the old `has_ops` gate broke. +#[test] +#[cfg(feature = "counter")] +fn nested_mergeable_chain_resolves_at_every_hop() { + let d = doc(1); + let profile = d.get_map("state").ensure_mergeable_map("profile").unwrap(); + let rev = profile.ensure_mergeable_counter("revision").unwrap(); + rev.increment(5.0).unwrap(); + d.commit_then_renew(); + + assert_eq!( + d.get_deep_value().to_json_value(), + json!({ "state": { "profile": { "revision": 5.0 } } }), + "intermediate mergeable map must be visible via its marker" + ); +} + +/// Two peers concurrently create the SAME kind under the same key. Both write the identical +/// marker, so the Map LWW merge is a no-op and both peers' contributions land in the one +/// deterministic cid. +#[test] +fn concurrent_same_kind_creation_merges_via_identical_marker() { + let a = doc(1); + let b = doc(2); + + let a_list = a.get_map("state").ensure_mergeable_list("tags").unwrap(); + a_list.insert(0, "from_a").unwrap(); + a.commit_then_renew(); + + let b_list = b.get_map("state").ensure_mergeable_list("tags").unwrap(); + b_list.insert(0, "from_b").unwrap(); + b.commit_then_renew(); + + sync(&a, &b); + + let va = a.get_deep_value().to_json_value(); + let vb = b.get_deep_value().to_json_value(); + assert_eq!(va, vb, "same-kind concurrent creation must converge"); + + let tags = &va["state"]["tags"]; + assert!(tags.is_array(), "tags must be a list, got {tags:?}"); + let items: Vec<&str> = tags + .as_array() + .unwrap() + .iter() + .map(|v| v.as_str().unwrap()) + .collect(); + assert!( + items.contains(&"from_a") && items.contains(&"from_b"), + "both peers' items must be preserved in the merged list; got {items:?}" + ); +} + +/// Kind-change cycle: a key cycles List -> Map -> List. Each `ensure_mergeable_<kind>` rewrites the +/// marker. When the marker returns to List, the ORIGINAL List's contents resurface (its container +/// state was preserved by name across the cycle), proving the cycle is non-lossy. +#[test] +fn kind_change_cycle_resurfaces_original_list_contents() { + let d = doc(1); + let root = d.get_map("state"); + + // v1: List with an item. + let list = root.ensure_mergeable_list("field").unwrap(); + list.insert(0, "original").unwrap(); + d.commit_then_renew(); + assert_eq!( + d.get_deep_value().to_json_value(), + json!({ "state": { "field": ["original"] } }) + ); + + // v2: Map (kind change). The List is now hidden, but its state is preserved by name. + let map = root.ensure_mergeable_map("field").unwrap(); + map.insert("k", 1).unwrap(); + d.commit_then_renew(); + assert_eq!( + d.get_deep_value().to_json_value(), + json!({ "state": { "field": { "k": 1 } } }), + "Map marker active; List hidden" + ); + + // v3: back to List. The marker returns to List and the ORIGINAL contents resurface. + let list_again = root.ensure_mergeable_list("field").unwrap(); + d.commit_then_renew(); + assert_eq!( + list_again.id(), + list.id(), + "List cid is deterministic across the cycle" + ); + assert_eq!( + d.get_deep_value().to_json_value(), + json!({ "state": { "field": ["original"] } }), + "original List contents resurface after the List -> Map -> List cycle" + ); +} + +/// Forward-compatibility envelope: the marker is stored as a real `LoroValue::Binary` in the +/// parent map's value table, so a client that doesn't understand mergeable containers — for +/// example one that consumes only the shallow JSON value — sees it as an inert binary scalar +/// rather than a fake container edge or a reserved-looking user string. +/// +/// New clients translate that binary marker into a Container value at the `MapHandler` boundary +/// (see `ensure_mergeable_writes_marker_into_parent_slot`); this test inspects the underlying +/// representation via `get_value`, which preserves the wire-level form. +#[test] +fn marker_is_observable_as_raw_binary_for_old_clients() { + let d = doc(1); + let root = d.get_map("state"); + let _list = root.ensure_mergeable_list("tags").unwrap(); + d.commit_then_renew(); + + // `get_value` materializes the parent map as a `LoroValue::Map`, which preserves the raw + // binary marker the way it travels in snapshots and updates to older peers. + let shallow = root.get_value(); + let LoroValue::Map(entries) = shallow else { + panic!("parent value must be a map"); + }; + let raw = entries.get("tags").expect("slot has a marker").clone(); + let LoroValue::Binary(bytes) = &raw else { + panic!("marker must be a binary value at the wire level; got {raw:?}"); + }; + assert_eq!(bytes.len(), 8); + assert!(bytes.starts_with(&MERGEABLE_MARKER_MAGIC)); + assert_eq!( + bytes[MERGEABLE_MARKER_MAGIC.len()], + ContainerType::List.to_u8() + ); + + // The same marker is the inputs to the public mergeable parser. + let expected = mergeable_marker(&root.id(), "tags", ContainerType::List); + assert_eq!(raw, expected); +} diff --git a/vendor/loro-internal/tests/mergeable_container/events_and_paths.rs b/vendor/loro-internal/tests/mergeable_container/events_and_paths.rs new file mode 100644 index 0000000..9abf50e --- /dev/null +++ b/vendor/loro-internal/tests/mergeable_container/events_and_paths.rs @@ -0,0 +1,266 @@ +//! Path resolution, deep value, subscriptions, undo, and has_container. + +#[path = "common.rs"] +mod common; +use common::doc; + +use std::sync::{Arc, Mutex}; + +use loro_internal::{event::Index, HandlerTrait, ToJson}; +use serde_json::json; + +#[test] +#[cfg(feature = "counter")] +fn get_path_returns_logical_parent_path_for_mergeable_child() { + let doc = doc(1); + let root = doc.get_map("state"); + let counter = root.ensure_mergeable_counter("revision").unwrap(); + // Exercise the cid path directly; child-side wiring needed to keep + // mutating ops alive arrives in a later commit. + let _ = counter.increment(1.0); + + let path = doc + .get_path_to_container(&counter.id()) + .expect("mergeable counter should have a logical path"); + let indexes = path + .iter() + .map(|(_, index)| index.clone()) + .collect::<Vec<_>>(); + assert_eq!( + indexes, + vec![Index::Key("state".into()), Index::Key("revision".into()),], + "mergeable child path should walk logical parent edges, not the synthetic Root name", + ); +} + +#[test] +#[cfg(feature = "counter")] +fn deep_value_nests_mergeable_child_under_parent_and_hides_synthetic_root() { + let doc = doc(1); + let root = doc.get_map("state"); + let counter = root.ensure_mergeable_counter("revision").unwrap(); + counter.increment(2.0).unwrap(); + + assert_eq!( + doc.get_deep_value().to_json_value(), + json!({ "state": { "revision": 2.0 } }) + ); +} + +/// `ensure_mergeable_*` writes a marker op into the parent map, which +/// realizes the child immediately (loro-dev/loro#759). So an unmutated +/// mergeable child IS visible in deep value, rendered as its empty default. +/// Because the marker is a real op, every peer that imports it agrees +/// on this view — there is no originating-peer divergence. +#[test] +fn deep_value_shows_unmutated_mergeable_child_as_empty() { + let a = doc(1); + let _child = a.get_map("state").ensure_mergeable_map("nested").unwrap(); + a.commit_then_renew(); + + assert_eq!( + a.get_deep_value().to_json_value(), + json!({ "state": { "nested": {} } }), + "the marker realizes the child; it shows as its empty default", + ); +} + +/// Subscribing to the *parent* map must receive events when one of its +/// mergeable children is mutated: subscriptions on ancestor containers should +/// observe deltas from mergeable descendants, not only subscriptions on the +/// mergeable child itself. +#[test] +#[cfg(feature = "counter")] +fn parent_map_subscription_receives_mergeable_child_events() { + let doc = doc(1); + let root = doc.get_map("state"); + let counter = root.ensure_mergeable_counter("revision").unwrap(); + + let received: Arc<Mutex<Vec<Vec<Index>>>> = Arc::new(Mutex::new(Vec::new())); + let received_clone = received.clone(); + let _sub = doc.subscribe( + &root.id(), + Arc::new(move |event| { + let mut g = received_clone.lock().unwrap(); + for container_diff in event.events.iter() { + g.push( + container_diff + .path + .iter() + .map(|(_, idx)| idx.clone()) + .collect::<Vec<_>>(), + ); + } + }), + ); + + counter.increment(1.0).unwrap(); + doc.commit_then_renew(); + + let captured = received.lock().unwrap(); + assert!( + captured.iter().any(|path| path + .iter() + .any(|idx| matches!(idx, Index::Key(k) if &**k == "revision"))), + "parent map subscriber should see an event whose path includes the mergeable child's key 'revision'; got {captured:?}", + ); +} + +/// A subscription on the mergeable child's cid must receive events when the +/// child is mutated, symmetric to the existing parent-map subscription test. +#[test] +#[cfg(feature = "counter")] +fn mergeable_child_subscription_receives_own_events() { + let doc = doc(1); + let counter = doc + .get_map("state") + .ensure_mergeable_counter("revision") + .unwrap(); + + let count: Arc<Mutex<usize>> = Arc::new(Mutex::new(0)); + let count_clone = count.clone(); + let _sub = doc.subscribe( + &counter.id(), + Arc::new(move |_event| { + *count_clone.lock().unwrap() += 1; + }), + ); + + counter.increment(1.0).unwrap(); + doc.commit_then_renew(); + counter.increment(2.0).unwrap(); + doc.commit_then_renew(); + + let observed = *count.lock().unwrap(); + assert!( + observed >= 2, + "mergeable-child subscription must fire at least once per commit; got {observed} events" + ); +} + +/// Mutations on a mergeable child must be undoable. Undoing reverts the +/// child's value; the parent marker persists (because it isn't the +/// increment op being undone). +#[test] +#[cfg(feature = "counter")] +fn undo_manager_reverts_mergeable_counter_mutation() { + use loro_internal::UndoManager; + + let doc = doc(1); + let counter = doc + .get_map("state") + .ensure_mergeable_counter("revision") + .unwrap(); + let undo = UndoManager::new(&doc); + + counter.increment(5.0).unwrap(); + doc.commit_then_renew(); + assert_eq!(counter.get_value().to_json_value(), json!(5.0)); + + let did_undo = undo.undo().expect("undo must succeed"); + assert!(did_undo, "undo must report it did something"); + + // The mergeable child still exists (registration is not an op), but its + // value is back to zero. + assert_eq!( + counter.get_value().to_json_value(), + json!(0.0), + "undo must revert the increment" + ); +} + +/// Mergeable Roots have a deterministic `ContainerID::Root` in a reserved namespace, +/// but they are conceptually parented to a regular Map. The top-level root enumeration +/// (driven by `DocState::preferred_root_containers`, surfaced through +/// `LoroDoc::get_value`) must NOT include the synthetic mergeable Root — otherwise +/// the doc would expose a top-level key in the `🤝:` namespace alongside the real +/// roots. +/// +/// This guards the `id.is_mergeable()` skip in `preferred_root_containers` against +/// accidental removal: without it, peers would see two top-level entries (the actual +/// parent map plus the synthetic mergeable root) instead of one. +#[test] +#[cfg(feature = "counter")] +fn top_level_root_enumeration_skips_mergeable_roots() { + use loro_common::MERGEABLE_NAMESPACE_PREFIX; + + let doc = doc(1); + let root = doc.get_map("state"); + let counter = root.ensure_mergeable_counter("revision").unwrap(); + counter.increment(1.0).unwrap(); + doc.commit_then_renew(); + + // Sanity: the mergeable cid carries the synthetic namespace prefix. + let mergeable_cid = counter.id(); + assert!(mergeable_cid.is_mergeable()); + + // `get_value()` returns a Map keyed by top-level root names. The mergeable cid's + // synthetic Root name must NOT appear here. + let top_level = doc.get_value().to_json_value(); + let map = top_level + .as_object() + .expect("top-level doc value must be a JSON object"); + let keys: Vec<&str> = map.keys().map(|s| s.as_str()).collect(); + assert!( + keys.iter().any(|k| *k == "state"), + "real parent root 'state' must appear in top-level enumeration; got {keys:?}" + ); + assert!( + keys.iter() + .all(|k| !k.starts_with(MERGEABLE_NAMESPACE_PREFIX)), + "no mergeable-namespace Root name must appear at the top level; got {keys:?}" + ); + // Even more strictly: the synthetic root's exact name must not be a top-level key. + let synthetic_name = match &mergeable_cid { + loro_common::ContainerID::Root { name, .. } => name.to_string(), + _ => unreachable!("mergeable cid is always a Root"), + }; + assert!( + !keys.iter().any(|k| *k == synthetic_name), + "synthetic mergeable root name {synthetic_name:?} must not be in top-level keys {keys:?}" + ); + + // Deep value must show the mergeable child nested under its logical parent, not as a + // sibling top-level entry. + assert_eq!( + doc.get_deep_value().to_json_value(), + json!({ "state": { "revision": 1.0 } }), + "mergeable child must be nested under its logical parent, not surfaced at the top level" + ); +} + +/// `LoroDoc::has_container(cid)` must return `false` for a mergeable cid +/// that has never been written to, and `true` after the child has been +/// mutated. Mergeable existence depends on state, not on the name shape, so +/// the short-circuit for plain `Root` ids must skip mergeable namespace cids. +#[test] +#[cfg(feature = "counter")] +fn has_container_reports_false_for_unwritten_mergeable_child() { + use loro_common::{ContainerID, ContainerType}; + + let doc = doc(1); + let root = doc.get_map("state"); + + // Build the deterministic mergeable cid by hand, WITHOUT calling + // ensure_mergeable_counter (which would write the marker). + let parent_id = root.id(); + let unwritten_cid = ContainerID::new_mergeable(&parent_id, "revision", ContainerType::Counter); + assert!(unwritten_cid.is_mergeable()); + assert!( + !doc.has_container(&unwritten_cid), + "has_container must report false for an unwritten mergeable cid" + ); + + // Now actually create and mutate the child. has_container must flip to true. + let counter = root.ensure_mergeable_counter("revision").unwrap(); + counter.increment(1.0).unwrap(); + assert_eq!(counter.id(), unwritten_cid, "cid is deterministic"); + assert!( + doc.has_container(&unwritten_cid), + "has_container must report true after the mergeable child has state" + ); + + // Regular root containers still report true as before (regression guard). + let regular_root = ContainerID::new_root("state", ContainerType::Map); + assert!(doc.has_container(®ular_root)); +} diff --git a/vendor/loro-internal/tests/mergeable_container/pending.rs b/vendor/loro-internal/tests/mergeable_container/pending.rs new file mode 100644 index 0000000..260f2ed --- /dev/null +++ b/vendor/loro-internal/tests/mergeable_container/pending.rs @@ -0,0 +1,53 @@ +//! Importing ops on mergeable children whose causal dependencies (the child's creation +//! and/or its parent map) have not arrived yet must be buffered as pending, not panic. +//! +//! Regression for the `unreachable`/`Option::unwrap()` trap in `ContainerWrapper::new` when a +//! pending change referenced a mergeable container under a not-yet-imported parent map. Mergeable +//! cids live in the `ContainerID::Root` namespace, so the pending-root materialization path used +//! to treat them as ordinary roots and eagerly build their state — but a mergeable container is a +//! logical *child* whose depth cannot be resolved before its parent exists. + +#[path = "common.rs"] +mod common; +use common::doc; + +use loro_internal::{cursor::PosType, handler::MapHandler, loro::ExportMode}; + +#[test] +fn import_edit_on_mergeable_child_under_normal_map_before_creation() { + // root map -> Normal child map `m` -> mergeable text `body` under `m`. + // The mergeable child's parent is a Normal (non-root) container, so delivering the edit + // without the creation exercises the unresolved-depth path that used to panic. + let a = doc(1); + let root = a.get_map("root"); + let m = root + .insert_container("m", MapHandler::new_detached()) + .unwrap(); + a.commit_then_renew(); + let after_create = a.oplog_vv(); + + // Capture the creation-only payload *now*, before the edit exists, so the second import + // delivers strictly the missing dependency. If we exported it after the edit, it would also + // re-include the edit and the convergence assert could pass even if the pending edit was lost. + let creation_only = a.export(ExportMode::updates(&Default::default())).unwrap(); + + let body = m.ensure_mergeable_text("body").unwrap(); + body.insert(0, "hi", PosType::Unicode).unwrap(); + a.commit_then_renew(); + + // Only the edit commit, without the creation it causally depends on. + let edit_only = a.export(ExportMode::updates(&after_create)).unwrap(); + + let b = doc(2); + // Must buffer as pending instead of panicking, and actually retain the edit as pending. + let status = b.import(&edit_only).unwrap(); + assert!( + status.pending.is_some(), + "edit on a mergeable child whose creation is missing must be buffered as pending" + ); + + // Delivering the missing creation (which does NOT contain the edit) replays the pending + // edit and converges. + b.import(&creation_only).unwrap(); + assert_eq!(a.get_deep_value(), b.get_deep_value()); +} diff --git a/vendor/loro-internal/tests/mergeable_container/snapshot.rs b/vendor/loro-internal/tests/mergeable_container/snapshot.rs new file mode 100644 index 0000000..811cb57 --- /dev/null +++ b/vendor/loro-internal/tests/mergeable_container/snapshot.rs @@ -0,0 +1,357 @@ +//! Snapshot and update-import round-trips, including LWW recovery. + +#[path = "common.rs"] +mod common; +use common::{doc, sync}; + +use loro_internal::{cursor::PosType, event::Index, loro::ExportMode, HandlerTrait, ToJson}; +use serde_json::json; + +/// Snapshot round-trip must preserve the parent edges (logical path) and +/// state values for mergeable child containers nested inside other mergeable +/// child containers. +/// +/// Source peer creates `state` → mergeable map `profile` → mergeable counter +/// `revision`, mutates each, then exports a snapshot. Importing into a fresh +/// peer must reproduce the same deep value and the same logical path for +/// the counter. +#[test] +#[cfg(feature = "counter")] +fn snapshot_roundtrip_preserves_mergeable_parent_edges_and_values() { + let source = doc(1); + let root = source.get_map("state"); + let nested = root.ensure_mergeable_map("profile").unwrap(); + nested.insert("name", "Ada").unwrap(); + let counter = nested.ensure_mergeable_counter("revision").unwrap(); + counter.increment(3.0).unwrap(); + let counter_id = counter.id(); + + let snapshot = source.export(ExportMode::Snapshot).unwrap(); + let imported = doc(2); + imported.import(&snapshot).unwrap(); + + let path = imported + .get_path_to_container(&counter_id) + .expect("mergeable counter must have a logical path after snapshot import"); + let indexes = path + .iter() + .map(|(_, index)| index.clone()) + .collect::<Vec<_>>(); + assert_eq!( + indexes, + vec![ + Index::Key("state".into()), + Index::Key("profile".into()), + Index::Key("revision".into()), + ], + "imported counter should walk logical parent edges across two mergeable hops" + ); + + assert_eq!( + imported.get_deep_value().to_json_value(), + source.get_deep_value().to_json_value(), + "deep value of the imported doc must match the source after snapshot round-trip" + ); + + let imported_counter = imported + .get_map("state") + .ensure_mergeable_map("profile") + .unwrap() + .ensure_mergeable_counter("revision") + .unwrap(); + assert_eq!(imported_counter.id(), counter_id); +} + +/// Peer B imports updates that originated from peer A's `ensure_mergeable_counter` +/// + `increment` calls, but peer B never locally called `ensure_mergeable_*`. +/// After import, peer B's deep value, container enumeration, and path +/// resolution for the mergeable child must all reflect the imported state. +#[test] +#[cfg(feature = "counter")] +fn update_import_resolves_mergeable_logical_edge_on_receiver() { + let a = doc(1); + let b = doc(2); + + let a_counter = a + .get_map("state") + .ensure_mergeable_counter("revision") + .unwrap(); + a_counter.increment(5.0).unwrap(); + let a_counter_id = a_counter.id(); + a.commit_then_renew(); + + // Peer B imports A's updates WITHOUT first calling ensure_mergeable_counter. + let updates = a.export(ExportMode::updates(&b.oplog_vv())).unwrap(); + b.import(&updates).unwrap(); + + // Path resolution must work directly from the deterministic cid. Calling the getter first + // would rewrite the marker and could hide resolver bugs after import. + let path = b.get_path_to_container(&a_counter_id).expect("path"); + let indexes = path.iter().map(|(_, idx)| idx.clone()).collect::<Vec<_>>(); + assert_eq!( + indexes, + vec![Index::Key("state".into()), Index::Key("revision".into())] + ); + + assert_eq!( + b.get_deep_value().to_json_value(), + json!({ "state": { "revision": 5.0 } }), + "after update import, peer B's deep value must include the mergeable child" + ); + + // Peer B then locally resolves the mergeable handler — this must return + // the same cid as the one peer A wrote, and the existing value. + let b_counter = b + .get_map("state") + .ensure_mergeable_counter("revision") + .unwrap(); + assert_eq!(b_counter.id(), a_counter_id); + assert_eq!(b_counter.get_value().to_json_value(), json!(5.0)); +} + +/// Create a mergeable counter but never mutate it, then export a snapshot. +/// `ensure_mergeable_*` writes a marker into the parent map's value table, +/// which is ordinary map state and rides through the snapshot like any other +/// value (loro-dev/loro#759). So the receiving peer resolves the marker +/// to the same deterministic cid and sees the child as its empty default — no +/// special recovery is needed. +#[test] +#[cfg(feature = "counter")] +fn unmutated_mergeable_child_survives_snapshot_via_marker() { + let a = doc(1); + let counter = a + .get_map("state") + .ensure_mergeable_counter("revision") + .unwrap(); + let counter_id = counter.id(); + // Deliberately no increment. Commit anyway so any pending state is flushed. + a.commit_then_renew(); + + let snapshot = a.export(ExportMode::Snapshot).unwrap(); + let b = doc(2); + b.import(&snapshot).unwrap(); + + let has_container_before_path = b.has_container(&counter_id); + let path = b + .get_path_to_container(&counter_id) + .expect("unmutated mergeable child must resolve from marker"); + let indexes = path.iter().map(|(_, idx)| idx.clone()).collect::<Vec<_>>(); + assert_eq!( + indexes, + vec![Index::Key("state".into()), Index::Key("revision".into())] + ); + assert_eq!( + b.has_container(&counter_id), + has_container_before_path, + "path lookup must not change has_container semantics for mergeable cids" + ); + + // The binary marker rides through the snapshot as a normal map value, so B + // resolves the same deterministic cid and renders it as an empty counter. + assert_eq!( + b.get_deep_value().to_json_value(), + json!({ "state": { "revision": 0.0 } }), + "marker survives snapshot round-trip; child resolves to its empty default", + ); + + let b_counter = b + .get_map("state") + .ensure_mergeable_counter("revision") + .unwrap(); + assert_eq!(b_counter.id(), counter_id, "cid still deterministic"); + assert_eq!(b_counter.get_value().to_json_value(), json!(0.0)); +} + +/// Snapshot import where both peers registered the same `(key, kind)`: +/// deterministic cids match, recovery walk converges, content from peer A +/// wins through normal CRDT merge. +#[test] +fn snapshot_import_same_type_collision_converges() { + let a = doc(1); + let a_text = a.get_map("state").ensure_mergeable_text("notes").unwrap(); + a_text.insert(0, "A", PosType::Unicode).unwrap(); + a.commit_then_renew(); + let snapshot = a.export(ExportMode::Snapshot).unwrap(); + + let b = doc(2); + let b_text = b.get_map("state").ensure_mergeable_text("notes").unwrap(); + b_text.insert(0, "B", PosType::Unicode).unwrap(); + b.commit_then_renew(); + assert_eq!(a_text.id(), b_text.id(), "cids must match before import"); + + b.import(&snapshot).unwrap(); + + // Sync back so A sees both. + sync(&a, &b); + let value = a.get_deep_value().to_json_value(); + assert!( + value == json!({ "state": { "notes": "AB" } }) + || value == json!({ "state": { "notes": "BA" } }), + "both edits must survive on same-type collision; got {value}" + ); + assert_eq!(b.get_deep_value().to_json_value(), value); +} + +/// Snapshot import where the LOCAL peer registered a different kind for the same key than the +/// SNAPSHOT peer. The two binary markers compete in the parent map's slot for "k"; the parent +/// map's regular LWW deterministically resolves to one, so exactly one kind is visible. Both +/// containers' states are preserved; the loser is reachable by explicit lookup. +#[test] +fn snapshot_import_different_type_collision_resolves_by_lww() { + let a = doc(1); + let a_text = a.get_map("state").ensure_mergeable_text("k").unwrap(); + a_text.insert(0, "hello", PosType::Unicode).unwrap(); + a.commit_then_renew(); + let snapshot = a.export(ExportMode::Snapshot).unwrap(); + + let b = doc(2); + let b_map = b.get_map("state").ensure_mergeable_map("k").unwrap(); + b_map.insert("flag", true).unwrap(); + b.commit_then_renew(); + assert_ne!( + a_text.id(), + b_map.id(), + "different kinds under the same key MUST produce different cids" + ); + + b.import(&snapshot).expect("import must not fail"); + + // Exactly one kind is visible in deep value (whichever marker won the Map LWW). + let value = b.get_deep_value().to_json_value(); + let k = &value["state"]["k"]; + let visible_kinds = [k.is_string(), k.is_object()]; + assert_eq!( + visible_kinds.iter().filter(|x| **x).count(), + 1, + "exactly one kind must be visible after LWW; got {k:?}" + ); + + // Both getters still succeed (each rewrites the marker to its kind). Neither errors — + // requesting a kind is a kind change, not a conflict. + let _ = b.get_map("state").ensure_mergeable_text("k").unwrap(); + let _ = b.get_map("state").ensure_mergeable_map("k").unwrap(); +} + +/// After snapshot import resolves `"k"` to a Text marker on the receiver, a local +/// `ensure_mergeable_map("k")` does NOT error — it rewrites the marker to Map (a deliberate +/// kind change). The Text container stays reachable by name; requesting it again rewrites the +/// marker back to Text and resurfaces its preserved contents. +#[test] +fn different_kind_request_after_snapshot_is_a_kind_change() { + let a = doc(1); + let a_text = a.get_map("state").ensure_mergeable_text("k").unwrap(); + a_text.insert(0, "x", PosType::Unicode).unwrap(); + a.commit_then_renew(); + let snapshot = a.export(ExportMode::Snapshot).unwrap(); + + let b = doc(2); + b.import(&snapshot).unwrap(); + assert_eq!( + b.get_deep_value().to_json_value(), + json!({ "state": { "k": "x" } }), + "imported Text marker resolves to its content" + ); + + // Requesting a Map rewrites the marker to Map; no error. + let b_map = b.get_map("state").ensure_mergeable_map("k").unwrap(); + b_map.insert("flag", true).unwrap(); + b.commit_then_renew(); + assert_eq!( + b.get_deep_value().to_json_value(), + json!({ "state": { "k": { "flag": true } } }), + "different-kind request is a kind change, not an error" + ); + + // The Text is still reachable; requesting it again resurfaces its preserved content. + let b_text = b.get_map("state").ensure_mergeable_text("k").unwrap(); + assert_eq!(b_text.id(), a_text.id()); + b.commit_then_renew(); + assert_eq!( + b.get_deep_value().to_json_value(), + json!({ "state": { "k": "x" } }), + "re-requesting Text rewrites the marker back and resurfaces preserved content" + ); +} + +/// Shallow snapshot export must also preserve the LOSING kind's state in a concurrent-kind +/// conflict. The loser is not reachable through the parent's winning marker — its only +/// addressability is via the deterministic mergeable cid. The snapshot's alive-container walk has +/// to include mergeable cids as retention roots, otherwise `retain_keys` would silently GC the +/// loser, and a later `ensure_mergeable_<loser_kind>` on the receiver would resurface an empty +/// child instead of preserved contents. +#[test] +fn shallow_snapshot_preserves_losing_kind_state() { + let a = doc(1); + let a_text = a.get_map("state").ensure_mergeable_text("k").unwrap(); + a_text.insert(0, "from_a", PosType::Unicode).unwrap(); + let a_text_id = a_text.id(); + a.commit_then_renew(); + + // Advance A's clock past A's text marker, then rewrite the marker to Map (a kind change). + // The Map marker now wins LWW on A and is the visible kind; the Text child becomes the loser + // whose state lives only at its deterministic cid. + for i in 0..6 { + a.get_map("state").insert(&format!("noise_{i}"), i).unwrap(); + a.commit_then_renew(); + } + let a_map = a.get_map("state").ensure_mergeable_map("k").unwrap(); + a_map.insert("from_a_map", true).unwrap(); + a.commit_then_renew(); + + let frontiers = a.state_frontiers(); + let snapshot = a + .export(ExportMode::ShallowSnapshot(std::borrow::Cow::Owned( + frontiers, + ))) + .unwrap(); + + let b = doc(2); + b.import(&snapshot).unwrap(); + + // Sanity: Map marker won on B; Text is not the visible kind under "k". + let value = b.get_deep_value().to_json_value(); + assert!( + value["state"]["k"].is_object(), + "Map marker wins on B; got {value}" + ); + + // The loser's Text state must have ridden through the shallow snapshot. Re-requesting it + // rewrites the marker to Text and resurfaces the preserved "from_a" content. + let b_text = b.get_map("state").ensure_mergeable_text("k").unwrap(); + assert_eq!(b_text.id(), a_text_id, "deterministic cid is stable"); + assert_eq!( + b_text.get_value().to_json_value(), + json!("from_a"), + "losing-kind state must survive shallow snapshot export" + ); +} + +/// Shallow snapshot export should preserve mergeable child state and parent +/// edges on the receiver, the same as a full snapshot. +#[test] +#[cfg(feature = "counter")] +fn shallow_snapshot_roundtrip_preserves_mergeable_child() { + let a = doc(1); + let counter = a + .get_map("state") + .ensure_mergeable_counter("revision") + .unwrap(); + counter.increment(4.0).unwrap(); + a.commit_then_renew(); + + // ShallowSnapshot at current frontiers. + let frontiers = a.state_frontiers(); + let snapshot = a + .export(ExportMode::ShallowSnapshot(std::borrow::Cow::Owned( + frontiers, + ))) + .unwrap(); + + let b = doc(2); + b.import(&snapshot).unwrap(); + assert_eq!( + b.get_deep_value().to_json_value(), + json!({ "state": { "revision": 4.0 } }), + "shallow snapshot must carry mergeable child state and logical edge resolution" + ); +} diff --git a/vendor/loro-internal/tests/mergeable_container/type_conflict.rs b/vendor/loro-internal/tests/mergeable_container/type_conflict.rs new file mode 100644 index 0000000..e0091f3 --- /dev/null +++ b/vendor/loro-internal/tests/mergeable_container/type_conflict.rs @@ -0,0 +1,182 @@ +//! Concurrent different-kind creation, resolved by the parent map's marker LWW. +//! +//! When two peers create different kinds under the same key, each writes a different binary marker +//! into the parent map's slot. The parent map's regular LWW deterministically resolves to one +//! marker, so every peer surfaces the same kind; the loser's container stays reachable only by an +//! explicit `ensure_mergeable_<kind>` lookup (which rewrites the marker). +//! See loro-dev/loro#759. + +#[path = "common.rs"] +mod common; +use common::{doc, sync}; + +use loro_internal::{cursor::PosType, event::Index, loro::ExportMode, HandlerTrait, ToJson}; +use serde_json::json; + +/// Requesting a different kind under a key that already holds another kind's marker is a +/// deliberate, local kind change: it rewrites the marker. The new kind becomes active and +/// the new handler is usable. (This is the building block of the List -> Map -> List cycle.) +#[test] +fn local_different_kind_request_rewrites_the_marker() { + let doc = doc(1); + let root = doc.get_map("state"); + + let text = root.ensure_mergeable_text("field").unwrap(); + text.insert(0, "hello", PosType::Unicode).unwrap(); + doc.commit_then_renew(); + assert_eq!( + doc.get_deep_value().to_json_value(), + json!({ "state": { "field": "hello" } }) + ); + + // Switch the kind: this rewrites the marker to Map. + let map = root.ensure_mergeable_map("field").unwrap(); + map.insert("k", 1).unwrap(); + doc.commit_then_renew(); + assert_eq!( + doc.get_deep_value().to_json_value(), + json!({ "state": { "field": { "k": 1 } } }), + "requesting a different kind rewrites the marker to that kind" + ); +} + +/// When two competing-kind markers land in the same parent's slot under the same key during +/// import, the parent map's regular LWW deterministically picks one. The visible kind is the same +/// on every peer; the loser's container is still reachable by name but not surfaced by default. +#[test] +#[cfg(feature = "counter")] +fn different_kind_collision_resolves_by_map_lww_at_import() { + // Peer A: text under "k", low lamport. + let a = doc(1); + let a_text = a.get_map("state").ensure_mergeable_text("k").unwrap(); + a_text.insert(0, "from_a", PosType::Unicode).unwrap(); + let a_text_id = a_text.id(); + a.commit_then_renew(); + + // Peer B: map under "k", with a later lamport (advance B's clock first). + let b = doc(2); + let b_state = b.get_map("state"); + for i in 0..5 { + b_state.insert(&format!("filler_{i}"), i).unwrap(); + b.commit_then_renew(); + } + let b_map = b_state.ensure_mergeable_map("k").unwrap(); + b_map.insert("from_b", true).unwrap(); + let b_map_id = b_map.id(); + b.commit_then_renew(); + + // B imports A's snapshot. The Text and Map markers compete in B's map slot for "k"; B's Map + // marker has the higher lamport, so Map wins. + let snapshot = a.export(ExportMode::Snapshot).unwrap(); + b.import(&snapshot).unwrap(); + + // Check the direct cids before calling any getter. The losing Text cid must not have a logical + // path while the Map marker wins; the winning Map cid resolves from the marker. + assert!( + b.get_path_to_container(&a_text_id).is_none(), + "old Text cid must be inactive while the Map marker wins" + ); + let map_path = b + .get_path_to_container(&b_map_id) + .expect("winning Map cid must resolve from the parent marker"); + let indexes = map_path + .iter() + .map(|(_, index)| index.clone()) + .collect::<Vec<_>>(); + assert_eq!( + indexes, + vec![Index::Key("state".into()), Index::Key("k".into())] + ); + + let value = b.get_deep_value().to_json_value(); + let k_value = &value["state"]["k"]; + assert!( + k_value.is_object(), + "Map marker won the LWW; got {k_value:?}" + ); + assert_eq!(k_value["from_b"], json!(true)); + + // The loser's Text container is still reachable by an explicit ensure_mergeable_text — which + // rewrites the marker back to Text (a local kind change), so it now resurfaces. + let b_text = b.get_map("state").ensure_mergeable_text("k").unwrap(); + assert_eq!(b_text.id(), a_text_id); + assert_eq!( + b_text.get_value().to_json_value(), + json!("from_a"), + "loser's container is preserved and reachable by name" + ); +} + +/// Three peers each create a different kind under the same key and mutate it once. After a full +/// round-robin sync, every peer's parent-map LWW resolves to the same marker, so all agree +/// on exactly one visible kind. +#[test] +#[cfg(feature = "counter")] +fn three_peer_different_kind_conflict_converges() { + let a = doc(1); + let b = doc(2); + let c = doc(3); + + let a_text = a.get_map("state").ensure_mergeable_text("k").unwrap(); + a_text.insert(0, "from_a", PosType::Unicode).unwrap(); + a.commit_then_renew(); + + let b_map = b.get_map("state").ensure_mergeable_map("k").unwrap(); + b_map.insert("from_b", true).unwrap(); + b.commit_then_renew(); + + let c_list = c.get_map("state").ensure_mergeable_list("k").unwrap(); + c_list.insert(0, "from_c").unwrap(); + c.commit_then_renew(); + + sync(&a, &b); + sync(&b, &c); + sync(&a, &c); + sync(&a, &b); + + let va = a.get_deep_value().to_json_value(); + let vb = b.get_deep_value().to_json_value(); + let vc = c.get_deep_value().to_json_value(); + assert_eq!(va, vb, "A and B must agree"); + assert_eq!(vb, vc, "B and C must agree"); + + // Exactly one kind is visible under "k": Text -> string, Map -> object, List -> array. + let k = &va["state"]["k"]; + let survivors = [k.is_string(), k.is_object(), k.is_array()]; + let count: usize = survivors.iter().filter(|x| **x).count(); + assert_eq!( + count, 1, + "exactly one kind must be visible; got {survivors:?} for value {k:?}" + ); +} + +/// Concurrent SAME-kind creation: both peers write the identical marker, so the Map LWW +/// merge is a no-op and both contributions land in the one deterministic cid. +#[test] +fn concurrent_same_kind_creation_converges() { + let a = doc(1); + let b = doc(2); + + let a_list = a.get_map("state").ensure_mergeable_list("k").unwrap(); + a_list.insert(0, "from_a").unwrap(); + a.commit_then_renew(); + + let b_list = b.get_map("state").ensure_mergeable_list("k").unwrap(); + b_list.insert(0, "from_b").unwrap(); + b.commit_then_renew(); + + sync(&a, &b); + + let va = a.get_deep_value().to_json_value(); + assert_eq!(va, b.get_deep_value().to_json_value(), "peers converge"); + let items: Vec<&str> = va["state"]["k"] + .as_array() + .expect("k is a list") + .iter() + .map(|v| v.as_str().unwrap()) + .collect(); + assert!( + items.contains(&"from_a") && items.contains(&"from_b"), + "both contributions preserved; got {items:?}" + ); +} diff --git a/vendor/loro-internal/tests/mergeable_container/undo_redo.rs b/vendor/loro-internal/tests/mergeable_container/undo_redo.rs new file mode 100644 index 0000000..436ce00 --- /dev/null +++ b/vendor/loro-internal/tests/mergeable_container/undo_redo.rs @@ -0,0 +1,178 @@ +//! Undo/redo coverage for mergeable child markers. +//! +//! Map diffs expose active mergeable markers as `Container` values at read/event +//! boundaries. Applying those diffs must write the marker for the destination +//! parent/key instead of recreating the child as a regular container. + +#[path = "common.rs"] +mod common; +use common::doc; + +use loro_common::{ContainerID, LoroValue}; +use loro_internal::{handler::MapHandler, HandlerTrait, TreeParentId, UndoManager}; + +fn expect_container(value: Option<LoroValue>, label: &str) -> ContainerID { + match value { + Some(LoroValue::Container(id)) => id, + other => panic!("expected {label} to be a container value, got {other:?}"), + } +} + +#[test] +fn undo_redo_restores_mergeable_child_marker_on_map() { + let doc = doc(1); + let root = doc.get_map("state"); + let undo = UndoManager::new(&doc); + + let attrs = root.ensure_mergeable_map("attrs").unwrap(); + attrs.insert("type", "paragraph").unwrap(); + doc.commit_then_renew(); + let attrs_id = attrs.id(); + assert!(attrs_id.is_mergeable()); + + assert!(undo.undo().unwrap()); + assert_eq!(root.get("attrs"), None); + + assert!(undo.redo().unwrap()); + let restored_id = expect_container(root.get("attrs"), "restored attrs"); + assert_eq!( + restored_id, attrs_id, + "same parent/key should restore the same deterministic mergeable cid" + ); + + let restored_attrs = root.ensure_mergeable_map("attrs").unwrap(); + assert_eq!(restored_attrs.id(), attrs_id); + assert_eq!(restored_attrs.get("type"), Some("paragraph".into())); +} + +#[test] +fn undo_delete_restores_mergeable_child_marker_on_existing_map() { + let doc = doc(1); + let root = doc.get_map("state"); + let attrs = root.ensure_mergeable_map("attrs").unwrap(); + attrs.insert("type", "paragraph").unwrap(); + doc.commit_then_renew(); + let attrs_id = attrs.id(); + + let undo = UndoManager::new(&doc); + root.delete("attrs").unwrap(); + doc.commit_then_renew(); + assert_eq!(root.get("attrs"), None); + + assert!(undo.undo().unwrap()); + let restored_id = expect_container(root.get("attrs"), "restored attrs"); + assert_eq!( + restored_id, attrs_id, + "undoing a mergeable child delete should restore the marker for the same cid" + ); + + let restored_attrs = root.ensure_mergeable_map("attrs").unwrap(); + assert_eq!(restored_attrs.id(), attrs_id); + assert_eq!(restored_attrs.get("type"), Some("paragraph".into())); +} + +#[test] +fn undo_parent_map_delete_restores_nested_mergeable_marker() { + let doc = doc(1); + let root = doc.get_map("state"); + let parent = root + .insert_container("parent", MapHandler::new_detached()) + .unwrap(); + let attrs = parent.ensure_mergeable_map("attrs").unwrap(); + attrs.insert("type", "paragraph").unwrap(); + doc.commit_then_renew(); + + let undo = UndoManager::new(&doc); + root.delete("parent").unwrap(); + doc.commit_then_renew(); + assert_eq!(root.get("parent"), None); + + assert!(undo.undo().unwrap()); + let restored_parent = root + .get_child_handler("parent") + .unwrap() + .into_map() + .unwrap(); + let restored_attrs_id = expect_container(restored_parent.get("attrs"), "restored attrs"); + assert!( + restored_attrs_id.is_mergeable(), + "nested mergeable child must be restored as a marker, not a regular child cid" + ); + + let restored_attrs = restored_parent.ensure_mergeable_map("attrs").unwrap(); + assert_eq!(restored_attrs.id(), restored_attrs_id); + assert_eq!(restored_attrs.get("type"), Some("paragraph".into())); +} + +#[test] +fn undo_mergeable_parent_map_delete_resurfaces_nested_mergeable_child() { + let doc = doc(1); + let root = doc.get_map("state"); + let parent = root.ensure_mergeable_map("parent").unwrap(); + let attrs = parent.ensure_mergeable_map("attrs").unwrap(); + attrs.insert("type", "paragraph").unwrap(); + doc.commit_then_renew(); + let parent_id = parent.id(); + let attrs_id = attrs.id(); + + let undo = UndoManager::new(&doc); + root.delete("parent").unwrap(); + doc.commit_then_renew(); + assert_eq!(root.get("parent"), None); + + assert!(undo.undo().unwrap()); + let restored_parent_id = expect_container(root.get("parent"), "restored parent"); + assert_eq!(restored_parent_id, parent_id); + + let restored_parent = root.ensure_mergeable_map("parent").unwrap(); + let restored_attrs_id = expect_container(restored_parent.get("attrs"), "restored attrs"); + assert_eq!( + restored_attrs_id, attrs_id, + "reactivating a mergeable parent should resurface its nested mergeable child" + ); + let restored_attrs = restored_parent.ensure_mergeable_map("attrs").unwrap(); + assert_eq!(restored_attrs.get("type"), Some("paragraph".into())); +} + +#[test] +fn redo_restores_tree_node_mergeable_meta_child_as_marker() { + let doc = doc(1); + let tree = doc.get_tree("root"); + let root = tree.create(TreeParentId::Root).unwrap(); + tree.get_meta(root).unwrap().insert("name", "root").unwrap(); + + let target = tree.create(TreeParentId::Node(root)).unwrap(); + tree.get_meta(target) + .unwrap() + .insert("name", "target") + .unwrap(); + doc.commit_then_renew(); + + let undo = UndoManager::new(&doc); + let child = tree.create(TreeParentId::Root).unwrap(); + let child_meta = tree.get_meta(child).unwrap(); + child_meta.insert("name", "child").unwrap(); + let attrs = child_meta.ensure_mergeable_map("sys_attrs").unwrap(); + attrs.insert("type", "paragraph").unwrap(); + tree.mov(child, TreeParentId::Node(target)).unwrap(); + doc.commit_then_renew(); + + assert!(undo.undo().unwrap()); + assert!(undo.redo().unwrap()); + + let target_children = tree.children(&TreeParentId::Node(target)).unwrap(); + let restored_child = target_children + .into_iter() + .find(|node| tree.get_meta(*node).unwrap().get("name") == Some("child".into())) + .expect("redo should restore the child under target"); + let restored_meta = tree.get_meta(restored_child).unwrap(); + let restored_attrs_id = expect_container(restored_meta.get("sys_attrs"), "sys_attrs"); + assert!( + restored_attrs_id.is_mergeable(), + "tree meta child should remain a mergeable cid after redo" + ); + + let restored_attrs = restored_meta.ensure_mergeable_map("sys_attrs").unwrap(); + assert_eq!(restored_attrs.id(), restored_attrs_id); + assert_eq!(restored_attrs.get("type"), Some("paragraph".into())); +} diff --git a/vendor/loro-internal/tests/richtext.md b/vendor/loro-internal/tests/richtext.md new file mode 100644 index 0000000..49b575d --- /dev/null +++ b/vendor/loro-internal/tests/richtext.md @@ -0,0 +1,98 @@ +# Richtext Test Cases + +#### 0. Insert into bold span + +| Name | Text | +|:----------------|:-------------------------| +| Origin | `Hello World` | +| Concurrent A | `<b>Hello World</b>` | +| Concurrent B | `Hello New World` | +| Expected Result | `<b>Hello New World</b>` | + +#### 1. Merge Concurrent Styles + +| Name | Text | +|:----------------|:---------------------| +| Origin | Hello World | +| Concurrent A | `<b>Hello</b> World` | +| Concurrent B | `Hel<b>lo World</b>` | +| Expected Result | `<b>Hello World</b>` | + +#### 2. Concurrent insert text & remove style + +| Name | Text | +|:----------------|:-----------------------| +| Origin | `<b>Hello World</b>` | +| Concurrent A | `Hello <b>World</b>` | +| Concurrent B | `<b>Hello a World</b>` | +| Expected Result | `Hello a <b>World</b>` | + +#### 3. Concurrent insert text & style + +| Name | Text | +|:----------------|:-----------------------| +| Origin | `Hello World` | +| Concurrent A | `Hello <b>World</b>` | +| Concurrent B | `Hello a World` | +| Expected Result | `Hello a <b>World</b>` | + +#### 4. Concurrent text edit & style that shrink + +| Name | Text | +|:----------------|:---------------------------| +| Origin | `Hello World` | +| Concurrent A | `<link>Hello</link> World` | +| Concurrent B | `Hey World` | +| Expected Result | `<link>Hey</link> World` | + +#### 5. Local insertion expand rules + +> [**Hello**](https://www.google.com) World + +When insert a new character after "Hello", the new char should be bold but not link + +> [**Hello**](https://www.google.com)**t** World + + +| Name | Text | +|:----------------|:----------------------------------| +| Origin | `<b><link>Hello</link><b> World` | +| Expected Result | `<b><link>Hello</link>t<b> World` | + + +#### 6. Concurrent unbold + +In Peritext paper 2.3.2 + +| Name | Text | +|:----------------|:---------------------------------------------| +| Origin | `<b>The fox jumped</b> over the dog.` | +| Concurrent A | `The fox jumped over the dog.` | +| Concurrent B | `<b>The </b>fox<b> jumped</b> over the dog.` | +| Expected Result | `The fox jumped over the dog.` | + +#### 7. Bold & Unbold + +In Peritext paper 2.3.3 + +| Name | Text | +|:----------------|:---------------------------------------------| +| Origin | `<b>The fox jumped</b> over the dog.` | +| Concurrent A | `<b>The fox</b> jumped over the dog.` | +| Concurrent B | `<b>The</b> fox jumped over the <b>dog</b>.` | +| Expected Result | `<b>The</b> fox jumped over the <b>dog</b>.` | + +#### 8. Overlapped formatting + +In Peritext paper 3.2, example 3 + +| Name | Text | +|:----------------|:-----------------------------| +| Origin | The fox jumped. | +| Concurrent A | **The fox** jumped. | +| Concurrent B | The *fox jumped*. | +| Expected Result | **The _fox_**<i> jumped</i>. | + +#### 9. Multiple instances of the same mark + +![](https://i.postimg.cc/MTNGq8cH/Clean-Shot-2023-10-09-at-12-16-29-2x.png) diff --git a/vendor/loro-internal/tests/richtext.rs b/vendor/loro-internal/tests/richtext.rs new file mode 100644 index 0000000..5347357 --- /dev/null +++ b/vendor/loro-internal/tests/richtext.rs @@ -0,0 +1,426 @@ +//! All the tests in this file are based on [richtext.md] + +use std::ops::Range; + +use loro_common::LoroValue; +use loro_internal::{cursor::PosType, loro::ExportMode, LoroDoc, ToJson}; +use serde_json::json; + +fn init(s: &str) -> LoroDoc { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let richtext = doc.get_text("r"); + richtext.insert(0, s, PosType::Unicode).unwrap(); + doc +} + +fn clone(doc: &LoroDoc, peer_id: u64) -> LoroDoc { + let doc2 = LoroDoc::new_auto_commit(); + doc2.set_peer_id(peer_id).unwrap(); + doc2.import(&doc.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + doc2 +} + +#[derive(Debug)] +enum Kind { + Bold, + Italic, + Link, +} + +impl Kind { + fn key(&self) -> &str { + match self { + Kind::Bold => "bold", + Kind::Link => "link", + Kind::Italic => "italic", + } + } +} + +fn insert(doc: &LoroDoc, pos: usize, s: &str) { + let richtext = doc.get_text("r"); + richtext.insert(pos, s, PosType::Unicode).unwrap(); +} + +fn delete(doc: &LoroDoc, pos: usize, len: usize) { + let richtext = doc.get_text("r"); + richtext.delete(pos, len, PosType::Unicode).unwrap(); +} + +fn mark(doc: &LoroDoc, range: Range<usize>, kind: Kind) { + let richtext = doc.get_text("r"); + richtext + .mark( + range.start, + range.end, + kind.key(), + true.into(), + PosType::Event, + ) + .unwrap(); +} + +fn unmark(doc: &LoroDoc, range: Range<usize>, kind: Kind) { + let richtext = doc.get_text("r"); + richtext + .mark( + range.start, + range.end, + kind.key(), + false.into(), + PosType::Event, + ) + .unwrap(); +} + +fn mark_kv(doc: &LoroDoc, range: Range<usize>, key: &str, value: impl Into<LoroValue>) { + let richtext = doc.get_text("r"); + richtext + .mark(range.start, range.end, key, value.into(), PosType::Event) + .unwrap(); +} + +fn merge(a: &LoroDoc, b: &LoroDoc) { + a.import(&b.export(ExportMode::updates(&a.oplog_vv())).unwrap()) + .unwrap(); + b.import(&a.export(ExportMode::updates(&b.oplog_vv())).unwrap()) + .unwrap(); +} + +fn expect_result(doc: &LoroDoc, json: serde_json::Value) { + let richtext = doc.get_text("r"); + let s = richtext.get_richtext_value().to_json_value(); + assert_eq!( + &s, + &json, + "expect: {}, got: {}", + serde_json::to_string_pretty(&json).unwrap(), + serde_json::to_string_pretty(&s).unwrap() + ); +} + +#[test] +fn case0() { + let doc_a = init("Hello World"); + let doc_b = clone(&doc_a, 2); + mark(&doc_a, 0..11, Kind::Bold); + insert(&doc_b, 6, "New "); + merge(&doc_a, &doc_b); + expect_result( + &doc_a, + json!([{"insert":"Hello New World","attributes":{"bold":true}}]), + ); + doc_a.check_state_diff_calc_consistency_slow(); + doc_b.check_state_diff_calc_consistency_slow(); +} + +#[test] +fn case1() { + let doc_a = init("Hello World"); + let doc_b = clone(&doc_a, 2); + mark(&doc_a, 0..5, Kind::Bold); + mark(&doc_b, 3..11, Kind::Bold); + merge(&doc_a, &doc_b); + expect_result( + &doc_a, + json!([{"insert":"Hello World","attributes":{"bold":true}}]), + ); + doc_a.check_state_diff_calc_consistency_slow(); + doc_b.check_state_diff_calc_consistency_slow(); +} + +#[test] +fn case2() { + let doc_a = init("Hello World"); + mark(&doc_a, 0..11, Kind::Bold); + let doc_b = clone(&doc_a, 2); + unmark(&doc_a, 0..6, Kind::Bold); + insert(&doc_b, 5, " a"); + merge(&doc_a, &doc_b); + expect_result( + &doc_a, + json!([{"insert":"Hello a ","attributes":{"bold":false}},{"insert":"World","attributes":{"bold":true}}]), + ); + doc_a.check_state_diff_calc_consistency_slow(); + doc_b.check_state_diff_calc_consistency_slow(); +} + +/// | Name | Text | +/// |:----------------|:-----------------------| +/// | Origin | `Hello World` | +/// | Concurrent A | `Hello <b>World</b>` | +/// | Concurrent B | `Hello a World` | +/// | Expected Result | `Hello a <b>World</b>` | +/// +#[test] +fn case3() { + let doc_a = init("Hello World"); + let doc_b = clone(&doc_a, 2); + mark(&doc_a, 6..11, Kind::Bold); + insert(&doc_b, 5, " a"); + merge(&doc_a, &doc_b); + expect_result( + &doc_a, + json!([{"insert":"Hello a "},{"insert":"World","attributes":{"bold":true}}]), + ); + doc_a.check_state_diff_calc_consistency_slow(); + doc_b.check_state_diff_calc_consistency_slow(); +} + +/// | Name | Text | +/// |:----------------|:---------------------------| +/// | Origin | `Hello World` | +/// | Concurrent A | `<link>Hello</link> World` | +/// | Concurrent B | `Hey World` | +/// | Expected Result | `<link>Hey</link> World` | +#[test] +fn case4() { + let doc_a = init("Hello World"); + let doc_b = clone(&doc_a, 2); + mark(&doc_a, 0..5, Kind::Link); + delete(&doc_b, 2, 3); + expect_result(&doc_b, json!([{"insert":"He World"}])); + insert(&doc_b, 2, "y"); + expect_result(&doc_b, json!([{"insert":"Hey World"}])); + merge(&doc_a, &doc_b); + expect_result( + &doc_b, + json!([{"insert":"Hey","attributes":{"link":true}},{"insert":" World"}]), + ); + expect_result( + &doc_a, + json!([{"insert":"Hey","attributes":{"link":true}},{"insert":" World"}]), + ); + doc_a.check_state_diff_calc_consistency_slow(); + doc_b.check_state_diff_calc_consistency_slow(); +} + +/// When insert a new character after "Hello", the new char should be bold but not link +/// +/// | Name | Text | +/// |:----------------|:----------------------------------| +/// | Origin | `<b><link>Hello</link><b> World` | +/// | Expected Result | `<b><link>Hello</link>t<b> World` | +#[test] +fn case5() { + let doc = init("Hello World"); + mark(&doc, 0..5, Kind::Bold); + expect_result( + &doc, + serde_json::json!([ + {"insert": "Hello", "attributes": {"bold": true}}, + {"insert": " World"} + ]), + ); + mark(&doc, 0..5, Kind::Link); + expect_result( + &doc, + serde_json::json!([ + {"insert": "Hello", "attributes": {"bold": true, "link": true}}, + {"insert": " World"} + ]), + ); + insert(&doc, 5, "t"); + expect_result( + &doc, + serde_json::json!([ + {"insert": "Hello", "attributes": {"bold": true, "link": true}}, + {"insert": "t", "attributes": {"bold": true}}, + {"insert": " World"} + ]), + ); + doc.check_state_diff_calc_consistency_slow(); +} + +/// +/// | Name | Text | +/// |:----------------|:---------------------------------------------| +/// | Origin | `<b>The fox jumped</b> over the dog.` | +/// | Concurrent A | `The fox jumped over the dog.` | +/// | Concurrent B | `<b>The </b>fox<b> jumped</b> over the dog.` | +/// | Expected Result | `The fox jumped over the dog.` | +#[test] +fn case6() { + let doc_a = init("The fox jumped over the dog."); + mark(&doc_a, 0..3, Kind::Bold); + let doc_b = clone(&doc_a, 2); + unmark(&doc_a, 0..3, Kind::Bold); + unmark(&doc_b, 4..7, Kind::Bold); + merge(&doc_a, &doc_b); + expect_result( + &doc_a, + json!([ + {"insert":"The", "attributes": {"bold": false}}, + {"insert":" ",}, + {"insert":"fox", "attributes": {"bold": false}}, + {"insert":" jumped over the dog."} + ]), + ); + doc_a.check_state_diff_calc_consistency_slow(); + doc_b.check_state_diff_calc_consistency_slow(); +} + +/// | Name | Text | +/// |:----------------|:---------------------------------------------| +/// | Origin | `<b>The fox jumped</b> over the dog.` | +/// | Concurrent A | `<b>The fox</b> jumped over the dog.` | +/// | Concurrent B | `<b>The</b> fox jumped over the <b>dog</b>.` | +/// | Expected Result | `<b>The</b> fox jumped over the <b>dog</b>.` | +#[test] +fn case7() { + let doc_a = init("The fox jumped over the dog."); + mark(&doc_a, 0..14, Kind::Bold); + let doc_b = clone(&doc_a, 2); + unmark(&doc_a, 7..14, Kind::Bold); + unmark(&doc_b, 3..14, Kind::Bold); + mark(&doc_b, 24..27, Kind::Bold); + merge(&doc_a, &doc_b); + expect_result( + &doc_a, + serde_json::json!([ + {"insert": "The", "attributes": {"bold": true}}, + {"insert": " fox jumped", "attributes": {"bold": false}}, + {"insert": " over the "}, + {"insert": "dog", "attributes": {"bold": true}}, + {"insert": "."} + ]), + ); + doc_a.check_state_diff_calc_consistency_slow(); + doc_b.check_state_diff_calc_consistency_slow(); +} + +/// | Name | Text | +/// |:----------------|:-----------------------------| +/// | Origin | The fox jumped. | +/// | Concurrent A | **The fox** jumped. | +/// | Concurrent B | The *fox jumped*. | +/// | Expected Result | **The _fox_**<i> jumped</i>. | +#[test] +fn case8() { + let doc_a = init("The fox jumped."); + let doc_b = clone(&doc_a, 2); + mark(&doc_a, 0..7, Kind::Bold); + mark(&doc_a, 4..14, Kind::Italic); + merge(&doc_a, &doc_b); + expect_result( + &doc_a, + serde_json::json!([ + {"insert": "The ", "attributes": {"bold": true}}, + {"insert": "fox", "attributes": {"bold": true, "italic": true}}, + {"insert": " jumped", "attributes": {"italic": true}}, + {"insert": "."} + ]), + ); + doc_a.check_state_diff_calc_consistency_slow(); + doc_b.check_state_diff_calc_consistency_slow(); +} + +/// ![](https://i.postimg.cc/MTNGq8cH/Clean-Shot-2023-10-09-at-12-16-29-2x.png) +#[test] +fn case9() { + let doc_a = init("The fox jumped."); + let doc_b = clone(&doc_a, 2); + mark_kv(&doc_a, 0..7, "comment:alice", "alice comment"); + mark_kv(&doc_a, 4..14, "comment:bob", "bob comment"); + merge(&doc_a, &doc_b); + expect_result( + &doc_a, + serde_json::json!([ + {"insert": "The ", "attributes": {"comment:alice": "alice comment"}}, + {"insert": "fox", "attributes": {"comment:alice": "alice comment", "comment:bob": "bob comment"}}, + {"insert": " jumped", "attributes": {"comment:bob": "bob comment"}}, + {"insert": "."} + ]), + ); +} + +#[test] +fn insert_after_link() { + let doc_a = init("The fox jumped."); + let doc_b = clone(&doc_a, 2); + mark(&doc_a, 0..3, Kind::Link); + merge(&doc_a, &doc_b); + insert(&doc_a, 3, "a"); + merge(&doc_a, &doc_b); + expect_result( + &doc_a, + serde_json::json!([ + {"insert": "The", "attributes": {"link": true}}, + {"insert": "a fox jumped."}, + ]), + ); + expect_result( + &doc_b, + serde_json::json!([ + {"insert": "The", "attributes": {"link": true}}, + {"insert": "a fox jumped."}, + ]), + ); + doc_a.check_state_diff_calc_consistency_slow(); + doc_b.check_state_diff_calc_consistency_slow(); +} + +#[test] +fn redundant_mark_spanning_style_boundaries_creates_no_ops() { + let doc = init("Hello World"); + mark(&doc, 0..5, Kind::Bold); + // This range spans a style boundary, so it genuinely changes 5..11. + mark(&doc, 0..11, Kind::Bold); + doc.commit_then_renew(); + let vv = doc.oplog_vv(); + + // The whole text is already bold; re-asserting the mark must not record + // new ops, even though the range spans multiple style ranges. Every + // redundant mark op leaves a pair of style anchors in the container state + // forever, permanently slowing down styled reads. + mark(&doc, 0..11, Kind::Bold); + doc.commit_then_renew(); + assert_eq!(doc.oplog_vv(), vv); + expect_result( + &doc, + serde_json::json!([ + {"insert": "Hello World", "attributes": {"bold": true}}, + ]), + ); +} + +#[test] +fn redundant_unmark_spanning_style_boundaries_creates_no_ops() { + let doc = init("Hello World"); + mark(&doc, 0..5, Kind::Bold); + mark(&doc, 6..11, Kind::Bold); + unmark(&doc, 0..11, Kind::Bold); + doc.commit_then_renew(); + let vv = doc.oplog_vv(); + + unmark(&doc, 0..11, Kind::Bold); + doc.commit_then_renew(); + assert_eq!(doc.oplog_vv(), vv); + expect_result( + &doc, + serde_json::json!([ + {"insert": "Hello World", "attributes": {"bold": false}}, + ]), + ); +} + +#[test] +fn mark_that_changes_part_of_the_range_still_applies() { + let doc = init("Hello World"); + mark(&doc, 0..5, Kind::Bold); + doc.commit_then_renew(); + let vv = doc.oplog_vv(); + + // 0..5 is already bold but 5..11 is not, so this must not be skipped. + mark(&doc, 0..11, Kind::Bold); + doc.commit_then_renew(); + assert_ne!(doc.oplog_vv(), vv); + expect_result( + &doc, + serde_json::json!([ + {"insert": "Hello World", "attributes": {"bold": true}}, + ]), + ); +} diff --git a/vendor/loro-internal/tests/test.rs b/vendor/loro-internal/tests/test.rs new file mode 100644 index 0000000..99889b3 --- /dev/null +++ b/vendor/loro-internal/tests/test.rs @@ -0,0 +1,1546 @@ +use loro_common::{ + loro_value, ContainerID, ContainerType, IdSpan, LoroError, LoroResult, LoroValue, PeerID, ID, +}; +use loro_internal::awareness::EphemeralStore; +use loro_internal::sync::{AtomicBool, Mutex}; +use loro_internal::{ + cursor::PosType, + delta::ResolvedMapValue, + encoding::ImportStatus, + event::{Diff, EventTriggerKind}, + fx_map, + handler::{Handler, TextDelta, ValueOrHandler}, + loro::{CommitOptions, ExportMode}, + version::{Frontiers, VersionRange}, + ApplyDiff, HandlerTrait, ListHandler, LoroDoc, MapHandler, TextHandler, ToJson, TreeHandler, + TreeParentId, +}; +use rustc_hash::FxHashMap; +use serde_json::json; +use std::sync::Arc; + +#[test] +fn issue_502() -> LoroResult<()> { + let doc = LoroDoc::new_auto_commit(); + doc.get_map("map").insert("stringA", "Original data")?; + doc.commit_then_renew(); + doc.get_map("map").insert("stringA", "Updated data")?; + doc.attach(); + doc.get_map("map").insert("stringB", "Something else")?; + doc.commit_then_renew(); + Ok(()) +} + +#[test] +fn issue_225() -> LoroResult<()> { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_unicode(0, "123")?; + text.mark(0, 3, "bold", true.into(), PosType::Event)?; + // when apply_delta, the attributes of insert should override the current styles + text.apply_delta(&[ + TextDelta::Retain { + retain: 3, + attributes: None, + }, + TextDelta::Insert { + insert: "new".into(), + attributes: None, + }, + ])?; + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([{ "insert": "123", "attributes": { "bold": true } }, { "insert": "new" }]) + ); + + Ok(()) +} + +#[test] +fn issue_211() -> LoroResult<()> { + let doc1 = LoroDoc::new_auto_commit(); + let doc2 = LoroDoc::new_auto_commit(); + doc1.get_text("text").insert_unicode(0, "T")?; + doc2.merge(&doc1)?; + let v0 = doc1.oplog_frontiers(); + doc1.get_text("text").insert_unicode(1, "A")?; + doc2.get_text("text").insert_unicode(1, "B")?; + doc1.checkout(&v0)?; + doc2.checkout(&v0)?; + doc1.checkout_to_latest(); + doc2.checkout_to_latest(); + // let v1_of_doc1 = doc1.oplog_frontiers(); + let v1_of_doc2 = doc2.oplog_frontiers(); + doc2.get_text("text").insert_unicode(2, "B")?; + doc2.checkout(&v1_of_doc2)?; + doc2.checkout(&v0)?; + assert_eq!( + doc2.get_deep_value().to_json_value(), + json!({ + "text": "T" + }) + ); + Ok(()) +} + +#[test] +fn mark_with_the_same_key_value_should_be_skipped() { + let a = LoroDoc::new_auto_commit(); + let text = a.get_text("text"); + text.insert_unicode(0, "Hello world!").unwrap(); + text.mark(0, 11, "bold", "value".into(), PosType::Event) + .unwrap(); + a.commit_then_renew(); + let v = a.oplog_vv(); + text.mark(0, 5, "bold", "value".into(), PosType::Event) + .unwrap(); + a.commit_then_renew(); + let new_v = a.oplog_vv(); + // new mark should be ignored, so vv should be the same + assert_eq!(v, new_v); +} + +#[test] +fn event_from_checkout() { + let a = LoroDoc::new_auto_commit(); + let sub = a.subscribe_root(Arc::new(|event| { + assert!(matches!( + event.event_meta.by, + EventTriggerKind::Checkout | EventTriggerKind::Local + )); + })); + a.get_text("text").insert_unicode(0, "hello").unwrap(); + a.commit_then_renew(); + let version = a.oplog_frontiers(); + a.get_text("text").insert_unicode(0, "hello").unwrap(); + a.commit_then_renew(); + sub.unsubscribe(); + let ran = Arc::new(AtomicBool::new(false)); + let ran_cloned = ran.clone(); + let _g = a.subscribe_root(Arc::new(move |event| { + assert!(event.event_meta.by.is_checkout()); + ran.store(true, std::sync::atomic::Ordering::Relaxed); + })); + a.checkout(&version).unwrap(); + assert!(ran_cloned.load(std::sync::atomic::Ordering::Relaxed)); +} + +#[test] +fn handler_in_event() { + let doc = LoroDoc::new_auto_commit(); + let _g = doc.subscribe_root(Arc::new(|e| { + dbg!(&e); + let value = e.events[0] + .diff + .as_list() + .unwrap() + .iter() + .next() + .unwrap() + .as_replace() + .unwrap() + .0 + .iter() + .next() + .unwrap(); + assert!(matches!(value, ValueOrHandler::Handler(Handler::Text(_)))); + })); + let list = doc.get_list("list"); + list.insert_container(0, TextHandler::new_detached()) + .unwrap(); + doc.commit_then_renew(); +} + +#[test] +fn out_of_bound_test() { + let a = LoroDoc::new_auto_commit(); + a.get_text("text").insert_unicode(0, "Hello").unwrap(); + a.get_list("list").insert(0, "Hello").unwrap(); + a.get_list("list").insert(1, "Hello").unwrap(); + // expect out of bound err + let err = a.get_text("text").insert_unicode(6, "Hello").unwrap_err(); + assert!(matches!(err, loro_common::LoroError::OutOfBound { .. })); + let err = a.get_text("text").delete_unicode(3, 5).unwrap_err(); + assert!(matches!(err, loro_common::LoroError::OutOfBound { .. })); + let err = a + .get_text("text") + .mark(0, 8, "h", 5.into(), PosType::Event) + .unwrap_err(); + assert!(matches!(err, loro_common::LoroError::OutOfBound { .. })); + let _err = a + .get_text("text") + .mark(3, 0, "h", 5.into(), PosType::Event) + .unwrap_err(); + let err = a.get_list("list").insert(6, "Hello").unwrap_err(); + assert!(matches!(err, loro_common::LoroError::OutOfBound { .. })); + let err = a.get_list("list").delete(3, 2).unwrap_err(); + assert!(matches!(err, loro_common::LoroError::OutOfBound { .. })); + let err = a + .get_list("list") + .insert_container(3, MapHandler::new_detached()) + .unwrap_err(); + assert!(matches!(err, loro_common::LoroError::OutOfBound { .. })); +} + +#[test] +fn list() { + let a = LoroDoc::new_auto_commit(); + a.get_list("list").insert(0, "Hello").unwrap(); + assert_eq!(a.get_list("list").get(0).unwrap(), LoroValue::from("Hello")); + let map = a + .get_list("list") + .insert_container(1, MapHandler::new_detached()) + .unwrap(); + map.insert("Hello", LoroValue::from("u")).unwrap(); + let pos = map + .insert_container("pos", MapHandler::new_detached()) + .unwrap(); + pos.insert("x", 0).unwrap(); + pos.insert("y", 100).unwrap(); + + let cid = map.id(); + let id = a.get_list("list").get(1); + assert_eq!(id.as_ref().unwrap().as_container().unwrap(), &cid); + let map = a.get_map(id.unwrap().into_container().unwrap()); + let new_pos = a.get_map(map.get("pos").unwrap().into_container().unwrap()); + assert_eq!( + new_pos.get_deep_value().to_json_value(), + json!({ + "x": 0, + "y": 100, + }) + ); +} + +#[test] +fn richtext_mark_event() { + let a = LoroDoc::new_auto_commit(); + let _g = a.subscribe( + &a.get_text("text").id(), + Arc::new(|e| { + let delta = e.events[0].diff.as_text().unwrap(); + assert_eq!( + delta.to_json_value(), + json!([ + {"insert": "He", "attributes": {"bold": true}}, + {"insert": "ll", "attributes": {"bold": null}}, + {"insert": "o", "attributes": {"bold": true}} + ]) + ) + }), + ); + a.get_text("text").insert_unicode(0, "Hello").unwrap(); + a.get_text("text") + .mark(0, 5, "bold", true.into(), PosType::Event) + .unwrap(); + a.get_text("text") + .mark(2, 4, "bold", LoroValue::Null, PosType::Event) + .unwrap(); + let _ = a.implicit_commit_then_stop(); + let b = LoroDoc::new_auto_commit(); + let _g = b.subscribe( + &a.get_text("text").id(), + Arc::new(|e| { + let delta = e.events[0].diff.as_text().unwrap(); + assert_eq!( + delta.to_json_value(), + json!([ + {"insert": "He", "attributes": {"bold": true}}, + {"insert": "ll", "attributes": {"bold": null}}, + {"insert": "o", "attributes": {"bold": true}} + ]) + ) + }), + ); + b.merge(&a).unwrap(); +} + +#[test] +fn concurrent_richtext_mark_event() { + let a = LoroDoc::new_auto_commit(); + let b = LoroDoc::new_auto_commit(); + let c = LoroDoc::new_auto_commit(); + a.get_text("text").insert_unicode(0, "Hello").unwrap(); + b.merge(&a).unwrap(); + c.merge(&a).unwrap(); + b.get_text("text") + .mark(0, 3, "bold", true.into(), PosType::Event) + .unwrap(); + c.get_text("text") + .mark(1, 4, "link", true.into(), PosType::Event) + .unwrap(); + b.merge(&c).unwrap(); + let sub_id = a.subscribe( + &a.get_text("text").id(), + Arc::new(|e| { + let delta = e.events[0].diff.as_text().unwrap(); + assert_eq!( + delta.to_json_value(), + json!([ + {"retain": 1, "attributes": {"bold": true, }}, + {"retain": 2, "attributes": {"bold": true, "link": true}}, + {"retain": 1, "attributes": {"link": true}}, + ]) + ) + }), + ); + + a.merge(&b).unwrap(); + sub_id.unsubscribe(); + + let sub_id = a.subscribe( + &a.get_text("text").id(), + Arc::new(|e| { + let delta = e.events[0].diff.as_text().unwrap(); + assert_eq!( + delta.to_json_value(), + json!([ + { + "retain": 2, + }, + { + "retain": 1, + "attributes": {"bold": null, "link": true} + } + ]) + ) + }), + ); + + b.get_text("text") + .mark(2, 3, "bold", LoroValue::Null, PosType::Event) + .unwrap(); + a.merge(&b).unwrap(); + sub_id.unsubscribe(); + let _g = a.subscribe( + &a.get_text("text").id(), + Arc::new(|e| { + for container_diff in e.events { + let delta = container_diff.diff.as_text().unwrap(); + assert_eq!( + delta.to_json_value(), + json!([ + { + "retain": 2, + }, + { + "insert": "A", + "attributes": {"bold": true, "link": true} + } + ]) + ) + } + }), + ); + a.get_text("text").insert_unicode(2, "A").unwrap(); + let _ = a.implicit_commit_then_stop(); +} + +#[test] +fn insert_richtext_event() { + let a = LoroDoc::new_auto_commit(); + a.get_text("text").insert_unicode(0, "Hello").unwrap(); + a.get_text("text") + .mark(0, 5, "bold", true.into(), PosType::Event) + .unwrap(); + a.commit_then_renew(); + let text = a.get_text("text"); + let _g = a.subscribe( + &text.id(), + Arc::new(|e| { + let delta = e.events[0].diff.as_text().unwrap(); + assert_eq!( + delta.to_json_value(), + json!([ + {"retain": 5,}, + {"insert": " World!", "attributes": {"bold": true}} + ]) + ) + }), + ); + + text.insert_unicode(5, " World!").unwrap(); +} + +#[test] +fn import_after_init_handlers() { + let a = LoroDoc::new_auto_commit(); + let _g = a.subscribe( + &ContainerID::new_root("text", ContainerType::Text), + Arc::new(|event| { + assert!(matches!( + event.events[0].diff, + loro_internal::event::Diff::Text(_) + )) + }), + ); + let _g = a.subscribe( + &ContainerID::new_root("map", ContainerType::Map), + Arc::new(|event| { + assert!(matches!( + event.events[0].diff, + loro_internal::event::Diff::Map(_) + )) + }), + ); + let _g = a.subscribe( + &ContainerID::new_root("list", ContainerType::List), + Arc::new(|event| { + assert!(matches!( + event.events[0].diff, + loro_internal::event::Diff::List(_) + )) + }), + ); + + let b = LoroDoc::new_auto_commit(); + b.get_list("list").insert(0, "list").unwrap(); + b.get_list("list_a").insert(0, "list_a").unwrap(); + b.get_text("text").insert_unicode(0, "text").unwrap(); + b.get_map("map").insert("m", "map").unwrap(); + a.import(&b.export(ExportMode::Snapshot).unwrap()).unwrap(); + a.commit_then_renew(); +} + +#[test] +fn test_from_snapshot() { + let a = LoroDoc::new_auto_commit(); + a.get_text("text").insert_unicode(0, "0").unwrap(); + let snapshot = a.export(ExportMode::Snapshot).unwrap(); + let c = LoroDoc::from_snapshot(&snapshot).unwrap(); + assert_eq!(a.get_deep_value(), c.get_deep_value()); + assert_eq!(a.oplog_frontiers(), c.oplog_frontiers()); + assert_eq!(a.state_frontiers(), c.state_frontiers()); + let updates = a.export(ExportMode::all_updates()).unwrap(); + let d = match LoroDoc::from_snapshot(&updates) { + Ok(_) => panic!(), + Err(e) => e, + }; + assert!(matches!(d, loro_common::LoroError::DecodeError(..))); +} + +#[test] +fn test_pending() { + let a = LoroDoc::new_auto_commit(); + a.set_peer_id(0).unwrap(); + a.get_text("text").insert_unicode(0, "0").unwrap(); + let b = LoroDoc::new_auto_commit(); + b.set_peer_id(1).unwrap(); + b.import(&a.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + b.get_text("text").insert_unicode(0, "1").unwrap(); + let c = LoroDoc::new_auto_commit(); + b.set_peer_id(2).unwrap(); + c.import(&b.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + c.get_text("text").insert_unicode(0, "2").unwrap(); + + // c creates a pending change for a, insert "2" cannot be merged into a yet + a.import(&c.export(ExportMode::updates(&b.oplog_vv())).unwrap()) + .unwrap(); + assert_eq!(a.get_deep_value().to_json_value(), json!({"text": "0"})); + + // b does not has c's change + a.import(&b.export(ExportMode::updates(&a.oplog_vv())).unwrap()) + .unwrap(); + dbg!(&a.oplog().lock()); + assert_eq!(a.get_deep_value().to_json_value(), json!({"text": "210"})); +} + +#[test] +fn test_checkout() { + let doc_0 = LoroDoc::new_auto_commit(); + doc_0.set_peer_id(0).unwrap(); + let doc_1 = LoroDoc::new_auto_commit(); + doc_1.set_peer_id(1).unwrap(); + + let value: Arc<Mutex<LoroValue>> = Arc::new(Mutex::new(LoroValue::Map(Default::default()))); + let root_value = value.clone(); + let _g = doc_0.subscribe_root(Arc::new(move |event| { + dbg!(&event); + let mut root_value = root_value.lock(); + for container_diff in event.events { + root_value.apply( + &container_diff.path.iter().map(|x| x.1.clone()).collect(), + std::slice::from_ref(&container_diff.diff), + ); + } + })); + + let map = doc_0.get_map("map"); + let handler = map + .insert_container("text", TextHandler::new_detached()) + .unwrap(); + let text = handler; + text.insert_unicode(0, "123").unwrap(); + + let map = doc_1.get_map("map"); + + let handler = map + .insert_container("text", TextHandler::new_detached()) + .unwrap(); + let text = handler; + text.insert_unicode(0, "123").unwrap(); + + doc_0 + .import(&doc_1.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + + doc_0 + .checkout(&Frontiers::from(vec![ID::new(0, 2)])) + .unwrap(); + + assert_eq!(&doc_0.get_deep_value(), &*value.lock()); + assert_eq!( + value.lock().to_json_value(), + json!({ + "map": { + "text": "12" + } + }) + ); +} + +#[test] +fn test_timestamp() { + let doc = LoroDoc::new(); + doc.set_record_timestamp(true); + let text = doc.get_text("text"); + let mut txn = doc.txn().unwrap(); + text.insert_with_txn(&mut txn, 0, "123", PosType::Unicode) + .unwrap(); + txn.commit().unwrap(); + let op_log = &doc.oplog().lock(); + let change = op_log.get_change_at(ID::new(doc.peer_id(), 0)).unwrap(); + assert!(change.timestamp() > 1690966970); +} + +#[test] +fn test_text_checkout() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let text = doc.get_text("text"); + text.insert_unicode(0, "你界").unwrap(); + text.insert_unicode(1, "好世").unwrap(); + doc.commit_then_renew(); + { + doc.checkout(&Frontiers::from([ID::new(doc.peer_id(), 0)].as_slice())) + .unwrap(); + assert_eq!(text.get_value().as_string().unwrap().as_str(), "你"); + } + { + doc.checkout(&Frontiers::from([ID::new(doc.peer_id(), 1)].as_slice())) + .unwrap(); + assert_eq!(text.get_value().as_string().unwrap().as_str(), "你界"); + } + { + doc.checkout(&Frontiers::from([ID::new(doc.peer_id(), 2)].as_slice())) + .unwrap(); + assert_eq!(text.get_value().as_string().unwrap().as_str(), "你好界"); + } + { + doc.checkout(&Frontiers::from([ID::new(doc.peer_id(), 3)].as_slice())) + .unwrap(); + assert_eq!(text.get_value().as_string().unwrap().as_str(), "你好世界"); + } + assert_eq!(text.len_unicode(), 4); + assert_eq!(text.len_utf8(), 12); + assert_eq!(text.len_unicode(), 4); + + doc.checkout_to_latest(); + text.delete_unicode(3, 1).unwrap(); + assert_eq!(text.get_value().as_string().unwrap().as_str(), "你好世"); + text.delete_unicode(2, 1).unwrap(); + assert_eq!(text.get_value().as_string().unwrap().as_str(), "你好"); + doc.checkout(&Frontiers::from([ID::new(doc.peer_id(), 3)].as_slice())) + .unwrap(); + assert_eq!(text.get_value().as_string().unwrap().as_str(), "你好世界"); + doc.checkout(&Frontiers::from([ID::new(doc.peer_id(), 4)].as_slice())) + .unwrap(); + assert_eq!(text.get_value().as_string().unwrap().as_str(), "你好世"); + doc.checkout(&Frontiers::from([ID::new(doc.peer_id(), 5)].as_slice())) + .unwrap(); + assert_eq!(text.get_value().as_string().unwrap().as_str(), "你好"); + { + doc.checkout(&Frontiers::from([ID::new(doc.peer_id(), 0)].as_slice())) + .unwrap(); + assert_eq!(text.get_value().as_string().unwrap().as_str(), "你"); + } + { + doc.checkout(&Frontiers::from([ID::new(doc.peer_id(), 1)].as_slice())) + .unwrap(); + assert_eq!(text.get_value().as_string().unwrap().as_str(), "你界"); + } + { + doc.checkout(&Frontiers::from([ID::new(doc.peer_id(), 2)].as_slice())) + .unwrap(); + assert_eq!(text.get_value().as_string().unwrap().as_str(), "你好界"); + } + { + doc.checkout(&Frontiers::from([ID::new(doc.peer_id(), 3)].as_slice())) + .unwrap(); + assert_eq!(text.get_value().as_string().unwrap().as_str(), "你好世界"); + } +} + +#[test] +fn map_checkout() { + let doc = LoroDoc::new_auto_commit(); + let meta = doc.get_map("meta"); + let v_empty = doc.oplog_frontiers(); + meta.insert("key", 0).unwrap(); + let v0 = doc.oplog_frontiers(); + meta.insert("key", 1).unwrap(); + let v1 = doc.oplog_frontiers(); + assert_eq!(meta.get_deep_value().to_json(), r#"{"key":1}"#); + doc.checkout(&v0).unwrap(); + assert_eq!(meta.get_deep_value().to_json(), r#"{"key":0}"#); + doc.checkout(&v_empty).unwrap(); + assert_eq!(meta.get_deep_value().to_json(), r#"{}"#); + doc.checkout(&v1).unwrap(); + assert_eq!(meta.get_deep_value().to_json(), r#"{"key":1}"#); +} + +#[test] +fn a_list_of_map_checkout() { + let doc = LoroDoc::new_auto_commit(); + let entry = doc.get_map("entry"); + let (list, sub) = { + let list = entry + .insert_container("list", ListHandler::new_detached()) + .unwrap(); + let sub_map = list + .insert_container(0, MapHandler::new_detached()) + .unwrap(); + sub_map.insert("x", 100).unwrap(); + sub_map.insert("y", 1000).unwrap(); + (list, sub_map) + }; + let v0 = doc.oplog_frontiers(); + let d0 = doc.get_deep_value().to_json(); + + list.insert(0, 3).unwrap(); + list.push(4).unwrap(); + list.insert_container(2, MapHandler::new_detached()) + .unwrap(); + list.insert_container(3, TextHandler::new_detached()) + .unwrap(); + + list.delete(2, 1).unwrap(); + sub.insert("x", 9).unwrap(); + sub.insert("y", 9).unwrap(); + sub.insert("z", 9).unwrap(); + let v1 = doc.oplog_frontiers(); + let d1 = doc.get_deep_value().to_json(); + sub.insert("x", 77).unwrap(); + sub.insert("y", 88).unwrap(); + list.delete(0, 1).unwrap(); + list.insert(0, 123).unwrap(); + list.push(99).unwrap(); + let v2 = doc.oplog_frontiers(); + let d2 = doc.get_deep_value().to_json(); + + doc.checkout(&v0).unwrap(); + assert_eq!(doc.get_deep_value().to_json(), d0); + doc.checkout(&v1).unwrap(); + assert_eq!(doc.get_deep_value().to_json(), d1); + doc.checkout(&v2).unwrap(); + println!("{}", doc.get_deep_value_with_id().to_json_pretty()); + assert_eq!(doc.get_deep_value().to_json(), d2); + doc.checkout(&v1).unwrap(); + + println!("{}", doc.get_deep_value_with_id().to_json_pretty()); + assert_eq!(doc.get_deep_value().to_json(), d1); + doc.checkout(&v0).unwrap(); + assert_eq!(doc.get_deep_value().to_json(), d0); +} + +#[test] +fn map_concurrent_checkout() { + let doc_a = LoroDoc::new_auto_commit(); + let meta_a = doc_a.get_map("meta"); + let doc_b = LoroDoc::new_auto_commit(); + let meta_b = doc_b.get_map("meta"); + + meta_a.insert("key", 0).unwrap(); + let va = doc_a.oplog_frontiers(); + meta_b.insert("s", 1).unwrap(); + let vb_0 = doc_b.oplog_frontiers(); + meta_b.insert("key", 1).unwrap(); + let vb_1 = doc_b.oplog_frontiers(); + doc_a + .import(&doc_b.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + meta_a.insert("key", 2).unwrap(); + + let v_merged = doc_a.oplog_frontiers(); + + doc_a.checkout(&va).unwrap(); + assert_eq!(meta_a.get_deep_value().to_json_value(), json!({"key":0})); + doc_a.checkout(&vb_0).unwrap(); + assert_eq!(meta_a.get_deep_value().to_json_value(), json!({"s":1})); + doc_a.checkout(&vb_1).unwrap(); + assert_eq!( + meta_a.get_deep_value().to_json_value(), + json!({"s":1,"key":1}) + ); + doc_a.checkout(&v_merged).unwrap(); + assert_eq!( + meta_a.get_deep_value().to_json_value(), + json!({"s":1,"key":2}) + ); +} + +#[test] +fn tree_checkout() { + let doc_a = LoroDoc::new_auto_commit(); + let _g = doc_a.subscribe_root(Arc::new(|_e| {})); + doc_a.set_peer_id(1).unwrap(); + let tree = doc_a.get_tree("root"); + let id1 = tree.create(TreeParentId::Root).unwrap(); + let id2 = tree.create(TreeParentId::Node(id1)).unwrap(); + let v1_state = tree.get_deep_value(); + let v1 = doc_a.oplog_frontiers(); + let _id3 = tree.create(TreeParentId::Node(id2)).unwrap(); + let v2_state = tree.get_deep_value(); + let v2 = doc_a.oplog_frontiers(); + tree.delete(id2).unwrap(); + let v3_state = tree.get_deep_value(); + let v3 = doc_a.oplog_frontiers(); + doc_a.checkout(&v1).unwrap(); + assert_eq!( + serde_json::to_value(tree.get_deep_value()) + .unwrap() + .get("roots"), + serde_json::to_value(v1_state).unwrap().get("roots") + ); + doc_a.checkout(&v2).unwrap(); + assert_eq!( + serde_json::to_value(tree.get_deep_value()) + .unwrap() + .get("roots"), + serde_json::to_value(v2_state).unwrap().get("roots") + ); + doc_a.checkout(&v3).unwrap(); + assert_eq!( + serde_json::to_value(tree.get_deep_value()) + .unwrap() + .get("roots"), + serde_json::to_value(v3_state).unwrap().get("roots") + ); + + doc_a.attach(); + tree.create(TreeParentId::Root).unwrap(); +} + +#[test] +fn issue_batch_import_snapshot() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(123).unwrap(); + let doc2 = LoroDoc::new_auto_commit(); + doc2.set_peer_id(456).unwrap(); + doc.get_map("map").insert("s", "hello world!").unwrap(); + doc2.get_map("map").insert("s", "hello?").unwrap(); + + let data1 = doc.export(ExportMode::Snapshot).unwrap(); + let data2 = doc2.export(ExportMode::Snapshot).unwrap(); + let doc3 = LoroDoc::new(); + doc3.import_batch(&[data1, data2]).unwrap(); +} + +#[test] +fn state_may_deadlock_when_import() { + // helper function ref: https://github.com/rust-lang/rfcs/issues/2798#issuecomment-552949300 + use std::time::Duration; + use std::{sync::mpsc, thread}; + fn panic_after<T, F>(d: Duration, f: F) -> T + where + T: Send + 'static, + F: FnOnce() -> T, + F: Send + 'static, + { + let (done_tx, done_rx) = mpsc::channel(); + let handle = thread::spawn(move || { + let val = f(); + done_tx.send(()).expect("Unable to send completion signal"); + val + }); + + match done_rx.recv_timeout(d) { + Ok(_) => handle.join().expect("Thread panicked"), + Err(_) => panic!("Thread took too long"), + } + } + + panic_after(Duration::from_millis(100), || { + let doc = LoroDoc::new_auto_commit(); + let map = doc.get_map("map"); + let _g = doc.subscribe_root(Arc::new(move |_e| { + map.id(); + })); + + let doc2 = LoroDoc::new_auto_commit(); + doc2.get_map("map").insert("foo", 123).unwrap(); + doc.import(&doc.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + }) +} + +#[ctor::ctor] +fn init() { + dev_utils::setup_test_log(); +} + +#[test] +fn missing_event_when_checkout() { + let doc = LoroDoc::new_auto_commit(); + doc.checkout(&doc.oplog_frontiers()).unwrap(); + let value = Arc::new(Mutex::new(FxHashMap::default())); + let map = value.clone(); + let _g = doc.subscribe( + &ContainerID::new_root("tree", ContainerType::Tree), + Arc::new(move |e| { + let mut v = map.lock(); + for container_diff in e.events.iter() { + let from_children = + container_diff.id != ContainerID::new_root("tree", ContainerType::Tree); + if from_children { + if let Diff::Map(map) = &container_diff.diff { + for (k, ResolvedMapValue { value, .. }) in map.updated.iter() { + match value { + Some(value) => { + v.insert( + k.to_string(), + *value.as_value().unwrap().as_i64().unwrap(), + ); + } + None => { + v.remove(&k.to_string()); + } + } + } + } + } + } + }), + ); + + let doc2 = LoroDoc::new_auto_commit(); + let tree = doc2.get_tree("tree"); + let node = tree.create_at(TreeParentId::Root, 0).unwrap(); + let _ = tree.create_at(TreeParentId::Root, 0).unwrap(); + let meta = tree.get_meta(node).unwrap(); + meta.insert("a", 0).unwrap(); + doc.import(&doc2.export(ExportMode::updates(&doc.oplog_vv())).unwrap()) + .unwrap(); + doc.attach(); + meta.insert("b", 1).unwrap(); + doc.checkout(&doc.oplog_frontiers()).unwrap(); + doc.import(&doc2.export(ExportMode::updates(&doc.oplog_vv())).unwrap()) + .unwrap(); + // checkout use the same diff_calculator, the depth of calculator is not updated + doc.attach(); + assert!(value.lock().contains_key("b")); +} + +#[test] +fn empty_event() { + let doc = LoroDoc::new_auto_commit(); + doc.get_map("map").insert("key", 123).unwrap(); + doc.commit_then_renew(); + let fire = Arc::new(AtomicBool::new(false)); + let fire_clone = Arc::clone(&fire); + let _g = doc.subscribe_root(Arc::new(move |_e| { + fire_clone.store(true, std::sync::atomic::Ordering::Relaxed); + })); + doc.import(&doc.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + assert!(!fire.load(std::sync::atomic::Ordering::Relaxed)); +} + +#[test] +fn insert_attach_container() -> LoroResult<()> { + let doc = LoroDoc::new_auto_commit(); + let list = doc.get_list("list"); + list.insert_container(0, MapHandler::new_detached())? + .insert("key", 1)?; + list.insert_container(1, MapHandler::new_detached())? + .insert("key", 2)?; + let elem = list.insert_container(2, MapHandler::new_detached())?; + elem.insert("key", 3)?; + let new_map = list.insert_container(0, elem)?; + assert_eq!(new_map.get_value().to_json_value(), json!({"key": 3})); + list.delete(3, 1)?; + + let elem = list.insert_container(0, TextHandler::new_detached())?; + elem.insert(0, "abc", PosType::Unicode)?; + elem.mark(0, 2, "bold", true.into(), PosType::Event)?; + let new_text = list.insert_container(0, elem)?; + assert_eq!( + new_text.get_richtext_value().to_json_value(), + json!([{"insert":"ab", "attributes": {"bold": true}}, {"insert":"c"}]) + ); + + let elem = list.insert_container(0, ListHandler::new_detached())?; + elem.insert(0, "list")?; + let new_list = list.insert_container(0, elem)?; + new_list.insert(0, "new_list")?; + assert_eq!( + new_list.get_value().to_json_value(), + json!(["new_list", "list"]) + ); + + // let elem = list.insert_container(2, TreeHandler::new_detached())?; + // let p = elem.create(None)?; + // elem.create(p)?; + // list.insert_container(0, elem)?; + + assert_eq!( + doc.get_deep_value().to_json_value(), + json!({ + "list": [["new_list", "list"], ["list"],"abc", "abc", {"key": 3}, {"key": 1}, {"key": 2}] + }) + ); + Ok(()) +} + +#[test] +fn tree_attach() { + let tree = TreeHandler::new_detached(); + let id = tree.create(TreeParentId::Root).unwrap(); + tree.get_meta(id).unwrap().insert("key", "value").unwrap(); + let doc = LoroDoc::new_auto_commit(); + doc.get_list("list").insert_container(0, tree).unwrap(); + let v = doc.get_deep_value(); + assert_eq!( + v.as_map().unwrap().get("list").unwrap().as_list().unwrap()[0] + .as_list() + .unwrap()[0] + .as_map() + .unwrap() + .get("meta") + .unwrap() + .to_json_value(), + json!({"key":"value"}) + ) +} + +#[test] +#[cfg(feature = "counter")] +fn counter() { + let doc = LoroDoc::new_auto_commit(); + let counter = doc.get_counter("counter"); + counter.increment(1.).unwrap(); + counter.increment(2.).unwrap(); + counter.decrement(1.).unwrap(); + let json = doc + .export_json_updates(&Default::default(), &doc.oplog_vv(), true) + .unwrap(); + let doc2 = LoroDoc::new_auto_commit(); + doc2.import_json_updates(json).unwrap(); +} + +#[test] +fn test_insert_utf8() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_utf8(0, "Hello ").unwrap(); + text.insert_utf8(6, "World").unwrap(); + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([{"insert":"Hello World"}]) + ) +} + +#[test] +fn test_insert_utf8_cross_unicode_1() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_utf8(0, "你好").unwrap(); + text.insert_utf8(3, "World").unwrap(); + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([{"insert":"你World好"}]) + ) +} + +#[test] +fn test_insert_utf8_cross_unicode_2() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_utf8(0, "你好").unwrap(); + text.insert_utf8(6, "World").unwrap(); + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([{"insert":"你好World"}]) + ) +} + +#[test] +fn test_insert_utf8_detached() { + let text = TextHandler::new_detached(); + text.insert_utf8(0, "Hello ").unwrap(); + text.insert_utf8(6, "World").unwrap(); + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([{"insert":"Hello World"}]) + ) +} + +#[test] +#[should_panic] +#[ignore = "fix me later after gbtree support Result for query"] +fn test_insert_utf8_panic_cross_unicode() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_utf8(0, "你好").unwrap(); + text.insert_utf8(1, "World").unwrap(); +} + +#[test] +#[should_panic] +fn test_insert_utf8_panic_out_bound() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_utf8(0, "Hello ").unwrap(); + text.insert_utf8(7, "World").unwrap(); +} + +// println!("{}", text.get_richtext_value().to_json_value().to_string()); + +#[test] +fn test_delete_utf8() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_utf8(0, "Hello").unwrap(); + text.delete_utf8(1, 3).unwrap(); + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([{"insert":"Ho"}]) + ) +} + +#[test] +fn test_delete_utf8_with_zero_len() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_utf8(0, "Hello").unwrap(); + text.delete_utf8(1, 0).unwrap(); + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([{"insert":"Hello"}]) + ) +} + +#[test] +fn test_delete_utf8_cross_unicode() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_utf8(0, "你好").unwrap(); + text.delete_utf8(0, 3).unwrap(); + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([{"insert":"好"}]) + ) +} + +#[test] +fn test_delete_utf8_detached() { + let text = TextHandler::new_detached(); + text.insert_utf8(0, "Hello").unwrap(); + text.delete_utf8(1, 3).unwrap(); + assert_eq!( + text.get_richtext_value().to_json_value(), + json!([{"insert":"Ho"}]) + ) +} + +// WARNING: +// Due to the current inability to report an error on +// get_offset_and_found on BTree, this test won't be ok. +// #[test] +// #[should_panic] +// fn test_delete_utf8_panic_cross_unicode() { +// let doc = LoroDoc::new_auto_commit(); +// let text = doc.get_text("text"); +// text.insert_utf8(0, "你好").unwrap(); +// text.delete_utf8(0, 2).unwrap(); +// } + +#[test] +#[should_panic] +fn test_delete_utf8_panic_out_bound_pos() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_unicode(0, "Hello").unwrap(); + text.delete_utf8(10, 1).unwrap(); +} + +#[test] +#[should_panic] +fn test_delete_utf8_panic_out_bound_len() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_unicode(0, "Hello").unwrap(); + text.delete_utf8(1, 10).unwrap(); +} + +#[test] +fn test_char_at() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_unicode(0, "Herld").unwrap(); + text.insert_unicode(2, "llo Wo").unwrap(); + assert_eq!(text.char_at(0, PosType::Unicode).unwrap(), 'H'); + assert_eq!(text.char_at(1, PosType::Unicode).unwrap(), 'e'); + assert_eq!(text.char_at(2, PosType::Unicode).unwrap(), 'l'); + assert_eq!(text.char_at(3, PosType::Unicode).unwrap(), 'l'); + let err = text.char_at(15, PosType::Unicode).unwrap_err(); + assert!(matches!(err, loro_common::LoroError::OutOfBound { .. })) +} + +#[test] +fn test_char_at_detached() { + let text = TextHandler::new_detached(); + text.insert_unicode(0, "Herld").unwrap(); + text.insert_unicode(2, "llo Wo").unwrap(); + assert_eq!(text.char_at(0, PosType::Unicode).unwrap(), 'H'); + assert_eq!(text.char_at(1, PosType::Unicode).unwrap(), 'e'); + assert_eq!(text.char_at(2, PosType::Unicode).unwrap(), 'l'); + assert_eq!(text.char_at(3, PosType::Unicode).unwrap(), 'l'); + let err = text.char_at(15, PosType::Unicode).unwrap_err(); + assert!(matches!(err, loro_common::LoroError::OutOfBound { .. })) +} + +#[test] +fn test_char_at_wchar() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_unicode(0, "你好").unwrap(); + text.insert_unicode(1, "世界").unwrap(); + assert_eq!(text.char_at(0, PosType::Unicode).unwrap(), '你'); + assert_eq!(text.char_at(1, PosType::Unicode).unwrap(), '世'); + assert_eq!(text.char_at(2, PosType::Unicode).unwrap(), '界'); + assert_eq!(text.char_at(3, PosType::Unicode).unwrap(), '好'); + let err = text.char_at(5, PosType::Unicode).unwrap_err(); + assert!(matches!(err, loro_common::LoroError::OutOfBound { .. })) +} + +#[test] +fn test_text_slice() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_unicode(0, "Hello").unwrap(); + text.insert_unicode(1, "World").unwrap(); + assert_eq!(text.slice(0, 4, PosType::Unicode).unwrap(), "HWor"); + assert_eq!(text.slice(0, 1, PosType::Unicode).unwrap(), "H"); +} + +#[test] +fn test_text_slice_detached() { + let text = TextHandler::new_detached(); + text.insert_unicode(0, "Herld").unwrap(); + text.insert_unicode(2, "llo Wo").unwrap(); + assert_eq!(text.slice(0, 4, PosType::Unicode).unwrap(), "Hell"); + assert_eq!(text.slice(0, 1, PosType::Unicode).unwrap(), "H"); +} + +#[test] +fn test_text_slice_wchar() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_unicode(0, "你好").unwrap(); + text.insert_unicode(1, "世界").unwrap(); + assert_eq!(text.slice(0, 3, PosType::Unicode).unwrap(), "你世界"); +} + +#[test] +#[should_panic] +fn test_text_slice_end_index_less_than_start() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_unicode(0, "你好").unwrap(); + text.insert_unicode(1, "世界").unwrap(); + text.slice(2, 1, PosType::Unicode).unwrap(); +} + +#[test] +#[should_panic] +fn test_text_slice_out_of_bound() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_unicode(0, "你好").unwrap(); + text.insert_unicode(1, "世界").unwrap(); + text.slice(1, 10, PosType::Unicode).unwrap(); +} + +#[test] +fn test_text_splice() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_unicode(0, "你好").unwrap(); + assert_eq!(text.splice(1, 1, "世界", PosType::Unicode).unwrap(), "好"); + assert_eq!(text.to_string(), "你世界"); +} + +#[test] +fn test_text_iter() { + let mut str = String::new(); + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_unicode(0, "Hello").unwrap(); + text.insert_unicode(1, "Hello").unwrap(); + text.iter(|s| { + str.push_str(s); + true + }); + assert_eq!(str, "HHelloello"); + str = String::new(); + let mut i = 0; + text.iter(|s| { + if i == 1 { + return false; + } + str.push_str(s); + i += 1; + true + }); + assert_eq!(str, "H"); +} + +#[test] +fn test_text_iter_detached() { + let mut str = String::new(); + let text = TextHandler::new_detached(); + text.insert_unicode(0, "Hello").unwrap(); + text.insert_unicode(1, "Hello").unwrap(); + text.iter(|s| { + str.push_str(s); + true + }); + assert_eq!(str, "HHelloello"); +} + +#[test] +fn test_text_update() { + let doc = LoroDoc::new_auto_commit(); + let text = doc.get_text("text"); + text.insert_unicode(0, "Hello 😊Bro").unwrap(); + text.update("Hello World Bro😊", Default::default()) + .unwrap(); + assert_eq!(text.to_string(), "Hello World Bro😊"); +} + +#[test] +fn test_map_contains_key() { + let doc = LoroDoc::new_auto_commit(); + let map = doc.get_map("m"); + assert!(!map.contains_key("bro")); + map.insert("bro", 114514).unwrap(); + assert!(map.contains_key("bro")); + map.delete("bro").unwrap(); + assert!(!map.contains_key("bro")); +} + +#[test] +fn set_max_peer_id() { + let doc = LoroDoc::new_auto_commit(); + assert_eq!( + doc.set_peer_id(PeerID::MAX), + Result::Err(LoroError::InvalidPeerID) + ); +} + +#[test] +fn import_status() -> LoroResult<()> { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(0)?; + let t = doc.get_text("text"); + t.insert_unicode(0, "a")?; + + let doc2 = LoroDoc::new_auto_commit(); + doc2.set_peer_id(1)?; + let t2 = doc2.get_text("text"); + t2.insert_unicode(0, "b")?; + doc2.commit_then_renew(); + let update1 = doc2.export(ExportMode::Snapshot).unwrap(); + let vv1 = doc2.oplog_vv(); + t2.insert_unicode(1, "c")?; + let update2 = doc2.export(ExportMode::updates(&vv1)).unwrap(); + + let status1 = doc.import(&update2)?; + let status2 = doc.import(&update1)?; + assert_eq!( + status1, + ImportStatus { + success: Default::default(), + pending: Some(VersionRange::from_map(fx_map!(1=>(1, 2)))) + } + ); + assert_eq!( + status2, + ImportStatus { + success: VersionRange::from_map(fx_map!(1=>(0, 2))), + pending: None + } + ); + + Ok(()) +} + +#[test] +fn test_on_first_commit_from_peer() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(0).unwrap(); + let p = Arc::new(Mutex::new(vec![])); + let p2 = Arc::clone(&p); + let sub = doc.subscribe_first_commit_from_peer(Box::new(move |e| { + p2.lock().push(e.peer); + true + })); + doc.get_text("text").insert_unicode(0, "a").unwrap(); + doc.commit_then_renew(); + doc.get_text("text").insert_unicode(0, "b").unwrap(); + doc.commit_then_renew(); + doc.set_peer_id(1).unwrap(); + doc.get_text("text").insert_unicode(0, "c").unwrap(); + doc.commit_then_renew(); + sub.unsubscribe(); + assert_eq!(p.lock().as_slice(), &[0, 1]); +} + +#[test] +fn test_on_first_commit_from_peer_when_drop_doc() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(0).unwrap(); + let p = Arc::new(Mutex::new(vec![])); + let p2 = Arc::clone(&p); + let _sub = doc.subscribe_first_commit_from_peer(Box::new(move |e| { + p2.lock().push(e.peer); + true + })); + doc.get_text("text").insert_unicode(0, "a").unwrap(); + drop(doc); + assert_eq!(p.lock().as_slice(), &[0]); +} + +#[test] +fn test_on_first_commit_from_peer_and_set_peer_id() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(0).unwrap(); + let f = Arc::new(AtomicBool::new(false)); + let f2 = Arc::clone(&f); + let sub = doc.subscribe_first_commit_from_peer(Box::new(move |_e| { + f2.store(true, std::sync::atomic::Ordering::Relaxed); + true + })); + doc.get_text("text").insert_unicode(0, "a").unwrap(); + doc.set_peer_id(1).unwrap(); + sub.unsubscribe(); + assert!(f.load(std::sync::atomic::Ordering::Relaxed)); +} + +#[test] +fn test_on_first_commit_from_peer_with_lock() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(0).unwrap(); + let doc_clone = doc.clone(); + let sub = doc.subscribe_first_commit_from_peer(Box::new(move |_e| { + doc_clone.get_text("text").insert_unicode(0, "b").unwrap(); + true + })); + doc.get_text("text").insert_unicode(0, "a").unwrap(); + doc.commit_then_renew(); + sub.unsubscribe(); + assert_eq!(doc.get_text("text").to_string(), "ba"); + assert_eq!( + doc.export_json_updates(&Default::default(), &doc.oplog_vv(), false) + .unwrap() + .changes + .len(), + 1 + ); +} + +#[test] +fn test_on_first_peer_commit_attach_user_id() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(0).unwrap(); + let doc_clone = doc.clone(); + let sub = doc.subscribe_first_commit_from_peer(Box::new(move |e| { + doc_clone + .get_map("::loro::user_id") + .insert(e.peer.to_string().as_str(), "user_bob") + .unwrap(); + true + })); + doc.get_text("text").insert_unicode(0, "a").unwrap(); + doc.commit_then_renew(); + sub.unsubscribe(); + assert_eq!( + doc.get_map("::loro::user_id").get_value(), + loro_value!({ + "0": "user_bob" + }) + ); +} + +#[test] +fn test_pre_commit_with_lock() { + let doc = LoroDoc::new_auto_commit(); + let doc_clone = doc.clone(); + let sub = doc.subscribe_pre_commit(Box::new(move |_e| { + // state lock + doc_clone.get_deep_value(); + // oplog lock + doc_clone.oplog_vv(); + true + })); + doc.get_text("text").insert_unicode(0, "a").unwrap(); + doc.commit_then_renew(); + sub.unsubscribe(); +} + +#[test] +fn test_pre_commit_with_hash() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(0).unwrap(); + let doc_clone = doc.clone(); + let sub = doc.subscribe_pre_commit(Box::new(move |e| { + let change_json = + doc_clone.export_json_in_id_span(e.change_meta.id.to_span(e.change_meta.len)); + assert!(change_json.len() == 1); + let mut deps = vec![]; + for dep in e.change_meta.deps.iter() { + let dep_msg = doc_clone + .oplog() + .lock() + .get_change_at(dep) + .unwrap() + .message() + .cloned() + .unwrap_or(Arc::from("")); + deps.push(dep_msg); + } + e.modifier.set_timestamp(0).set_message(&format!( + "{:08x}\n{}", + // just for test example, should use sha256 or blake3 for hash + xxhash_rust::xxh32::xxh32( + serde_json::to_string(&(&change_json, &deps)) + .unwrap() + .as_bytes(), + 0 + ), + e.change_meta.message() + )); + true + })); + doc.get_text("text").insert_unicode(0, "a").unwrap(); + doc.commit_with( + CommitOptions::default() + .commit_msg("add a") + .immediate_renew(true), + ); + doc.get_text("text").insert_unicode(0, "b").unwrap(); + doc.commit_with( + CommitOptions::default() + .commit_msg("add b") + .immediate_renew(true), + ); + sub.unsubscribe(); + let changes = doc + .export_json_updates(&Default::default(), &doc.oplog_vv(), false) + .unwrap() + .changes; + assert_eq!(changes.len(), 2); + for c in changes { + let mut msg = c.msg.as_ref().unwrap().lines(); + assert_eq!(msg.next().unwrap().len(), 8); + assert!(msg.next().is_some()); + } +} + +#[test] +fn test_change_to_json_schema_include_uncommit() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(0).unwrap(); + doc.get_text("text").insert_unicode(0, "a").unwrap(); + doc.commit_then_renew(); + let doc_clone = doc.clone(); + let _sub = doc.subscribe_pre_commit(Box::new(move |e| { + let changes = doc_clone.export_json_in_id_span(IdSpan::new( + 0, + 0, + e.change_meta.id.counter + e.change_meta.len as i32, + )); + assert_eq!(changes.len(), 2); + true + })); + doc.get_text("text").insert_unicode(0, "b").unwrap(); + let changes = doc.export_json_in_id_span(IdSpan::new(0, 0, 2)); + assert_eq!(changes.len(), 1); + doc.commit_then_renew(); + // change merged + assert_eq!(changes.len(), 1); +} + +#[test] +fn test_ephemeral_store() { + let store = EphemeralStore::new(1000); + let store_clone = store.clone(); + let _sub = store.subscribe(Box::new(move |_| { + store_clone.get_all_states(); + true + })); + store.set("a", 1); + store.set("b", 2); + store.set("c", 3); +} + +#[test] +fn test_origin() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(0).unwrap(); + let remote = LoroDoc::new_auto_commit(); + remote.set_peer_id(1).unwrap(); + doc.get_map("map").insert("a", 1).unwrap(); + doc.commit_then_renew(); + let snapshot = doc.export(ExportMode::Snapshot).unwrap(); + let expected_origin_string = "expectedOriginString"; + + let sub = remote.subscribe_root(Arc::new(move |e| { + assert_eq!(e.event_meta.origin, expected_origin_string.into()); + })); + remote + .import_with(&snapshot, expected_origin_string.into()) + .unwrap(); + sub.unsubscribe(); +} + +#[test] +fn apply_diff_with_same_peer_id_should_not_hang() { + let doc1 = LoroDoc::new_auto_commit(); + doc1.set_peer_id(1).unwrap(); + + let doc2 = doc1.fork(); + doc2.set_peer_id(1).unwrap(); // Same peer ID + + // The key issue: setContainer creates a nested container + let map = doc2.get_map("root"); + let nested = map + .insert_container("nested", MapHandler::new_detached()) + .unwrap(); // This is what triggers the hang + nested.insert("key", "value").unwrap(); + doc2.commit_then_renew(); + + let frontiers_before = doc1.oplog_frontiers(); + let frontiers_after = doc2.oplog_frontiers(); + let diff = doc2.diff(&frontiers_before, &frontiers_after).unwrap(); + + // This should NOT hang + doc1.apply_diff(diff).unwrap(); + assert_eq!( + doc1.get_deep_value().to_json_value(), + doc2.get_deep_value().to_json_value() + ); +} diff --git a/vendor/loro-internal/tests/tree.rs b/vendor/loro-internal/tests/tree.rs new file mode 100644 index 0000000..8cdae51 --- /dev/null +++ b/vendor/loro-internal/tests/tree.rs @@ -0,0 +1,35 @@ +use loro_internal::{LoroDoc, TreeParentId}; + +#[test] +fn tree_index() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(0).unwrap(); + let tree = doc.get_tree("tree"); + let root = tree.create(TreeParentId::Root).unwrap(); + let child = tree.create(root.into()).unwrap(); + let child2 = tree.create_at(root.into(), 0).unwrap(); + // sort with OpID + assert_eq!(tree.get_index_by_tree_id(&child).unwrap(), 1); + assert_eq!(tree.get_index_by_tree_id(&child2).unwrap(), 0); + + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(0).unwrap(); + let tree = doc.get_tree("tree"); + tree.enable_fractional_index(0); + let root = tree.create(TreeParentId::Root).unwrap(); + let child = tree.create(root.into()).unwrap(); + let child2 = tree.create_at(root.into(), 0).unwrap(); + // sort with fractional index + assert_eq!(tree.get_index_by_tree_id(&child).unwrap(), 1); + assert_eq!(tree.get_index_by_tree_id(&child2).unwrap(), 0); +} + +#[test] +fn tree_move_in_parent() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(0).unwrap(); + let tree = doc.get_tree("tree"); + let root = tree.create(TreeParentId::Root).unwrap(); + let child = tree.create(root.into()).unwrap(); + tree.mov(child, root.into()).unwrap(); +} diff --git a/vendor/loro-internal/tests/undo.rs b/vendor/loro-internal/tests/undo.rs new file mode 100644 index 0000000..6c64dd8 --- /dev/null +++ b/vendor/loro-internal/tests/undo.rs @@ -0,0 +1,281 @@ +use std::borrow::Cow; + +use loro_internal::{ + cursor::PosType, handler::UpdateOptions, loro::ExportMode, LoroDoc, UndoManager, +}; + +#[test] +fn consecutive_noops_consume_one_item_and_notify_once() { + use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, + }; + + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let undo = UndoManager::new(&doc); + undo.set_merge_interval(0); + let pops = Arc::new(AtomicUsize::new(0)); + let popped = pops.clone(); + undo.set_on_pop(Some(Box::new(move |_, _, _| { + popped.fetch_add(1, Ordering::Relaxed); + }))); + doc.get_map("map").insert("prior", 42).unwrap(); + doc.commit_then_renew(); + let text = doc.get_text("text"); + text.insert(0, "a", PosType::Unicode).unwrap(); + doc.commit_then_renew(); + text.insert(1, "b", PosType::Unicode).unwrap(); + doc.commit_then_renew(); + + let other = LoroDoc::from_snapshot(&doc.export(ExportMode::Snapshot).unwrap()).unwrap(); + other.set_peer_id(2).unwrap(); + other + .get_text("text") + .delete(0, 2, PosType::Unicode) + .unwrap(); + doc.import(&other.export(ExportMode::all_updates()).unwrap()) + .unwrap(); + let before = doc.get_deep_value(); + assert_eq!(undo.undo_count(), 3); + for remaining in [2, 1] { + assert!(!undo.undo().unwrap()); + assert_eq!(undo.undo_count(), remaining); + assert_eq!(undo.redo_count(), 0); + assert_eq!(pops.load(Ordering::Relaxed), 3 - remaining); + assert_eq!(doc.get_deep_value(), before); + } + assert!(undo.undo().unwrap()); + assert_eq!(pops.load(Ordering::Relaxed), 3); + assert!(!undo.can_undo()); + assert!(!undo.undo().unwrap()); + assert_eq!(pops.load(Ordering::Relaxed), 3); + assert!(undo.redo().unwrap()); + assert_eq!(doc.get_deep_value(), before); +} + +#[test] +fn test_basic_undo_group_checkpoint() { + let doc = LoroDoc::new(); + let undo_manager = UndoManager::new(&doc); + let text = doc.get_text("text"); + + text.update("0", UpdateOptions::default()).unwrap(); + doc.commit_then_renew(); + undo_manager.group_start().unwrap(); + text.update("1", UpdateOptions::default()).unwrap(); + doc.commit_then_renew(); + text.update("12", UpdateOptions::default()).unwrap(); + doc.commit_then_renew(); + undo_manager.group_end(); + undo_manager.undo().unwrap(); + assert_eq!( + text.to_string(), + "0", + "undo should undo the grouped updates" + ); + undo_manager.redo().unwrap(); + assert_eq!( + text.to_string(), + "12", + "redo should redo the grouped updates" + ); +} + +#[test] +fn test_invalid_nested_group() { + let doc = LoroDoc::new(); + + let undo_manager = UndoManager::new(&doc); + + assert!( + undo_manager.group_start().is_ok(), + "group start should succeed" + ); + assert!( + undo_manager.group_start().is_err(), + "nested group start should fail" + ); + undo_manager.group_end(); + assert!( + undo_manager.group_start().is_ok(), + "nested group end should fail" + ); +} + +#[test] +fn test_simulate_intersecting_remote_undo() { + let doc = LoroDoc::new(); + let undo_manager = UndoManager::new(&doc); + let text = doc.get_text("text"); + undo_manager.group_start().unwrap(); + println!("pushing 1"); + text.update("1", UpdateOptions::default()).unwrap(); + doc.commit_then_renew(); + println!("pushing 2"); + text.update("12", UpdateOptions::default()).unwrap(); + doc.commit_then_renew(); + + // At this point, the doc has state of "12" in the "text" container + + let snapshot = doc.export(ExportMode::Snapshot).unwrap(); + let doc2 = LoroDoc::from_snapshot(&snapshot).unwrap(); + let text2 = doc2.get_text("text"); + let vv = doc2.state_vv(); + text2.update("123", UpdateOptions::default()).unwrap(); + doc2.commit_then_renew(); + + let update = doc2 + .export(ExportMode::Updates { + from: Cow::Borrowed(&vv), + }) + .unwrap(); + + println!("importing 3"); + doc.import(&update).unwrap(); + + // At this point, the doc has state of "123" in the "text" container + + text.update("1234", UpdateOptions::default()).unwrap(); + println!("pushing 4"); + doc.commit_then_renew(); + println!("ending group"); + undo_manager.group_end(); + + undo_manager.undo().unwrap(); + + assert_eq!(text.to_string(), "123"); +} + +#[test] +fn test_simulate_non_intersecting_remote_undo() { + let doc = LoroDoc::new(); + let undo_manager = UndoManager::new(&doc); + let text = doc.get_text("text"); + undo_manager.group_start().unwrap(); + text.update("1", UpdateOptions::default()).unwrap(); + doc.commit_then_renew(); + text.update("12", UpdateOptions::default()).unwrap(); + doc.commit_then_renew(); + let snapshot = doc.export(ExportMode::Snapshot).unwrap(); + // At the point the first doc has state of "12" in the "text" container + + // Doc 2 makes changes to a separate container + // The doc 2 has state of "123" in the "text2" container + let doc2 = LoroDoc::from_snapshot(&snapshot).unwrap(); + let text2 = doc2.get_text("text2"); + let vv = doc2.state_vv(); + text2.update("123", UpdateOptions::default()).unwrap(); + doc2.commit_then_renew(); + let update = doc2 + .export(ExportMode::Updates { + from: Cow::Borrowed(&vv), + }) + .unwrap(); + doc.import(&update).unwrap(); + + text.update("123", UpdateOptions::default()).unwrap(); + doc.commit_then_renew(); + undo_manager.group_end(); + + undo_manager.undo().unwrap(); + + assert_eq!(text.to_string(), ""); +} + +#[test] +fn test_undo_group_start_with_remote_ops() { + let doc = LoroDoc::new(); + let doc2 = LoroDoc::new(); + let undo_manager = UndoManager::new(&doc); + doc.get_text("text") + .insert(0, "hi", PosType::Unicode) + .unwrap(); + doc2.import(&doc.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + doc2.get_text("text") + .insert(0, "test", PosType::Unicode) + .unwrap(); + doc.import(&doc2.export(ExportMode::Snapshot).unwrap()) + .unwrap(); + undo_manager.group_start().unwrap(); + doc.get_text("text") + .insert(0, "t", PosType::Unicode) + .unwrap(); + undo_manager.undo().unwrap(); + assert_eq!(doc.get_text("text").to_string(), "testhi"); + undo_manager.undo().unwrap(); + assert_eq!(doc.get_text("text").to_string(), "test"); + undo_manager.redo().unwrap(); + assert_eq!(doc.get_text("text").to_string(), "testhi"); + undo_manager.redo().unwrap(); + assert_eq!(doc.get_text("text").to_string(), "ttesthi"); + undo_manager.undo().unwrap(); + assert_eq!(doc.get_text("text").to_string(), "testhi"); + undo_manager.undo().unwrap(); + assert_eq!(doc.get_text("text").to_string(), "test"); +} + +#[test] +fn test_clear_redo() { + let doc = LoroDoc::new(); + let undo_manager = UndoManager::new(&doc); + let text = doc.get_text("text"); + + // Make some edits + text.update("hello", UpdateOptions::default()).unwrap(); + doc.commit_then_renew(); + text.update("hello world", UpdateOptions::default()) + .unwrap(); + doc.commit_then_renew(); + + // Undo to create redo stack + undo_manager.undo().unwrap(); + assert_eq!(text.to_string(), "hello"); + assert!(undo_manager.can_redo(), "should be able to redo"); + assert!(undo_manager.can_undo(), "should be able to undo"); + + // Clear only redo stack + undo_manager.clear_redo(); + assert!(!undo_manager.can_redo(), "redo stack should be empty"); + assert!( + undo_manager.can_undo(), + "undo stack should still have items" + ); + + // Verify undo still works + undo_manager.undo().unwrap(); + assert_eq!(text.to_string(), ""); +} + +#[test] +fn test_clear_undo() { + let doc = LoroDoc::new(); + let undo_manager = UndoManager::new(&doc); + let text = doc.get_text("text"); + + // Make some edits + text.update("hello", UpdateOptions::default()).unwrap(); + doc.commit_then_renew(); + text.update("hello world", UpdateOptions::default()) + .unwrap(); + doc.commit_then_renew(); + + // Undo to create redo stack + undo_manager.undo().unwrap(); + assert_eq!(text.to_string(), "hello"); + assert!(undo_manager.can_redo(), "should be able to redo"); + assert!(undo_manager.can_undo(), "should be able to undo"); + + // Clear only undo stack + undo_manager.clear_undo(); + assert!( + undo_manager.can_redo(), + "redo stack should still have items" + ); + assert!(!undo_manager.can_undo(), "undo stack should be empty"); + + // Verify redo still works + undo_manager.redo().unwrap(); + assert_eq!(text.to_string(), "hello world"); +} diff --git a/vendor/loro-internal/tests/unknown_parent.rs b/vendor/loro-internal/tests/unknown_parent.rs new file mode 100644 index 0000000..dae7b18 --- /dev/null +++ b/vendor/loro-internal/tests/unknown_parent.rs @@ -0,0 +1,102 @@ +//! A snapshot from a newer Loro may store a child whose parent has a container +//! type unknown to this version. `parent()` used to hit `unreachable!()`. + +use bytes::Bytes; +use loro_common::{ContainerID, ContainerType}; +use loro_internal::{ + handler::Handler, loro::ExportMode, HandlerTrait, ListHandler, LoroDoc, ToJson, +}; +use loro_kv_store::{mem_store::MemKvConfig, MemKvStore}; + +const UNKNOWN: ContainerType = ContainerType::Unknown(9); + +/// Header of a stored container: kind, depth, parent. See +/// `ContainerWrapper::encode`. +fn header(kind: ContainerType, depth: u64, parent: &Option<ContainerID>) -> Vec<u8> { + let mut out = vec![kind.to_u8()]; + leb128::write::unsigned(&mut out, depth).unwrap(); + postcard::to_io(parent, &mut out).unwrap(); + out +} + +/// Rewrites the stored header of `child` so its parent is the root container +/// `parent`, which is added with an empty (unknown) state. +fn reparent_in_kv(section: &[u8], child: &ContainerID, parent: &ContainerID) -> Vec<u8> { + let mut kv = MemKvStore::new(MemKvConfig::default()); + kv.import_all(Bytes::copy_from_slice(section)).unwrap(); + let key = child.to_bytes(); + let Some(value) = kv.get(&key) else { + return section.to_vec(); + }; + let kind = ContainerType::try_from_u8(value[0]).unwrap(); + let mut reader = &value[1..]; + let depth = leb128::read::unsigned(&mut reader).unwrap(); + let (_, payload) = postcard::take_from_bytes::<Option<ContainerID>>(reader).unwrap(); + let mut new_value = header(kind, depth, &Some(parent.clone())); + new_value.extend_from_slice(payload); + kv.set(&key, new_value.into()); + kv.set( + &parent.to_bytes(), + header(parent.container_type(), 1, &None).into(), + ); + kv.export_all().to_vec() +} + +/// Rewrites every container state section of a snapshot. +fn forge_snapshot(bytes: &[u8], child: &ContainerID, parent: &ContainerID) -> Vec<u8> { + // magic (4) + checksum (16) + encode mode (2), then the body + let (head, mut body) = bytes.split_at(22); + let mut sections = Vec::new(); + for _ in 0..3 { + let len = u32::from_le_bytes(body[..4].try_into().unwrap()) as usize; + sections.push(&body[4..4 + len]); + body = &body[4 + len..]; + } + assert!(body.is_empty()); + + let mut out = head.to_vec(); + for (i, section) in sections.into_iter().enumerate() { + // The oplog, and a state section of length 1 (a marker), stay as is + let section = if i == 0 || section.len() <= 1 { + section.to_vec() + } else { + reparent_in_kv(section, child, parent) + }; + out.extend_from_slice(&(section.len() as u32).to_le_bytes()); + out.extend_from_slice(§ion); + } + let checksum = xxhash_rust::xxh32::xxh32(&out[20..], u32::from_le_bytes(*b"LORO")); + out[16..20].copy_from_slice(&checksum.to_le_bytes()); + out +} + +#[test] +fn parent_of_a_child_of_an_unknown_container() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(1).unwrap(); + let list = doc + .get_map("m") + .insert_container("x", ListHandler::new_detached()) + .unwrap(); + list.push(loro_common::LoroValue::from(1)).unwrap(); + doc.commit_then_renew(); + let child = list.id(); + + // The creating op is not in a shallow snapshot at the latest version, so + // the stored header decides the parent + let bytes = doc + .export(ExportMode::shallow_snapshot(&doc.oplog_frontiers())) + .unwrap(); + let parent = ContainerID::new_root("future", UNKNOWN); + let forged = forge_snapshot(&bytes, &child, &parent); + assert_ne!(forged, bytes); + + let doc = LoroDoc::new_auto_commit(); + doc.import(&forged).unwrap(); + let list = doc.get_list(child); + let Some(Handler::Unknown(p)) = list.parent() else { + panic!("expected an unknown parent, got {:?}", list.parent()); + }; + assert_eq!(p.id(), parent); + assert_eq!(list.get_value().to_json_value(), serde_json::json!([1])); +} diff --git a/web/build.ts b/web/build.ts deleted file mode 100644 index 6a534ff..0000000 --- a/web/build.ts +++ /dev/null @@ -1,48 +0,0 @@ -// Bundles the editor into ../assets: editor.js (+ map), editor.css, and the Loro WASM as -// a separate content-hashed file (loro-<hash>.wasm). The server serves assets/ with -// mime_guess, so the .wasm goes out as application/wasm and can be stream-compiled. -import { readdirSync, unlinkSync } from "node:fs"; -import { dirname } from "node:path"; -import type { BunPlugin } from "bun"; - -const outdir = `${import.meta.dir}/../assets`; - -// loro-crdt's "web" entry takes the WASM URL in its default init(), so nothing is inlined. -// Aliasing the bare specifier makes loro-prosemirror share the same Loro instance. -const loroWeb: BunPlugin = { - name: "loro-crdt-web", - setup(build) { - build.onResolve({ filter: /^loro-crdt$/ }, () => ({ - path: Bun.resolveSync("loro-crdt/web", import.meta.dir), - })); - }, -}; - -// Copy the WASM out under a name that changes with its bytes; remove older copies we made. -const wasmSource = `${dirname(Bun.resolveSync("loro-crdt/web", import.meta.dir))}/loro_wasm_bg.wasm`; -const wasmBytes = new Uint8Array(await Bun.file(wasmSource).arrayBuffer()); -const digest = new Bun.CryptoHasher("sha256").update(wasmBytes).digest("hex").slice(0, 12); -const wasmName = `loro-${digest}.wasm`; -for (const file of readdirSync(outdir)) { - if (/^loro-[0-9a-f]{12}\.wasm$/.test(file) && file !== wasmName) unlinkSync(`${outdir}/${file}`); -} -await Bun.write(`${outdir}/${wasmName}`, wasmBytes); -console.log(`${outdir}/${wasmName} ${(wasmBytes.length / 1024).toFixed(1)} KiB`); - -for (const entry of ["src/editor.ts", "src/editor.css"]) { - const result = await Bun.build({ - entrypoints: [`${import.meta.dir}/${entry}`], - outdir, - target: "browser", - format: "esm", - minify: true, - sourcemap: "linked", - define: { __LORO_WASM_NAME__: JSON.stringify(wasmName) }, - plugins: [loroWeb], - }); - if (!result.success) { - for (const log of result.logs) console.error(log); - process.exit(1); - } - for (const out of result.outputs) console.log(`${out.path} ${(out.size / 1024).toFixed(1)} KiB`); -} diff --git a/web/bun.lock b/web/bun.lock deleted file mode 100644 index 5da6262..0000000 --- a/web/bun.lock +++ /dev/null @@ -1,58 +0,0 @@ -{ - "lockfileVersion": 2, - "configVersion": 1, - "workspaces": { - "": { - "name": "project-note-editor", - "dependencies": { - "loro-crdt": "1.17.1", - "loro-prosemirror": "0.4.4", - "prosemirror-commands": "1.7.2", - "prosemirror-dropcursor": "^1.8.4", - "prosemirror-gapcursor": "^1.4.1", - "prosemirror-inputrules": "^1.5.1", - "prosemirror-keymap": "1.2.3", - "prosemirror-model": "1.25.12", - "prosemirror-schema-basic": "1.2.5", - "prosemirror-schema-list": "1.5.1", - "prosemirror-state": "1.4.4", - "prosemirror-view": "1.42.8", - }, - }, - }, - "packages": { - "isomorphic.js": ["isomorphic.js@0.2.5", "", {}, "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw=="], - - "lib0": ["lib0@0.2.119", "", { "dependencies": { "isomorphic.js": "^0.2.4" }, "bin": { "0serve": "bin/0serve.js", "0gentesthtml": "bin/gentesthtml.js", "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js" } }, "sha512-vh+TiejVy8Xm+hCdnRfn9BthGNvNUZdEXltNjVZL3TzRIKP3s1lnQh8pWd/Q0wCgY0FPAGVVjFF4ZiHUV3LFgA=="], - - "loro-crdt": ["loro-crdt@1.17.1", "", {}, "sha512-83hWRYG6eMMpPezm+yXWlOqCuUsC0BYY1MVCPW9x2zlikgkHhL7GC7Q6JFH+Hjvauyn287Q1MiwTuRW0lUOUag=="], - - "loro-prosemirror": ["loro-prosemirror@0.4.4", "", { "dependencies": { "lib0": "^0.2.42", "prosemirror-model": "^1.18.1", "prosemirror-state": "^1.4.1", "prosemirror-view": "^1.28.0" }, "peerDependencies": { "loro-crdt": "^1.10.2" } }, "sha512-9Ttd3yHcb6Y+qxsqiS+fNMy9c9bNeimlLd7FShbVwRUBer8iosI9txWZlegzKnNjUUqIRyV15ybM6w3c2zS+Jg=="], - - "orderedmap": ["orderedmap@2.1.1", "", {}, "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g=="], - - "prosemirror-commands": ["prosemirror-commands@1.7.2", "", { "dependencies": { "prosemirror-model": "^1.0.0", "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.10.2" } }, "sha512-q6Q6szxqdu9Xd6EcdKsqXghu5nQdZTpB4Q9yd04WRc7/jt763e/rT60Owh0L1GYY+T46o5rD+9lEN36dZS43tw=="], - - "prosemirror-dropcursor": ["prosemirror-dropcursor@1.8.4", "", { "dependencies": { "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.1.0", "prosemirror-view": "^1.1.0" } }, "sha512-VmKxhcA6a+h5oPSYmfF1ZNeQqPbyYaIxqZsKqeYCyTlPtrjUgNaHL3P8vVaO19oqAV0zuaM/axkowZHrB1P3Tg=="], - - "prosemirror-gapcursor": ["prosemirror-gapcursor@1.4.1", "", { "dependencies": { "prosemirror-keymap": "^1.0.0", "prosemirror-model": "^1.0.0", "prosemirror-state": "^1.0.0", "prosemirror-view": "^1.0.0" } }, "sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw=="], - - "prosemirror-inputrules": ["prosemirror-inputrules@1.5.1", "", { "dependencies": { "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.0.0" } }, "sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw=="], - - "prosemirror-keymap": ["prosemirror-keymap@1.2.3", "", { "dependencies": { "prosemirror-state": "^1.0.0", "w3c-keyname": "^2.2.0" } }, "sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw=="], - - "prosemirror-model": ["prosemirror-model@1.25.12", "", { "dependencies": { "orderedmap": "^2.0.0" } }, "sha512-Ue2gTmXMa7EhpLNhC7J+h4+ykD8ha12K6rrZFFKKJHBForfIStw5gJ6Zrf1mqqAa9NmpmEB4wp9bKmA4eUVjWg=="], - - "prosemirror-schema-basic": ["prosemirror-schema-basic@1.2.5", "", { "dependencies": { "prosemirror-model": "^1.25.0" } }, "sha512-McBWhfgOfThyu3Nltbs8SOUbM4t/h0pxteibaaHd1QR4S+F1t0u7M1ETaCE6/cveFoF+2fowTIBNkJOyeZQjNg=="], - - "prosemirror-schema-list": ["prosemirror-schema-list@1.5.1", "", { "dependencies": { "prosemirror-model": "^1.0.0", "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.7.3" } }, "sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q=="], - - "prosemirror-state": ["prosemirror-state@1.4.4", "", { "dependencies": { "prosemirror-model": "^1.0.0", "prosemirror-transform": "^1.0.0", "prosemirror-view": "^1.27.0" } }, "sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw=="], - - "prosemirror-transform": ["prosemirror-transform@1.12.4", "", { "dependencies": { "prosemirror-model": "^1.21.0" } }, "sha512-2/WuPum3pn+O/Vi2vzpi8210ICUe2kIPXdLYjQ09Pv5DtT5bcKWMJhAKPBwvpPjpp5iOYUVwVEr0gOM1BY1Mgw=="], - - "prosemirror-view": ["prosemirror-view@1.42.8", "", { "dependencies": { "prosemirror-model": "^1.25.12", "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.1.0" } }, "sha512-ftDZjCs9AjAekXmCfJRn2U3IdlRCl0Yc4tZT1/jJWCsz4DiSifEBXtWmpJpw/4f1Rg328uAUQ+u2lCJ0+AVZkw=="], - - "w3c-keyname": ["w3c-keyname@2.2.8", "", {}, "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ=="], - } -} diff --git a/web/package.json b/web/package.json deleted file mode 100644 index 680482e..0000000 --- a/web/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "project-note-editor", - "version": "0.1.0", - "private": true, - "type": "module", - "scripts": { - "build": "bun build.ts" - }, - "dependencies": { - "loro-crdt": "1.17.1", - "loro-prosemirror": "0.4.4", - "prosemirror-commands": "1.7.2", - "prosemirror-dropcursor": "^1.8.4", - "prosemirror-gapcursor": "^1.4.1", - "prosemirror-inputrules": "^1.5.1", - "prosemirror-keymap": "1.2.3", - "prosemirror-model": "1.25.12", - "prosemirror-schema-basic": "1.2.5", - "prosemirror-schema-list": "1.5.1", - "prosemirror-state": "1.4.4", - "prosemirror-view": "1.42.8" - } -} diff --git a/web/src/dom.ts b/web/src/dom.ts deleted file mode 100644 index 0bb0e05..0000000 --- a/web/src/dom.ts +++ /dev/null @@ -1,76 +0,0 @@ -// Shared DOM helpers for the editor chrome: element builder, keycaps, tooltips and -// viewport positioning for floating surfaces (position: fixed, from coordsAtPos). -import type { EditorView } from "prosemirror-view"; - -export const isMac = /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent); -export const MOD = isMac ? "⌘" : "Ctrl"; -export const SHIFT = isMac ? "⇧" : "Shift"; -export const ALT = isMac ? "⌥" : "Alt"; - -/** Creates an element with string attributes and children. Only pass trusted literals as text. */ -export function h<K extends keyof HTMLElementTagNameMap>( - tag: K, - attrs: Record<string, string> = {}, - ...kids: (Node | string)[] -): HTMLElementTagNameMap[K] { - const node = document.createElement(tag); - for (const [name, value] of Object.entries(attrs)) node.setAttribute(name, value); - node.append(...kids); - return node; -} - -/** Mono keycap chips, e.g. keycaps("Ctrl", "K"). Decorative: screen readers get aria-keyshortcuts elsewhere. */ -export function keycaps(...keys: string[]): HTMLSpanElement { - return h( - "span", - { class: "keycaps", "aria-hidden": "true" }, - ...keys.map((key) => h("kbd", { class: "keycap" }, key)), - ); -} - -/** Tooltip shown on hover/focus of its parent button: label, keycaps, optional reason. */ -export function tooltip(label: string, keys: string[], reason?: string): HTMLSpanElement { - const children: (Node | string)[] = [h("span", { class: "tip-label" }, label)]; - if (keys.length) children.push(keycaps(...keys)); - if (reason) children.push(h("span", { class: "tip-reason" }, reason)); - return h("span", { class: "tip", "aria-hidden": "true", role: "presentation" }, ...children); -} - -export interface Box { - top: number; - bottom: number; - left: number; - right: number; -} - -/** Viewport box around the text between two positions (spans lines when needed). */ -export function rangeBox(view: EditorView, from: number, to: number): Box { - const a = view.coordsAtPos(from); - const b = view.coordsAtPos(to); - return { - top: Math.min(a.top, b.top), - bottom: Math.max(a.bottom, b.bottom), - left: Math.min(a.left, b.left), - right: Math.max(a.right, b.right), - }; -} - -const GAP = 8; - -/** - * Positions a fixed element next to a box, centred horizontally and clamped to the - * viewport. "above" flips below when there is no room; "below" flips above at the bottom. - */ -export function placeFloating(el: HTMLElement, box: Box, prefer: "above" | "below"): void { - const width = el.offsetWidth; - const height = el.offsetHeight; - const above = box.top - height - GAP; - const below = box.bottom + GAP; - let top: number; - if (prefer === "above") top = above >= GAP ? above : below; - else top = below + height <= window.innerHeight - GAP ? below : above; - const center = (box.left + box.right) / 2; - const left = Math.min(Math.max(center - width / 2, GAP), window.innerWidth - width - GAP); - el.style.top = `${Math.max(top, GAP)}px`; - el.style.left = `${Math.max(left, GAP)}px`; -} diff --git a/web/src/editing.ts b/web/src/editing.ts deleted file mode 100644 index ed8a0ab..0000000 --- a/web/src/editing.ts +++ /dev/null @@ -1,294 +0,0 @@ -// Editing behaviour on top of the base schema: block/mark commands, keyboard -// shortcuts, markdown-style input rules, cursors for gaps and drops, and the -// empty-note placeholder. The toolbar (toolbar.ts) drives the same commands. -import { - Fragment, - type Attrs, - type Mark, - type MarkType, - type Node as PMNode, - type NodeType, - type Schema, -} from "prosemirror-model"; -import { Plugin, TextSelection, type Command, type EditorState } from "prosemirror-state"; -import { Decoration, DecorationSet, type EditorView } from "prosemirror-view"; -import { t } from "./i18n"; -import { keymap } from "prosemirror-keymap"; -import { lift, setBlockType, toggleMark, wrapIn } from "prosemirror-commands"; -import { liftListItem, wrapInList } from "prosemirror-schema-list"; -import { - InputRule, - inputRules, - textblockTypeInputRule, - undoInputRule, - wrappingInputRule, -} from "prosemirror-inputrules"; -import { dropCursor } from "prosemirror-dropcursor"; -import { gapCursor } from "prosemirror-gapcursor"; - -/** True when the mark applies at the cursor (stored marks included) or across the selection. */ -export function isMarkActive(state: EditorState, type: MarkType): boolean { - const { from, to, empty, $from } = state.selection; - if (empty) return !!type.isInSet(state.storedMarks || $from.marks()); - return state.doc.rangeHasMark(from, to, type); -} - -/** True when the selection's textblock is of `type` (and matches `attrs`, if given). */ -export function isBlockActive(state: EditorState, type: NodeType, attrs?: Attrs): boolean { - const parent = state.selection.$from.parent; - if (parent.type !== type) return false; - return !attrs || Object.keys(attrs).every((k) => parent.attrs[k] === attrs[k]); -} - -/** Nearest ancestor of the selection matching `match`, with its document position. */ -export function findAncestor( - state: EditorState, - match: (node: PMNode) => boolean, -): { node: PMNode; pos: number } | null { - const { $from } = state.selection; - for (let d = $from.depth; d > 0; d--) { - const node = $from.node(d); - if (match(node)) return { node, pos: $from.before(d) }; - } - return null; -} - -/** - * Input rule for inline marks written with delimiters ("**x**", "*x*", "`x`"). - * `pattern` must end with the closing delimiter; capture group 1 is the marked text. - * The delimiter length is passed explicitly so the text positions are exact. - */ -function markInputRule(pattern: RegExp, markType: MarkType, delimLength: number): InputRule { - return new InputRule(pattern, (state, match, start, end) => { - const content = match[1]; - if (!content) return null; - // Input rules run before the last typed character is inserted, so the closing - // delimiter is one character short in the doc. Positions come from the match start. - const textStart = start + match[0].length - delimLength - content.length; - const textEnd = textStart + content.length; - const openStart = textStart - delimLength; - const tr = state.tr; - tr.delete(textEnd, end); - tr.delete(openStart, textStart); - tr.addMark(openStart, openStart + content.length, markType.create()); - tr.removeStoredMark(markType); - return tr; - }); -} - -/** Range of the mark of `type` that contains `pos` within its textblock, or null. */ -export function markRangeAt( - doc: PMNode, - pos: number, - type: MarkType, -): { from: number; to: number; mark: Mark } | null { - const $pos = doc.resolve(pos); - if (!$pos.parent.inlineContent) return null; - const start = $pos.start(); - let found: { from: number; to: number; mark: Mark } | null = null; - $pos.parent.forEach((child, offset) => { - if (found) return; - const from = start + offset; - const to = from + child.nodeSize; - const mark = type.isInSet(child.marks); - if (mark && from <= pos && pos <= to) found = { from, to, mark }; - }); - return found; -} - -/** Accepts plain URLs (adds https://) and http/mailto/relative links; rejects script-like schemes. */ -export function normalizeHref(raw: string): string | null { - const href = raw.trim(); - if (!href) return null; - // Whitespace and control characters are removed before the check, so "java\tscript:" is caught too. - if (/^(javascript|data|vbscript):/i.test(href.replace(/[\s\x00-\x1f]/g, ""))) return null; - if (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("/") || href.startsWith("#")) return href; - return `https://${href}`; -} - -export interface Editing { - /** Keymap, input rules, drop/gap cursors and placeholder. Insert before baseKeymap. */ - plugins: Plugin[]; - paragraph: Command; - heading(level: number): Command; - codeBlock: Command; - bold: Command; - italic: Command; - inlineCode: Command; - link: Command; - bulletList: Command; - orderedList: Command; - blockquote: Command; - horizontalRule: Command; -} - -export interface EditingHooks { - /** Called by Mod-K and the toolbar/bubble link buttons; the floating UI opens the link popover. */ - requestLink(view: EditorView): void; -} - -export function createEditing(schema: Schema, hooks: EditingHooks): Editing { - const { paragraph, heading, code_block, blockquote, horizontal_rule, bullet_list, ordered_list, list_item } = - schema.nodes; - const { strong, em, code, link: linkMark } = schema.marks; - - // Toggling variants: applying the active block type again returns to a paragraph. - const toParagraph = setBlockType(paragraph); - const toggleBlock = - (type: NodeType, attrs?: Attrs): Command => - (state, dispatch) => - isBlockActive(state, type, attrs) - ? toParagraph(state, dispatch) - : setBlockType(type, attrs)(state, dispatch); - - const toggleList = - (type: NodeType): Command => - (state, dispatch) => { - const list = findAncestor(state, (n) => n.type === bullet_list || n.type === ordered_list); - if (!list) return wrapInList(type)(state, dispatch); - if (list.node.type === type) return liftListItem(list_item)(state, dispatch); - // Switching between bullet and ordered: retype the existing list in place. - if (dispatch) dispatch(state.tr.setNodeMarkup(list.pos, type)); - return true; - }; - - const toggleQuote: Command = (state, dispatch) => - findAncestor(state, (n) => n.type === blockquote) - ? lift(state, dispatch) - : wrapIn(blockquote)(state, dispatch); - - // Opens the link popover for a selection, or for the link the cursor is inside. - const toggleLink: Command = (state, dispatch, view) => { - const { $from, empty } = state.selection; - const insideLink = empty && markRangeAt(state.doc, state.selection.from, linkMark) !== null; - const canLink = !empty && $from.parent.inlineContent && $from.parent.type.allowsMarkType(linkMark); - if (!insideLink && !canLink) return false; - if (dispatch && view) hooks.requestLink(view); - return true; - }; - - const insertRule: Command = (state, dispatch) => { - const { $from } = state.selection; - if ($from.parent.type.spec.code) return false; - if (!dispatch) return true; - const tr = state.tr.replaceSelectionWith(horizontal_rule.create()); - if (!tr.selection.$from.parent.inlineContent) { - // Keep a text position after a trailing rule so the user can keep typing. - const pos = tr.selection.from; - tr.insert(pos, paragraph.create()); - tr.setSelection(TextSelection.create(tr.doc, pos + 1)); - } - dispatch(tr.scrollIntoView()); - return true; - }; - - // "---" on its own line becomes a rule followed by an empty paragraph. - const hrRule = new InputRule(/^---$/, (state, _match, start, end) => { - const $start = state.doc.resolve(start); - const depth = $start.depth; - if (depth < 1 || $start.parent.type.spec.code) return null; - const index = $start.index(depth - 1); - const parent = $start.node(depth - 1); - const replacement = Fragment.from([horizontal_rule.create(), paragraph.create()]); - if (!parent.canReplace(index, index + 1, replacement)) return null; - const before = $start.before(); - const tr = state.tr.replaceWith(before, $start.after(), [horizontal_rule.create(), paragraph.create()]); - tr.setSelection(TextSelection.create(tr.doc, before + horizontal_rule.create().nodeSize + 1)); - return tr; - }); - - // Ctrl/Cmd+Shift+V pastes plain text. The keydown sets a short-lived flag, and the paste - // event the browser fires next reads it. Normal paste keeps basic structure and drops styling. - let plainPasteUntil = 0; - const paste = new Plugin({ - props: { - transformPastedHTML(html) { - return html.replace(/\s(?:style|class)\s*=\s*("[^"]*"|'[^']*')/gi, ""); - }, - handleKeyDown(_view, event) { - if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLowerCase() === "v") { - plainPasteUntil = Date.now() + 1000; - } - return false; - }, - handlePaste(view, event) { - if (Date.now() > plainPasteUntil) return false; - plainPasteUntil = 0; - const text = event.clipboardData?.getData("text/plain"); - if (!text) return false; - view.pasteText(text); - return true; - }, - }, - }); - - const keys = keymap({ - "Mod-Alt-0": toParagraph, - "Mod-Alt-1": toggleBlock(heading, { level: 1 }), - "Mod-Alt-2": toggleBlock(heading, { level: 2 }), - "Mod-Alt-3": toggleBlock(heading, { level: 3 }), - "Mod-Shift-8": toggleList(bullet_list), - "Mod-Shift-9": toggleList(ordered_list), - "Mod-k": toggleLink, - "Mod-e": toggleMark(code), - Backspace: undoInputRule, - }); - - const rules = inputRules({ - rules: [ - textblockTypeInputRule(/^(#{1,3})\s$/, heading, (m) => ({ level: m[1].length })), - textblockTypeInputRule(/^```$/, code_block), - wrappingInputRule(/^\s*([-*])\s$/, bullet_list), - wrappingInputRule( - /^(\d+)\.\s$/, - ordered_list, - (m) => ({ order: Number(m[1]) }), - (m, node) => node.childCount + node.attrs.order === Number(m[1]), - ), - wrappingInputRule(/^\s*>\s$/, blockquote), - markInputRule(/\*\*([^*]+)\*\*$/, strong, 2), - markInputRule(/(?:^|[^*])\*([^*]+)\*$/, em, 1), - markInputRule(/`([^`]+)`$/, code, 1), - hrRule, - ], - }); - - // Shown only while the whole note is one empty paragraph. - const placeholder = new Plugin({ - props: { - decorations(state) { - const { doc } = state; - const first = doc.firstChild; - if (doc.childCount !== 1 || !first || first.type !== paragraph || first.content.size > 0) return null; - return DecorationSet.create(doc, [ - Decoration.node(0, first.nodeSize, { - class: "is-placeholder", - "data-placeholder": t("placeholder"), - }), - ]); - }, - }, - }); - - return { - plugins: [ - paste, - keys, - rules, - dropCursor({ color: "var(--primary)", width: 2 }), - gapCursor(), - placeholder, - ], - paragraph: toParagraph, - heading: (level) => toggleBlock(heading, { level }), - codeBlock: toggleBlock(code_block), - bold: toggleMark(strong), - italic: toggleMark(em), - inlineCode: toggleMark(code), - link: toggleLink, - bulletList: toggleList(bullet_list), - orderedList: toggleList(ordered_list), - blockquote: toggleQuote, - horizontalRule: insertRule, - }; -} diff --git a/web/src/editor.css b/web/src/editor.css deleted file mode 100644 index 6b64f63..0000000 --- a/web/src/editor.css +++ /dev/null @@ -1,800 +0,0 @@ -@import "prosemirror-view/style/prosemirror.css"; -@import "prosemirror-gapcursor/style/gapcursor.css"; - -/* - * Editor styles, tokens only ("Graphite & Highlighter", see styles.css). Light/dark is - * handled by the theme variables themselves. Fallbacks are the light values. - * Type: Atkinson Hyperlegible Next (UI and body), Atkinson Hyperlegible Mono (meta, keycaps, code). - */ - -.sr-only { - position: absolute; - width: 1px; - height: 1px; - padding: 0; - margin: -1px; - overflow: hidden; - clip: rect(0, 0, 0, 0); - white-space: nowrap; - border: 0; -} - -/* ---- Keycaps (every visible command shows its shortcut as these) ---- */ - -.keycaps { - display: inline-flex; - align-items: center; - gap: 3px; - margin-inline-start: 6px; - vertical-align: middle; -} - -.keycap { - display: inline-flex; - align-items: center; - justify-content: center; - min-width: 18px; - height: 18px; - padding: 0 4px; - border: 1px solid var(--border, #e3e5ea); - border-bottom-width: 2px; - border-radius: 6px; - background: var(--keycap-bg, #ffffff); - color: var(--muted-foreground, #5b6270); - font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); - font-size: 11px; - font-weight: 500; - line-height: 1; - font-variant-numeric: tabular-nums; -} - -/* ---- Tooltips (toolbar and bubble buttons) ---- */ - -.tip { - position: absolute; - top: calc(100% + 6px); - left: 50%; - z-index: 40; - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 2px; - max-width: 240px; - padding: 4px 6px 4px 8px; - border: 1px solid var(--border, #e3e5ea); - border-radius: 10px; - background: var(--popover, #ffffff); - color: var(--popover-foreground, #16181d); - box-shadow: var(--shadow-float, 0 8px 24px rgb(0 0 0 / 0.12)); - font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); - font-size: 12px; - font-weight: 500; - line-height: 16px; - white-space: nowrap; - pointer-events: none; - opacity: 0; - transform: translate(-50%, -2px); - transition: - opacity 150ms ease-out, - transform 150ms ease-out; -} - -.tip .keycaps { - margin-inline-start: 4px; -} - -.tip-reason { - display: none; - flex-basis: 100%; - color: var(--muted-foreground, #5b6270); - font-weight: 400; -} - -.editor-toolbar-btn:disabled .tip-reason { - display: block; -} - -.editor-toolbar-btn:hover .tip, -.editor-toolbar-btn:focus-visible .tip, -.bubble-btn:hover .tip, -.bubble-btn:focus-visible .tip { - opacity: 1; - transform: translate(-50%, 0); - transition-delay: 300ms; -} - -.bubble .tip { - top: auto; - bottom: calc(100% + 6px); -} - -/* ---- Sync status pill (in the note header's #sync-slot) ---- */ - -#sync-status { - display: inline-flex; - align-items: center; - gap: 6px; - height: 24px; - padding: 0 10px 0 8px; - border: 1px solid var(--border, #e3e5ea); - border-radius: 999px; - background: var(--card, #ffffff); - color: var(--muted-foreground, #5b6270); - font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); - font-size: 12px; - font-weight: 400; - line-height: 16px; - white-space: nowrap; - transition: color 150ms ease-out; -} - -#sync-status::before { - content: ""; - width: 6px; - height: 6px; - border-radius: 50%; - background: currentColor; - flex: none; -} - -#sync-status[data-state="saved"] { - color: var(--ok, #1f7a4d); -} - -#sync-status[data-state="saving"] { - color: var(--muted-foreground, #5b6270); -} - -#sync-status[data-state="local"], -#sync-status[data-state="reconnecting"] { - color: var(--warn, #9a5b00); -} - -/* ---- Note header: one row, the formatting toolbar sits inside it ---- */ - -#note-header { - container: note-header / inline-size; -} - -/* ---- Toolbar: compact, icons only, one line (groups drop out when the row is narrow) ---- */ - -.editor-toolbar { - display: flex; - flex: 0 0 auto; - flex-wrap: nowrap; - align-items: center; - gap: 2px; -} - -.editor-toolbar-group { - display: flex; - align-items: center; - gap: 2px; -} - -.editor-toolbar-group + .editor-toolbar-group::before { - content: ""; - width: 1px; - height: 16px; - margin: 0 4px; - background: var(--border, #e3e5ea); -} - -/* Lower-priority commands leave the bar as the header narrows, so the title keeps - at least 8rem. They stay reachable through the slash menu (/) and markdown shortcuts. */ -@container note-header (max-width: 879px) { - .note-crumb-notebook { - display: none; - } -} - -@container note-header (max-width: 779px) { - .editor-toolbar-group[data-group="blocks"] { - display: none; - } -} - -@container note-header (max-width: 619px) { - .editor-toolbar-btn[data-command="h1"], - .editor-toolbar-btn[data-command="h2"], - .editor-toolbar-btn[data-command="h3"] { - display: none; - } -} - -@container note-header (max-width: 559px) { - #sync-status { - gap: 0; - padding: 0 8px; - font-size: 0; - } -} - -@container note-header (max-width: 469px) { - .editor-toolbar-group[data-group="history"] { - display: none; - } -} - -@container note-header (max-width: 419px) { - .editor-toolbar-btn[data-command="paragraph"], - .editor-toolbar-group[data-group="headings"] { - display: none; - } - .note-crumb { - min-width: 6rem; - } -} - -.editor-toolbar-btn { - position: relative; - display: inline-grid; - place-items: center; - width: 28px; - height: 28px; - margin: 0; - padding: 0; - border: 0; - border-radius: 6px; - background: transparent; - color: var(--muted-foreground, #5b6270); - cursor: pointer; - transition: - background-color 150ms ease-out, - color 150ms ease-out; -} - -.editor-toolbar-icon { - display: grid; - place-items: center; -} - -.editor-toolbar-icon svg { - display: block; -} - -.editor-toolbar-btn:hover:not(:disabled) { - background: var(--sidebar-accent, #e3e6eb); - color: var(--foreground, #16181d); -} - -.editor-toolbar-btn[aria-pressed="true"] { - background: var(--active-row, #d9ebd3); - color: var(--active-row-foreground, #1f3d22); -} - -.editor-toolbar-btn:disabled { - opacity: 0.4; - cursor: not-allowed; -} - -.editor-toolbar-btn:focus-visible, -.bubble-btn:focus-visible, -.btn:focus-visible, -.link-input:focus-visible, -.slash-item:focus-visible { - outline: 2px solid var(--ring, #8a5a00); - outline-offset: 2px; -} - -/* ---- Floating surfaces: bubble, link popover, slash menu ---- */ - -.bubble, -.popover { - position: fixed; - z-index: 50; - color: var(--popover-foreground, #16181d); - background: var(--popover, #ffffff); - border: 1px solid var(--border, #e3e5ea); - border-radius: 10px; - box-shadow: var(--shadow-float, 0 8px 24px rgb(0 0 0 / 0.12)); - font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); - font-size: 14px; - line-height: 20px; -} - -.bubble[hidden], -.popover[hidden], -.link-view[hidden], -.link-edit[hidden], -.link-error[hidden] { - display: none; -} - -.bubble { - display: flex; - align-items: center; - gap: 2px; - padding: 4px; -} - -.bubble-btn { - position: relative; - display: inline-grid; - place-items: center; - min-width: 28px; - height: 28px; - margin: 0; - padding: 0 6px; - border: 0; - border-radius: 6px; - background: transparent; - color: var(--foreground, #16181d); - font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); - font-size: 13px; - font-weight: 700; - line-height: 1; - cursor: pointer; - transition: background-color 150ms ease-out; -} - -.bubble-btn:hover:not(:disabled) { - background: var(--sidebar-accent, #e3e6eb); -} - -.bubble-btn[aria-pressed="true"] { - background: var(--active-row, #d9ebd3); -} - -.bubble-btn:disabled { - opacity: 0.4; - cursor: not-allowed; -} - -.bubble-btn[data-command="italic"] .bubble-glyph { - font-style: italic; - font-weight: 500; -} - -.bubble-btn[data-command="bold"] .bubble-glyph { - font-weight: 800; -} - -.bubble-btn[data-command="code"] .bubble-glyph { - font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); - font-size: 12px; - font-weight: 500; -} - -.link-popover { - width: min(360px, calc(100vw - 16px)); - box-sizing: border-box; - padding: 10px; -} - -.link-row { - display: flex; - gap: 6px; -} - -.link-input { - flex: 1; - min-width: 0; - height: 32px; - padding: 0 10px; - border: 1px solid var(--border, #e3e5ea); - border-radius: 6px; - background: var(--card, #ffffff); - color: var(--foreground, #16181d); - font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); - font-size: 13px; -} - -.link-input[aria-invalid="true"] { - border-color: var(--bad, #b3261e); -} - -.link-input::placeholder { - color: var(--muted-foreground, #5b6270); -} - -.link-error { - margin: 6px 0 0; - color: var(--bad, #b3261e); - font-size: 12px; - line-height: 16px; -} - -.link-actions { - display: flex; - flex-wrap: wrap; - gap: 6px; - margin-top: 8px; -} - -.link-view { - display: grid; - gap: 2px; -} - -.link-href { - display: block; - color: var(--link, #8a5a00); - font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); - font-size: 13px; - line-height: 18px; - overflow-wrap: anywhere; -} - -.btn { - display: inline-flex; - align-items: center; - gap: 6px; - height: 28px; - padding: 0 10px; - border: 1px solid var(--border, #e3e5ea); - border-radius: 6px; - background: var(--card, #ffffff); - color: var(--foreground, #16181d); - font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); - font-size: 13px; - font-weight: 500; - line-height: 1; - cursor: pointer; - transition: background-color 150ms ease-out; -} - -.btn:hover:not(:disabled) { - background: var(--sidebar-accent, #e3e6eb); -} - -.btn:disabled { - opacity: 0.45; - cursor: not-allowed; -} - -.btn-primary { - border-color: transparent; - background: var(--primary, #f2b600); - color: var(--primary-foreground, #16181d); -} - -.btn-primary:hover:not(:disabled) { - background: var(--primary, #f2b600); - opacity: 0.9; -} - -.btn-primary .keycaps { - margin-inline-start: 2px; -} - -.btn-primary .keycap { - border-color: transparent; - border-bottom-color: color-mix(in srgb, var(--primary-foreground, #16181d) 35%, transparent); - background: transparent; - color: inherit; -} - -.slash-menu { - width: 264px; - max-width: calc(100vw - 16px); - box-sizing: border-box; - padding: 4px; -} - -.slash-list { - max-height: 288px; - overflow-y: auto; -} - -.slash-item { - display: flex; - align-items: center; - justify-content: space-between; - gap: 12px; - min-height: 32px; - padding: 0 8px; - border-radius: 6px; - color: var(--foreground, #16181d); - cursor: pointer; -} - -.slash-item[aria-selected="true"] { - background: var(--active-row, #d9ebd3); -} - -.slash-item .keycaps { - margin-inline-start: 0; -} - -.slash-empty { - padding: 8px; - color: var(--muted-foreground, #5b6270); - font-size: 13px; -} - -.slash-footer { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 2px; - margin-top: 4px; - padding: 6px 8px 2px; - border-top: 1px solid var(--border, #e3e5ea); - color: var(--muted-foreground, #5b6270); - font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); - font-size: 11px; - line-height: 16px; -} - -.slash-footer .keycaps { - margin-inline-start: 0; -} - -/* Note suggestions: long titles are cut with an ellipsis */ - -.note-menu .slash-label { - min-width: 0; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -/* ---- Editor surface ---- */ - -#editor { - max-width: calc(68ch + 48px); - margin: 0 auto; - padding: 32px 24px 30vh; - box-sizing: border-box; -} - -#editor .ProseMirror { - min-height: 60vh; - max-width: 68ch; - margin: 0 auto; - outline: none; - color: var(--foreground, #16181d); - caret-color: var(--foreground, #16181d); - font-family: var(--font-sans, "Atkinson Hyperlegible Next", sans-serif); - font-size: 17px; - line-height: 1.65; - overflow-wrap: break-word; - word-wrap: break-word; - font-variant-ligatures: common-ligatures; -} - -#editor .ProseMirror:focus, -#editor .ProseMirror:focus-visible { - outline: none; -} - -#editor .ProseMirror > * + * { - margin-top: 0.75em; -} - -#editor .ProseMirror ::selection, -#editor .ProseMirror::selection { - background: var(--mark, #ffe08a); - color: var(--foreground, #16181d); -} - -#editor .ProseMirror p { - margin: 0; -} - -/* Placeholder: shown by the placeholder decoration while the note is empty. */ -#editor .ProseMirror p.is-placeholder::before { - content: attr(data-placeholder); - float: left; - height: 0; - color: var(--muted-foreground, #5b6270); - pointer-events: none; -} - -/* Headings: 30/36, 23/30, 19/26, all bold. */ -#editor .ProseMirror h1, -#editor .ProseMirror h2, -#editor .ProseMirror h3 { - margin: 0; - color: var(--foreground, #16181d); - font-weight: 700; - letter-spacing: -0.01em; -} - -#editor .ProseMirror > * + h1, -#editor .ProseMirror > * + h2, -#editor .ProseMirror > * + h3 { - margin-top: 1.4em; -} - -#editor .ProseMirror h1 { - font-size: 30px; - line-height: 36px; -} - -#editor .ProseMirror h2 { - font-size: 23px; - line-height: 30px; -} - -#editor .ProseMirror h3 { - font-size: 19px; - line-height: 26px; -} - -/* Lists */ - -#editor .ProseMirror ul, -#editor .ProseMirror ol { - margin: 0; - padding-left: 1.6em; -} - -#editor .ProseMirror ul { - list-style: disc; -} - -#editor .ProseMirror ol { - list-style: decimal; -} - -#editor .ProseMirror ul ul { - list-style: circle; -} - -#editor .ProseMirror ul ul ul { - list-style: square; -} - -#editor .ProseMirror li { - margin: 0.2em 0; -} - -#editor .ProseMirror li::marker { - color: var(--muted-foreground, #5b6270); -} - -#editor .ProseMirror li > p + p, -#editor .ProseMirror li > * + ul, -#editor .ProseMirror li > * + ol { - margin-top: 0.2em; -} - -/* Quote */ - -#editor .ProseMirror blockquote { - margin: 0; - padding: 2px 0 2px 16px; - border-left: 3px solid var(--border, #e3e5ea); - color: var(--muted-foreground, #5b6270); -} - -/* Code: mono on the background token, hairline border */ - -#editor .ProseMirror code { - padding: 1px 5px; - border: 1px solid var(--border, #e3e5ea); - border-radius: 6px; - background: var(--background, #f5f6f8); - color: var(--foreground, #16181d); - font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); - font-size: 0.88em; -} - -#editor .ProseMirror pre { - margin: 0; - padding: 12px 14px; - border: 1px solid var(--border, #e3e5ea); - border-radius: 10px; - background: var(--background, #f5f6f8); - color: var(--foreground, #16181d); - font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); - font-size: 14px; - line-height: 22px; - overflow-x: auto; - white-space: pre; -} - -#editor .ProseMirror pre code { - padding: 0; - border: 0; - border-radius: 0; - background: none; - font-size: inherit; -} - -/* Marks: search-style highlight */ - -#editor .ProseMirror mark { - padding: 0 0.1em; - border-radius: 3px; - background: var(--mark, #ffe08a); - color: inherit; -} - -/* Links: accent ink with a quiet underline */ - -#editor .ProseMirror a { - color: var(--link, #8a5a00); - text-decoration-line: underline; - text-decoration-thickness: 1px; - text-decoration-color: color-mix(in srgb, var(--link, #8a5a00) 45%, transparent); - text-underline-offset: 3px; - cursor: pointer; -} - -#editor .ProseMirror a:hover { - text-decoration-color: var(--link, #8a5a00); -} - -/* Note links (href /notes/<id>): a tinted chip, underlined only on hover */ - -#editor .ProseMirror a[href^="/notes/"] { - padding: 0 0.2em; - border-radius: 4px; - background: color-mix(in srgb, var(--link, #8a5a00) 12%, transparent); - text-decoration-line: none; - box-decoration-break: clone; - -webkit-box-decoration-break: clone; -} - -#editor .ProseMirror a[href^="/notes/"]:hover { - text-decoration-line: underline; -} - -/* Horizontal rule */ - -#editor .ProseMirror hr { - margin: 2em 0; - border: 0; - border-top: 1px solid var(--border, #e3e5ea); -} - -#editor .ProseMirror hr.ProseMirror-selectednode { - outline: 2px solid var(--ring, #8a5a00); - outline-offset: 4px; - border-radius: 2px; -} - -/* ---- Remote cursors and selections (loro-prosemirror classes) ---- */ - -.ProseMirror-loro-cursor { - position: relative; - margin-left: -1px; - margin-right: -1px; - /* border-color is set inline per user */ - border-left: 2px solid; - word-break: normal; - pointer-events: none; -} - -/* Name label in the user's color, mono 11px. */ -.ProseMirror-loro-cursor > div { - position: absolute; - top: -1.5em; - left: -2px; - padding: 0 5px; - border-radius: 4px 4px 4px 0; - /* background-color is set inline per user */ - color: #ffffff; - font-family: var(--font-mono, "Atkinson Hyperlegible Mono", ui-monospace, monospace); - font-size: 11px; - font-weight: 500; - line-height: 16px; - white-space: nowrap; - user-select: none; -} - -.loro-selection { - border-radius: 2px; -} - -@media (prefers-reduced-motion: reduce) { - .editor-toolbar-btn, - .bubble-btn, - .btn, - .tip, - #sync-status { - transition-duration: 0ms !important; - transition-delay: 0ms !important; - } -} - -@media (forced-colors: active) { - .editor-toolbar-btn[aria-pressed="true"], - .bubble-btn[aria-pressed="true"], - .slash-item[aria-selected="true"] { - outline: 2px solid CanvasText; - } -} diff --git a/web/src/editor.ts b/web/src/editor.ts deleted file mode 100644 index ed236cc..0000000 --- a/web/src/editor.ts +++ /dev/null @@ -1,394 +0,0 @@ -// "loro-crdt/web" is the entry build.ts bundles for every "loro-crdt" import. Its init is the -// default export of loro_wasm.js, the module web/index.js re-exports, so there is one WASM instance. -import { LoroDoc, VersionVector } from "loro-crdt/web"; -import init from "loro-crdt/web/loro_wasm.js"; -import { - CursorEphemeralStore, - LoroEphemeralCursorPlugin, - LoroSyncPlugin, - LoroUndoPlugin, - redo, - undo, -} from "loro-prosemirror"; -import type { CursorUser, LoroDocType } from "loro-prosemirror"; -import { Schema, type NodeSpec } from "prosemirror-model"; -import { EditorState } from "prosemirror-state"; -import { EditorView } from "prosemirror-view"; -import { schema as basicSchema } from "prosemirror-schema-basic"; -import { - addListNodes, - liftListItem, - sinkListItem, - splitListItem, -} from "prosemirror-schema-list"; -import { keymap } from "prosemirror-keymap"; -import { baseKeymap, toggleMark } from "prosemirror-commands"; -import { createEditing } from "./editing"; -import { createFloating } from "./floating"; -import { createNoteLinks } from "./noteLinks"; -import { createToolbar } from "./toolbar"; -import { h } from "./dom"; -import { t, type Key } from "./i18n"; - -// Replaced at build time with the content-hashed name of the WASM file in assets/. -declare const __LORO_WASM_NAME__: string; - -// The WASM ships as its own file so browsers can stream-compile and cache it. It must be -// initialized before the first LoroDoc or ephemeral store exists. -await init({ module_or_path: new URL(`/${__LORO_WASM_NAME__}`, location.origin) }); - -// ---- Wire protocol (must match the Rust server) ---- -const TAG_SYNC_REQ = 0x01; -const TAG_UPDATE = 0x02; -const TAG_EPHEMERAL = 0x03; - -// ---- Schema: basic nodes/marks + lists ---- -// Code blocks keep the fence language (```rust) so markdown round-trips. -const codeBlock: NodeSpec = { - ...basicSchema.spec.nodes.get("code_block")!, - attrs: { language: { default: null } }, - parseDOM: [ - { - tag: "pre", - preserveWhitespace: "full", - getAttrs: (dom) => ({ language: (dom as HTMLElement).dataset.language || null }), - }, - ], - toDOM: (node) => [ - "pre", - node.attrs.language ? { "data-language": node.attrs.language } : {}, - ["code", 0], - ], -}; - -const schema = new Schema({ - nodes: addListNodes( - basicSchema.spec.nodes.update("code_block", codeBlock), - "paragraph block*", - "block", - ), - marks: basicSchema.spec.marks, -}); - -// ---- Per-tab peer identity for cursors ---- -function peerIdentity(): CursorUser { - const key = "project-note-peer"; - let stored: CursorUser | null = null; - try { - const raw = sessionStorage.getItem(key); - if (raw) stored = JSON.parse(raw) as CursorUser; - } catch { - stored = null; - } - if (!stored) { - const n = 1000 + Math.floor(Math.random() * 9000); - const hue = Math.floor(Math.random() * 360); - stored = { name: `user-${n}`, color: `hsl(${hue} 70% 45%)` }; - try { - sessionStorage.setItem(key, JSON.stringify(stored)); - } catch { - // sessionStorage unavailable: identity just lasts for this load - } - } - return stored; -} - -// ---- Document, presence, editor ---- -const mount = document.getElementById("editor"); -if (!mount) throw new Error("#editor element not found"); -const noteId = mount.dataset.noteId ?? ""; -const noteTitle = - mount.dataset.noteTitle?.trim() || - document.querySelector<HTMLElement>("header span.truncate")?.textContent?.trim() || - "Note"; - -const doc = new LoroDoc() as unknown as LoroDocType; -const user = peerIdentity(); -const presence = new CursorEphemeralStore((doc as unknown as LoroDoc).peerIdStr); - -const statusEl = ensureStatusElement(mount); -const liveEl = ensureLiveRegion(); - -// Remote selections are tinted with the peer's color instead of loro's default yellow. -function peerSelection(peer: string) { - const all = presence.getAll() as Record<string, { user?: { color?: string } } | undefined>; - const color = all[peer]?.user?.color ?? "currentColor"; - return { - class: "loro-selection", - "data-peer": peer, - style: `background-color: color-mix(in srgb, ${color} 28%, transparent)`, - }; -} - -// Link commands open the floating popover; the floating UI is created right after. -const editing = createEditing(schema, { requestLink: (v) => floating.openLink(v) }); -const floating = createFloating(schema, editing); -const toolbarPlugin = createToolbar(mount, schema, editing, { undo, redo }); - -const noteLinks = createNoteLinks(schema, { currentNoteId: noteId }); - -const listKeys = keymap({ - Enter: splitListItem(schema.nodes.list_item), - Tab: sinkListItem(schema.nodes.list_item), - "Shift-Tab": liftListItem(schema.nodes.list_item), - "Mod-b": toggleMark(schema.marks.strong), - "Mod-i": toggleMark(schema.marks.em), - "Mod-`": toggleMark(schema.marks.code), -}); - -const state = EditorState.create({ - schema, - plugins: [ - LoroSyncPlugin({ doc }), - LoroUndoPlugin({ doc }), - keymap({ - "Mod-z": undo, - "Mod-y": redo, - "Shift-Mod-z": redo, - }), - ...floating.plugins, - ...noteLinks.plugins, - listKeys, - ...editing.plugins, - keymap(baseKeymap), - toolbarPlugin, - LoroEphemeralCursorPlugin(presence, { user, createSelection: peerSelection }), - ], -}); - -// The editor is created only after the server's state is imported. Creating it on an -// empty doc makes loro-prosemirror write a fresh root that competes with the real one. -let view: EditorView | null = null; -let serverVersion: VersionVector | null = null; - -function maybeCreateEditor() { - if (view || !serverVersion) return; - const ours = (doc as unknown as LoroDoc).oplogVersion(); - const cmp = serverVersion.compare(ours); - if (cmp === undefined || cmp > 0) return; - view = new EditorView(mount!, { - state, - attributes: { - role: "textbox", - "aria-multiline": "true", - "aria-label": noteTitle, - }, - }); -} - -// ---- Transport ---- -const url = `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/notes/${encodeURIComponent(noteId)}/ws`; -const BASE_DELAY = 500; -const MAX_DELAY = 5000; -let socket: WebSocket | null = null; -let retryDelay = BASE_DELAY; -// False until this connection has sent our offline changes. Presence refers to -// containers inside the doc, so it must not reach peers before those changes do. -let presenceReady = false; - -function frame(tag: number, payload: Uint8Array): Uint8Array<ArrayBuffer> { - const out = new Uint8Array(payload.length + 1); - out[0] = tag; - out.set(payload, 1); - return out; -} - -function isOpen(): boolean { - return socket !== null && socket.readyState === WebSocket.OPEN; -} - -function send(tag: number, payload: Uint8Array) { - if (isOpen()) socket!.send(frame(tag, payload)); -} - -// ---- Sync status ---- -// "Saving…" is shown only when local changes stay unsent for more than 1.5s. A change is -// confirmed sent once the socket's buffer is empty and 300ms have passed without edits. -type SyncState = "connecting" | "reconnecting" | "saved" | "saving" | "local"; -const STATUS_KEY: Record<SyncState, Key> = { - connecting: "statusConnecting", - reconnecting: "statusReconnecting", - saved: "statusSaved", - saving: "statusSaving", - local: "statusLocal", -}; - -let connected = false; -let everConnected = false; -let dirty = false; -let savingShown = false; -let savingTimer: ReturnType<typeof setTimeout> | undefined; -let flushTimer: ReturnType<typeof setTimeout> | undefined; - -function currentSyncState(): SyncState { - if (navigator.onLine === false) return "local"; - if (!connected) return everConnected ? "reconnecting" : "connecting"; - return savingShown ? "saving" : "saved"; -} - -function renderStatus() { - const syncState = currentSyncState(); - statusEl.dataset.state = syncState; - statusEl.textContent = t(STATUS_KEY[syncState]); -} - -function markLocalChange() { - if (!dirty) { - dirty = true; - clearTimeout(savingTimer); - savingTimer = setTimeout(() => { - if (dirty) { - savingShown = true; - renderStatus(); - } - }, 1500); - } - clearTimeout(flushTimer); - flushTimer = setTimeout(checkFlushed, 300); -} - -function checkFlushed() { - if (!dirty) return; - if (isOpen() && socket!.bufferedAmount > 0) { - flushTimer = setTimeout(checkFlushed, 100); - return; - } - dirty = false; - clearTimeout(savingTimer); - savingShown = false; - renderStatus(); -} - -function setConnected(value: boolean) { - connected = value; - if (value) everConnected = true; - renderStatus(); -} - -// The pill lives in the note header's #sync-slot (right side, next to the actions menu). -function ensureStatusElement(anchor: HTMLElement): HTMLElement { - let el = document.getElementById("sync-status"); - if (!el) { - el = document.createElement("span"); - el.id = "sync-status"; - const slot = document.getElementById("sync-slot"); - if (slot) slot.append(el); - else anchor.before(el); - } - return el; -} - -// Visually hidden; only offline/online transitions are announced. -function ensureLiveRegion(): HTMLElement { - const el = h("div", { class: "sr-only", role: "status", "aria-live": "polite" }); - document.body.append(el); - return el; -} - -function announce(message: string) { - liveEl.textContent = message; -} - -window.addEventListener("offline", () => { - renderStatus(); - announce(t("announceOffline")); -}); -window.addEventListener("online", () => { - renderStatus(); - announce(t("announceOnline")); -}); - -// Local doc changes: only sent while the socket is open. -// Offline changes are delivered by the SYNC_REQ handshake on reconnect. -(doc as unknown as LoroDoc).subscribeLocalUpdates((bytes: Uint8Array) => { - send(TAG_UPDATE, bytes); - markLocalChange(); -}); - -// Local presence changes: sent while open. -presence.subscribeLocalUpdates((bytes: Uint8Array) => { - if (presenceReady) send(TAG_EPHEMERAL, bytes); -}); - -function handleMessage(data: ArrayBuffer | string) { - if (typeof data === "string") return; - const bytes = new Uint8Array(data); - if (bytes.length === 0) return; - const tag = bytes[0]; - const payload = bytes.subarray(1); - switch (tag) { - case TAG_SYNC_REQ: { - // Peer asks for what we have beyond its version: reply with an update. - const from = VersionVector.decode(payload); - const update = (doc as unknown as LoroDoc).export({ mode: "update", from }); - send(TAG_UPDATE, update); - if (!presenceReady) { - presenceReady = true; - send(TAG_EPHEMERAL, presence.encodeAll()); - } - if (!serverVersion) { - serverVersion = from; - maybeCreateEditor(); - } - break; - } - case TAG_UPDATE: - try { - (doc as unknown as LoroDoc).import(payload); - maybeCreateEditor(); - } catch (err) { - console.error("failed to import update", err); - } - break; - case TAG_EPHEMERAL: - try { - presence.apply(payload); - } catch (err) { - console.error("failed to apply presence", err); - } - break; - default: - console.warn("unknown frame tag", tag); - } -} - -function connect() { - const ws = new WebSocket(url); - ws.binaryType = "arraybuffer"; - socket = ws; - - ws.onopen = () => { - retryDelay = BASE_DELAY; - setConnected(true); - // Handshake: ask the server for what we are missing. - presenceReady = false; - send(TAG_SYNC_REQ, (doc as unknown as LoroDoc).oplogVersion().encode()); - }; - - ws.onmessage = (ev: MessageEvent) => handleMessage(ev.data); - - ws.onerror = () => { - ws.close(); - }; - - ws.onclose = () => { - if (socket === ws) socket = null; - if (detached) return; - setConnected(false); - setTimeout(connect, retryDelay); - retryDelay = Math.min(retryDelay * 2, MAX_DELAY); - }; -} - -// Live search swaps the page content without a reload; it fires `note:detach` first so -// this editor closes its socket instead of syncing a note that is no longer on screen. -let detached = false; -window.addEventListener("note:detach", () => { - detached = true; - socket?.close(); - view?.destroy(); - view = null; -}); - -renderStatus(); -connect(); diff --git a/web/src/floating.ts b/web/src/floating.ts deleted file mode 100644 index 2cf4514..0000000 --- a/web/src/floating.ts +++ /dev/null @@ -1,453 +0,0 @@ -// Floating editor UI, all plain DOM on <body> and positioned from view.coordsAtPos: -// - selection bubble menu (formatting, shown for a non-empty text selection), -// - link popover (edit mode for Mod-K / buttons, view mode when a link is clicked), -// - slash menu (typing "/" at the start of a block or after a space). -// One ProseMirror plugin keeps them in sync with the editor state. -import type { MarkType, Schema } from "prosemirror-model"; -import { Plugin, TextSelection, type Command, type EditorState } from "prosemirror-state"; -import type { EditorView } from "prosemirror-view"; -import { t } from "./i18n"; -import { isBlockActive, isMarkActive, markRangeAt, normalizeHref, type Editing } from "./editing"; -import { ALT, MOD, SHIFT, h, keycaps, placeFloating, rangeBox, tooltip } from "./dom"; -import { isNoteHref } from "./noteLinks"; - -interface BubbleItem { - id: string; - label: string; - glyph: string; - keys: string[]; - run: Command; - active: (state: EditorState) => boolean; -} - -interface SlashItem { - id: string; - label: string; - /** English words the filter also matches, so "h2" or "list" work in either language. */ - keywords: string; - keys: string[]; - run: Command; -} - -export interface Floating { - plugins: Plugin[]; - /** Opens the link popover for the selection, or for the link the cursor is in. */ - openLink(view: EditorView): void; -} - -interface LinkState { - from: number; - to: number; - mode: "edit" | "view"; - /** Existing href at the range, if any. */ - href: string | null; -} - -/** Position of an open "/query" trigger and what has been typed after the slash. */ -function slashContext(state: EditorState): { from: number; query: string } | null { - const { selection } = state; - if (!(selection instanceof TextSelection) || !selection.empty) return null; - const $from = selection.$from; - if (!$from.parent.isTextblock || $from.parent.type.spec.code) return null; - const before = $from.parent.textBetween(0, $from.parentOffset, undefined, "\n"); - const match = /(?:^|\s)\/([^\s/]*)$/.exec(before); - if (!match) return null; - return { from: $from.pos - match[1].length - 1, query: match[1] }; -} - -function hrefInRange(state: EditorState, from: number, to: number, type: MarkType): string | null { - let href: string | null = null; - state.doc.nodesBetween(from, to, (node) => { - if (href !== null) return false; - const mark = type.isInSet(node.marks); - if (mark) href = String(mark.attrs.href); - return href === null; - }); - return href; -} - -export function createFloating(schema: Schema, editing: Editing): Floating { - const { strong, em, code, link: linkMark } = schema.marks; - const { heading } = schema.nodes; - - let view: EditorView | null = null; - let bubbleDismissed = false; - let link: LinkState | null = null; - let slashFrom: number | null = null; - let slashQuery = ""; - let slashIndex = 0; - let slashFiltered: SlashItem[] = []; - let slashDismissed: number | null = null; - - // ---- Bubble menu ---- - const bubbleItems: BubbleItem[] = [ - { id: "bold", label: t("bold"), glyph: "B", keys: [MOD, "B"], run: editing.bold, active: (s) => isMarkActive(s, strong) }, - { id: "italic", label: t("italic"), glyph: "I", keys: [MOD, "I"], run: editing.italic, active: (s) => isMarkActive(s, em) }, - { id: "code", label: t("inlineCode"), glyph: "</>", keys: [MOD, "E"], run: editing.inlineCode, active: (s) => isMarkActive(s, code) }, - { id: "link", label: t("link"), glyph: "Link", keys: [MOD, "K"], run: editing.link, active: (s) => isMarkActive(s, linkMark) }, - { id: "h1", label: t("heading1"), glyph: "H1", keys: [MOD, ALT, "1"], run: editing.heading(1), active: (s) => isBlockActive(s, heading, { level: 1 }) }, - { id: "h2", label: t("heading2"), glyph: "H2", keys: [MOD, ALT, "2"], run: editing.heading(2), active: (s) => isBlockActive(s, heading, { level: 2 }) }, - { id: "h3", label: t("heading3"), glyph: "H3", keys: [MOD, ALT, "3"], run: editing.heading(3), active: (s) => isBlockActive(s, heading, { level: 3 }) }, - ]; - - const bubble = h("div", { class: "bubble", role: "toolbar", "aria-label": t("bubbleLabel") }); - bubble.hidden = true; - const bubbleButtons = bubbleItems.map((item) => { - const btn = h( - "button", - { type: "button", class: "bubble-btn", "aria-label": item.label, "data-command": item.id }, - h("span", { class: "bubble-glyph", "aria-hidden": "true" }, item.glyph), - tooltip(item.label, item.keys), - ); - btn.addEventListener("click", () => { - if (!view) return; - item.run(view.state, view.dispatch, view); - if (item.id !== "link") view.focus(); - }); - bubble.append(btn); - return { btn, item }; - }); - // Keep the text selection while pressing bubble buttons. - bubble.addEventListener("mousedown", (e) => e.preventDefault()); - - // ---- Link popover (edit and view panels share one element) ---- - const linkPop = h("div", { class: "popover link-popover", role: "dialog", "aria-label": t("linkDialog") }); - linkPop.hidden = true; - - const editPanel = h("form", { class: "link-edit", novalidate: "" }); - const linkInput = h("input", { - type: "text", - class: "link-input", - inputmode: "url", - autocomplete: "off", - autocapitalize: "off", - spellcheck: "false", - placeholder: "https://", - "aria-label": t("linkUrl"), - "aria-describedby": "link-error", - }); - const linkError = h("p", { class: "link-error", id: "link-error", role: "alert" }); - linkError.hidden = true; - const applyBtn = h("button", { type: "submit", class: "btn btn-primary" }, t("apply"), keycaps("↵")); - const editRemove = h("button", { type: "button", class: "btn" }, t("remove")); - const editOpen = h("button", { type: "button", class: "btn" }, t("open")); - editPanel.append( - h("div", { class: "link-row" }, linkInput, applyBtn), - linkError, - h("div", { class: "link-actions" }, editRemove, editOpen), - ); - - // View mode is a small menu: href as its label, then Edit / Remove / Open as menu items. - const viewPanel = h("div", { class: "link-view", role: "menu", "aria-label": t("linkMenu") }); - const linkHref = h("span", { class: "link-href" }); - const viewEdit = h("button", { type: "button", class: "btn", role: "menuitem" }, t("edit")); - const viewRemove = h("button", { type: "button", class: "btn", role: "menuitem" }, t("remove")); - const viewOpen = h("button", { type: "button", class: "btn", role: "menuitem" }, t("open")); - viewPanel.append(linkHref, h("div", { class: "link-actions", role: "none" }, viewEdit, viewRemove, viewOpen)); - - linkPop.append(editPanel, viewPanel); - - function closeLink(restoreFocus: boolean) { - if (!link) return; - link = null; - linkPop.hidden = true; - if (restoreFocus) view?.focus(); - } - - function showLink(v: EditorView, from: number, to: number, mode: "edit" | "view") { - closeSlash(); - const href = hrefInRange(v.state, from, to, linkMark); - link = { from, to, mode, href }; - linkPop.hidden = false; - editPanel.hidden = mode !== "edit"; - viewPanel.hidden = mode !== "view"; - linkError.hidden = true; - linkInput.removeAttribute("aria-invalid"); - linkInput.value = href ?? ""; - linkHref.textContent = href ?? ""; - for (const btn of [editRemove, editOpen, viewRemove, viewOpen]) { - btn.disabled = href === null; - btn.title = href === null ? t("linkNeedsLink") : ""; - } - renderFloating(v); - if (mode === "edit") { - linkInput.focus(); - linkInput.select(); - } else { - viewEdit.focus(); - } - } - - function openLink(v: EditorView) { - const sel = v.state.selection; - const range = sel.empty ? markRangeAt(v.state.doc, sel.from, linkMark) : { from: sel.from, to: sel.to }; - if (!range) return; - showLink(v, range.from, range.to, "edit"); - } - - editPanel.addEventListener("submit", (e) => { - e.preventDefault(); - if (!link || !view) return; - const href = normalizeHref(linkInput.value); - if (!href) { - linkError.textContent = t("linkInvalid"); - linkError.hidden = false; - linkInput.setAttribute("aria-invalid", "true"); - linkInput.focus(); - return; - } - const { from, to } = link; - closeLink(false); - view.dispatch(view.state.tr.removeMark(from, to, linkMark).addMark(from, to, linkMark.create({ href }))); - view.focus(); - }); - - function removeLink() { - if (!link || !view) return; - const { from, to } = link; - closeLink(false); - view.dispatch(view.state.tr.removeMark(from, to, linkMark)); - view.focus(); - } - - function openHref() { - if (!link?.href) return; - // Note links open in this tab; external links keep opening in a new one. - if (isNoteHref(link.href)) { - location.assign(link.href); - return; - } - window.open(link.href, "_blank", "noopener,noreferrer"); - } - - editRemove.addEventListener("click", removeLink); - viewRemove.addEventListener("click", removeLink); - editOpen.addEventListener("click", openHref); - viewOpen.addEventListener("click", openHref); - viewEdit.addEventListener("click", () => { - if (view && link) showLink(view, link.from, link.to, "edit"); - }); - - linkPop.addEventListener("keydown", (e) => { - if (e.key === "Escape") { - e.preventDefault(); - e.stopPropagation(); - closeLink(true); - return; - } - // Arrow keys move between the menu items in view mode. - if ((e.key === "ArrowDown" || e.key === "ArrowUp") && !viewPanel.hidden) { - const items = [viewEdit, viewRemove, viewOpen].filter((b) => !b.disabled); - const index = items.indexOf(document.activeElement as HTMLButtonElement); - const step = e.key === "ArrowDown" ? 1 : -1; - const next = items[(index + step + items.length) % items.length]; - if (next) { - e.preventDefault(); - next.focus(); - } - } - }); - - // ---- Slash menu ---- - const slashItems: SlashItem[] = [ - { id: "text", label: t("paragraph"), keywords: "text paragraph p", keys: [MOD, ALT, "0"], run: editing.paragraph }, - { id: "h1", label: t("heading1"), keywords: "heading title h1", keys: [MOD, ALT, "1"], run: editing.heading(1) }, - { id: "h2", label: t("heading2"), keywords: "heading subtitle h2", keys: [MOD, ALT, "2"], run: editing.heading(2) }, - { id: "h3", label: t("heading3"), keywords: "heading h3", keys: [MOD, ALT, "3"], run: editing.heading(3) }, - { id: "bullets", label: t("bulletList"), keywords: "list ul bullet unordered", keys: [MOD, SHIFT, "8"], run: editing.bulletList }, - { id: "ordered", label: t("numberedList"), keywords: "list ol number ordered", keys: [MOD, SHIFT, "9"], run: editing.orderedList }, - { id: "quote", label: t("quote"), keywords: "blockquote quote", keys: [">"], run: editing.blockquote }, - { id: "codeblock", label: t("codeBlock"), keywords: "code pre fence", keys: ["```"], run: editing.codeBlock }, - { id: "divider", label: t("divider"), keywords: "hr rule line divider", keys: ["---"], run: editing.horizontalRule }, - ]; - - const slashMenu = h("div", { class: "popover slash-menu", role: "presentation" }); - slashMenu.hidden = true; - const slashList = h("div", { class: "slash-list", role: "listbox", "aria-label": t("blockMenu") }); - const slashFooter = h( - "div", - { class: "slash-footer", "aria-hidden": "true" }, - keycaps("↑", "↓"), - ` ${t("navigate")} `, - keycaps("↵"), - ` ${t("insert")} `, - keycaps("Esc"), - ` ${t("close")}`, - ); - slashMenu.append(slashList, slashFooter); - // Keep focus in the editor while clicking menu items. - slashMenu.addEventListener("mousedown", (e) => e.preventDefault()); - - function closeSlash() { - slashFrom = null; - slashMenu.hidden = true; - view?.dom.removeAttribute("aria-activedescendant"); - } - - function renderSlash() { - if (!view || slashFrom === null) return; - const q = slashQuery.toLowerCase(); - slashFiltered = slashItems.filter( - (item) => !q || item.label.toLowerCase().includes(q) || item.keywords.split(" ").some((w) => w.startsWith(q)), - ); - if (slashIndex >= slashFiltered.length) slashIndex = 0; - if (slashFiltered.length === 0) { - slashList.replaceChildren(h("div", { class: "slash-empty", role: "presentation" }, t("noMatches"))); - view.dom.removeAttribute("aria-activedescendant"); - return; - } - slashList.replaceChildren( - ...slashFiltered.map((item, i) => { - const el = h( - "div", - { class: "slash-item", role: "option", id: `slash-opt-${item.id}`, "aria-selected": String(i === slashIndex) }, - h("span", { class: "slash-label" }, item.label), - keycaps(...item.keys), - ); - el.addEventListener("click", () => applySlash(item)); - return el; - }), - ); - const active = slashFiltered[slashIndex]; - view.dom.setAttribute("aria-activedescendant", `slash-opt-${active.id}`); - slashList.querySelector<HTMLElement>(`#slash-opt-${active.id}`)?.scrollIntoView({ block: "nearest" }); - } - - function applySlash(item: SlashItem) { - const v = view; - if (!v || slashFrom === null) return; - const from = slashFrom; - const to = v.state.selection.from; - closeSlash(); - v.dispatch(v.state.tr.delete(from, to)); - item.run(v.state, v.dispatch, v); - v.focus(); - } - - /** Opens, filters or closes the slash menu from the current selection. */ - function syncSlash(v: EditorView) { - const ctx = slashContext(v.state); - if (!ctx) { - slashDismissed = null; - closeSlash(); - return; - } - if (ctx.from === slashDismissed || link) { - closeSlash(); - return; - } - if (ctx.from !== slashFrom || ctx.query !== slashQuery) slashIndex = 0; - slashFrom = ctx.from; - slashQuery = ctx.query; - slashMenu.hidden = false; - renderSlash(); - } - - // ---- Positioning and visibility ---- - function bubbleVisible(v: EditorView): boolean { - const sel = v.state.selection; - return sel instanceof TextSelection && !sel.empty && !v.composing && !bubbleDismissed && link === null; - } - - function renderFloating(v: EditorView) { - view = v; - const state = v.state; - const show = bubbleVisible(v); - bubble.hidden = !show; - if (show) { - for (const { btn, item } of bubbleButtons) { - const on = item.active(state); - btn.dataset.active = String(on); - btn.setAttribute("aria-pressed", String(on)); - btn.disabled = !item.run(state); - } - placeFloating(bubble, rangeBox(v, state.selection.from, state.selection.to), "above"); - } - if (link) { - placeFloating(linkPop, rangeBox(v, link.from, link.to), "above"); - } - if (slashFrom !== null && !slashMenu.hidden) { - placeFloating(slashMenu, rangeBox(v, slashFrom, state.selection.from), "below"); - } - } - - // ---- Keyboard and mouse ---- - const plugin = new Plugin({ - props: { - handleKeyDown(v, e) { - if (slashFrom !== null) { - const n = slashFiltered.length; - if (e.key === "ArrowDown" && n) { - slashIndex = (slashIndex + 1) % n; - renderSlash(); - return true; - } - if (e.key === "ArrowUp" && n) { - slashIndex = (slashIndex - 1 + n) % n; - renderSlash(); - return true; - } - if (e.key === "Enter" && n) { - applySlash(slashFiltered[slashIndex]); - return true; - } - if (e.key === "Escape") { - slashDismissed = slashFrom; - closeSlash(); - return true; - } - } - if (e.key === "Escape" && bubbleVisible(v)) { - bubbleDismissed = true; - renderFloating(v); - return true; - } - return false; - }, - handleClick(v, pos, event) { - const target = event.target as Element | null; - const anchor = target?.closest?.("a"); - if (!anchor) return false; - // Ctrl/Cmd+click navigates to a note (noteLinks.ts), so no popover opens for it. - if ((event.ctrlKey || event.metaKey) && isNoteHref(anchor.getAttribute("href"))) return false; - const range = markRangeAt(v.state.doc, pos, linkMark); - if (range) showLink(v, range.from, range.to, "view"); - return false; - }, - }, - view(v) { - view = v; - document.body.append(bubble, linkPop, slashMenu); - const onViewport = () => { - if (view) renderFloating(view); - }; - const onOutsideDown = (e: MouseEvent) => { - if (link && !linkPop.contains(e.target as Node)) closeLink(false); - }; - window.addEventListener("scroll", onViewport, { capture: true, passive: true }); - window.addEventListener("resize", onViewport); - document.addEventListener("mousedown", onOutsideDown, true); - renderFloating(v); - return { - update(u, prev) { - if (!prev.selection.eq(u.state.selection)) bubbleDismissed = false; - // A popover refers to a fixed range; remote or local edits invalidate it. - if (link && u.state.doc !== prev.doc) closeLink(false); - syncSlash(u); - renderFloating(u); - }, - destroy() { - window.removeEventListener("scroll", onViewport, { capture: true }); - window.removeEventListener("resize", onViewport); - document.removeEventListener("mousedown", onOutsideDown, true); - bubble.remove(); - linkPop.remove(); - slashMenu.remove(); - view = null; - }, - }; - }, - }); - - return { plugins: [plugin], openLink }; -} diff --git a/web/src/i18n.ts b/web/src/i18n.ts deleted file mode 100644 index 8e29f18..0000000 --- a/web/src/i18n.ts +++ /dev/null @@ -1,109 +0,0 @@ -// Editor UI strings. The language comes from <html lang>; anything but Turkish uses English. - -const en = { - placeholder: "Start writing…", - toolbarLabel: "Formatting", - bubbleLabel: "Text formatting", - blockMenu: "Insert block", - noMatches: "No matches", - navigate: "navigate", - insert: "insert", - close: "close", - unavailable: "Not available here", - undo: "Undo", - redo: "Redo", - paragraph: "Paragraph", - heading1: "Heading 1", - heading2: "Heading 2", - heading3: "Heading 3", - bold: "Bold", - italic: "Italic", - inlineCode: "Inline code", - link: "Link", - bulletList: "Bullet list", - numberedList: "Numbered list", - quote: "Quote", - codeBlock: "Code block", - divider: "Divider", - text: "Text", - linkDialog: "Link", - linkMenu: "Link options", - linkUrl: "Link URL", - linkInvalid: "Enter a valid link, such as example.com", - linkNeedsLink: "Add a link first", - apply: "Apply", - remove: "Remove", - open: "Open", - edit: "Edit", - statusSaved: "Saved", - statusSaving: "Saving…", - statusLocal: "Saved on this device", - statusReconnecting: "Reconnecting…", - statusConnecting: "Connecting…", - announceOffline: "You are offline. Changes stay on this device.", - announceOnline: "Back online.", - pasteAsText: "Paste as plain text", - noteMenu: "Link to a note", - createNote: "Create note “{q}”", - noNotesFound: "No notes found", - untitled: "Untitled", -} as const; - -export type Key = keyof typeof en; - -const tr: Record<Key, string> = { - placeholder: "Yazmaya başla…", - toolbarLabel: "Biçimlendirme", - bubbleLabel: "Metin biçimlendirme", - blockMenu: "Blok ekle", - noMatches: "Eşleşme yok", - navigate: "gezin", - insert: "ekle", - close: "kapat", - unavailable: "Bu alanda kullanılamaz", - undo: "Geri al", - redo: "Yinele", - paragraph: "Metin", - heading1: "Başlık 1", - heading2: "Başlık 2", - heading3: "Başlık 3", - bold: "Kalın", - italic: "İtalik", - inlineCode: "Kod", - link: "Bağlantı", - bulletList: "Madde listesi", - numberedList: "Numaralı liste", - quote: "Alıntı", - codeBlock: "Kod bloğu", - divider: "Ayırıcı", - text: "Metin", - linkDialog: "Bağlantı", - linkMenu: "Bağlantı seçenekleri", - linkUrl: "Bağlantı adresi", - linkInvalid: "Geçerli bir bağlantı girin, ör. example.com", - linkNeedsLink: "Önce bir bağlantı ekleyin", - apply: "Uygula", - remove: "Kaldır", - open: "Aç", - edit: "Düzenle", - statusSaved: "Kaydedildi", - statusSaving: "Kaydediliyor…", - statusLocal: "Bu cihazda kaydedildi", - statusReconnecting: "Yeniden bağlanıyor…", - statusConnecting: "Bağlanıyor…", - announceOffline: "Çevrimdışısınız. Değişiklikler bu cihazda kalır.", - announceOnline: "Yeniden çevrimiçisiniz.", - pasteAsText: "Düz metin olarak yapıştır", - noteMenu: "Nota bağlantısı", - createNote: "“{q}” notunu oluştur", - noNotesFound: "Not bulunamadı", - untitled: "Adsız", -}; - -const lang: "en" | "tr" = (document.documentElement.lang || "en").toLowerCase().startsWith("tr") ? "tr" : "en"; - -/** Looks up a UI string; `{name}` placeholders are filled from `vars`. */ -export function t(key: Key, vars?: Record<string, string>): string { - const text: string = lang === "tr" ? tr[key] : en[key]; - return vars ? text.replace(/\{(\w+)\}/g, (match, name: string) => vars[name] ?? match) : text; -} diff --git a/web/src/noteLinks.ts b/web/src/noteLinks.ts deleted file mode 100644 index 4f85eae..0000000 --- a/web/src/noteLinks.ts +++ /dev/null @@ -1,334 +0,0 @@ -// Note-to-note links. Typing "[[" opens a suggestion menu of note titles. Picking one (or -// "Create note") replaces "[[query" with the title as a link mark whose href is /notes/<id>. -// The menu reuses the slash menu's classes and keyboard model so it looks and behaves the same. -import type { MarkType, Schema } from "prosemirror-model"; -import { Plugin, TextSelection, type EditorState } from "prosemirror-state"; -import type { EditorView } from "prosemirror-view"; -import { t } from "./i18n"; -import { h, keycaps, placeFloating, rangeBox } from "./dom"; - -interface NoteHit { - id: string; - title: string; -} - -type Item = { kind: "note"; hit: NoteHit } | { kind: "create"; title: string }; - -/** "[[" trigger: `from` is the position of the first bracket, `query` the text after it. */ -interface Trigger { - from: number; - query: string; -} - -const SEARCH_DEBOUNCE_MS = 120; - -export interface NoteLinks { - plugins: Plugin[]; -} - -export function isNoteHref(href: string | null | undefined): boolean { - return !!href && href.startsWith("/notes/"); -} - -/** The "[[query" right before the cursor, when the cursor is in a textblock outside code. */ -function triggerAt(state: EditorState, code: MarkType): Trigger | null { - const { selection } = state; - if (!(selection instanceof TextSelection) || !selection.empty) return null; - const $from = selection.$from; - if (!$from.parent.isTextblock || $from.parent.type.spec.code) return null; - if (code.isInSet(state.storedMarks || $from.marks())) return null; - const before = $from.parent.textBetween(0, $from.parentOffset, undefined, "\n"); - // A closing "]]" or a stray bracket ends the match, so the menu closes on its own. - const match = /\[\[([^\[\]\n]*)$/.exec(before); - if (!match) return null; - return { from: $from.pos - match[0].length, query: match[1] }; -} - -function parseHits(data: unknown): NoteHit[] { - if (!Array.isArray(data)) return []; - return data.filter( - (x): x is NoteHit => - typeof x === "object" && x !== null && typeof x.id === "string" && typeof x.title === "string", - ); -} - -async function createNote(title: string): Promise<string> { - const res = await fetch("/notes/quick", { method: "POST", body: new URLSearchParams({ title }) }); - if (!res.ok) throw new Error(`quick ${res.status}`); - const id = (await res.text()).trim(); - if (!id) throw new Error("empty note id"); - return id; -} - -export function createNoteLinks(schema: Schema, opts: { currentNoteId: string }): NoteLinks { - const linkMark = schema.marks.link; - const codeMark = schema.marks.code; - const currentId = opts.currentNoteId; - - let view: EditorView | null = null; - let active: Trigger | null = null; - let dismissedFrom: number | null = null; - let results: NoteHit[] = []; - let loaded = false; - let items: Item[] = []; - let index = 0; - let busy = false; - let fetchTimer: ReturnType<typeof setTimeout> | undefined; - let controller: AbortController | null = null; - - const menu = h("div", { class: "popover slash-menu note-menu", role: "presentation" }); - menu.hidden = true; - const list = h("div", { class: "slash-list", role: "listbox", "aria-label": t("noteMenu") }); - const footer = h( - "div", - { class: "slash-footer", "aria-hidden": "true" }, - keycaps("↑", "↓"), - ` ${t("navigate")} `, - keycaps("↵"), - ` ${t("insert")} `, - keycaps("Esc"), - ` ${t("close")}`, - ); - menu.append(list, footer); - // Keep focus in the editor while clicking menu items. - menu.addEventListener("mousedown", (e) => e.preventDefault()); - - function itemText(item: Item): string { - if (item.kind === "create") return item.title; - return item.hit.title.trim() || t("untitled"); - } - - function itemLabel(item: Item): string { - return item.kind === "create" ? t("createNote", { q: item.title }) : itemText(item); - } - - function buildItems(query: string): Item[] { - const list: Item[] = results.map((hit): Item => ({ kind: "note", hit })); - const q = query.trim(); - const exact = results.some((hit) => hit.title.trim().toLowerCase() === q.toLowerCase()); - if (q && !exact) list.push({ kind: "create", title: q }); - return list; - } - - function abortFetch() { - clearTimeout(fetchTimer); - controller?.abort(); - controller = null; - } - - function close() { - abortFetch(); - active = null; - items = []; - results = []; - loaded = false; - index = 0; - menu.hidden = true; - view?.dom.removeAttribute("aria-activedescendant"); - } - - async function search(query: string) { - const ctrl = new AbortController(); - controller = ctrl; - try { - const res = await fetch(`/notes/titles.json?q=${encodeURIComponent(query)}`, { - signal: ctrl.signal, - headers: { accept: "application/json" }, - }); - if (!res.ok) throw new Error(`titles ${res.status}`); - const data: unknown = await res.json(); - if (ctrl.signal.aborted) return; - results = parseHits(data).filter((hit) => hit.id !== currentId); - } catch (err) { - if (ctrl.signal.aborted) return; - console.error("note search failed", err); - results = []; - } - if (controller === ctrl) controller = null; - loaded = true; - renderList(); - } - - function scheduleSearch(query: string) { - abortFetch(); - loaded = false; - fetchTimer = setTimeout(() => void search(query), SEARCH_DEBOUNCE_MS); - } - - function markActive() { - if (!view) return; - const rows = list.querySelectorAll<HTMLElement>(".slash-item"); - rows.forEach((row, i) => row.setAttribute("aria-selected", String(i === index))); - const row = rows[index]; - if (row) { - view.dom.setAttribute("aria-activedescendant", row.id); - row.scrollIntoView({ block: "nearest" }); - } - } - - function setIndex(i: number) { - index = i; - markActive(); - } - - function renderList() { - if (!view || !active) return; - items = buildItems(active.query); - if (index >= items.length) index = 0; - if (items.length === 0) { - // Only shown once the search for this query has answered; an empty query with no notes lands here. - list.replaceChildren( - ...(loaded ? [h("div", { class: "slash-empty", role: "presentation" }, t("noNotesFound"))] : []), - ); - view.dom.removeAttribute("aria-activedescendant"); - return; - } - list.replaceChildren( - ...items.map((item, i) => { - const el = h( - "div", - { class: "slash-item", role: "option", id: `note-opt-${i}`, "aria-selected": String(i === index) }, - h("span", { class: "slash-label" }, itemLabel(item)), - ); - el.addEventListener("mouseenter", () => setIndex(i)); - el.addEventListener("click", () => pick(item)); - return el; - }), - ); - markActive(); - } - - function place(v: EditorView) { - if (!active) return; - placeFloating(menu, rangeBox(v, active.from, v.state.selection.from), "below"); - } - - /** Replaces [from, to) with the link text, a plain space, and the cursor after it. One transaction. */ - function insertLink(v: EditorView, from: number, to: number, text: string, id: string) { - const tr = v.state.tr.replaceWith(from, to, schema.text(text, [linkMark.create({ href: `/notes/${id}` })])); - const end = from + text.length; - tr.insert(end, schema.text(" ")); - tr.setSelection(TextSelection.create(tr.doc, end + 1)); - tr.setStoredMarks([]); - v.dispatch(tr.scrollIntoView()); - v.focus(); - } - - async function createAndInsert(v: EditorView, from: number, to: number, title: string) { - // The range as it reads now; if the user edits it while the request runs, nothing is inserted. - const before = v.state.doc.textBetween(from, to); - busy = true; - let id: string; - try { - id = await createNote(title); - } catch (err) { - console.error("note create failed", err); - return; - } finally { - busy = false; - } - const cur = view; - if (!cur) return; - const sel = cur.state.selection; - if (!sel.empty || sel.from !== to || cur.state.doc.textBetween(from, to) !== before) return; - insertLink(cur, from, to, title, id); - } - - function pick(item: Item) { - const v = view; - if (!v || !active || busy) return; - const { from } = active; - const to = v.state.selection.from; - if (item.kind === "note") { - insertLink(v, from, to, itemText(item), item.hit.id); - return; - } - void createAndInsert(v, from, to, item.title); - } - - /** Opens, refetches or closes the menu from the current selection. */ - function sync(v: EditorView) { - view = v; - const trig = triggerAt(v.state, codeMark); - if (!trig) { - dismissedFrom = null; - close(); - return; - } - if (trig.from === dismissedFrom) { - close(); - return; - } - const changed = !active || trig.from !== active.from || trig.query !== active.query; - active = trig; - if (changed) { - index = 0; - scheduleSearch(trig.query); - } - menu.hidden = false; - if (changed) renderList(); - place(v); - } - - const plugin = new Plugin({ - props: { - handleKeyDown(v, e) { - if (!active) return false; - const n = items.length; - if (e.key === "Escape") { - dismissedFrom = active.from; - close(); - return true; - } - if (e.key === "ArrowDown" && n) { - setIndex((index + 1) % n); - return true; - } - if (e.key === "ArrowUp" && n) { - setIndex((index - 1 + n) % n); - return true; - } - if ((e.key === "Enter" || e.key === "Tab") && n) { - if (!busy) pick(items[index]); - return true; - } - return false; - }, - // Ctrl/Cmd+click on a note link opens the note in this tab. - handleDOMEvents: { - click(_view, event) { - if (!(event.ctrlKey || event.metaKey)) return false; - const anchor = (event.target as Element | null)?.closest?.("a"); - const href = anchor?.getAttribute("href"); - if (!href || !isNoteHref(href)) return false; - event.preventDefault(); - location.assign(href); - return true; - }, - }, - }, - view(v) { - view = v; - document.body.append(menu); - const onViewport = () => { - if (view) place(view); - }; - window.addEventListener("scroll", onViewport, { capture: true, passive: true }); - window.addEventListener("resize", onViewport); - return { - update(u) { - sync(u); - }, - destroy() { - window.removeEventListener("scroll", onViewport, { capture: true }); - window.removeEventListener("resize", onViewport); - abortFetch(); - menu.remove(); - view = null; - }, - }; - }, - }); - - return { plugins: [plugin] }; -} diff --git a/web/src/toolbar.ts b/web/src/toolbar.ts deleted file mode 100644 index 2406627..0000000 --- a/web/src/toolbar.ts +++ /dev/null @@ -1,279 +0,0 @@ -// Formatting toolbar: plain DOM, rendered once. A ProseMirror plugin view keeps the -// active/disabled state of every button in sync with the editor. Icons only, with -// keycap tooltips; roving tabindex so the bar is one Tab stop. -import type { Schema } from "prosemirror-model"; -import { Plugin, type Command, type EditorState } from "prosemirror-state"; -import type { EditorView } from "prosemirror-view"; -import { findAncestor, isBlockActive, isMarkActive, type Editing } from "./editing"; -import { t } from "./i18n"; -import { ALT, MOD, SHIFT, h, tooltip } from "./dom"; - - -// Lucide-style glyphs (24x24, stroke based). Static strings, safe for innerHTML. -const ICONS = { - undo: '<path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/>', - redo: '<path d="m15 14 5-5-5-5"/><path d="M20 9H9.5a5.5 5.5 0 0 0 0 11H13"/>', - paragraph: '<path d="M13 4v16"/><path d="M17 4v16"/><path d="M19 4H9.5a4.5 4.5 0 0 0 0 9H13"/>', - h1: '<path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="m17 12 3-2v8"/>', - h2: '<path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1"/>', - h3: '<path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2"/><path d="M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2"/>', - bold: '<path d="M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8"/>', - italic: '<line x1="19" x2="10" y1="4" y2="4"/><line x1="14" x2="5" y1="20" y2="20"/><line x1="15" x2="9" y1="4" y2="20"/>', - code: '<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>', - link: '<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>', - bullets: - '<line x1="8" x2="21" y1="6" y2="6"/><line x1="8" x2="21" y1="12" y2="12"/><line x1="8" x2="21" y1="18" y2="18"/><line x1="3" x2="3.01" y1="6" y2="6"/><line x1="3" x2="3.01" y1="12" y2="12"/><line x1="3" x2="3.01" y1="18" y2="18"/>', - ordered: - '<line x1="10" x2="21" y1="6" y2="6"/><line x1="10" x2="21" y1="12" y2="12"/><line x1="10" x2="21" y1="18" y2="18"/><path d="M4 6h1v4"/><path d="M4 10h2"/><path d="M6 18H4c0-1 2-2 2-3s-1-1.5-2-1"/>', - quote: '<path d="M17 6H3"/><path d="M21 12H8"/><path d="M21 18H8"/><path d="M3 12v6"/>', - codeBlock: '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="m10 9-3 3 3 3"/><path d="m14 15 3-3-3-3"/>', - rule: '<line x1="5" x2="19" y1="12" y2="12"/>', -} as const; - -interface Item { - id: string; - label: string; - keys: string[]; - icon: string; - run: Command; - /** Present for toggles: drives aria-pressed and the active look. */ - isActive?: (state: EditorState) => boolean; -} - -type Entry = Item | "|"; - -function buildItems(schema: Schema, editing: Editing, history: { undo: Command; redo: Command }): Entry[] { - const { paragraph, heading, code_block, blockquote, bullet_list, ordered_list } = schema.nodes; - const { strong, em, code, link } = schema.marks; - const headingItem = (level: 1 | 2 | 3): Item => ({ - id: `h${level}`, - label: t(`heading${level}` as "heading1"), - keys: [MOD, ALT, String(level)], - icon: level === 1 ? ICONS.h1 : level === 2 ? ICONS.h2 : ICONS.h3, - run: editing.heading(level), - isActive: (s) => isBlockActive(s, heading, { level }), - }); - const inList = (type: typeof bullet_list) => (s: EditorState) => findAncestor(s, (n) => n.type === type) !== null; - - return [ - { id: "undo", label: t("undo"), keys: [MOD, "Z"], icon: ICONS.undo, run: history.undo }, - { id: "redo", label: t("redo"), keys: [MOD, SHIFT, "Z"], icon: ICONS.redo, run: history.redo }, - "|", - { - id: "paragraph", - label: t("paragraph"), - keys: [MOD, ALT, "0"], - icon: ICONS.paragraph, - run: editing.paragraph, - isActive: (s) => isBlockActive(s, paragraph), - }, - headingItem(1), - headingItem(2), - headingItem(3), - "|", - { - id: "bold", - label: t("bold"), - keys: [MOD, "B"], - icon: ICONS.bold, - run: editing.bold, - isActive: (s) => isMarkActive(s, strong), - }, - { - id: "italic", - label: t("italic"), - keys: [MOD, "I"], - icon: ICONS.italic, - run: editing.italic, - isActive: (s) => isMarkActive(s, em), - }, - { - id: "code", - label: t("inlineCode"), - keys: [MOD, "E"], - icon: ICONS.code, - run: editing.inlineCode, - isActive: (s) => isMarkActive(s, code), - }, - { - id: "link", - label: t("link"), - keys: [MOD, "K"], - icon: ICONS.link, - run: editing.link, - isActive: (s) => isMarkActive(s, link), - }, - "|", - { - id: "bullets", - label: t("bulletList"), - keys: [MOD, SHIFT, "8"], - icon: ICONS.bullets, - run: editing.bulletList, - isActive: inList(bullet_list), - }, - { - id: "ordered", - label: t("numberedList"), - keys: [MOD, SHIFT, "9"], - icon: ICONS.ordered, - run: editing.orderedList, - isActive: inList(ordered_list), - }, - { - id: "quote", - label: t("quote"), - keys: [">"], - icon: ICONS.quote, - run: editing.blockquote, - isActive: (s) => findAncestor(s, (n) => n.type === blockquote) !== null, - }, - { - id: "codeblock", - label: t("codeBlock"), - keys: ["```"], - icon: ICONS.codeBlock, - run: editing.codeBlock, - isActive: (s) => isBlockActive(s, code_block), - }, - { - id: "rule", - label: t("divider"), - keys: ["---"], - icon: ICONS.rule, - run: editing.horizontalRule, - }, - ]; -} - -// data-group names, in order: one per run of buttons between the separators of buildItems. -const GROUP_NAMES = ["history", "headings", "marks", "blocks"] as const; - -/** - * Creates the toolbar DOM (into #editor-toolbar, or just before `mount`) and returns - * the ProseMirror plugin that drives it. Buttons stay disabled until the view exists. - */ -export function createToolbar( - mount: HTMLElement, - schema: Schema, - editing: Editing, - history: { undo: Command; redo: Command }, -): Plugin { - let el = document.getElementById("editor-toolbar"); - if (!el) { - el = document.createElement("div"); - el.id = "editor-toolbar"; - mount.before(el); - } - el.classList.add("editor-toolbar"); - el.setAttribute("role", "toolbar"); - el.setAttribute("aria-label", t("toolbarLabel")); - - let current: EditorView | null = null; - const buttons: { btn: HTMLButtonElement; item: Item; enabled: boolean }[] = []; - - // Each run of buttons between separators is a group; CSS hides low-priority groups - // and draws the dividers between them (see editor.css, container queries). - let group = h("div", { class: "editor-toolbar-group", "data-group": GROUP_NAMES[0] }); - el.append(group); - let groupIndex = 0; - - for (const entry of buildItems(schema, editing, history)) { - if (entry === "|") { - groupIndex += 1; - group = h("div", { class: "editor-toolbar-group", "data-group": GROUP_NAMES[groupIndex] }); - el.append(group); - continue; - } - const btn = h( - "button", - { - type: "button", - class: "editor-toolbar-btn", - "aria-label": entry.label, - "aria-keyshortcuts": ariaKeys(entry.keys), - "data-command": entry.id, - tabindex: "-1", - }, - h("span", { class: "editor-toolbar-icon", "aria-hidden": "true" }), - tooltip(entry.label, entry.keys, t("unavailable")), - ); - // Static icon paths only (see ICONS above). - btn.querySelector(".editor-toolbar-icon")!.innerHTML = `<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${entry.icon}</svg>`; - btn.disabled = true; - btn.addEventListener("click", () => { - if (!current) return; - entry.run(current.state, current.dispatch, current); - current.focus(); - }); - group.append(btn); - buttons.push({ btn, item: entry, enabled: false }); - } - - // Keep the editor's selection and focus when pressing toolbar buttons. - el.addEventListener("mousedown", (e) => e.preventDefault()); - - // Roving tabindex: arrows, Home and End move among enabled buttons. - const enabledButtons = () => buttons.map((b) => b.btn).filter((b) => !b.disabled); - const setStop = (target: HTMLButtonElement) => { - for (const { btn } of buttons) btn.tabIndex = btn === target ? 0 : -1; - }; - el.addEventListener("keydown", (e) => { - const list = enabledButtons(); - if (!list.length) return; - const index = list.indexOf(document.activeElement as HTMLButtonElement); - let next: HTMLButtonElement | undefined; - if (e.key === "ArrowRight") next = list[(index + 1 + list.length) % list.length]; - else if (e.key === "ArrowLeft") next = list[(index - 1 + list.length) % list.length]; - else if (e.key === "Home") next = list[0]; - else if (e.key === "End") next = list[list.length - 1]; - if (!next) return; - e.preventDefault(); - setStop(next); - next.focus(); - }); - - const sync = (state: EditorState) => { - for (const entry of buttons) { - // Commands without a dispatch only report whether they would apply. - entry.enabled = !!entry.item.run(state); - entry.btn.disabled = !entry.enabled; - if (entry.item.isActive) { - const active = entry.item.isActive(state); - entry.btn.dataset.active = String(active); - entry.btn.setAttribute("aria-pressed", String(active)); - } - } - // Keep one enabled button in the tab order, preferring the last one focused. - const stop = buttons.find((b) => b.btn.tabIndex === 0 && !b.btn.disabled)?.btn ?? enabledButtons()[0]; - if (stop) setStop(stop); - }; - - return new Plugin({ - view(view) { - current = view; - sync(view.state); - return { - update(v) { - sync(v.state); - }, - destroy() { - current = null; - }, - }; - }, - }); -} - -/** Keyboard shortcut in aria-keyshortcuts form, e.g. "Control+B" or "Meta+Shift+8". */ -function ariaKeys(keys: string[]): string { - const names: Record<string, string> = { - Ctrl: "Control", - "⌘": "Meta", - Shift: "Shift", - "⇧": "Shift", - Alt: "Alt", - "⌥": "Alt", - }; - return keys.map((k) => names[k] ?? k).join("+"); -} diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml new file mode 100644 index 0000000..eb1eb88 --- /dev/null +++ b/xtask/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "xtask" +version = "0.1.0" +edition = "2024" +publish = false + +[dependencies] +anyhow = "1.0.104" +blake3 = "1.8.7" +wasm-bindgen-cli-support = "=0.2.129" +wasm-opt = "0.116.1" +serde_json = "1" +ureq = { version = "3", features = ["json"] } + +[lints] +workspace = true diff --git a/xtask/src/e2e.rs b/xtask/src/e2e.rs new file mode 100644 index 0000000..c75b7d3 --- /dev/null +++ b/xtask/src/e2e.rs @@ -0,0 +1,528 @@ +//! `cargo xtask e2e`: drives the editor in headless Firefox through geckodriver. +//! Starts the server on a scratch database; nothing is shown on screen +//! (`-headless`, and DISPLAY/WAYLAND_DISPLAY are removed for the browser). + +use std::io::Read; +use std::path::Path; +use std::process::{Child, Command, Stdio}; +use std::thread::sleep; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, bail}; +use serde_json::{Value, json}; + +const SERVER: &str = "http://127.0.0.1:3917"; +const ELEMENT: &str = "element-6066-11e4-a52e-4f735466cecf"; +const ENTER: &str = "\u{E007}"; +const BACKSPACE: &str = "\u{E003}"; +const CONTROL: &str = "\u{E009}"; + +pub(crate) struct Kill(pub(crate) Child); + +impl Drop for Kill { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +pub(crate) fn agent() -> ureq::Agent { + ureq::Agent::config_builder().http_status_as_error(false).build().into() +} + +pub(crate) struct Session { + agent: ureq::Agent, + driver: String, + id: String, +} + +impl Session { + pub(crate) fn new(agent: &ureq::Agent, driver: &str, profile_dir: &Path) -> Result<Session> { + let caps = json!({"capabilities": {"alwaysMatch": { + "browserName": "firefox", + "moz:firefoxOptions": { + "args": ["-headless", "-profile", profile_dir.to_str().unwrap()], + // Page console output goes to geckodriver's log (see `run`). + "prefs": { + "devtools.console.stdout.content": true, + "media.navigator.streams.fake": true, + "media.navigator.permission.disabled": true + } + } + }}}); + let v = call(agent, "POST", &format!("{driver}/session"), Some(caps))?; + let id = v["sessionId"].as_str().context("no session id")?.to_owned(); + Ok(Session { agent: agent.clone(), driver: driver.to_owned(), id }) + } + + pub(crate) fn cmd(&self, method: &str, path: &str, body: Option<Value>) -> Result<Value> { + call(&self.agent, method, &format!("{}/session/{}{path}", self.driver, self.id), body) + } + + pub(crate) fn go(&self, url: &str) -> Result<()> { + self.cmd("POST", "/url", Some(json!({"url": url})))?; + Ok(()) + } + + pub(crate) fn js(&self, script: &str) -> Result<Value> { + self.cmd("POST", "/execute/sync", Some(json!({"script": script, "args": []}))) + } + + fn wait(&self, script: &str, what: &str) -> Result<()> { + self.wait_for(script, what, 15) + } + + pub(crate) fn wait_for(&self, script: &str, what: &str, secs: u64) -> Result<()> { + let t = Instant::now(); + while t.elapsed() < Duration::from_secs(secs) { + if self.js(script)? == Value::Bool(true) { + return Ok(()); + } + sleep(Duration::from_millis(100)); + } + bail!("timed out waiting for {what}") + } + + pub(crate) fn keys(&self, css: &str, text: &str) -> Result<()> { + let el = self.cmd("POST", "/element", Some(json!({"using": "css selector", "value": css})))?; + let id = el[ELEMENT].as_str().context("element not found")?; + self.cmd("POST", &format!("/element/{id}/value"), Some(json!({"text": text})))?; + Ok(()) + } + + pub(crate) fn screenshot(&self, path: &Path) -> Result<()> { + let v = self.cmd("GET", "/screenshot", None)?; + let b64 = v.as_str().context("no screenshot")?; + std::fs::write(path, decode_b64(b64))?; + Ok(()) + } + + pub(crate) fn close(&self) { + let _ = self.cmd("DELETE", "", None); + } +} + +fn call(agent: &ureq::Agent, method: &str, url: &str, body: Option<Value>) -> Result<Value> { + let mut resp = match method { + "POST" => agent.post(url).send_json(body.unwrap_or(json!({})))?, + "DELETE" => agent.delete(url).call()?, + _ => agent.get(url).call()?, + }; + let v: Value = resp.body_mut().read_json()?; + if let Some(err) = v["value"].get("error") { + bail!("webdriver {method} {url}: {err} {}", v["value"]["message"]); + } + Ok(v["value"].clone()) +} + +fn decode_b64(s: &str) -> Vec<u8> { + let val = |c: u8| match c { + b'A'..=b'Z' => c - b'A', + b'a'..=b'z' => c - b'a' + 26, + b'0'..=b'9' => c - b'0' + 52, + b'+' => 62, + _ => 63, + }; + let bytes: Vec<u8> = s.bytes().filter(|&c| c != b'=' && !c.is_ascii_whitespace()).map(val).collect(); + let mut out = Vec::with_capacity(bytes.len() * 3 / 4); + for ch in bytes.chunks(4) { + let n = ch.iter().enumerate().fold(0u32, |n, (i, &b)| n | (b as u32) << (18 - 6 * i)); + for i in 0..ch.len().saturating_sub(1) { + out.push((n >> (16 - 8 * i)) as u8); + } + } + out +} + +pub(crate) fn wait_http(agent: &ureq::Agent, url: &str) -> Result<()> { + let t = Instant::now(); + while t.elapsed() < Duration::from_secs(30) { + if agent.get(url).call().is_ok() { + return Ok(()); + } + sleep(Duration::from_millis(200)); + } + bail!("{url} did not come up") +} + +pub(crate) const CAPTURE: &str = "window.__log = []; for (const k of ['error', 'warn', 'log']) { const o = console[k]; \ + console[k] = (...a) => { __log.push(k + ': ' + a.join(' ')); o(...a) } } \ + addEventListener('error', e => __log.push('uncaught: ' + e.message)); \ + for (const t of ['keydown', 'beforeinput', 'input']) document.addEventListener(t, e => \ + __log.push(t + ':' + (e.inputType || e.key) + (e.defaultPrevented ? '!' : '')), true); return true"; +pub(crate) const EDITABLE: &str = "return document.querySelector('#editor .ProseMirror')?.contentEditable === 'true'"; +const CARET_END: &str = "const r = document.querySelector('#editor .ProseMirror'); r.focus(); \ + const s = getSelection(); s.selectAllChildren(r); s.collapseToEnd(); return true"; + +/// The server on the scratch database. `run` and the restart in `media` both start it this way. +fn spawn_server(root: &Path, target: &Path, dir: &Path) -> Result<Kill> { + Ok(Kill( + Command::new(target.join("debug/project_note")) + .current_dir(root) + .env("NOTE_DB", dir.join("notes.db")) + .env("NOTE_MEDIA", dir.join("media")) + .env("PORT", "3917") + .stdout(Stdio::null()) + .spawn() + .context("starting the server")?, + )) +} + +pub fn run(root: &Path, target: &Path) -> Result<()> { + // Builds the server and bundles its assets next to the executable. + let status = Command::new("topcoat") + .args(["asset", "bundle", "-p", "project_note"]) + .current_dir(root) + .status()?; + if !status.success() { + bail!("server build failed"); + } + let dir = target.join("e2e"); + let _ = std::fs::remove_file(dir.join("notes.db")); + let _ = std::fs::remove_dir_all(dir.join("media/rec")); + std::fs::create_dir_all(dir.join("profile-a"))?; + std::fs::create_dir_all(dir.join("profile-b"))?; + let start = || spawn_server(root, target, &dir); + let mut server = start()?; + // geckodriver runs one session per process: one per client. + let gecko = |port: &str| -> Result<Kill> { + let log = std::fs::File::create(dir.join(format!("gecko-{port}.log")))?; + Ok(Kill( + Command::new("geckodriver") + .args(["--port", port]) + .env("MOZ_HEADLESS", "1") + .env_remove("DISPLAY") + .env_remove("WAYLAND_DISPLAY") + .stdout(log.try_clone()?) + .stderr(log) + .spawn() + .context("starting geckodriver (cargo install geckodriver)")?, + )) + }; + let drivers = [gecko("4917")?, gecko("4918")?]; + let agent = agent(); + wait_http(&agent, &format!("{SERVER}/"))?; + for port in ["4917", "4918"] { + wait_http(&agent, &format!("http://127.0.0.1:{port}/status"))?; + } + + let id = agent + .post(&format!("{SERVER}/notes/quick")) + .send_form([("title", "E2E")])? + .body_mut() + .read_to_string()? + .trim() + .to_owned(); + let note = format!("{SERVER}/notes/{id}"); + println!("note {id}"); + + let a = Session::new(&agent, "http://127.0.0.1:4917", &dir.join("profile-a"))?; + let result = scenario(&agent, &a, ¬e, &dir) + .and_then(|_| media(&agent, &a, &dir, &mut server, &start)) + .and_then(|_| code(&agent, &a, &dir)) + .and_then(|_| perf(&agent, &a)); + let _ = a.screenshot(&dir.join("a.png")); + if let Ok(log) = a.js("return window.__log") { + println!("console: {log}"); + } + if let Ok(html) = a.js("return document.querySelector('#editor .ProseMirror').innerHTML") { + println!("dom: {}", html.as_str().unwrap_or_default()); + } + a.close(); + drop(drivers); + drop(server); + if result.is_err() { + // The page's console (panics land there), from the first client's browser. + let log = std::fs::read_to_string(dir.join("gecko-4917.log")).unwrap_or_default(); + for l in log.lines().filter(|l| l.starts_with("console.") || l.contains("JavaScript") || l.contains("panicked")).take(40) { + println!("browser: {l}"); + } + } + result?; + println!("e2e ok (screenshot in {})", dir.join("a.png").display()); + Ok(()) +} + +fn markdown(agent: &ureq::Agent, note: &str) -> Result<String> { + Ok(agent.get(&format!("{note}/export.md")).call()?.body_mut().read_to_string()?) +} + +fn expect_md(agent: &ureq::Agent, note: &str, want: &str) -> Result<()> { + let t = Instant::now(); + let mut got = String::new(); + while t.elapsed() < Duration::from_secs(5) { + got = markdown(agent, note)?; + if got.trim() == want.trim() { + return Ok(()); + } + sleep(Duration::from_millis(200)); + } + bail!("markdown mismatch\n--- want\n{want}\n--- got\n{got}") +} + +fn scenario(agent: &ureq::Agent, a: &Session, note: &str, dir: &Path) -> Result<()> { + let ed = "#editor .ProseMirror"; + a.go(note)?; + a.wait(EDITABLE, "the editor to become editable")?; + a.js(CAPTURE)?; + a.js(CARET_END)?; + a.keys(ed, &format!("{ENTER}hello world{ENTER}- item one{ENTER}item two{ENTER}{ENTER}**bold** done"))?; + expect_md(agent, note, "# E2E\n\nhello world\n\n- item one\n- item two\n\n**bold** done")?; + + // Deleting is its own undo step once typing has paused past the merge interval. + sleep(Duration::from_millis(1200)); + a.js(CARET_END)?; + a.keys(ed, &BACKSPACE.repeat(5))?; + expect_md(agent, note, "# E2E\n\nhello world\n\n- item one\n- item two\n\n**bold**")?; + a.keys(ed, &format!("{CONTROL}z{CONTROL}"))?; + expect_md(agent, note, "# E2E\n\nhello world\n\n- item one\n- item two\n\n**bold** done")?; + + // A second client sees the same content. + let b = Session::new(agent, "http://127.0.0.1:4918", &dir.join("profile-b"))?; + let seen = (|| -> Result<()> { + b.go(note)?; + b.wait(EDITABLE, "the second editor")?; + b.wait( + "return document.querySelector('#editor .ProseMirror').textContent.includes('bold done')", + "the second client to show the text", + )?; + b.js(CARET_END)?; + b.keys(ed, " from b")?; + a.wait( + "return document.querySelector('#editor .ProseMirror').textContent.includes('done from b')", + "the first client to see the second's edit", + ) + })(); + b.close(); + seen +} + +const MEASURE: &str = "const root = document.querySelector('#editor .ProseMirror'); \ + const mo = new MutationObserver(() => {}); \ + mo.observe(root, {subtree: true, childList: true, characterData: true, attributes: true}); \ + const run = (n, f) => { const t = []; let m = 0; for (let i = 0; i < n; i++) { \ + const s = performance.now(); f(); t.push(performance.now() - s); m += mo.takeRecords().length; } \ + t.sort((a, b) => a - b); \ + return {avg: t.reduce((a, b) => a + b, 0) / n, p95: t[Math.floor(n * 0.95)], mutations_per_op: m / n}; }; \ + const type = run(50, () => root.dispatchEvent(new InputEvent('beforeinput', \ + {inputType: 'insertText', data: ' ', cancelable: true, bubbles: true}))); \ + const enter = run(20, () => root.dispatchEvent(new KeyboardEvent('keydown', \ + {key: 'Enter', code: 'Enter', cancelable: true, bubbles: true}))); \ + mo.disconnect(); \ + return {type, enter, blocks: root.querySelectorAll(':scope > .pm-page > *').length}"; + +const AUDIOS: &str = "document.querySelectorAll('#editor audio.note-media').length"; +const RECORD: &str = "document.querySelector('[data-command=record]').click(); return true"; +const TAKES: &str = "document.querySelectorAll('#editor .note-take').length"; +const RECS: &str = "document.querySelectorAll('#editor audio[src^=\"/media/rec/\"]').length"; +/// The state of the note's last take. +const TAKE_STATE: &str = "[...document.querySelectorAll('#editor .note-take')].pop()?.dataset.takeState"; + +/// Waits until the `n`th (from 1) recording audio of the note has loaded with a duration in `want` +/// seconds, and returns its src and duration. +fn loaded_take(a: &Session, n: usize, want: (f64, f64), wait: u64) -> Result<(String, f64)> { + let t = Instant::now(); + let mut last = Value::Null; + while t.elapsed() < Duration::from_secs(wait) { + last = a.js(&format!( + "const x = [...document.querySelectorAll('#editor audio[src^=\"/media/rec/\"]')][{}]; \ + return x ? {{src: x.getAttribute('src'), ready: x.readyState, duration: x.duration}} : null", + n - 1 + ))?; + if let (Some(d), Some(r)) = (last["duration"].as_f64(), last["ready"].as_u64()) { + if r >= 1 && d >= want.0 && d <= want.1 { + return Ok((last["src"].as_str().unwrap_or_default().to_owned(), d)); + } + } + sleep(Duration::from_millis(100)); + } + bail!("recording {n} did not load as {want:?} s: {last}") +} + +/// Uploads, Range, import rewriting, recording, and a recording cut off by leaving the note. +fn media(agent: &ureq::Agent, a: &Session, dir: &Path, server: &mut Kill, start: &dyn Fn() -> Result<Kill>) -> Result<()> { + let upload = |name: &str, bytes: &[u8]| -> Result<String> { + let url = format!("{SERVER}/media?name={name}"); + Ok(agent.post(&url).send(bytes)?.body_mut().read_to_string()?.trim().to_owned()) + }; + let cat = upload("cat.PNG", b"not really a png")?; + if !cat.starts_with("/media/") || !cat.ends_with(".png") || upload("again.png", b"not really a png")? != cat { + bail!("upload answered {cat}"); + } + let resp = agent.get(&format!("{SERVER}{cat}")).header("range", "bytes=4-9").call()?; + if resp.status() != 206 || resp.headers()["content-range"] != "bytes 4-9/16" { + bail!("range: {:?}", resp.headers()); + } + let svg = upload("evil.svg", b"<svg onload=alert(1)>")?; + let resp = agent.get(&format!("{SERVER}{svg}")).call()?; + if resp.headers()["content-disposition"] != "attachment" || resp.headers()["content-type"] != "application/octet-stream" { + bail!("svg served as {:?}", resp.headers()); + } + + let song = upload("song.mp3", b"not really an mp3")?; + let text = "# Media\n\n![a cat](../att/cat.png)\n\n![[song.mp3|tune]]\n\n`![[song.mp3]]`\n"; + let map = json!({"att/cat.png": cat, "vault/song.mp3": song}).to_string(); + let id = agent + .post(&format!("{SERVER}/import/file")) + .send_form([("path", "vault/note.md"), ("text", text), ("media", map.as_str())])? + .body_mut() + .read_to_string()? + .trim() + .to_owned(); + let note = format!("{SERVER}/notes/{id}"); + expect_md(agent, ¬e, &format!("# Media\n\n![a cat]({cat})\n\n![tune]({song})\n\n`![[song.mp3]]`"))?; + a.go(¬e)?; + a.wait(EDITABLE, "the media note")?; + a.wait(&format!("return {AUDIOS} === 1 && !!document.querySelector('#editor img')"), "the embeds to show")?; + + // Dropped file. + a.js(CARET_END)?; + a.js("const dt = new DataTransfer(); dt.items.add(new File(['pasted'], 'p.png', {type: 'image/png'})); \ + document.querySelector('#editor .ProseMirror').dispatchEvent(new DragEvent('drop', \ + {dataTransfer: dt, bubbles: true, cancelable: true})); return true")?; + a.wait("return document.querySelectorAll('#editor img').length === 2", "the dropped image")?; + + // Recording from the fake microphone. The take's embed appears at its first ack and stays. + a.js(CARET_END)?; + a.js(RECORD)?; + a.wait("return !!document.querySelector('[data-recording=true]')", "recording to start")?; + sleep(Duration::from_millis(2500)); + a.wait(&format!("return {TAKE_STATE} === 'live'"), "the take to show as live while recording")?; + a.js(RECORD)?; + a.wait(&format!("return {RECS} === 1 && {TAKES} === 1"), "the recording to appear")?; + let (src, d) = loaded_take(a, 1, (2.0, 3.2), 40)?; + println!("recorded {src} {d:.2} s"); + let src1 = src; + + // Continue the take: same embed, one more part. + a.js("document.querySelector('#editor .note-take-continue').click(); return true")?; + a.wait("return !!document.querySelector('[data-recording=true]')", "the continued recording")?; + sleep(Duration::from_millis(2000)); + a.js(RECORD)?; + a.wait(&format!("return {TAKES} === 1 && {RECS} === 1 && {TAKE_STATE} === 'absent'"), "the continued take to end")?; + a.go(¬e)?; + a.wait(EDITABLE, "the note after continuing")?; + let (_, d) = loaded_take(a, 1, (4.0, 5.2), 40)?; + println!("continued take {d:.2} s"); + a.js("const x = document.querySelector('#editor audio[src^=\"/media/rec/\"]'); window.__seeked = false; \ + x.addEventListener('seeked', () => window.__seeked = true, {once: true}); x.currentTime = 3.5; return true")?; + a.wait("return window.__seeked === true", "the continued take to seek")?; + + // The server restarts mid-take: the client reconnects to the same part and the gap arrives. + a.js(CARET_END)?; + a.js(RECORD)?; + a.wait("return !!document.querySelector('[data-recording=true]')", "the restart recording")?; + sleep(Duration::from_millis(2000)); + server.0.kill()?; + server.0.wait()?; + sleep(Duration::from_millis(3000)); + *server = start()?; + wait_http(agent, &format!("{SERVER}/"))?; + sleep(Duration::from_millis(3000)); + a.js(RECORD)?; + a.wait(&format!("return {TAKES} === 2 && {TAKE_STATE} === 'absent'"), "the restart take to end")?; + let n = a.js(&format!("return {RECS}"))?.as_u64().unwrap_or(0) as usize; + let (_, d) = loaded_take(a, n, (7.0, 9.5), 40)?; + println!("restart take {d:.2} s"); + + // A browser killed outright mid-recording: the embed in the other client shows the take as lost, + // and the audio is whatever reached the server. + let b = Session::new(agent, "http://127.0.0.1:4918", &dir.join("profile-b"))?; + b.go(¬e)?; + b.wait(EDITABLE, "the recording client")?; + b.js(CARET_END)?; + b.js(RECORD)?; + b.wait("return !!document.querySelector('[data-recording=true]')", "the crash recording")?; + sleep(Duration::from_millis(4000)); + a.wait(&format!("return {TAKES} === 3"), "the crash take to reach the other client")?; + let killed = Command::new("pkill").args(["-9", "-f", dir.join("profile-b").to_str().unwrap()]).status()?; + if !killed.success() { + bail!("no browser to kill"); + } + a.wait( + "const t = [...document.querySelectorAll('#editor .note-take')].pop(); return !!t && t.dataset.takeState !== 'live'", + "the crash take to stop being live", + )?; + let n = a.js(&format!("return {RECS}"))?.as_u64().unwrap_or(0) as usize; + let (_, d) = loaded_take(a, n, (3.0, 4.2), 45)?; + println!("crash take {d:.2} s"); + let _ = a.screenshot(&dir.join("media.png")); + + // The import page: a note and the image it references, then a lone media file. + let vault = dir.join("vault"); + std::fs::create_dir_all(&vault)?; + let (picked, pic, tone) = (vault.join("Picked.md"), vault.join("my pic.png"), vault.join("tone.mp3")); + std::fs::write(&picked, "# Picked\n\n![pic](my%20pic.png)\n")?; + std::fs::write(&pic, "picked image")?; + std::fs::write(&tone, "picked audio")?; + let import = format!("{SERVER}/import"); + let done = "return !document.querySelector('#import-link').classList.contains('hidden')"; + a.go(&import)?; + a.keys("#import-files", &format!("{}\n{}", picked.display(), pic.display()))?; + a.wait(done, "the import to finish")?; + a.go(&format!("{SERVER}/notes/by-title/Picked"))?; + a.wait(EDITABLE, "the imported note")?; + a.wait("return !!document.querySelector('#editor img[src^=\"/media/\"]')", "the imported image")?; + a.go(&import)?; + a.keys("#import-files", &tone.display().to_string())?; + a.wait(done, "the media import to finish")?; + a.go(&format!("{SERVER}/notes/by-title/tone"))?; + a.wait(EDITABLE, "the note of the lone file")?; + a.wait(&format!("return {AUDIOS} === 1"), "the imported audio")?; + + let mut zip = Vec::new(); + agent.get(&format!("{SERVER}/export.zip")).call()?.into_body().into_reader().read_to_end(&mut zip)?; + std::fs::write(dir.join("export.zip"), &zip)?; + let entry = format!("media/rec/{}", src1.trim_start_matches("/media/rec/")); + if !zip.windows(entry.len()).any(|w| w == entry.as_bytes()) { + bail!("the export has no {entry}"); + } + Ok(()) +} + +/// Code blocks: the language is detected and Format rewrites the code through the server. +fn code(agent: &ureq::Agent, a: &Session, dir: &Path) -> Result<()> { + let text = "Code\n\n```\nlet x=foo( a,b );\nlet y = x.map(|s|s.len());\n```\n"; + let id = agent + .post(&format!("{SERVER}/import/file")) + .send_form([("path", "code.md"), ("text", text)])? + .body_mut() + .read_to_string()? + .trim() + .to_owned(); + let note = format!("{SERVER}/notes/{id}"); + a.go(¬e)?; + a.wait(EDITABLE, "the code note")?; + a.wait( + "const s = document.querySelector('.code-head .code-lang'); return !!s && s.options[0].text.includes('Rust')", + "the header to show the detected language", + )?; + let _ = a.screenshot(&dir.join("code.png")); + a.js("document.querySelector('.code-head .code-format').click(); return true")?; + expect_md(agent, ¬e, "# code\n\nCode\n\n```rust\nlet x = foo(a, b);\nlet y = x.map(|s| s.len());\n```") +} + +/// Typing latency on a 5000-paragraph note. +fn perf(agent: &ureq::Agent, a: &Session) -> Result<()> { + let text: String = (0..5000).map(|i| format!("Paragraph {i} with some ordinary words in it.\n\n")).collect(); + let id = agent + .post(&format!("{SERVER}/import/file")) + .send_form([("path", "big.md"), ("text", text.as_str())])? + .body_mut() + .read_to_string()? + .trim() + .to_owned(); + a.go(&format!("{SERVER}/notes/{id}"))?; + a.wait(EDITABLE, "the big note to become editable")?; + let ready = a.js("return performance.now()")?; + // Top-level blocks live in pages that are built near the viewport: scroll there first. + a.js("const r = document.querySelector('#editor .ProseMirror'); r.focus(); \ + const pages = r.querySelectorAll(':scope > .pm-page'); pages[pages.length >> 1].scrollIntoView({block: 'center'}); return true")?; + sleep(Duration::from_millis(300)); + a.js("const pages = document.querySelectorAll('#editor .ProseMirror > .pm-page'); \ + const p = pages[pages.length >> 1].firstElementChild; getSelection().collapse(p.firstChild, 9); return true")?; + sleep(Duration::from_millis(100)); + let m = a.js(MEASURE)?; + println!("perf: editable after {ready} ms; {m}"); + Ok(()) +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs new file mode 100644 index 0000000..fb77138 --- /dev/null +++ b/xtask/src/main.rs @@ -0,0 +1,232 @@ +use std::collections::HashSet; +use std::fs; +use std::path::PathBuf; +use std::process::Command; +use std::time::Instant; + +use anyhow::{Context, Result, bail}; + +mod e2e; +mod stress; + +const USAGE: &str = "usage: cargo xtask editor [--dev] | cargo xtask e2e | cargo xtask stress [data|huge|flood|all] [--notes N] [--notebooks N] [--only CASE] [--keep]"; + +fn main() -> Result<()> { + let args: Vec<String> = std::env::args().skip(1).collect(); + match args.first().map(String::as_str) { + Some("editor") => { + let mut dev = false; + for arg in &args[1..] { + match arg.as_str() { + "--dev" => dev = true, + other => bail!("unknown argument `{other}`\n{USAGE}"), + } + } + build_editor(!dev) + } + Some("e2e") => e2e::run(&workspace_root()?, &target_dir()?), + Some("stress") => stress::run(&workspace_root()?, &target_dir()?, &args[1..]), + _ => bail!("{USAGE}"), + } +} + +fn build_editor(release: bool) -> Result<()> { + let started = Instant::now(); + let root = workspace_root()?; + let target = target_dir()?; + let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()); + + // 1. Build the wasm library. + let mut build = Command::new(&cargo); + build + .args(["build", "-p", "editor", "--lib", "--target", "wasm32-unknown-unknown"]) + // SIMD: byte scans (UTF-8 counts, memchr, lz4) on 100 MB notes. Every current browser has it. + .env("CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUSTFLAGS", "-C target-feature=+simd128") + .current_dir(&root); + if release { + build.args(["--profile", "editor"]); + } + let status = build.status().context("failed to spawn cargo build")?; + if !status.success() { + bail!("cargo build -p editor failed with {status}"); + } + + let profile = if release { "editor" } else { "debug" }; + let raw_wasm = target + .join("wasm32-unknown-unknown") + .join(profile) + .join("editor.wasm"); + if !raw_wasm.is_file() { + bail!("expected wasm at {}", raw_wasm.display()); + } + + // 2. Run wasm-bindgen as a library. + let out_dir = target.join("xtask-editor"); + fs::create_dir_all(&out_dir)?; + wasm_bindgen_cli_support::Bindgen::new() + .input_path(&raw_wasm) + .web(true)? + .typescript(false) + .generate(&out_dir) + .context("wasm-bindgen generate failed")?; + let bg_wasm_path = out_dir.join("editor_bg.wasm"); + let glue_path = out_dir.join("editor.js"); + + // 3. Optimize the wasm in release mode. + let mut wasm_bytes = fs::read(&bg_wasm_path) + .with_context(|| format!("reading {}", bg_wasm_path.display()))?; + if release { + let opt_path = out_dir.join("editor_bg.opt.wasm"); + // The features rustc's wasm32 target emits by default, plus SIMD. + use wasm_opt::Feature; + wasm_opt::OptimizationOptions::new_opt_level_3() + .enable_feature(Feature::Simd) + .enable_feature(Feature::BulkMemory) + .enable_feature(Feature::SignExt) + .enable_feature(Feature::TruncSat) + .enable_feature(Feature::MutableGlobals) + .enable_feature(Feature::ReferenceTypes) + .enable_feature(Feature::Multivalue) + // EDITOR_NAMES=1 (with CARGO_PROFILE_EDITOR_STRIP=false) keeps function names for profiling. + .debug_info(std::env::var_os("EDITOR_NAMES").is_some()) + .run(&bg_wasm_path, &opt_path) + .context("wasm-opt failed")?; + wasm_bytes = fs::read(&opt_path)?; + } + + // 4. Content-hash the wasm, then patch and hash the JS glue. + let wasm_name = format!("editor-{}.wasm", short_hash(&wasm_bytes)); + let glue = fs::read_to_string(&glue_path) + .with_context(|| format!("reading {}", glue_path.display()))?; + let init_name = default_export_name(&glue)?; + let mut js = glue; + if !js.ends_with('\n') { + js.push('\n'); + } + js.push_str(&format!( + "await {init_name}({{ module_or_path: new URL(\"./{wasm_name}\", import.meta.url) }});\n" + )); + let js_name = format!("editor-{}.js", short_hash(js.as_bytes())); + + // 5. Write outputs and manifest into assets/. + let assets = root.join("assets"); + fs::create_dir_all(&assets)?; + let js_path = assets.join(&js_name); + let wasm_path = assets.join(&wasm_name); + let manifest_path = assets.join("editor.manifest"); + fs::write(&js_path, js.as_bytes())?; + fs::write(&wasm_path, &wasm_bytes)?; + fs::write( + &manifest_path, + format!("js={js_name}\nwasm={wasm_name}\n"), + )?; + + // 6. Remove older hashed outputs (exact pattern only). + let keep: HashSet<&str> = [js_name.as_str(), wasm_name.as_str()].into_iter().collect(); + for entry in fs::read_dir(&assets)? { + let entry = entry?; + let file_name = entry.file_name(); + let Some(name) = file_name.to_str() else { continue }; + if is_generated_name(name) && !keep.contains(name) && entry.file_type()?.is_file() { + fs::remove_file(entry.path()) + .with_context(|| format!("removing {}", entry.path().display()))?; + println!("removed old output {name}"); + } + } + + // 7. Report. + println!("init function: {init_name}"); + for path in [&js_path, &wasm_path, &manifest_path] { + let size = fs::metadata(path)?.len(); + println!( + "{}\t{} bytes", + path.file_name().unwrap_or_default().to_string_lossy(), + size + ); + } + println!( + "profile: {profile}, elapsed: {:.2}s", + started.elapsed().as_secs_f64() + ); + Ok(()) +} + +fn short_hash(bytes: &[u8]) -> String { + let hex = blake3::hash(bytes).to_hex(); + hex[..16].to_string() +} + +/// Matches `editor-<16 lowercase hex>.js` or `editor-<16 lowercase hex>.wasm`. +fn is_generated_name(name: &str) -> bool { + let Some(rest) = name.strip_prefix("editor-") else { + return false; + }; + if rest.len() < 16 { + return false; + } + let (hash, ext) = rest.split_at(16); + (ext == ".js" || ext == ".wasm") + && hash.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +/// Finds the name of the default export in the wasm-bindgen glue, e.g. `__wbg_init`. +fn default_export_name(glue: &str) -> Result<String> { + for line in glue.lines() { + // wasm-bindgen web output: `export { initSync, __wbg_init as default };` + if let Some(idx) = line.find(" as default") { + let name = line[..idx] + .rsplit(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')) + .next() + .unwrap_or_default(); + if line.trim_start().starts_with("export {") && !name.is_empty() { + return Ok(name.to_string()); + } + } + if let Some(rest) = line.strip_prefix("export default ") { + let name: String = rest + .trim_end_matches(';') + .trim() + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$') + .collect(); + if !name.is_empty() { + return Ok(name); + } + } + } + bail!("could not find `export default <init>` in wasm-bindgen output") +} + +fn workspace_root() -> Result<PathBuf> { + json_field(&cargo_metadata()?, "workspace_root").map(PathBuf::from) +} + +fn target_dir() -> Result<PathBuf> { + json_field(&cargo_metadata()?, "target_directory").map(PathBuf::from) +} + +fn cargo_metadata() -> Result<String> { + let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()); + let output = Command::new(cargo) + .args(["metadata", "--format-version", "1", "--no-deps"]) + .output() + .context("failed to run cargo metadata")?; + if !output.status.success() { + bail!("cargo metadata failed"); + } + Ok(String::from_utf8(output.stdout)?) +} + +/// Extracts a top-level string field from cargo metadata JSON without a JSON parser. +/// Paths on this machine contain no escape sequences, so a plain scan is enough. +fn json_field(json: &str, key: &str) -> Result<String> { + let needle = format!("\"{key}\":\""); + let start = json + .find(&needle) + .with_context(|| format!("`{key}` missing from cargo metadata"))? + + needle.len(); + let end = json[start..] + .find('"') + .with_context(|| format!("unterminated `{key}`"))?; + Ok(json[start..start + end].to_string()) +} diff --git a/xtask/src/stress.rs b/xtask/src/stress.rs new file mode 100644 index 0000000..1d2e6e2 --- /dev/null +++ b/xtask/src/stress.rs @@ -0,0 +1,756 @@ +//! `cargo xtask stress [data|huge|flood|all] [--notes N] [--notebooks N] [--keep] [--start N]`: +//! load tests against a release server on a scratch database, with the editor driven +//! in headless Firefox (never on screen). +//! +//! - data: thousands of notebooks and many notes through the import endpoint, then the +//! latency of the pages that list and search them. +//! - huge: very large single notes (a 200k-line code block, 1M lorem paragraphs, ...): +//! import, export, page size, time to editable and real keystroke latency. +//! - billion / billion-check: a billion lines over a thousand notes on their own +//! database (`billion.db`), imported in rounds of `--notes`, then read, searched and +//! exported whole, with the exported zip's lines counted. +//! - flood: an endless upload (a billion lines) must be refused without the server +//! growing, and the server must stay responsive. + +use std::io::Read; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::thread::sleep; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, bail}; +use serde_json::{Value, json}; + +use crate::e2e::{CAPTURE, EDITABLE, Kill, Session, agent, wait_http}; + +const PORT: &str = "3918"; +const SERVER: &str = "http://127.0.0.1:3918"; +const DRIVER_PORT: &str = "4919"; + +struct Opts { + notes: usize, + notebooks: usize, + keep: bool, + /// First note number of the data phase, to add more notes to a kept database. + start: usize, + build: bool, + only: Vec<String>, +} + +pub fn run(root: &Path, target: &Path, args: &[String]) -> Result<()> { + let mut opts = Opts { notes: 20_000, notebooks: 2_000, keep: false, start: 0, build: true, only: Vec::new() }; + let mut it = args.iter(); + let mut phase = "all".to_owned(); + while let Some(a) = it.next() { + match a.as_str() { + "--notes" => opts.notes = it.next().context("--notes N")?.parse()?, + "--notebooks" => opts.notebooks = it.next().context("--notebooks N")?.parse()?, + "--keep" => opts.keep = true, + "--start" => opts.start = it.next().context("--start N")?.parse()?, + "--no-build" => opts.build = false, + "--only" => opts.only.push(it.next().context("--only NAME")?.clone()), + p => phase = p.to_owned(), + } + } + + // Builds the release server and bundles its assets next to the executable. + if opts.build { + let status = Command::new("topcoat").args(["asset", "bundle", "--release", "-p", "project_note"]).current_dir(root).status()?; + if !status.success() { + bail!("server build failed"); + } + } + let dir = target.join("stress"); + std::fs::create_dir_all(dir.join("profile"))?; + let db = if phase.starts_with("billion") { "billion.db" } else { "notes.db" }; + if !opts.keep { + for f in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(dir.join(format!("{db}{f}"))); + } + } + let server = Kill( + Command::new(target.join("release/project_note")) + .current_dir(root) + .env("NOTE_DB", dir.join(db)) + .env("PORT", PORT) + .stdout(Stdio::null()) + .spawn() + .context("starting the server")?, + ); + let pid = server.0.id(); + let agent = agent(); + wait_http(&agent, &format!("{SERVER}/"))?; + println!("server pid {pid}, rss {} MB", rss_mb(pid)); + + match phase.as_str() { + "data" => data(&agent, &opts, pid)?, + "huge" => huge(&agent, &opts, &dir, pid)?, + "flood" => flood(&agent, pid)?, + "billion" => billion(&agent, &opts, pid)?, + "billion-check" => billion_check(&agent, &dir, pid)?, + "exp" => exp(&agent, &dir, &opts.only)?, + "all" => { + data(&agent, &opts, pid)?; + huge(&agent, &opts, &dir, pid)?; + flood(&agent, pid)?; + } + p => bail!("unknown phase {p}"), + } + println!("server rss at end {} MB", rss_mb(pid)); + drop(server); + Ok(()) +} + +fn rss_mb(pid: u32) -> u64 { + let s = std::fs::read_to_string(format!("/proc/{pid}/status")).unwrap_or_default(); + s.lines() + .find_map(|l| l.strip_prefix("VmRSS:")) + .and_then(|v| v.split_whitespace().next()?.parse::<u64>().ok()) + .map_or(0, |kb| kb / 1024) +} + +fn import(agent: &ureq::Agent, path: &str, text: &str) -> Result<String> { + let mut resp = agent.post(&format!("{SERVER}/import/file")).send_form([("path", path), ("text", text)])?; + let status = resp.status(); + let body = resp.body_mut().with_config().limit(u64::MAX).read_to_string()?; + if !status.is_success() { + bail!("import {path}: {status} {}", body.chars().take(200).collect::<String>()); + } + Ok(body.trim().to_owned()) +} + +/// GET `url`; returns (seconds, body bytes, status). +fn timed_get(agent: &ureq::Agent, url: &str) -> Result<(f64, usize, u16)> { + let t = Instant::now(); + let mut resp = agent.get(url).call()?; + let status = resp.status().as_u16(); + let mut n = 0usize; + let mut buf = vec![0u8; 1 << 16]; + let mut r = resp.body_mut().with_config().limit(u64::MAX).reader(); + loop { + let k = r.read(&mut buf)?; + if k == 0 { + break; + } + n += k; + } + Ok((t.elapsed().as_secs_f64(), n, status)) +} + +fn report_get(agent: &ureq::Agent, label: &str, url: &str) -> Result<()> { + let mut times = Vec::new(); + let mut size = 0; + for _ in 0..5 { + let (t, n, status) = timed_get(agent, url)?; + if status >= 400 { + bail!("{label}: HTTP {status}"); + } + times.push(t * 1000.0); + size = n; + } + times.sort_by(f64::total_cmp); + println!(" {label:<28} median {:>8.1} ms max {:>8.1} ms {:>10} bytes", times[2], times[4], size); + Ok(()) +} + +// --------------------------------------------------------------------------- +// data: many notes and notebooks +// --------------------------------------------------------------------------- + +fn small_note(i: usize) -> String { + format!( + "Note {i} about the project.\n\nSome words for search: alpha{a} beta{b} gamma.\n\n- item one\n- item two [[Note {link}]]\n\n```rust\nfn note_{i}() -> usize {{ {i} }}\n```\n", + a = i % 97, + b = i % 13, + link = (i * 7 + 1) % (i + 1).max(1) + ) +} + +fn data(agent: &ureq::Agent, opts: &Opts, pid: u32) -> Result<()> { + println!("data: {} notes in {} notebooks", opts.notes, opts.notebooks); + let next = AtomicUsize::new(opts.start); + let end = opts.start + opts.notes; + let errors = AtomicUsize::new(0); + let t = Instant::now(); + std::thread::scope(|s| { + for _ in 0..12 { + s.spawn(|| { + let agent = agent.clone(); + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= end { + break; + } + let path = format!("Notebook {}/Note {i}.md", i % opts.notebooks.max(1)); + if let Err(e) = import(&agent, &path, &small_note(i)) { + if errors.fetch_add(1, Ordering::Relaxed) < 5 { + eprintln!(" {e}"); + } + } + if i % 50000 == 49999 { + println!(" {} notes, {:.0}/s", i + 1, (i + 1 - opts.start) as f64 / t.elapsed().as_secs_f64()); + } + } + }); + } + }); + let secs = t.elapsed().as_secs_f64(); + println!( + " imported in {secs:.1}s ({:.0} notes/s), {} errors, server rss {} MB", + opts.notes as f64 / secs, + errors.load(Ordering::Relaxed), + rss_mb(pid) + ); + + let id = import(agent, "probe.md", "probe note")?; + report_get(agent, "GET / (all notes)", &format!("{SERVER}/"))?; + report_get(agent, "GET /unfiled", &format!("{SERVER}/unfiled"))?; + report_get(agent, "GET /notes/<id>", &format!("{SERVER}/notes/{id}"))?; + report_get(agent, "titles.json?q=Note 12", &format!("{SERVER}/notes/titles.json?q=Note%2012"))?; + report_get(agent, "titles.json?q=", &format!("{SERVER}/notes/titles.json?q="))?; + report_get(agent, "search alpha42", &format!("{SERVER}/search?q=alpha42"))?; + report_get(agent, "search gamma (all match)", &format!("{SERVER}/search?q=gamma"))?; + let nb = notebook_url(agent)?; + report_get(agent, "GET /notebooks/<id>", &format!("{SERVER}{nb}"))?; + let (t, n, _) = timed_get(agent, &format!("{SERVER}/export.zip"))?; + println!(" GET /export.zip {:>8.1} s {:>10} bytes, rss {} MB", t, n, rss_mb(pid)); + Ok(()) +} + +// --------------------------------------------------------------------------- +// billion: a billion lines over many notes +// --------------------------------------------------------------------------- + +const BILLION_LINES_PER_NOTE: usize = 1_000_000; + +/// Note `i` of the billion-line set: a heading, a searchable line, then a code block. +/// Every line of the code block and the two lines above it count. +fn billion_note(i: usize) -> String { + let mut s = format!("# Billion {i}\n\nmarker{} of the billion set\n\n```\n", i % 97); + s.reserve(BILLION_LINES_PER_NOTE * 14); + for k in 0..BILLION_LINES_PER_NOTE - 2 { + s.push_str(" ret v"); + s.push_str(&(k % 1000).to_string()); + s.push('\n'); + } + s + "```\n" +} + +fn billion(agent: &ureq::Agent, opts: &Opts, pid: u32) -> Result<()> { + let end = opts.start + opts.notes; + println!("billion: notes {}..{end}, {} lines each", opts.start, BILLION_LINES_PER_NOTE); + let next = AtomicUsize::new(opts.start); + let errors = AtomicUsize::new(0); + let t = Instant::now(); + std::thread::scope(|s| { + for _ in 0..4 { + s.spawn(|| { + let agent = agent.clone(); + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= end { + break; + } + let path = format!("Billion {}/Billion {i}.md", i % 50); + if let Err(e) = import(&agent, &path, &billion_note(i)) { + if errors.fetch_add(1, Ordering::Relaxed) < 5 { + eprintln!(" {e}"); + } + } + if i % 50 == 49 { + println!(" {} notes, {:.1}/s, rss {} MB", i + 1, (i + 1 - opts.start) as f64 / t.elapsed().as_secs_f64(), rss_mb(pid)); + } + } + }); + } + }); + println!( + " imported in {:.1}s, {} errors, server rss {} MB", + t.elapsed().as_secs_f64(), + errors.load(Ordering::Relaxed), + rss_mb(pid) + ); + Ok(()) +} + +fn billion_check(agent: &ureq::Agent, dir: &Path, pid: u32) -> Result<()> { + println!("billion-check: server rss {} MB", rss_mb(pid)); + report_get(agent, "GET / (all notes)", &format!("{SERVER}/"))?; + report_get(agent, "search marker42", &format!("{SERVER}/search?q=marker42"))?; + report_get(agent, "search v999 (in every line block)", &format!("{SERVER}/search?q=v999"))?; + report_get(agent, "search exact \"ret v999\"", &format!("{SERVER}/search?q=ret%20v999&exact=1"))?; + report_get(agent, "search regex absent zzq\\d+", &format!("{SERVER}/search?q=zzq%5Cd%2B&re=1"))?; + report_get(agent, "search regex ret v99\\d", &format!("{SERVER}/search?q=ret%20v99%5Cd&re=1"))?; + report_get(agent, "search regex (no literal) \\d{9}", &format!("{SERVER}/search?q=%5Cd%7B9%7D&re=1"))?; + report_get(agent, "search regex (no literal) v\\d{3}\\b", &format!("{SERVER}/search?q=v%5Cd%7B3%7D%5Cb&re=1"))?; + report_get(agent, "search regex (spans words) \\w+ \\w{9}", &format!("{SERVER}/search?q=%5Cw%2B%20%5Cw%7B9%7D&re=1"))?; + report_get(agent, " same, every note (all=1)", &format!("{SERVER}/search?q=%5Cw%2B%20%5Cw%7B9%7D&re=1&all=1"))?; + report_get(agent, "titles.json?q=Billion 7", &format!("{SERVER}/notes/titles.json?q=Billion%207"))?; + let nb = notebook_url(agent)?; + report_get(agent, "GET /notebooks/<id>", &format!("{SERVER}{nb}"))?; + let page = agent.get(&format!("{SERVER}{nb}")).call()?.body_mut().with_config().limit(u64::MAX).read_to_string()?; + let at = page.find("href=\"/notes/").context("no note link")?; + let rest = &page[at + 6..]; + let note = &rest[..rest.find('"').unwrap()]; + report_get(agent, "GET /notes/<id> (1M lines)", &format!("{SERVER}{note}"))?; + report_get(agent, "GET export.md (1M lines)", &format!("{SERVER}{note}/export.md"))?; + + let zip = dir.join("billion.zip"); + let t = Instant::now(); + let mut resp = agent.get(&format!("{SERVER}/export.zip")).call()?; + let mut out = std::io::BufWriter::new(std::fs::File::create(&zip)?); + let n = std::io::copy(&mut resp.body_mut().with_config().limit(u64::MAX).reader(), &mut out)?; + drop(out); + println!(" GET /export.zip {:.1}s, {:.0} MB, rss {} MB", t.elapsed().as_secs_f64(), n as f64 / 1e6, rss_mb(pid)); + let t = Instant::now(); + let lines = Command::new("sh") + .arg("-c") + .arg("unzip -p \"$0\" | wc -l") + .arg(&zip) + .output()?; + println!(" lines in zip: {} ({:.1}s)", String::from_utf8_lossy(&lines.stdout).trim(), t.elapsed().as_secs_f64()); + std::fs::remove_file(&zip)?; + Ok(()) +} + +fn notebook_url(agent: &ureq::Agent) -> Result<String> { + let html = agent.get(&format!("{SERVER}/")).call()?.body_mut().with_config().limit(u64::MAX).read_to_string()?; + let at = html.find("href=\"/notebooks/").context("no notebook link")?; + let rest = &html[at + 6..]; + Ok(rest[..rest.find('"').unwrap()].to_owned()) +} + +// --------------------------------------------------------------------------- +// huge: single very large notes +// --------------------------------------------------------------------------- + +const WORDS: &[&str] = &[ + "lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod", "tempor", + "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim", "ad", "minim", "veniam", "quis", +]; + +fn lorem_line(i: usize) -> String { + let n = 6 + i % 7; + let mut s = String::new(); + for k in 0..n { + if k > 0 { + s.push(' '); + } + s.push_str(WORDS[(i * 31 + k * 7) % WORDS.len()]); + } + s +} + +fn code_lines(n: usize) -> String { + let mut s = String::from("```rust\n"); + for i in 0..n { + match i % 8 { + 0 => s.push_str(&format!("pub fn handler_{i}(state: &State, id: u64) -> Result<Vec<Row>> {{\n")), + 1 => s.push_str(" let rows = load_rows(state, id, 50)?;\n"), + 2 => s.push_str(" let skipped = rows.iter().filter(|r| !r.name.is_empty()).count();\n"), + 3 => s.push_str(" if skipped > 2000 {\n"), + 4 => s.push_str(" return Err(anyhow!(\"too many rows: {skipped}\"));\n"), + 5 => s.push_str(" }\n"), + 6 => s.push_str(" Ok(rows.into_iter().map(|r| r.with_lang(\"en\")).collect())\n"), + _ => s.push_str("}\n"), + } + } + s.push_str("```\n"); + s +} + +/// The server, for RSS readings along a browser run. +static SERVER_PID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +fn server_rss() -> u64 { + rss_mb(SERVER_PID.load(Ordering::Relaxed)) +} + +fn huge(agent: &ureq::Agent, opts: &Opts, dir: &Path, pid: u32) -> Result<()> { + SERVER_PID.store(pid, Ordering::Relaxed); + let cases: Vec<(&str, Box<dyn Fn() -> String>)> = vec![ + ("tiny", Box::new(|| (0..3).map(|i| lorem_line(i) + "\n\n").collect())), + ("p10k", Box::new(|| (0..10_000).map(|i| lorem_line(i) + "\n\n").collect())), + ("code200k", Box::new(|| code_lines(200_000))), + ("p100k", Box::new(|| (0..100_000).map(|i| lorem_line(i) + "\n\n").collect())), + ("lines1m", Box::new(|| (0..1_000_000).map(|i| lorem_line(i) + "\n").collect())), + ("p1m", Box::new(|| (0..1_000_000).map(|i| lorem_line(i) + "\n\n").collect())), + // Near the 128 MB upload limit once form-encoded: short lines, little punctuation. + ("code8m", Box::new(|| { + let mut s = String::from("```\n"); + for i in 0..8_000_000 { + s.push_str(&format!(" ret v{}\n", i % 1000)); + } + s + "```\n" + })), + ]; + // The page's console (panics land there) goes to gecko.log. + let log = std::fs::File::create(dir.join("gecko.log"))?; + let gecko = Kill( + Command::new("geckodriver") + .args(["--port", DRIVER_PORT]) + .env("MOZ_HEADLESS", "1") + .env_remove("DISPLAY") + .env_remove("WAYLAND_DISPLAY") + .stdout(log.try_clone()?) + .stderr(log) + .spawn() + .context("starting geckodriver")?, + ); + wait_http(agent, &format!("http://127.0.0.1:{DRIVER_PORT}/status"))?; + let session = Session::new(agent, &format!("http://127.0.0.1:{DRIVER_PORT}"), &dir.join("profile"))?; + session.cmd("POST", "/timeouts", Some(json!({"script": 600_000, "pageLoad": 600_000})))?; + let result = (|| -> Result<()> { + for (name, make) in &cases { + if !opts.only.is_empty() && !opts.only.iter().any(|o| o == name) { + continue; + } + let text = make(); + println!("huge {name}: {} lines, {:.1} MB", text.lines().count(), text.len() as f64 / 1e6); + let t = Instant::now(); + let id = match import(agent, &format!("{name}.md"), &text) { + Ok(id) => id, + Err(e) => { + println!(" import failed after {:.1}s: {e}", t.elapsed().as_secs_f64()); + continue; + } + }; + println!(" import {:.2}s, server rss {} MB", t.elapsed().as_secs_f64(), rss_mb(pid)); + let note = format!("{SERVER}/notes/{id}"); + let (t, n, _) = timed_get(agent, &format!("{note}/export.md"))?; + println!(" export.md {:.2}s {:.1} MB", t, n as f64 / 1e6); + let (t, n, _) = timed_get(agent, ¬e)?; + println!(" page html {:.2}s {:.1} MB", t, n as f64 / 1e6); + browse(agent, &session, ¬e, name, dir)?; + let t = Instant::now(); + session.go(¬e)?; + session.wait_for(EDITABLE, "editable", 600)?; + println!(" reopen: editable after {:.2}s", t.elapsed().as_secs_f64()); + println!(" server rss {} MB", rss_mb(pid)); + // Kept DBs would otherwise gain 100+ MB per run. + session.go(&format!("{SERVER}/"))?; + agent.post(&format!("{note}/trash")).send_empty()?; + agent.post(&format!("{SERVER}/trash/empty")).send_empty()?; + } + Ok(()) + })(); + session.close(); + drop(gecko); + result +} + +/// Records, for each real keydown, the main-thread time it costs: our event handlers up +/// to the next frame plus that frame (rAF callbacks, style, layout, paint) until a timer +/// after it runs. `__raw` keeps keydown to that timer, which adds the idle wait for the +/// browser's 60 Hz frame clock (0 to 16.7 ms, set by when the key happens to land). +const LATENCY: &str = "window.__lat = []; window.__raw = []; if (!window.__latOn) { window.__latOn = true; let cur = null; \ + for (const t of ['keydown', 'beforeinput', 'input', 'selectionchange']) { let s = 0; \ + window.addEventListener(t, () => { s = performance.now(); if (t !== 'keydown') return; const c = cur = {t0: s, busy: 0}; \ + requestAnimationFrame(() => { const t2 = performance.now(); if (cur === c) cur = null; \ + setTimeout(() => { const t3 = performance.now(); __raw.push(t3 - c.t0); __lat.push(c.busy + t3 - t2); }, 0); }); }, true); \ + window.addEventListener(t, () => { if (cur) cur.busy += performance.now() - s; }, false); } } return true"; + +/// Splits the time: our handlers per event type (capture to bubble on window), rAF and +/// timer callbacks, and the rest (browser style, layout and paint). +const PROFILE: &str = "if (!window.__prof) { const P = window.__prof = {ev: {}, raf: 0, rafN: 0, tm: 0, tmN: 0}; \ + for (const t of ['keydown', 'beforeinput', 'input', 'keyup', 'selectionchange', 'compositionend']) { let s = 0; \ + window.addEventListener(t, () => { s = performance.now(); }, true); \ + window.addEventListener(t, () => { const d = performance.now() - s; P.ev[t] = (P.ev[t] || 0) + d; }, false); } \ + { let s = 0; document.addEventListener('selectionchange', () => { s = performance.now(); }, true); document.addEventListener('selectionchange', () => { P.ev.docsel = (P.ev.docsel || 0) + performance.now() - s; P.ev.docselN = (P.ev.docselN || 0) + 1; }, false); } \ + const raf = window.requestAnimationFrame.bind(window); window.requestAnimationFrame = cb => raf(ts => { const s = performance.now(); cb(ts); P.raf += performance.now() - s; P.rafN++; }); \ + const st = window.setTimeout.bind(window); window.setTimeout = (cb, ms, ...a) => st((...b) => { const s = performance.now(); cb(...b); P.tm += performance.now() - s; P.tmN++; }, ms, ...a); } \ + const P = window.__prof; P.ev = {}; P.raf = 0; P.rafN = 0; P.tm = 0; P.tmN = 0; return true"; + +const PROF_STATS: &str = "const P = window.__prof; const r = x => +x.toFixed(1); const ev = {}; \ + for (const k in P.ev) ev[k] = r(P.ev[k]); return {handlers_ms: ev, raf_ms: r(P.raf), raf_n: P.rafN, timers_ms: r(P.tm), timers_n: P.tmN}"; + +/// Each key's time, then with the frame wait. +const SERIES: &str = "const f = a => a.map(x => Math.round(x)).join(' '); return `${f(__lat)} | wait incl. ${f(__raw)}`"; + +const LAT_STATS: &str = "const t = [...__lat].sort((a, b) => a - b); if (!t.length) return null; \ + return {n: t.length, avg: +(t.reduce((a, b) => a + b, 0) / t.length).toFixed(2), p50: +t[t.length >> 1].toFixed(2), \ + p95: +t[Math.floor(t.length * 0.95)].toFixed(2), max: +t[t.length - 1].toFixed(2)}"; + +fn caret_at_block(s: &Session, frac: f64) -> Result<Value> { + // Scroll to `frac` of the editor's height (as a person would with the scrollbar); + // only blocks near the viewport are in the DOM, built on the next frames. + let n = s.js(&format!( + "const r = document.querySelector('#editor .ProseMirror'); r.focus(); \ + let sc = r.parentElement; \ + while (sc && !(sc.scrollHeight > sc.clientHeight && /(auto|scroll)/.test(getComputedStyle(sc).overflowY))) sc = sc.parentElement; \ + sc = sc || document.scrollingElement; \ + const top = sc === document.scrollingElement ? 0 : sc.getBoundingClientRect().top; \ + const rr = r.getBoundingClientRect(); \ + sc.scrollTop += rr.top - top + rr.height * {frac} - sc.clientHeight / 2; \ + return r.querySelectorAll('p, pre, li, h1, h2, h3').length" + ))?; + sleep(Duration::from_millis(400)); + // Units in document order among what is built: blocks, long ones chunk by chunk. + s.js(&format!( + "const r = document.querySelector('#editor .ProseMirror'); const units = []; \ + for (const b of r.querySelectorAll('p, pre, li, h1, h2, h3')) {{ const c = b.querySelectorAll('.code-chunk, .text-chunk'); if (c.length) units.push(...c); else units.push(b); }} \ + const u = units[Math.floor((units.length - 1) * {frac})]; \ + const w = document.createTreeWalker(u, NodeFilter.SHOW_TEXT); const tn = w.nextNode(); \ + if (tn) getSelection().collapse(tn, Math.min(5, tn.length)); else getSelection().collapse(u, 0); return true" + ))?; + Ok(n) +} + +fn keys_latency(s: &Session, keys: &str) -> Result<Value> { + s.js(LATENCY)?; + s.js(PROFILE)?; + // One key at a time, ~16 keys/s like a fast typist: a burst would queue keys behind + // each other and measure throughput instead of latency. + for k in keys.chars() { + s.keys("#editor .ProseMirror", &k.to_string())?; + sleep(Duration::from_millis(60)); + } + sleep(Duration::from_millis(300)); + let mut v = s.js(LAT_STATS)?; + v["with_frame_wait"] = s.js(&LAT_STATS.replace("__lat", "__raw"))?; + v["profile"] = s.js(PROF_STATS)?; + Ok(v) +} + +fn browse(agent: &ureq::Agent, s: &Session, note: &str, name: &str, dir: &Path) -> Result<()> { + let t = Instant::now(); + s.go(note)?; + let loaded = t.elapsed().as_secs_f64(); + if let Err(e) = s.wait_for(EDITABLE, "editable", 600) { + println!(" browser: {e}"); + return Ok(()); + } + println!(" browser: load {loaded:.2}s, editable after {:.2}s, server rss {} MB", t.elapsed().as_secs_f64(), server_rss()); + s.js(CAPTURE)?; + let blocks = caret_at_block(s, 0.5)?; + sleep(Duration::from_millis(500)); + println!(" blocks in DOM {blocks}, {}", s.js("const c = document.querySelectorAll('.code-chunk, .text-chunk'); \ + return c.length ? `${c.length} code chunks, ${getComputedStyle(c[0]).contentVisibility}, ${getComputedStyle(c[0]).containIntrinsicHeight}` : 'no code chunks'")?); + const MID: &str = "alpha bravo charlie delta echo foxtrot "; + const END: &str = "golf hotel india juliet kilo lima mike "; + const START: &str = "november oscar papa quebec romeo sierra"; + let at_mid = s.js("const s = getSelection(); return s.anchorNode && s.anchorNode.textContent.slice(Math.max(0, s.anchorOffset - 20), s.anchorOffset)")?; + println!(" type 40 chars mid {}", keys_latency(s, MID)?); + // 40 presses: of 10, the 95th percentile would be the slowest one. + println!(" enter x40 mid {}", keys_latency(s, &"\u{E007}".repeat(40))?); + println!(" series {}", s.js(SERIES)?); + println!(" backspace x40 mid {}", keys_latency(s, &"\u{E003}".repeat(40))?); + println!(" series {}", s.js(SERIES)?); + // STRESS_PROBE="label=js;;label=js": run each snippet, then time typing again (bisecting). + if let Ok(probe) = std::env::var("STRESS_PROBE") { + for step in probe.split(";;") { + let (label, js) = step.split_once('=').unwrap_or((step, "")); + s.js(&format!("{js}; return true"))?; + caret_at_block(s, 0.5)?; + sleep(Duration::from_millis(300)); + println!(" probe {label:<20} {}", keys_latency(s, "abcdefghijklmnopqrst")?); + println!(" series {}", s.js(SERIES)?); + } + } + caret_at_block(s, 1.0)?; + sleep(Duration::from_millis(300)); + let at_end = s.js("const s = getSelection(); return s.anchorNode && s.anchorNode.textContent.slice(Math.max(0, s.anchorOffset - 20), s.anchorOffset)")?; + println!(" type 40 chars end {}", keys_latency(s, END)?); + caret_at_block(s, 0.0)?; + sleep(Duration::from_millis(300)); + let at_start = s.js("const s = getSelection(); return s.anchorNode && s.anchorNode.textContent.slice(Math.max(0, s.anchorOffset - 20), s.anchorOffset)")?; + println!(" type 40 chars start {}", keys_latency(s, START)?); + println!(" after typing: server rss {} MB", server_rss()); + // The model must hold each typed string once, right after where the caret was. + // The server applies updates a moment after the client sent them: wait for all + // three strings (a lost keystroke still shows as WRONG after the deadline). + let waited = Instant::now(); + let mut md; + loop { + sleep(Duration::from_millis(250)); + md = agent.get(&format!("{note}/export.md")).call()?.body_mut().with_config().limit(u64::MAX).read_to_string()?; + if [MID, END, START].iter().all(|x| md.contains(x)) || waited.elapsed() > Duration::from_secs(15) { + break; + } + } + println!(" server has the edits after {:.2}s, server rss {} MB", waited.elapsed().as_secs_f64(), server_rss()); + println!( + " sync state {}, export {} MB, errors so far {}", + s.js("const e = document.querySelector('[data-state]'); return e && e.dataset.state")?, + md.len() >> 20, + s.js("return __log.filter(l => l.startsWith('error') || l.startsWith('uncaught')).length")? + ); + for (what, text, before) in [("mid", MID, &at_mid), ("end", END, &at_end), ("start", START, &at_start)] { + let found: Vec<usize> = md.match_indices(text).map(|(i, _)| i).collect(); + let ok = found.len() == 1 && before.as_str().is_some_and(|b| md[..found[0]].ends_with(b)); + let ctx = found.first().map(|&i| md[i.saturating_sub(30)..(i + text.len() + 10).min(md.len())].replace('\n', "⏎")).unwrap_or_default(); + let line = found.first().map_or(0, |&i| md[..i].matches('\n').count() + 1); + println!(" check {what:<5} {} (found {}x at line {line}, caret after {before}) …{ctx}…", if ok { "ok" } else { "WRONG" }, found.len()); + if found.is_empty() { + let head: String = md.chars().take(160).collect(); + println!(" export starts {:?}; dom starts {}", head, s.js("return document.querySelector('#editor .ProseMirror').textContent.slice(0, 160)")?); + } + } + // Select all, delete, undo: the heaviest structural edits. + let ops = s.js( + "const r = document.querySelector('#editor .ProseMirror'); r.focus(); \ + const ev = (k, c, mod) => r.dispatchEvent(new KeyboardEvent('keydown', {key: k, code: c, ctrlKey: mod, cancelable: true, bubbles: true})); \ + const time = f => { const s = performance.now(); f(); return +(performance.now() - s).toFixed(1); }; \ + const all = time(() => ev('a', 'KeyA', true)); \ + const del = time(() => ev('Backspace', 'Backspace', false)); \ + const after = r.scrollHeight; \ + const undo = time(() => ev('z', 'KeyZ', true)); \ + return {select_all_ms: all, delete_ms: del, height_after_delete: after, undo_ms: undo, height_after_undo: r.scrollHeight}", + )?; + println!(" {ops}"); + sleep(Duration::from_millis(3000)); + println!(" after undo + 3 s: server rss {} MB", server_rss()); + std::thread::sleep(Duration::from_millis(1500)); + println!(" after undo: {}", s.js("const r = document.querySelector('#editor .ProseMirror'); return {height: r.scrollHeight, text: r.textContent.length, children: r.children.length, code: r.querySelectorAll('pre').length}")?); + let _ = s.screenshot(&dir.join(format!("{name}.png"))); + let err = s.js("return window.__log ? __log.filter(l => l.startsWith('error') || l.startsWith('uncaught')).slice(0, 40) : []")?; + if err.as_array().is_some_and(|a| !a.is_empty()) { + println!(" console errors: {err}"); + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// flood: an upload that never ends +// --------------------------------------------------------------------------- + +/// A urlencoded form body with `lines` lorem lines, produced on the fly. +struct Endless { + prefix: Vec<u8>, + at: usize, + lines: u64, + line: Vec<u8>, + pos: usize, +} + +impl Read for Endless { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { + if self.at < self.prefix.len() { + let n = (self.prefix.len() - self.at).min(buf.len()); + buf[..n].copy_from_slice(&self.prefix[self.at..self.at + n]); + self.at += n; + return Ok(n); + } + let mut n = 0; + while n < buf.len() { + if self.pos == self.line.len() { + if self.lines == 0 { + break; + } + self.lines -= 1; + self.pos = 0; + } + let k = (self.line.len() - self.pos).min(buf.len() - n); + buf[n..n + k].copy_from_slice(&self.line[self.pos..self.pos + k]); + self.pos += k; + n += k; + } + Ok(n) + } +} + +fn flood(agent: &ureq::Agent, pid: u32) -> Result<()> { + println!("flood: POST /import/file with 1e9 lines (~45 GB)"); + let line = b"lorem+ipsum+dolor+sit+amet+consectetur+adipiscing%0A".to_vec(); + let mut body = Endless { prefix: b"path=flood.md&text=".to_vec(), at: 0, lines: 1_000_000_000, pos: line.len(), line }; + let t = Instant::now(); + let res = agent + .post(&format!("{SERVER}/import/file")) + .header("content-type", "application/x-www-form-urlencoded") + .send(ureq::SendBody::from_reader(&mut body)); + match res { + Ok(r) => println!(" answered {} after {:.2}s", r.status(), t.elapsed().as_secs_f64()), + Err(e) => println!(" connection ended after {:.2}s: {e}", t.elapsed().as_secs_f64()), + } + println!(" server rss {} MB", rss_mb(pid)); + report_get(agent, "GET / after flood", &format!("{SERVER}/"))?; + Ok(()) +} + + +// --------------------------------------------------------------------------- +// exp: which DOM shape keeps native typing fast in a huge code block +// --------------------------------------------------------------------------- + +fn exp(agent: &ureq::Agent, dir: &Path, only: &[String]) -> Result<()> { + let lines: Vec<String> = (0..200_000).map(|i| format!(" let rows_{i} = load_rows(state, id, 50)?;\n")).collect(); + let esc = |s: &str| s.replace('&', "&").replace('<', "<"); + let page = |body: String| format!("<!DOCTYPE html><html><body><pre contenteditable=true style='white-space:pre'><code>{body}</code></pre></body></html>"); + let shapes: Vec<(&str, String)> = vec![ + ("one text node", page(esc(&lines.concat()))), + ("text node per line", String::new()), + ("text node per 100 lines", String::new()), + ("span per line", page(lines.iter().map(|l| format!("<span>{}</span>", esc(l))).collect())), + ("div per line", page(lines.iter().map(|l| format!("<div>{}</div>", esc(l.trim_end_matches('\n')))).collect())), + ("cv chunk per 100 lines", page(lines.chunks(100).map(|c| format!("<div style='content-visibility:auto;contain-intrinsic-size:auto 1px auto 1500px'>{}</div>", esc(&c.concat()))).collect())), + ("cv chunk per 1000 lines", page(lines.chunks(1000).map(|c| format!("<div style='content-visibility:auto;contain-intrinsic-size:auto 1px auto 15000px'>{}</div>", esc(&c.concat()))).collect())), + ("cv in editable div", format!("<!DOCTYPE html><html><body><div contenteditable=true><h1>t</h1><pre><code style='display:block'>{}</code></pre></div></body></html>", + lines.chunks(1000).map(|c| format!("<div style='content-visibility:auto;contain-intrinsic-size:auto none auto 22000px'>{}</div>", esc(&c.concat()))).collect::<String>())), + ("cv in div, pre overflow", format!("<!DOCTYPE html><html><body><div contenteditable=true><h1>t</h1><pre style='overflow-x:auto;line-height:22px'><code style='display:block'>{}</code></pre></div></body></html>", + lines.chunks(1000).map(|c| format!("<div style='content-visibility:auto;contain-intrinsic-size:auto none auto 22000px'>{}</div>", esc(&c.concat()))).collect::<String>())), + ("cv in div, 20 chunks only", format!("<!DOCTYPE html><html><body><div contenteditable=true><h1>t</h1><pre style='overflow-x:auto;line-height:22px'><code style='display:block'>{}</code></pre></div></body></html>", + lines[..20_000].chunks(1000).map(|c| format!("<div style='content-visibility:auto;contain-intrinsic-size:auto none auto 22000px'>{}</div>", esc(&c.concat()))).collect::<String>())), + ("plain 1000 lines", page(esc(&lines[..1000].concat()))), + ("cv in div, nospell", format!("<!DOCTYPE html><html><body><div contenteditable=true spellcheck=false><h1>t</h1><pre style='overflow-x:auto;line-height:22px'><code style='display:block'>{}</code></pre></div></body></html>", + lines.chunks(1000).map(|c| format!("<div style='content-visibility:auto;contain-intrinsic-size:auto none auto 22000px'>{}</div>", esc(&c.concat()))).collect::<String>())), + ("cv in div, virtual", format!("<!DOCTYPE html><html><body><div contenteditable=true><h1>t</h1><pre style='overflow-x:auto;line-height:22px'><code style='display:block'>{}</code></pre></div></body></html>", + lines.chunks(1000).enumerate().map(|(i, c)| if (i == 0) || (98..103).contains(&i) || i == 199 { format!("<div style='height:22000px'>{}</div>", esc(&c.concat())) } else { "<div style='height:22000px'></div>".to_owned() }).collect::<String>())), + ("p100k text", format!("<!DOCTYPE html><html><body><div contenteditable=true><pre><code></code></pre>{}</div></body></html>", + (0..100_000).map(|i| format!("<p>Paragraph {i} lorem ipsum dolor sit amet consectetur adipiscing elit sed do</p>")).collect::<String>())), + ("p100k empty", format!("<!DOCTYPE html><html><body><div contenteditable=true><pre><code></code></pre>{}</div></body></html>", + (0..100_000).map(|i| if i < 50 || (50_000..50_050).contains(&i) { format!("<p>Paragraph {i} lorem ipsum dolor sit amet consectetur adipiscing elit sed do</p>") } else { "<p style='height:28px'></p>".to_owned() }).collect::<String>())), + ("p100k grouped", format!("<!DOCTYPE html><html><body><div contenteditable=true><pre><code></code></pre>{}</div></body></html>", + (0..100).map(|g| if g == 0 || g == 50 { format!("<div>{}</div>", (0..1000).map(|i| format!("<p>Paragraph {i} lorem ipsum dolor sit amet consectetur adipiscing elit sed do</p>")).collect::<String>()) } else { "<div style='height:28000px'></div>".to_owned() }).collect::<String>())), + ("textarea", format!("<!DOCTYPE html><html><body><textarea style='width:90vw;height:90vh'>{}</textarea></body></html>", esc(&lines.concat()))), + ]; + let gecko = Kill( + Command::new("geckodriver").args(["--port", DRIVER_PORT]).env("MOZ_HEADLESS", "1") + .env_remove("DISPLAY").env_remove("WAYLAND_DISPLAY").stdout(Stdio::null()).stderr(Stdio::null()).spawn()?, + ); + wait_http(agent, &format!("http://127.0.0.1:{DRIVER_PORT}/status"))?; + let s = Session::new(agent, &format!("http://127.0.0.1:{DRIVER_PORT}"), &dir.join("profile"))?; + s.cmd("POST", "/timeouts", Some(json!({"script": 600_000, "pageLoad": 600_000})))?; + for (name, html) in shapes { + if !only.is_empty() && !only.iter().any(|o| name.contains(o.as_str())) { + continue; + } + let html = if html.is_empty() { + // Text nodes are built by script: HTML parsing merges adjacent text. + let per = if name.contains("100") { 100 } else { 1 }; + format!("<!DOCTYPE html><html><body><pre contenteditable=true style='white-space:pre'><code></code></pre><script>\ + const c = document.querySelector('code'); const L = []; for (let i = 0; i < 200000; i++) L.push(' let rows_' + i + ' = load_rows(state, id, 50)?;\\n'); \ + for (let i = 0; i < L.length; i += {per}) c.appendChild(document.createTextNode(L.slice(i, i + {per}).join('')));</script></body></html>") + } else { + html + }; + let file = dir.join("exp.html"); + std::fs::write(&file, html)?; + let t = Instant::now(); + s.go(&format!("file://{}", file.display()))?; + let load = t.elapsed().as_secs_f64(); + for (where_, frac) in [("start", 0.0), ("middle", 0.5), ("end", 1.0)] { + if name == "textarea" { + s.js(&format!("const t = document.querySelector('textarea'); t.focus(); const at = Math.floor(t.value.length * {frac}); t.setSelectionRange(at, at); return true"))?; + s.js(LATENCY.replace("#editor .ProseMirror", "textarea").as_str())?; + s.keys("textarea", "abcdefghij")?; + sleep(Duration::from_millis(300)); + println!("{name:<26} load {load:5.1}s {where_:<6} {}", s.js(LAT_STATS)?); + continue; + } + s.js(&format!("const pre = document.querySelector('[contenteditable]'); pre.focus(); const code = document.querySelector('pre code').firstChild ? document.querySelector('pre') : pre; \ + const w = document.createTreeWalker(code, NodeFilter.SHOW_TEXT); const all = []; let n; while ((n = w.nextNode())) all.push(n); \ + const tn = all[Math.floor((all.length - 1) * {frac})]; getSelection().collapse(tn, Math.floor(tn.length * {frac})); tn.parentElement.scrollIntoView({{block: 'center'}}); return true"))?; + s.js(LATENCY.replace("#editor .ProseMirror", "[contenteditable]").as_str())?; + for k in "abcdefghij".chars() { + s.keys("[contenteditable]", &k.to_string())?; + sleep(Duration::from_millis(60)); + } + sleep(Duration::from_millis(300)); + println!("{name:<26} load {load:5.1}s {where_:<6} {}", s.js(LAT_STATS)?); + } + } + s.close(); + drop(gecko); + Ok(()) +}