@cero-base/cero 2.2.1 → 2.3.1

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.
Files changed (42) hide show
  1. package/README.md +24 -16
  2. package/package.json +7 -6
  3. package/src/build/index.js +38 -34
  4. package/src/build/internal.js +96 -11
  5. package/src/build/schemas.js +119 -19
  6. package/src/extensions/handle-sync.js +8 -12
  7. package/src/extensions/index.js +17 -63
  8. package/src/extensions/mirror.js +44 -0
  9. package/src/extensions/profile-sync.js +10 -12
  10. package/src/handle/index.js +499 -374
  11. package/src/handle/join.js +144 -0
  12. package/src/index.js +91 -119
  13. package/src/lib/bluetooth.js +83 -19
  14. package/src/lib/constants.js +1 -0
  15. package/src/lib/operators.js +296 -128
  16. package/src/lib/peek.js +1 -1
  17. package/src/lib/refs.js +7 -7
  18. package/src/lib/spec.js +32 -0
  19. package/src/local/index.js +27 -3
  20. package/src/rpc/client.js +247 -205
  21. package/src/rpc/server.js +186 -133
  22. package/types/build/index.d.ts +3 -8
  23. package/types/build/internal.d.ts +86 -27
  24. package/types/build/schemas.d.ts +91 -12
  25. package/types/extensions/handle-sync.d.ts +4 -12
  26. package/types/extensions/index.d.ts +59 -59
  27. package/types/extensions/mirror.d.ts +13 -0
  28. package/types/extensions/profile-sync.d.ts +4 -13
  29. package/types/handle/index.d.ts +229 -198
  30. package/types/handle/join.d.ts +63 -0
  31. package/types/index.d.ts +36 -53
  32. package/types/lib/bluetooth.d.ts +57 -19
  33. package/types/lib/constants.d.ts +1 -0
  34. package/types/lib/operators.d.ts +166 -81
  35. package/types/lib/peek.d.ts +2 -2
  36. package/types/lib/refs.d.ts +14 -15
  37. package/types/lib/spec.d.ts +87 -0
  38. package/types/local/index.d.ts +19 -9
  39. package/types/rpc/client.d.ts +110 -93
  40. package/types/rpc/server.d.ts +91 -50
  41. package/src/rpc/index.js +0 -8
  42. package/types/rpc/index.d.ts +0 -7
@@ -1,6 +1,7 @@
1
1
  export const NS = 'cero'
2
2
  export const COUNTERS = 'counters'
3
3
  export const EPOCHS = 'epochs'
4
+ export const REMOVALS = 'removals'
4
5
 
5
6
  // Writer-admission / pairing timeout (ms), and the initial discovery-flush wait (ms).
6
7
  export const TIMEOUT = 30000
@@ -1,31 +1,29 @@
1
1
  import { Readable } from 'streamx'
2
- import b4a from 'b4a'
3
2
 
4
3
  import { encodeId, decodeId } from '@cero-base/core/blobs/codec'
5
- import { CeroError } from '@cero-base/core/errors'
6
- import { onAbort } from '@cero-base/core/utils'
4
+ import { onAbort, subscribe } from '@cero-base/core/utils'
7
5
 
8
6
  /**
9
7
  * @typedef {import('./refs.js').Ref} Ref
10
8
  * @typedef {import('@cero-base/core/database').HookContext} HookContext
11
- * @typedef {import('../handle/index.js').CeroHandle} CeroHandle
12
- * @typedef {{ data: any }} SingleResult
13
- * @typedef {{ data: any[], total: number, size: number }} ListResult
14
- * @typedef {{ data: any | null }} GetByIdResult
9
+ * @typedef {import('../handle/index.js').Context | import('../rpc/client.js').Context} Context
10
+ * @typedef {import('@cero-base/core/database').Row} Row
11
+ * @typedef {import('@cero-base/core/database').SingleResult} SingleResult
12
+ * @typedef {import('@cero-base/core/database').ListResult} ListResult
15
13
  */
16
14
 
