@cero-base/cero 2.12.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cero-base/cero",
3
- "version": "2.12.0",
3
+ "version": "3.0.0",
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,
@@ -113,24 +113,25 @@
113
113
  "test:node": "find test -name '*.test.js' | sort | xargs -P4 -n1 brittle-node"
114
114
  },
115
115
  "dependencies": {
116
- "@cero-base/core": "^2.12.0",
116
+ "@cero-base/core": "^3.0.0",
117
117
  "b4a": "^1.9.0",
118
118
  "bare-abort-controller": "^1.1.2",
119
119
  "bare-crypto": "^1.15.4",
120
120
  "bare-fs": "^4.8.4",
121
121
  "bare-path": "^3.1.2",
122
122
  "ble-swarm": "^2.4.0",
123
- "compact-encoding": "^3.5.2",
123
+ "compact-encoding": "^3.6.0",
124
124
  "corestore": "^7.16.1",
125
+ "fd-lock": "^2.2.0",
125
126
  "hrpc": "^4.3.1",
126
- "hypercore": "^11.40.0",
127
+ "hypercore": "^11.40.3",
127
128
  "hypercore-crypto": "^3.7.0",
128
129
  "hypercore-id-encoding": "^1.3.0",
129
130
  "hypercore-storage": "^3.4.0",
130
131
  "hyperdb": "^6.11.1",
131
132
  "hyperdispatch": "^1.6.0",
132
133
  "hyperschema": "^1.26.2",
133
- "protomux": "^3.13.0",
134
+ "protomux": "^3.13.1",
134
135
  "ready-resource": "^1.2.0",
135
136
  "safety-catch": "^1.0.3",
136
137
  "streamx": "^2.28.1",
@@ -13,6 +13,7 @@ import { CeroError } from '@cero-base/core/errors'
13
13
 
14
14
  import { NS } from '../lib/constants.js'
15
15
  import { extensionsOf } from '../extensions/index.js'
16
+ import { reserved } from '../lib/reserved.js'
16
17
  import * as internal from './internal.js'
17
18
 
18
19
  /**
@@ -45,8 +46,10 @@ export async function build(specDir, schema, { ns = NS, extensions } = {}) {
45
46
  const fold = (entries, target, fromExt) => {
46
47
  for (const [k, v] of Object.entries(entries)) {
47
48
  if (v && v.kind === 'extend') {
49
+ if (v.later) throw CeroError.INVALID(`'${k}' extends a builtin: ${holds}`)
48
50
  const type = internal.defs.main[k]?.type
49
51
  if (!type) throw CeroError.INVALID(`'${k}' is not an extendable builtin`)
52
+ if ('memberId' in v.fields) throw CeroError.INVALID(written('memberId', k))
50
53
  // app schema wins on field conflicts, extensions only add new fields
51
54
  extend[type] = fromExt ? { ...v.fields, ...extend[type] } : { ...extend[type], ...v.fields }
52
55
  } else if (fromExt && isPlainHandle(v)) {
@@ -67,33 +70,55 @@ export async function build(specDir, schema, { ns = NS, extensions } = {}) {
67
70
  }
68
71
  for (const { meta } of [main, ...Object.values(handles)]) extendBuiltins(meta.refs, extend)
69
72
 
70
- emitMain(join(specDir, 'main'), ns, main, { rpc: true, extend })
71
- emitLocal(join(specDir, 'local'), ns, local)
72
- for (const [name, handle] of Object.entries(handles)) {
73
- emitMain(join(specDir, 'handles', name), ns, handle, { rpc: false, extend })
74
- }
73
+ // a refused build leaves the spec as it was: it is written beside it and moved in whole
74
+ const next = `${specDir}.next`
75
+ await fs.rm(next, { recursive: true, force: true })
76
+ if (existsSync(specDir)) await fs.cp(specDir, next, { recursive: true })
77
+ try {
78
+ emitMain(join(next, 'main'), ns, main, { rpc: true, extend })
79
+ emitLocal(join(next, 'local'), ns, local)
80
+ for (const [name, handle] of Object.entries(handles)) {
81
+ emitMain(join(next, 'handles', name), ns, handle, { rpc: false, extend })
82
+ }
75
83
 
76
- const dirs = ['main', ...Object.keys(handles).map((n) => join('handles', n))]
77
- const version = await contract(specDir, dirs)
78
- const meta = {
79
- ...main.meta,
80
- version,
81
- local: local.meta,
82
- handles: Object.fromEntries(
83
- Object.entries(handles).map(([n, h]) => [n, { ...h.meta, type: n, version }])
84
- )
85
- }
84
+ const dirs = ['main', ...Object.keys(handles).map((n) => join('handles', n))]
85
+ const compiled = [main, ...Object.values(handles)]
86
+ const { version, start, target, dated } = await contract(next, specDir, dirs, compiled, extend)
87
+ // what a write means to Cero: a view applied under older rules applies its log again
88
+ const rules = internal.contract.version
89
+ const app = { version, rules, start, target }
90
+ const meta = {
91
+ ...main.meta,
92
+ ...app,
93
+ ...dated[0],
94
+ local: local.meta,
95
+ handles: Object.fromEntries(
96
+ Object.entries(handles).map(([n, h], i) => [
97
+ n,
98
+ { ...h.meta, type: n, ...app, ...dated[i + 1] }
99
+ ])
100
+ )
101
+ }
86
102
 
87
- // the type marker tells the runtime which handle type to open
88
- for (const [name] of Object.entries(handles)) {
89
- if (meta.refs[name]) meta.refs[name] = { kind: 'handle', type: name, schema: `@${ns}/handle` }
90
- }
103
+ // the type marker tells the runtime which handle type to open
104
+ for (const [name] of Object.entries(handles)) {
105
+ const ref = meta.refs[name]
106
+ if (ref) {
107
+ meta.refs[name] = { kind: 'handle', type: name, schema: `@${ns}/handle`, since: ref.since }
108
+ }
109
+ }
91
110
 
92
- await fs.writeFile(
93
- join(specDir, 'index.js'),
94
- wireModule(meta, Object.keys(handles), from, extensions),
95
- 'utf-8'
96
- )
111
+ await fs.writeFile(
112
+ join(next, 'index.js'),
113
+ wireModule(meta, Object.keys(handles), from, extensions),
114
+ 'utf-8'
115
+ )
116
+ } catch (err) {
117
+ await fs.rm(next, { recursive: true, force: true })
118
+ throw err
119
+ }
120
+ await fs.rm(specDir, { recursive: true, force: true })
121
+ await fs.rename(next, specDir)
97
122
  }
98
123
 
99
124
  const str = (v) => (typeof v === 'string' ? v : null)
@@ -125,8 +150,9 @@ function splitMain(defs) {
125
150
  function splitHandles(defs) {
126
151
  const out = {}
127
152
  for (const [k, v] of Object.entries(defs)) {
128
- if (k === 'local') continue
129
- if (isPlainHandle(v)) out[k] = v
153
+ if (k === 'local' || !isPlainHandle(v)) continue
154
+ if (v.later) throw CeroError.INVALID(`'${k}' is a handle type: ${holds}`)
155
+ out[k] = v
130
156
  }
131
157
  return out
132
158
  }
@@ -141,33 +167,41 @@ function compile(root, ns, scope = 'main', top = false) {
141
167
  collections: [],
142
168
  dispatches: [],
143
169
  indexes: [],
170
+ things: [],
144
171
  meta: { ns, refs: {} },
145
172
  ns,
146
- scope
173
+ scope,
174
+ taken: internal.reserved(ns, scope, top)
147
175
  }
148
176
 
149
177
  Object.assign(ctx.meta.refs, internal.refs(ns, scope))
150
178
 
151
179
  for (const [name, node] of Object.entries(root)) {
180
+ if (!node.kind || node.kind === 'extend') continue
181
+ if (ctx.taken.refs.has(name)) throw CeroError.INVALID(`'${name}' is a builtin ref, rename it`)
182
+ if (name.startsWith('_') || reserved.includes(name)) {
183
+ throw CeroError.INVALID(`'${name}' is taken by the handle or the client, rename it`)
184
+ }
152
185
  if (node.kind === 'handle') {
186
+ if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(name)) {
187
+ throw CeroError.INVALID(
188
+ `'${name}' is not a handle name: a letter, then letters, digits or _; rename it`
189
+ )
190
+ }
153
191
  ctx.meta.refs[name] = { kind: 'handle', type: node.type || name, schema: `@${ns}/handle` }
154
192
  continue
155
193
  }
156
194
  register(name, node, ctx)
157
195
  }
158
196
 
159
- if (scope === 'main') {
160
- for (const [name, ref] of Object.entries(internal.live(ns, top))) {
161
- if (name in root) throw CeroError.INVALID(`'${name}' is a builtin ref, rename it`)
162
- ctx.meta.refs[name] = ref
163
- }
164
- }
197
+ if (scope === 'main') Object.assign(ctx.meta.refs, internal.live(ns, top))
165
198
 
166
199
  return {
167
200
  types: ctx.types,
168
201
  collections: ctx.collections,
169
202
  dispatches: ctx.dispatches,
170
203
  indexes: ctx.indexes,
204
+ things: ctx.things,
171
205
  meta: ctx.meta
172
206
  }
173
207
  }
@@ -179,8 +213,23 @@ function extendBuiltins(refs, extend) {
179
213
  }
180
214
  }
181
215
 
216
+ const holds = 't.later holds back a field, a collection, a single or an action'
217
+
218
+ const written = (field, name) => `'${field}' in '${name}' is a field Cero writes, rename it`
219
+
182
220
  function register(name, node, ctx) {
183
221
  const fqn = `@${ctx.ns}/${name}`
222
+ const routes = node.kind === 'action' ? [name] : ['add', 'set', 'del'].map((v) => `${v}-${name}`)
223
+ const route = routes.find((r) => ctx.taken.routes.has(r))
224
+ if (route) throw CeroError.INVALID(`'${name}' makes Cero's route '${route}', rename it`)
225
+ if (ctx.taken.types.has(name)) throw CeroError.INVALID(`'${name}' is a builtin type, rename it`)
226
+ const fields = Object.keys(node.fields)
227
+ const marked = fields.filter((f) => node.fields[f].later)
228
+ const held = node.later ? `'${name}'` : marked.length > 0 && `'${marked[0]}' in '${name}'`
229
+ if (ctx.scope === 'local' && held) {
230
+ throw CeroError.INVALID(`${held} is local: t.later holds back what a database shares`)
231
+ }
232
+ ctx.things.push({ name, type: fqn, fields, later: node.later === true, marked })
184
233
  if (node.kind === 'action') {
185
234
  ctx.types.push({ name, compact: false, fields: internal.fields(node.fields) })
186
235
  ctx.dispatches.push({ name, requestType: fqn })
@@ -189,6 +238,7 @@ function register(name, node, ctx) {
189
238
  return
190
239
  }
191
240
  if (node.kind === 'single') {
241
+ if ('memberId' in node.fields) throw CeroError.INVALID(written('memberId', name))
192
242
  ctx.types.push({ name, compact: false, fields: internal.fields(node.fields) })
193
243
  ctx.collections.push({ name, schema: fqn, key: [] })
194
244
  ctx.dispatches.push({ name: `set-${name}`, requestType: fqn })
@@ -201,17 +251,12 @@ function register(name, node, ctx) {
201
251
  return
202
252
  }
203
253
  if (node.kind === 'collection') {
254
+ const field = internal.base.find((f) => f.name in node.fields)
255
+ if (field) throw CeroError.INVALID(written(field.name, name))
204
256
  ctx.types.push({
205
257
  name,
206
258
  compact: false,
207
- fields: [
208
- { name: 'id', type: 'string', required: true },
209
- { name: 'memberId', type: 'string', required: false },
210
- { name: 'index', type: 'uint', required: false },
211
- { name: 'createdAt', type: 'int', required: false },
212
- { name: 'updatedAt', type: 'int', required: false },
213
- ...internal.fields(node.fields)
214
- ]
259
+ fields: [...internal.base, ...internal.fields(node.fields)]
215
260
  })
216
261
  ctx.collections.push({ name, schema: fqn, key: ['id'] })
217
262
  ctx.dispatches.push({ name: `add-${name}`, requestType: fqn })
@@ -240,29 +285,179 @@ function register(name, node, ctx) {
240
285
 
241
286
  // one contract for the app, kept in contract.json: it rises once per build that changes what is
242
287
  // stored, at the root or in any handle type, or what a write means to Cero, never for RPC alone.
243
- // A spec without one starts from its builders' versions, so a shipped app's number never goes down
244
- async function contract(specDir, dirs) {
288
+ // A spec without one starts from its builders' versions, so a shipped app's number never goes down.
289
+ // Its history keeps what each builder was at for every contract, which dates each field, ref and route
290
+ async function contract(specDir, prior, dirs, compiled, extend) {
245
291
  const file = join(specDir, 'contract.json')
246
- const shapes = await Promise.all(dirs.map((dir) => shapeOf(join(specDir, dir))))
247
- const json = JSON.stringify([internal.contract.version, ...shapes.map((s) => s.stored)])
248
- const shape = b4a.toString(crypto.hash(b4a.from(json)), 'hex')
249
292
  const kept = await fs.readFile(file, 'utf-8').then(JSON.parse, () => null)
293
+ // apply reads own from the reader's spec, so a collection keeps the one it shipped with
294
+ const own = { ...kept?.own }
295
+ dirs.forEach((dir, i) => {
296
+ const was = own[dir] || {}
297
+ const now = owned(compiled[i].meta.refs)
298
+ for (const [name, on] of Object.entries(now)) {
299
+ if (name in was && was[name] !== on) {
300
+ throw CeroError.INVALID(
301
+ `'${name}' in ${dir} shipped ${on ? 'without' : 'with'} own: a new rule needs a new collection`
302
+ )
303
+ }
304
+ }
305
+ own[dir] = { ...was, ...now }
306
+ })
307
+ const shapes = await Promise.all(dirs.map((dir) => shapeOf(join(specDir, dir))))
308
+ const shape = hash(shapes)
250
309
  const version = kept
251
310
  ? kept.version + (kept.shape === shape ? 0 : 1)
252
311
  : Math.max(...shapes.flatMap((s) => s.versions))
253
- await fs.writeFile(file, JSON.stringify({ version, shape }, null, 2) + '\n')
254
- return version
312
+
313
+ const rules = internal.contract.version
314
+ const start = kept?.history ? kept.start : (kept?.version ?? version)
315
+ const { floor, history } = await past(kept, prior, dirs, version, start)
316
+ history[version] = Object.fromEntries(dirs.map((dir, i) => [dir, shapes[i].builders]))
317
+
318
+ const contracts = Object.keys(history).map(Number)
319
+ const since = (c) => (c === start ? 0 : c)
320
+ const dated = dirs.map((dir, i) => {
321
+ const first = (at, v) => since(contracts.find((c) => history[c][dir]?.[at] >= v))
322
+ const [types, , routes] = shapes[i].stored
323
+ const out = {
324
+ since: {
325
+ routes: Object.fromEntries(routes.schema.map((r) => [r.name, first(1, r.version)])),
326
+ types: Object.fromEntries(
327
+ types.schema.map((type) => [
328
+ `@${type.namespace}/${type.name}`,
329
+ Object.fromEntries(type.fields.map((f) => [f.name, first(0, f.version)]))
330
+ ])
331
+ )
332
+ },
333
+ encoding: Object.fromEntries(
334
+ contracts.filter((c) => history[c][dir]).map((c) => [c, history[c][dir][0]])
335
+ )
336
+ }
337
+ const { ns, refs } = compiled[i].meta
338
+ for (const ref of Object.values(refs)) {
339
+ if (ref.live) ref.since = 0
340
+ else if (ref.kind === 'handle') {
341
+ ref.since = since(contracts.find((c) => history[c][join('handles', ref.type)]))
342
+ } else ref.since = out.since.routes[routeOf(ref, ns)]
343
+ }
344
+ return out
345
+ })
346
+
347
+ const target = aim(
348
+ dirs.flatMap((dir, i) => declared(compiled[i], extend, dated[i].since.types)),
349
+ Math.max(kept?.target ?? start, floor),
350
+ version
351
+ )
352
+ await fs.writeFile(
353
+ file,
354
+ JSON.stringify({ version, shape, own, rules, start, floor, target, history }, null, 2) + '\n'
355
+ )
356
+ return { version, start, target, dated }
357
+ }
358
+
359
+ function hash(shapes) {
360
+ const json = JSON.stringify([internal.contract.version, ...shapes.map((s) => s.stored)])
361
+ return b4a.toString(crypto.hash(b4a.from(json)), 'hex')
362
+ }
363
+
364
+ // a spec with no history starts one at its contract, from the builders its own spec was at. It
365
+ // kept no rules: hashed under today's, its spec gives the shape it kept only when Cero's rules did
366
+ // not change since
367
+ async function past(kept, prior, dirs, version, start) {
368
+ if (kept?.history) {
369
+ const floor = kept.rules === internal.contract.version ? kept.floor : version
370
+ return { floor, history: { ...kept.history } }
371
+ }
372
+ const had = dirs.filter((dir) => existsSync(join(prior, dir)))
373
+ const shapes = await Promise.all(had.map((dir) => shapeOf(join(prior, dir))))
374
+ const floor = !kept || hash(shapes) === kept.shape ? start : version
375
+ return {
376
+ floor,
377
+ history: { [start]: Object.fromEntries(had.map((d, i) => [d, shapes[i].builders])) }
378
+ }
379
+ }
380
+
381
+ function routeOf({ kind, path, verb }, ns) {
382
+ if (kind === 'action') return `@${ns}/${path[0]}`
383
+ if (kind === 'single') return `@${ns}/set-${path[0]}`
384
+ return `@${ns}/add-${verb || path[0]}`
385
+ }
386
+
387
+ // every thing the app declares in a directory, with its since and whether t.later holds it back
388
+ function declared({ things, meta }, extend, types) {
389
+ const out = []
390
+ for (const { name, type, fields, later, marked } of things) {
391
+ out.push({ label: `'${name}'`, since: meta.refs[name].since, mark: later, held: later })
392
+ for (const f of fields) {
393
+ const mark = marked.includes(f)
394
+ out.push({ label: `'${f}' in '${name}'`, since: types[type][f], mark, held: later || mark })
395
+ }
396
+ }
397
+ // a handle type cannot be held: what it brings turns on with it
398
+ for (const [name, ref] of Object.entries(meta.refs)) {
399
+ if (ref.kind === 'handle') out.push({ label: `'${name}'`, since: ref.since, mark: false })
400
+ }
401
+ for (const [type, fields] of Object.entries(extend)) {
402
+ const ref = Object.keys(internal.defs.main).find((k) => internal.defs.main[k].type === type)
403
+ for (const [f, m] of Object.entries(fields)) {
404
+ const mark = m.later === true
405
+ out.push({
406
+ label: `'${f}' in '${ref}'`,
407
+ since: types[`@${meta.ns}/${type}`][f],
408
+ mark,
409
+ held: mark
410
+ })
411
+ }
412
+ }
413
+ return out
255
414
  }
256
415
 
257
- // what a spec directory stores: its types without the RPC ones, its collections and its routes
416
+ // one below the oldest thing held back: things turn on in the order they shipped, and stay on
417
+ function aim(things, used, version) {
418
+ const marks = things.filter((x) => x.mark)
419
+ const gone = marks.find((x) => x.since <= used)
420
+ if (gone) {
421
+ throw CeroError.INVALID(
422
+ `${gone.label} is in use already: a database may have it, so t.later cannot hold it back`
423
+ )
424
+ }
425
+ if (marks.length === 0) return version
426
+ const oldest = marks.reduce((a, b) => (b.since < a.since ? b : a))
427
+ const target = oldest.since - 1
428
+ const early = things.find((x) => !x.held && x.since > target)
429
+ if (early) {
430
+ throw CeroError.INVALID(
431
+ `${early.label} shipped with or after ${oldest.label}, which t.later holds back: things turn on in the order they shipped, so mark it too, or release ${oldest.label}`
432
+ )
433
+ }
434
+ return target
435
+ }
436
+
437
+ function owned(refs) {
438
+ return Object.fromEntries(
439
+ Object.entries(refs)
440
+ .filter(([, ref]) => ref.kind === 'collection' && !ref.internal)
441
+ .map(([name, ref]) => [name, ref.own === true])
442
+ )
443
+ }
444
+
445
+ // what a spec directory stores: its collections, its routes and the types they name, nothing else in schema.json
258
446
  async function shapeOf(dir) {
259
447
  const read = async (rel) => JSON.parse(await fs.readFile(join(dir, rel), 'utf-8'))
260
- const rpc = new Set(internal.types('rpc').map((type) => type.name))
261
448
  const { version: types, ...schema } = await read('schema/schema.json')
262
449
  const { version: db, ...collections } = await read('db/db.json')
263
450
  const { version: dispatch, ...routes } = await read('dispatch/dispatch.json')
264
- schema.schema = schema.schema.filter((type) => !rpc.has(type.name))
265
- return { stored: [schema, collections, routes], versions: [types || 1, db || 1, dispatch || 1] }
451
+ const named = new Set([
452
+ ...collections.schema.map((x) => x.schema),
453
+ ...routes.schema.map((x) => x.requestType)
454
+ ])
455
+ schema.schema = schema.schema.filter((type) => named.has(`@${type.namespace}/${type.name}`))
456
+ return {
457
+ stored: [schema, collections, routes],
458
+ versions: [types || 1, db || 1, dispatch || 1],
459
+ builders: [types || 1, dispatch || 1]
460
+ }
266
461
  }
267
462
 
268
463
  function emitMain(dir, ns, { types, collections, dispatches, indexes = [] }, { rpc, extend = {} }) {
@@ -273,7 +468,13 @@ function emitMain(dir, ns, { types, collections, dispatches, indexes = [] }, { r
273
468
 
274
469
  const s = Hyperschema.from(schemaDir)
275
470
  const sns = s.namespace(ns)
276
- const keep = slots(schemaDir, ns)
471
+ const added = internal.added(ns)
472
+ const stored = [...internal.collections(ns, 'main'), ...collections, ...added].map(
473
+ (x) => x.schema
474
+ )
475
+ const routes = [...internal.dispatches(ns), ...dispatches, ...internal.appended(ns)]
476
+ const sent = routes.map((x) => x.requestType)
477
+ const keep = slots(schemaDir, ns, new Set([...stored, ...sent]))
277
478
  for (const desc of internal.types('main', extend)) sns.register(keep(desc))
278
479
  for (const desc of types) sns.register(keep(desc))
279
480
  if (rpc) for (const desc of internal.types('rpc')) sns.register(keep(desc))
@@ -284,12 +485,15 @@ function emitMain(dir, ns, { types, collections, dispatches, indexes = [] }, { r
284
485
  for (const desc of internal.collections(ns, 'main')) dns.collections.register(desc)
285
486
  for (const desc of collections) dns.collections.register(desc)
286
487
  for (const desc of indexes) dns.indexes.register(desc)
488
+ // after the app's: indexes number by position, and the app's keep theirs
489
+ for (const desc of internal.indexes(ns, 'main')) dns.indexes.register(desc)
490
+ for (const desc of added) dns.collections.register(desc)
287
491
  HyperdbBuilder.toDisk(db, dbDir, { esm: true })
288
492
 
289
493
  const d = Hyperdispatch.from(schemaDir, dispatchDir)
290
494
  const xns = d.namespace(ns)
291
- for (const desc of internal.dispatches(ns)) xns.register(desc)
292
- for (const desc of dispatches) xns.register(desc)
495
+ const numbered = routeIds(dispatchDir, ns, routes)
496
+ for (const desc of routes) xns.register(numbered(desc))
293
497
  Hyperdispatch.toDisk(d, dispatchDir, { esm: true })
294
498
 
295
499
  if (rpc) {
@@ -306,7 +510,8 @@ function emitLocal(dir, ns, { types, collections, indexes = [] }) {
306
510
 
307
511
  const s = Hyperschema.from(schemaDir)
308
512
  const sns = s.namespace(ns)
309
- const keep = slots(schemaDir, ns)
513
+ const stored = [...internal.collections(ns, 'local'), ...collections].map((x) => x.schema)
514
+ const keep = slots(schemaDir, ns, new Set(stored))
310
515
  for (const desc of internal.types('local')) sns.register(keep(desc))
311
516
  for (const desc of types) sns.register(keep(desc))
312
517
  Hyperschema.toDisk(s, schemaDir, { esm: true })
@@ -319,10 +524,29 @@ function emitLocal(dir, ns, { types, collections, indexes = [] }) {
319
524
  HyperdbBuilder.toDisk(db, dbDir, { esm: true })
320
525
  }
321
526
 
527
+ // a route keeps the id the built spec gave it, and one the spec lacks takes the next free: its id
528
+ // is what an op starts with on the wire, and left to hyperdispatch a new route takes its position
529
+ // in the list, which a route registered after it already has
530
+ function routeIds(dispatchDir, ns, routes) {
531
+ const file = join(dispatchDir, 'dispatch.json')
532
+ const built = existsSync(file) ? JSON.parse(readFileSync(file, 'utf-8')).schema : []
533
+ // a built route stays in the spec: with no handler left for it, the first write would fail
534
+ const names = new Set(routes.map((route) => `@${ns}/${route.name}`))
535
+ const gone = built.find((route) => !names.has(route.name))
536
+ if (gone) {
537
+ throw CeroError.INVALID(
538
+ `route '${gone.name}' shipped and this schema lacks it: every log holds writes to it, so what shipped stays declared as it was`
539
+ )
540
+ }
541
+ const had = new Map(built.map((route) => [route.name, route.id]))
542
+ let next = built.reduce((max, route) => Math.max(max, route.id + 1), 0)
543
+ return (desc) => ({ ...desc, id: had.get(`@${ns}/${desc.name}`) ?? next++ })
544
+ }
545
+
322
546
  // a field keeps the slot the built spec gave it, whichever schema declares it: hyperschema stores
323
547
  // a row by position, and a type's fields are cero's, then its extensions', then the app's, so one
324
548
  // more of cero's would take an extension's slot. A field the spec lacks goes after the ones it has
325
- function slots(schemaDir, ns) {
549
+ function slots(schemaDir, ns, stored) {
326
550
  const file = join(schemaDir, 'schema.json')
327
551
  const built = existsSync(file) ? JSON.parse(readFileSync(file, 'utf-8')).schema : []
328
552
  const had = new Map(
@@ -333,6 +557,21 @@ function slots(schemaDir, ns) {
333
557
  return (desc) => {
334
558
  const names = had.get(desc.name)
335
559
  if (!names || !desc.fields) return desc
560
+ const lost = (n) => !desc.fields.some((f) => f.name === n)
561
+ const kept = stored.has(`@${ns}/${desc.name}`)
562
+ const gone = kept && names.find(lost)
563
+ if (gone) {
564
+ throw CeroError.INVALID(
565
+ `'${gone}' was removed from '${desc.name}': fields are stored by position`
566
+ )
567
+ }
568
+ // a required field is stored with no sign of its absence: a row written before it would not decode
569
+ const late = kept && desc.fields.find((f) => f.required && !names.includes(f.name))
570
+ if (late) {
571
+ throw CeroError.INVALID(
572
+ `'${late.name}' on '${desc.name}' is required, and rows stored before it lack it: add it without required`
573
+ )
574
+ }
336
575
  const at = (f) => (names.includes(f.name) ? names.indexOf(f.name) : names.length)
337
576
  return { ...desc, fields: desc.fields.toSorted((a, b) => at(a) - at(b)) }
338
577
  }
@@ -1,5 +1,5 @@
1
1
  import { CeroError } from '@cero-base/core/errors'
2
- import { COUNTERS, EPOCHS, REMOVALS, REFUSALS, SPENT } from '../lib/constants.js'
2
+ import { COUNTERS, EPOCHS, REMOVALS, REFUSALS, SPENT, ASKS } from '../lib/constants.js'
3
3
  import * as schemas from './schemas.js'
4
4
 
5
5
  // internal refs by scope; kind defaults to collection
@@ -10,7 +10,8 @@ export const defs = {
10
10
  members: { type: 'member' },
11
11
  devices: { type: 'device' },
12
12
  invites: { type: 'invite' },
13
- handles: { type: 'handle' },
13
+ // the handles of one state, and a page of one type and state in list order, are read through them
14
+ handles: { type: 'handle', indexes: { state: ['state'], type: ['type', 'state', 'index'] } },
14
15
  files: { type: 'file' },
15
16
  requests: { type: 'request' }
16
17
  },
@@ -24,14 +25,24 @@ export const defs = {
24
25
  outbox: { type: 'mail' },
25
26
  environment: { type: 'environment', kind: 'single' },
26
27
  serving: { type: 'serving' },
27
- topics: { type: 'subscription' }
28
+ topics: { type: 'subscription' },
29
+ told: { type: 'told', kind: 'single' },
30
+ asks: { type: 'ask' }
28
31
  }
29
32
  }
30
33
 
34
+ // the fields Cero writes on every collection row, ahead of the app's
35
+ export const base = [
36
+ { name: 'id', type: 'string', required: true },
37
+ { name: 'memberId', type: 'string', required: false },
38
+ { name: 'index', type: 'uint', required: false },
39
+ { name: 'createdAt', type: 'int', required: false },
40
+ { name: 'updatedAt', type: 'int', required: false }
41
+ ]
42
+
31
43
  // computed on the device, never stored: `get` and `watch` read them like any other ref
32
44
  const LIVE = {
33
45
  status: { type: 'status', kind: 'single' },
34
- joins: { type: 'joining', root: true },
35
46
  nearby: { type: 'peer', root: true },
36
47
  topics: { type: 'topic', root: true }
37
48
  }
@@ -112,6 +123,7 @@ export function refs(ns, scope) {
112
123
  path: [name],
113
124
  internal: true,
114
125
  ...(scope === 'main' && declare({ verb: def.type }, schemas.main[def.type])),
126
+ ...(def.indexes && { indexes: def.indexes }),
115
127
  schema: `@${ns}/${def.type}`
116
128
  }
117
129
  ])
@@ -156,11 +168,36 @@ export function collections(ns, scope) {
156
168
  return out
157
169
  }
158
170
 
171
+ /**
172
+ * @param {string} ns
173
+ * @returns {Array<{ name: string, schema: string, key: string[] }>}
174
+ */
175
+ // collections cero added once apps shipped: numbered after the app's collections and indexes, so
176
+ // a new spec gives each of those the id an older release gave it
177
+ export function added(ns) {
178
+ return [{ name: ASKS, schema: `@${ns}/owed`, key: ['id'] }]
179
+ }
180
+
181
+ /**
182
+ * @param {string} ns
183
+ * @param {'main' | 'local'} scope
184
+ * @returns {Array<{ name: string, collection: string, key: string[] }>}
185
+ */
186
+ export function indexes(ns, scope) {
187
+ return Object.entries(defs[scope]).flatMap(([name, def]) =>
188
+ Object.entries(def.indexes || {}).map(([idx, key]) => ({
189
+ name: `${name}-${idx}`,
190
+ collection: `@${ns}/${name}`,
191
+ key
192
+ }))
193
+ )
194
+ }
195
+
159
196
  /**
160
197
  * @param {string} ns
161
198
  * @returns {Array<{ name: string, requestType: string }>}
162
199
  */
163
- // frozen once an app ships: routes number by position, so a new one goes after the app's
200
+ // a route keeps the id a built spec gave it, and one added here takes the next free id there
164
201
  export function dispatches(ns) {
165
202
  return [
166
203
  { name: 'add-writer', requestType: `@${ns}/writer` },
@@ -178,6 +215,44 @@ export function dispatches(ns) {
178
215
  ]
179
216
  }
180
217
 
218
+ /**
219
+ * @param {string} ns
220
+ * @returns {Array<{ name: string, requestType: string }>}
221
+ */
222
+ // routes cero added once apps shipped: numbered after the app's, so a new spec gives the app's
223
+ // routes the ids an older release gave them
224
+ export function appended(ns) {
225
+ return [
226
+ { name: 'upgrade', requestType: `@${ns}/upgrade` },
227
+ { name: 'revoke', requestType: `@${ns}/revoke` },
228
+ { name: 'ask-key', requestType: `@${ns}/owed` },
229
+ { name: 'del-owed', requestType: `@${ns}/del-by-id` },
230
+ { name: 'cancel-join', requestType: `@${ns}/del-by-id` }
231
+ ]
232
+ }
233
+
234
+ /**
235
+ * The names Cero takes in a scope, which an app ref would shadow: its refs and collections, its
236
+ * types and its routes.
237
+ *
238
+ * @param {string} ns
239
+ * @param {'main' | 'local'} scope
240
+ * @param {boolean} root
241
+ * @returns {{ refs: Set<string>, types: Set<string>, routes: Set<string> }}
242
+ */
243
+ export function reserved(ns, scope, root) {
244
+ const main = scope === 'main'
245
+ return {
246
+ refs: new Set([
247
+ ...collections(ns, scope).map((c) => c.name),
248
+ ...(main ? added(ns) : []).map((c) => c.name),
249
+ ...Object.keys(main ? live(ns, root) : {})
250
+ ]),
251
+ types: new Set(Object.keys({ ...schemas[scope], ...(main && schemas.rpc) })),
252
+ routes: new Set(main ? [...dispatches(ns), ...appended(ns)].map((d) => d.name) : [])
253
+ }
254
+ }
255
+
181
256
  // hrpc commands: name, request type, response type, streaming response
182
257
  const COMMANDS = [
183
258
  ['init', 'req-empty', 'res-identity'],