@cero-base/cero 2.2.0 → 2.3.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.
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 +89 -118
  13. package/src/lib/bluetooth.js +83 -19
  14. package/src/lib/constants.js +1 -0
  15. package/src/lib/operators.js +298 -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 +240 -202
  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 +27 -55
  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 +55 -112
  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
@@ -28,7 +28,6 @@ export const main = {
28
28
  name: string,
29
29
  createdAt: int,
30
30
  updatedAt: int,
31
- sig: bytes,
32
31
  index: uint
33
32
  },
34
33
  device: {
@@ -42,16 +41,13 @@ export const main = {
42
41
  },
43
42
  invite: {
44
43
  id: required(string),
45
- invite: required(bytes),
46
- publicKey: required(bytes),
47
- data: bytes,
48
- sig: bytes,
49
44
  role: required(string),
50
45
  expires: int,
46
+ reuse: bool,
51
47
  createdAt: int,
52
48
  index: uint,
53
- seed: bytes,
54
- reuse: bool
49
+ // its joins wait for a member to accept them
50
+ confirm: bool
55
51
  },
56
52
  handle: {
57
53
  id: required(string),
@@ -70,7 +66,9 @@ export const main = {
70
66
  createdAt: int,
71
67
  updatedAt: int,
72
68
  index: uint,
73
- stamp: uint
69
+ stamp: uint,
70
+ // the file this one was copied from, so a sync copies it once
71
+ from: string
74
72
  },
75
73
  claim: {
76
74
  identity: required(bytes),
@@ -84,6 +82,58 @@ export const main = {
84
82
  createdAt: int,
85
83
  commit: bytes,
86
84
  stamp: uint
85
+ },
86
+ // appended by the joiner's own writer core, sealed to the database's address
87
+ join: {
88
+ box: required(bytes)
89
+ },
90
+ accept: {
91
+ id: required(string),
92
+ role: string
93
+ },
94
+ // a join from its arrival until the joiner has its keys: waiting for a member on a confirm
95
+ // invite, then admitted and owed its reply. `id` is the joiner's writer
96
+ request: {
97
+ id: required(string),
98
+ identity: required(bytes),
99
+ invite: required(string),
100
+ reply: required(bytes),
101
+ createdAt: int,
102
+ index: uint,
103
+ admitted: bool,
104
+ expires: int,
105
+ // what the join asks for, the invite's role; once admitted, the role granted
106
+ role: string
107
+ },
108
+ // a removed member comes back only through an invite minted after `index`
109
+ removal: {
110
+ id: required(string),
111
+ index: required(uint)
112
+ },
113
+ // this device's live view of a context: computed on read, never stored
114
+ status: {
115
+ role: string,
116
+ writable: bool,
117
+ epoch: uint,
118
+ suspended: bool,
119
+ // an app version this one cannot read ops from, 0 when current
120
+ behind: uint,
121
+ // the Bluetooth radio: 'on', 'off', 'waiting', 'unauthorized', 'unsupported', null without it
122
+ nearby: string
123
+ },
124
+ // a join this device still waits on, without its keys
125
+ joining: {
126
+ id: required(string),
127
+ type: required(string),
128
+ invite: required(string)
129
+ },
130
+ // a person linked over Bluetooth, by the identity that signed their device's key, with the name
131
+ // and device type that device told
132
+ peer: {
133
+ id: required(string),
134
+ name: string,
135
+ isMobile: bool,
136
+ device: string
87
137
  }
88
138
  }
89
139
 
@@ -93,7 +143,9 @@ export const local = {
93
143
  },
94
144
  keypair: {
95
145
  publicKey: required(bytes),
96
- secretKey: required(bytes)
146
+ secretKey: required(bytes),
147
+ // 'create' or 'recover' until this device's setup finished: a killed launch resumes it
148
+ setup: string
97
149
  },
98
150
  'handle-keypair': {
99
151
  id: required(string),
@@ -101,6 +153,32 @@ export const local = {
101
153
  secretKey: required(bytes),
102
154
  encryptionKey: bytes
103
155
  },
156
+ // a room with invites, reopened at boot so its joins are answered
157
+ serving: {
158
+ id: required(string),
159
+ type: required(string)
160
+ },
161
+ // a join not answered yet: the writer is fixed before the join is written, so a resumed one
162
+ // hears the reply to it
163
+ join: {
164
+ id: required(string),
165
+ type: required(string),
166
+ invite: required(string),
167
+ publicKey: required(bytes),
168
+ secretKey: required(bytes),
169
+ // the reply, once it landed: the join then opens the room without joining again
170
+ key: bytes,
171
+ encryptionKey: bytes,
172
+ epochs: bytes
173
+ },
174
+ // mail the device's mailbox keeps: received until handled, sent until read. `mirrors` are
175
+ // 32-byte keys back to back
176
+ mail: {
177
+ id: required(string),
178
+ address: required(bytes),
179
+ message: required(bytes),
180
+ mirrors: bytes
181
+ },
104
182
  environment: {
105
183
  channel: required(string)
106
184
  }
@@ -118,7 +196,9 @@ export const rpc = {
118
196
  ref: required(string),
119
197
  data: required(bytes),
120
198
  local: bool,
121
- noUpsert: bool
199
+ noUpsert: bool,
200
+ // the indexes of the fields a set sends: the typed row decodes the others as defaults
201
+ fields: { ...uint, array: true }
122
202
  },
123
203
  'req-id': {
124
204
  handle: required(string),
@@ -140,8 +220,11 @@ export const rpc = {
140
220
  'req-invite': {
141
221
  handle: required(string),
142
222
  role: string,
143
- expiresIn: uint,
144
- reuse: bool
223
+ // ms, or a duration like '12h'
224
+ ttl: string,
225
+ reuse: bool,
226
+ data: bytes,
227
+ confirm: bool
145
228
  },
146
229
  'req-revoke': {
147
230
  handle: required(string),
@@ -152,6 +235,9 @@ export const rpc = {
152
235
  ref: required(string),
153
236
  invite: required(string)
154
237
  },
238
+ 'req-cancel': {
239
+ invite: required(string)
240
+ },
155
241
  'req-open': {
156
242
  parent: required(string),
157
243
  row: required(string)
@@ -171,17 +257,16 @@ export const rpc = {
171
257
  total: required(int),
172
258
  size: required(int)
173
259
  },
174
- 'res-changes': {
175
- changes: required(bytes),
176
- reset: bool
177
- },
178
260
  'res-invite': {
179
261
  invite: required(string)
180
262
  },
181
263
  'res-handle': {
182
264
  id: required(string),
183
265
  type: required(string),
184
- name: string
266
+ name: string,
267
+ // a join turned away: an error crosses as code and message, without its reason
268
+ denied: bool,
269
+ reason: string
185
270
  },
186
271
  'req-add-file': {
187
272
  handle: required(string),
@@ -193,7 +278,8 @@ export const rpc = {
193
278
  id: required(string),
194
279
  deviceId: string,
195
280
  fileBase: string,
196
- fileToken: string
281
+ fileToken: string,
282
+ deviceName: string
197
283
  },
198
284
  'res-seed': {
199
285
  phrase: string
@@ -207,6 +293,20 @@ export const rpc = {
207
293
  'res-error': {
208
294
  message: required(string),
209
295
  code: string,
210
- stack: string
296
+ stack: string,
297
+ reason: string
298
+ },
299
+ // accept, or deny with a reason
300
+ 'req-answer': {
301
+ handle: required(string),
302
+ id: required(string),
303
+ accept: bool,
304
+ role: string,
305
+ reason: string
306
+ },
307
+ // the mesh when `on`, one invite's rendezvous when `invite` is set
308
+ 'req-nearby': {
309
+ on: bool,
310
+ invite: string
211
311
  }
212
312
  }
@@ -1,34 +1,30 @@
1
1
  import { t } from '../lib/spec.js'
2
- import { get, set, watch } from '../lib/operators.js'
2
+ import { set, watch } from '../lib/operators.js'
3
+ import { mirror } from './mirror.js'
3
4
 
4
5
  /**
5
6
  * Mirror a child handle's `profile` (name + avatar) onto its row in the parent's `handles`
6
7
  * list — so a handle list shows names + avatars without opening each one.
7
8
  *
8
- * @param {{ fields?: Record<string, any> }} [opts]
9
+ * @param {{ fields?: Record<string, object> }} [opts] Extra fields, as `t` types.
10
+ * @returns {import('./index.js').Extension}
9
11
  */
10
12
  export function handleSync({ fields = { avatar: t.string } } = {}) {
11
13
  return {
12
14
  name: 'handle-sync',
13
15
  schema: { handles: t.extend(fields) },
14
16
  setup(me) {
15
- const keys = ['name', ...Object.keys(fields)]
16
- // an unconditional set on every open is a new op in the log forever
17
- const reflect = async (child, data) => {
18
- child.name = data.name
19
- const { data: row } = await get(me.handles, child.id)
20
- if (row && keys.every((k) => row[k] === data[k])) return
21
- await set(me.handles, { id: child.id, ...data }, { upsert: false })
22
- }
23
17
  const onHandle = (child, opts) => {
24
18
  if (!child.profile) return
25
19
  if (opts.name) set(child.profile, { name: opts.name }).catch(me._onerror)
26
20
  watch(child.profile).on('data', ({ data }) => {
27
21
  if (!data?.name) return
28
- reflect(child, data).catch(me._onerror)
22
+ child.name = data.name
23
+ mirror(child.profile, data, fields, me.handles, child.id).catch(me._onerror)
29
24
  })
30
25
  }
31
- me.on('handle', onHandle, { signal: me.signal })
26
+ me.on('handle', onHandle)
27
+ return () => me.off('handle', onHandle)
32
28
  }
33
29
  }
34
30
  }
@@ -1,3 +1,5 @@
1
+ import { CeroError } from '@cero-base/core/errors'
2
+
1
3
  import { profileSync } from './profile-sync.js'
2
4
  import { handleSync } from './handle-sync.js'
3
5
  import { t, schema } from '../lib/spec.js'
@@ -8,81 +10,33 @@ export * from './handle-sync.js'
8
10
 
9
11
  // everything an extension module needs, light enough for the UI bundle the spec pulls it into
10
12
  export { t, schema }
11
- export const { put, set, get, del, watch, changes, call, open, rotate, before, after } = operators
12
- export const cero = {
13
- t,
14
- schema,
15
- put,
16
- set,
17
- get,
18
- del,
19
- watch,
20
- changes,
21
- call,
22
- open,
23
- rotate,
24
- before,
25
- after
26
- }
13
+ export * from '../lib/operators.js'
14
+ export const cero = { t, schema, ...operators }
27
15
 
28
16
  /**
29
17
  * @typedef {object} Extension
30
- * @property {Record<string, any>} [schema] Refs to add, or `t.extend` on a builtin, nested by handle type like the app schema.
31
- * @property {(me: any) => any} [setup] Runs once the root is ready; a returned function runs on close.
18
+ * @property {string} [name]
19
+ * @property {Record<string, object>} [schema] Refs to add, or `t.extend` on a builtin, nested by handle type like the app schema.
20
+ * @property {(me: import('../handle/index.js').Context) => void | (() => void) | Promise<void | (() => void)>} [setup] Runs before the root opens; a returned function runs on close.
32
21
  */
33
22
 
34
23
  /** The two every app gets unless its build names a list. */
35
24
  export const bundled = [profileSync(), handleSync()]
36
25
 
37
26
  /**
38
- * The extensions a spec carries, else the bundled two. A bare function is `{ setup }`.
27
+ * The override, else the list the spec carries, else the bundled two. A bare function is `{ setup }`.
39
28
  *
40
- * @param {any} spec
41
- * @param {Array<any>} [override]
29
+ * @param {import('../lib/spec.js').Spec | null} spec
30
+ * @param {Array<Extension | Extension['setup']>} [override]
42
31
  * @returns {Extension[]}
43
32
  */
44
33
  export function extensionsOf(spec, override) {
45
- const list = override || spec?.extensions || bundled
46
- return list.map((e) => (typeof e === 'function' ? { setup: e } : e))
47
- }
48
-
49
- /**
50
- * The operators a spec carries: functions taking the handle first, keyed by namespace, a
51
- * key naming a handle type holding that type's namespaces.
52
- *
53
- * @param {any} spec
54
- * @param {Record<string, any>} [override]
55
- * @returns {Record<string, any>}
56
- */
57
- export function operatorsOf(spec, override) {
58
- return override || spec?.operators || {}
59
- }
60
-
61
- // handle.ns.fn(args) calls fn(handle, args)
62
- function attach(handle, ns, fns) {
63
- const bound = {}
64
- for (const key of Object.keys(fns)) {
65
- if (typeof fns[key] === 'function') bound[key] = (...args) => fns[key](handle, ...args)
66
- }
67
- handle[ns] = bound
68
- }
69
-
70
- /**
71
- * Put the operators for `handle` on it: the root when `type` is null, else a child of `type`.
72
- *
73
- * @param {any} handle
74
- * @param {string | null} type
75
- * @param {Record<string, any>} operators
76
- * @returns {any} handle
77
- */
78
- export function bind(handle, type, operators) {
79
- const handles = handle.spec?.meta?.handles || {}
80
- for (const [ns, fns] of Object.entries(operators)) {
81
- if (type === null) {
82
- if (!(ns in handles)) attach(handle, ns, fns)
83
- } else if (ns === type) {
84
- for (const [k, group] of Object.entries(fns)) attach(handle, k, group)
85
- }
34
+ const list = override ?? spec?.extensions
35
+ // a list built in memory cannot be written into the spec
36
+ if (list === null) {
37
+ throw CeroError.INVALID(
38
+ 'the spec was built with a list of extensions: pass it to cero(dir, spec, { extensions })'
39
+ )
86
40
  }
87
- return handle
41
+ return (list ?? bundled).map((e) => (typeof e === 'function' ? { setup: e } : e))
88
42
  }
@@ -0,0 +1,44 @@
1
+ import { decodeId } from '@cero-base/core/blobs/codec'
2
+
3
+ import { put, get, set } from '../lib/operators.js'
4
+
5
+ /**
6
+ * Write `row`'s name and `fields`, read from `from`, onto row `id` of `to`. A file is copied
7
+ * into `to`'s handle, so it resolves there for everyone in it. Nothing is written when there is
8
+ * no row or it already matches: an unconditional set on every open is an op in the log forever.
9
+ *
10
+ * @param {import('../lib/refs.js').Ref} from
11
+ * @param {Record<string, unknown>} row
12
+ * @param {Record<string, object>} fields
13
+ * @param {import('../lib/refs.js').Ref} to
14
+ * @param {string} id
15
+ * @returns {Promise<void>}
16
+ */
17
+ export async function mirror(from, row, fields, to, id) {
18
+ const { data: was } = await get(to, id)
19
+ if (!was) return
20
+ const files = from.handle.store.refs[from.name]?.files || []
21
+ const out = {}
22
+ let changed = false
23
+ for (const k of ['name', ...Object.keys(fields)]) {
24
+ const file = files.includes(k) && idOf(row[k])
25
+ const prev = idOf(was[k])
26
+ if (!file) {
27
+ out[k] = row[k]
28
+ changed ||= was[k] !== row[k]
29
+ } else if (prev && (await get(to.handle.files, prev)).data?.from === file) {
30
+ out[k] = prev
31
+ } else {
32
+ const data = await from.handle._bytes(file)
33
+ const { type } = decodeId(file)
34
+ const copy = { data, type, name: row[k]?.name ?? null, from: file }
35
+ out[k] = (await put(to.handle.files, copy)).data.id
36
+ changed = true
37
+ }
38
+ }
39
+ if (changed) await set(to, { id, ...out }, { upsert: false })
40
+ }
41
+
42
+ function idOf(value) {
43
+ return typeof value === 'string' ? value : value?.id || null
44
+ }
@@ -1,10 +1,12 @@
1
1
  import { t } from '../lib/spec.js'
2
- import { get, set, changes } from '../lib/operators.js'
2
+ import { get, watch } from '../lib/operators.js'
3
+ import { mirror } from './mirror.js'
3
4
 
4
5
  /**
5
6
  * Mirror your `profile` onto your `member` row in every handle you're in.
6
7
  *
7
- * @param {{ fields?: Record<string, any> }} [opts]
8
+ * @param {{ fields?: Record<string, object> }} [opts] Extra fields, as `t` types.
9
+ * @returns {import('./index.js').Extension}
8
10
  */
9
11
  export function profileSync({ fields = { avatar: t.string } } = {}) {
10
12
  return {
@@ -14,30 +16,26 @@ export function profileSync({ fields = { avatar: t.string } } = {}) {
14
16
  members: t.extend(fields)
15
17
  },
16
18
  setup(me) {
17
- const keys = ['name', ...Object.keys(fields)]
18
-
19
- // an unconditional set on every open is a room-wide op forever
20
- const publish = async (child, profile) => {
21
- const { data: member } = await get(child.members, me.identity.id)
22
- if (member && keys.every((k) => member[k] === profile[k])) return
23
- await set(child.members, { id: me.identity.id, ...profile }, { upsert: false })
24
- }
19
+ const publish = (child, profile) =>
20
+ mirror(me.profile, profile, fields, child.members, me.identity.id)
25
21
 
26
22
  const onHandle = async (child) => {
27
23
  const { data: profile } = await get(me.profile)
28
24
  if (profile) await publish(child, profile)
29
25
  }
30
26
 
31
- me.on('handle', (child) => onHandle(child).catch(me._onerror), { signal: me.signal })
27
+ const onchild = (child) => onHandle(child).catch(me._onerror)
28
+ me.on('handle', onchild)
32
29
 
33
30
  // a local edit and one replicated from another device both land here
34
- const stream = changes(me.profile, {}, { signal: me.signal })
31
+ const stream = watch(me.profile, { changes: true }, { signal: me.signal })
35
32
  stream.on('error', me._onerror)
36
33
  stream.on('data', ({ changes: batch }) => {
37
34
  for (const { next } of batch) {
38
35
  if (next) me.children.forEach((child) => publish(child, next).catch(me._onerror))
39
36
  }
40
37
  })
38
+ return () => me.off('handle', onchild)
41
39
  }
42
40
  }
43
41
  }