@loro-dev/roost 0.3.1 → 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/README.md CHANGED
@@ -12,13 +12,14 @@ The `Inbox` module adds atomic raw receipt/cursor storage, without authenticatin
12
12
  or applying those bytes.
13
13
 
14
14
  ```sh
15
- npm install @loro-dev/roost@0.3.1
15
+ npm install @loro-dev/roost@0.4.0
16
16
  ```
17
17
 
18
- This source targets the coordinated Rust/TypeScript/Native 0.3.1 release;
19
- the registry determines npm availability. Native SQLite storage in
20
- this release accepts fresh/v10 containers only. Preserve older databases with
21
- their compatible runtime; there is no automatic migration or deletion.
18
+ The TypeScript SDK uses Streams client 0.17.0 for framed RR backward pages.
19
+ `StreamsTransport.readBackward` returns frames in stream order with opaque
20
+ start cursors and continuation flags. `HistoryReader` reassembles complete
21
+ messages within the requested byte budget and resumes existing prefix scans at
22
+ their persisted cursors. Registry availability follows the npm release.
22
23
 
23
24
  For source development and browser tests:
24
25
 
@@ -285,287 +286,92 @@ intake commits, and initialize `Link.catchUpAt` from the original window tail,
285
286
  never a later `head()` result. The Node window API is unchanged.
286
287
 
287
288
  `pnpm pack:consumer -- /absolute/output/directory` builds the npm tarball and
288
- checks its public entries. It depends on the exact registry release
289
- `@loro-dev/streams-client@0.8.0`, with no bundled SDK. `pnpm check:consumer`
290
- installs that tarball into a fresh project with a fresh npm cache and checks
291
- the root, `./sync`, and `./lody-history` exports.
289
+ checks its public entries. The package pins `@loro-dev/streams-client` to an
290
+ exact registry version in `package.json`. `pnpm check:consumer` installs the
291
+ tarball in a fresh project with a fresh npm cache, verifies the installed
292
+ Streams version against that pin, and checks the root, `./sync`, and
293
+ `./lody-history` exports.
292
294
 
293
295
  IndexedDB container version is now 2. Opening a valid version-1 database upgrades
294
296
  only its version, retaining all records; incompatible layouts abort the upgrade.
295
297
  Older version-1 openers are refused. Existing connections must close on
296
298
  versionchange; a blocked upgrade is an error, never a reason to delete data.
297
299
 
