@loro-dev/roost 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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +397 -0
  3. package/dist/codec.d.ts +66 -0
  4. package/dist/codec.js +275 -0
  5. package/dist/crypto.d.ts +21 -0
  6. package/dist/crypto.js +103 -0
  7. package/dist/durable-framing.d.ts +44 -0
  8. package/dist/durable-framing.js +207 -0
  9. package/dist/framing.d.ts +28 -0
  10. package/dist/framing.js +144 -0
  11. package/dist/history-publication.d.ts +58 -0
  12. package/dist/history-publication.js +234 -0
  13. package/dist/identity.d.ts +14 -0
  14. package/dist/identity.js +62 -0
  15. package/dist/inbox.d.ts +69 -0
  16. package/dist/inbox.js +262 -0
  17. package/dist/index.d.ts +9 -0
  18. package/dist/index.js +6 -0
  19. package/dist/indexeddb.d.ts +38 -0
  20. package/dist/indexeddb.js +299 -0
  21. package/dist/json.d.ts +23 -0
  22. package/dist/json.js +221 -0
  23. package/dist/lody-history.d.ts +397 -0
  24. package/dist/lody-history.js +1559 -0
  25. package/dist/projection.d.ts +53 -0
  26. package/dist/projection.js +543 -0
  27. package/dist/replay.d.ts +63 -0
  28. package/dist/replay.js +201 -0
  29. package/dist/sender.d.ts +26 -0
  30. package/dist/sender.js +67 -0
  31. package/dist/store.d.ts +384 -0
  32. package/dist/store.js +1437 -0
  33. package/dist/sync/coverage.d.ts +276 -0
  34. package/dist/sync/coverage.js +1084 -0
  35. package/dist/sync/crypto.d.ts +64 -0
  36. package/dist/sync/crypto.js +155 -0
  37. package/dist/sync/execute.d.ts +142 -0
  38. package/dist/sync/execute.js +321 -0
  39. package/dist/sync/history.d.ts +214 -0
  40. package/dist/sync/history.js +786 -0
  41. package/dist/sync/index.d.ts +17 -0
  42. package/dist/sync/index.js +9 -0
  43. package/dist/sync/link.d.ts +192 -0
  44. package/dist/sync/link.js +663 -0
  45. package/dist/sync/mod.d.ts +24 -0
  46. package/dist/sync/mod.js +15 -0
  47. package/dist/sync/policy.d.ts +62 -0
  48. package/dist/sync/policy.js +128 -0
  49. package/dist/sync/registry.d.ts +129 -0
  50. package/dist/sync/registry.js +333 -0
  51. package/dist/sync/transport.d.ts +91 -0
  52. package/dist/sync/transport.js +162 -0
  53. package/dist/sync/work.d.ts +351 -0
  54. package/dist/sync/work.js +1344 -0
  55. package/package.json +47 -0
