@loro-dev/roost 0.1.0 → 0.1.2

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.
@@ -201,8 +201,14 @@ export declare class HistoryReader {
201
201
  * Network, receipt persistence, import and coverage marks are atomic
202
202
  * per batch; the walk's buffer is never persisted (a crash re-walks:
203
203
  * the fetch cost is visible in `bytesFetched`, the ledger absorbs every
204
- * re-receipt). */
205
- fetchWindow(source: BackwardByteSource, budgetBytes: number, pageLimitBytes: number, stop: StopToken): Promise<HistoryReport>;
204
+ * re-receipt). `before` continues an older window at a previously returned
205
+ * complete-message boundary. With `completePrefixes: false`, the report's
206
+ * range is a contiguous imported suffix: prefix repair is deferred to
207
+ * `completePrefixes`, so a pagination cursor never skips filtered messages. */
208
+ fetchWindow(source: BackwardByteSource, budgetBytes: number, pageLimitBytes: number, stop: StopToken, options?: {
209
+ before?: string;
210
+ completePrefixes?: boolean;
211
+ }): Promise<HistoryReport>;
206
212
  /** The durable reverse-scan position for incomplete window-turn prefixes. */
207
213
  prefixScan(): Promise<PrefixScan | undefined>;
208
214
  /** Resume the reverse scan for pending window-turn prefixes. Each call
@@ -257,16 +257,19 @@ export class HistoryReader {
257
257
  * Network, receipt persistence, import and coverage marks are atomic
258
258
  * per batch; the walk's buffer is never persisted (a crash re-walks:
259
259
  * the fetch cost is visible in `bytesFetched`, the ledger absorbs every
260
- * re-receipt). */
261
- async fetchWindow(source, budgetBytes, pageLimitBytes, stop) {
260
+ * re-receipt). `before` continues an older window at a previously returned
261
+ * complete-message boundary. With `completePrefixes: false`, the report's
262
+ * range is a contiguous imported suffix: prefix repair is deferred to
263
+ * `completePrefixes`, so a pagination cursor never skips filtered messages. */
264
+ async fetchWindow(source, budgetBytes, pageLimitBytes, stop, options = {}) {
262
265
  try {
263
- return await this.#fetchWindow(source, budgetBytes, pageLimitBytes, stop);
266
+ return await this.#fetchWindow(source, budgetBytes, pageLimitBytes, stop, options);
264
267
  }
265
268
  catch (e) {
266
269
  return rethrow(e);
267
270
  }
268
271
  }
269
- async #fetchWindow(source, budgetBytes, pageLimitBytes, stop) {
272
+ async #fetchWindow(source, budgetBytes, pageLimitBytes, stop, options) {
270
273
  if (!await this.policy.allowsDownload(this.scope))
271
274
  throw new HistoryError('policyDenied', 'mirror policy denies download for this scope');
272
275
  if (pageLimitBytes === 0 || budgetBytes === 0)
