@loro-dev/roost 0.3.2 → 0.4.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/dist/store.d.ts CHANGED
@@ -115,6 +115,15 @@ export type ImportReport = {
115
115
  * repaired. */
116
116
  conflicts: ParentConflict[];
117
117
  };
118
+ export type PurgeOptions = {
119
+ keepIndexTables?: string[];
120
+ forgetRemotes?: Uint8Array[];
121
+ };
122
+ export type PurgeReport = {
123
+ spacesDropped: number;
124
+ syncScopesCleared: number;
125
+ scrubbed: boolean;
126
+ };
118
127
  /** How an imported frame is admitted (N3): the complete path (`full`,
119
128
  * existing semantics — missing parents pend, seals verify the ancestor
120
129
  * chain) or the partial-replica path (`partial` — parents are recorded as
@@ -181,6 +190,13 @@ export declare class Store {
181
190
  host<T>(fn: () => T): T;
182
191
  authorize(stream: string, owner: Uint8Array): boolean;
183
192
  stream(id: string): Stream;
193
+ /** Permanently removes stream `id` from this store in one IndexedDB write
194
+ * transaction: every space of the stream except `options.keepIndexTables`,
195
+ * the stream's sync coverage, tasks, policies and history scans under every
196
+ * remote and generation, its browser inbox/replay ledgers, and any remote
197
+ * registrations listed in `options.forgetRemotes`. IndexedDB cannot confirm
198
+ * backing-medium zeroing, so `report.scrubbed` is always `false`. */
199
+ purgeStream(id: string, options?: PurgeOptions): Promise<PurgeReport>;
184
200
  run<T>(write: boolean, stream: string, program: Program<T>, notify?: (result: T) => boolean): Promise<T>;
185
201
  subscribe(stream: string): ChangeSubscription;
186
202
  close(): Promise<void>;