@@ -0,0 +1,53 @@
1
+ import { type ContentOp, type ValuePath } from './codec.js';
2
+ import { type JsonValue } from './json.js';
3
+ import type { KvTransaction, Step } from './indexeddb.js';
4
+ export type Link = Readonly<{
5
+ id: bigint;
6
+ bytes: number;
7
+ depth: number;
8
+ }>;
9
+ export type Layout = Readonly<{
10
+ root: Link;
11
+ next: bigint;
12
+ }>;
13
+ export declare class ProjectionError extends Error {
14
+ name: string;
15
+ }
16
+ export declare class ProjectionCorruptionError extends Error {
17
+ name: string;
18
+ }
19
+ type Tx = Pick<KvTransaction, 'get' | 'put' | 'delete' | 'scan'>;
20
+ export declare function encodeLayout(layout: Layout): Uint8Array;
21
+ export declare function decodeLayout(bytes: Uint8Array): Layout;
22
+ /** Private chunked projection. Build/edit stage changes; callers flush only after all Turn checks. */
23
+ export declare class Projection {
24
+ private readonly tx;
25
+ private readonly space;
26
+ private next;
27
+ private readonly turn;
28
+ private readonly changes;
29
+ private failed;
30
+ constructor(tx: Tx, space: string, turnId: Uint8Array, layout?: Layout);
31
+ private key;
32
+ private stage;
33
+ private get;
34
+ private child;
35
+ private node;
36
+ private putNode;
37
+ private page;
38
+ private putPage;
39
+ private allocate;
40
+ layout(root: Link): Layout;
41
+ flush(): Step<void>;
42
+ build(value: JsonValue): Step<Link>;
43
+ private buildInner;
44
+ private writeBlocks;
45
+ resolve(root: Link, path: ValuePath): Step<Link>;
46
+ read(root: Link): Step<JsonValue>;
47
+ readText(root: Link, path: ValuePath, start: bigint, end: bigint): Step<string>;
48
+ private readTextLink;
49
+ private deleteTree;
50
+ edit(root: Link, op: ContentOp): Step<Link>;
51
+ private editAt;
52
+ }
53
+ export {};
@@ -0,0 +1,543 @@
1
+ import { MAX_FRAME } from './codec.js';
2
+ import { assertScalars, compareScalarKeys, decodeJson, decodeUtf8, encodeJson, encodeUtf8, MAX_JSON_DEPTH, U64_MAX } from './json.js';
3
+ export class ProjectionError extends Error {
4
+ name = 'ProjectionError';
5
+ }
6
+ export class ProjectionCorruptionError extends Error {
7
+ name = 'ProjectionCorruptionError';
8
+ }
9
+ const BLOCK = 1024, PAGE = 128;
10
+ const corrupt = (message) => { throw new ProjectionCorruptionError(message); };
11
+ const invalid = (message) => { throw new ProjectionError(message); };
12
+ const uint = (n, max = MAX_FRAME) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0 && n <= max ? n : corrupt('invalid projection integer');
13
+ function id(n) {
14
+ if (typeof n !== 'string' || !/^(0|[1-9][0-9]{0,19})$/.test(n))
15
+ return corrupt('invalid projection id');
16
+ const value = BigInt(n);
17
+ return value <= U64_MAX ? value : corrupt('projection id overflow');
18
+ }
19
+ const packLink = (link) => [link.id.toString(), link.bytes, link.depth];
20
+ function unpackLink(value) {
21
+ if (!Array.isArray(value) || value.length !== 3)
22
+ return corrupt('invalid projection link');
23
+ const link = { id: id(value[0]), bytes: uint(value[1]), depth: uint(value[2], MAX_JSON_DEPTH) };
24
+ if (link.bytes < 1)
25
+ return corrupt('invalid projection byte summary');
26
+ return link;
27
+ }
28
+ function checkedLayout(layout) {
29
+ if (!layout || typeof layout.next !== 'bigint' || layout.next < 1n || layout.next > U64_MAX || !layout.root || typeof layout.root.id !== 'bigint')
30
+ return corrupt('invalid projection layout');
31
+ const root = unpackLink(packLink(layout.root));
32
+ if (root.id >= layout.next)
33
+ return corrupt('projection root outside allocation');
34
+ return { root, next: layout.next };
35
+ }
36
+ const serialize = (value) => encodeUtf8(JSON.stringify(value));
37
+ function parse(bytes) {
38
+ try {
39
+ return JSON.parse(decodeUtf8(bytes));
40
+ }
41
+ catch {
42
+ return corrupt('invalid projection metadata');
43
+ }
44
+ }
45
+ export function encodeLayout(layout) {
46
+ const value = checkedLayout(layout);
47
+ return serialize([1, packLink(value.root), value.next.toString()]);
48
+ }
49
+ export function decodeLayout(bytes) {
50
+ const v = parse(bytes);
51
+ if (!Array.isArray(v) || v.length !== 3 || v[0] !== 1)
52
+ return corrupt('unsupported projection layout');
53
+ return checkedLayout({ root: unpackLink(v[1]), next: id(v[2]) });
54
+ }
55
+ function jsonBytes(value) {
56
+ try {
57
+ return encodeJson(value);
58
+ }
59
+ catch (error) {
60
+ return invalid(error instanceof Error ? error.message : 'invalid JSON');
61
+ }
62
+ }
63
+ const size = (text) => jsonBytes(text).length;
64
+ function scalarCount(text) { let count = 0; for (const _ of text)
65
+ count++; return count; }
66
+ function budget(link) {
67
+ if (!Number.isSafeInteger(link.bytes) || link.bytes > MAX_FRAME || link.bytes < 1)
68
+ return invalid('JSON payload too large');
69
+ if (link.depth > MAX_JSON_DEPTH)
70
+ return invalid('json too deep');
71
+ return link;
72
+ }
73
+ function index(value, len) {
74
+ if (typeof value !== 'bigint' || value < 0n || value > BigInt(len))
75
+ return invalid('range out of bounds');
76
+ return Number(value);
77
+ }
78
+ function depth(depths) { return 1 + Math.max(0, ...depths.keys()); }
79
+ function add(depths, d) { depths.set(d, (depths.get(d) ?? 0) + 1); }
80
+ function remove(depths, d) {
81
+ const n = depths.get(d);
82
+ if (!n)
83
+ return corrupt('projection depth count');
84
+ if (n === 1)
85
+ depths.delete(d);
86
+ else
87
+ depths.set(d, n - 1);
88
+ }
89
+ function summarize(link, refs) {
90
+ let bytes = 2 + Math.max(0, refs.size - 1), depth = 1;
91
+ for (const [key, child] of refs) {
92
+ bytes += size(key) + 1 + child.bytes;
93
+ depth = Math.max(depth, child.depth + 1);
94
+ }
95
+ return { id: link.id, bytes, depth };
96
+ }
97
+ const keyString = (key) => [...key].map(v => v.toString(16).padStart(2, '0')).join('');
98
+ /** Private chunked projection. Build/edit stage changes; callers flush only after all Turn checks. */
99
+ export class Projection {
100
+ tx;
101
+ space;
102
+ next;
103
+ turn;
104
+ changes = new Map();
105
+ failed = false;
106
+ constructor(tx, space, turnId, layout) {
107
+ this.tx = tx;
108
+ this.space = space;
109
+ if (!(turnId instanceof Uint8Array) || turnId.length !== 16)
110
+ throw new ProjectionError('Turn id must have 16 bytes');
111
+ this.turn = new Uint8Array(turnId);
112
+ this.next = layout ? checkedLayout(layout).next : 0n;
113
+ }
114
+ key(id, part) {
115
+ const key = new Uint8Array(part === undefined ? 24 : 32);
116
+ key.set(this.turn);
117
+ const view = new DataView(key.buffer);
118
+ view.setBigUint64(16, id);
119
+ if (part !== undefined)
120
+ view.setBigUint64(24, BigInt(part));
121
+ return key;
122
+ }
123
+ stage(key, value) { this.changes.set(keyString(key), { key, value }); }
124
+ *get(key) {
125
+ const staged = this.changes.get(keyString(key));
126
+ const result = staged ? staged.value : yield* this.tx.get(this.space, key);
127
+ return result ?? corrupt('missing projection block');
128
+ }
129
+ child(value, parent) {
130
+ const link = unpackLink(value);
131
+ if (link.id <= parent.id || link.id >= this.next)
132
+ return corrupt('invalid child allocation');
133
+ return link;
134
+ }
135
+ *node(link) {
136
+ if (link.id < 0n || link.id >= this.next)
137
+ return corrupt('invalid node allocation');
138
+ const v = parse(yield* this.get(this.key(link.id)));
139
+ if (!Array.isArray(v) || v.length < 5 || v[0] !== 1 || v[1] !== link.bytes || v[2] !== link.depth)
140
+ return corrupt('invalid node summary');
141
+ if (v[3] === 'text' && v.length === 5) {
142
+ const len = uint(v[4]);
143
+ if (link.depth !== 0 || link.bytes < len + 2 || link.bytes > len * 6 + 2)
144
+ return corrupt('invalid text summary');
145
+ return { kind: 'text', len };
146
+ }
147
+ if (v[3] === 'atom' && v.length === 5 && typeof v[4] === 'string') {
148
+ let value;
149
+ try {
150
+ value = decodeJson(encodeUtf8(v[4]));
151
+ }
152
+ catch {
153
+ return corrupt('invalid projection atom');
154
+ }
155
+ if (typeof value === 'string' || Array.isArray(value) || value instanceof Map || link.depth !== 0 || encodeUtf8(v[4]).length !== link.bytes)
156
+ return corrupt('invalid atom summary');
157
+ return { kind: 'atom', value };
158
+ }
159
+ if (v[3] === 'object' && v.length === 5 && Array.isArray(v[4])) {
160
+ const refs = new Map();
161
+ let prev;
162
+ for (const entry of v[4]) {
163
+ if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string')
164
+ return corrupt('invalid object reference');
165
+ try {
166
+ assertScalars(entry[0]);
167
+ }
168
+ catch {
169
+ return corrupt('invalid object key');
170
+ }
171
+ if (prev !== undefined && compareScalarKeys(prev, entry[0]) >= 0)
172
+ return corrupt('unordered object keys');
173
+ prev = entry[0];
174
+ refs.set(entry[0], this.child(entry[1], link));
175
+ }
176
+ let summary;
177
+ try {
178
+ summary = summarize(link, refs);
179
+ }
180
+ catch (error) {
181
+ if (error instanceof ProjectionError)
182
+ return corrupt('invalid object key size');
183
+ throw error;
184
+ }
185
+ if (summary.bytes !== link.bytes || summary.depth !== link.depth)
186
+ return corrupt('invalid object summary');
187
+ return { kind: 'object', refs };
188
+ }
189
+ if (v[3] === 'array' && v.length === 6 && Array.isArray(v[5])) {
190
+ const len = uint(v[4]), depths = new Map();
191
+ let total = 0, prev = -1;
192
+ for (const entry of v[5]) {
193
+ if (!Array.isArray(entry) || entry.length !== 2)
194
+ return corrupt('invalid array depths');
195
+ const d = uint(entry[0], MAX_JSON_DEPTH), count = uint(entry[1]);
196
+ if (d <= prev || count === 0)
197
+ return corrupt('invalid array depth frequency');
198
+ prev = d;
199
+ total += count;
200
+ depths.set(d, count);
201
+ }
202
+ if (total !== len || depth(depths) !== link.depth || link.bytes < 1 + Math.max(0, len - 1) + len)
203
+ return corrupt('invalid array summary');
204
+ return { kind: 'array', len, depths };
205
+ }
206
+ return corrupt('unsupported projection node');
207
+ }
208
+ putNode(link, node) {
209
+ const v = [1, link.bytes, link.depth, node.kind];
210
+ if (node.kind === 'atom')
211
+ v.push(decodeUtf8(jsonBytes(node.value)));
212
+ else if (node.kind === 'text')
213
+ v.push(node.len);
214
+ else if (node.kind === 'object')
215
+ v.push([...node.refs].sort(([a], [b]) => compareScalarKeys(a, b)).map(([k, c]) => [k, packLink(c)]));
216
+ else
217
+ v.push(node.len, [...node.depths].sort(([a], [b]) => a - b));
218
+ this.stage(this.key(link.id), serialize(v));
219
+ }
220
+ *page(link, page, len) {
221
+ const v = parse(yield* this.get(this.key(link.id, page)));
222
+ if (!Array.isArray(v) || v.length !== Math.min(PAGE, len - page * PAGE))
223
+ return corrupt('invalid array page length');
224
+ return v.map(c => this.child(c, link));
225
+ }
226
+ putPage(link, page, refs) { this.stage(this.key(link.id, page), serialize(refs.map(packLink))); }
227
+ allocate() {
228
+ if (this.next === U64_MAX)
229
+ return invalid('projection id overflow');
230
+ return { id: this.next++, bytes: 0, depth: 0 };
231
+ }
232
+ layout(root) { return checkedLayout({ root: { ...root }, next: this.next }); }
233
+ *flush() {
234
+ if (this.failed)
235
+ return invalid('failed projection cannot flush');
236
+ try {
237
+ for (const [, { key, value }] of [...this.changes].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
238
+ if (value === undefined)
239
+ yield* this.tx.delete(this.space, key);
240
+ else
241
+ yield* this.tx.put(this.space, key, value);
242
+ }
243
+ this.changes.clear();
244
+ }
245
+ catch (error) {
246
+ this.failed = true;
247
+ throw error;
248
+ }
249
+ }
250
+ *build(value) {
251
+ if (this.failed)
252
+ return invalid('failed projection');
253
+ try {
254
+ jsonBytes(value);
255
+ return budget(yield* this.buildInner(value));
256
+ }
257
+ catch (error) {
258
+ this.failed = true;
259
+ throw error;
260
+ }
261
+ }
262
+ *buildInner(value) {
263
+ let link = this.allocate();
264
+ let node;
265
+ if (typeof value === 'string') {
266
+ link = { ...link, bytes: size(value) };
267
+ this.writeBlocks(link, 0, value);
268
+ node = { kind: 'text', len: scalarCount(value) };
269
+ }
270
+ else if (value instanceof Map) {
271
+ const refs = new Map();
272
+ for (const [k, v] of [...value].sort(([a], [b]) => compareScalarKeys(a, b)))
273
+ refs.set(k, yield* this.buildInner(v));
274
+ link = summarize(link, refs);
275
+ node = { kind: 'object', refs };
276
+ }
277
+ else if (Array.isArray(value)) {
278
+ const depths = new Map();
279
+ let bytes = 2 + Math.max(0, value.length - 1);
280
+ for (let i = 0; i < value.length; i += PAGE) {
281
+ const refs = [];
282
+ for (const v of value.slice(i, i + PAGE)) {
283
+ const child = yield* this.buildInner(v);
284
+ refs.push(child);
285
+ bytes += child.bytes;
286
+ add(depths, child.depth);
287
+ }
288
+ this.putPage(link, i / PAGE, refs);
289
+ }
290
+ link = { ...link, bytes, depth: depth(depths) };
291
+ node = { kind: 'array', len: value.length, depths };
292
+ }
293
+ else {
294
+ link = { ...link, bytes: jsonBytes(value).length };
295
+ node = { kind: 'atom', value };
296
+ }
297
+ this.putNode(link, node);
298
+ return link;
299
+ }
300
+ writeBlocks(link, first, text) {
301
+ let block = '', len = 0;
302
+ for (const scalar of text) {
303
+ block += scalar;
304
+ if (++len === BLOCK) {
305
+ this.stage(this.key(link.id, first++), encodeUtf8(block));
306
+ block = '';
307
+ len = 0;
308
+ }
309
+ }
310
+ if (len)
311
+ this.stage(this.key(link.id, first), encodeUtf8(block));
312
+ }
313
+ *resolve(root, path) {
314
+ let link = root;
315
+ for (const segment of path) {
316
+ const node = yield* this.node(link);
317
+ if ('key' in segment && node.kind === 'object')
318
+ link = node.refs.get(segment.key) ?? invalid('path not found');
319
+ else if ('index' in segment && node.kind === 'array') {
320
+ const i = index(segment.index, node.len);
321
+ if (i === node.len)
322
+ return invalid('path not found');
323
+ link = (yield* this.page(link, Math.floor(i / PAGE), node.len))[i % PAGE];
324
+ }
325
+ else
326
+ return invalid('path not found');
327
+ }
328
+ return link;
329
+ }
330
+ *read(root) {
331
+ const node = yield* this.node(root);
332
+ if (node.kind === 'atom')
333
+ return node.value;
334
+ if (node.kind === 'text') {
335
+ const text = yield* this.readTextLink(root, node.len, 0, node.len);
336
+ let bytes;
337
+ try {
338
+ bytes = encodeJson(text).length;
339
+ }
340
+ catch {
341
+ return corrupt('invalid complete text size');
342
+ }
343
+ if (bytes !== root.bytes)
344
+ return corrupt('invalid complete text summary');
345
+ return text;
346
+ }
347
+ if (node.kind === 'object') {
348
+ const result = new Map();
349
+ for (const [key, child] of node.refs)
350
+ result.set(key, yield* this.read(child));
351
+ return result;
352
+ }
353
+ const result = [], depths = new Map();
354
+ let bytes = 2 + Math.max(0, node.len - 1);
355
+ for (let i = 0; i < Math.ceil(node.len / PAGE); i++)
356
+ for (const child of yield* this.page(root, i, node.len)) {
357
+ bytes += child.bytes;
358
+ add(depths, child.depth);
359
+ result.push(yield* this.read(child));
360
+ }
361
+ if (bytes !== root.bytes || depths.size !== node.depths.size || [...depths].some(([d, n]) => node.depths.get(d) !== n))
362
+ return corrupt('invalid complete array summary');
363
+ return result;
364
+ }
365
+ *readText(root, path, start, end) {
366
+ const link = yield* this.resolve(root, path), node = yield* this.node(link);
367
+ if (node.kind !== 'text')
368
+ return invalid('not text');
369
+ return yield* this.readTextLink(link, node.len, index(start, node.len), index(end, node.len));
370
+ }
371
+ *readTextLink(link, len, start, end) {
372
+ if (start > end)
373
+ return invalid('reversed range');
374
+ if (start === end)
375
+ return '';
376
+ const first = Math.floor(start / BLOCK), last = Math.floor((end - 1) / BLOCK);
377
+ let result = '';
378
+ const append = (block, value) => {
379
+ let text;
380
+ try {
381
+ text = decodeUtf8(value);
382
+ }
383
+ catch {
384
+ return corrupt('invalid projection UTF-8');
385
+ }
386
+ const scalars = [...text], offset = block * BLOCK;
387
+ if (scalars.length !== Math.min(BLOCK, len - offset))
388
+ corrupt('text block length');
389
+ result += scalars.slice(Math.max(0, start - offset), Math.min(BLOCK, end - offset)).join('');
390
+ };
391
+ if (this.changes.size === 0) {
392
+ let rows = yield* this.tx.scan(this.space, this.key(link.id, first), this.key(link.id, last + 1), last - first + 1);
393
+ if (rows.length !== last - first + 1)
394
+ return corrupt('missing text blocks');
395
+ for (let i = 0; i < rows.length; i++) {
396
+ const row = rows[i];
397
+ rows[i] = undefined;
398
+ if (!row)
399
+ return corrupt('missing text block');
400
+ const [key, value] = row;
401
+ if (keyString(key) !== keyString(this.key(link.id, first + i)))
402
+ return corrupt('text block order');
403
+ append(first + i, value);
404
+ }
405
+ }
406
+ else {
407
+ for (let block = first; block <= last; block++)
408
+ append(block, yield* this.get(this.key(link.id, block)));
409
+ }
410
+ return result;
411
+ }
412
+ *deleteTree(link) {
413
+ const node = yield* this.node(link);
414
+ if (node.kind === 'object')
415
+ for (const child of node.refs.values())
416
+ yield* this.deleteTree(child);
417
+ else if (node.kind === 'array')
418
+ for (let i = 0; i < Math.ceil(node.len / PAGE); i++) {
419
+ for (const child of yield* this.page(link, i, node.len))
420
+ yield* this.deleteTree(child);
421
+ this.stage(this.key(link.id, i));
422
+ }
423
+ else if (node.kind === 'text')
424
+ for (let i = 0; i < Math.ceil(node.len / BLOCK); i++)
425
+ this.stage(this.key(link.id, i));
426
+ this.stage(this.key(link.id));
427
+ }
428
+ *edit(root, op) {
429
+ if (this.failed)
430
+ return invalid('failed projection');
431
+ try {
432
+ if (op.kind === 'set')
433
+ jsonBytes(op.value);
434
+ if (op.kind === 'spliceArray')
435
+ jsonBytes(op.values);
436
+ if (op.kind === 'appendText' || op.kind === 'spliceText')
437
+ jsonBytes(op.text);
438
+ for (const segment of op.path)
439
+ if ('key' in segment)
440
+ jsonBytes(segment.key);
441
+ return budget(yield* this.editAt(root, op.path, op));
442
+ }
443
+ catch (error) {
444
+ this.failed = true;
445
+ throw error;
446
+ }
447
+ }
448
+ *editAt(link, path, op) {
449
+ if (path.length) {
450
+ const [segment, ...rest] = path, node = yield* this.node(link);
451
+ if (segment && 'key' in segment && node.kind === 'object') {
452
+ const old = node.refs.get(segment.key);
453
+ if (!rest.length && op.kind === 'remove') {
454
+ if (old) {
455
+ yield* this.deleteTree(old);
456
+ node.refs.delete(segment.key);
457
+ }
458
+ }
459
+ else if (!old && !rest.length && op.kind === 'set')
460
+ node.refs.set(segment.key, yield* this.buildInner(op.value));
461
+ else {
462
+ if (!old)
463
+ return invalid('path not found');
464
+ node.refs.set(segment.key, yield* this.editAt(old, rest, op));
465
+ }
466
+ link = summarize(link, node.refs);
467
+ }
468
+ else if (segment && 'index' in segment && node.kind === 'array') {
469
+ const i = index(segment.index, node.len);
470
+ if (i === node.len)
471
+ return invalid('path not found');
472
+ if (!rest.length && op.kind === 'remove')
473
+ return invalid('remove requires object field');
474
+ const refs = yield* this.page(link, Math.floor(i / PAGE), node.len), old = refs[i % PAGE];
475
+ const updated = yield* this.editAt(old, rest, op);
476
+ refs[i % PAGE] = updated;
477
+ remove(node.depths, old.depth);
478
+ add(node.depths, updated.depth);
479
+ link = { ...link, bytes: link.bytes - old.bytes + updated.bytes, depth: depth(node.depths) };
480
+ this.putPage(link, Math.floor(i / PAGE), refs);
481
+ }
482
+ else
483
+ return invalid('path not found');
484
+ this.putNode(link, node);
485
+ return link;
486
+ }
487
+ if (op.kind === 'set') {
488
+ yield* this.deleteTree(link);
489
+ return yield* this.buildInner(op.value);
490
+ }
491
+ if (op.kind === 'remove')
492
+ return invalid('remove requires object field');
493
+ const node = yield* this.node(link);
494
+ if (op.kind === 'appendText' || op.kind === 'spliceText') {
495
+ if (node.kind !== 'text')
496
+ return invalid('not text');
497
+ const i = op.kind === 'appendText' ? node.len : index(op.index, node.len);
498
+ const deleted = op.kind === 'appendText' ? 0 : index(op.delete, node.len - i);
499
+ if (!deleted && !op.text.length)
500
+ return link;
501
+ const first = Math.floor(i / BLOCK), start = first * BLOCK, inserted = scalarCount(op.text);
502
+ const affectedEnd = inserted === deleted ? Math.min(node.len, Math.ceil((i + deleted) / BLOCK) * BLOCK) : node.len;
503
+ const suffix = yield* this.readTextLink(link, node.len, start, affectedEnd), chars = [...suffix];
504
+ const replacement = chars.slice(0, i - start).join('') + op.text + chars.slice(i + deleted - start).join('');
505
+ link = { ...link, bytes: link.bytes - size(suffix) + size(replacement) };
506
+ const len = node.len - deleted + inserted;
507
+ this.writeBlocks(link, first, replacement);
508
+ for (let b = Math.ceil(len / BLOCK); b < Math.ceil(node.len / BLOCK); b++)
509
+ this.stage(this.key(link.id, b));
510
+ this.putNode(link, { kind: 'text', len });
511
+ return link;
512
+ }
513
+ if (node.kind !== 'array')
514
+ return invalid('not array');
515
+ const i = index(op.index, node.len), deleted = index(op.delete, node.len - i), first = Math.floor(i / PAGE);
516
+ const suffix = [];
517
+ for (let p = first; p < Math.ceil(node.len / PAGE); p++)
518
+ suffix.push(...yield* this.page(link, p, node.len));
519
+ let bytes = link.bytes;
520
+ for (const old of suffix.splice(i % PAGE, deleted)) {
521
+ bytes -= old.bytes;
522
+ remove(node.depths, old.depth);
523
+ yield* this.deleteTree(old);
524
+ }
525
+ const inserted = [];
526
+ for (const value of op.values) {
527
+ const child = yield* this.buildInner(value);
528
+ inserted.push(child);
529
+ bytes += child.bytes;
530
+ add(node.depths, child.depth);
531
+ }
532
+ // Avoid spreading arbitrarily large input through the JS argument stack.
533
+ const refs = suffix.slice(0, i % PAGE).concat(inserted, suffix.slice(i % PAGE));
534
+ const len = node.len - deleted + inserted.length;
535
+ link = { ...link, bytes: bytes - Math.max(0, node.len - 1) + Math.max(0, len - 1), depth: depth(node.depths) };
536
+ for (let p = 0; p < Math.ceil(refs.length / PAGE); p++)
537
+ this.putPage(link, first + p, refs.slice(p * PAGE, (p + 1) * PAGE));
538
+ for (let p = Math.ceil(len / PAGE); p < Math.ceil(node.len / PAGE); p++)
539
+ this.stage(this.key(link.id, p));
540
+ this.putNode(link, { kind: 'array', len, depths: node.depths });
541
+ return link;
542
+ }
543
+ }
@@ -0,0 +1,63 @@
1
+ import { Inbox } from './inbox.js';
2
+ import { Stream, type ImportReport } from './store.js';
3
+ export declare class ReplayError extends Error {
4
+ readonly code: 'invalid' | 'limit' | 'corrupt';
5
+ readonly name = "ReplayError";
6
+ constructor(code: 'invalid' | 'limit' | 'corrupt', message: string);
7
+ }
8
+ export interface ReplayLimits {
9
+ maxBatchBytes: number;
10
+ maxReportBytes: number;
11
+ /** Report binary keys + values; excludes head metadata and physical IDB overhead. */
12
+ maxRetainedReportBytes: bigint;
13
+ maxPageRecords: number;
14
+ }
15
+ export interface ReplayState {
16
+ nextSequence: bigint;
17
+ retainedReportBytes: bigint;
18
+ }
19
+ export type ReplayRecord = {
20
+ sequence: bigint;
21
+ outcome: {
22
+ kind: 'imported';
23
+ report: ImportReport;
24
+ } | {
25
+ kind: 'rejected';
26
+ reason: 'invalid-batch';
27
+ };
28
+ };
29
+ export type ReplayStep = {
30
+ kind: 'idle';
31
+ } | {
32
+ kind: 'processed' | 'raced';
33
+ record: ReplayRecord;
34
+ } | {
35
+ kind: 'retry';
36
+ sequence: bigint;
37
+ report: ImportReport;
38
+ };
39
+ /** Host-driven, no close/loop/GC. Stop and await step before closing shared storage.
40
+ * A checkpoint records one successful attempt, not a lost earlier attempt or current verification state. */
41
+ /** How the runner imports receipts (N3): the complete path (`full`,
42
+ * existing semantics — missing parents pend) or the partial-replica path
43
+ * (`partial` — the reverse-history intake; seals verify this turn only).
44
+ * Mirror of `ImportMode` in src/replay.rs. */
45
+ export type ImportMode = 'full' | 'partial';
46
+ export declare class DurableReplay {
47
+ #private;
48
+ private readonly inbox;
49
+ private readonly stream;
50
+ private readonly mode;
51
+ private constructor();
52
+ static open(inbox: Inbox, stream: Stream, limits: ReplayLimits): DurableReplay;
53
+ /** The partial-replica intake (N3): receipts import through
54
+ * `importPartialBatch` — parents are declared references and seals
55
+ * verify this turn only, so a reverse-history window becomes
56
+ * displayable `selfVerified` content instead of pending forever. */
57
+ static openPartial(inbox: Inbox, stream: Stream, limits: ReplayLimits): DurableReplay;
58
+ /** Whether this runner imports through the complete or partial path. */
59
+ get importMode(): ImportMode;
60
+ state(): Promise<ReplayState>;
61
+ records(afterSequence: bigint | null, limit: number): Promise<ReplayRecord[]>;
62
+ step(): Promise<ReplayStep>;
63
+ }