@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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 LoroDev Team
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
# Loro Roost for TypeScript
|
|
2
|
+
|
|
3
|
+
Experimental TypeScript package with IndexedDB storage, a chunked Turn state machine
|
|
4
|
+
and experimental v1 codec/cryptography. It supports local writes, remote import,
|
|
5
|
+
seal verification, pending dependencies, outbox and stream-scoped change hints.
|
|
6
|
+
The sync entry provides explicit Streams authentication and host payload crypto.
|
|
7
|
+
Lody runtime integration, device support and stable APIs remain separate
|
|
8
|
+
acceptance work. Wire v1 and storage layout can change. Unsealed updates are
|
|
9
|
+
provisional and unsigned; production E2EE is not implemented. Author
|
|
10
|
+
equivocation has no convergence guarantee.
|
|
11
|
+
The `Inbox` module adds atomic raw receipt/cursor storage, without authenticating
|
|
12
|
+
or applying those bytes.
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npm install @loro-dev/roost@0.1.0
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
For source development and browser tests:
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
pnpm install --frozen-lockfile
|
|
22
|
+
pnpm check
|
|
23
|
+
pnpm test
|
|
24
|
+
# Only one engine, when installed:
|
|
25
|
+
BROWSERS=chromium pnpm test
|
|
26
|
+
# Install test browsers if this machine does not already have them:
|
|
27
|
+
pnpm exec playwright install chromium webkit
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Tests launch genuine Chromium and WebKit against a loopback-only fixture server
|
|
31
|
+
and fresh browser contexts. There is no fake-indexeddb, external service, sleep or
|
|
32
|
+
timing race. A test deadline only terminates failures; synchronization depends on
|
|
33
|
+
actual request/transaction events. WebKit desktop tests are not iOS device tests.
|
|
34
|
+
|
|
35
|
+
## Transaction API
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import { IndexedDbStorage } from '@loro-dev/roost';
|
|
39
|
+
|
|
40
|
+
const storage = await IndexedDbStorage.open('roost-example');
|
|
41
|
+
const key = new Uint8Array([1]);
|
|
42
|
+
await storage.transact(true, function* (tx) {
|
|
43
|
+
const previous = yield* tx.get('projection', key);
|
|
44
|
+
yield* tx.put('projection', key, new Uint8Array([previous?.[0] ?? 0, 42]));
|
|
45
|
+
yield* tx.put('outbox', key, new Uint8Array([42]));
|
|
46
|
+
}); // Resolves only after IndexedDB's complete event.
|
|
47
|
+
await storage.close();
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`transact(write, program)` invokes the synchronous generator once, with no retry.
|
|
51
|
+
`yield* tx.get/put/delete/scan` resumes in a request event while IndexedDB permits
|
|
52
|
+
new requests. This low-level generator contract is deliberately different from
|
|
53
|
+
Rust's synchronous callback. The `Store` message API exposes ordinary
|
|
54
|
+
Promises above it. Do not await network, worker computation, timers or unrelated
|
|
55
|
+
Promises in a transaction. Programs must do finite synchronous computation; no execution-time or memory budget is imposed here. Empty-scan chains use an iterative driver, not recursive callbacks. Compute outside and recheck any dependent versions in
|
|
56
|
+
the transaction. No keepalive requests are issued.
|
|
57
|
+
|
|
58
|
+
The transaction methods use arbitrary byte keys and byte values with a string
|
|
59
|
+
namespace. `get` returns `undefined` for absence; `put` replaces; `delete` of an
|
|
60
|
+
absent key succeeds. `scan(space, start, end, limit)` uses byte lexicographic
|
|
61
|
+
order, inclusive start and exclusive end; zero limit or reversed/empty intervals
|
|
62
|
+
return no rows. Pass `undefined` for no end; the limit is always explicit. Keys and values are copied, including offset views. Inputs are
|
|
63
|
+
snapshotted when an operation is created, not when it is eventually yielded.
|
|
64
|
+
|
|
65
|
+
All namespaces share one private IDB object store with `[namespace, binaryKey]`
|
|
66
|
+
keys. Thus projection/oplog/outbox/cursor namespaces can commit or abort together,
|
|
67
|
+
without defining an object store for each namespace. This is local layout v1,
|
|
68
|
+
not a new Roost wire/schema version or Rust RSP1 interchange format. Readonly
|
|
69
|
+
transactions reject mutations. Overlapping writes from different connections are
|
|
70
|
+
serialized by IndexedDB, including read-modify-write programs.
|
|
71
|
+
|
|
72
|
+
A thrown exception, `tx.abort()` (even if caught), native request failure or
|
|
73
|
+
invalid yield aborts the transaction. Only opaque, single-use operations belonging
|
|
74
|
+
to that transaction are accepted; promises, async generators and borrowed
|
|
75
|
+
operations fail. Native abort rejects after rollback even when earlier requests
|
|
76
|
+
succeeded. A request error is fatal; the generator cannot catch and recover that
|
|
77
|
+
individual request. Retained transaction views cannot be used after the program.
|
|
78
|
+
|
|
79
|
+
`close()` immediately rejects new work and waits for already-created transactions
|
|
80
|
+
to complete or abort. It is idempotent; existing work is not cancelled. A
|
|
81
|
+
`versionchange` event initiates close automatically, allowing another connection
|
|
82
|
+
to upgrade. Version 1 must contain exactly the expected key/value object store;
|
|
83
|
+
unknown versions or layouts are refused without resetting user data. Blocked open
|
|
84
|
+
fails explicitly, and a subsequently opened connection is closed instead of leaked.
|
|
85
|
+
There is no migration, cross-tab broadcast, quota recovery or data deletion API.
|
|
86
|
+
|
|
87
|
+
Writes request IndexedDB's `strict` durability hint. `complete` proves the browser's
|
|
88
|
+
commit boundary; it is not proof against device failure, browser storage eviction,
|
|
89
|
+
quota exhaustion or an OS wiping this origin. Pending messages and keys still need
|
|
90
|
+
product-level retention and recovery policies.
|
|
91
|
+
|
|
92
|
+
References: [W3C transaction lifecycle](https://www.w3.org/TR/IndexedDB/#transaction-lifecycle),
|
|
93
|
+
[transaction scheduling](https://www.w3.org/TR/IndexedDB/#transaction-scheduling).
|
|
94
|
+
Owner: P1-03.
|
|
95
|
+
|
|
96
|
+
## Durable receipt ledger
|
|
97
|
+
|
|
98
|
+
`Inbox.open(storage, stream, source, limits)` shares the same IndexedDB backend.
|
|
99
|
+
Use `receive(previousCursor, nextCursor, bytes)` to commit raw data and its receive
|
|
100
|
+
position together. `null` is the initial cursor; an empty byte cursor is distinct.
|
|
101
|
+
Exact historical retries return `duplicate` without rewinding the head; stale
|
|
102
|
+
predecessors and conflicting cursor reuse fail. Sequences and retained-byte quotas
|
|
103
|
+
are bigint values; lengths and page sizes must be explicit safe integers.
|
|
104
|
+
`state()` and `records(afterSequence, limit)` expose committed local receipts.
|
|
105
|
+
|
|
106
|
+
Source names are routing metadata, not identity proofs. No authentication,
|
|
107
|
+
Roost import, verification or transport is performed. Record/index bytes count
|
|
108
|
+
towards a per-namespace logical quota; physical storage and the total number of
|
|
109
|
+
namespaces need host policy. There is no GC or implicit reset. The browser-private
|
|
110
|
+
layout does not share Rust inbox state records.
|
|
111
|
+
|
|
112
|
+
## Experimental v1 codec
|
|
113
|
+
|
|
114
|
+
`encodeBatch` / `decodeBatch` in `codec.ts` implement current Rust v1 bytes.
|
|
115
|
+
`JsonValue` in `json.ts` uses `Map` for objects, explicit bigint u64/i64 integers
|
|
116
|
+
and an explicit f64 variant (including negative zero). Native JS numbers and
|
|
117
|
+
plain objects are not implicitly converted; the eventual application JSON API is
|
|
118
|
+
not settled. UTF8 and surrogate validation is strict, scalar-key ordering is
|
|
119
|
+
canonical, and decode refuses noncanonical spellings rather than repairing them.
|
|
120
|
+
|
|
121
|
+
Codec acceptance is syntax only: it does not authenticate the source, validate a
|
|
122
|
+
seal, apply a Turn or enforce business ownership. Browser tests build the Rust
|
|
123
|
+
`codec_interop` example and compare real Rust/TS bytes in both directions. The
|
|
124
|
+
fixture includes all operations and finite floating-point samples, not an
|
|
125
|
+
exhaustive IEEE proof. Running these tests requires the root Cargo dependencies
|
|
126
|
+
to have been fetched; the oracle build uses `--offline --locked`.
|
|
127
|
+
|
|
128
|
+
## Hash, signatures and IDs
|
|
129
|
+
|
|
130
|
+
`crypto.ts` provides `nodePreimage`, `nodeHash`, `isValidOwner` and
|
|
131
|
+
`verifySealSignature`; `identity.ts` provides an in-memory `Identity` signer and
|
|
132
|
+
`nextTurnId` with explicit clock, observed maximum and random-source inputs. The
|
|
133
|
+
strict signature wrapper uses maintained noble primitives to match Rust dalek
|
|
134
|
+
verification; noble's default verifier alone has different acceptance rules.
|
|
135
|
+
A decodable public key is not an authorized device. A valid signature over a
|
|
136
|
+
claimed hash is not proof that received content matches that hash.
|
|
137
|
+
|
|
138
|
+
Fixed vectors and strict counterexamples run in both browsers. These helpers do
|
|
139
|
+
not persist keys or authenticate transports. The Store below persists admitted
|
|
140
|
+
observed maxima atomically with message state.
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
## Message Store
|
|
144
|
+
|
|
145
|
+
`new Store(storage, allows, {clock, randomBytes, verifyHashIntegrity?})` shares the
|
|
146
|
+
same IndexedDB owner as `Inbox`. Clock returns bigint milliseconds; randomBytes
|
|
147
|
+
returns 16 bytes. Both callbacks are explicit, synchronous host inputs. The
|
|
148
|
+
allowlist callback checks a claimed owner, not proof of authorship. The user accepts
|
|
149
|
+
claimed-author spoofing during streaming; per-device source authentication is not
|
|
150
|
+
a prerequisite for importing provisional updates. Service access controls remain.
|
|
151
|
+
|
|
152
|
+
`store.stream(id)` offers `writer(identity)`, `importBatch`, `readTurn`,
|
|
153
|
+
`readTurns`, `scanTurns`, `readValue`, `readText`, `snapshot`, `eventsAfter`,
|
|
154
|
+
`pendingTurns`, `missingDependencies`, `exportUpdates` and `exportTurns`.
|
|
155
|
+
Writer `create`, `edit`, `seal` and `writeBatch` return committed update references.
|
|
156
|
+
Sequences, text positions and array positions are bigint. Text positions count
|
|
157
|
+
Unicode scalars. Objects and numbers use the lossless `JsonValue` representation
|
|
158
|
+
above; no native JS object/Number coercion is implied.
|
|
159
|
+
|
|
160
|
+
Local batches commit content blocks, Turn headers, operation log, pending indexes,
|
|
161
|
+
observed ID maximum, outgoing log and events in one transaction. A failed later
|
|
162
|
+
operation rolls back earlier operations. Import isolates semantic frame rejection,
|
|
163
|
+
but storage failures abort the entire batch. Remote import never echoes to outbox.
|
|
164
|
+
Hash recomputation defaults on; disabling it never disables seal signature checks.
|
|
165
|
+
Corrupt persisted metadata is an error, not an empty or repaired Turn.
|
|
166
|
+
|
|
167
|
+
Text uses 1024-scalar blocks and arrays use 128-reference pages. Tail append and
|
|
168
|
+
text ranges access necessary blocks; variable-length middle splices may rewrite
|
|
169
|
+
the affected suffix. Objects retain field tables. Whole snapshots and seals may
|
|
170
|
+
read complete content. Stored bytes/depth summaries enforce the complete Turn
|
|
171
|
+
budget before writes, including Rust-compatible metadata overhead.
|
|
172
|
+
|
|
173
|
+
`subscribeOutgoing(consumer).nextBatch(limits)` returns bytes plus an opaque,
|
|
174
|
+
Store/stream/consumer-scoped receipt; `ack(receipt)` advances that consumer only.
|
|
175
|
+
An unacknowledged prefix survives reopen. When a durable sender has pinned a
|
|
176
|
+
batch, ordinary ack cannot advance past it; use sender confirmation.
|
|
177
|
+
|
|
178
|
+
`watch()` registers a subscription before taking its consistent snapshot/event
|
|
179
|
+
cursor. Hints coalesce; use the durable event log or reread state after a hint.
|
|
180
|
+
Hints are local to this Store, not cross-tab broadcasts. Close subscriptions when
|
|
181
|
+
finished. `store.close()` rejects new work, releases subscriptions and waits for
|
|
182
|
+
started transactions; it does **not** close the shared IndexedDB owner. After all
|
|
183
|
+
clients (including Inbox) finish, call `storage.close()` separately. Host callbacks
|
|
184
|
+
cannot reenter or close Store, and cannot return Promises.
|
|
185
|
+
|
|
186
|
+
Scope/evidence: projection,
|
|
187
|
+
state machine,
|
|
188
|
+
real SQLite/browser interop.
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
## Durable one-step sender
|
|
192
|
+
|
|
193
|
+
`new DurableSender(outgoing).sendNext(limits, async bytes => { ... })` first pins
|
|
194
|
+
an exact batch in IndexedDB, then invokes the host outside a transaction. A fulfilled
|
|
195
|
+
callback asserts that the remote endpoint durably accepted those bytes under the
|
|
196
|
+
host's transport contract. Only then does a transaction advance the consumer and
|
|
197
|
+
remove the pending pair. The helper itself cannot prove remote durability or
|
|
198
|
+
identity. It is not a background network loop.
|
|
199
|
+
|
|
200
|
+
After failure or reopen, the same consumer retries the original bytes even after
|
|
201
|
+
new edits or larger limits. Limits too small for the pinned batch fail without
|
|
202
|
+
sending. Concurrent senders may deliver duplicates; a late confirmation cannot
|
|
203
|
+
remove a later pinned batch. Remote acceptance followed by local confirmation
|
|
204
|
+
failure retains a safe duplicate retry.
|
|
205
|
+
|
|
206
|
+
The callback receives a copy. Visible mutation or transfer/detachment followed by
|
|
207
|
+
success causes a local failure, retaining the original batch. Callback throws stay
|
|
208
|
+
transport failures with their original `cause`, including non-Error JS values.
|
|
209
|
+
`SendError.kind` distinguishes `local` from `transport`; neither means an earlier
|
|
210
|
+
remote write was rolled back. Stop the host loop and await in-flight sendNext calls
|
|
211
|
+
before closing shared storage. Store.close does not wait for external transport;
|
|
212
|
+
confirmation after close fails locally and the pinned batch survives restart.
|
|
213
|
+
|
|
214
|
+
Evidence: browser sender Owner.
|
|
215
|
+
|
|
216
|
+
## Durable replay and batch framing
|
|
217
|
+
|
|
218
|
+
`DurableReplay.open(inbox, stream, limits).step()` processes one complete RST1
|
|
219
|
+
batch receipt. Import commits first; its report and processed position commit
|
|
220
|
+
together afterwards. A crash between them safely repeats import. Quota/storage
|
|
221
|
+
failures keep the receipt for retry. Processed does not mean applied or verified.
|
|
222
|
+
Use the exact same storage owner and stream, and await outstanding steps before
|
|
223
|
+
closing storage. Original receipts and reports are retained; there is no GC.
|
|
224
|
+
|
|
225
|
+
`BatchFramer` in `framing.ts` accepts windows up to 64 KiB and returns at most one
|
|
226
|
+
complete batch per push, with the number of consumed bytes. It handles fragmented
|
|
227
|
+
and concatenated batches without changing payload bytes. Call `finish` only at
|
|
228
|
+
final EOF, not on cancellation or a temporary empty response. It is an in-memory
|
|
229
|
+
parser; durable tail handling is provided by DurableFraming below. The actual
|
|
230
|
+
Streams adapter remains unfinished.
|
|
231
|
+
Never pass arbitrary HTTP chunks directly to DurableReplay.
|
|
232
|
+
|
|
233
|
+
Evidence: replay,
|
|
234
|
+
framing and remaining work.
|
|
235
|
+
|
|
236
|
+
## Durable fragmented receipts
|
|
237
|
+
|
|
238
|
+
`DurableFraming.open(rawInbox, batchInbox)` uses two namespaces on the same storage
|
|
239
|
+
owner and logical stream. Call `step()` to process at most one 64KiB window or
|
|
240
|
+
receipt transition. `restoring` rebuilds an unfinished batch after restart;
|
|
241
|
+
`progress` and `batch` mean more work may remain; `idle` means no currently saved
|
|
242
|
+
raw bytes remain to scan. `invalid` preserves the bad tail and stops.
|
|
243
|
+
|
|
244
|
+
The completed batch and scan checkpoint commit in one transaction. Use batchInbox
|
|
245
|
+
with DurableReplay, never rawInbox. Original raw offsets remain opaque; derived
|
|
246
|
+
cursors are explicitly local receipt/byte positions. Quota or native transaction
|
|
247
|
+
failure leaves the checkpoint for retry. Await an active step before closing the
|
|
248
|
+
owner; overlapping calls on one bridge return busy. Only call `finish()` after
|
|
249
|
+
confirmed final remote EOF, repeating until end/invalid. New raw data after end
|
|
250
|
+
is an explicit consistency error, not silently ignored.
|
|
251
|
+
|
|
252
|
+
No background transport, automatic repair or GC is included. A restart may reread
|
|
253
|
+
one unfinished batch; the first raw record read still loads its complete body.
|
|
254
|
+
Implementation and real-browser evidence.
|
|
255
|
+
|
|
256
|
+
## Consumer entry points and pinned SDK
|
|
257
|
+
|
|
258
|
+
Import the experimental application surface from `@loro-dev/roost`
|
|
259
|
+
and synchronization from `@loro-dev/roost/sync`. The business adapter is
|
|
260
|
+
`@loro-dev/roost/lody-history`. Storage keys and
|
|
261
|
+
internal record DTOs are not application exports. Pin the exact artifact until
|
|
262
|
+
the Lody consumer contract is accepted. Content uses lossless `JsonValue`;
|
|
263
|
+
ordinary JavaScript Number/object conversion is not implicit.
|
|
264
|
+
|
|
265
|
+
`Link.uploadCycle` runs durable discovery before flushing target work.
|
|
266
|
+
`Executor.discoverCycle` reads local Changed events, so applied P2P/server imports
|
|
267
|
+
with older Turn IDs are discovered after restart without a `discoverTurns` call.
|
|
268
|
+
Tasks and each target's event checkpoint commit together; target coverage remains
|
|
269
|
+
the confirmed lower bound of exact operations, and imported updates do not enter
|
|
270
|
+
the core outbox. Discovery page size bounds each page, while `maxSend` bounds only
|
|
271
|
+
sends. Partial replicas keep directed `Link.bridgeTurns` and its `waitingParent`
|
|
272
|
+
result for missing dependencies. See the discovery and upgrade contract.
|
|
273
|
+
|
|
274
|
+
`pnpm pack:consumer -- /absolute/output/directory` builds the npm tarball and
|
|
275
|
+
checks its public entries. It depends on the exact registry release
|
|
276
|
+
`@loro-dev/streams-client@0.8.0`, with no bundled SDK. `pnpm check:consumer`
|
|
277
|
+
installs that tarball into a fresh project with a fresh npm cache and checks
|
|
278
|
+
the root, `./sync`, and `./lody-history` exports.
|
|
279
|
+
|
|
280
|
+
IndexedDB container version is now 2. Opening a valid version-1 database upgrades
|
|
281
|
+
only its version, retaining all records; incompatible layouts abort the upgrade.
|
|
282
|
+
Older version-1 openers are refused. Existing connections must close on
|
|
283
|
+
versionchange; a blocked upgrade is an error, never a reason to delete data.
|
|
284
|
+
|
|
285
|
+
The experimental `./lody-history` entry provides the shared browser/Node business
|
|
286
|
+
envelope. `NodeLodyHistory` persists business bindings, diagnostics and its processed
|
|
287
|
+
local event cursor through the single SQLite owner. Each page consumes at most 128
|
|
288
|
+
events and atomically commits its derived rows and cursor, comparing the prior
|
|
289
|
+
cursor to reject stale concurrent work. Identity lookups use database keys; normal
|
|
290
|
+
reopen processes only the event backlog. Existing databases without this index
|
|
291
|
+
need one resumable initial rebuild. First-page reads still wait for outstanding
|
|
292
|
+
indexing, so their cost includes that backlog, not only the returned page.
|
|
293
|
+
|
|
294
|
+
Browser and Node batch recovery scan a persistent pending-receipt index instead of every
|
|
295
|
+
completed receipt. P2P imports and delayed pending application enter the same local
|
|
296
|
+
event log, even for old TurnIDs; these private indexes and cursors are not copied
|
|
297
|
+
between peers. Imported updates still do not enter the core outbox automatically.
|
|
298
|
+
Concurrent plans retain their original processed cursor, retrying when intervening
|
|
299
|
+
events invalidate their absence/revision reads. Neither this entry nor the generic
|
|
300
|
+
package automatically replaces Lody runtime storage.
|
|
301
|
+
|
|
302
|
+
Imported messages now rebuild local publication membership during read-side
|
|
303
|
+
catch-up or `recoverPendingBatches()` (which returns `Promise<void>`). New direct
|
|
304
|
+
messages carry original Create intent; batch members and explicitly promoted
|
|
305
|
+
private messages use verified sealed publication receipts. A receiver can derive
|
|
306
|
+
these indexes without an admitted local signing identity, and never replays a
|
|
307
|
+
remote author's pending commands or adds imported operations to outbox.
|
|
308
|
+
Missing targets/seqs wait in a persistent reverse index. One receipt's previously
|
|
309
|
+
hidden members become visible together; ordinary P2P edits to already visible
|
|
310
|
+
messages still follow their applied prefixes. See the
|
|
311
|
+
format and legacy compatibility contract.
|
|
312
|
+
|
|
313
|
+
The independent publication cursor performs a one-time, resumable catch-up for
|
|
314
|
+
existing databases; initial reads wait for it, so the upgrade can cost a history
|
|
315
|
+
scan. Subsequent reopens consume only new local events. Old committed receipts
|
|
316
|
+
are supported, including zero-ID placeholders, but an old standalone sealed
|
|
317
|
+
message cannot reveal whether its author chose `publish:false`. It stays hidden
|
|
318
|
+
on a new receiver until the original author repeats `accept` with its original
|
|
319
|
+
input and synchronizes the resulting signed publication Turn. New hidden messages
|
|
320
|
+
also stay hidden until explicitly promoted; sealing alone does not publish them.
|
|
321
|
+
Recovery does not change a message's verification level. Implementation evidence:
|
|
322
|
+
publication recovery plan.
|
|
323
|
+
|
|
324
|
+
Published message pages use the publication index for membership/order and batch
|
|
325
|
+
read current Turn bodies. `append` and `finish` do not maintain a second body
|
|
326
|
+
snapshot. A local event-cursor fence retries reads that overlap a commit, so a
|
|
327
|
+
page cannot combine membership from before a batch with content from after it.
|
|
328
|
+
Already published incomplete Turns expose their applied prefix. Unsealed content
|
|
329
|
+
remains provisional; the projected `sealed` flag is not a verification level.
|
|
330
|
+
|
|
331
|
+
Use the shared cache for a live list on either adapter:
|
|
332
|
+
|
|
333
|
+
```ts
|
|
334
|
+
const view = history.createMessageView(40);
|
|
335
|
+
const initial = await view.initialize(); // latest 40, oldest first
|
|
336
|
+
// In the host's change callback/poll loop:
|
|
337
|
+
const delta = await view.refresh();
|
|
338
|
+
// Patch delta.changed; delta.messages supplies the full retained order.
|
|
339
|
+
// Unchanged rows retain object identity and their bodies are not read again.
|
|
340
|
+
const older = await view.loadOlder(); // another page when hasMoreOlder is true
|
|
341
|
+
view.dispose();
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
`refresh` consumes bounded pages of the database's local event log and deduplicates
|
|
345
|
+
affected TurnIDs before reading their published bodies. One changed message in a
|
|
346
|
+
40-message cache reads only that body, including when many append events were
|
|
347
|
+
coalesced. Edits older than the loaded interval read no bodies. Newly published
|
|
348
|
+
messages in the interval are added; older ones remain available through
|
|
349
|
+
`loadOlder`. New arrivals do not evict loaded rows. Methods serialize, and failures
|
|
350
|
+
or disposal leave the previous cache/cursor intact. Sustained concurrent commits
|
|
351
|
+
can return `stale` after four attempts; the host may retry. Treat returned rows and
|
|
352
|
+
nested content as read-only. The in-memory cursor belongs to this cache, not a
|
|
353
|
+
standalone restart checkpoint. A fresh view loads a fresh page after reopen.
|
|
354
|
+
|
|
355
|
+
`readProjectedMessagesById(ids)` also provides a deduplicated, consistent point
|
|
356
|
+
read for up to 1000 TurnIDs, excluding unpublished IDs. Hosts still own wakeup,
|
|
357
|
+
polling and rendering. Browser hosts should subscribe before initializing the
|
|
358
|
+
view; the Node adapter currently uses host polling/change hints. The external
|
|
359
|
+
Lody UI is not wired by this library change.
|
|
360
|
+
|
|
361
|
+
New records in the private `lody_history_published_v1` table have a `version: "2"`
|
|
362
|
+
membership-only value. Current readers also accept legacy full-snapshot values;
|
|
363
|
+
there is no separate startup scan solely to convert these membership values
|
|
364
|
+
(the publication catch-up above still applies). Reading an unchanged legacy row incurs
|
|
365
|
+
its old index payload until republished, but never uses that payload as current
|
|
366
|
+
content. New receipt publication lists contain compact references; legacy lists
|
|
367
|
+
and batch recovery command/base snapshots remain readable. Stop older adapters
|
|
368
|
+
before opening stores written with this layout or the new `indexChanged` local
|
|
369
|
+
events, and ship matching browser/Node client and owner revisions.
|
|
370
|
+
|
|
371
|
+
For a reproducible SQLite comparison, build the Node owner at the repository root
|
|
372
|
+
with `cargo +1.98.1 build --locked --bin roost-node-owner`, then run in `ts/`:
|
|
373
|
+
|
|
374
|
+
```sh
|
|
375
|
+
pnpm build
|
|
376
|
+
node scripts/history-publication-bench.mjs --history 1000 --samples 7 --output /tmp/publication-bench.json
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
The checkout must contain Git commit `4a282c826d54434f596ab6183ead7222e5a397f4`;
|
|
380
|
+
the script reads that local object and does not fetch it. Archive/packed or shallow
|
|
381
|
+
checkouts missing that commit cannot load the baseline. The example compares
|
|
382
|
+
that adapter with current code using the same Rust owner. It covers 4/16/64 KiB messages, 40-row reads, owner reopen, single-row
|
|
383
|
+
refresh and imported publication recovery. `--history`, `--sizes`, `--samples`
|
|
384
|
+
and `--binary` control the fixture. Output includes latency, row counts, actual
|
|
385
|
+
body/field/Create reads, event records and IPC requests. It asserts one body read
|
|
386
|
+
for a single change and zero old-event/Create reads after caught-up reopen.
|
|
387
|
+
The old adapter's empty imported list is a correctness failure, not equivalent
|
|
388
|
+
work completed faster. This measures the adapter/storage path without Lody UI.
|
|
389
|
+
`--history` sets the local page/refresh/reopen fixture size. Each import sample
|
|
390
|
+
uses a fresh receiver with 40 messages; the batch variant sends two receipts of
|
|
391
|
+
20 messages each. Reopen timing excludes owner process startup/ready and leaves
|
|
392
|
+
the OS filesystem cache warm. Latencies are observations, not CI thresholds.
|
|
393
|
+
Recorded example: 2026-09-17 results and measurement limits.
|
|
394
|
+
|
|
395
|
+
Host payload crypto may return a Promise (`AsyncPayloadCrypto`), including
|
|
396
|
+
WebCrypto. Encryption and decryption are awaited outside storage transactions;
|
|
397
|
+
failed transforms never fall back to plaintext. See RSE1.
|
package/dist/codec.d.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { type JsonValue } from './json.js';
|
|
2
|
+
export declare const MAX_FRAME: number;
|
|
3
|
+
export declare const MAX_BATCH: number;
|
|
4
|
+
export declare const MAX_UPDATES = 4096;
|
|
5
|
+
export declare const MAX_PATH_SEGMENTS = 128;
|
|
6
|
+
export type PathSegment = {
|
|
7
|
+
key: string;
|
|
8
|
+
} | {
|
|
9
|
+
index: bigint;
|
|
10
|
+
};
|
|
11
|
+
export type ValuePath = PathSegment[];
|
|
12
|
+
export type ParentRef = {
|
|
13
|
+
id: Uint8Array;
|
|
14
|
+
hash: Uint8Array;
|
|
15
|
+
};
|
|
16
|
+
export type ContentOp = {
|
|
17
|
+
kind: 'set';
|
|
18
|
+
path: ValuePath;
|
|
19
|
+
value: JsonValue;
|
|
20
|
+
} | {
|
|
21
|
+
kind: 'remove';
|
|
22
|
+
path: ValuePath;
|
|
23
|
+
} | {
|
|
24
|
+
kind: 'appendText';
|
|
25
|
+
path: ValuePath;
|
|
26
|
+
text: string;
|
|
27
|
+
} | {
|
|
28
|
+
kind: 'spliceText';
|
|
29
|
+
path: ValuePath;
|
|
30
|
+
index: bigint;
|
|
31
|
+
delete: bigint;
|
|
32
|
+
text: string;
|
|
33
|
+
} | {
|
|
34
|
+
kind: 'spliceArray';
|
|
35
|
+
path: ValuePath;
|
|
36
|
+
index: bigint;
|
|
37
|
+
delete: bigint;
|
|
38
|
+
values: JsonValue[];
|
|
39
|
+
};
|
|
40
|
+
export type Operation = {
|
|
41
|
+
kind: 'create';
|
|
42
|
+
parents: ParentRef[];
|
|
43
|
+
content: JsonValue;
|
|
44
|
+
} | {
|
|
45
|
+
kind: 'edit';
|
|
46
|
+
op: ContentOp;
|
|
47
|
+
} | {
|
|
48
|
+
kind: 'seal';
|
|
49
|
+
hash: Uint8Array;
|
|
50
|
+
};
|
|
51
|
+
export type Update = {
|
|
52
|
+
turnId: Uint8Array;
|
|
53
|
+
seq: bigint;
|
|
54
|
+
owner: Uint8Array;
|
|
55
|
+
operation: Operation;
|
|
56
|
+
signature?: Uint8Array;
|
|
57
|
+
};
|
|
58
|
+
export declare function encodeFrame(update: Update): Uint8Array;
|
|
59
|
+
/** Adds bounded batch framing; does not decode or verify the supplied frames. */
|
|
60
|
+
export declare function assembleFrames(frames: readonly Uint8Array[]): Uint8Array;
|
|
61
|
+
export declare function encodeBatch(updates: Update[]): Uint8Array;
|
|
62
|
+
export declare function decodeFrame(bytes: Uint8Array): Update;
|
|
63
|
+
/** Validates outer framing and returns owned frame copies for callers that retain them. */
|
|
64
|
+
export declare function splitBatch(bytes: Uint8Array): Uint8Array[];
|
|
65
|
+
/** Syntax and canonical bytes only. Import applies owner admission and seal verification; unsealed authorship remains provisional. */
|
|
66
|
+
export declare function decodeBatch(bytes: Uint8Array): Update[];
|