@@ -199,6 +215,7 @@ export declare class Stream {
199
215
  readonly id: string;
200
216
  constructor(store: Store, id: string);
201
217
  space(table: string): string;
218
+ purge(options?: PurgeOptions): Promise<PurgeReport>;
202
219
  /** Unsigned, local derived state. Only actual selected changes emit events. */
203
220
  compareAndWriteIndex(expected: {
204
221
  table: string;
@@ -263,7 +280,12 @@ export declare class Stream {
263
280
  * honest: nothing here sets `hashVerified` for a turn with parents.
264
281
  * Mirror of `import_partial_batch` in src/store.rs. */
265
282
  importPartialBatch(bytes: Uint8Array): Promise<ImportReport>;
266
- importInner(bytes: Uint8Array, admission: Admission): Promise<ImportReport>;
283
+ /** Import a batch and run `after` inside the exact same write transaction
284
+ * before commit so import, pending unlocks, served receipts and coverage
285
+ * marks commit or roll back atomically. */
286
+ importBatchWithTx(bytes: Uint8Array, partial: boolean, after: (tx: KvTransaction, report: ImportReport) => Step<void>): Promise<ImportReport>;
287
+ exportSingleUpdateIn(tx: KvTransaction, id: Uint8Array, seq: bigint): Step<Uint8Array | null>;
288
+ importInner(bytes: Uint8Array, admission: Admission, after?: (tx: KvTransaction, report: ImportReport) => Step<void>): Promise<ImportReport>;
267
289
  /** The verification level of one turn (N3, Spec §88): the display
268
290
  * layer's contract. `ancestorsVerified` is exactly the existing
269
291
  * `hashVerified` meaning; `selfVerified` requires this turn's stored
package/dist/store.js CHANGED
@@ -228,6 +228,56 @@ export class Store {
228
228
  return value;
229
229
  }
230
230
  stream(id) { this.check(); return new Stream(this, namespace(id)); }
231
+ /** Permanently removes stream `id` from this store in one IndexedDB write
232
+ * transaction: every space of the stream except `options.keepIndexTables`,
233
+ * the stream's sync coverage, tasks, policies and history scans under every
234
+ * remote and generation, its browser inbox/replay ledgers, and any remote
235
+ * registrations listed in `options.forgetRemotes`. IndexedDB cannot confirm
236
+ * backing-medium zeroing, so `report.scrubbed` is always `false`. */
237
+ purgeStream(id, options = {}) {
238
+ const stream = this.stream(id);
239
+ const keep = new Set();
240
+ for (const table of options.keepIndexTables ?? []) {
241
+ if (typeof table !== 'string')
242
+ throw invalid('index table');
243
+ keep.add(stream.space(appTable(table)));
244
+ }
245
+ const forgetRemotes = [];
246
+ for (const remote of options.forgetRemotes ?? []) {
247
+ if (!(remote instanceof Uint8Array) || remote.length !== 16)
248
+ throw invalid('remoteId must be 16 bytes');
249
+ forgetRemotes.push(remote.slice());
250
+ }
251
+ const ownPrefix = stream.space('');
252
+ const idUtf8 = encodeUtf8(stream.id);
253
+ const ledgerPrefix = new Uint8Array(4 + idUtf8.length);
254
+ new DataView(ledgerPrefix.buffer).setUint32(0, idUtf8.length, false);
255
+ ledgerPrefix.set(idUtf8, 4);
256
+ const ledgerEnd = endPrefix(ledgerPrefix);
257
+ return this.run(true, stream.id, function* (tx) {
258
+ let spacesDropped = 0;
259
+ let syncScopesCleared = 0;
260
+ for (const space of yield* tx.spaceNames(ownPrefix)) {
261
+ if (!keep.has(space)) {
262
+ yield* tx.dropSpace(space);
263
+ spacesDropped += 1;
264
+ }
265
+ }
266
+ for (const space of PURGE_SCOPED_SPACES) {
267
+ syncScopesCleared += yield* clearScopedInTx(tx, space, ledgerPrefix);
268
+ }
269
+ for (const space of PURGE_LEDGER_SPACES) {
270
+ if ((yield* tx.deleteRange(space, ledgerPrefix, ledgerEnd)) > 0)
271
+ syncScopesCleared += 1;
272
+ }
273
+ for (const remote of forgetRemotes) {
274
+ yield* tx.delete('rsync_remote', cat(Uint8Array.of(0x01), remote));
275
+ const archivePfx = cat(Uint8Array.of(0x02), remote);
276
+ yield* tx.deleteRange('rsync_remote', archivePfx, endPrefix(archivePfx));
277
+ }
278
+ return { spacesDropped, syncScopesCleared, scrubbed: false };
279
+ });
280
+ }
231
281
  run(write, stream, program, notify) {
232
282
  this.check();
233
283
  const p = this.storage.transact(write, program);
@@ -302,6 +352,38 @@ export class ChangeSubscription {
302
352
  resolve(false);
303
353
  }
304
354
  }
355
+ const PURGE_SCOPED_SPACES = ['rsync_cov', 'rsync_work', 'rsync_policy', 'rsync_history'];
356
+ const PURGE_LEDGER_SPACES = [
357
+ 'browser_inbox_state_v1',
358
+ 'browser_inbox_records_v1',
359
+ 'browser_inbox_cursors_v1',
360
+ 'browser_replay_state_v1',
361
+ 'browser_replay_reports_v1',
362
+ ];
363
+ function* clearScopedInTx(tx, space, streamTail) {
364
+ let cleared = 0;
365
+ let start = empty;
366
+ for (;;) {
367
+ const rows = yield* tx.scan(space, start, undefined, 1);
368
+ if (rows.length === 0)
369
+ return cleared;
370
+ const key = rows[0][0];
371
+ const headLen = key.length > 17 ? 19 + key[17] : undefined;
372
+ if (headLen === undefined || key.length < headLen) {
373
+ start = cat(key, Uint8Array.of(0));
374
+ continue;
375
+ }
376
+ const head = key.subarray(0, headLen);
377
+ const scope = head[headLen - 1] === 0 ? head.subarray(0, headLen - 1) : head;
378
+ const prefix = cat(scope, streamTail);
379
+ if ((yield* tx.deleteRange(space, prefix, endPrefix(prefix))) > 0)
380
+ cleared += 1;
381
+ const next = endPrefix(head);
382
+ if (next === undefined)
383
+ return cleared;
384
+ start = next;
385
+ }
386
+ }
305
387
  function appTable(table) {
306
388
  if (table.length > 64 || !(table.startsWith('lody_') || table.startsWith('app_')) || !/^[a-z0-9_]+$/.test(table))
307
389
  throw invalid('index table');
@@ -315,6 +397,7 @@ export class Stream {
315
397
  this.id = id;
316
398
  }
317
399
  space(table) { return `roost-ts-v1:${encodeUtf8(this.id).length}:${this.id}:${table}`; }
400
+ purge(options) { return this.store.purgeStream(this.id, options); }
318
401
  /** Unsigned, local derived state. Only actual selected changes emit events. */
319
402
  async compareAndWriteIndex(expected, changes, options) {
320
403
  if (expected.length > 1001 || changes.length > 1001 || (options?.eventKeys?.length ?? 0) > 1001)
@@ -683,7 +766,19 @@ export class Stream {
683
766
  async importPartialBatch(bytes) {
684
767
  return this.importInner(bytes, 'partial');
685
768
  }
686
- async importInner(bytes, admission) {
769
+ /** Import a batch and run `after` inside the exact same write transaction
770
+ * before commit so import, pending unlocks, served receipts and coverage
771
+ * marks commit or roll back atomically. */
772
+ async importBatchWithTx(bytes, partial, after) {
773
+ return this.importInner(bytes, partial ? 'partial' : 'full', after);
774
+ }
775
+ *exportSingleUpdateIn(tx, id, seq) {
776
+ const raw = yield* tx.get(this.space('updates'), updateKey(id, seq));
777
+ if (!raw)
778
+ return null;
779
+ return syntax(() => assembleFrames([raw]));
780
+ }
781
+ async importInner(bytes, admission, after) {
687
782
  this.store.check();
688
783
  const copy = bytes.slice();
689
784
  let frames;
@@ -810,7 +905,10 @@ export class Stream {
810
905
  else if (!(yield* tx.get(s.space('pending'), key)))
811
906
  statuses[i] = { kind: 'rejected', reason: 'dependency resolution rejected update; see events' };
812
907
  }
813
- return { statuses, applied, conflicts };
908
+ const report = { statuses, applied, conflicts };
909
+ if (after)
910
+ yield* after(tx, report);
911
+ return report;
814
912
  });
815
913
  }
816
914
  /** The verification level of one turn (N3, Spec §88): the display
@@ -173,13 +173,21 @@ export declare class CoverageStore {
173
173
  * rejected mark commits nothing as a whole. */
174
174
  processedReports(scope: CoverageScope, source: string): Promise<bigint>;
175
175
  finishReport(scope: CoverageScope, source: string, sequence: bigint): Promise<void>;
176
+ recordServedIn(tx: KvTransaction, scope: CoverageScope, entries: {
177
+ turn: Uint8Array;
178
+ seq: number;
179
+ fp: Uint8Array;
180
+ }[]): Step<void>;
176
181
  recordServed(scope: CoverageScope, entries: {
177
182
  turn: Uint8Array;
178
183
  seq: number;
179
184
  fp: Uint8Array;
180
185
  }[]): Promise<void>;
186
+ wasServedIn(tx: KvTransaction, scope: CoverageScope, turn: Uint8Array, seq: number, fp: Uint8Array): Step<boolean>;
181
187
  wasServed(scope: CoverageScope, turn: Uint8Array, seq: number, fp: Uint8Array): Promise<boolean>;
188
+ unresolvedChildrenIn(tx: KvTransaction, scope: CoverageScope, parent: Uint8Array): Step<Uint8Array[]>;
182
189
  unresolvedChildren(scope: CoverageScope, parent: Uint8Array): Promise<Uint8Array[]>;
190
+ markReceivedIn(tx: KvTransaction, scope: CoverageScope, turn: Uint8Array, seq: number, fp: Uint8Array, isSeal: boolean, parents: ParentRef[], unresolved: DeclaredParent[]): Step<MarkResult>;
183
191
  markReceived(scope: CoverageScope, turn: Uint8Array, seq: number, fp: Uint8Array, isSeal: boolean, parents: ParentRef[], unresolved: DeclaredParent[]): Promise<MarkResult>;
184
192
  markPresent(scope: CoverageScope, turn: Uint8Array, seq: number, fingerprint: Uint8Array, isSeal: boolean, parents: ParentRef[]): Promise<MarkResult>;
185
193
  /** The mark-present logic inside a caller's transaction (the composition
@@ -269,6 +277,9 @@ export declare class CoverageStore {
269
277
  * matching seal fingerprint; then the closed record is written once and
270
278
  * never changed. */
271
279
  private closeWithDeps;
280
+ /** Delete every coverage record belonging to `scope` inside the caller's
281
+ * write transaction, preserving stream content and other scopes. */
282
+ static clearScopeIn(tx: KvTransaction, scope: CoverageScope): Step<number>;
272
283
  /** Append both fingerprints of a content conflict to the diagnostic
273
284
  * record of one `(turn, seq)`; diagnostics are observability only. */
274
285
  private recordConflict;
@@ -553,63 +553,70 @@ export class CoverageStore {
553
553
  }
554
554
  });
555
555
  }
556
+ *recordServedIn(tx, scope, entries) {
557
+ for (const e of entries) {
558
+ const key = cat(Uint8Array.of(7), scopeBytes(scope), e.turn, u32be(e.seq), e.fp);
559
+ if ((yield* tx.get(COVERAGE_SPACE, key)) === undefined)
560
+ yield* tx.put(COVERAGE_SPACE, key, new Uint8Array());
561
+ }
562
+ }
556
563
  async recordServed(scope, entries) {
557
- return this.storage.transact(true, function* (tx) {
558
- for (const e of entries) {
559
- const key = cat(Uint8Array.of(7), scopeBytes(scope), e.turn, u32be(e.seq), e.fp);
560
- if ((yield* tx.get(COVERAGE_SPACE, key)) === undefined)
561
- yield* tx.put(COVERAGE_SPACE, key, new Uint8Array());
562
- }
563
- });
564
+ const self = this;
565
+ return this.storage.transact(true, tx => self.recordServedIn(tx, scope, entries));
566
+ }
567
+ *wasServedIn(tx, scope, turn, seq, fp) {
568
+ return (yield* tx.get(COVERAGE_SPACE, cat(Uint8Array.of(7), scopeBytes(scope), turn, u32be(seq), fp))) !== undefined;
564
569
  }
565
570
  async wasServed(scope, turn, seq, fp) {
566
- return this.storage.transact(false, function* (tx) {
567
- return (yield* tx.get(COVERAGE_SPACE, cat(Uint8Array.of(7), scopeBytes(scope), turn, u32be(seq), fp))) !== undefined;
568
- });
571
+ const self = this;
572
+ return this.storage.transact(false, tx => self.wasServedIn(tx, scope, turn, seq, fp));
573
+ }
574
+ *unresolvedChildrenIn(tx, scope, parent) {
575
+ const prefix = cat(Uint8Array.of(8), scopeBytes(scope), parent);
576
+ return (yield* tx.scan(COVERAGE_SPACE, prefix, successor(prefix), Number.MAX_SAFE_INTEGER)).map(([key]) => key.slice(-16));
569
577
  }
570
578
  async unresolvedChildren(scope, parent) {
571
- return this.storage.transact(false, function* (tx) {
572
- const prefix = cat(Uint8Array.of(8), scopeBytes(scope), parent);
573
- return (yield* tx.scan(COVERAGE_SPACE, prefix, successor(prefix), Number.MAX_SAFE_INTEGER)).map(([key]) => key.slice(-16));
574
- });
579
+ const self = this;
580
+ return this.storage.transact(false, tx => self.unresolvedChildrenIn(tx, scope, parent));
581
+ }
582
+ *markReceivedIn(tx, scope, turn, seq, fp, isSeal, parents, unresolved) {
583
+ const key = coverageKey(scope, turn), raw = yield* tx.get(COVERAGE_SPACE, key);
584
+ let dto;
585
+ if (raw === undefined)
586
+ dto = freshSummary();
587
+ else {
588
+ const record = decodeTurnRecord(raw);
589
+ dto = record.kind === 'summary' ? record.dto : yield* this.convertLegacy(tx, scope, turn, record.dto);
590
+ }
591
+ for (const p of dto.unresolved ?? []) {
592
+ const other = unresolved.find(x => compareBytes(x.turn, p.turn) === 0);
593
+ if (other && compareBytes(other.hash, p.hash) !== 0)
594
+ throw new CoverageError('invalid', 'parent declaration changed');
595
+ if (!other && !parents.some(x => compareBytes(x.turnId, p.turn) === 0))
596
+ throw new CoverageError('invalid', 'parent resolution omitted');
597
+ yield* tx.delete(COVERAGE_SPACE, cat(Uint8Array.of(8), scopeBytes(scope), Uint8Array.from(p.turn), turn));
598
+ }
599
+ if (unresolved.length)
600
+ dto.unresolved = unresolved;
601
+ else
602
+ delete dto.unresolved;
603
+ dto.v = unresolved.length ? 3 : 2;
604
+ for (const p of parentsToDto(parents)) {
605
+ const old = dto.parents.find(x => compareBytes(x.turn, p.turn) === 0);
606
+ if (old && compareBytes(old.seal_fp, p.seal_fp) !== 0)
607
+ throw new CoverageError('invalid', 'parent binding changed');
608
+ if (!old)
609
+ dto.parents.push(p);
610
+ }
611
+ dto.parents.sort((a, b) => compareBytes(a.turn, b.turn));
612
+ for (const p of unresolved)
613
+ yield* tx.put(COVERAGE_SPACE, cat(Uint8Array.of(8), scopeBytes(scope), Uint8Array.from(p.turn), turn), new Uint8Array());
614
+ yield* tx.put(COVERAGE_SPACE, key, encodeWith(dto.v, dto));
615
+ return yield* this.markPresentIn(tx, scope, turn, seq, fp, isSeal, parentsToDto(parents));
575
616
  }
576
617
  async markReceived(scope, turn, seq, fp, isSeal, parents, unresolved) {
577
618
  const self = this;
578
- return this.storage.transact(true, function* (tx) {
579
- const key = coverageKey(scope, turn), raw = yield* tx.get(COVERAGE_SPACE, key);
580
- let dto;
581
- if (raw === undefined)
582
- dto = freshSummary();
583
- else {
584
- const record = decodeTurnRecord(raw);
585
- dto = record.kind === 'summary' ? record.dto : yield* self.convertLegacy(tx, scope, turn, record.dto);
586
- }
587
- for (const p of dto.unresolved ?? []) {
588
- const other = unresolved.find(x => compareBytes(x.turn, p.turn) === 0);
589
- if (other && compareBytes(other.hash, p.hash) !== 0)
590
- throw new CoverageError('invalid', 'parent declaration changed');
591
- if (!other && !parents.some(x => compareBytes(x.turnId, p.turn) === 0))
592
- throw new CoverageError('invalid', 'parent resolution omitted');
593
- yield* tx.delete(COVERAGE_SPACE, cat(Uint8Array.of(8), scopeBytes(scope), Uint8Array.from(p.turn), turn));
594
- }
595
- if (unresolved.length)
596
- dto.unresolved = unresolved;
597
- else
598
- delete dto.unresolved;
599
- dto.v = unresolved.length ? 3 : 2;
600
- for (const p of parentsToDto(parents)) {
601
- const old = dto.parents.find(x => compareBytes(x.turn, p.turn) === 0);
602
- if (old && compareBytes(old.seal_fp, p.seal_fp) !== 0)
603
- throw new CoverageError('invalid', 'parent binding changed');
604
- if (!old)
605
- dto.parents.push(p);
606
- }
607
- dto.parents.sort((a, b) => compareBytes(a.turn, b.turn));
608
- for (const p of unresolved)
609
- yield* tx.put(COVERAGE_SPACE, cat(Uint8Array.of(8), scopeBytes(scope), Uint8Array.from(p.turn), turn), new Uint8Array());
610
- yield* tx.put(COVERAGE_SPACE, key, encodeWith(dto.v, dto));
611
- return yield* self.markPresentIn(tx, scope, turn, seq, fp, isSeal, parentsToDto(parents));
612
- });
619
+ return this.storage.transact(true, tx => self.markReceivedIn(tx, scope, turn, seq, fp, isSeal, parents, unresolved));
613
620
  }
614
621
  async markPresent(scope, turn, seq, fingerprint, isSeal, parents) {
615
622
  const turnCopy = idCopy(turn, 'turn id');
@@ -1068,6 +1075,27 @@ export class CoverageStore {
1068
1075
  yield* tx.put(COVERAGE_SPACE, key, value);
1069
1076
  return true;
1070
1077
  }
1078
+ /** Delete every coverage record belonging to `scope` inside the caller's
1079
+ * write transaction, preserving stream content and other scopes. */
1080
+ static *clearScopeIn(tx, scope) {
1081
+ const scopePart = scopeBytes(scope);
1082
+ let deleted = 0;
1083
+ for (const tag of [
1084
+ COVERAGE_KEY_TAG,
1085
+ CLOSED_KEY_TAG,
1086
+ CONFLICT_KEY_TAG,
1087
+ CHILD_KEY_TAG,
1088
+ SEQ_KEY_TAG,
1089
+ ISLAND_KEY_TAG,
1090
+ 0x07,
1091
+ 0x08,
1092
+ 0x09,
1093
+ ]) {
1094
+ const prefix = cat(Uint8Array.of(tag), scopePart);
1095
+ deleted += yield* tx.deleteRange(COVERAGE_SPACE, prefix, successor(prefix));
1096
+ }
1097
+ return deleted;
1098
+ }
1071
1099
  /** Append both fingerprints of a content conflict to the diagnostic
1072
1100
  * record of one `(turn, seq)`; diagnostics are observability only. */
1073
1101
  *recordConflict(tx, scope, turn, seq, existing, fresh) {
@@ -1,10 +1,10 @@
1
1
  import type { IndexedDbStorage } from '../indexeddb.js';
2
- import type { Stream } from '../store.js';
2
+ import type { Stream, TurnHeader } from '../store.js';
3
3
  import type { MarkResult } from './coverage.js';
4
4
  import type { RemoteId } from './registry.js';
5
5
  import { RemoteRegistry } from './registry.js';
6
6
  import { WorkStore } from './work.js';
7
- import type { DiscoverResult, ResumePlan, TaskRef, WorkScope } from './work.js';
7
+ import type { DiscoverResult, OpRef, ResumePlan, TaskRef, WorkScope } from './work.js';
8
8
  /**
9
9
  * Dependency-first backfill execution (RS2-03), the IndexedDB mirror of
10
10
  * src/sync/execute.rs: the wiring between the host's stream store and the
@@ -140,3 +140,15 @@ export declare class Executor {
140
140
  * `inflight` and a later flush retries the identical frozen bytes. */
141
141
  flush(scope: WorkScope, transport: SendTransport, maxSend: number): Promise<FlushReport>;
142
142
  }
143
+ /** Build the OpRef list of one turn from the stream's real frames: seqs
144
+ * `fromSeq..nextSeq` (`fromSeq = 0` offers the whole turn; a higher `fromSeq`
145
+ * is the open-turn re-scan offering only newly appended ops, G009), frozen
146
+ * bytes = the exact `exportUpdates` frame, fingerprint = blake3 of the frame;
147
+ * seq 0 carries the turn's parent seals as cross-turn deps, later seqs carry
148
+ * exactly the direct predecessor (transitive closure is the prefix
149
+ * watermark's job). The predecessor fingerprint chain is recomputed from the
150
+ * frame just below the offered range, so a partial offer keeps its deps exact
151
+ * without re-offering persisted ops. Parents are resolved through
152
+ * `readTurnHeader` — a parent is always a sealed turn and never read beyond
153
+ * its header plus its raw seal frame. */
154
+ export declare function opsOfTurn(stream: Stream, header: TurnHeader, fromSeq: number, toSeq?: bigint): Promise<OpRef[]>;
@@ -275,7 +275,7 @@ export class Executor {
275
275
  * without re-offering persisted ops. Parents are resolved through
276
276
  * `readTurnHeader` — a parent is always a sealed turn and never read beyond
277
277
  * its header plus its raw seal frame. */
278
- async function opsOfTurn(stream, header, fromSeq, toSeq = header.nextSeq) {
278
+ export async function opsOfTurn(stream, header, fromSeq, toSeq = header.nextSeq) {
279
279
  if (toSeq > header.nextSeq || toSeq <= BigInt(fromSeq))
280
280
  throw new ExecuteError('invalid', 'invalid discovery op range');
281
281
  const parents = [];
@@ -0,0 +1,66 @@
1
+ import type { IndexedDbStorage } from '../indexeddb.js';
2
+ import type { ImportReport, Stream } from '../store.js';
3
+ import type { ConfirmResult, WorkScope } from './work.js';
4
+ /**
5
+ * Network-free local sync primitives for host-carried transports (such as
6
+ * `@loro-dev/streams-crdt/effect` `makeDurableStream({ mode: "explicit" })`),
7
+ * the IndexedDB mirror of `src/sync/explicit.rs`.
8
+ *
9
+ * Each item exchanged across the host transport is one raw Roost v1 frame
10
+ * (`encodeFrame`). Upload batches obey the exact `encodeItems` plaintext byte
11
+ * ceiling `Σ(4 + item.length) <= maxBytes`. Remote imports mark `CoverageStore`
12
+ * directly without writing to `browser_inbox_*` or `browser_replay_*`.
13
+ */
14
+ export declare class ExplicitSyncError extends Error {
15
+ readonly code: 'invalid' | 'work' | 'coverage' | 'execute' | 'link' | 'store';
16
+ constructor(code: 'invalid' | 'work' | 'coverage' | 'execute' | 'link' | 'store', message?: string, options?: ErrorOptions);
17
+ }
18
+ export type PullOptions = {
19
+ /** Exact `encodeItems` plaintext byte budget: `Σ(4 + item.length) <= maxBytes`. Defaults to `MAX_FRAME`. */
20
+ maxBytes?: number;
21
+ /** Maximum raw Roost frames in one batch (clamped to `MAX_UPDATES`). Defaults to `MAX_UPDATES`. */
22
+ maxItems?: number;
23
+ /** Partial replicas discover only `origin: 'local'` events unless `turnIds` are provided. */
24
+ partial?: boolean;
25
+ /** Optional explicit turn IDs to discover instead of scanning the journal. */
26
+ turnIds?: readonly Uint8Array[];
27
+ };
28
+ export type BatchReceiptEntry = {
29
+ turnId: Uint8Array;
30
+ seq: number;
31
+ attempt: number;
32
+ };
33
+ export type PulledBatch = {
34
+ /** Raw Roost v1 frames (`encodeFrame`), in `(TurnId, seq)` topological order. */
35
+ items: Uint8Array[];
36
+ /** Attempt-scoped receipt tokens matching `items` 1-to-1. */
37
+ receipt: BatchReceiptEntry[];
38
+ };
39
+ export type RemoteImportReport = {
40
+ report: ImportReport;
41
+ appliedTurns: Uint8Array[];
42
+ pendingTurns: Uint8Array[];
43
+ hasPendingDependencies: boolean;
44
+ retryQuotaExceeded: boolean;
45
+ };
46
+ export type ResetSyncReport = {
47
+ workKeysRemoved: number;
48
+ coverageKeysRemoved: number;
49
+ };
50
+ export declare class ExplicitSync {
51
+ #private;
52
+ constructor(storage: IndexedDbStorage);
53
+ /** Discover pending local work and acquire the next dependency-ready batch
54
+ * of raw Roost v1 frames bounded by `options.maxBytes` and `options.maxItems`. */
55
+ pullPendingBatch(stream: Stream, scope: WorkScope, options?: PullOptions): Promise<PulledBatch | null>;
56
+ /** Atomically confirm a pulled batch in `WorkStore` + `CoverageStore` after
57
+ * the host transport receives durable server ACK. */
58
+ confirmPendingBatch(scope: WorkScope, receipt: readonly BatchReceiptEntry[]): Promise<ConfirmResult[]>;
59
+ /** Import raw Roost v1 frames received from the remote transport directly
60
+ * into `stream` and mark `CoverageStore` without writing to `browser_inbox_*`
61
+ * or `browser_replay_*`. */
62
+ importRemoteBatch(stream: Stream, scope: WorkScope, items: readonly Uint8Array[], partial?: boolean): Promise<RemoteImportReport>;
63
+ /** Clear `WorkStore` and `CoverageStore` state for `scope` in a single write
64
+ * transaction while preserving local stream Turns, events and indexes. */
65
+ resetSyncState(scope: WorkScope): Promise<ResetSyncReport>;
66
+ }