298
- The experimental `./lody-history` entry provides the shared browser/Node business
299
- envelope. `NodeLodyHistory` persists business bindings, diagnostics and its processed
300
- local event cursor through the single SQLite owner. Each page consumes at most 128
301
- events and atomically commits its derived rows and cursor, comparing the prior
302
- cursor to reject stale concurrent work. Identity lookups use database keys; normal
303
- reopen processes only the event backlog. Existing databases without this index
304
- need one resumable initial rebuild. First-page reads still wait for outstanding
305
- indexing, so their cost includes that backlog, not only the returned page.
306
-
307
- Browser and Node batch recovery scan a persistent pending-receipt index instead of every
308
- completed receipt. P2P imports and delayed pending application enter the same local
309
- event log, even for old TurnIDs; these private indexes and cursors are not copied
310
- between peers. Imported updates still do not enter the core outbox automatically.
311
- Concurrent plans retain their original processed cursor, retrying when intervening
312
- events invalidate their absence/revision reads. Neither this entry nor the generic
313
- package automatically replaces Lody runtime storage.
314
-
315
- `commitHistoryBatch(batchId, commands, {recovery: 'local'})` explicitly keeps
316
- pending command bodies in the authoritative `lody_history_local_batch_plans_v1`
317
- journal of that owner database. Preparation creates the compact pending receipt
318
- and journal together. Apply commits all effects, publication references, receipt
319
- seal and an empty journal tombstone together. A lost reply therefore preserves
320
- either recoverable pending commands or the original committed outcome. Committed
321
- receipts and their retained updates contain no command bodies. New batches also
322
- omit unused baseline snapshots in both modes. No historical signed data is pruned.
323
-
324
- The default remains `recovery: 'replicated'`, preserving recovery commands in the
325
- receipt. Retries keep the first preparation's recovery mode. Local mode requires backing up the whole owner database to move unfinished
326
- work; exporting Turns does not export its journal. A same-owner imported pending
327
- local receipt is observed without executing or failing it, and an explicit retry
328
- of that unfinished batch requires its originating database. Committed publication
329
- still rebuilds from the verified seal and target references on other replicas.
330
- Stop older SDKs before writing local-mode pending work; use matching browser/Node
331
- revisions. This option changes the business adapter, not core wire framing or seals.
332
-
333
- Imported messages now rebuild local publication membership during read-side
334
- catch-up or `recoverPendingBatches()` (which returns `Promise<void>`). New direct
335
- messages carry original Create intent; batch members and explicitly promoted
336
- private messages use verified sealed publication receipts. A receiver can derive
337
- these indexes without an admitted local signing identity, and never replays a
338
- remote author's pending commands or adds imported operations to outbox.
339
- Missing targets/seqs wait in a persistent reverse index. One receipt's previously
340
- hidden members become visible together; ordinary P2P edits to already visible
341
- messages still follow their applied prefixes. See the
342
- format and legacy compatibility contract.
343
-
344
- The independent publication cursor performs a one-time, resumable catch-up for
345
- existing databases; initial reads wait for it, so the upgrade can cost a history
346
- scan. Subsequent reopens consume only new local events. Old committed receipts
347
- are supported, including zero-ID placeholders, but an old standalone sealed
348
- message cannot reveal whether its author chose `publish:false`. It stays hidden
349
- on a new receiver until the original author repeats `accept` with its original
350
- input and synchronizes the resulting signed publication Turn. New hidden messages
351
- also stay hidden until explicitly promoted; sealing alone does not publish them.
352
- Recovery does not change a message's verification level. Implementation evidence:
353
- publication recovery plan.
354
-
355
- Published message pages use the publication index for membership/order and batch
356
- read current Turn bodies. `append` and `finish` do not maintain a second body
357
- snapshot. A local event-cursor fence retries reads that overlap a commit, so a
358
- page cannot combine membership from before a batch with content from after it.
359
- Already published incomplete Turns expose their applied prefix. Unsealed content
360
- remains provisional; the projected `sealed` flag is not a verification level.
361
-
362
- Node active-branch pages privately reuse sealed bodies after matching authoritative
363
- headers, including sequence, seal and parent edges. The per-history cache keeps at
364
- most 64 bodies and 8 MiB of source JSON UTF-16 bytes (an input budget, not exact
365
- heap usage). Oversized and unsealed bodies are not retained. Returned bodies are
366
- independent copies. Page membership, cursors, availability and event fences are
367
- still checked on every read; first hydration performs the usual JSON validation.
368
-
369
- After Node binding/publication indexes settle at one event cursor, repeated
370
- catch-up calls still read the journal directly. They reuse the settled checkpoint
371
- only if that fresh read finds no event. New events or failed reads retain normal
372
- indexing, dependency wakeup and retry behavior. A publication page that adds no
373
- work may commit its cursor and ready marker together, with the old ready/revision
374
- in the same CAS; pending or newly discovered work keeps the full drain path.
375
- `observedEventCursor()` returns that private settled cursor after the same fresh
376
- event check; it needs no second persisted-cursor read. A failed event query still
377
- rejects, and a new history handle must establish its own checkpoint.
378
-
379
- With a matching `derived-indexes-v1` Native host, `NodeLodyHistory.commitContentBatch`
380
- can commit edits, application receipts and private SDK checkpoints in one durable
381
- transaction. It only plans a fast checkpoint for content-subtree edits of at most
382
- 16 already published message Turns, with settled binding/publication checkpoints,
383
- matching Create/binding/member records and no waiting target dependency. Other
384
- writes keep ordinary catch-up. Callers may provide `derivedIndexPuts` for their own
385
- cursor-fenced projections; the SDK owns all private table names and formats.
386
- Native independently checks the entire actual event interval before installing
387
- any derived put. `derivedIndexesApplied` is false when that proof fails; complete
388
- catch-up still processes all events. SDK reuse is installed only after a confirmed
389
- matching reply, and never after a lost reply. This is an additive local API;
390
- subprocess/browser hosts retain their existing paths and advertise no new support.
391
-
392
- After confirmed application, Node retains one private checkpoint plan (at most
393
- 16 IDs and 256 KiB). Each subsequent eligible write still compares every original
394
- proof row inside Native; only the committed progress values advance. An index-only
395
- CAS change refreshes the plan once after Native proves the attempt committed no
396
- write. Unknown outcomes clear reuse and never trigger an automatic retry.
397
- Fresh plans are detached once from host index results and command IDs before
398
- reuse. Every host call receives its own copied proof; subsequent private plans
399
- can share the retained SDK evidence without copying it again after each commit.
400
-
401
- Use the shared cache for a live list on either adapter:
300
+ The `./lody-history` entry provides the shared browser (`LodyHistory`) and Node
301
+ (`NodeLodyHistory`) multi-writer append-only business envelope over a Roost
302
+ stream without altering wire framing, seals, or SQLite container v10.
303
+
304
+ ### Multi-writer history model
305
+
306
+ - **Records (`lodyHistory.kind`)**:
307
+ - `message`: primary messages (`segmentId: "primary"` or `"primary:<suffix>"`) and execution-machine state segments (`segmentId: "state:<primaryTurnId>:<ownerHex>[:<suffix>]"`).
308
+ - `permission_response`: writer-scoped permission decisions (`segmentId: "response:<ownerHex>"`).
309
+ - `supersession`: sealed replacement/deletion markers (`segmentId: "supersession"`, `content.supersedes: string[]`) whose core `parents` must include every superseded physical `primaryTurnId`.
310
+ - **No single-writer locks or global positions**: multiple devices and execution
311
+ machines append concurrently without branch-revision conflicts. Writer-scoped
312
+ `segmentId` suffixes (`<ownerHex>`) must match the Turn's signing author pubkey
313
+ hex; forged suffixes are quarantined in `invalidMessages()`, while
314
+ `(kind, businessId, segmentId)` uniqueness still detects same-author
315
+ equivocation.
316
+ - **Supersession & atomic edit/resend**:
317
+ - `supersede({ operationId, supersedes })` and
318
+ `supersedeAndAppend({ operationId, supersedes, replacements })`
319
+ commit atomically in one `writeBatch` fenced by `expectedEventCursor` CAS.
320
+ - Superseding a physical `primaryTurnId` hides that primary message and all
321
+ `state:<primaryTurnId>:*` segments attached to it from visible reads, while
322
+ preserving immutable sealed Turns and concurrent sibling messages.
323
+ - Attempting to supersede an already-superseded target fails with `conflict`;
324
+ retrying with the exact same `operationId` and input is idempotent.
325
+ - **Pure `TurnId` cursor pagination & tail-join helpers**:
326
+ - `readVisiblePrimaryPage({ latest?, oldest?, before?, after?, limit })` and
327
+ `readVisibleSegmentsPage(...)` paginate strictly by `TurnId` order (newest-first
328
+ via `latest` / `before`, or oldest-first forward via `oldest: true` / `after: null`
329
+ / `after: turnId`) with no unstable global `position` or `totalCount`, and hydrate
330
+ visible bodies with event-cursor fencing.
331
+ - `readVisibleByBusinessId(businessId)` and
332
+ `readVisiblePrimaryTurnIdsByBusinessIds(businessIds)` provide fenced
333
+ visible-only lookups by logical `businessId` without hydrating superseded bodies.
334
+ - `countVisiblePrimaries(atLeast?)` counts visible primary messages (with
335
+ optional early-stop bound) to drive partial-replica `tail-join` windows.
336
+ - `classifyHistoryFrame(rawFrame)` inspects a raw Roost v1 frame before import
337
+ to identify `primary_create`, `state_create`, `permission_response_create`,
338
+ and `supersession_create` creates (versus `other_op` / `invalid`).
339
+ - **Zero cross-transaction in-memory cache & read-only replicas**:
340
+ - Derived indexes (`lody_history_*_v2`) are updated in resumable CAS pages
341
+ (`indexPage` defaults to 64 events, max 128); `NodeLodyHistory` uses
342
+ `fieldReads` to index message creates without exporting large bodies.
343
+ - Neither adapter retains cross-transaction in-memory index caches, keeping
344
+ multi-tab shared IndexedDB writers safe.
345
+ - `LodyHistory.readOnly(stream)` and `NodeLodyHistory.readOnly(stream)` index
346
+ and read admitted history without a signing identity and reject local writes.
402
347
 
