@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.
- package/LICENSE +21 -0
- package/README.md +397 -0
- package/dist/codec.d.ts +66 -0
- package/dist/codec.js +275 -0
- package/dist/crypto.d.ts +21 -0
- package/dist/crypto.js +103 -0
- package/dist/durable-framing.d.ts +44 -0
- package/dist/durable-framing.js +207 -0
- package/dist/framing.d.ts +28 -0
- package/dist/framing.js +144 -0
- package/dist/history-publication.d.ts +58 -0
- package/dist/history-publication.js +234 -0
- package/dist/identity.d.ts +14 -0
- package/dist/identity.js +62 -0
- package/dist/inbox.d.ts +69 -0
- package/dist/inbox.js +262 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +6 -0
- package/dist/indexeddb.d.ts +38 -0
- package/dist/indexeddb.js +299 -0
- package/dist/json.d.ts +23 -0
- package/dist/json.js +221 -0
- package/dist/lody-history.d.ts +397 -0
- package/dist/lody-history.js +1559 -0
- package/dist/projection.d.ts +53 -0
- package/dist/projection.js +543 -0
- package/dist/replay.d.ts +63 -0
- package/dist/replay.js +201 -0
- package/dist/sender.d.ts +26 -0
- package/dist/sender.js +67 -0
- package/dist/store.d.ts +384 -0
- package/dist/store.js +1437 -0
- package/dist/sync/coverage.d.ts +276 -0
- package/dist/sync/coverage.js +1084 -0
- package/dist/sync/crypto.d.ts +64 -0
- package/dist/sync/crypto.js +155 -0
- package/dist/sync/execute.d.ts +142 -0
- package/dist/sync/execute.js +321 -0
- package/dist/sync/history.d.ts +214 -0
- package/dist/sync/history.js +786 -0
- package/dist/sync/index.d.ts +17 -0
- package/dist/sync/index.js +9 -0
- package/dist/sync/link.d.ts +192 -0
- package/dist/sync/link.js +663 -0
- package/dist/sync/mod.d.ts +24 -0
- package/dist/sync/mod.js +15 -0
- package/dist/sync/policy.d.ts +62 -0
- package/dist/sync/policy.js +128 -0
- package/dist/sync/registry.d.ts +129 -0
- package/dist/sync/registry.js +333 -0
- package/dist/sync/transport.d.ts +91 -0
- package/dist/sync/transport.js +162 -0
- package/dist/sync/work.d.ts +351 -0
- package/dist/sync/work.js +1344 -0
- package/package.json +47 -0
package/dist/replay.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/** One complete RST1 batch per Inbox receipt. This is not an SDK byte framer. */
|
|
2
|
+
import { splitBatch } from './codec.js';
|
|
3
|
+
import { _isRetryableImportStatus } from './store.js';
|
|
4
|
+
const STATE = 'browser_replay_state_v1', REPORTS = 'browser_replay_reports_v1';
|
|
5
|
+
const MAX_U64 = (1n << 64n) - 1n;
|
|
6
|
+
const encoder = new TextEncoder(), decoder = new TextDecoder('utf-8', { fatal: true });
|
|
7
|
+
export class ReplayError extends Error {
|
|
8
|
+
code;
|
|
9
|
+
name = 'ReplayError';
|
|
10
|
+
constructor(code, message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.code = code;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const fail = (code, message) => { throw new ReplayError(code, message); };
|
|
16
|
+
function integer(value) {
|
|
17
|
+
if (typeof value !== 'string' || !/^(0|[1-9][0-9]*)$/.test(value))
|
|
18
|
+
return fail('corrupt', 'invalid replay integer');
|
|
19
|
+
const n = BigInt(value);
|
|
20
|
+
if (n > MAX_U64)
|
|
21
|
+
return fail('corrupt', 'replay integer overflow');
|
|
22
|
+
return n;
|
|
23
|
+
}
|
|
24
|
+
function u64(n) { const b = new Uint8Array(8); new DataView(b.buffer).setBigUint64(0, n); return b; }
|
|
25
|
+
function join(a, b) { const out = new Uint8Array(a.length + b.length); out.set(a); out.set(b, a.length); return out; }
|
|
26
|
+
function successor(prefix) {
|
|
27
|
+
let i = prefix.length - 1;
|
|
28
|
+
while (i >= 0 && prefix[i] === 255)
|
|
29
|
+
--i;
|
|
30
|
+
if (i < 0)
|
|
31
|
+
return fail('corrupt', 'replay namespace');
|
|
32
|
+
const end = prefix.slice(0, i + 1);
|
|
33
|
+
end[i] = end[i] + 1;
|
|
34
|
+
return end;
|
|
35
|
+
}
|
|
36
|
+
function encodeRecord(record) {
|
|
37
|
+
const out = record.outcome;
|
|
38
|
+
return encoder.encode(JSON.stringify(out.kind === 'rejected'
|
|
39
|
+
? [1, String(record.sequence), 'rejected', out.reason]
|
|
40
|
+
: [1, String(record.sequence), 'imported', out.report.statuses.map(s => s.kind === 'rejected' ? [s.kind, s.reason] : [s.kind]),
|
|
41
|
+
out.report.applied.map(r => [Array.from(r.turnId, b => b.toString(16).padStart(2, '0')).join(''), String(r.seq)])]));
|
|
42
|
+
}
|
|
43
|
+
function decodeRecord(bytes, expected) {
|
|
44
|
+
let value;
|
|
45
|
+
try {
|
|
46
|
+
value = JSON.parse(decoder.decode(bytes));
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return fail('corrupt', 'invalid replay report');
|
|
50
|
+
}
|
|
51
|
+
if (!Array.isArray(value) || value[0] !== 1 || integer(value[1]) !== expected)
|
|
52
|
+
return fail('corrupt', 'replay report sequence/version');
|
|
53
|
+
if (value.length === 4 && value[2] === 'rejected' && value[3] === 'invalid-batch')
|
|
54
|
+
return { sequence: expected, outcome: { kind: 'rejected', reason: 'invalid-batch' } };
|
|
55
|
+
if (value.length !== 5 || value[2] !== 'imported' || !Array.isArray(value[3]) || !Array.isArray(value[4]))
|
|
56
|
+
return fail('corrupt', 'replay report shape');
|
|
57
|
+
const statuses = value[3].map((s) => {
|
|
58
|
+
if (!Array.isArray(s))
|
|
59
|
+
return fail('corrupt', 'replay status');
|
|
60
|
+
if (s.length === 2 && s[0] === 'rejected' && typeof s[1] === 'string')
|
|
61
|
+
return { kind: 'rejected', reason: s[1] };
|
|
62
|
+
if (s.length === 1 && ['applied', 'duplicate', 'pending'].includes(s[0]))
|
|
63
|
+
return { kind: s[0] };
|
|
64
|
+
return fail('corrupt', 'replay status');
|
|
65
|
+
});
|
|
66
|
+
const applied = value[4].map((r) => {
|
|
67
|
+
if (!Array.isArray(r) || r.length !== 2 || typeof r[0] !== 'string' || !/^[0-9a-f]{32}$/.test(r[0]))
|
|
68
|
+
return fail('corrupt', 'replay applied reference');
|
|
69
|
+
return { turnId: Uint8Array.from(r[0].match(/../g), b => Number.parseInt(b, 16)), seq: integer(r[1]) };
|
|
70
|
+
});
|
|
71
|
+
if (statuses.some(_isRetryableImportStatus))
|
|
72
|
+
return fail('corrupt', 'retryable report cannot be checkpointed');
|
|
73
|
+
return { sequence: expected, outcome: { kind: 'imported', report: { statuses, applied, conflicts: [] } } };
|
|
74
|
+
}
|
|
75
|
+
export class DurableReplay {
|
|
76
|
+
inbox;
|
|
77
|
+
stream;
|
|
78
|
+
mode;
|
|
79
|
+
#limits;
|
|
80
|
+
constructor(inbox, stream, limits, mode = 'full') {
|
|
81
|
+
this.inbox = inbox;
|
|
82
|
+
this.stream = stream;
|
|
83
|
+
this.mode = mode;
|
|
84
|
+
for (const n of [limits.maxBatchBytes, limits.maxReportBytes, limits.maxPageRecords])
|
|
85
|
+
if (!Number.isSafeInteger(n) || n <= 0)
|
|
86
|
+
fail('invalid', 'positive safe integer limits required');
|
|
87
|
+
if (typeof limits.maxRetainedReportBytes !== 'bigint' || limits.maxRetainedReportBytes <= 0n || limits.maxRetainedReportBytes > MAX_U64)
|
|
88
|
+
fail('invalid', 'report quota must be positive u64');
|
|
89
|
+
this.#limits = Object.freeze({ ...limits });
|
|
90
|
+
}
|
|
91
|
+
static open(inbox, stream, limits) { return new DurableReplay(inbox, stream, limits); }
|
|
92
|
+
/** The partial-replica intake (N3): receipts import through
|
|
93
|
+
* `importPartialBatch` — parents are declared references and seals
|
|
94
|
+
* verify this turn only, so a reverse-history window becomes
|
|
95
|
+
* displayable `selfVerified` content instead of pending forever. */
|
|
96
|
+
static openPartial(inbox, stream, limits) { return new DurableReplay(inbox, stream, limits, 'partial'); }
|
|
97
|
+
/** Whether this runner imports through the complete or partial path. */
|
|
98
|
+
get importMode() { return this.mode; }
|
|
99
|
+
#transact(write, program) {
|
|
100
|
+
return this.inbox._replayTransact(write, this.stream.store.storage, this.stream.id, program);
|
|
101
|
+
}
|
|
102
|
+
#decode(bytes, expected) {
|
|
103
|
+
if (bytes.length > this.#limits.maxReportBytes)
|
|
104
|
+
fail('limit', 'stored report exceeds current report limit');
|
|
105
|
+
return decodeRecord(bytes, expected);
|
|
106
|
+
}
|
|
107
|
+
*#state(tx, key) {
|
|
108
|
+
const bytes = yield* tx.get(STATE, key);
|
|
109
|
+
if (bytes === undefined) {
|
|
110
|
+
if ((yield* tx.scan(REPORTS, key, successor(key), 1)).length)
|
|
111
|
+
fail('corrupt', 'replay report without state');
|
|
112
|
+
return { nextSequence: 0n, retainedReportBytes: 0n };
|
|
113
|
+
}
|
|
114
|
+
if (bytes.length !== 16)
|
|
115
|
+
return fail('corrupt', 'replay state length');
|
|
116
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
117
|
+
const nextSequence = view.getBigUint64(0), retainedReportBytes = view.getBigUint64(8);
|
|
118
|
+
if (nextSequence === 0n || retainedReportBytes === 0n)
|
|
119
|
+
return fail('corrupt', 'empty persisted replay state');
|
|
120
|
+
const last = yield* tx.get(REPORTS, join(key, u64(nextSequence - 1n)));
|
|
121
|
+
if (last === undefined)
|
|
122
|
+
return fail('corrupt', 'replay state without report');
|
|
123
|
+
this.#decode(last, nextSequence - 1n);
|
|
124
|
+
if (retainedReportBytes < BigInt(key.length + 8 + last.length))
|
|
125
|
+
return fail('corrupt', 'replay byte accounting');
|
|
126
|
+
return { nextSequence, retainedReportBytes };
|
|
127
|
+
}
|
|
128
|
+
state() { const self = this; return this.#transact(false, function* (tx, key) { return yield* self.#state(tx, key); }); }
|
|
129
|
+
records(afterSequence, limit) {
|
|
130
|
+
if (!Number.isSafeInteger(limit) || limit <= 0 || limit > this.#limits.maxPageRecords)
|
|
131
|
+
fail('invalid', 'replay page limit');
|
|
132
|
+
if (afterSequence !== null && (typeof afterSequence !== 'bigint' || afterSequence < 0n || afterSequence > MAX_U64))
|
|
133
|
+
fail('invalid', 'afterSequence must be u64');
|
|
134
|
+
const self = this;
|
|
135
|
+
return this.#transact(false, function* (tx, key) {
|
|
136
|
+
const state = yield* self.#state(tx, key), start = afterSequence === null ? 0n : afterSequence + 1n;
|
|
137
|
+
if (start >= state.nextSequence)
|
|
138
|
+
return [];
|
|
139
|
+
const count = Number(state.nextSequence - start < BigInt(limit) ? state.nextSequence - start : BigInt(limit));
|
|
140
|
+
const rows = yield* tx.scan(REPORTS, join(key, u64(start)), successor(key), count);
|
|
141
|
+
if (rows.length !== count)
|
|
142
|
+
return fail('corrupt', 'missing replay report');
|
|
143
|
+
return rows.map(([k, value], i) => {
|
|
144
|
+
const expectedKey = join(key, u64(start + BigInt(i)));
|
|
145
|
+
if (k.length !== expectedKey.length || !k.every((v, j) => v === expectedKey[j]))
|
|
146
|
+
return fail('corrupt', 'replay report key');
|
|
147
|
+
return self.#decode(value, start + BigInt(i));
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
async step() {
|
|
152
|
+
const state = await this.state(), received = await this.inbox.state();
|
|
153
|
+
if (state.nextSequence > received.nextSequence)
|
|
154
|
+
return fail('corrupt', 'processed cursor beyond Inbox');
|
|
155
|
+
if (state.nextSequence === received.nextSequence)
|
|
156
|
+
return { kind: 'idle' };
|
|
157
|
+
const record = (await this.inbox.records(state.nextSequence === 0n ? null : state.nextSequence - 1n, 1))[0];
|
|
158
|
+
if (!record || record.sequence !== state.nextSequence)
|
|
159
|
+
return fail('corrupt', 'missing Inbox receipt');
|
|
160
|
+
if (record.bytes.length > this.#limits.maxBatchBytes)
|
|
161
|
+
return fail('limit', 'receipt exceeds current batch limit');
|
|
162
|
+
let malformed = false;
|
|
163
|
+
try {
|
|
164
|
+
splitBatch(record.bytes);
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
malformed = true;
|
|
168
|
+
}
|
|
169
|
+
let outcome;
|
|
170
|
+
if (malformed)
|
|
171
|
+
outcome = { kind: 'rejected', reason: 'invalid-batch' };
|
|
172
|
+
else {
|
|
173
|
+
const report = this.mode === 'partial'
|
|
174
|
+
? await this.stream.importPartialBatch(record.bytes)
|
|
175
|
+
: await this.stream.importBatch(record.bytes);
|
|
176
|
+
if (report.statuses.some(_isRetryableImportStatus))
|
|
177
|
+
return { kind: 'retry', sequence: record.sequence, report };
|
|
178
|
+
outcome = { kind: 'imported', report };
|
|
179
|
+
}
|
|
180
|
+
const result = { sequence: record.sequence, outcome }, encoded = encodeRecord(result), self = this;
|
|
181
|
+
if (encoded.length > this.#limits.maxReportBytes)
|
|
182
|
+
return fail('limit', 'report exceeds current report limit');
|
|
183
|
+
return this.#transact(true, function* (tx, key) {
|
|
184
|
+
const current = yield* self.#state(tx, key), reportKey = join(key, u64(record.sequence));
|
|
185
|
+
if (current.nextSequence > record.sequence) {
|
|
186
|
+
const winner = yield* tx.get(REPORTS, reportKey);
|
|
187
|
+
if (winner === undefined)
|
|
188
|
+
return fail('corrupt', 'CAS winner report missing');
|
|
189
|
+
return { kind: 'raced', record: self.#decode(winner, record.sequence) };
|
|
190
|
+
}
|
|
191
|
+
if (current.nextSequence !== record.sequence || (yield* tx.get(REPORTS, reportKey)) !== undefined)
|
|
192
|
+
return fail('corrupt', 'replay checkpoint conflict');
|
|
193
|
+
const retained = current.retainedReportBytes + BigInt(reportKey.length + encoded.length);
|
|
194
|
+
if (retained > self.#limits.maxRetainedReportBytes || retained > MAX_U64)
|
|
195
|
+
return fail('limit', 'retained report quota');
|
|
196
|
+
yield* tx.put(REPORTS, reportKey, encoded);
|
|
197
|
+
yield* tx.put(STATE, key, join(u64(record.sequence + 1n), u64(retained)));
|
|
198
|
+
return { kind: 'processed', record: result };
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
}
|
package/dist/sender.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { OutgoingSubscription } from './store.js';
|
|
2
|
+
export type SendOutcome = {
|
|
3
|
+
kind: 'idle' | 'confirmed';
|
|
4
|
+
};
|
|
5
|
+
export declare class SendError extends Error {
|
|
6
|
+
readonly kind: 'local' | 'transport';
|
|
7
|
+
readonly cause: unknown;
|
|
8
|
+
readonly name = "SendError";
|
|
9
|
+
constructor(kind: 'local' | 'transport', cause: unknown);
|
|
10
|
+
}
|
|
11
|
+
/** Share the consumer name across restart to resume its original pending batch.
|
|
12
|
+
* Concurrent senders may deliver duplicates. Use one host loop per consumer if
|
|
13
|
+
* requests must not overlap. No network work runs inside an IDB transaction.
|
|
14
|
+
*/
|
|
15
|
+
export declare class DurableSender {
|
|
16
|
+
private readonly outgoing;
|
|
17
|
+
constructor(outgoing: OutgoingSubscription);
|
|
18
|
+
/** A fulfilled callback asserts remote durable acceptance under the host's contract.
|
|
19
|
+
* Stop and await sendNext before physically closing shared storage. Store.close
|
|
20
|
+
* during transport makes local confirmation fail, retaining the pinned bytes.
|
|
21
|
+
*/
|
|
22
|
+
sendNext(limits: {
|
|
23
|
+
maxUpdates: number;
|
|
24
|
+
maxBytes: number;
|
|
25
|
+
}, send: (bytes: Uint8Array) => void | Promise<void>): Promise<SendOutcome>;
|
|
26
|
+
}
|
package/dist/sender.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/** Durable at-least-once sending; host confirmation is not transport authentication. */
|
|
2
|
+
import { blake3 } from '@noble/hashes/blake3.js';
|
|
3
|
+
import { StoreError } from './store.js';
|
|
4
|
+
export class SendError extends Error {
|
|
5
|
+
kind;
|
|
6
|
+
cause;
|
|
7
|
+
name = 'SendError';
|
|
8
|
+
constructor(kind, cause) {
|
|
9
|
+
// A host may throw any JS value; do not invoke its toString or getters.
|
|
10
|
+
super(`${kind} sender failure`, { cause });
|
|
11
|
+
this.kind = kind;
|
|
12
|
+
this.cause = cause;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** Share the consumer name across restart to resume its original pending batch.
|
|
16
|
+
* Concurrent senders may deliver duplicates. Use one host loop per consumer if
|
|
17
|
+
* requests must not overlap. No network work runs inside an IDB transaction.
|
|
18
|
+
*/
|
|
19
|
+
export class DurableSender {
|
|
20
|
+
outgoing;
|
|
21
|
+
constructor(outgoing) {
|
|
22
|
+
this.outgoing = outgoing;
|
|
23
|
+
}
|
|
24
|
+
/** A fulfilled callback asserts remote durable acceptance under the host's contract.
|
|
25
|
+
* Stop and await sendNext before physically closing shared storage. Store.close
|
|
26
|
+
* during transport makes local confirmation fail, retaining the pinned bytes.
|
|
27
|
+
*/
|
|
28
|
+
async sendNext(limits, send) {
|
|
29
|
+
let prepared;
|
|
30
|
+
let bytes;
|
|
31
|
+
let digest;
|
|
32
|
+
try {
|
|
33
|
+
if (typeof send !== 'function')
|
|
34
|
+
throw new StoreError('invalid', 'send callback required');
|
|
35
|
+
const pending = await this.outgoing._durablePrepare({ maxUpdates: limits.maxUpdates, maxBytes: limits.maxBytes });
|
|
36
|
+
if (!pending)
|
|
37
|
+
return { kind: 'idle' };
|
|
38
|
+
prepared = pending;
|
|
39
|
+
bytes = prepared.bytes();
|
|
40
|
+
digest = blake3(bytes);
|
|
41
|
+
}
|
|
42
|
+
catch (cause) {
|
|
43
|
+
throw new SendError('local', cause);
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
await send(bytes);
|
|
47
|
+
}
|
|
48
|
+
catch (cause) {
|
|
49
|
+
throw new SendError('transport', cause);
|
|
50
|
+
}
|
|
51
|
+
try {
|
|
52
|
+
let unchanged = false;
|
|
53
|
+
try {
|
|
54
|
+
const after = blake3(bytes);
|
|
55
|
+
unchanged = after.every((b, i) => b === digest[i]);
|
|
56
|
+
}
|
|
57
|
+
catch { /* A transferred/detached buffer is also a visible mutation. */ }
|
|
58
|
+
if (!unchanged)
|
|
59
|
+
throw new StoreError('invalid', 'transport mutated the prepared batch');
|
|
60
|
+
await this.outgoing._durableConfirm(prepared);
|
|
61
|
+
}
|
|
62
|
+
catch (cause) {
|
|
63
|
+
throw new SendError('local', cause);
|
|
64
|
+
}
|
|
65
|
+
return { kind: 'confirmed' };
|
|
66
|
+
}
|
|
67
|
+
}
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
import { IndexedDbStorage, type KvTransaction, type Program, type Step } from './indexeddb.js';
|
|
2
|
+
import { type ContentOp, type ParentRef, type Update, type ValuePath } from './codec.js';
|
|
3
|
+
import { type JsonValue } from './json.js';
|
|
4
|
+
import { Identity } from './identity.js';
|
|
5
|
+
import { type Layout } from './projection.js';
|
|
6
|
+
export declare class StoreError extends Error {
|
|
7
|
+
readonly code: 'invalid' | 'pending' | 'conflict' | 'sealed' | 'stale' | 'unauthorized' | 'corrupt' | 'closed';
|
|
8
|
+
constructor(code: 'invalid' | 'pending' | 'conflict' | 'sealed' | 'stale' | 'unauthorized' | 'corrupt' | 'closed', message?: string, options?: ErrorOptions);
|
|
9
|
+
}
|
|
10
|
+
export type TurnSnapshot = {
|
|
11
|
+
turnId: Uint8Array;
|
|
12
|
+
owner: Uint8Array;
|
|
13
|
+
parents: ParentRef[];
|
|
14
|
+
content: JsonValue;
|
|
15
|
+
nextSeq: bigint;
|
|
16
|
+
sealed: Uint8Array | null;
|
|
17
|
+
hashVerified: boolean;
|
|
18
|
+
/** True only after this turn's *stored body* was recomputed and matched
|
|
19
|
+
* `sealed` (mirror of Rust `TurnSnapshot::body_verified`). The seal
|
|
20
|
+
* signature alone binds the declared hash, not the local bytes, so an
|
|
21
|
+
* admission that skipped hash recomputation leaves this false. */
|
|
22
|
+
bodyVerified: boolean;
|
|
23
|
+
};
|
|
24
|
+
/** Lightweight Turn header for reverse keyset pagination; everything
|
|
25
|
+
* TurnSnapshot carries except content. Rust mirror: `TurnHeader` in
|
|
26
|
+
* src/model.rs. Content is fetched on demand via the normal read paths. */
|
|
27
|
+
export type TurnHeader = Omit<TurnSnapshot, 'content'>;
|
|
28
|
+
type Header = Omit<TurnSnapshot, 'content'> & {
|
|
29
|
+
layout: Layout;
|
|
30
|
+
};
|
|
31
|
+
export type UpdateRef = {
|
|
32
|
+
turnId: Uint8Array;
|
|
33
|
+
seq: bigint;
|
|
34
|
+
};
|
|
35
|
+
export type Commit = {
|
|
36
|
+
updates: UpdateRef[];
|
|
37
|
+
};
|
|
38
|
+
export type Write = {
|
|
39
|
+
kind: 'create';
|
|
40
|
+
parents: ParentRef[];
|
|
41
|
+
content: JsonValue;
|
|
42
|
+
} | {
|
|
43
|
+
kind: 'createOnce';
|
|
44
|
+
key: Uint8Array;
|
|
45
|
+
parents: ParentRef[];
|
|
46
|
+
content: JsonValue;
|
|
47
|
+
} | {
|
|
48
|
+
kind: 'edit';
|
|
49
|
+
turnId: Uint8Array;
|
|
50
|
+
expectedNextSeq: bigint;
|
|
51
|
+
ops: ContentOp[];
|
|
52
|
+
} | {
|
|
53
|
+
kind: 'editOnce';
|
|
54
|
+
key: Uint8Array;
|
|
55
|
+
expectedNextSeq: bigint;
|
|
56
|
+
ops: ContentOp[];
|
|
57
|
+
} | {
|
|
58
|
+
kind: 'seal';
|
|
59
|
+
turnId: Uint8Array;
|
|
60
|
+
expectedNextSeq: bigint;
|
|
61
|
+
} | {
|
|
62
|
+
kind: 'sealOnce';
|
|
63
|
+
key: Uint8Array;
|
|
64
|
+
expectedNextSeq: bigint;
|
|
65
|
+
};
|
|
66
|
+
export type IndexPut = {
|
|
67
|
+
table: string;
|
|
68
|
+
key: Uint8Array;
|
|
69
|
+
value: Uint8Array;
|
|
70
|
+
onceKey?: Uint8Array;
|
|
71
|
+
emitEvent?: boolean;
|
|
72
|
+
};
|
|
73
|
+
export type TurnReadResult = {
|
|
74
|
+
kind: 'found';
|
|
75
|
+
turn: TurnSnapshot;
|
|
76
|
+
} | {
|
|
77
|
+
kind: 'notFound';
|
|
78
|
+
turnId: Uint8Array;
|
|
79
|
+
} | {
|
|
80
|
+
kind: 'incomplete';
|
|
81
|
+
turnId: Uint8Array;
|
|
82
|
+
prefix: TurnSnapshot | null;
|
|
83
|
+
};
|
|
84
|
+
/** The header-level tri-state read, mirroring `TurnReadResult` without ever
|
|
85
|
+
* materializing content (G026): discovery and other metadata-only consumers
|
|
86
|
+
* must not pay for the projection. Rust mirror: `TurnHeaderResult` in
|
|
87
|
+
* src/store.rs. */
|
|
88
|
+
export type TurnHeaderResult = {
|
|
89
|
+
kind: 'found';
|
|
90
|
+
turn: TurnHeader;
|
|
91
|
+
} | {
|
|
92
|
+
kind: 'notFound';
|
|
93
|
+
turnId: Uint8Array;
|
|
94
|
+
} | {
|
|
95
|
+
kind: 'incomplete';
|
|
96
|
+
turnId: Uint8Array;
|
|
97
|
+
prefix: TurnHeader | null;
|
|
98
|
+
};
|
|
99
|
+
export type ImportStatus = {
|
|
100
|
+
kind: 'applied' | 'duplicate' | 'pending';
|
|
101
|
+
} | {
|
|
102
|
+
kind: 'rejected';
|
|
103
|
+
reason: string;
|
|
104
|
+
};
|
|
105
|
+
/** Maximum rows per reverse keyset header page. Mirror of MAX_PAGE_HEADERS in
|
|
106
|
+
* src/store.rs; keep both languages in sync (1000). */
|
|
107
|
+
export declare const MAX_PAGE_HEADERS = 1000;
|
|
108
|
+
/** Internal replay classification; public import status and reason remain unchanged. */
|
|
109
|
+
export declare function _isRetryableImportStatus(status: ImportStatus): boolean;
|
|
110
|
+
export type ImportReport = {
|
|
111
|
+
statuses: ImportStatus[];
|
|
112
|
+
applied: UpdateRef[];
|
|
113
|
+
/** Declared parent hashes that the seals admitted in this batch
|
|
114
|
+
* contradicted (N3 backfill reconcile): diagnosed, never silently
|
|
115
|
+
* repaired. */
|
|
116
|
+
conflicts: ParentConflict[];
|
|
117
|
+
};
|
|
118
|
+
/** How an imported frame is admitted (N3): the complete path (`full`,
|
|
119
|
+
* existing semantics — missing parents pend, seals verify the ancestor
|
|
120
|
+
* chain) or the partial-replica path (`partial` — parents are recorded as
|
|
121
|
+
* declared references, seals verify this turn only). Mirror of `Admission`
|
|
122
|
+
* in src/store.rs. */
|
|
123
|
+
export type Admission = 'full' | 'partial';
|
|
124
|
+
/** The verification level of a locally stored turn (N3, Spec §88): four
|
|
125
|
+
* mutually exclusive states the display layer can rely on.
|
|
126
|
+
* `hashVerified` keeps its full meaning (this turn AND all ancestors
|
|
127
|
+
* verified); only the complete import path can reach
|
|
128
|
+
* `ancestorsVerified`. */
|
|
129
|
+
export type Verification = 'notRetrieved' | 'provisional' | 'selfVerified' | 'ancestorsVerified';
|
|
130
|
+
/** A declared parent hash that a later-arriving seal contradicted (N3
|
|
131
|
+
* backfill reconcile). */
|
|
132
|
+
export type ParentConflict = {
|
|
133
|
+
child: Uint8Array;
|
|
134
|
+
parent: Uint8Array;
|
|
135
|
+
declared: Uint8Array;
|
|
136
|
+
actual: Uint8Array;
|
|
137
|
+
};
|
|
138
|
+
export type Event = {
|
|
139
|
+
kind: 'changed';
|
|
140
|
+
update: UpdateRef;
|
|
141
|
+
origin: 'local' | 'remote';
|
|
142
|
+
} | {
|
|
143
|
+
kind: 'rejected';
|
|
144
|
+
digest: Uint8Array;
|
|
145
|
+
reason: string;
|
|
146
|
+
} | {
|
|
147
|
+
/** Local application-index change; never part of the wire or outbox. */
|
|
148
|
+
kind: 'indexChanged';
|
|
149
|
+
table: string;
|
|
150
|
+
key: Uint8Array;
|
|
151
|
+
};
|
|
152
|
+
export type EventRecord = {
|
|
153
|
+
cursor: bigint;
|
|
154
|
+
event: Event;
|
|
155
|
+
};
|
|
156
|
+
export type MissingDependencies = {
|
|
157
|
+
turnId: Uint8Array;
|
|
158
|
+
nextSeq: bigint;
|
|
159
|
+
sequences: {
|
|
160
|
+
start: bigint;
|
|
161
|
+
end: bigint;
|
|
162
|
+
}[];
|
|
163
|
+
parents: ParentRef[];
|
|
164
|
+
};
|
|
165
|
+
export type StreamSnapshot = {
|
|
166
|
+
turns: TurnReadResult[];
|
|
167
|
+
eventCursor: bigint;
|
|
168
|
+
};
|
|
169
|
+
export type StoreOptions = {
|
|
170
|
+
clock: () => bigint;
|
|
171
|
+
randomBytes: () => Uint8Array;
|
|
172
|
+
verifyHashIntegrity?: boolean;
|
|
173
|
+
};
|
|
174
|
+
export declare class Store {
|
|
175
|
+
#private;
|
|
176
|
+
readonly storage: IndexedDbStorage;
|
|
177
|
+
private readonly allows;
|
|
178
|
+
readonly options: Readonly<StoreOptions>;
|
|
179
|
+
constructor(storage: IndexedDbStorage, allows: (stream: string, owner: Uint8Array) => boolean, options: StoreOptions);
|
|
180
|
+
check(): void;
|
|
181
|
+
host<T>(fn: () => T): T;
|
|
182
|
+
authorize(stream: string, owner: Uint8Array): boolean;
|
|
183
|
+
stream(id: string): Stream;
|
|
184
|
+
run<T>(write: boolean, stream: string, program: Program<T>, notify?: (result: T) => boolean): Promise<T>;
|
|
185
|
+
subscribe(stream: string): ChangeSubscription;
|
|
186
|
+
close(): Promise<void>;
|
|
187
|
+
}
|
|
188
|
+
export declare class ChangeSubscription {
|
|
189
|
+
#private;
|
|
190
|
+
private readonly release;
|
|
191
|
+
constructor(release: () => void);
|
|
192
|
+
signal(): void;
|
|
193
|
+
drain(): boolean;
|
|
194
|
+
wait(): Promise<boolean>;
|
|
195
|
+
close(): void;
|
|
196
|
+
}
|
|
197
|
+
export declare class Stream {
|
|
198
|
+
readonly store: Store;
|
|
199
|
+
readonly id: string;
|
|
200
|
+
constructor(store: Store, id: string);
|
|
201
|
+
space(table: string): string;
|
|
202
|
+
/** Unsigned, local derived state. Only actual selected changes emit events. */
|
|
203
|
+
compareAndWriteIndex(expected: {
|
|
204
|
+
table: string;
|
|
205
|
+
key: Uint8Array;
|
|
206
|
+
value: Uint8Array | null;
|
|
207
|
+
}[], changes: {
|
|
208
|
+
table: string;
|
|
209
|
+
key: Uint8Array;
|
|
210
|
+
value: Uint8Array | null;
|
|
211
|
+
}[], options?: {
|
|
212
|
+
eventKeys?: {
|
|
213
|
+
table: string;
|
|
214
|
+
key: Uint8Array;
|
|
215
|
+
}[];
|
|
216
|
+
}): Promise<boolean>;
|
|
217
|
+
scanIndex(table: string, start: Uint8Array, limit: number): Promise<{
|
|
218
|
+
key: Uint8Array;
|
|
219
|
+
value: Uint8Array;
|
|
220
|
+
}[]>;
|
|
221
|
+
scanIndexReverse(table: string, end: Uint8Array | null, limit: number): Promise<{
|
|
222
|
+
key: Uint8Array;
|
|
223
|
+
value: Uint8Array;
|
|
224
|
+
}[]>;
|
|
225
|
+
writer(identity: Identity): Writer;
|
|
226
|
+
header(tx: KvTransaction, id: Uint8Array): Step<Header | undefined>;
|
|
227
|
+
counter(tx: KvTransaction, name: string): Step<bigint>;
|
|
228
|
+
append(tx: KvTransaction, table: string, value: Uint8Array): Step<bigint>;
|
|
229
|
+
reject(tx: KvTransaction, raw: Uint8Array, e: StoreError): Step<void>;
|
|
230
|
+
observe(tx: KvTransaction, id: Uint8Array): Step<void>;
|
|
231
|
+
turn(tx: KvTransaction, id: Uint8Array): Step<TurnSnapshot | undefined>;
|
|
232
|
+
turnFromHeader(tx: KvTransaction, id: Uint8Array, h: Header): Step<TurnSnapshot>;
|
|
233
|
+
ancestors(tx: KvTransaction, parents: ParentRef[]): Step<void>;
|
|
234
|
+
/** N3: the local-seal chain check — like `ancestors` but returns
|
|
235
|
+
* `false` instead of throwing on a missing ancestor (a partial
|
|
236
|
+
* boundary): the reply seals cryptographically regardless, and
|
|
237
|
+
* `hashVerified` says honestly whether the whole chain is locally
|
|
238
|
+
* verified. A conflicting claim (hash mismatch on a present turn)
|
|
239
|
+
* stays a typed error. Mirror of `chain_fully_verified` in
|
|
240
|
+
* src/store.rs. */
|
|
241
|
+
/** N017 P1-A: recompute one stored turn's body and compare it with its
|
|
242
|
+
* persisted seal hash. `false` means the local bytes contradict the
|
|
243
|
+
* admitted seal (only reachable when an earlier import skipped hash
|
|
244
|
+
* recomputation): the caller must not promote the turn. Mirror of
|
|
245
|
+
* `body_matches_seal` in src/store.rs. */
|
|
246
|
+
bodyMatchesSeal(tx: KvTransaction, h: Header): Step<boolean>;
|
|
247
|
+
chainFullyVerified(tx: KvTransaction, parents: ParentRef[]): Step<boolean>;
|
|
248
|
+
/** Semantic preparation performs no persistent writes. The returned program must not be caught as a frame rejection. */
|
|
249
|
+
prepare(tx: KvTransaction, u: Update, raw: Uint8Array, origin: 'local' | 'remote', admission?: Admission, conflicts?: ParentConflict[]): Step<Step<void>>;
|
|
250
|
+
indexParents(tx: KvTransaction, u: Update, insert: boolean): Step<void>;
|
|
251
|
+
insertPending(tx: KvTransaction, u: Update, raw: Uint8Array): Step<void>;
|
|
252
|
+
removePending(tx: KvTransaction, key: Uint8Array): Step<void>;
|
|
253
|
+
persistedUpdate(raw: Uint8Array, key: Uint8Array): Update;
|
|
254
|
+
drain(tx: KvTransaction, seeds: Uint8Array[], applied: UpdateRef[], admission?: Admission, conflicts?: ParentConflict[]): Step<void>;
|
|
255
|
+
importBatch(bytes: Uint8Array): Promise<ImportReport>;
|
|
256
|
+
/** N3 partial-replica admission (the reverse-history intake): frames
|
|
257
|
+
* are decoded, signature-verified and authorized exactly like the
|
|
258
|
+
* complete path, but a Create's parents are recorded as declared
|
|
259
|
+
* references (their turns need not be local — the seal's hash binds
|
|
260
|
+
* them cryptographically, and the backfill reconcile checks the claim
|
|
261
|
+
* when the parent arrives) and a Seal verifies this turn's content
|
|
262
|
+
* hash and signature only, never the ancestor chain. Levels are
|
|
263
|
+
* honest: nothing here sets `hashVerified` for a turn with parents.
|
|
264
|
+
* Mirror of `import_partial_batch` in src/store.rs. */
|
|
265
|
+
importPartialBatch(bytes: Uint8Array): Promise<ImportReport>;
|
|
266
|
+
importInner(bytes: Uint8Array, admission: Admission): Promise<ImportReport>;
|
|
267
|
+
/** The verification level of one turn (N3, Spec §88): the display
|
|
268
|
+
* layer's contract. `ancestorsVerified` is exactly the existing
|
|
269
|
+
* `hashVerified` meaning; `selfVerified` requires this turn's stored
|
|
270
|
+
* body to have been checked against its seal (`bodyVerified` — a seal
|
|
271
|
+
* whose hash recomputation was skipped proves only the signature over
|
|
272
|
+
* the declared hash); stored-but-unsealed-or-unchecked is `provisional`;
|
|
273
|
+
* no record is `notRetrieved`. Mirror of `verification` in
|
|
274
|
+
* src/store.rs. */
|
|
275
|
+
verification(id: Uint8Array): Promise<Verification>;
|
|
276
|
+
readResultWithTurn(tx: KvTransaction, id: Uint8Array, turn: TurnSnapshot | undefined): Step<TurnReadResult>;
|
|
277
|
+
readResult(tx: KvTransaction, id: Uint8Array): Step<TurnReadResult>;
|
|
278
|
+
readTurn(id: Uint8Array): Promise<TurnReadResult>;
|
|
279
|
+
readTurns(ids: Uint8Array[]): Promise<TurnReadResult[]>;
|
|
280
|
+
scanTurns(query: {
|
|
281
|
+
start?: Uint8Array;
|
|
282
|
+
end?: Uint8Array;
|
|
283
|
+
limit: number;
|
|
284
|
+
}): Promise<TurnReadResult[]>;
|
|
285
|
+
readStream(): Promise<TurnReadResult[]>;
|
|
286
|
+
/** The header-level tri-state read, mirroring `readResult` without ever
|
|
287
|
+
* materializing content (G026): the header row plus the one-row pending
|
|
288
|
+
* probe only. */
|
|
289
|
+
headerResult(tx: KvTransaction, id: Uint8Array): Step<TurnHeaderResult>;
|
|
290
|
+
headerResultWithHeader(tx: KvTransaction, id: Uint8Array, header: Header | undefined): Step<TurnHeaderResult>;
|
|
291
|
+
/** One Turn's header with the same tri-state as `readTurn`, never reading
|
|
292
|
+
* content (discovery and other metadata-only consumers must not pay for
|
|
293
|
+
* the projection). */
|
|
294
|
+
readTurnHeader(id: Uint8Array): Promise<TurnHeaderResult>;
|
|
295
|
+
/** Forward keyset page of Turn headers in ascending TurnID order,
|
|
296
|
+
* strictly newer than `after` (exclusive — the same keyset discipline as
|
|
297
|
+
* `turnHeadersBefore`, mirrored). `after === undefined` pages from the
|
|
298
|
+
* beginning. `n === 0` returns empty; larger `n` clamps to
|
|
299
|
+
* MAX_PAGE_HEADERS (the clamp bounds RETURNED rows, so a full page never
|
|
300
|
+
* ends a continuation early). Each row carries the tri-state; the content
|
|
301
|
+
* projection is never read. */
|
|
302
|
+
turnHeadersAfter(after: Uint8Array | undefined, n: number): Promise<TurnHeaderResult[]>;
|
|
303
|
+
/** One reverse keyset page of lightweight headers. A single bounded
|
|
304
|
+
* scanReverse decodes each returned per-turn row in place; content lives
|
|
305
|
+
* in projection blocks and is never read for a header page. */
|
|
306
|
+
pageHeaders(tx: KvTransaction, end: Uint8Array | undefined, n: number): Step<TurnHeader[]>;
|
|
307
|
+
/** Newest `n` Turn headers in descending TurnID order; `n === 0` returns
|
|
308
|
+
* empty, larger `n` clamps to MAX_PAGE_HEADERS. Pages are per-request
|
|
309
|
+
* snapshots: re-fetch after change notifications (subscribeChanges). */
|
|
310
|
+
latestTurnHeaders(n: number): Promise<TurnHeader[]>;
|
|
311
|
+
/** Keyset page of headers strictly older than `before` (exclusive) in
|
|
312
|
+
* descending TurnID order; `before` need not exist. A late-arriving older
|
|
313
|
+
* Turn lands in its byte-order position on the next request; pages are not
|
|
314
|
+
* live-merged. */
|
|
315
|
+
turnHeadersBefore(before: Uint8Array, n: number): Promise<TurnHeader[]>;
|
|
316
|
+
readValue(id: Uint8Array, path: ValuePath): Promise<{
|
|
317
|
+
value: JsonValue;
|
|
318
|
+
nextSeq: bigint;
|
|
319
|
+
}>;
|
|
320
|
+
readText(id: Uint8Array, path: ValuePath, start: bigint, end: bigint): Promise<{
|
|
321
|
+
text: string;
|
|
322
|
+
nextSeq: bigint;
|
|
323
|
+
}>;
|
|
324
|
+
snapshot(): Promise<StreamSnapshot>;
|
|
325
|
+
eventsAfter(after: bigint, n: number): Promise<EventRecord[]>;
|
|
326
|
+
pendingTurns(after: Uint8Array | undefined, n: number): Promise<Uint8Array[]>;
|
|
327
|
+
missingDependencies(ids: Uint8Array[]): Promise<MissingDependencies[]>;
|
|
328
|
+
exportUpdates(id: Uint8Array, fromSeq: bigint, n: number): Promise<Uint8Array>;
|
|
329
|
+
exportTurns(ids: Uint8Array[]): Promise<Uint8Array>;
|
|
330
|
+
subscribeChanges(): ChangeSubscription;
|
|
331
|
+
watch(): Promise<{
|
|
332
|
+
snapshot: StreamSnapshot;
|
|
333
|
+
subscription: ChangeSubscription;
|
|
334
|
+
}>;
|
|
335
|
+
subscribeOutgoing(consumer: string): OutgoingSubscription;
|
|
336
|
+
}
|
|
337
|
+
export declare class Writer {
|
|
338
|
+
readonly stream: Stream;
|
|
339
|
+
private readonly identity;
|
|
340
|
+
constructor(stream: Stream, identity: Identity);
|
|
341
|
+
create(parents: ParentRef[], content: JsonValue): Promise<Commit>;
|
|
342
|
+
edit(turnId: Uint8Array, expectedNextSeq: bigint, ops: ContentOp[]): Promise<Commit>;
|
|
343
|
+
seal(turnId: Uint8Array, expectedNextSeq: bigint): Promise<Commit>;
|
|
344
|
+
writeBatch(writes: Write[], indexPuts?: IndexPut[], expectedEventCursor?: bigint): Promise<Commit>;
|
|
345
|
+
/** Local retry identity, scoped to this stream and signer. Receipt and Create
|
|
346
|
+
* commit together; this is not cross-author business-key deduplication. */
|
|
347
|
+
createOnce(key: Uint8Array, parents: ParentRef[], content: JsonValue, expectedEventCursor?: bigint): Promise<{
|
|
348
|
+
turnId: Uint8Array;
|
|
349
|
+
created: boolean;
|
|
350
|
+
}>;
|
|
351
|
+
private writeBatchInternal;
|
|
352
|
+
}
|
|
353
|
+
export interface DeliveryReceipt {
|
|
354
|
+
readonly receipt: unique symbol;
|
|
355
|
+
}
|
|
356
|
+
export type OutgoingBatch = {
|
|
357
|
+
updates: Uint8Array;
|
|
358
|
+
receipt: DeliveryReceipt;
|
|
359
|
+
};
|
|
360
|
+
/** Internal sender capability. Its identity, original bytes and scoped receipt are private. */
|
|
361
|
+
export interface PreparedReceipt {
|
|
362
|
+
readonly preparedReceipt: unique symbol;
|
|
363
|
+
bytes(): Uint8Array;
|
|
364
|
+
}
|
|
365
|
+
export declare class OutgoingSubscription {
|
|
366
|
+
readonly stream: Stream;
|
|
367
|
+
readonly consumer: string;
|
|
368
|
+
constructor(stream: Stream, consumer: string);
|
|
369
|
+
nextBatch(options: {
|
|
370
|
+
maxUpdates: number;
|
|
371
|
+
maxBytes: number;
|
|
372
|
+
}): Promise<OutgoingBatch | null>;
|
|
373
|
+
private consumerCursor;
|
|
374
|
+
private readDurablePending;
|
|
375
|
+
/** @internal Pins exact bytes before transport. Does not call a host or confirm delivery. */
|
|
376
|
+
_durablePrepare(options: {
|
|
377
|
+
maxUpdates: number;
|
|
378
|
+
maxBytes: number;
|
|
379
|
+
}): Promise<PreparedReceipt | null>;
|
|
380
|
+
/** @internal Confirms only a genuine prepared token bound to this Store/stream/consumer. */
|
|
381
|
+
_durableConfirm(token: PreparedReceipt): Promise<void>;
|
|
382
|
+
ack(receipt: DeliveryReceipt): Promise<void>;
|
|
383
|
+
}
|
|
384
|
+
export {};
|