@storacha/md-merge 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,204 @@
1
+ The contents of this repository are Copyright (c) corresponding authors and
2
+ contributors, licensed under the `Permissive License Stack` meaning either of:
3
+
4
+ - Apache-2.0 Software License: https://www.apache.org/licenses/LICENSE-2.0
5
+ ([...4tr2kfsq](https://dweb.link/ipfs/bafkreiankqxazcae4onkp436wag2lj3ccso4nawxqkkfckd6cg4tr2kfsq))
6
+
7
+ - MIT Software License: https://opensource.org/licenses/MIT
8
+ ([...vljevcba](https://dweb.link/ipfs/bafkreiepofszg4gfe2gzuhojmksgemsub2h4uy2gewdnr35kswvljevcba))
9
+
10
+ You may not use the contents of this repository except in compliance
11
+ with one of the listed Licenses. For an extended clarification of the
12
+ intent behind the choice of Licensing please refer to
13
+ https://protocol.ai/blog/announcing-the-permissive-license-stack/
14
+
15
+ Unless required by applicable law or agreed to in writing, software
16
+ distributed under the terms listed in this notice is distributed on
17
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
18
+ either express or implied. See each License for the specific language
19
+ governing permissions and limitations under that License.
20
+
21
+ <!--- SPDX-License-Identifier: Apache-2.0 OR MIT -->
22
+
23
+ `SPDX-License-Identifier: Apache-2.0 OR MIT`
24
+
25
+ Verbatim copies of both licenses are included below:
26
+
27
+ <details><summary>Apache-2.0 Software License</summary>
28
+
29
+ ```
30
+ Apache License
31
+ Version 2.0, January 2004
32
+ http://www.apache.org/licenses/
33
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
34
+ 1. Definitions.
35
+ "License" shall mean the terms and conditions for use, reproduction,
36
+ and distribution as defined by Sections 1 through 9 of this document.
37
+ "Licensor" shall mean the copyright owner or entity authorized by
38
+ the copyright owner that is granting the License.
39
+ "Legal Entity" shall mean the union of the acting entity and all
40
+ other entities that control, are controlled by, or are under common
41
+ control with that entity. For the purposes of this definition,
42
+ "control" means (i) the power, direct or indirect, to cause the
43
+ direction or management of such entity, whether by contract or
44
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
45
+ outstanding shares, or (iii) beneficial ownership of such entity.
46
+ "You" (or "Your") shall mean an individual or Legal Entity
47
+ exercising permissions granted by this License.
48
+ "Source" form shall mean the preferred form for making modifications,
49
+ including but not limited to software source code, documentation
50
+ source, and configuration files.
51
+ "Object" form shall mean any form resulting from mechanical
52
+ transformation or translation of a Source form, including but
53
+ not limited to compiled object code, generated documentation,
54
+ and conversions to other media types.
55
+ "Work" shall mean the work of authorship, whether in Source or
56
+ Object form, made available under the License, as indicated by a
57
+ copyright notice that is included in or attached to the work
58
+ (an example is provided in the Appendix below).
59
+ "Derivative Works" shall mean any work, whether in Source or Object
60
+ form, that is based on (or derived from) the Work and for which the
61
+ editorial revisions, annotations, elaborations, or other modifications
62
+ represent, as a whole, an original work of authorship. For the purposes
63
+ of this License, Derivative Works shall not include works that remain
64
+ separable from, or merely link (or bind by name) to the interfaces of,
65
+ the Work and Derivative Works thereof.
66
+ "Contribution" shall mean any work of authorship, including
67
+ the original version of the Work and any modifications or additions
68
+ to that Work or Derivative Works thereof, that is intentionally
69
+ submitted to Licensor for inclusion in the Work by the copyright owner
70
+ or by an individual or Legal Entity authorized to submit on behalf of
71
+ the copyright owner. For the purposes of this definition, "submitted"
72
+ means any form of electronic, verbal, or written communication sent
73
+ to the Licensor or its representatives, including but not limited to
74
+ communication on electronic mailing lists, source code control systems,
75
+ and issue tracking systems that are managed by, or on behalf of, the
76
+ Licensor for the purpose of discussing and improving the Work, but
77
+ excluding communication that is conspicuously marked or otherwise
78
+ designated in writing by the copyright owner as "Not a Contribution."
79
+ "Contributor" shall mean Licensor and any individual or Legal Entity
80
+ on behalf of whom a Contribution has been received by Licensor and
81
+ subsequently incorporated within the Work.
82
+ 2. Grant of Copyright License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ copyright license to reproduce, prepare Derivative Works of,
86
+ publicly display, publicly perform, sublicense, and distribute the
87
+ Work and such Derivative Works in Source or Object form.
88
+ 3. Grant of Patent License. Subject to the terms and conditions of
89
+ this License, each Contributor hereby grants to You a perpetual,
90
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
91
+ (except as stated in this section) patent license to make, have made,
92
+ use, offer to sell, sell, import, and otherwise transfer the Work,
93
+ where such license applies only to those patent claims licensable
94
+ by such Contributor that are necessarily infringed by their
95
+ Contribution(s) alone or by combination of their Contribution(s)
96
+ with the Work to which such Contribution(s) was submitted. If You
97
+ institute patent litigation against any entity (including a
98
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
99
+ or a Contribution incorporated within the Work constitutes direct
100
+ or contributory patent infringement, then any patent licenses
101
+ granted to You under this License for that Work shall terminate
102
+ as of the date such litigation is filed.
103
+ 4. Redistribution. You may reproduce and distribute copies of the
104
+ Work or Derivative Works thereof in any medium, with or without
105
+ modifications, and in Source or Object form, provided that You
106
+ meet the following conditions:
107
+ (a) You must give any other recipients of the Work or
108
+ Derivative Works a copy of this License; and
109
+ (b) You must cause any modified files to carry prominent notices
110
+ stating that You changed the files; and
111
+ (c) You must retain, in the Source form of any Derivative Works
112
+ that You distribute, all copyright, patent, trademark, and
113
+ attribution notices from the Source form of the Work,
114
+ excluding those notices that do not pertain to any part of
115
+ the Derivative Works; and
116
+ (d) If the Work includes a "NOTICE" text file as part of its
117
+ distribution, then any Derivative Works that You distribute must
118
+ include a readable copy of the attribution notices contained
119
+ within such NOTICE file, excluding those notices that do not
120
+ pertain to any part of the Derivative Works, in at least one
121
+ of the following places: within a NOTICE text file distributed
122
+ as part of the Derivative Works; within the Source form or
123
+ documentation, if provided along with the Derivative Works; or,
124
+ within a display generated by the Derivative Works, if and
125
+ wherever such third-party notices normally appear. The contents
126
+ of the NOTICE file are for informational purposes only and
127
+ do not modify the License. You may add Your own attribution
128
+ notices within Derivative Works that You distribute, alongside
129
+ or as an addendum to the NOTICE text from the Work, provided
130
+ that such additional attribution notices cannot be construed
131
+ as modifying the License.
132
+ You may add Your own copyright statement to Your modifications and
133
+ may provide additional or different license terms and conditions
134
+ for use, reproduction, or distribution of Your modifications, or
135
+ for any such Derivative Works as a whole, provided Your use,
136
+ reproduction, and distribution of the Work otherwise complies with
137
+ the conditions stated in this License.
138
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
139
+ any Contribution intentionally submitted for inclusion in the Work
140
+ by You to the Licensor shall be under the terms and conditions of
141
+ this License, without any additional terms or conditions.
142
+ Notwithstanding the above, nothing herein shall supersede or modify
143
+ the terms of any separate license agreement you may have executed
144
+ with Licensor regarding such Contributions.
145
+ 6. Trademarks. This License does not grant permission to use the trade
146
+ names, trademarks, service marks, or product names of the Licensor,
147
+ except as required for reasonable and customary use in describing the
148
+ origin of the Work and reproducing the content of the NOTICE file.
149
+ 7. Disclaimer of Warranty. Unless required by applicable law or
150
+ agreed to in writing, Licensor provides the Work (and each
151
+ Contributor provides its Contributions) on an "AS IS" BASIS,
152
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
153
+ implied, including, without limitation, any warranties or conditions
154
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
155
+ PARTICULAR PURPOSE. You are solely responsible for determining the
156
+ appropriateness of using or redistributing the Work and assume any
157
+ risks associated with Your exercise of permissions under this License.
158
+ 8. Limitation of Liability. In no event and under no legal theory,
159
+ whether in tort (including negligence), contract, or otherwise,
160
+ unless required by applicable law (such as deliberate and grossly
161
+ negligent acts) or agreed to in writing, shall any Contributor be
162
+ liable to You for damages, including any direct, indirect, special,
163
+ incidental, or consequential damages of any character arising as a
164
+ result of this License or out of the use or inability to use the
165
+ Work (including but not limited to damages for loss of goodwill,
166
+ work stoppage, computer failure or malfunction, or any and all
167
+ other commercial damages or losses), even if such Contributor
168
+ has been advised of the possibility of such damages.
169
+ 9. Accepting Warranty or Additional Liability. While redistributing
170
+ the Work or Derivative Works thereof, You may choose to offer,
171
+ and charge a fee for, acceptance of support, warranty, indemnity,
172
+ or other liability obligations and/or rights consistent with this
173
+ License. However, in accepting such obligations, You may act only
174
+ on Your own behalf and on Your sole responsibility, not on behalf
175
+ of any other Contributor, and only if You agree to indemnify,
176
+ defend, and hold each Contributor harmless for any liability
177
+ incurred by, or claims asserted against, such Contributor by reason
178
+ of your accepting any such warranty or additional liability.
179
+ END OF TERMS AND CONDITIONS
180
+ ```
181
+
182
+ </details>
183
+
184
+ <details><summary>MIT Software License</summary>
185
+
186
+ ```
187
+ Permission is hereby granted, free of charge, to any person obtaining a copy
188
+ of this software and associated documentation files (the "Software"), to deal
189
+ in the Software without restriction, including without limitation the rights
190
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
191
+ copies of the Software, and to permit persons to whom the Software is
192
+ furnished to do so, subject to the following conditions:
193
+ The above copyright notice and this permission notice shall be included in
194
+ all copies or substantial portions of the Software.
195
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
196
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
197
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
198
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
199
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
200
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
201
+ THE SOFTWARE.
202
+ ```
203
+
204
+ </details>
package/README.md ADDED
@@ -0,0 +1,163 @@
1
+ # md-merge
2
+
3
+ CRDT-based markdown merging using RGA-backed mdast trees.
4
+
5
+ Every `children` array in a markdown AST is replaced with an [RGA](https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type#Sequence_CRDTs) (Replicated Growable Array), giving deterministic merge semantics at every nesting level — paragraphs, list items, inline formatting, everything.
6
+
7
+ No three-way merge needed. The RGA *is* the history.
8
+
9
+ ## How it works
10
+
11
+ 1. **Parse** markdown to an [mdast](https://github.com/syntax-tree/mdast) tree
12
+ 2. **Convert** to an RGA-backed tree (`RGATree`) — each `children` array becomes an RGA with unique node IDs and causal ordering
13
+ 3. **Edit** by generating `RGAChangeSet`s from new markdown — diffs are resolved to RGA node IDs, not array indices
14
+ 4. **Merge** by applying each peer's changesets — RGA semantics handle concurrent inserts/deletes deterministically
15
+ 5. **Serialize** trees and changesets to DAG-CBOR for storage and exchange
16
+
17
+ ## Install
18
+
19
+ ```
20
+ npm install md-merge
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ### Bootstrap a tree from markdown
26
+
27
+ ```typescript
28
+ import { parse, toRGATree, toMdast, stringify } from 'md-merge'
29
+ import type { RGAEvent, EventComparator } from 'md-merge'
30
+
31
+ // Define your event type (identifies who made each edit)
32
+ class MyEvent implements RGAEvent {
33
+ constructor(readonly name: string) {}
34
+ toString() { return this.name }
35
+ }
36
+
37
+ const compare: EventComparator<MyEvent> = (a, b) =>
38
+ a.name < b.name ? -1 : a.name > b.name ? 1 : 0
39
+
40
+ // Create an RGA tree
41
+ const tree = toRGATree(parse('# Hello\n\nWorld.\n'), new MyEvent('alice'), compare)
42
+
43
+ // Convert back to markdown
44
+ stringify(toMdast(tree)) // '# Hello\n\nWorld.\n'
45
+ ```
46
+
47
+ ### Generate and apply changesets
48
+
49
+ ```typescript
50
+ import { generateRGAChangeSet, applyRGAChangeSet } from 'md-merge'
51
+
52
+ const aliceEdit = new MyEvent('alice-v2')
53
+ const newDoc = parse('# Hello\n\nWorld.\n\nNew paragraph.\n')
54
+
55
+ // Generate an RGA-addressed changeset (uses node IDs, not indices)
56
+ const changeset = generateRGAChangeSet(tree, newDoc, aliceEdit)
57
+
58
+ // Apply it
59
+ const updated = applyRGAChangeSet(tree, changeset, compare)
60
+ stringify(toMdast(updated)) // '# Hello\n\nWorld.\n\nNew paragraph.\n'
61
+ ```
62
+
63
+ ### Merge concurrent edits
64
+
65
+ ```typescript
66
+ // Alice and Bob both start from the same tree
67
+ // Alice adds a paragraph, Bob deletes one — each generates a changeset
68
+
69
+ const aliceCS = generateRGAChangeSet(tree, aliceNewDoc, aliceEvent)
70
+ const bobCS = generateRGAChangeSet(tree, bobNewDoc, bobEvent)
71
+
72
+ // Apply both — order doesn't matter, result converges
73
+ let merged = applyRGAChangeSet(tree, aliceCS, compare)
74
+ merged = applyRGAChangeSet(merged, bobCS, compare)
75
+
76
+ // Or the other way — same result
77
+ let merged2 = applyRGAChangeSet(tree, bobCS, compare)
78
+ merged2 = applyRGAChangeSet(merged2, aliceCS, compare)
79
+ ```
80
+
81
+ ### Serialize to DAG-CBOR
82
+
83
+ ```typescript
84
+ import { encodeTree, decodeTree, encodeChangeSet, decodeChangeSet } from 'md-merge'
85
+
86
+ // Encode a tree to a content-addressed block
87
+ const block = await encodeTree(tree)
88
+ block.cid // CID of the block
89
+ block.bytes // Uint8Array of DAG-CBOR
90
+
91
+ // Decode it back (provide event parser + fingerprint fn + comparator)
92
+ const decoded = await decodeTree(
93
+ { bytes: block.bytes },
94
+ s => new MyEvent(s), // parseEvent
95
+ fingerprintFn, // node fingerprint function
96
+ compare,
97
+ )
98
+
99
+ // Same for changesets
100
+ const csBlock = await encodeChangeSet(changeset)
101
+ const decodedCS = await decodeChangeSet({ bytes: csBlock.bytes }, s => new MyEvent(s))
102
+ ```
103
+
104
+ ## Architecture
105
+
106
+ ```
107
+ markdown string
108
+ ↓ parse()
109
+ mdast Root
110
+ ↓ toRGATree(root, event, compare)
111
+ RGATreeRoot ← every children[] is now an RGA
112
+ ↓ generateRGAChangeSet(tree, newMdast, event)
113
+ RGAChangeSet ← ID-addressed ops (no array indices)
114
+ ↓ applyRGAChangeSet(tree, changeset, compare)
115
+ RGATreeRoot (updated)
116
+ ↓ toMdast(tree)
117
+ mdast Root
118
+ ↓ stringify()
119
+ markdown string
120
+ ```
121
+
122
+ ### Key types
123
+
124
+ | Type | Description |
125
+ |------|-------------|
126
+ | `RGATreeRoot<E>` | Root node with RGA-backed children |
127
+ | `RGAChangeSet<E>` | Set of ID-addressed changes + the event that produced them |
128
+ | `RGAChange<E>` | Single op: insert/delete/modify with `parentPath`, `targetId`, `afterId` |
129
+ | `RGA<T, E>` | Replicated Growable Array — ordered CRDT sequence |
130
+ | `RGANodeId<E>` | `{ uuid, event }` — unique ID for each node |
131
+ | `RGAEvent` | Interface for event types (just needs `toString()`) |
132
+
133
+ ### Why no three-way merge?
134
+
135
+ Traditional text merge needs a common ancestor to figure out what changed on each side. With RGA, every node carries its causal history (who inserted it, after which predecessor). Two RGA trees can be merged by applying each other's operations — concurrent inserts land deterministically based on event ordering, and tombstoned deletes are idempotent.
136
+
137
+ ## API Reference
138
+
139
+ ### Parsing
140
+ - `parse(markdown: string): Root` — parse markdown to mdast
141
+ - `stringify(root: Root): string` — serialize mdast to markdown
142
+ - `fingerprint(node: RootContent): string` — content hash of a node
143
+
144
+ ### Diffing (index-based, internal)
145
+ - `diff(oldRoot, newRoot): ChangeSet` — LCS-based mdast diff
146
+ - `applyChangeSet(root, changeset): Root` — apply index-based changes
147
+
148
+ ### RGA Tree
149
+ - `toRGATree(root, event, compare): RGATreeRoot` — convert mdast to RGA tree
150
+ - `toMdast(rgaRoot): Root` — convert RGA tree back to mdast
151
+ - `applyMdastToRGATree(existing, newRoot, event, compare): RGATreeRoot` — shorthand for generate + apply
152
+ - `generateRGAChangeSet(existing, newRoot, event): RGAChangeSet` — diff and resolve to RGA IDs
153
+ - `applyRGAChangeSet(root, changeset, compare): RGATreeRoot` — apply ID-addressed changes
154
+
155
+ ### Codec (DAG-CBOR)
156
+ - `encodeTree(root): Promise<Block>` — serialize RGA tree
157
+ - `decodeTree(block, parseEvent, fpFn, compare): Promise<RGATreeRoot>` — deserialize
158
+ - `encodeChangeSet(cs): Promise<Block>` — serialize changeset
159
+ - `decodeChangeSet(block, parseEvent): Promise<RGAChangeSet>` — deserialize
160
+
161
+ ## License
162
+
163
+ MIT — see [LICENSE.md](./LICENSE.md)
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@storacha/md-merge",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": "./dist/index.js"
9
+ },
10
+ "dependencies": {
11
+ "remark": "^15",
12
+ "remark-parse": "^11",
13
+ "remark-stringify": "^11",
14
+ "unified": "^11",
15
+ "@storacha/ucn": "1.1.1-rc.3",
16
+ "multiformats": "^13",
17
+ "@ipld/dag-cbor": "^9"
18
+ },
19
+ "devDependencies": {
20
+ "typescript": "^5.4",
21
+ "vitest": "^3",
22
+ "@types/node": "^22",
23
+ "@types/mdast": "^4"
24
+ },
25
+ "scripts": {
26
+ "build": "tsc",
27
+ "check": "tsc --noEmit",
28
+ "test": "vitest run"
29
+ }
30
+ }
package/src/codec.ts ADDED
@@ -0,0 +1,245 @@
1
+ /**
2
+ * DAG-CBOR serialization for RGATree and RGAChangeSet.
3
+ *
4
+ * Converts RGA class instances (with Maps, nested RGAs) to plain
5
+ * CBOR-friendly objects and back.
6
+ */
7
+
8
+ import { encode, decode } from 'multiformats/block'
9
+ import { sha256 } from 'multiformats/hashes/sha2'
10
+ import * as cbor from '@ipld/dag-cbor'
11
+ import { RGA, type RGANodeId, type RGANode, type RGAEvent, type EventComparator } from './crdt/rga.js'
12
+ import type { RGATreeRoot, RGATreeNode, RGAParentNode } from './types.js'
13
+ import type { RGAChangeSet, RGAChange } from './types.js'
14
+
15
+
16
+ /** Recursively strip `undefined` values (not IPLD-compatible). */
17
+ function stripUndefined(obj: unknown): unknown {
18
+ if (obj === null || obj === undefined) return null
19
+ if (Array.isArray(obj)) return obj.map(stripUndefined)
20
+ if (typeof obj === 'object') {
21
+ const clean: Record<string, unknown> = {}
22
+ for (const [k, v] of Object.entries(obj as Record<string, unknown>)) {
23
+ if (v !== undefined) clean[k] = stripUndefined(v)
24
+ }
25
+ return clean
26
+ }
27
+ return obj
28
+ }
29
+
30
+ // ---- Serializable shapes (plain objects, no class instances) ----
31
+
32
+ interface SerializedRGANode {
33
+ id: { uuid: string; event: string }
34
+ value: unknown
35
+ afterId: { uuid: string; event: string } | null
36
+ tombstone: boolean
37
+ }
38
+
39
+ interface SerializedRGA {
40
+ nodes: SerializedRGANode[]
41
+ }
42
+
43
+ interface SerializedRGATreeRoot {
44
+ type: 'root'
45
+ children: SerializedRGA
46
+ }
47
+
48
+ interface SerializedRGAChangeSet {
49
+ event: string
50
+ changes: SerializedRGAChange[]
51
+ }
52
+
53
+ interface SerializedRGAChange {
54
+ type: 'insert' | 'delete' | 'modify'
55
+ parentPath: Array<{ uuid: string; event: string }>
56
+ targetId?: { uuid: string; event: string } | null
57
+ afterId?: { uuid: string; event: string } | null
58
+ nodes?: unknown[]
59
+ before?: unknown[]
60
+ }
61
+
62
+ // ---- Helpers ----
63
+
64
+ function serializeNodeId<E extends RGAEvent>(id: RGANodeId<E>): { uuid: string; event: string } {
65
+ return { uuid: id.uuid, event: id.event.toString() }
66
+ }
67
+
68
+ function deserializeNodeId<E extends RGAEvent>(
69
+ raw: { uuid: string; event: string },
70
+ parseEvent: (s: string) => E,
71
+ ): RGANodeId<E> {
72
+ return { uuid: raw.uuid, event: parseEvent(raw.event) }
73
+ }
74
+
75
+ function isRGAParentSerialized(node: unknown): node is { type: string; children: SerializedRGA } {
76
+ return (
77
+ node != null &&
78
+ typeof node === 'object' &&
79
+ 'children' in node &&
80
+ typeof (node as Record<string, unknown>).children === 'object' &&
81
+ (node as Record<string, unknown>).children !== null &&
82
+ 'nodes' in ((node as Record<string, unknown>).children as Record<string, unknown>)
83
+ )
84
+ }
85
+
86
+ function isRGAParentNode<E extends RGAEvent>(node: RGATreeNode<E>): node is RGAParentNode<E> {
87
+ return 'children' in node && node.children instanceof RGA
88
+ }
89
+
90
+ // ---- RGATree serialization ----
91
+
92
+ function serializeRGA<E extends RGAEvent>(rga: RGA<RGATreeNode<E>, E>): SerializedRGA {
93
+ const nodes: SerializedRGANode[] = []
94
+ for (const node of rga.nodes.values()) {
95
+ nodes.push({
96
+ id: serializeNodeId(node.id),
97
+ value: serializeTreeNodeValue(node.value),
98
+ afterId: node.afterId ? serializeNodeId(node.afterId) : null,
99
+ tombstone: node.tombstone,
100
+ })
101
+ }
102
+ return { nodes }
103
+ }
104
+
105
+ function serializeTreeNodeValue<E extends RGAEvent>(node: RGATreeNode<E>): unknown {
106
+ if (isRGAParentNode(node)) {
107
+ const { children, ...rest } = node
108
+ return { ...rest, children: serializeRGA(children) }
109
+ }
110
+ return node
111
+ }
112
+
113
+ function serializeTree<E extends RGAEvent>(root: RGATreeRoot<E>): SerializedRGATreeRoot {
114
+ return {
115
+ type: 'root',
116
+ children: serializeRGA(root.children),
117
+ }
118
+ }
119
+
120
+ function deserializeRGA<E extends RGAEvent>(
121
+ raw: SerializedRGA,
122
+ parseEvent: (s: string) => E,
123
+ fingerprintFn: (value: RGATreeNode<E>) => string,
124
+ compareEvents: EventComparator<E>,
125
+ ): RGA<RGATreeNode<E>, E> {
126
+ const rga = new RGA<RGATreeNode<E>, E>(fingerprintFn, compareEvents)
127
+ for (const rawNode of raw.nodes) {
128
+ const id = deserializeNodeId(rawNode.id, parseEvent)
129
+ const afterId = rawNode.afterId ? deserializeNodeId(rawNode.afterId, parseEvent) : undefined
130
+ const value = deserializeTreeNodeValue(rawNode.value, parseEvent, fingerprintFn, compareEvents)
131
+ const key = `${id.uuid}:${id.event.toString()}`
132
+ rga.nodes.set(key, { id, value, afterId, tombstone: rawNode.tombstone })
133
+ }
134
+ return rga
135
+ }
136
+
137
+ function deserializeTreeNodeValue<E extends RGAEvent>(
138
+ raw: unknown,
139
+ parseEvent: (s: string) => E,
140
+ fingerprintFn: (value: RGATreeNode<E>) => string,
141
+ compareEvents: EventComparator<E>,
142
+ ): RGATreeNode<E> {
143
+ if (isRGAParentSerialized(raw)) {
144
+ const { children, ...rest } = raw
145
+ return {
146
+ ...rest,
147
+ children: deserializeRGA(children, parseEvent, fingerprintFn, compareEvents),
148
+ } as RGAParentNode<E>
149
+ }
150
+ return raw as RGATreeNode<E>
151
+ }
152
+
153
+ function deserializeTree<E extends RGAEvent>(
154
+ raw: SerializedRGATreeRoot,
155
+ parseEvent: (s: string) => E,
156
+ fingerprintFn: (value: RGATreeNode<E>) => string,
157
+ compareEvents: EventComparator<E>,
158
+ ): RGATreeRoot<E> {
159
+ return {
160
+ type: 'root',
161
+ children: deserializeRGA(raw.children, parseEvent, fingerprintFn, compareEvents),
162
+ }
163
+ }
164
+
165
+ // ---- RGAChangeSet serialization ----
166
+
167
+ function serializeChangeSet<E extends RGAEvent>(cs: RGAChangeSet<E>): SerializedRGAChangeSet {
168
+ return {
169
+ event: cs.event.toString(),
170
+ changes: cs.changes.map(c => ({
171
+ type: c.type,
172
+ parentPath: c.parentPath.map(serializeNodeId),
173
+ targetId: c.targetId ? serializeNodeId(c.targetId) : null,
174
+ afterId: c.afterId ? serializeNodeId(c.afterId) : null,
175
+ nodes: c.nodes,
176
+ before: c.before,
177
+ })),
178
+ }
179
+ }
180
+
181
+ function deserializeChangeSet<E extends RGAEvent>(
182
+ raw: SerializedRGAChangeSet,
183
+ parseEvent: (s: string) => E,
184
+ ): RGAChangeSet<E> {
185
+ return {
186
+ event: parseEvent(raw.event),
187
+ changes: raw.changes.map(c => {
188
+ const change: RGAChange<E> = {
189
+ type: c.type,
190
+ parentPath: c.parentPath.map(id => deserializeNodeId(id, parseEvent)),
191
+ }
192
+ if (c.targetId) change.targetId = deserializeNodeId(c.targetId, parseEvent)
193
+ if (c.afterId) change.afterId = deserializeNodeId(c.afterId, parseEvent)
194
+ if (c.nodes) change.nodes = c.nodes as any
195
+ if (c.before) change.before = c.before as any
196
+ return change
197
+ }),
198
+ }
199
+ }
200
+
201
+ // ---- Public API: encode/decode to DAG-CBOR blocks ----
202
+
203
+ /**
204
+ * Encode an RGATree as a DAG-CBOR block.
205
+ */
206
+ export async function encodeTree<E extends RGAEvent>(
207
+ root: RGATreeRoot<E>,
208
+ ) {
209
+ const value = stripUndefined(serializeTree(root)) as SerializedRGATreeRoot
210
+ return encode({ value, codec: cbor, hasher: sha256 })
211
+ }
212
+
213
+ /**
214
+ * Decode an RGATree from a DAG-CBOR block.
215
+ */
216
+ export async function decodeTree<E extends RGAEvent>(
217
+ block: { bytes: Uint8Array },
218
+ parseEvent: (s: string) => E,
219
+ fingerprintFn: (value: RGATreeNode<E>) => string,
220
+ compareEvents: EventComparator<E>,
221
+ ): Promise<RGATreeRoot<E>> {
222
+ const decoded = await decode({ bytes: block.bytes, codec: cbor, hasher: sha256 })
223
+ return deserializeTree(decoded.value as SerializedRGATreeRoot, parseEvent, fingerprintFn, compareEvents)
224
+ }
225
+
226
+ /**
227
+ * Encode an RGAChangeSet as a DAG-CBOR block.
228
+ */
229
+ export async function encodeChangeSet<E extends RGAEvent>(
230
+ cs: RGAChangeSet<E>,
231
+ ) {
232
+ const value = stripUndefined(serializeChangeSet(cs)) as SerializedRGAChangeSet
233
+ return encode({ value, codec: cbor, hasher: sha256 })
234
+ }
235
+
236
+ /**
237
+ * Decode an RGAChangeSet from a DAG-CBOR block.
238
+ */
239
+ export async function decodeChangeSet<E extends RGAEvent>(
240
+ block: { bytes: Uint8Array },
241
+ parseEvent: (s: string) => E,
242
+ ): Promise<RGAChangeSet<E>> {
243
+ const decoded = await decode({ bytes: block.bytes, codec: cbor, hasher: sha256 })
244
+ return deserializeChangeSet(decoded.value as SerializedRGAChangeSet, parseEvent)
245
+ }