403
348
  ```ts
404
- const view = history.createMessageView(40);
405
- const initial = await view.initialize(); // latest 40, oldest first
406
- // In the host's change callback/poll loop:
407
- const delta = await view.refresh();
408
- // Patch delta.changed; delta.messages supplies the full retained order.
409
- // Unchanged rows retain object identity and their bodies are not read again.
410
- const older = await view.loadOlder(); // another page when hasMoreOlder is true
411
- view.dispose();
412
- ```
413
-
414
- `refresh` consumes bounded pages of the database's local event log and deduplicates
415
- affected TurnIDs before reading their published bodies. One changed message in a
416
- 40-message cache reads only that body, including when many append events were
417
- coalesced. Edits older than the loaded interval read no bodies. Newly published
418
- messages in the interval are added; older ones remain available through
419
- `loadOlder`. New arrivals do not evict loaded rows. Methods serialize, and failures
420
- or disposal leave the previous cache/cursor intact. Sustained concurrent commits
421
- can return `stale` after four attempts; the host may retry. Treat returned rows and
422
- nested content as read-only. The in-memory cursor belongs to this cache, not a
423
- standalone restart checkpoint. A fresh view loads a fresh page after reopen.
424
-
425
- `readProjectedMessagesById(ids)` also provides a deduplicated, consistent point
426
- read for up to 1000 TurnIDs, excluding unpublished IDs. Hosts still own wakeup,
427
- polling and rendering. Browser hosts should subscribe before initializing the
428
- view; the Node adapter currently uses host polling/change hints. The external
429
- Lody UI is not wired by this library change.
430
-
431
- New sessions can use the adapter's active-view primitives without changing the
432
- existing LoroDoc path:
433
-
434
- ```ts
435
- const first = await history.acceptToView({
436
- viewId: sessionId,
437
- expectedRevision: 0n,
438
- expectedHead: null,
439
- operationId: requestId,
440
- input: { kind: 'message', businessId: userId, segmentId: 'primary', parents: [], content },
349
+ const first = await history.accept(
350
+ { kind: 'message', businessId: userId, segmentId: 'primary', parents: [], content: fromApplicationJson({ text: 'hi' }) },
351
+ { seal: true },
352
+ );
353
+ const state = await history.acceptState({
354
+ businessId: userId,
355
+ primaryTurnId: first.turnId,
356
+ content: fromApplicationJson({ status: 'seen' }),
441
357
  });
442
- const page = await history.readActiveBranchPage(sessionId, { latest: true, limit: 40 });
443
- if (!page.complete) throw new Error('Active branch is incomplete');
444
- const older = page.cursor
445
- ? await history.readActiveBranchPage(sessionId, { before: page.cursor, limit: 40 })
446
- : null;
447
- ```
448
-
449
- Use `forkAndActivate` for an edit/resend. Its replacement Create must include
450
- the retained base Turn as a parent; the old suffix remains stored and immutable.
451
- The active-view revision/head is checked with the same atomic write and event
452
- cursor CAS as the Turn Create. Repeating an operation ID is idempotent, while a
453
- different input under that ID is a conflict. `LodyHistory` and `NodeLodyHistory`
454
- expose the same contract. The caller still owns queue, steer and ACP lifecycle
455
- decisions.
456
-
457
- For immutable input delivery, use `acceptInputToView` with the same
458
- `BranchAcceptInput` shape, then query `readInputAcceptance({ viewId, operationId,
459
- input })`. Both browser and Node adapters bind an immutable input fingerprint
460
- and operation receipt in the same transaction as the branch mutation. Input is
461
- copied before asynchronous work begins. The fingerprint includes owner, business/segment identity, content and attachment
462
- identity; the receipt key binds view and operation identity. Mutable parents,
463
- expected head and revision are excluded.
464
-
465
- Repeating an identical accept returns its original receipt even after edits,
466
- later appends or active-branch removal. Changed input conflicts. Read-only lookup
467
- returns `undefined` when unobserved, never inserts history, and does not prove a
468
- pending accept cannot later commit. A host may retry the identical operation
469
- without inventing a new input. Receipts remain owner-local derived indexes;
470
- hosts own access checks, retained-generation lookup, execution and guide recovery.
471
-
472
- `LodyHistory.readOnly(stream)` indexes and projects admitted native history without
473
- a signing identity; authoring through that instance rejects. The host still owns
474
- stream authorization and seal verification. `restoreActiveBranch` is available in
475
- both browser and Node adapters: it atomically creates and seals a non-message
476
- `branch_state` record with its local branch/operation indexes. Remote indexers
477
- reconstruct the rollback, including an empty restored view, from that native
478
- record. `branch_state` is readable as an internal history identity but is excluded
479
- from `HistoryWriteIdentity`, `AcceptHistory` and batch commands; generic authoring
480
- rejects it at runtime as well. Use the dedicated branch APIs for this reserved identity. It
481
- does not edit sealed Turns or change the Rust state machine/wire.
482
-
483
- Active-branch pages return `startPosition`, `totalCount`, `hasMoreOlder`, and an
484
- opaque ancestry cursor alongside the selected messages. Positions/counts refer
485
- to logical `businessId` rows: use `primary` for the initial segment and distinct
486
- successor IDs for late output. Project all returned segments of a business ID
487
- into one row. Linear branches written with this metadata read a bounded page;
488
- legacy/nonlinear ancestry may rebuild a complete directory. `readActiveBranch`
489
- remains available for explicit full snapshots, fenced by the durable event cursor
490
- so a concurrent import cannot mix branch membership and bodies. A partial replica
491
- missing an older boundary reports incomplete and preserves the logical count;
492
- the host fetches or repairs that boundary instead of declaring shorter history.
493
- Generic published-message reverse
494
- pages include superseded messages and cannot substitute for active-branch pages.
495
-
496
- For a confirmed Native linear creation, `advanceActiveBranchDirectory(page, result,
497
- limit)` can return a directory transition with `retainedFrom`, one new `message`,
498
- and its committed `through` cursor. Retain `page.messages.slice(retainedFrom)`
499
- and append `message`; use the returned state/count/older cursor. This transforms
500
- membership only, retaining the consumer's own checkpoint-bound old bodies. It is
501
- not a fresh read or proof that no later event exists. The owner must still observe
502
- and process subsequent events, including state/permission corrections. Results
503
- and page state are matched against private host proofs; copied results, forks,
504
- partial pages and uncertain intervals return undefined and require ordinary page
505
- reads. Older cursors retain late successor segments when the window advances.
506
-
507
- An append preserves older cursors while adding any intervening late successors.
508
- A fork that removes the cursor's ancestry rejects it as `stale`; refresh the
509
- loaded window and obtain a new cursor. The last reverse page can contain fewer
510
- than `limit` rows and never extends past the cursor. Lody uses these APIs in its
511
- Node owner and read-only browser replica. Static checks of that composition do
512
- not establish live-service synchronization or product performance acceptance.
513
-
514
- New records in the private `lody_history_published_v1` table have a `version: "2"`
515
- membership-only value. Current readers also accept legacy full-snapshot values;
516
- there is no separate startup scan solely to convert these membership values
517
- (the publication catch-up above still applies). Reading an unchanged legacy row incurs
518
- its old index payload until republished, but never uses that payload as current
519
- content. New receipt publication lists contain compact references; legacy lists
520
- and batch recovery command/base snapshots remain readable. Stop older adapters
521
- before opening stores written with this layout or the new `indexChanged` local
522
- events, and ship matching browser/Node client and owner revisions.
523
-
524
- For a reproducible SQLite comparison, build the Node owner at the repository root
525
- with `cargo +1.98.1 build --locked --bin roost-node-owner`, then run in `ts/`:
526
-
527
- ```sh
528
- pnpm build
529
- node scripts/history-publication-bench.mjs --history 1000 --samples 7 --output /tmp/publication-bench.json
358
+ const firstRef = await history.latestSealedTurn();
359
+ await history.supersedeAndAppend({
360
+ operationId: 'edit-1',
361
+ supersedes: [first.turnId],
362
+ replacements: [
363
+ {
364
+ businessId: userId,
365
+ segmentId: 'primary:edit-1',
366
+ parents: firstRef ? [firstRef] : [],
367
+ content: fromApplicationJson({ text: 'edited' }),
368
+ seal: true,
369
+ },
370
+ ],
371
+ });
372
+ const page = await history.readVisiblePrimaryPage({ latest: true, limit: 40 });
530
373
  ```
