@loro-dev/roost 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,10 +12,10 @@ 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.2
15
+ npm install @loro-dev/roost@0.4.0
16
16
  ```
17
17
 
18
- The TypeScript SDK uses Streams client 0.16.0 for framed RR backward pages.
18
+ The TypeScript SDK uses Streams client 0.17.0 for framed RR backward pages.
19
19
  `StreamsTransport.readBackward` returns frames in stream order with opaque
20
20
  start cursors and continuation flags. `HistoryReader` reassembles complete
21
21
  messages within the requested byte budget and resumes existing prefix scans at
@@ -297,279 +297,81 @@ only its version, retaining all records; incompatible layouts abort the upgrade.
297
297
  Older version-1 openers are refused. Existing connections must close on
298
298
  versionchange; a blocked upgrade is an error, never a reason to delete data.
299
299
 
300
- The experimental `./lody-history` entry provides the shared browser/Node business
301
- envelope. `NodeLodyHistory` persists business bindings, diagnostics and its processed
302
- local event cursor through the single SQLite owner. Each page consumes at most 128
303
- events and atomically commits its derived rows and cursor, comparing the prior
304
- cursor to reject stale concurrent work. Identity lookups use database keys; normal
305
- reopen processes only the event backlog. Existing databases without this index
306
- need one resumable initial rebuild. First-page reads still wait for outstanding
307
- indexing, so their cost includes that backlog, not only the returned page.
308
-
309
- Browser and Node batch recovery scan a persistent pending-receipt index instead of every
310
- completed receipt. P2P imports and delayed pending application enter the same local
311
- event log, even for old TurnIDs; these private indexes and cursors are not copied
312
- between peers. Imported updates still do not enter the core outbox automatically.
313
- Concurrent plans retain their original processed cursor, retrying when intervening
314
- events invalidate their absence/revision reads. Neither this entry nor the generic
315
- package automatically replaces Lody runtime storage.
316
-
317
- `commitHistoryBatch(batchId, commands, {recovery: 'local'})` explicitly keeps
318
- pending command bodies in the authoritative `lody_history_local_batch_plans_v1`
319
- journal of that owner database. Preparation creates the compact pending receipt
320
- and journal together. Apply commits all effects, publication references, receipt
321
- seal and an empty journal tombstone together. A lost reply therefore preserves
322
- either recoverable pending commands or the original committed outcome. Committed
323
- receipts and their retained updates contain no command bodies. New batches also
324
- omit unused baseline snapshots in both modes. No historical signed data is pruned.
325
-
326
- The default remains `recovery: 'replicated'`, preserving recovery commands in the
327
- receipt. Retries keep the first preparation's recovery mode. Local mode requires backing up the whole owner database to move unfinished
328
- work; exporting Turns does not export its journal. A same-owner imported pending
329
- local receipt is observed without executing or failing it, and an explicit retry
330
- of that unfinished batch requires its originating database. Committed publication
331
- still rebuilds from the verified seal and target references on other replicas.
332
- Stop older SDKs before writing local-mode pending work; use matching browser/Node
333
- revisions. This option changes the business adapter, not core wire framing or seals.
334
-
335
- Imported messages now rebuild local publication membership during read-side
336
- catch-up or `recoverPendingBatches()` (which returns `Promise<void>`). New direct
337
- messages carry original Create intent; batch members and explicitly promoted
338
- private messages use verified sealed publication receipts. A receiver can derive
339
- these indexes without an admitted local signing identity, and never replays a
340
- remote author's pending commands or adds imported operations to outbox.
341
- Missing targets/seqs wait in a persistent reverse index. One receipt's previously
342
- hidden members become visible together; ordinary P2P edits to already visible
343
- messages still follow their applied prefixes. See the
344
- format and legacy compatibility contract.
345
-
346
- The independent publication cursor performs a one-time, resumable catch-up for
347
- existing databases; initial reads wait for it, so the upgrade can cost a history
348
- scan. Subsequent reopens consume only new local events. Old committed receipts
349
- are supported, including zero-ID placeholders, but an old standalone sealed
350
- message cannot reveal whether its author chose `publish:false`. It stays hidden
351
- on a new receiver until the original author repeats `accept` with its original
352
- input and synchronizes the resulting signed publication Turn. New hidden messages
353
- also stay hidden until explicitly promoted; sealing alone does not publish them.
354
- Recovery does not change a message's verification level. Implementation evidence:
355
- publication recovery plan.
356
-
357
- Published message pages use the publication index for membership/order and batch
358
- read current Turn bodies. `append` and `finish` do not maintain a second body
359
- snapshot. A local event-cursor fence retries reads that overlap a commit, so a
360
- page cannot combine membership from before a batch with content from after it.
361
- Already published incomplete Turns expose their applied prefix. Unsealed content
362
- remains provisional; the projected `sealed` flag is not a verification level.
363
-
364
- Node active-branch pages privately reuse sealed bodies after matching authoritative
365
- headers, including sequence, seal and parent edges. Initial Native page hydration
366
- also reuses the same Turn's already-read header for immutable parents, avoiding a
367
- second full Create export. The per-history cache keeps at
368
- most 64 bodies and 8 MiB of source JSON UTF-16 bytes (an input budget, not exact
369
- heap usage). Oversized and unsealed bodies are not retained. Returned bodies are
370
- independent copies. Page membership, cursors, availability and event fences are
371
- still checked on every read; first hydration performs the usual JSON validation.
372
-
373
- After Node binding/publication indexes settle at one event cursor, repeated
374
- catch-up calls still read the journal directly. They reuse the settled checkpoint
375
- only if that fresh read finds no event. New events or failed reads retain normal
376
- indexing, dependency wakeup and retry behavior. A publication page that adds no
377
- work may commit its cursor and ready marker together, with the old ready/revision
378
- in the same CAS; pending or newly discovered work keeps the full drain path.
379
- `observedEventCursor()` returns that private settled cursor after the same fresh
380
- event check; it needs no second persisted-cursor read. A failed event query still
381
- rejects, and a new history handle must establish its own checkpoint.
382
-
383
- With a matching `derived-indexes-v1` Native host, `NodeLodyHistory.commitContentBatch`
384
- can commit edits, application receipts and private SDK checkpoints in one durable
385
- transaction. It only plans a fast checkpoint for content-subtree edits of at most
386
- 16 already published message Turns, with settled binding/publication checkpoints,
387
- matching Create/binding/member records and no waiting target dependency. Other
388
- writes keep ordinary catch-up. Callers may provide `derivedIndexPuts` for their own
389
- cursor-fenced projections; the SDK owns all private table names and formats.
390
- Native independently checks the entire actual event interval before installing
391
- any derived put. `derivedIndexesApplied` is false when that proof fails; complete
392
- catch-up still processes all events. SDK reuse is installed only after a confirmed
393
- matching reply, and never after a lost reply. This is an additive local API;
394
- subprocess/browser hosts retain their existing paths and advertise no new support.
395
-
396
- After confirmed application, Node retains one private checkpoint plan (at most
397
- 16 IDs and 256 KiB). Each subsequent eligible write still compares every original
398
- proof row inside Native; only the committed progress values advance. An index-only
399
- CAS change refreshes the plan once after Native proves the attempt committed no
400
- write. Unknown outcomes clear reuse and never trigger an automatic retry.
401
- Fresh plans are detached once from host index results and command IDs before
402
- reuse. Every host call receives its own copied proof; subsequent private plans
403
- can share the retained SDK evidence without copying it again after each commit.
404
-
405
- 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.
406
347
 
407
348
  ```ts
