@sovereignbase/convergent-replicated-list 0.0.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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,326 @@
1
+ [![npm version](https://img.shields.io/npm/v/@sovereignbase/convergent-replicated-list)](https://www.npmjs.com/package/@sovereignbase/convergent-replicated-list)
2
+ [![CI](https://github.com/sovereignbase/convergent-replicated-list/actions/workflows/ci.yaml/badge.svg?branch=master)](https://github.com/sovereignbase/convergent-replicated-list/actions/workflows/ci.yaml)
3
+ [![codecov](https://codecov.io/gh/sovereignbase/convergent-replicated-list/branch/master/graph/badge.svg)](https://codecov.io/gh/sovereignbase/convergent-replicated-list)
4
+ [![license](https://img.shields.io/npm/l/@sovereignbase/convergent-replicated-list)](LICENSE)
5
+
6
+ # convergent-replicated-list
7
+
8
+ Convergent Replicated List (CR-List), a delta CRDT for an ordered sequence of entries.
9
+
10
+ ## Compatibility
11
+
12
+ - Runtimes: Node >= 20, modern browsers, Bun, Deno, Cloudflare Workers, Edge Runtime.
13
+ - Module format: ESM + CommonJS.
14
+ - Required globals / APIs: `EventTarget`, `CustomEvent`, `structuredClone`.
15
+ - TypeScript: bundled types.
16
+
17
+ ## Goals
18
+
19
+ - Deterministic convergence of the live list projection under asynchronous gossip delivery.
20
+ - Consistent behavior across Node, browsers, worker, and edge runtimes.
21
+ - Garbage collection possibility without breaking live-view convergence.
22
+ - Event-driven API
23
+
24
+ ## Installation
25
+
26
+ ```sh
27
+ npm install @sovereignbase/convergent-replicated-list
28
+ # or
29
+ pnpm add @sovereignbase/convergent-replicated-list
30
+ # or
31
+ yarn add @sovereignbase/convergent-replicated-list
32
+ # or
33
+ bun add @sovereignbase/convergent-replicated-list
34
+ # or
35
+ deno add jsr:@sovereignbase/convergent-replicated-list
36
+ # or
37
+ vlt install jsr:@sovereignbase/convergent-replicated-list
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ ### Copy-paste example
43
+
44
+ ```ts
45
+ import { CRList } from '@sovereignbase/convergent-replicated-list'
46
+
47
+ const alice = new CRList<string>()
48
+ const bob = new CRList<string>()
49
+
50
+ alice.addEventListener('delta', (event) => {
51
+ bob.merge(event.detail)
52
+ })
53
+
54
+ alice.append('hello')
55
+ alice.append('world')
56
+ alice.prepend('first')
57
+
58
+ console.log([...alice]) // ['first', 'hello', 'world']
59
+ console.log([...bob]) // ['first', 'hello', 'world']
60
+ console.log(alice[1]) // 'hello'
61
+ ```
62
+
63
+ ### Hydrating from a snapshot
64
+
65
+ ```ts
66
+ import {
67
+ CRList,
68
+ type CRListSnapshot,
69
+ } from '@sovereignbase/convergent-replicated-list'
70
+
71
+ const source = new CRList<string>()
72
+ let snapshot!: CRListSnapshot<string>
73
+
74
+ source.addEventListener(
75
+ 'snapshot',
76
+ (event) => {
77
+ snapshot = event.detail
78
+ },
79
+ { once: true }
80
+ )
81
+
82
+ source.append('draft')
83
+ source.append('ready')
84
+ source.snapshot()
85
+
86
+ const restored = new CRList<string>(snapshot)
87
+
88
+ console.log([...restored]) // ['draft', 'ready']
89
+ ```
90
+
91
+ ### Event channels
92
+
93
+ ```ts
94
+ import { CRList } from '@sovereignbase/convergent-replicated-list'
95
+
96
+ const list = new CRList<string>()
97
+
98
+ list.addEventListener('delta', (event) => {
99
+ console.log('delta', event.detail)
100
+ })
101
+
102
+ list.addEventListener('change', (event) => {
103
+ console.log('change', event.detail)
104
+ })
105
+
106
+ list.addEventListener('snapshot', (event) => {
107
+ console.log('snapshot', event.detail)
108
+ })
109
+
110
+ list.addEventListener('ack', (event) => {
111
+ console.log('ack', event.detail)
112
+ })
113
+
114
+ list.append('a')
115
+ list[0] = 'b'
116
+ delete list[0]
117
+ ```
118
+
119
+ ### Iteration and JSON serialization
120
+
121
+ ```ts
122
+ import { CRList } from '@sovereignbase/convergent-replicated-list'
123
+
124
+ const list = new CRList<string>()
125
+
126
+ list[0] = 'up'
127
+ list.append('dude!')
128
+ list.prepend('What is')
129
+
130
+ const serialized = JSON.stringify(list)
131
+ const restored = new CRList<string>(JSON.parse(serialized))
132
+
133
+ for (const value of list) {
134
+ console.log(value)
135
+ }
136
+
137
+ for (const index in list) {
138
+ console.log(index)
139
+ }
140
+
141
+ list.forEach((value, index, target) => {
142
+ console.log(index, value, target.size)
143
+ })
144
+
145
+ console.log([...restored]) // ['What is', 'up', 'dude!']
146
+ ```
147
+
148
+ ### Acknowledgements and garbage collection
149
+
150
+ ```ts
151
+ import { CRList } from '@sovereignbase/convergent-replicated-list'
152
+
153
+ const alice = new CRList<string>()
154
+ const bob = new CRList<string>()
155
+ const frontiers = new Map<string, string>()
156
+
157
+ alice.addEventListener('delta', (event) => bob.merge(event.detail))
158
+ bob.addEventListener('delta', (event) => alice.merge(event.detail))
159
+
160
+ alice.addEventListener('ack', (event) => {
161
+ frontiers.set('alice', event.detail)
162
+ })
163
+
164
+ bob.addEventListener('ack', (event) => {
165
+ frontiers.set('bob', event.detail)
166
+ })
167
+
168
+ alice.append('x')
169
+ alice[0] = 'y'
170
+ delete alice[0]
171
+
172
+ alice.acknowledge()
173
+ bob.acknowledge()
174
+
175
+ alice.garbageCollect([...frontiers.values()])
176
+ bob.garbageCollect([...frontiers.values()])
177
+ ```
178
+
179
+ ### Advanced exports
180
+
181
+ If you need to build your own ordered-sequence CRDT binding instead of using the
182
+ high-level `CRList` class, the package also exports the core CRUD and MAGS
183
+ functions together with the replica and payload types.
184
+
185
+ Those low-level exports let you build custom list abstractions, protocol
186
+ wrappers, or framework-specific bindings while preserving the same convergence
187
+ rules as the default `CRList` binding.
188
+
189
+ ```ts
190
+ import {
191
+ __create,
192
+ __update,
193
+ __merge,
194
+ __snapshot,
195
+ type CRListDelta,
196
+ type CRListSnapshot,
197
+ } from '@sovereignbase/convergent-replicated-list'
198
+
199
+ const replica = __create<string>()
200
+ const local = __update(0, ['hello', 'world'], replica, 'after')
201
+
202
+ if (local) {
203
+ const outgoing: CRListDelta<string> = local.delta
204
+ const remoteChange = __merge(replica, outgoing)
205
+
206
+ console.log(remoteChange)
207
+ }
208
+
209
+ const snapshot: CRListSnapshot<string> = __snapshot(replica)
210
+ console.log(snapshot)
211
+ ```
212
+
213
+ The intended split is:
214
+
215
+ - `__create`, `__read`, `__update`, `__delete` for local replica mutations.
216
+ - `__merge`, `__acknowledge`, `__garbageCollect`, `__snapshot` for gossip,
217
+ compaction, and serialization.
218
+ - `CRList` when you want the default event-driven class API.
219
+
220
+ ## Runtime behavior
221
+
222
+ ### Validation and errors
223
+
224
+ Low-level exports can throw `CRListError` with stable error codes:
225
+
226
+ - `VALUE_NOT_CLONEABLE`
227
+ - `INDEX_OUT_OF_BOUNDS`
228
+ - `LIST_EMPTY`
229
+ - `LIST_INTEGRITY_VIOLATION`
230
+ - `UPDATE_EXPECTED_AN_ARRAY`
231
+
232
+ Ingress stays tolerant:
233
+
234
+ - malformed top-level merge payloads are ignored
235
+ - malformed snapshot values are dropped during hydration
236
+ - invalid UUIDs are ignored
237
+ - duplicate insert and delete deltas are idempotent
238
+ - stale or malicious deltas do not break convergence of the live view
239
+
240
+ ### Safety and copying semantics
241
+
242
+ - Snapshots are serializable full-state payloads.
243
+ - Deltas are serializable gossip payloads.
244
+ - `change` is a minimal index-keyed local patch.
245
+ - `toJSON()` returns a detached serializable snapshot.
246
+ - `for...of`, `forEach()`, numeric indexing, `append()`, `prepend()`, `remove()`, `merge()`, `snapshot()`, `acknowledge()`, and `garbageCollect()` all operate on the live list projection.
247
+
248
+ ### Convergence and compaction
249
+
250
+ - The convergence target is the live list projection, not internal cursor placement.
251
+ - Stable `predecessor` anchors determine deterministic ordering together with UUIDv7 sorting when placement cannot be resolved from a live predecessor chain.
252
+ - Tombstones remain until acknowledgement frontiers make them safe to collect.
253
+ - Garbage collection does not change the converged live projection for replicas that later catch up from delta or snapshot state.
254
+
255
+ ## Tests
256
+
257
+ ```sh
258
+ npm run test
259
+ ```
260
+
261
+ What the current test suite covers:
262
+
263
+ - Coverage on built `dist/**/*.js`: `100%` statements, `99.67%` branches, `100%` functions, and `100%` lines, together with focused source-coverage tests for helper edge paths.
264
+ - Public `CRList` surface: indexing, iteration, `forEach`, proxy traps, events, JSON/inspect behavior.
265
+ - Core edge paths and malicious ingress handling for `__create`, `__read`, `__update`, `__delete`, `__merge`, `__snapshot`, `__acknowledge`, and `__garbageCollect`.
266
+ - Internal defensive branches under intentionally corrupt in-memory replica state.
267
+ - Integration convergence stress for:
268
+ - local CRUD live-view semantics
269
+ - snapshot hydration independent of value order
270
+ - merge idempotency for duplicate insert/delete deltas
271
+ - stale-peer acknowledgement and garbage collection recovery
272
+ - shuffled asynchronous gossip delivery
273
+ - shuffled delivery with replica restarts
274
+ - concurrent insert after concurrently deleted predecessor
275
+ - `100` aggressive deterministic convergence scenarios
276
+ - End-to-end runtime matrix for:
277
+ - Node ESM
278
+ - Node CJS
279
+ - Bun ESM
280
+ - Bun CJS
281
+ - Deno ESM
282
+ - Cloudflare Workers ESM
283
+ - Edge Runtime ESM
284
+ - Browsers via Playwright: Chromium, Firefox, WebKit, mobile Chrome, mobile Safari
285
+
286
+ ## Benchmarks
287
+
288
+ ```sh
289
+ npm run bench
290
+ ```
291
+
292
+ The benchmark runner currently uses:
293
+
294
+ - `LIST_SIZE = 5_000`
295
+ - `RUN_TIMES = 250`
296
+ - output columns: `group`, `scenario`, `n`, `ops`, `ms`, `ms/op`, `ops/sec`
297
+
298
+ Last measured on Node `v22.14.0` (`win32 x64`):
299
+
300
+ | group | scenario | n | ops | ms | ms/op | ops/sec |
301
+ | ------- | ------------------------------------- | ----: | --: | -------: | ----: | ---------: |
302
+ | `crud` | `create / hydrate snapshot` | 5,000 | 250 | 8,817.80 | 35.27 | 28.35 |
303
+ | `crud` | `read / random indexed reads` | 5,000 | 250 | 12.59 | 0.05 | 19,854.03 |
304
+ | `crud` | `update / append after tail` | 5,000 | 250 | 2.26 | 0.01 | 110,507.01 |
305
+ | `crud` | `update / insert before middle` | 5,000 | 250 | 22.27 | 0.09 | 11,224.10 |
306
+ | `crud` | `update / overwrite random` | 5,000 | 250 | 13.95 | 0.06 | 17,919.61 |
307
+ | `crud` | `delete / single deletes from middle` | 5,000 | 250 | 23.21 | 0.09 | 10,772.98 |
308
+ | `crud` | `delete / range deletes` | 5,000 | 250 | 6.32 | 0.03 | 39,562.60 |
309
+ | `mags` | `snapshot` | 5,000 | 250 | 5,354.28 | 21.42 | 46.69 |
310
+ | `mags` | `acknowledge` | 5,000 | 250 | 47.24 | 0.19 | 5,291.76 |
311
+ | `mags` | `garbage collect` | 5,000 | 250 | 163.55 | 0.65 | 1,528.59 |
312
+ | `mags` | `merge ordered deltas` | 5,000 | 250 | 19.25 | 0.08 | 12,986.74 |
313
+ | `mags` | `merge shuffled gossip` | 5,000 | 250 | 485.99 | 1.94 | 514.41 |
314
+ | `class` | `constructor / hydrate snapshot` | 5,000 | 250 | 8,119.67 | 32.48 | 30.79 |
315
+ | `class` | `append after tail` | 5,000 | 250 | 2.87 | 0.01 | 87,232.63 |
316
+ | `class` | `prepend before middle` | 5,000 | 250 | 7.76 | 0.03 | 32,228.95 |
317
+ | `class` | `remove from middle` | 5,000 | 250 | 5.20 | 0.02 | 48,084.32 |
318
+ | `class` | `snapshot` | 5,000 | 250 | 5,842.47 | 23.37 | 42.79 |
319
+ | `class` | `acknowledge` | 5,000 | 250 | 127.77 | 0.51 | 1,956.68 |
320
+ | `class` | `garbage collect` | 5,000 | 250 | 323.20 | 1.29 | 773.51 |
321
+ | `class` | `merge ordered deltas` | 5,000 | 250 | 8.61 | 0.03 | 29,021.17 |
322
+ | `class` | `merge shuffled gossip` | 5,000 | 250 | 523.53 | 2.09 | 477.53 |
323
+
324
+ ## License
325
+
326
+ Apache-2.0