531
374
 
532
- The checkout must contain Git commit `4a282c826d54434f596ab6183ead7222e5a397f4`;
533
- the script reads that local object and does not fetch it. Archive/packed or shallow
534
- checkouts missing that commit cannot load the baseline. The example compares
535
- that adapter with current code using the same Rust owner. It covers 4/16/64 KiB messages, 40-row reads, owner reopen, single-row
536
- refresh and imported publication recovery. `--history`, `--sizes`, `--samples`
537
- and `--binary` control the fixture. Output includes latency, row counts, actual
538
- body/field/Create reads, event records and IPC requests. It asserts one body read
539
- for a single change and zero old-event/Create reads after caught-up reopen.
540
- The old adapter's empty imported list is a correctness failure, not equivalent
541
- work completed faster. This measures the adapter/storage path without Lody UI.
542
- `--history` sets the local page/refresh/reopen fixture size. Each import sample
543
- uses a fresh receiver with 40 messages; the batch variant sends two receipts of
544
- 20 messages each. Reopen timing excludes owner process startup/ready and leaves
545
- the OS filesystem cache warm. Latencies are observations, not CI thresholds.
546
- Recorded example: 2026-09-17 results and measurement limits.
547
-
548
375
  Host payload crypto may return a Promise (`AsyncPayloadCrypto`), including