17
15
  /**
18
16
  * Resolve a durable file id (+ optional name) to the read shape returned
19
17
  * everywhere: `{ id, name?, type, size, url }`.
20
18
  *
21
- * @param {object} handle
19
+ * @param {Context} handle
22
20
  * @param {string} id
23
21
  * @param {string} [name]
24
22
  * @returns {{ id: string, type: string, size: number, url: string, name?: string }}
25
23
  */
26
- export function resolveFile(handle, id, name) {
24
+ function resolveFile(handle, id, name) {
27
25
  const { type, blobId } = decodeId(id)
28
- const file = { id, type, size: blobId.byteLength, url: handle.getLink(id) }
26
+ const file = { id, type, size: blobId.byteLength, url: handle._link(id) }
29
27
  if (name != null) file.name = name
30
28
  return file
31
29
  }
@@ -34,22 +32,26 @@ export function resolveFile(handle, id, name) {
34
32
  * Insert (or overwrite by id) a row on `ref`.
35
33
  *
36
34
  * @param {Ref} ref
37
- * @param {Record<string, any>} row
35
+ * @param {Row} row
38
36
  * @returns {Promise<SingleResult>}
39
37
  */
40
- export function put(ref, row) {
38
+ export async function put(ref, row) {
39
+ // an extension's setup runs while the root opens, so a call there waits for the open; on an open
40
+ // handle nothing is awaited, so the call reaches the database in the caller's run, where a hook's
41
+ // guard sees it
42
+ if (ref.handle.opened === false) await ref.handle.ready()
41
43
  return ref.name === 'files' ? putFile(ref, row) : ref.handle.store.put(ref.name, row)
42
44
  }
43
45
 
44
46
  async function putFile(ref, row) {
45
47
  const handle = ref.handle
46
48
  if (handle.rpc) return handle.put('files', row)
47
- const { data, type, name = null } = row
49
+ const { data, type, name = null, from = null } = row
48
50
  const blobs = handle.blobs // captured once — the instance carries its epoch stamp
49
51
  await blobs.ready()
50
52
  const blobId = await blobs.put(data)
51
53
  const id = encodeId(blobs.key, blobId, type)
52
- await handle.store.call('add-file', { id, name, stamp: blobs.stamp || 0 })
54
+ await handle.store.call('add-file', { id, name, stamp: blobs.stamp || 0, from })
53
55
  return { data: resolveFile(handle, id, name) }
54
56
  }
55
57
 
@@ -57,11 +59,12 @@ async function putFile(ref, row) {
57
59
  * Upsert a row on `ref` — merges with the existing row and preserves `createdAt`.
58
60
  *
59
61
  * @param {Ref} ref
60
- * @param {Record<string, any>} row
62
+ * @param {Row} row
61
63
  * @param {{ upsert?: boolean }} [opts]
62
- * @returns {Promise<SingleResult>}
64
+ * @returns {Promise<SingleResult | null>}
63
65
  */
64
- export function set(ref, row, opts) {
66
+ export async function set(ref, row, opts) {
67
+ if (ref.handle.opened === false) await ref.handle.ready()
65
68
  return ref.handle.store.set(ref.name, row, opts)
66
69
  }
67
70
 
@@ -72,7 +75,8 @@ export function set(ref, row, opts) {
72
75
  * @param {string} [id]
73
76
  * @returns {Promise<void>}
74
77
  */
75
- export function del(ref, id) {
78
+ export async function del(ref, id) {
79
+ if (ref.handle.opened === false) await ref.handle.ready()
76
80
  return ref.handle.store.del(ref.name, id)
77
81
  }
78
82
 
@@ -80,24 +84,26 @@ export function del(ref, id) {
80
84
  * Invoke an `action`-kind ref (a custom mutation declared in the schema).
81
85
  *
82
86
  * @param {Ref} ref
83
- * @param {Record<string, any>} [d]
84
- * @returns {Promise<any>}
87
+ * @param {Row} [d]
88
+ * @returns {Promise<void>}
85
89
  */
86
- export function call(ref, d) {
90
+ export async function call(ref, d) {
91
+ if (ref.handle.opened === false) await ref.handle.ready()
87
92
  return ref.handle.store.call(ref.name, d)
88
93
  }
89
94
 
90
95
  const WRITES = { single: ['set', 'del'], collection: ['put', 'set', 'del'] }
91
96
 
92
97
  /**
93
- * Rule that runs before a write to `ref` lands — at apply, on every peer, inside the op's
94
- * transaction. Return `false` to refuse it: the writer's own call rejects with `REFUSED`.
95
- * `ctx` is `{ op, name, row, existing, id, memberId, role, get, put, set, del }`; mutate
96
- * `ctx.row` to rewrite what is stored. `op` is the op as it applies, so an upsert on a
97
- * collection is a `put`. The four operators on `ctx` read and write the room as it stands at
98
- * this op, inside the transaction. Must be deterministic — read only `ctx`, never a clock or
99
- * local state — and registered before any op applies, in the process that owns the data. The
100
- * imported operators throw inside a hook; use the ones on `ctx`. Not available over RPC.
98
+ * Rule that runs before a write to `ref` lands, or before an action does: at apply, on every
99
+ * peer, inside the op's transaction. Return `false` to refuse it: the writer's own call rejects
100
+ * with `REFUSED`. `ctx` is `{ op, name, row, existing, id, memberId, role, get, put, set, del }`;
101
+ * mutate `ctx.row` to rewrite what is stored. `op` is the op as it applies, so an upsert on a
102
+ * collection is a `put`. The four operators on `ctx` read and write the room as it stands at this
103
+ * op, inside the transaction. Must be deterministic: read only `ctx`, never a clock or local
104
+ * state. On a type ref (`me.room.notes`) it reaches every room of the type before the room
105
+ * opens; register in an extension's `setup` to see every op the root applies too. The imported
106
+ * operators throw inside a hook; use the ones on `ctx`. Not available over RPC.
101
107
  *
102
108
  * @param {Ref} ref
103
109
  * @param {(ctx: HookContext) => unknown} fn
@@ -105,26 +111,14 @@ const WRITES = { single: ['set', 'del'], collection: ['put', 'set', 'del'] }
105
111
  * @returns {() => void}
106
112
  */
107
113
  export function before(ref, fn, opts) {
108
- if (ref.type) return ref.handle._hookType(before, ref, fn, opts)
109
- const db = ref.handle.store
110
- const ops = WRITES[ref.kind] || ['set']
111
- const offs = ops.map((op) =>
112
- db.before(op, (ctx) => (ctx.name === ref.name ? fn(ctx) : undefined))
113
- )
114
- let stopAbort
115
- const off = () => {
116
- offs.forEach((unsub) => unsub())
117
- stopAbort?.()
118
- }
119
- stopAbort = onAbort(opts?.signal, off)
120
- return off
114
+ return hook('before', ref, fn, opts)
121
115
  }
122
116
 
123
117
  /**
124
- * Rule that runs after a write to `ref` lands — at apply, on every peer, inside the op's
125
- * transaction. Write derived rows through `ctx.put` / `ctx.set` / `ctx.del`; a throw refuses
126
- * the whole op. Same `ctx` and the same determinism and registration rules as `before`. Use
127
- * `changes(ref)` instead to observe writes locally.
118
+ * Rule that runs after a write to `ref` lands, at apply, on every peer, inside the op's
119
+ * transaction. On an action it is what the action does. Write derived rows through `ctx.put` /
120
+ * `ctx.set` / `ctx.del`; a throw refuses the whole op. Same `ctx`, determinism and reach as
121
+ * `before`. Use `watch(ref)` instead to observe writes locally.
128
122
  *
129
123
  * @param {Ref} ref
130
124
  * @param {(ctx: HookContext) => unknown} fn
@@ -132,10 +126,21 @@ export function before(ref, fn, opts) {
132
126
  * @returns {() => void}
133
127
  */
134
128
  export function after(ref, fn, opts) {
135
- if (ref.type) return ref.handle._hookType(after, ref, fn, opts)
129
+ return hook('after', ref, fn, opts)
130
+ }
131
+
132
+ // a write hook runs on each write op and keeps to its ref; an action is an op of its own
133
+ function hook(phase, ref, fn, opts) {
134
+ if (ref.type) {
135
+ return ref.handle._hookType(ref, (room) => hook(phase, room[ref.name], fn), opts)
136
+ }
136
137
  const db = ref.handle.store
137
- const ops = WRITES[ref.kind] || ['set']
138
- const offs = ops.map((op) => db.after(op, (ctx) => (ctx.name === ref.name ? fn(ctx) : undefined)))
138
+ const offs =
139
+ ref.kind === 'action'
140
+ ? [db[phase](ref.name, fn)]
141
+ : (WRITES[ref.kind] || ['set']).map((op) =>
142
+ db[phase](op, (ctx) => (ctx.name === ref.name ? fn(ctx) : undefined))
143
+ )
139
144
  let stopAbort
140
145
  const off = () => {
141
146
  offs.forEach((unsub) => unsub())
@@ -149,7 +154,8 @@ export function after(ref, fn, opts) {
149
154
  const parentStore = (ref) => (ref.handle.root ? ref.handle.root.store : ref.handle.store)
150
155
 
151
156
  const normalize = (rows, name) => {
152
- const data = (rows || []).filter((r) => r.type === name)
157
+ if (!Array.isArray(rows)) return { data: rows?.type === name ? rows : null }
158
+ const data = rows.filter((r) => r.type === name)
153
159
  return { data, total: data.length, size: data.length }
154
160
  }
155
161
 
@@ -187,10 +193,13 @@ function resolveRow(ref, row) {
187
193
  * Read from `ref`. For data refs, dispatches to the underlying store.
188
194
  *
189
195
  * @param {Ref} ref
190
- * @param {string | Record<string, any>} [q]
191
- * @returns {Promise<SingleResult | ListResult | GetByIdResult>}
196
+ * @param {string | Record<string, unknown>} [q]
197
+ * @returns {Promise<SingleResult | ListResult>}
192
198
  */
193
199
  export async function get(ref, q) {
200
+ if (ref.handle.opened === false) await ref.handle.ready()
201
+ const live = ref.handle._live?.[ref.name]
202
+ if (live) return live.get(q)
194
203
  if (ref.kind === 'handle') {
195
204
  const { data } = await parentStore(ref).get('handles', q)
196
205
  return normalize(data, ref.name)
@@ -208,78 +217,44 @@ const bindStream = (owner, stream, opts) => {
208
217
  }
209
218
 
210
219
  /**
211
- * Live snapshot stream on `ref` — re-emits the latest `get()` result on every underlying
212
- * mutation.
220
+ * Read a ref as it changes. Each item is what `get(ref, query)` returns now; a slow reader gets
221
+ * only the newest. With `changes: true` in the query each item also carries `changes`, the
222
+ * `{ prev, next }` rows that changed since the item before, so a slow reader gets fewer items,
223
+ * never fewer changes, and `reset`, set on the first item, whose changes list every row with
224
+ * `prev: null`.
213
225
  *
214
226
  * @param {Ref} ref
215
- * @param {Record<string, any>} [q]
227
+ * @param {string | Record<string, unknown> & { changes?: boolean }} [query]
216
228
  * @param {{ signal?: AbortSignal }} [opts]
217
229
  * @returns {import('streamx').Readable}
218
230
  */
219
- export function watch(ref, q, opts) {
231
+ export function watch(ref, query, opts) {
232
+ const id = typeof query === 'string'
233
+ const { changes, ...rest } = (!id && query) || {}
234
+ const q = id ? query : rest
220
235
  const owner = ref.handle
221
- if (ref.kind !== 'handle') {
222
- const src = owner.store.watch(ref.name, q)
223
- const out = snapshotStream(src, (res) => resolveResult(ref, res))
224
- return bindStream(owner, out, opts)
225
- }
226
- const source = parentStore(ref).watch('handles', q)
227
- const out = snapshotStream(source, (snap) => normalize(snap?.data, ref.name))
228
- return bindStream(owner, out, opts)
236
+ const from = owner.opened === false ? owner.ready().then(() => source(ref, q)) : source(ref, q)
237
+ const diff = changes ? differ(ref.kind === 'single') : null
238
+ return bindStream(owner, snapshotStream(from, diff), opts)
229
239
  }
230
240
 
231
- /**
232
- * Delta subscription: batches of `{ prev, next }` row pairs instead of full snapshots —
233
- * lossless under backpressure, self-contained (the first batch, and any batch after a view
234
- * swap, replays current.
235
- */
236
- export function changes(ref, q, opts) {
237
- const owner = ref.handle
238
- if (ref.kind === 'handle') throw CeroError.INVALID('changes does not support handle refs')
239
- const src = owner.store.changes(ref.name, q)
240
- let resume = null
241
- const wake = () => {
242
- const r = resume
243
- resume = null
244
- if (r) r()
241
+ function source(ref, q) {
242
+ const live = ref.handle._live?.[ref.name]
243
+ if (live) {
244
+ return { src: subscribe({ get: () => live.get(q), watch: live.watch }), map: (res) => res }
245
245
  }
246
- const out = new Readable({
247
- read(cb) {
248
- wake()
249
- cb(null)
250
- },
251
- destroy(cb) {
252
- wake()
253
- src.destroy()
254
- cb(null)
255
- }
256
- })
257
- const pump = async () => {
258
- for await (const batch of src) {
259
- const changes = []
260
- for (const { prev, next } of batch.changes) {
261
- changes.push({
262
- prev: prev && resolveRow(ref, prev),
263
- next: next && resolveRow(ref, next)
264
- })
265
- }
266
- if (out.push({ ...batch, changes }) === false) {
267
- await new Promise((r) => {
268
- resume = r
269
- })
270
- if (out.destroyed) return
271
- }
246
+ if (ref.kind === 'handle') {
247
+ return {
248
+ src: parentStore(ref).watch('handles', q),
249
+ map: (snap) => normalize(snap?.data, ref.name)
272
250
  }
273
- out.push(null)
274
251
  }
275
- pump().catch((err) => {
276
- if (!out.destroyed) out.destroy(err)
277
- })
278
- return bindStream(owner, out, opts)
252
+ return { src: ref.handle.store.watch(ref.name, q), map: (res) => resolveResult(ref, res) }
279
253
  }
280
254
 
281
- // snapshots are idempotent: a slow consumer gets only the newest
282
- function snapshotStream(src, map) {
255
+ // snapshots are idempotent: a slow reader gets only the newest
256
+ function snapshotStream(from, diff) {
257
+ let src = null
283
258
  let pending
284
259
  let wanted = false
285
260
  const out = new Readable({
@@ -289,7 +264,7 @@ function snapshotStream(src, map) {
289
264
  cb(null)
290
265
  },
291
266
  destroy(cb) {
292
- src.destroy()
267
+ src?.destroy()
293
268
  cb(null)
294
269
  }
295
270
  })
@@ -297,39 +272,232 @@ function snapshotStream(src, map) {
297
272
  if (!wanted || pending === undefined || out.destroyed) return
298
273
  const snap = pending
299
274
  pending = undefined
300
- wanted = out.push(snap) !== false
275
+ wanted = out.push(diff ? diff(snap) : snap) !== false
301
276
  }
302
- src.on('data', (res) => {
303
- pending = map(res)
304
- flush()
305
- })
306
- src.on('end', () => out.push(null))
307
- src.on('error', (err) => out.destroy(err))
277
+ const attach = ({ src: s, map }) => {
278
+ if (out.destroyed) return s.destroy()
279
+ src = s
280
+ src.on('data', (res) => {
281
+ pending = map(res)
282
+ flush()
283
+ })
284
+ src.on('end', () => out.push(null))
285
+ src.on('error', (err) => out.destroy(err))
286
+ }
287
+ if (from.then) from.then(attach, (err) => out.destroy(err))
288
+ else attach(from)
308
289
  return out
309
290
  }
310
291
 
292
+ // each item against the last one this reader got, so skipped snapshots fold into the next
293
+ function differ(single) {
294
+ let last
295
+ return (snap) => {
296
+ const prev = last
297
+ last = snap.data
298
+ const changes = single ? diffOne(prev ?? null, snap.data) : diffRows(prev || [], snap.data)
299
+ return { ...snap, changes, reset: prev === undefined }
300
+ }
301
+ }
302
+
303
+ function diffOne(prev, next) {
304
+ return same(prev, next) ? [] : [{ prev, next }]
305
+ }
306
+
307
+ function diffRows(prev, next) {
308
+ const was = new Map(prev.map((row) => [row.id, row]))
309
+ const changes = []
310
+ for (const row of next) {
311
+ const before = was.get(row.id) ?? null
312
+ was.delete(row.id)
313
+ if (!same(before, row)) changes.push({ prev: before, next: row })
314
+ }
315
+ for (const row of was.values()) changes.push({ prev: row, next: null })
316
+ return changes
317
+ }
318
+
319
+ function same(a, b) {
320
+ return JSON.stringify(a) === JSON.stringify(b)
321
+ }
322
+
311
323
  /**
312
324
  * Open (or create / join / load) a child handle through a `handle`-kind ref.
313
325
  *
314
326
  * @param {Ref} ref
315
- * @param {string | { invite?: string, id?: string, name?: string, routes?: any, role?: string, accept?: boolean } | undefined} [arg]
316
- * @returns {Promise<CeroHandle>} The resolved child handle.
327
+ * @param {string | { invite?: string, id?: string, name?: string } | undefined} [arg]
328
+ * @returns {Promise<Context>} The resolved child handle.
317
329
  */
318
330
  export function open(ref, arg) {
319
331
  if (typeof arg === 'string') return ref.handle._join(arg, ref.name)
320
332
  if (arg && typeof arg.invite === 'string') return ref.handle._join(arg.invite, ref.name)
321
- if (arg && typeof arg.id === 'string') return ref.handle._load(ref.name, arg.id, arg)
333
+ if (arg && typeof arg.id === 'string') return ref.handle._load(ref.name, arg.id)
322
334
  return ref.handle._create(ref.name, arg)
323
335
  }
324
336
 
325
337
  /**
326
- * Rotate a handle's encryption epoch. A fresh secret is sealed to every current member and
327
- * announced through the log — members removed before the rotation cannot decrypt anything
328
- * written after it.
338
+ * Mint an invite code into a room.
339
+ *
340
+ * @param {Context} ctx
341
+ * @param {import('@cero-base/core/pairing').InviteOpts} [opts]
342
+ * @returns {Promise<string>}
343
+ */
344
+ export function invite(ctx, opts) {
345
+ return ctx._invite(opts)
346
+ }
347
+
348
+ /**
349
+ * Kill an invite, for every member.
329
350
  *
330
- * @param {any} handle
351
+ * @param {Context} ctx
352
+ * @param {string} code
353
+ * @returns {Promise<boolean>} Whether it was live.
354
+ */
355
+ export function revoke(ctx, code) {
356
+ return ctx._revoke(code)
357
+ }
358
+
359
+ /**
360
+ * Re-key a room now: a new epoch sealed to its members, so one removed before it reads nothing
361
+ * written after. Needs the remove permission. A removal also re-keys on its own shortly after it
362
+ * lands; this is the one to await.
363
+ *
364
+ * @param {Context} ctx
331
365
  * @returns {Promise<{ epoch: number }>}
332
366
  */
333
- export function rotate(handle) {
334
- return handle.store.rotate()
367
+ export function rotate(ctx) {
368
+ return ctx._rotate()
369
+ }
370
+
371
+ /**
372
+ * Write atomically: every write `fn` makes through `tx`, the context it is handed, lands as one
373
+ * batch, or none does. Reads through `tx` see the room as it was before the batch. Not available
374
+ * over RPC.
375
+ *
376
+ * @template T
377
+ * @param {Context} ctx
378
+ * @param {(tx: Context) => Promise<T>} fn
379
+ * @returns {Promise<T>}
380
+ */
381
+ export function tx(ctx, fn) {
382
+ return ctx._tx(fn)
383
+ }
384
+
385
+ /**
386
+ * Let in a join waiting on a `confirm` invite. `role` is the invite's by default, never above it.
387
+ *
388
+ * @param {Context} ctx
389
+ * @param {{ id: string }} request A row of `ctx.requests`.
390
+ * @param {{ role?: string }} [opts]
391
+ * @returns {Promise<void>}
392
+ */
393
+ export function accept(ctx, request, { role } = {}) {
394
+ return ctx._answer(request.id, { accept: true, role })
395
+ }
396
+
397
+ /**
398
+ * Turn away a join waiting on a `confirm` invite. The joiner's `open` rejects with `DENIED`.
399
+ *
400
+ * @param {Context} ctx
401
+ * @param {{ id: string }} request A row of `ctx.requests`.
402
+ * @param {string} [reason]
403
+ * @returns {Promise<void>}
404
+ */
405
+ export function deny(ctx, request, reason = '') {
406
+ return ctx._answer(request.id, { accept: false, reason })
407
+ }
408
+
409
+ /**
410
+ * Quit a room for good: it leaves your list and closes on this device.
411
+ *
412
+ * @param {Context} ctx
413
+ * @returns {Promise<void>}
414
+ */
415
+ export function leave(ctx) {
416
+ return ctx._leave()
417
+ }
418
+
419
+ /**
420
+ * Stop using a context on this device; everything stays. Closing the root closes it all.
421
+ *
422
+ * @param {Context} ctx
423
+ * @returns {Promise<void>}
424
+ */
425
+ export function close(ctx) {
426
+ return ctx.close()
427
+ }
428
+
429
+ /**
430
+ * Give up a join still waiting for an answer, for good: it is not resumed on the next boot.
431
+ *
432
+ * @param {Context} me
433
+ * @param {string} code
434
+ * @returns {Promise<boolean>} Whether a join was waiting.
435
+ */
436
+ export function cancel(me, code) {
437
+ return me._cancel(code)
438
+ }
439
+
440
+ /**
441
+ * The app goes to the background: networking, storage and the Bluetooth radio pause together,
442
+ * and every context reports `status.suspended`. On `me` only.
443
+ *
444
+ * @param {Context} me
445
+ * @returns {Promise<void>}
446
+ */
447
+ export function suspend(me) {
448
+ return me._suspend()
449
+ }
450
+
451
+ /**
452
+ * The app is back in the foreground: everything `suspend` paused resumes. On `me` only.
453
+ *
454
+ * @param {Context} me
455
+ * @returns {Promise<void>}
456
+ */
457
+ export function resume(me) {
458
+ return me._resume()
459
+ }
460
+
461
+ /**
462
+ * Mark a room as the one in use: it ranks first on the swarm, searching and announcing. Rooms are
463
+ * otherwise ranked by their last update.
464
+ *
465
+ * @param {Context} room
466
+ * @returns {Promise<void>}
467
+ */
468
+ export async function activate(room) {
469
+ return room._active(true)
470
+ }
471
+
472
+ /**
473
+ * Take a room off the swarm until something lands in it.
474
+ *
475
+ * @param {Context} room
476
+ * @returns {Promise<void>}
477
+ */
478
+ export async function deactivate(room) {
479
+ return room._active(false)
480
+ }
481
+
482
+ /**
483
+ * Reveal the recovery phrase.
484
+ *
485
+ * @param {Context} me
486
+ * @returns {Promise<string>}
487
+ */
488
+ export function phrase(me) {
489
+ return me._phrase()
490
+ }
491
+
492
+ /**
493
+ * Choose what the device's Bluetooth radio does: find the mesh (`true`), nothing (`false`), or
494
+ * hold one invite's rendezvous (its code) so a joiner in range finds this device with no internet,
495
+ * until the next call or the invite expires.
496
+ *
497
+ * @param {Context} ctx
498
+ * @param {boolean | string} mode
499
+ * @returns {Promise<void>}
500
+ */
501
+ export function nearby(ctx, mode) {
502
+ return ctx._nearby(mode)
335
503
  }
package/src/lib/peek.js CHANGED
@@ -13,7 +13,7 @@ import { Local } from '../local/index.js'
13
13
  * identity (i.e. a stored master seed).
14
14
  *
15
15
  * @param {string} dir Cero data directory.
16
- * @param {any} spec Built spec — same value passed to `cero(dir, spec)`.
16
+ * @param {import('./spec.js').Spec} spec Built spec, the value passed to `cero(dir, spec)`.
17
17
  * @returns {Promise<boolean>} `true` if a master seed exists on disk.
18
18
  */
19
19
  export async function peek(dir, spec) {
package/src/lib/refs.js CHANGED
@@ -2,10 +2,9 @@ import { CeroError } from '@cero-base/core/errors'
2
2
 
3
3
  /**
4
4
  * @typedef {'collection' | 'single' | 'action' | 'handle'} RefKind
5
- * @typedef {{ kind?: string, schema?: string }} RefInfo
6
- * Shape of the entries in `meta.refs` — describes a single ref name.
7
- * `kind` is one of {@link RefKind}, kept as `string` since it originates
8
- * from a generated spec.
5
+ * @typedef {import('./spec.js').RefInfo} RefInfo
6
+ * @typedef {import('./spec.js').Spec} Spec
7
+ * @typedef {import('../handle/index.js').Context | import('../local/index.js').Local} Owner
9
8
  */
10
9
 
11
10
  /**
@@ -13,10 +12,11 @@ import { CeroError } from '@cero-base/core/errors'
13
12
  */
14
13
  export class Ref {
15
14
  /**
16
- * @param {any} handle Owner — a `Handle` (or `Local`) the ref lives on.
15
+ * @param {Owner} handle The root, a room or the local store the ref lives on.
17
16
  * @param {string} name Ref name as declared in the schema.
18
17
  * @param {string} kind Ref kind: `'collection'`, `'single'`, `'action'`, or `'handle'`.
19
18
  * @param {string | null} [schema] Fully-qualified schema id, if any.
19
+ * @param {string | null} [type] On a ref under a handle type (`me.room.notes`), that type.
20
20
  */
21
21
  constructor(handle, name, kind, schema = null, type = null) {
22
22
  this.handle = handle
@@ -30,9 +30,9 @@ export class Ref {
30
30
  * Attach a `Ref` property to `target` for every entry in `refs`, so callers
31
31
  * write `handle.someRef` instead of looking refs up by name.
32
32
  *
33
- * @param {any} target
33
+ * @param {Owner} target
34
34
  * @param {Record<string, RefInfo>} refs
35
- * @param {Record<string, any>} [handles] The handle types, so `target.room.notes` names every room's notes.
35
+ * @param {Record<string, Spec>} [handles] The handle types, so `target.room.notes` names every room's notes.
36
36
  */
37
37
  static attach(target, refs, handles) {
38
38
  for (const [name, info] of Object.entries(refs || {})) {
package/src/lib/spec.js CHANGED
@@ -3,3 +3,35 @@
3
3
  * so cero apps can describe their tables without pulling in the core package directly.
4
4
  */
5
5
  export { t, schema } from '@cero-base/core/schema'
6
+
7
+ /**
8
+ * @typedef {object} RefInfo One entry of a spec's `meta.refs`.
9
+ * @property {'single' | 'collection' | 'action' | 'handle'} [kind]
10
+ * @property {string} [schema]
11
+ * @property {string} [type] The handle type a `handle` ref opens.
12
+ * @property {boolean} [internal] A builtin: members, devices, files and the like.
13
+ * @property {boolean} [live] Computed on the device, never stored: status, joins, nearby.
14
+ * @property {string[]} [fields] The declared fields, in schema order.
15
+ * @property {Record<string, string>} [required] The required fields and their types.
16
+ * @property {string[]} [files] The fields holding file ids.
17
+ * @property {string} [verb]
18
+ *
19
+ * @typedef {object} SpecMeta
20
+ * @property {string} [ns]
21
+ * @property {string} [type] The handle type, on a handle's spec.
22
+ * @property {number} [version]
23
+ * @property {Record<string, RefInfo>} refs
24
+ * @property {{ refs: Record<string, RefInfo> }} [local]
25
+ * @property {Record<string, SpecMeta>} [handles]
26
+ *
27
+ * @typedef {import('@cero-base/core/rpc').Spec & {
28
+ * meta: SpecMeta,
29
+ * database?: object,
30
+ * dispatch?: object,
31
+ * local?: { database: object, schema: object, meta: SpecMeta, codec?: import('@cero-base/core/rpc').Codec },
32
+ * extensions?: import('../extensions/index.js').Extension[] | null,
33
+ * handles?: Record<string, Spec>
34
+ * }} Spec What `build` writes and `cero()` opens.
35
+ *
36
+ * @typedef {import('@cero-base/core/database').Row} Row
37
+ */