408
- const view = history.createMessageView(40);
409
- const initial = await view.initialize(); // latest 40, oldest first
410
- // In the host's change callback/poll loop:
411
- const delta = await view.refresh();
412
- // Patch delta.changed; delta.messages supplies the full retained order.
413
- // Unchanged rows retain object identity and their bodies are not read again.
414
- const older = await view.loadOlder(); // another page when hasMoreOlder is true
415
- view.dispose();
416
- ```
417
-
418
- `refresh` consumes bounded pages of the database's local event log and deduplicates
419
- affected TurnIDs before reading their published bodies. One changed message in a
420
- 40-message cache reads only that body, including when many append events were
421
- coalesced. Edits older than the loaded interval read no bodies. Newly published
422
- messages in the interval are added; older ones remain available through
423
- `loadOlder`. New arrivals do not evict loaded rows. Methods serialize, and failures
424
- or disposal leave the previous cache/cursor intact. Sustained concurrent commits
425
- can return `stale` after four attempts; the host may retry. Treat returned rows and
426
- nested content as read-only. The in-memory cursor belongs to this cache, not a
427
- standalone restart checkpoint. A fresh view loads a fresh page after reopen.
428
-
429
- `readProjectedMessagesById(ids)` also provides a deduplicated, consistent point
430
- read for up to 1000 TurnIDs, excluding unpublished IDs. Hosts still own wakeup,
431
- polling and rendering. Browser hosts should subscribe before initializing the
432
- view; the Node adapter currently uses host polling/change hints. The external
433
- Lody UI is not wired by this library change.
434
-
435
- New sessions can use the adapter's active-view primitives without changing the
436
- existing LoroDoc path:
437
-
438
- ```ts
439
- const first = await history.acceptToView({
440
- viewId: sessionId,
441
- expectedRevision: 0n,
442
- expectedHead: null,
443
- operationId: requestId,
444
- 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' }),
445
357
  });