549
376
  WebCrypto. Encryption and decryption are awaited outside storage transactions;
550
377
  failed transforms never fall back to plaintext. See RSE1.
551
-
552
- ### Selected membership and sparse branch changes (0.3.1)
553
-
554
- `readActiveBranchMembers(viewId, options)` returns logical positions, member references and ancestry
555
- cursors. `lookupMember(identity)` returns header information;
556
- `readActiveBranchMessages(viewId, businessIds)` hydrates selected active bodies.
557
-
558
- `NodeLodyHistory.replaceActiveBranchMembers` accepts an ordered list of logical segment references
559
- and optional new messages. Each logical row has one primary. Existing physical Turns are reused;
560
- a fresh `primary:<id>` physical segment can represent a reinserted business ID's logical `primary`.
561
- A signed `branch_state` with v2 metadata holds the membership root, which subsequent appends reference.
562
- New messages are sealed by default; `sealed: false` creates an unsealed replacement.
563
-
564
- The manifest uses bounded private array appends. Its Create binds the intent digest, retries compare
565
- the stored prefix, and the completed root is sealed. A small activation claim commits branch state
566
- and operation/application receipts in one exclusive Native transaction. Operation-ID retries return
567
- the original receipt. Incomplete membership is reported until referenced records arrive.
568
-
569
- The SDK reads existing v1 branches in place and v2 membership views. V1 SDKs read v1 views. This API
570
- requires matching `field-reads-v1` and `exclusive-batch-v1` Native capabilities; consumers update their
571
- version pins after the paired SDK/Native release.
@@ -3,6 +3,7 @@ export declare class Identity {
3
3
  #private;
4
4
  private constructor();
5
5
  static fromSeed(seed: Uint8Array): Identity;
6
+ static generate(randomBytes?: (length: number) => Uint8Array): Identity;
6
7
  owner(): Uint8Array;
7
8
  signHash(hash: Uint8Array): Uint8Array;
8
9
  }
