@cero-base/cero 2.3.4 → 2.4.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.
package/README.md CHANGED
@@ -69,7 +69,7 @@ That is a working, encrypted, offline-first, peer-to-peer app. Your phrase, `awa
69
69
 
70
70
  | Subpath | What it gives you |
71
71
  | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
72
- | `@cero-base/cero` | `cero`, `t`, `schema`, `restore`, `toSeed`, `peek`, the 24 operators, `Handle`, `Ref`, `Local` |
72
+ | `@cero-base/cero` | `cero`, `t`, `schema`, `restore`, `peek`, the 24 operators, `Handle`, `Ref`, `Local` |
73
73
  | `@cero-base/cero/build` | `build(specDir, schema, opts)` |
74
74
  | `@cero-base/cero/server` | `serve(ipc, spec, opts)` and `Server`, the worker that owns the data |
75
75
  | `@cero-base/cero/client` | `cero(ipc, spec)` (also `connect`), `Client`, `restore`, `t`, `schema` and every operator but `before`, `after` and `tx`, for a UI process |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cero-base/cero",
3
- "version": "2.3.4",
3
+ "version": "2.4.1",
4
4
  "description": "The ideal p2p API — everything is a handle, handles contain refs, refs contain rows.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -99,7 +99,7 @@
99
99
  "test:node": "find test -name '*.test.js' | sort | xargs -P4 -n1 brittle-node"
100
100
  },
101
101
  "dependencies": {
102
- "@cero-base/core": "^2.3.4",
102
+ "@cero-base/core": "^2.4.1",
103
103
  "b4a": "^1.9.0",
104
104
  "bare-abort-controller": "^1.1.2",
105
105
  "bare-crypto": "^1.15.4",
@@ -116,6 +116,7 @@
116
116
  "hyperdb": "^6.9.0",
117
117
  "hyperdispatch": "^1.6.0",
118
118
  "hyperschema": "^1.26.2",
119
+ "protomux": "^3.12.1",
119
120
  "ready-resource": "^1.2.0",
120
121
  "safety-catch": "^1.0.3",
121
122
  "streamx": "^2.28.1",
@@ -2,6 +2,8 @@ import { join, resolve } from 'path'
2
2
  import { promises as fs } from 'fs'
3
3
  import { pathToFileURL } from 'url'
4
4
 
5
+ import b4a from 'b4a'
6
+ import crypto from 'hypercore-crypto'
5
7
  import Hyperschema from 'hyperschema'
6
8
  import HyperdbBuilder from 'hyperdb/builder'
7
9
  import Hyperdispatch from 'hyperdispatch'
@@ -9,7 +11,7 @@ import HRPCBuilder from 'hrpc'
9
11
 
10
12
  import { CeroError } from '@cero-base/core/errors'
11
13
 
12
- import { NS, REFUSALS, SPENT } from '../lib/constants.js'
14
+ import { NS } from '../lib/constants.js'
13
15
  import { extensionsOf } from '../extensions/index.js'
14
16
  import * as internal from './internal.js'
15
17
 
@@ -71,12 +73,14 @@ export async function build(specDir, schema, { ns = NS, extensions } = {}) {
71
73
  emitMain(join(specDir, 'handles', name), ns, handle, { rpc: false, extend })
72
74
  }
73
75
 
76
+ const dirs = ['main', ...Object.keys(handles).map((n) => join('handles', n))]
77
+ const version = await contract(specDir, dirs)
74
78
  const meta = {
75
79
  ...main.meta,
76
- version: await contractVersion(join(specDir, 'main')),
80
+ version,
77
81
  local: local.meta,
78
82
  handles: Object.fromEntries(
79
- Object.entries(handles).map(([n, h]) => [n, { ...h.meta, type: n }])
83
+ Object.entries(handles).map(([n, h]) => [n, { ...h.meta, type: n, version }])
80
84
  )
81
85
  }
82
86
 
@@ -231,18 +235,31 @@ function register(name, node, ctx) {
231
235
  }
232
236
  }
233
237
 
234
- // the contract version is the highest of the schema, db and dispatch versions
235
- async function contractVersion(mainDir) {
236
- const read = async (rel) => {
237
- const j = JSON.parse(await fs.readFile(join(mainDir, rel), 'utf-8'))
238
- return j.version || 1
239
- }
240
- const versions = await Promise.all([
241
- read('schema/schema.json'),
242
- read('db/db.json'),
243
- read('dispatch/dispatch.json')
244
- ])
245
- return Math.max(...versions)
238
+ // one contract for the app, kept in contract.json: it rises once per build that changes what is
239
+ // stored, at the root or in any handle type, never for RPC alone. A spec without one starts from
240
+ // its builders' versions, so a shipped app's number never goes down
241
+ async function contract(specDir, dirs) {
242
+ const file = join(specDir, 'contract.json')
243
+ const shapes = await Promise.all(dirs.map((dir) => shapeOf(join(specDir, dir))))
244
+ const json = JSON.stringify(shapes.map((s) => s.stored))
245
+ const shape = b4a.toString(crypto.hash(b4a.from(json)), 'hex')
246
+ const kept = await fs.readFile(file, 'utf-8').then(JSON.parse, () => null)
247
+ const version = kept
248
+ ? kept.version + (kept.shape === shape ? 0 : 1)
249
+ : Math.max(...shapes.flatMap((s) => s.versions))
250
+ await fs.writeFile(file, JSON.stringify({ version, shape }, null, 2) + '\n')
251
+ return version
252
+ }
253
+
254
+ // what a spec directory stores: its types without the RPC ones, its collections and its routes
255
+ async function shapeOf(dir) {
256
+ const read = async (rel) => JSON.parse(await fs.readFile(join(dir, rel), 'utf-8'))
257
+ const rpc = new Set(internal.types('rpc').map((type) => type.name))
258
+ const { version: types, ...schema } = await read('schema/schema.json')
259
+ const { version: db, ...collections } = await read('db/db.json')
260
+ const { version: dispatch, ...routes } = await read('dispatch/dispatch.json')
261
+ schema.schema = schema.schema.filter((type) => !rpc.has(type.name))
262
+ return { stored: [schema, collections, routes], versions: [types || 1, db || 1, dispatch || 1] }
246
263
  }
247
264
 
248
265
  function emitMain(dir, ns, { types, collections, dispatches, indexes = [] }, { rpc, extend = {} }) {
@@ -263,18 +280,12 @@ function emitMain(dir, ns, { types, collections, dispatches, indexes = [] }, { r
263
280
  for (const desc of internal.collections(ns, 'main')) dns.collections.register(desc)
264
281
  for (const desc of collections) dns.collections.register(desc)
265
282
  for (const desc of indexes) dns.indexes.register(desc)
266
- // after the app's: hyperdb numbers collections positionally and persists them
267
- dns.collections.register({ name: REFUSALS, schema: `@${ns}/refusal`, key: ['id'] })
268
- dns.collections.register({ name: SPENT, schema: `@${ns}/spent`, key: ['id'] })
269
283
  HyperdbBuilder.toDisk(db, dbDir, { esm: true })
270
284
 
271
285
  const d = Hyperdispatch.from(schemaDir, dispatchDir)
272
286
  const xns = d.namespace(ns)
273
287
  for (const desc of internal.dispatches(ns)) xns.register(desc)
274
288
  for (const desc of dispatches) xns.register(desc)
275
- // after the app's dispatches: hyperdispatch numbers routes positionally and persists them
276
- xns.register({ name: 'rotate-key', requestType: `@${ns}/epoch` })
277
- xns.register({ name: 'del-refusal', requestType: `@${ns}/del-by-id` })
278
289
  Hyperdispatch.toDisk(d, dispatchDir, { esm: true })
279
290
 
280
291
  if (rpc) {
@@ -1,5 +1,5 @@
1
1
  import { CeroError } from '@cero-base/core/errors'
2
- import { COUNTERS, EPOCHS, REMOVALS } from '../lib/constants.js'
2
+ import { COUNTERS, EPOCHS, REMOVALS, REFUSALS, SPENT } from '../lib/constants.js'
3
3
  import * as schemas from './schemas.js'
4
4
 
5
5
  // internal refs by scope; kind defaults to collection
@@ -134,6 +134,7 @@ export function declare(ref, fields) {
134
134
  * @param {'main' | 'local'} scope
135
135
  * @returns {Array<{ name: string, schema: string, key: string[] }>}
136
136
  */
137
+ // frozen once an app ships: collections number by position, so a new one goes after the app's
137
138
  export function collections(ns, scope) {
138
139
  const out = Object.entries(defs[scope]).map(([name, def]) => ({
139
140
  name,
@@ -144,6 +145,8 @@ export function collections(ns, scope) {
144
145
  out.push({ name: COUNTERS, schema: `@${ns}/counter`, key: ['name'] })
145
146
  out.push({ name: EPOCHS, schema: `@${ns}/epoch`, key: ['epoch'] })
146
147
  out.push({ name: REMOVALS, schema: `@${ns}/removal`, key: ['id'] })
148
+ out.push({ name: REFUSALS, schema: `@${ns}/refusal`, key: ['id'] })
149
+ out.push({ name: SPENT, schema: `@${ns}/spent`, key: ['id'] })
147
150
  }
148
151
  return out
149
152
  }
@@ -152,18 +155,21 @@ export function collections(ns, scope) {
152
155
  * @param {string} ns
153
156
  * @returns {Array<{ name: string, requestType: string }>}
154
157
  */
158
+ // frozen once an app ships: routes number by position, so a new one goes after the app's
155
159
  export function dispatches(ns) {
156
160
  return [
157
161
  { name: 'add-writer', requestType: `@${ns}/writer` },
158
162
  { name: 'del-writer', requestType: `@${ns}/writer` },
159
- { name: 'claim-writer', requestType: `@${ns}/claim` },
160
163
  ...Object.values(defs.main).flatMap(({ type }) => [
161
164
  { name: `add-${type}`, requestType: `@${ns}/${type}` },
162
165
  { name: `set-${type}`, requestType: `@${ns}/${type}` },
163
166
  { name: `del-${type}`, requestType: `@${ns}/del-by-id` }
164
167
  ]),
165
168
  { name: 'join', requestType: `@${ns}/join` },
166
- { name: 'accept', requestType: `@${ns}/accept` }
169
+ { name: 'accept', requestType: `@${ns}/accept` },
170
+ { name: 'deny', requestType: `@${ns}/deny` },
171
+ { name: 'rotate-key', requestType: `@${ns}/epoch` },
172
+ { name: 'del-refusal', requestType: `@${ns}/del-by-id` }
167
173
  ]
168
174
  }
169
175
 
@@ -171,29 +177,21 @@ export function dispatches(ns) {
171
177
  const COMMANDS = [
172
178
  ['init', 'req-empty', 'res-identity'],
173
179
  ['restore', 'req-restore', 'res-identity'],
174
- ['seed', 'req-empty', 'res-seed'],
180
+ ['errors', 'req-empty', 'res-error', true],
175
181
  ['add-row', 'req-row', 'res-data'],
176
182
  ['add-file', 'req-add-file', 'res-data'],
177
- ['add-handle', 'req-row', 'res-handle'],
178
183
  ['set', 'req-row', 'res-data'],
179
184
  ['get', 'req-query', 'res-rows'],
180
185
  ['del', 'req-id', 'res-ok'],
181
186
  ['watch', 'req-query', 'res-rows', true],
182
187
  ['call', 'req-call', 'res-data'],
183
- ['invite', 'req-invite', 'res-invite'],
184
- ['revoke', 'req-revoke', 'res-ok'],
185
- ['join', 'req-join', 'res-handle'],
186
- ['cancel', 'req-cancel', 'res-ok'],
188
+ ['add-handle', 'req-row', 'res-handle'],
187
189
  ['open-handle', 'req-open', 'res-handle'],
190
+ ['join', 'req-join', 'res-handle'],
188
191
  ['close-handle', 'req-handle', 'res-ok'],
192
+ // not a verb: it ends the handle on both sides
189
193
  ['leave', 'req-handle', 'res-ok'],
190
- ['rotate', 'req-handle', 'res-epoch'],
191
- ['set-active', 'req-set-active', 'res-ok'],
192
- ['suspend', 'req-handle', 'res-ok'],
193
- ['resume', 'req-handle', 'res-ok'],
194
- ['errors', 'req-empty', 'res-error', true],
195
- ['answer', 'req-answer', 'res-ok'],
196
- ['nearby', 'req-nearby', 'res-ok']
194
+ ['verb', 'req-verb', 'res-data']
197
195
  ]
198
196
 
199
197
  /**
@@ -70,12 +70,6 @@ export const main = {
70
70
  // the file this one was copied from, so a sync copies it once
71
71
  from: string
72
72
  },
73
- claim: {
74
- identity: required(bytes),
75
- writer: required(bytes),
76
- sig: required(bytes),
77
- ts: int
78
- },
79
73
  epoch: {
80
74
  epoch: required(uint),
81
75
  wrapped: required(bytes),
@@ -135,7 +129,7 @@ export const main = {
135
129
  isMobile: bool,
136
130
  device: string
137
131
  },
138
- // a join the room turned away, until the joiner read why. `id` is the joiner's writer
132
+ // a join the handle turned away, until the joiner read why. `id` is the joiner's writer
139
133
  refusal: {
140
134
  id: required(string),
141
135
  reply: required(bytes),
@@ -147,6 +141,10 @@ export const main = {
147
141
  id: required(string),
148
142
  reason: required(string),
149
143
  expires: int
144
+ },
145
+ deny: {
146
+ id: required(string),
147
+ reason: string
150
148
  }
151
149
  }
152
150
 
@@ -166,7 +164,7 @@ export const local = {
166
164
  secretKey: required(bytes),
167
165
  encryptionKey: bytes
168
166
  },
169
- // a room with invites, reopened at boot so its joins are answered
167
+ // a handle with invites, reopened at boot so its joins are answered
170
168
  serving: {
171
169
  id: required(string),
172
170
  type: required(string)
@@ -179,7 +177,7 @@ export const local = {
179
177
  invite: required(string),
180
178
  publicKey: required(bytes),
181
179
  secretKey: required(bytes),
182
- // the reply, once it landed: the join then opens the room without joining again
180
+ // the reply, once it landed: the join then opens the handle without joining again
183
181
  key: bytes,
184
182
  encryptionKey: bytes,
185
183
  epochs: bytes
@@ -230,38 +228,25 @@ export const rpc = {
230
228
  op: required(string),
231
229
  data: bytes
232
230
  },
233
- 'req-invite': {
231
+ // an operator by name, run on the handle as in the worker: the args and the result are c.any
232
+ 'req-verb': {
234
233
  handle: required(string),
235
- role: string,
236
- // ms, or a duration like '12h'
237
- ttl: string,
238
- reuse: bool,
239
- data: bytes,
240
- confirm: bool
241
- },
242
- 'req-revoke': {
243
- handle: required(string),
244
- invite: required(string)
234
+ verb: required(string),
235
+ args: required(bytes)
245
236
  },
246
237
  'req-join': {
247
238
  parent: required(string),
248
239
  ref: required(string),
249
240
  invite: required(string)
250
241
  },
251
- 'req-cancel': {
252
- invite: required(string)
253
- },
254
242
  'req-open': {
255
243
  parent: required(string),
256
- row: required(string)
244
+ row: required(string),
245
+ type: string
257
246
  },
258
247
  'req-handle': {
259
248
  handle: required(string)
260
249
  },
261
- 'req-set-active': {
262
- handle: required(string),
263
- active: bool
264
- },
265
250
  'res-data': {
266
251
  data: bytes
267
252
  },
@@ -270,9 +255,6 @@ export const rpc = {
270
255
  total: required(int),
271
256
  size: required(int)
272
257
  },
273
- 'res-invite': {
274
- invite: required(string)
275
- },
276
258
  'res-handle': {
277
259
  id: required(string),
278
260
  type: required(string),
@@ -294,32 +276,13 @@ export const rpc = {
294
276
  fileToken: string,
295
277
  deviceName: string
296
278
  },
297
- 'res-seed': {
298
- phrase: string
299
- },
300
279
  'res-ok': {
301
280
  ok: bool
302
281
  },
303
- 'res-epoch': {
304
- epoch: required(uint)
305
- },
306
282
  'res-error': {
307
283
  message: required(string),
308
284
  code: string,
309
285
  stack: string,
310
286
  reason: string
311
- },
312
- // accept, or deny with a reason
313
- 'req-answer': {
314
- handle: required(string),
315
- id: required(string),
316
- accept: bool,
317
- role: string,
318
- reason: string
319
- },
320
- // the mesh when `on`, one invite's rendezvous when `invite` is set
321
- 'req-nearby': {
322
- on: bool,
323
- invite: string
324
287
  }
325
288
  }
@@ -16,8 +16,14 @@ export function profileSync({ fields = { avatar: t.string } } = {}) {
16
16
  members: t.extend(fields)
17
17
  },
18
18
  setup(me) {
19
- const publish = (child, profile) =>
20
- mirror(me.profile, profile, fields, child.members, me.identity.id)
19
+ const publish = async (child, profile) => {
20
+ try {
21
+ await mirror(me.profile, profile, fields, child.members, me.identity.id)
22
+ } catch (err) {
23
+ // a handle that closed meanwhile has no member row left to update
24
+ if (!child.closing) throw err
25
+ }
26
+ }
21
27
 
22
28
  const onHandle = async (child) => {
23
29
  const { data: profile } = await get(me.profile)