446
- const page = await history.readActiveBranchPage(sessionId, { latest: true, limit: 40 });
447
- if (!page.complete) throw new Error('Active branch is incomplete');
448
- const older = page.cursor
449
- ? await history.readActiveBranchPage(sessionId, { before: page.cursor, limit: 40 })
450
- : null;
451
- ```
452
-
453
- Use `forkAndActivate` for an edit/resend. Its replacement Create must include
454
- the retained base Turn as a parent; the old suffix remains stored and immutable.
455
- The active-view revision/head is checked with the same atomic write and event
456
- cursor CAS as the Turn Create. Repeating an operation ID is idempotent, while a
457
- different input under that ID is a conflict. `LodyHistory` and `NodeLodyHistory`
458
- expose the same contract. The caller still owns queue, steer and ACP lifecycle
459
- decisions.
460
-
461
- For immutable input delivery, use `acceptInputToView` with the same
462
- `BranchAcceptInput` shape, then query `readInputAcceptance({ viewId, operationId,
463
- input })`. Both browser and Node adapters bind an immutable input fingerprint
464
- and operation receipt in the same transaction as the branch mutation. Input is
465
- copied before asynchronous work begins. The fingerprint includes owner, business/segment identity, content and attachment
466
- identity; the receipt key binds view and operation identity. Mutable parents,
467
- expected head and revision are excluded.
468
-
469
- Repeating an identical accept returns its original receipt even after edits,
470
- later appends or active-branch removal. Changed input conflicts. Read-only lookup
471
- returns `undefined` when unobserved, never inserts history, and does not prove a
472
- pending accept cannot later commit. A host may retry the identical operation
473
- without inventing a new input. Receipts remain owner-local derived indexes;
474
- hosts own access checks, retained-generation lookup, execution and guide recovery.
475
-
476
- `LodyHistory.readOnly(stream)` indexes and projects admitted native history without
477
- a signing identity; authoring through that instance rejects. The host still owns
478
- stream authorization and seal verification. `restoreActiveBranch` is available in
479
- both browser and Node adapters: it atomically creates and seals a non-message
480
- `branch_state` record with its local branch/operation indexes. Remote indexers
481
- reconstruct the rollback, including an empty restored view, from that native
482
- record. `branch_state` is readable as an internal history identity but is excluded
483
- from `HistoryWriteIdentity`, `AcceptHistory` and batch commands; generic authoring
484
- rejects it at runtime as well. Use the dedicated branch APIs for this reserved identity. It
485
- does not edit sealed Turns or change the Rust state machine/wire.
486
-
487
- Active-branch pages return `startPosition`, `totalCount`, `hasMoreOlder`, and an
488
- opaque ancestry cursor alongside the selected messages. Positions/counts refer
489
- to logical `businessId` rows: use `primary` for the initial segment and distinct
490
- successor IDs for late output. Project all returned segments of a business ID
491
- into one row. Linear branches written with this metadata read a bounded page;
492
- legacy/nonlinear ancestry may rebuild a complete directory. `readActiveBranch`
493
- remains available for explicit full snapshots, fenced by the durable event cursor
494
- so a concurrent import cannot mix branch membership and bodies. A partial replica
495
- missing an older boundary reports incomplete and preserves the logical count;
496
- the host fetches or repairs that boundary instead of declaring shorter history.
497
- Generic published-message reverse
498
- pages include superseded messages and cannot substitute for active-branch pages.
499
-
500
- For a confirmed Native linear creation, `advanceActiveBranchDirectory(page, result,
501
- limit)` can return a directory transition with `retainedFrom`, one new `message`,
502
- and its committed `through` cursor. Retain `page.messages.slice(retainedFrom)`
503
- and append `message`; use the returned state/count/older cursor. This transforms
504
- membership only, retaining the consumer's own checkpoint-bound old bodies. It is
505
- not a fresh read or proof that no later event exists. The owner must still observe
506
- and process subsequent events, including state/permission corrections. Results
507
- and page state are matched against private host proofs; copied results, forks,
508
- partial pages and uncertain intervals return undefined and require ordinary page
509
- reads. Older cursors retain late successor segments when the window advances.
510
-
511
- An append preserves older cursors while adding any intervening late successors.
512
- A fork that removes the cursor's ancestry rejects it as `stale`; refresh the
513
- loaded window and obtain a new cursor. The last reverse page can contain fewer
514
- than `limit` rows and never extends past the cursor. Lody uses these APIs in its
515
- Node owner and read-only browser replica. Static checks of that composition do
516
- not establish live-service synchronization or product performance acceptance.
517
-
518
- New records in the private `lody_history_published_v1` table have a `version: "2"`
519
- membership-only value. Current readers also accept legacy full-snapshot values;
520
- there is no separate startup scan solely to convert these membership values
521
- (the publication catch-up above still applies). Reading an unchanged legacy row incurs
522
- its old index payload until republished, but never uses that payload as current
523
- content. New receipt publication lists contain compact references; legacy lists
524
- and batch recovery command/base snapshots remain readable. Stop older adapters
525
- before opening stores written with this layout or the new `indexChanged` local
526
- events, and ship matching browser/Node client and owner revisions.
527
-
528
- For a reproducible SQLite comparison, build the Node owner at the repository root
529
- with `cargo +1.98.1 build --locked --bin roost-node-owner`, then run in `ts/`:
530
-
531
- ```sh
532
- pnpm build
533
- 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 });
534
373
  ```
535
374
 
536
- The checkout must contain Git commit `4a282c826d54434f596ab6183ead7222e5a397f4`;
537
- the script reads that local object and does not fetch it. Archive/packed or shallow
538
- checkouts missing that commit cannot load the baseline. The example compares
539
- that adapter with current code using the same Rust owner. It covers 4/16/64 KiB messages, 40-row reads, owner reopen, single-row
540
- refresh and imported publication recovery. `--history`, `--sizes`, `--samples`
541
- and `--binary` control the fixture. Output includes latency, row counts, actual
542
- body/field/Create reads, event records and IPC requests. It asserts one body read
543
- for a single change and zero old-event/Create reads after caught-up reopen.
544
- The old adapter's empty imported list is a correctness failure, not equivalent
545
- work completed faster. This measures the adapter/storage path without Lody UI.
546
- `--history` sets the local page/refresh/reopen fixture size. Each import sample
547
- uses a fresh receiver with 40 messages; the batch variant sends two receipts of
548
- 20 messages each. Reopen timing excludes owner process startup/ready and leaves
549
- the OS filesystem cache warm. Latencies are observations, not CI thresholds.
550
- Recorded example: 2026-09-17 results and measurement limits.
551
-
552
375
  Host payload crypto may return a Promise (`AsyncPayloadCrypto`), including
553
376
  WebCrypto. Encryption and decryption are awaited outside storage transactions;
554
377
  failed transforms never fall back to plaintext. See RSE1.
555
-
556
- ### Selected membership and sparse branch changes (0.3.1)
557
-
558
- `readActiveBranchMembers(viewId, options)` returns logical positions, member references and ancestry
559
- cursors. `lookupMember(identity)` returns header information;
560
- `readActiveBranchMessages(viewId, businessIds)` hydrates selected active bodies.
561
-
562
- `NodeLodyHistory.replaceActiveBranchMembers` accepts an ordered list of logical segment references
563
- and optional new messages. Each logical row has one primary. Existing physical Turns are reused;
564
- a fresh `primary:<id>` physical segment can represent a reinserted business ID's logical `primary`.
565
- A signed `branch_state` with v2 metadata holds the membership root, which subsequent appends reference.
566
- New messages are sealed by default; `sealed: false` creates an unsealed replacement.
567
-
568
- The manifest uses bounded private array appends. Its Create binds the intent digest, retries compare
569
- the stored prefix, and the completed root is sealed. A small activation claim commits branch state
570
- and operation/application receipts in one exclusive Native transaction. Operation-ID retries return
571
- the original receipt. Incomplete membership is reported until referenced records arrive.
572
-
573
- The SDK reads existing v1 branches in place and v2 membership views. V1 SDKs read v1 views. This API
574
- requires matching `field-reads-v1` and `exclusive-batch-v1` Native capabilities; consumers update their
575
- 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);