@@ -288,7 +291,7 @@ export class HistoryReader {
288
291
  // bytes so far, and the message offset the NEXT (older) fragment
289
292
  // must end at.
290
293
  let partial;
291
- let from;
294
+ let from = options.before;
292
295
  let tail;
293
296
  let oldestBoundary;
294
297
  // Turns that appeared in the budget-bounded window. After the
@@ -308,6 +311,8 @@ export class HistoryReader {
308
311
  windowTurns = await turnsInWindow(this.#crypto, collected);
309
312
  await this.#includePriorWanted(windowTurns);
310
313
  }
314
+ if (options.completePrefixes === false)
315
+ break;
311
316
  if (windowTurns.size === 0 || await prefixesComplete(this.#crypto, collected, windowTurns)
312
317
  || extraFetched >= pageLimitBytes)
313
318
  break;
@@ -0,0 +1,102 @@
1
+ /** Private prototype API. Pair this client with the artifact's matching owner binary. */
2
+ export const MAX_MESSAGE_BYTES: number;
3
+ export class RoostHostError extends Error { readonly code: string; }
4
+ export type OwnerCapability = 'history-v1' | 'create-once-v1' | 'create-once-cas-v1' | 'sync-v1' | 'host-crypto-v1' | 'index-cas-v1' | 'index-events-v1' | 'index-cas-events-v1';
5
+ export type ParentRef = { id: Uint8Array; hash: Uint8Array };
6
+ export type UpdateRef = { turnId: Uint8Array; seq: bigint };
7
+ export type Verification = 'notRetrieved' | 'provisional' | 'selfVerified' | 'ancestorsVerified';
8
+ export type Header = { turnId: Uint8Array; owner: Uint8Array; parents: ParentRef[]; nextSeq: bigint; sealed: Uint8Array | null; hashVerified: boolean; bodyVerified: boolean };
9
+ export type Turn = Header & { contentJson: string };
10
+ export type ReadResult<T> = { kind: 'found'; turn: T } | { kind: 'notFound'; turnId: Uint8Array } | { kind: 'incomplete'; turnId: Uint8Array; prefix: T | null };
11
+ export type Path = ({ key: string } | { index: bigint })[];
12
+ export type ContentOp =
13
+ | { kind: 'set'; path: Path; contentJson: string }
14
+ | { kind: 'remove'; path: Path }
15
+ | { kind: 'appendText'; path: Path; text: string }
16
+ | { kind: 'spliceText'; path: Path; index: bigint; delete: bigint; text: string }
17
+ | { kind: 'spliceArray'; path: Path; index: bigint; delete: bigint; valuesJson: string };
18
+ export type Write =
19
+ | { kind: 'create'; parents: ParentRef[]; contentJson: string }
20
+ | { kind: 'createOnce'; key: Uint8Array; parents: ParentRef[]; contentJson: string }
21
+ | { kind: 'edit'; turnId: Uint8Array; expectedNextSeq: bigint; ops: ContentOp[] }
22
+ | { kind: 'editOnce'; key: Uint8Array; expectedNextSeq: bigint; ops: ContentOp[] }
23
+ | { kind: 'seal'; turnId: Uint8Array; expectedNextSeq: bigint }
24
+ | { kind: 'sealOnce'; key: Uint8Array; expectedNextSeq: bigint };
25
+ export type IndexKey = { table: string; key: Uint8Array };
26
+ export type IndexEntry = IndexKey & { value: Uint8Array | null };
27
+ export type IndexPut = IndexKey & { value: Uint8Array; onceKey?: Uint8Array; emitEvent?: boolean };
28
+ export type ImportReport = {
29
+ statuses: ({ kind: 'applied' | 'duplicate' | 'pending' } | { kind: 'rejected'; reason: string })[];
30
+ applied: UpdateRef[];
31
+ conflicts: { child: Uint8Array; parent: Uint8Array; declared: Uint8Array; actual: Uint8Array }[];
32
+ };
33
+ export type EventRecord = { cursor: bigint; event:
34
+ | { kind: 'changed'; update: UpdateRef; origin: 'local' | 'remote' }
35
+ | { kind: 'indexChanged'; table: string; key: Uint8Array }
36
+ | { kind: 'rejected'; digest: Uint8Array; reason: string }
37
+ };
38
+ /** Cancellation applies only before dispatch. testBarrier is synthetic debug-only. */
39
+ export type RequestOptions = { signal?: AbortSignal; testBarrier?: 'beforeCommit' | 'afterCommit' };
40
+ export interface RoostNodeStream {
41
+ sync(remoteId: Uint8Array, modes: SyncModes): RoostNodeSync;
42
+ create(parents: ParentRef[], contentJson: string, options?: RequestOptions): Promise<{ updates: UpdateRef[] }>;
43
+ createOnce(key: Uint8Array, parents: ParentRef[], contentJson: string, options?: RequestOptions & {expectedEventCursor?: bigint}): Promise<{ turnId: Uint8Array; created: boolean }>;
44
+ edit(turnId: Uint8Array, expectedNextSeq: bigint, ops: ContentOp[], options?: RequestOptions): Promise<{ updates: UpdateRef[] }>;
45
+ seal(turnId: Uint8Array, expectedNextSeq: bigint, options?: RequestOptions): Promise<{ updates: UpdateRef[] }>;
46
+ writeBatch(writes: Write[], options?: RequestOptions & {indexPuts?: IndexPut[]; expectedEventCursor?: bigint}): Promise<{ updates: UpdateRef[] }>;
47
+ readIndex(keys: IndexKey[], options?: RequestOptions): Promise<(Uint8Array | null)[]>;
48
+ compareAndWriteIndex(expected: IndexEntry[], changes: IndexEntry[], options?: RequestOptions & {eventKeys?: IndexKey[]}): Promise<boolean>;
49
+ scanIndex(table: string, start: Uint8Array, limit: bigint, options?: RequestOptions): Promise<{key: Uint8Array; value: Uint8Array}[]>;
50
+ scanIndexReverse(table: string, end: Uint8Array | null, limit: bigint, options?: RequestOptions): Promise<{key: Uint8Array; value: Uint8Array}[]>;
51
+ readTurn(turnId: Uint8Array, options?: RequestOptions): Promise<ReadResult<Turn>>;
52
+ readTurns(turnIds: Uint8Array[], options?: RequestOptions): Promise<ReadResult<Turn>[]>;
53
+ readTurnHeader(turnId: Uint8Array, options?: RequestOptions): Promise<ReadResult<Header>>;
54
+ latestTurnHeaders(limit: bigint, options?: RequestOptions): Promise<Header[]>;
55
+ turnHeadersBefore(before: Uint8Array, limit: bigint, options?: RequestOptions): Promise<Header[]>;
56
+ turnHeadersAfter(after: Uint8Array | null, limit: bigint, options?: RequestOptions): Promise<ReadResult<Header>[]>;
57
+ readValue(turnId: Uint8Array, path: Path, options?: RequestOptions): Promise<{ contentJson: string; nextSeq: bigint }>;
58
+ readText(turnId: Uint8Array, path: Path, start: bigint, end: bigint, options?: RequestOptions): Promise<{ text: string; nextSeq: bigint }>;
59
+ verification(turnId: Uint8Array, options?: RequestOptions): Promise<Verification>;
60
+ eventsAfter(after: bigint, limit: bigint, options?: RequestOptions): Promise<EventRecord[]>;
61
+ importBatch(updates: Uint8Array, options?: RequestOptions): Promise<ImportReport>;
62
+ importPartialBatch(updates: Uint8Array, options?: RequestOptions): Promise<ImportReport>;
63
+ exportTurns(turnIds: Uint8Array[], options?: RequestOptions): Promise<Uint8Array>;
64
+ exportUpdates(turnId: Uint8Array, fromSeq: bigint, limit: bigint, options?: RequestOptions): Promise<Uint8Array>;
65
+ }
66
+ export type ClientOptions = {
67
+ binaryPath: string; dbPath: string; seed: Uint8Array; allowedOwners: Uint8Array[];
68
+ /** Omit for live Unix time; explicit values select a fixed clock. */
69
+ clockMs?: bigint;
70
+ crypto?: { encrypt(input: CryptoInput): Promise<Uint8Array> | Uint8Array; decrypt(input: CryptoInput): Promise<Uint8Array> | Uint8Array };
71
+ auth?: (input: {remoteId: Uint8Array; reason: "request" | "unauthorized"; signal: AbortSignal}) => Promise<string> | string;
72
+ maxQueuedRequests: number; maxQueuedBytes: number; maxMessageBytes?: number; testBarriers?: boolean;
73
+ };
74
+ export class RoostNodeClient {
75
+ constructor(options: ClientOptions);
76
+ readonly ready: Promise<{ owner: Uint8Array; apiVersion: 2; capabilities: readonly OwnerCapability[] }>;
77
+ readonly capabilities: readonly OwnerCapability[];
78
+ registerRemote(config: Omit<RemoteRecord, "id" | "enabled">, options?: RequestOptions): Promise<{id: Uint8Array}>;
79
+ listRemotes(options?: RequestOptions): Promise<RemoteRecord[]>;
80
+ setRemoteEnabled(id: Uint8Array, enabled: boolean, options?: RequestOptions): Promise<void>;
81
+ readonly exited: Promise<{ code: number | null; signal: string | null }>;
82
+ stream(id: string): RoostNodeStream;
83
+ close(): Promise<void>;
84
+ }
85
+
86
+ /** Available only when this client was started with testBarriers:true. */
87
+ export function testControl(client: RoostNodeClient): { barrier(): Promise<'beforeCommit' | 'afterCommit'>; resume(): void; expireCallback(): void; expireClose(): void; kill(): void; endInput(): void; readonly pid: number | undefined };
88
+
89
+ export type CryptoInput = {remoteId: Uint8Array; bytes: Uint8Array; signal: AbortSignal};
90
+ export type RemoteRecord = {id: Uint8Array; name: string; url: string; physicalStream: string; generation: {bytes: Uint8Array; source: string}; enabled: boolean};
91
+ export type SyncModes = {partial: boolean; encryption: 'host' | 'plaintext'; authentication: 'host' | 'none'};
92
+ export type HistoryLimits = {budgetBytes: bigint; pageLimitBytes: bigint};
93
+ export type HistoryReport = {pages: bigint; batches: bigint; bytesFetched: bigint; fetchedRange: [string,string] | null; appliedTurns: Uint8Array[]; pendingTurns: Uint8Array[]; reachedStart: boolean; stopped: boolean};
94
+ export interface RoostNodeSync {
95
+ ensureRemote(options?: RequestOptions): Promise<void>;
96
+ /** Partial replicas must supply 1..1000 exact ids; absent ancestors remain waiting. */
97
+ upload(input: {maxSend: bigint; turnIds?: Uint8Array[]}, options?: RequestOptions): Promise<{turnsScanned: bigint | null; tasksCreated: bigint | null; waitingParents: Uint8Array[]; sent: UpdateRef[]; confirmed: UpdateRef[]; waitingLocal: UpdateRef[]; transportError: string | null}>;
98
+ download(input: {pageLimit: bigint}, options?: RequestOptions): Promise<{pages: bigint; batches: bigint; appliedTurns: Uint8Array[]; pendingTurns: Uint8Array[]; upToDate: boolean; closed: boolean; stopped: boolean; position: string | null}>;
99
+ fetchWindow(limits: HistoryLimits, options?: RequestOptions): Promise<HistoryReport>;
100
+ completePrefixes(limits: HistoryLimits, options?: RequestOptions): Promise<HistoryReport>;
101
+ catchUpAt(windowTail: string, options?: RequestOptions): Promise<void>;
102
+ }
@@ -0,0 +1,316 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import { isAbsolute } from 'node:path';
4
+
5
+ export const MAX_MESSAGE_BYTES = 136 * 1024 * 1024;
6
+ const U64_MAX = (1n << 64n) - 1n;
7
+ export class RoostHostError extends Error {
8
+ constructor(code, message = code) { super(message); this.name = 'RoostHostError'; this.code = code; }
9
+ }
10
+ const error = code => new RoostHostError(code);
11
+ function positive(n, name, maximum = Number.MAX_SAFE_INTEGER) {
12
+ if (!Number.isSafeInteger(n) || n <= 0 || n > maximum) throw new TypeError(`${name} must be a positive safe integer <= ${maximum}`);
13
+ return n;
14
+ }
15
+ function string(v) { if (typeof v !== 'string') throw new TypeError('string required'); return v; }
16
+ function decimal(v) { if (typeof v !== 'bigint' || v < 0n || v > U64_MAX) throw new TypeError('u64 bigint required'); return v.toString(); }
17
+ function fromDecimal(v) { if (typeof v !== 'string' || !/^(0|[1-9][0-9]*)$/.test(v)) throw error('protocol'); const n = BigInt(v); if (n > U64_MAX) throw error('protocol'); return n; }
18
+ function hex(v, size) { if (!(v instanceof Uint8Array) || (size !== undefined && v.length !== size)) throw new TypeError('byte array length'); return Buffer.from(v).toString('hex'); }
19
+ function unhex(v, size) { if (typeof v !== 'string' || !/^(?:[0-9a-f]{2})*$/.test(v) || (size !== undefined && v.length !== 2 * size)) throw error('protocol'); return Uint8Array.from(Buffer.from(v, 'hex')); }
20
+ function path(p) { if (!Array.isArray(p)) throw new TypeError('path array'); return p.map(s => 'key' in s ? { key: string(s.key) } : { index: decimal(s.index) }); }
21
+ function operation(op) {
22
+ const base = { kind: string(op.kind), path: path(op.path) };
23
+ switch (op.kind) {
24
+ case 'set': return { ...base, contentJson: string(op.contentJson) };
25
+ case 'remove': return base;
26
+ case 'appendText': return { ...base, text: string(op.text) };
27
+ case 'spliceText': return { ...base, index: decimal(op.index), delete: decimal(op.delete), text: string(op.text) };
28
+ case 'spliceArray': return { ...base, index: decimal(op.index), delete: decimal(op.delete), valuesJson: string(op.valuesJson) };
29
+ default: throw new TypeError('unknown content operation');
30
+ }
31
+ }
32
+ function refs(v) { if (!Array.isArray(v)) throw error('protocol'); return v.map(u => ({ turnId: unhex(u.turnId, 16), seq: fromDecimal(u.seq) })); }
33
+ function header(v) {
34
+ if (typeof v.hashVerified !== 'boolean' || typeof v.bodyVerified !== 'boolean' || !Array.isArray(v.parents)) throw error('protocol');
35
+ return { turnId: unhex(v.turnId,16), owner:unhex(v.owner,32), parents:v.parents.map(p=>({id:unhex(p.id,16),hash:unhex(p.hash,32)})), nextSeq:fromDecimal(v.nextSeq),sealed:v.sealed===null?null:unhex(v.sealed,32),hashVerified:v.hashVerified,bodyVerified:v.bodyVerified };
36
+ }
37
+ function turn(v) {
38
+ if (typeof v.contentJson !== 'string' || typeof v.hashVerified !== 'boolean' || !Array.isArray(v.parents)) throw error('protocol');
39
+ return {...header(v), contentJson:v.contentJson};
40
+ }
41
+ function read(v, decode = turn) {
42
+ if (v.kind === 'found') return { kind: 'found', turn: decode(v.turn) };
43
+ if (v.kind === 'notFound') return { kind: 'notFound', turnId: unhex(v.turnId, 16) };
44
+ if (v.kind === 'incomplete') return { kind: 'incomplete', turnId: unhex(v.turnId, 16), prefix: v.prefix === null ? null : decode(v.prefix) };
45
+ throw error('protocol');
46
+ }
47
+ function report(v) {
48
+ if (!Array.isArray(v.statuses) || !Array.isArray(v.conflicts)) throw error('protocol');
49
+ return {statuses:v.statuses.map(s=>{if(!['applied','duplicate','pending','rejected'].includes(s.kind) || (s.kind==='rejected' && typeof s.reason!=='string'))throw error('protocol');return s.kind==='rejected'?{kind:s.kind,reason:s.reason}:{kind:s.kind};}),applied:refs(v.applied),conflicts:v.conflicts.map(c=>({child:unhex(c.child,16),parent:unhex(c.parent,16),declared:unhex(c.declared,32),actual:unhex(c.actual,32)}))};
50
+ }
51
+ function encoded(message, maximum) {
52
+ const text = JSON.stringify(message), size = Buffer.byteLength(text);
53
+ if (size === 0 || size > maximum) throw error('messageLimit');
54
+ const bytes = Buffer.allocUnsafe(size + 4); bytes.writeUInt32BE(size); bytes.write(text, 4); return bytes;
55
+ }
56
+ const testOwners = new WeakMap();
57
+ /** Debug-binary-only fault controls, absent unless testBarriers was explicitly enabled. */
58
+ export function testControl(client) { const value = testOwners.get(client); if (!value) throw new Error('test controls disabled'); return value; }
59
+
60
+ /** Experimental, local-only engine host. This is not Lody's history API or a key store. */
61
+ export class RoostNodeClient {
62
+ #child; #queue = []; #queueBytes = 0; #active;
63
+ #maxRequests; #maxBytes; #maxMessage;
64
+ #state = 'open'; #failure; #exited = false; #closeSent = false; #closeAck = false;
65
+ #closePromise; #closeResolve; #closeReject;
66
+ #header = Buffer.alloc(4); #headerUsed = 0; #body; #bodyUsed = 0;
67
+ #testEnabled; #barriers = []; #barrierWaiters = [];
68
+ #crypto; #auth; #hostCall; #closeTimer; #callbackContext=new AsyncLocalStorage(); #capabilities=Object.freeze([]);
69
+ constructor({ binaryPath, dbPath, seed, allowedOwners, clockMs, maxQueuedRequests, maxQueuedBytes, maxMessageBytes = MAX_MESSAGE_BYTES, testBarriers = false, crypto, auth }) {
70
+ if (!isAbsolute(string(binaryPath)) || !isAbsolute(string(dbPath))) throw new TypeError('absolute binaryPath and dbPath required');
71
+ this.#maxRequests = positive(maxQueuedRequests, 'maxQueuedRequests');
72
+ this.#maxBytes = positive(maxQueuedBytes, 'maxQueuedBytes');
73
+ this.#maxMessage = positive(maxMessageBytes, 'maxMessageBytes', MAX_MESSAGE_BYTES);
74
+ if (typeof testBarriers !== 'boolean') throw new TypeError('testBarriers must be boolean');
75
+ this.#testEnabled = testBarriers; this.#crypto=crypto; this.#auth=auth;
76
+ if (!Array.isArray(allowedOwners) || allowedOwners.length > 256) throw new TypeError('allowedOwners must be an explicit array of at most 256 keys');
77
+ const init = encoded({ version: 1, method: 'init', dbPath, seedHex: hex(seed, 32), allowedOwners: allowedOwners.map(v => hex(v, 32)), ...(clockMs === undefined ? {} : { clockMs: decimal(clockMs) }) }, this.#maxMessage);
78
+ this.#child = spawn(binaryPath, testBarriers ? ['--test-barriers'] : [], { shell: false, detached: false, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
79
+ // Never log request payloads or inherited environment. Child emits fixed diagnostics only.
80
+ this.#child.stderr.on('data', () => {});
81
+ this.exited = new Promise(resolve => this.#child.once('close', (code, signal) => {
82
+ this.#exited = true; clearTimeout(this.#closeTimer);
83
+ if (!this.#closeAck || code !== 0) this.#fail(error('ownerExited'), false);
84
+ this.#state = 'closed';
85
+ if (this.#closeAck && code === 0 && !this.#failure) this.#closeResolve?.();
86
+ else this.#closeReject?.(this.#failure ?? error('ownerExited'));
87
+ for (const waiter of this.#barrierWaiters.splice(0)) waiter.reject(error('ownerExited'));
88
+ resolve({ code, signal });
89
+ }));
90
+ this.#child.on('error', () => this.#fail(error('ownerUnavailable')));
91
+ this.#child.stdin.on('error', () => this.#fail(error('inputClosed')));
92
+ this.#child.stdout.on('data', chunk => { try { this.#receive(chunk); } catch { this.#fail(error('protocol')); } });
93
+ this.ready = new Promise((resolve, reject) => this.#send({ bytes: init, resolve, reject, initialization: true, decode: v => {if(v.apiVersion!==2||!Array.isArray(v.capabilities)||['history-v1','create-once-v1','create-once-cas-v1','sync-v1','host-crypto-v1','index-cas-v1','index-events-v1','index-cas-events-v1'].some(cap=>!v.capabilities.includes(cap)))throw error('incompatibleOwner');this.#capabilities=Object.freeze([...v.capabilities]);return {owner:unhex(v.owner,32),apiVersion:2,capabilities:this.#capabilities};} }));
94
+ void this.ready.catch(() => this.#fail(error('initializationFailed')));
95
+ if (testBarriers) testOwners.set(this, Object.freeze({
96
+ barrier: () => this.#barriers.length ? Promise.resolve(this.#barriers.shift()) : this.#exited ? Promise.reject(error('ownerExited')) : new Promise((resolve, reject) => this.#barrierWaiters.push({ resolve, reject })),
97
+ resume: () => { if (!this.#active || this.#exited) throw error('closed'); this.#child.stdin.write(encoded({ version: 1, method: 'resume' }, this.#maxMessage)); },
98
+ kill: () => { if (!this.#exited) this.#child.kill('SIGKILL'); },
99
+ endInput: () => this.#child.stdin.end(),
100
+ pid: this.#child.pid,
101
+ expireCallback: () => this.#hostCall?.finish(false),
102
+ expireClose: () => { if(this.#state!=='closing')throw error('closed');this.#fail(error('closeTimeout')); },
103
+ }));
104
+ }
105
+ get capabilities() {return this.#capabilities;}
106
+ stream(id) { if (this.#state !== 'open') throw error('closed'); return new RoostNodeStream(this, string(id)); }
107
+ async registerRemote({name,url,physicalStream,generation}, options) { return this.request({method:'sync.register',name:string(name),url:string(url),physicalStream:string(physicalStream),generation:{bytes:hex(generation.bytes),source:string(generation.source)}},v=>({id:unhex(v.id,16)}),options); }
108
+ async listRemotes(options) { return this.request({method:'sync.list'},v=>v.map(r=>({...r,id:unhex(r.id,16),generation:{...r.generation,bytes:unhex(r.generation.bytes)}})),options); }
109
+ async setRemoteEnabled(remoteId,enabled,options) { if(typeof enabled!=='boolean')throw new TypeError('enabled boolean');return this.request({method:'sync.enabled',remoteId:hex(remoteId,16),enabled},v=>{if(v!==null)throw error('protocol');},options); }
110
+ async resolveAuth(remoteId, reason, signal) {
111
+ if(typeof this.#auth!=='function')throw error('auth');
112
+ const controller=new AbortController();const abort=()=>controller.abort();signal?.addEventListener('abort',abort,{once:true});
113
+ let timer;
114
+ try {
115
+ const token=await Promise.race([Promise.resolve().then(()=>this.#auth({remoteId:remoteId.slice(),reason,signal:controller.signal})),new Promise((_,reject)=>{timer=setTimeout(()=>{controller.abort();reject(error('auth'));},30000);})]);
116
+ if(signal?.aborted)throw error('cancelledBeforeDispatch');
117
+ if(typeof token!=='string'||!token.trim()||Buffer.byteLength(token)>16384)throw error('auth');
118
+ return token;
119
+ } catch(e) {if(e?.code==='cancelledBeforeDispatch')throw e;throw error('auth');}
120
+ finally {clearTimeout(timer);signal?.removeEventListener('abort',abort);}
121
+ }
122
+ #handleHostCall(message) {
123
+ if(!this.#active||this.#hostCall||!['encrypt','decrypt'].includes(message.kind))throw error('protocol');
124
+ const callbackId=fromDecimal(message.callbackId).toString(), remoteId=unhex(message.remoteId,16), bytes=unhex(message.bytesHex);
125
+ const controller=new AbortController();let timer;
126
+ const call={controller,finish:(ok,result)=>{
127
+ if(this.#hostCall!==call||this.#failure||this.#exited)return;
128
+ clearTimeout(timer);this.#hostCall=undefined;controller.abort();
129
+ let response;
130
+ try{response=encoded({version:1,method:'hostResult',callbackId,ok,...(ok?{bytesHex:hex(result)}:{})},this.#maxMessage);}
131
+ catch{response=encoded({version:1,method:'hostResult',callbackId,ok:false},this.#maxMessage);}
132
+ this.#child.stdin.write(response,err=>{if(err)this.#fail(error('inputClosed'));});
133
+ }};
134
+ this.#hostCall=call;timer=setTimeout(()=>call.finish(false),30000);
135
+ Promise.resolve().then(()=>{const transform=this.#crypto?.[message.kind];if(typeof transform!=='function')throw error('crypto');return this.#callbackContext.run(true,()=>transform({remoteId,bytes,signal:controller.signal}));}).then(value=>call.finish(true,value),()=>call.finish(false));
136
+ }
137
+ #send(item) {
138
+ this.#active = item;
139
+ item.signal?.removeEventListener('abort', item.abort);
140
+ this.#child.stdin.write(item.bytes, err => { if (err) this.#fail(error('inputClosed')); });
141
+ }
142
+ #pump() {
143
+ if (this.#active || this.#failure || this.#exited) return;
144
+ const next = this.#queue.shift();
145
+ if (next) { this.#queueBytes -= next.bytes.length; this.#send(next); return; }
146
+ if (this.#state === 'closing' && !this.#closeSent) {
147
+ this.#closeSent = true;
148
+ this.#send({ bytes: encoded({ version: 1, method: 'close' }, this.#maxMessage), decode: v => { if (v !== null) throw error('protocol'); }, resolve: () => { this.#closeAck = true; this.#child.stdin.end(); }, reject: e => this.#fail(e) });
149
+ }
150
+ }
151
+ request(message, decode, { signal, testBarrier } = {}) {
152
+ if (this.#state !== 'open' || this.#failure) return Promise.reject(error('closed'));
153
+ if(this.#callbackContext.getStore()===true)return Promise.reject(error('callbackReentry'));
154
+ if (signal !== undefined && !(signal instanceof AbortSignal)) return Promise.reject(new TypeError('AbortSignal required'));
155
+ if (signal?.aborted) return Promise.reject(error('cancelledBeforeDispatch'));
156
+ if (testBarrier !== undefined && (!this.#testEnabled || !['beforeCommit', 'afterCommit'].includes(testBarrier))) return Promise.reject(error('testControlsDisabled'));
157
+ let bytes;
158
+ try { bytes = encoded({ ...message, version: 1, ...(testBarrier === undefined ? {} : { testBarrier }) }, this.#maxMessage); }
159
+ catch (e) { return Promise.reject(e); }
160
+ if (this.#active && (this.#queue.length >= this.#maxRequests || this.#queueBytes + bytes.length > this.#maxBytes)) return Promise.reject(error('queueLimit'));
161
+ return new Promise((resolve, reject) => {
162
+ const item = { bytes, decode, resolve, reject, signal };
163
+ item.abort = () => {
164
+ const index = this.#queue.indexOf(item);
165
+ if (index < 0) return;
166
+ this.#queue.splice(index, 1); this.#queueBytes -= item.bytes.length;
167
+ signal.removeEventListener('abort', item.abort); reject(error('cancelledBeforeDispatch'));
168
+ };
169
+ if (this.#active) { this.#queue.push(item); this.#queueBytes += bytes.length; signal?.addEventListener('abort', item.abort, { once: true }); }
170
+ else this.#send(item);
171
+ });
172
+ }
173
+ #receive(chunk) {
174
+ if (this.#failure) return;
175
+ let offset = 0;
176
+ while (offset < chunk.length) {
177
+ if (!this.#body) {
178
+ const size = Math.min(4 - this.#headerUsed, chunk.length - offset);
179
+ chunk.copy(this.#header, this.#headerUsed, offset, offset + size); this.#headerUsed += size; offset += size;
180
+ if (this.#headerUsed !== 4) continue;
181
+ const length = this.#header.readUInt32BE(0); this.#headerUsed = 0;
182
+ if (length === 0 || length > this.#maxMessage) throw error('protocol');
183
+ this.#body = Buffer.allocUnsafe(length); this.#bodyUsed = 0;
184
+ }
185
+ const size = Math.min(this.#body.length - this.#bodyUsed, chunk.length - offset);
186
+ chunk.copy(this.#body, this.#bodyUsed, offset, offset + size); this.#bodyUsed += size; offset += size;
187
+ if (this.#bodyUsed === this.#body.length) {
188
+ const message = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(this.#body)); this.#body = undefined;
189
+ if (message?.version !== 1) throw error('protocol');
190
+ if(message.event==='hostCall'){this.#handleHostCall(message);continue;}
191
+ if (message.event === 'barrier') {
192
+ if (!this.#testEnabled || !this.#active || !['beforeCommit', 'afterCommit'].includes(message.point)) throw error('protocol');
193
+ const waiter = this.#barrierWaiters.shift(); if (waiter) waiter.resolve(message.point); else this.#barriers.push(message.point);
194
+ continue;
195
+ }
196
+ const active = this.#active;
197
+ if (!active || typeof message.ok !== 'boolean') throw error('protocol');
198
+ if (message.ok) {
199
+ let result;try{result=active.decode(message.result);}catch(e){if(active.initialization){this.#active=undefined;active.reject(e);this.#fail(e);return;}throw e;} this.#active = undefined; active.resolve(result);
200
+ } else {
201
+ if (!['invalid', 'pending', 'conflict', 'sealed', 'stale', 'unauthorized', 'storage', 'auth', 'transport', 'crypto', 'registry', 'sync', 'disabled'].includes(message.error?.code)) throw error('protocol');
202
+ this.#active = undefined; active.reject(error(message.error.code));
203
+ if (active.initialization) this.#fail(error('initializationFailed'));
204
+ }
205
+ this.#pump();
206
+ }
207
+ }
208
+ }
209
+ #fail(reason, kill = true) {
210
+ if (this.#failure) return;
211
+ clearTimeout(this.#closeTimer);this.#hostCall?.controller.abort();this.#hostCall=undefined;
212
+ this.#failure = reason; this.#state = 'failed';
213
+ const active = this.#active; this.#active = undefined; active?.reject(error('unknownOutcome'));
214
+ for (const item of this.#queue.splice(0)) { item.signal?.removeEventListener('abort', item.abort); item.reject(error('notDispatched')); }
215
+ this.#queueBytes = 0; this.#body = undefined;
216
+ for (const waiter of this.#barrierWaiters.splice(0)) waiter.reject(reason);
217
+ if (kill && !this.#exited) this.#child.kill('SIGKILL');
218
+ }
219
+ close() {
220
+ if(this.#callbackContext.getStore()===true)return Promise.reject(error("callbackReentry"));
221
+ if (this.#closePromise) return this.#closePromise;
222
+ if (this.#failure || this.#exited) return this.#closePromise = this.exited.then(() => { if (this.#failure) throw this.#failure; });
223
+ this.#state = 'closing';
224
+ this.#closeTimer=setTimeout(()=>this.#fail(error('closeTimeout')),30000);
225
+ this.#closePromise = new Promise((resolve, reject) => { this.#closeResolve = resolve; this.#closeReject = reject; });
226
+ this.#pump(); return this.#closePromise;
227
+ }
228
+ }
229
+ class RoostNodeStream {
230
+ constructor(client, id) { this.client = client; this.id = id; }
231
+ sync(remoteId, modes) { return new RoostNodeSync(this.client,this.id,remoteId,modes); }
232
+ async createOnce(key, parents, contentJson, options) { return this.client.request({method:'createOnce',stream:this.id,keyHex:hex(key),...(options?.expectedEventCursor===undefined?{}:{expectedEventCursor:decimal(options.expectedEventCursor)}),parents:parents.map(p=>({id:hex(p.id,16),hash:hex(p.hash,32)})),contentJson:string(contentJson)},v=>{if(typeof v.created!=='boolean')throw error('protocol');return {turnId:unhex(v.turnId,16),created:v.created};},options); }
233
+ async create(parents, contentJson, options) { return this.client.request({ method: 'create', stream: this.id, parents: parents.map(p => ({ id: hex(p.id, 16), hash: hex(p.hash, 32) })), contentJson: string(contentJson) }, v => ({ updates: refs(v.updates) }), options); }
234
+ async edit(turnId, expectedNextSeq, ops, options) { return this.client.request({ method: 'edit', stream: this.id, turnId: hex(turnId, 16), expectedNextSeq: decimal(expectedNextSeq), ops: ops.map(operation) }, v => ({ updates: refs(v.updates) }), options); }
235
+ async seal(turnId, expectedNextSeq, options) { return this.client.request({ method: 'seal', stream: this.id, turnId: hex(turnId, 16), expectedNextSeq: decimal(expectedNextSeq) }, v => ({ updates: refs(v.updates) }), options); }
236
+ async readTurn(turnId, options) { return this.client.request({ method: 'readTurn', stream: this.id, turnId: hex(turnId, 16) }, read, options); }
237
+ async readText(turnId, valuePath, start, end, options) { return this.client.request({ method: 'readText', stream: this.id, turnId: hex(turnId, 16), path: path(valuePath), start: decimal(start), end: decimal(end) }, v => ({ text: string(v.text), nextSeq: fromDecimal(v.nextSeq) }), options); }
238
+ async importBatch(updates, options) { return this.client.request({method:'importBatch',stream:this.id,updatesHex:hex(updates)}, report, options); }
239
+ async importPartialBatch(updates, options) { return this.client.request({method:'importPartialBatch',stream:this.id,updatesHex:hex(updates)}, report, options); }
240
+ async readTurnHeader(turnId, options) { return this.client.request({method:'readTurnHeader',stream:this.id,turnId:hex(turnId,16)}, v=>read(v,header),options); }
241
+ async latestTurnHeaders(limit, options) { return this.client.request({method:'latestTurnHeaders',stream:this.id,limit:decimal(limit)}, v=>v.map(header),options); }
242
+ async turnHeadersBefore(before, limit, options) { return this.client.request({method:'turnHeadersBefore',stream:this.id,before:hex(before,16),limit:decimal(limit)},v=>v.map(header),options); }
243
+ async turnHeadersAfter(after, limit, options) { return this.client.request({method:'turnHeadersAfter',stream:this.id,after:after===null?null:hex(after,16),limit:decimal(limit)},v=>v.map(r=>read(r,header)),options); }
244
+ async readTurns(turnIds, options) { return this.client.request({method:'readTurns',stream:this.id,turnIds:turnIds.map(id=>hex(id,16))},v=>v.map(r=>read(r)),options); }
245
+ async readValue(turnId, p, options) { return this.client.request({method:'readValue',stream:this.id,turnId:hex(turnId,16),path:path(p)},v=>{if(typeof v.contentJson!=='string')throw error('protocol');return {contentJson:v.contentJson,nextSeq:fromDecimal(v.nextSeq)};},options); }
246
+ async verification(turnId, options) { return this.client.request({method:'verification',stream:this.id,turnId:hex(turnId,16)},v=>{if(!['notRetrieved','provisional','selfVerified','ancestorsVerified'].includes(v))throw error('protocol');return v;},options); }
247
+ async writeBatch(writes, options) {
248
+ const indexPuts = options?.indexPuts;
249
+ const cursor = options?.expectedEventCursor;
250
+ return this.client.request({method:'writeBatch',stream:this.id,writes:writes.map(w=>{
251
+ switch(w.kind){
252
+ case 'create':return {kind:w.kind,parents:w.parents.map(p=>({id:hex(p.id,16),hash:hex(p.hash,32)})),contentJson:string(w.contentJson)};
253
+ case 'createOnce':return {kind:w.kind,keyHex:hex(w.key),parents:w.parents.map(p=>({id:hex(p.id,16),hash:hex(p.hash,32)})),contentJson:string(w.contentJson)};
254
+ case 'edit':return {kind:w.kind,turnId:hex(w.turnId,16),expectedNextSeq:decimal(w.expectedNextSeq),ops:w.ops.map(operation)};
255
+ case 'editOnce':return {kind:w.kind,keyHex:hex(w.key),expectedNextSeq:decimal(w.expectedNextSeq),ops:w.ops.map(operation)};
256
+ case 'seal':return {kind:w.kind,turnId:hex(w.turnId,16),expectedNextSeq:decimal(w.expectedNextSeq)};
257
+ case 'sealOnce':return {kind:w.kind,keyHex:hex(w.key),expectedNextSeq:decimal(w.expectedNextSeq)};
258
+ default:throw new TypeError('unknown write');
259
+ }
260
+ }),...(indexPuts===undefined?{}:{indexPuts:indexPuts.map(p=>({table:string(p.table),keyHex:hex(p.key),valueHex:hex(p.value),...(p.emitEvent===undefined?{}:{emitEvent:bool(p.emitEvent)}),...(p.onceKey===undefined?{}:{onceKeyHex:hex(p.onceKey)})}))}),...(cursor===undefined?{}:{expectedEventCursor:decimal(cursor)})},v=>({updates:refs(v.updates)}),options); }
261
+ async scanIndex(table, start, limit, options) {
262
+ return this.client.request({method:'indexScan',stream:this.id,table:string(table),start:hex(start),limit:decimal(limit)},v=>v.map(r=>({key:unhex(r.keyHex),value:unhex(r.valueHex)})),options);
263
+ }
264
+ async readIndex(keys, options) {
265
+ const count = keys.length;
266
+ return this.client.request({method:'indexRead',stream:this.id,keys:keys.map(k=>({table:string(k.table),keyHex:hex(k.key)}))},v=>{
267
+ if (!Array.isArray(v) || v.length !== count) throw error('protocol');
268
+ return v.map(value=>value===null?null:unhex(value));
269
+ },options);
270
+ }
271
+ async compareAndWriteIndex(expected, changes, options) {
272
+ const entries = rows => rows.map(r=>({table:string(r.table),keyHex:hex(r.key),valueHex:r.value===null?null:hex(r.value)}));
273
+ return this.client.request({method:'indexCompareWrite',stream:this.id,expected:entries(expected),changes:entries(changes),...(options?.eventKeys ? {eventKeys:options.eventKeys.map(k=>({table:string(k.table),keyHex:hex(k.key)}))} : {})},v=>{
274
+ if (typeof v !== 'boolean') throw error('protocol');
275
+ return v;
276
+ },options);
277
+ }
278
+ async scanIndexReverse(table, end, limit, options) {
279
+ return this.client.request({method:'indexScanReverse',stream:this.id,table:string(table),end:end==null?null:hex(end),limit:decimal(limit)},v=>v.map(r=>({key:unhex(r.keyHex),value:unhex(r.valueHex)})),options);
280
+ }
281
+ async eventsAfter(after, limit, options) { return this.client.request({method:'eventsAfter',stream:this.id,after:decimal(after),limit:decimal(limit)},v=>v.map(r=>{
282
+ const e=r.event; let event;
283
+ if(e.kind==='changed' && ['local','remote'].includes(e.origin)) event={kind:e.kind,update:refs([e.update])[0],origin:e.origin};
284
+ else if(e.kind==='indexChanged' && typeof e.table==='string') event={kind:e.kind,table:e.table,key:unhex(e.keyHex)};
285
+ else if(e.kind==='rejected' && typeof e.reason==='string') event={kind:e.kind,digest:unhex(e.digest,32),reason:e.reason};
286
+ else throw error('protocol');
287
+ return {cursor:fromDecimal(r.cursor),event};
288
+ }),options); }
289
+
290
+ async exportTurns(turnIds, options) { return this.client.request({ method: 'exportTurns', stream: this.id, turnIds: turnIds.map(v => hex(v, 16)) }, v => unhex(v.updatesHex), options); }
291
+ async exportUpdates(turnId, fromSeq, limit, options) { return this.client.request({ method: 'exportUpdates', stream: this.id, turnId: hex(turnId, 16), fromSeq: decimal(fromSeq), limit: decimal(limit) }, v => unhex(v.updatesHex), options); }
292
+ }
293
+
294
+ class RoostNodeSync {
295
+ constructor(client,stream,remoteId,{partial,encryption,authentication}) {
296
+ if(typeof partial!=='boolean'||!['host','plaintext'].includes(encryption)||!['host','none'].includes(authentication))throw new TypeError('explicit sync modes required');
297
+ this.client=client;this.stream=stream;this.remoteId=unhex(hex(remoteId,16),16);this.modes={partial,encryption,authentication};this.authReason='request';
298
+ }
299
+ async call(method,args,options) {
300
+ const token=this.modes.authentication==='host'?await this.client.resolveAuth(this.remoteId,this.authReason,options?.signal):undefined;
301
+ try {
302
+ const value=await this.client.request({method:'sync.'+method,stream:this.stream,remoteId:hex(this.remoteId,16),...this.modes,...args,...(token===undefined?{}:{token})},v=>v,options);
303
+ if(value?.transportError==='auth')this.authReason='unauthorized';else this.authReason='request';
304
+ return value;
305
+ }catch(e){if(e?.code==='auth')this.authReason='unauthorized';throw e;}
306
+ }
307
+ async ensureRemote(options){await this.call('ensure',{},options);}
308
+ async upload({maxSend,turnIds},options){const r=await this.call('upload',{maxSend:decimal(maxSend),...(turnIds===undefined?{}:{turnIds:turnIds.map(x=>hex(x,16))})},options);return {...r,waitingParents:r.waitingParents.map(x=>unhex(x,16)),turnsScanned:r.turnsScanned===null?null:fromDecimal(r.turnsScanned),tasksCreated:r.tasksCreated===null?null:fromDecimal(r.tasksCreated),sent:refs(r.sent),confirmed:refs(r.confirmed),waitingLocal:refs(r.waitingLocal)};}
309
+ async download({pageLimit},options){const r=await this.call('download',{pageLimit:decimal(pageLimit)},options);return {...r,pages:fromDecimal(r.pages),batches:fromDecimal(r.batches),appliedTurns:r.appliedTurns.map(id=>unhex(id,16)),pendingTurns:r.pendingTurns.map(id=>unhex(id,16))};}
310
+ async fetchWindow(limits,options){return this.history('window',limits,options);}
311
+ async completePrefixes(limits,options){return this.history('prefixes',limits,options);}
312
+ async history(method,{budgetBytes,pageLimitBytes},options){const r=await this.call(method,{budgetBytes:decimal(budgetBytes),pageLimitBytes:decimal(pageLimitBytes)},options);return {...r,pages:fromDecimal(r.pages),batches:fromDecimal(r.batches),bytesFetched:fromDecimal(r.bytesFetched),appliedTurns:r.appliedTurns.map(id=>unhex(id,16)),pendingTurns:r.pendingTurns.map(id=>unhex(id,16))};}
313
+ async catchUpAt(tail,options){await this.call('catchUp',{tail:string(tail)},options);}
314
+ }
315
+
316
+ function bool(value) { if (typeof value !== 'boolean') throw new TypeError('boolean required'); return value; }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@loro-dev/roost",
3
- "version": "0.1.0",
4
- "description": "Experimental browser conversation history and sync for Loro Roost",
3
+ "version": "0.1.2",
4
+ "description": "Browser conversation history and sync for Loro Roost",
5
5
  "license": "MIT",
6
6
  "publishConfig": { "access": "public" },
7
7
  "type": "module",
@@ -37,10 +37,16 @@
37
37
  "./lody-history": {
38
38
  "types": "./dist/lody-history.d.ts",
39
39
  "import": "./dist/lody-history.js"
40
+ },
41
+ "./node/client.mjs": {
42
+ "types": "./node/client.d.mts",
43
+ "import": "./node/client.mjs"
40
44
  }
41
45
  },
42
46
  "files": [
43
47
  "dist",
48
+ "node/client.mjs",
49
+ "node/client.d.mts",
44
50
  "README.md",
45
51
  "LICENSE"
46
52
  ]