package/dist/identity.js CHANGED
@@ -13,6 +13,19 @@ export class Identity {
13
13
  this.#owner = ed25519.getPublicKey(this.#seed);
14
14
  }
15
15
  static fromSeed(seed) { return new Identity(seed); }
16
+ static generate(randomBytes) {
17
+ let seed;
18
+ if (randomBytes !== undefined) {
19
+ seed = randomBytes(32);
20
+ }
21
+ else if (typeof globalThis.crypto?.getRandomValues === 'function') {
22
+ seed = globalThis.crypto.getRandomValues(new Uint8Array(32));
23
+ }
24
+ else {
25
+ throw new Error('cryptographic random source unavailable');
26
+ }
27
+ return new Identity(seed);
28
+ }
16
29
  owner() { return this.#owner.slice(); }
17
30
  signHash(hash) {
18
31
  bytes(hash, 32, 'hash');
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  export { IndexedDbStorage } from './indexeddb.js';
3
3
  export { Identity } from './identity.js';
4
4
  export { Store, Stream, Writer, StoreError, MAX_PAGE_HEADERS } from './store.js';
5
- export type { StoreOptions, TurnSnapshot, TurnHeader, TurnReadResult, TurnHeaderResult, Verification, ParentConflict, ImportReport, ImportStatus, UpdateRef, Commit, Write, Event, EventRecord, MissingDependencies, StreamSnapshot, } from './store.js';
5
+ export type { StoreOptions, TurnSnapshot, TurnHeader, TurnReadResult, TurnHeaderResult, Verification, ParentConflict, ImportReport, ImportStatus, UpdateRef, Commit, Write, Event, EventRecord, MissingDependencies, StreamSnapshot, PurgeOptions, PurgeReport, } from './store.js';
6
6
  export { encodeJson, decodeJson } from './json.js';
7
7
  export type { JsonValue, JsonNumber } from './json.js';
8
8
  export { encodeBatch, decodeBatch } from './codec.js';
@@ -15,6 +15,12 @@ export declare class KvTransaction {
15
15
  get(space: string, key: Uint8Array): Step<Uint8Array | undefined>;
16
16
  put(space: string, key: Uint8Array, value: Uint8Array): Step<void>;
17
17
  delete(space: string, key: Uint8Array): Step<void>;
18
+ /** Distinct space names starting with `prefix`, in ascending UTF-16 order. */
19
+ spaceNames(prefix: string): Step<string[]>;
20
+ /** Remove every key in `space` in a single range delete. */
21
+ dropSpace(space: string): Step<void>;
22
+ /** Delete keys in `space` within `[start, end)` and return the removed count. */
23
+ deleteRange(space: string, start: Uint8Array, end: Uint8Array | undefined): Step<number>;
18
24
  /** Ascending byte order; start inclusive, end exclusive; bounded results. */
19
25
  scan(space: string, start: Uint8Array, end: Uint8Array | undefined, limit: number): Step<Row[]>;
20
26
  /** Descending byte order (newest first); end exclusive; bounded results. */
package/dist/indexeddb.js CHANGED
@@ -44,6 +44,57 @@ export class KvTransaction {
44
44
  request.onsuccess = () => done(undefined);
45
45
  }, true);
46
46
  }
47
+ /** Distinct space names starting with `prefix`, in ascending UTF-16 order. */
48
+ spaceNames(prefix) {
49
+ return this.#step((store, done) => {
50
+ const names = [];
51
+ const range = IDBKeyRange.lowerBound([prefix], false);
52
+ const request = store.openKeyCursor(range);
53
+ request.onsuccess = () => {
54
+ const cursor = request.result;
55
+ if (!cursor) {
56
+ done(names);
57
+ return;
58
+ }
59
+ const key = cursor.key;
60
+ if (!Array.isArray(key) || typeof key[0] !== 'string' || !key[0].startsWith(prefix)) {
61
+ done(names);
62
+ return;
63
+ }
64
+ names.push(key[0]);
65
+ // Array sorts after every binary key, skipping the rest of this space in one seek.
66
+ cursor.continue([key[0], []]);
67
+ };
68
+ });
69
+ }
70
+ /** Remove every key in `space` in a single range delete. */
71
+ dropSpace(space) {
72
+ return this.#step((store, done) => {
73
+ const request = store.delete(IDBKeyRange.bound([space], [space, []], false, false));
74
+ request.onsuccess = () => done(undefined);
75
+ }, true);
76
+ }
77
+ /** Delete keys in `space` within `[start, end)` and return the removed count. */
78
+ deleteRange(space, start, end) {
79
+ const low = bytes(start), high = end === undefined ? undefined : bytes(end);
80
+ return this.#step((store, done) => {
81
+ if (high !== undefined && indexedDB.cmp(low, high) >= 0) {
82
+ done(0);
83
+ return;
84
+ }
85
+ const range = IDBKeyRange.bound([space, low], [space, high ?? []], false, true);
86
+ const countReq = store.count(range);
87
+ countReq.onsuccess = () => {
88
+ const count = countReq.result;
89
+ if (count === 0) {
90
+ done(0);
91
+ return;
92
+ }
93
+ const delReq = store.delete(range);
94
+ delReq.onsuccess = () => done(count);
95
+ };
96
+ }, true);
97
+ }
47
98
  /** Ascending byte order; start inclusive, end exclusive; bounded results. */
48
99
  scan(space, start, end, limit) {
49
100
  const low = bytes(start), high = end === undefined ? undefined : bytes(end);