@cero-base/core 2.2.1 → 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 (55) hide show
  1. package/README.md +32 -212
  2. package/package.json +18 -9
  3. package/src/blobs/index.js +9 -0
  4. package/src/blobs/server.js +2 -0
  5. package/src/database/changes.js +1 -1
  6. package/src/database/dispatch.js +341 -209
  7. package/src/database/encryption.js +83 -33
  8. package/src/database/index.js +184 -83
  9. package/src/database/rotation.js +43 -30
  10. package/src/identity/index.js +20 -78
  11. package/src/index.js +3 -10
  12. package/src/lib/constants.js +2 -0
  13. package/src/lib/errors.js +3 -11
  14. package/src/lib/spec/index.js +136 -132
  15. package/src/lib/spec/schema.json +84 -99
  16. package/src/lib/utils.js +57 -3
  17. package/src/mailbox/inbox.js +103 -0
  18. package/src/mailbox/index.js +146 -0
  19. package/src/mailbox/post.js +69 -0
  20. package/src/network/discovery.js +26 -1
  21. package/src/network/index.js +105 -64
  22. package/src/network/presence.js +6 -2
  23. package/src/pairing/index.js +330 -254
  24. package/src/pairing/invite.js +83 -144
  25. package/src/pairing/request.js +54 -56
  26. package/src/rpc/index.js +18 -93
  27. package/src/rpc/peer.js +4 -1
  28. package/src/storage/index.js +78 -39
  29. package/types/blobs/index.d.ts +22 -9
  30. package/types/blobs/server.d.ts +4 -2
  31. package/types/database/changes.d.ts +2 -2
  32. package/types/database/dispatch.d.ts +19 -13
  33. package/types/database/encryption.d.ts +67 -29
  34. package/types/database/index.d.ts +144 -119
  35. package/types/database/rotation.d.ts +32 -13
  36. package/types/identity/index.d.ts +6 -47
  37. package/types/index.d.ts +3 -16
  38. package/types/lib/constants.d.ts +1 -0
  39. package/types/lib/errors.d.ts +3 -9
  40. package/types/lib/spec/index.d.ts +52 -16
  41. package/types/lib/utils.d.ts +40 -8
  42. package/types/mailbox/inbox.d.ts +52 -0
  43. package/types/mailbox/index.d.ts +111 -0
  44. package/types/mailbox/post.d.ts +37 -0
  45. package/types/network/discovery.d.ts +21 -5
  46. package/types/network/index.d.ts +64 -48
  47. package/types/network/presence.d.ts +17 -4
  48. package/types/pairing/index.d.ts +143 -134
  49. package/types/pairing/invite.d.ts +70 -114
  50. package/types/pairing/request.d.ts +58 -98
  51. package/types/rpc/index.d.ts +26 -44
  52. package/types/rpc/peer.d.ts +10 -7
  53. package/types/storage/index.d.ts +64 -54
  54. package/src/pairing/candidate.js +0 -123
  55. package/types/pairing/candidate.d.ts +0 -36
@@ -1,6 +1,6 @@
1
- import BlindPairing from 'blind-pairing'
2
- import sodium from 'sodium-universal'
1
+ import crypto from 'hypercore-crypto'
3
2
  import b4a from 'b4a'
3
+ import ms from 'ms'
4
4
  import z32 from 'z32'
5
5
  import c from 'compact-encoding'
6
6
 
@@ -8,194 +8,133 @@ import { getEncoding } from '../lib/spec/index.js'
8
8
  import { CeroError } from '../lib/errors.js'
9
9
 
10
10
  const VERSION = 1
11
- const Envelope = getEncoding('@cero/invite')
12
- const SignBody = getEncoding('@cero/invite-body')
11
+ const Encoding = getEncoding('@cero/invite')
12
+ const [NS_KEY, NS_PROOF] = crypto.namespace('cero/invite', 2)
13
13
 
14
14
  /**
15
15
  * @typedef {object} InviteFields
16
- * @property {Uint8Array} publicKey Signer's long-lived public key.
17
- * @property {string} role Optional role tag baked into the signed body.
18
- * @property {number} expires Absolute expiry timestamp; `0` means never.
19
- * @property {Uint8Array | null} data Encoded payload (raw or via `encoding`).
20
- * @property {Uint8Array} blind Raw blind-pairing invite handed to candidates.
21
- * @property {Uint8Array} [sig] Ed25519 signature over the canonical body.
22
- * @property {string | null} [_str] Cached z32 string form.
23
- *
24
- * @typedef {object} CreateInviteOpts
25
- * @property {Uint8Array} secretKey 64-byte Ed25519 secret key used to sign.
26
- * @property {Uint8Array} publicKey 32-byte Ed25519 public key matching `secretKey`.
27
- * @property {string} role Optional role tag for the joiner.
28
- * @property {number} expiresIn TTL in ms from now; `0` means never expires.
29
- * @property {any} data Caller payload; encoded via `encoding` when provided.
30
- * @property {Uint8Array} blind Raw blind-pairing invite to wrap.
31
- * @property {any} [encoding] compact-encoding type used to encode `data`.
32
- *
33
- * @typedef {object} ParseInviteOpts
34
- * @property {any} [encoding] compact-encoding type used to decode the embedded payload.
16
+ * @property {number} expires Absolute expiry timestamp; `0` means never.
17
+ * @property {Uint8Array} key Key of the database the invite opens.
18
+ * @property {Uint8Array} address The database's address: a join is sealed to it.
19
+ * @property {Uint8Array} seed The invite's secret; its keypair proves a join.
20
+ * @property {{ key: Uint8Array, length: number } | null} link The node that added its record: a join links it, so no member applies the join first.
21
+ * @property {Uint8Array | null} [data] The app's payload, readable before joining. Unsigned: a hint, not proof.
35
22
  */
36
23
 
37
24
  /**
38
- * Signed, expirable pairing invite. Wraps a blind-pairing invite with a role, optional
39
- * payload and an Ed25519 signature so the host can be authenticated by the joiner before
40
- * any handshake happens.
41
- *
42
- * @property {any} [_rawData] Decoded payload kept alongside the encoded `data` for convenience.
43
- * @property {Uint8Array} _discoveryKey Cached discovery key of the wrapped blind invite.
25
+ * An invite: the database it opens, the address a join is sealed to, and a seed whose keypair
26
+ * proves the joiner holds the invite. Role and expiry come from the database's own record;
27
+ * `expires` is here so a joiner fails fast.
44
28
  */
45
29
  export class Invite {
46
- /** @param {InviteFields} fields */
47
- constructor(fields) {
30
+ /** @param {InviteFields & { _str?: string }} fields */
31
+ constructor({ expires, key, address, seed, link = null, data = null, _str = null }) {
48
32
  this.version = VERSION
49
- this.publicKey = fields.publicKey
50
- this.role = fields.role
51
- this.expires = fields.expires
52
- this.data = fields.data
53
- this.blind = fields.blind
54
- this.sig = fields.sig
55
- this._str = fields._str || null
56
-
57
- this._discoveryKey = null
33
+ this.expires = expires
34
+ this.key = key
35
+ this.address = address
36
+ this.seed = seed
37
+ this.link = link
38
+ this.data = data
39
+ /** @private */
40
+ this._str = _str
41
+ /** @private */
42
+ this._keyPair = null
58
43
  }
59
44
 
60
- /**
61
- * Whether the invite is past its TTL (always `false` when `expires === 0`).
62
- *
63
- * @returns {boolean}
64
- */
45
+ /** @returns {boolean} Whether the invite is past its expiry (never when `expires === 0`). */
65
46
  get expired() {
66
47
  return this.expires > 0 && Date.now() > this.expires
67
48
  }
68
49
 
69
- /**
70
- * Discovery key of the wrapped blind-pairing invite — the topic it targets.
71
- *
72
- * @returns {Uint8Array}
73
- */
50
+ /** @returns {Uint8Array} Discovery key of the database the invite opens. */
74
51
  get discoveryKey() {
75
- if (!this._discoveryKey) {
76
- this._discoveryKey = BlindPairing.decodeInvite(this.blind).discoveryKey
77
- }
78
- return this._discoveryKey
52
+ return crypto.discoveryKey(this.key)
53
+ }
54
+
55
+ /** @returns {Uint8Array} The invite's id: the public key of its seed's keypair. */
56
+ get id() {
57
+ return this._pair().publicKey
79
58
  }
80
59
 
81
60
  /**
82
- * Verify the embedded signature against the encoded body.
61
+ * Sign a writer with the invite's key, proving the join in that writer's core comes from its
62
+ * holder.
83
63
  *
84
- * @returns {boolean}
64
+ * @param {Uint8Array} writer
65
+ * @returns {Uint8Array}
85
66
  */
86
- verify() {
87
- const body = c.encode(SignBody, this)
88
- return sodium.crypto_sign_verify_detached(this.sig, body, this.publicKey)
67
+ prove(writer) {
68
+ return crypto.sign(crypto.hash([NS_PROOF, writer]), this._pair().secretKey)
69
+ }
70
+
71
+ /** @returns {string} The z32 wire form. */
72
+ toString() {
73
+ this._str ??= z32.encode(c.encode(Encoding, this))
74
+ return this._str
75
+ }
76
+
77
+ /** @private */
78
+ _pair() {
79
+ this._keyPair ??= crypto.keyPair(crypto.hash([NS_KEY, this.seed]))
80
+ return this._keyPair
89
81
  }
90
82
 
91
83
  /**
92
- * Serialise to the canonical z32 wire form (cached).
84
+ * Whether `proof` is the invite `id`'s signature over `writer`.
93
85
  *
94
- * @returns {string}
86
+ * @param {Uint8Array} id
87
+ * @param {Uint8Array} writer
88
+ * @param {Uint8Array} proof
89
+ * @returns {boolean}
95
90
  */
96
- toString() {
97
- if (this._str) return this._str
98
- const buf = c.encode(Envelope, this)
99
- this._str = z32.encode(buf)
100
- return this._str
91
+ static proven(id, writer, proof) {
92
+ return crypto.verify(crypto.hash([NS_PROOF, writer]), proof, id)
101
93
  }
102
94
 
103
95
  /**
104
- * Build and sign a new invite envelope wrapping a blind-pairing invite.
96
+ * A new invite with a fresh seed.
105
97
  *
106
- * @param {CreateInviteOpts} opts
98
+ * @param {{ ttl?: number | string, key: Uint8Array, address: Uint8Array, link?: { key: Uint8Array, length: number } | null, data?: Uint8Array | null }} opts
107
99
  * @returns {Invite}
108
100
  */
109
- static create({ secretKey, publicKey, role, expiresIn, data, blind, encoding }) {
110
- if (!secretKey || secretKey.length !== 64) {
111
- throw CeroError.INVALID('secretKey must be a 64-byte buffer')
112
- }
113
- if (!publicKey || publicKey.length !== 32) {
114
- throw CeroError.INVALID('publicKey must be a 32-byte buffer')
115
- }
116
- if (!b4a.isBuffer(blind)) {
117
- throw CeroError.INVALID('blind invite must be a buffer')
118
- }
119
-
120
- const expires = expiresIn ? Date.now() + expiresIn : 0
121
- const encoded = data == null ? null : encoding ? c.encode(encoding, data) : data
122
-
123
- const fields = {
124
- version: VERSION,
125
- publicKey,
126
- role: role || '',
101
+ static create({ ttl = 0, key, address, link = null, data = null }) {
102
+ if (key?.byteLength !== 32) throw CeroError.INVALID('key must be a 32-byte buffer')
103
+ if (address?.byteLength !== 32) throw CeroError.INVALID('address must be a 32-byte buffer')
104
+ const expires = ttl ? Date.now() + toMs(ttl) : 0
105
+ if (data !== null && !b4a.isBuffer(data)) throw CeroError.INVALID('data must be a buffer')
106
+ return new Invite({
127
107
  expires,
128
- data: encoded,
129
- blind
130
- }
131
-
132
- const body = c.encode(SignBody, fields)
133
- const sig = b4a.alloc(64)
134
- sodium.crypto_sign_detached(sig, body, secretKey)
135
- fields.sig = sig
136
-
137
- const inv = new Invite(fields)
138
- inv._rawData = data // remember decoded form for convenience
139
- return inv
108
+ key,
109
+ address,
110
+ seed: crypto.randomBytes(32),
111
+ link,
112
+ data
113
+ })
140
114
  }
141
115
 
142
116
  /**
143
- * Parse a z32 invite string, verify its signature and (optionally) decode
144
- * its payload.
117
+ * Parse an invite string.
145
118
  *
146
119
  * @param {string} str
147
- * @param {ParseInviteOpts} [opts]
148
120
  * @returns {Invite}
149
121
  */
150
- static parse(str, { encoding } = {}) {
122
+ static parse(str) {
151
123
  if (typeof str !== 'string') throw CeroError.INVALID_INVITE('invite must be a string')
152
-
153
- let buf
154
- try {
155
- buf = z32.decode(str)
156
- } catch {
157
- throw CeroError.INVALID_INVITE('invite is not valid z32')
158
- }
159
-
160
124
  let fields
161
125
  try {
162
- fields = c.decode(Envelope, buf)
126
+ fields = c.decode(Encoding, z32.decode(str))
163
127
  } catch {
164
- throw CeroError.INVALID_INVITE('invite envelope failed to decode')
128
+ throw CeroError.INVALID_INVITE('not an invite')
165
129
  }
166
-
167
130
  if (fields.version !== VERSION) throw CeroError.INVALID_INVITE('unknown invite version')
168
-
169
- const inv = new Invite({ ...fields, _str: str })
170
- if (!inv.verify()) throw CeroError.INVALID_INVITE('invite signature is invalid')
171
-
172
- if (encoding && inv.data) {
173
- try {
174
- inv._rawData = c.decode(encoding, inv.data)
175
- } catch {
176
- throw CeroError.INVALID_INVITE('invite data failed to decode')
177
- }
178
- }
179
-
180
- return inv
131
+ return new Invite({ ...fields, _str: str })
181
132
  }
133
+ }
182
134
 
183
- /**
184
- * Cheap structural test — does `str` decode as an invite envelope? Does not
185
- * verify the signature.
186
- *
187
- * @param {unknown} str
188
- * @returns {boolean}
189
- */
190
- static isInvite(str) {
191
- if (typeof str !== 'string') return false
192
- try {
193
- const buf = z32.decode(str)
194
- const fields = c.decode(Envelope, buf)
195
- if (fields.blind) BlindPairing.decodeInvite(fields.blind)
196
- return true
197
- } catch {
198
- return false
199
- }
200
- }
135
+ // ms, or a duration like '12h' or '2d'
136
+ function toMs(ttl) {
137
+ const value = typeof ttl === 'string' ? ms(ttl) : ttl
138
+ if (!Number.isFinite(value)) throw CeroError.INVALID(`ttl '${ttl}' is not a duration`)
139
+ return value
201
140
  }
@@ -1,96 +1,94 @@
1
- import b4a from 'b4a'
1
+ import hid from 'hypercore-id-encoding'
2
2
  import c from 'compact-encoding'
3
- import { keyPair, sign } from 'hypercore-crypto'
4
3
 
5
4
  import { getEncoding } from '../lib/spec/index.js'
6
5
  import { CeroError } from '../lib/errors.js'
6
+ import { grants, isRank } from '../lib/utils.js'
7
7
 
8
8
  export const STATUS_ACCEPTED = 0
9
9
  export const STATUS_DENIED = 1
10
10
 
11
- // success and deny both ride the confirm response
11
+ // an accept and a deny both ride this response
12
+ /** @type {import('compact-encoding').Encoder<{ status: number, reason?: string, key?: Uint8Array | null, encryptionKey?: Uint8Array | null, epochs?: Array<{ epoch: number, stamp: number, entropy: Uint8Array }> | null }>} */
12
13
  export const Response = getEncoding('@cero/confirm')
13
14
 
14
15
  /**
15
- * @typedef {object} ConfirmOpts
16
- * @property {Uint8Array} [key] 32-byte resource key delivered to the joiner; required at runtime.
17
- * @property {Uint8Array | null} [encryptionKey] Optional 32-byte symmetric key.
18
- * @property {Uint8Array | null} [additional] Extra opaque bytes piggybacked on the response.
19
- *
20
16
  * @typedef {object} RequestOpts
21
17
  * @property {import('./index.js').Pairing} pairing Owning Pairing instance.
22
- * @property {any} req blind-pairing candidate request being answered.
23
- * @property {import('./invite.js').Invite} invite Invite the candidate paired against.
24
- * @property {Uint8Array} seed Per-invite seed used to sign the response.
25
- * @property {any} userData Decoded joiner payload (raw bytes when no encoding).
26
- * @property {() => void} onsettle Called once when the candidate is confirmed or denied.
18
+ * @property {{ id: string, role: string, expires?: number }} invite The record of the invite the joiner used.
19
+ * @property {{ id: string, identity: Uint8Array, reply: Uint8Array }} row The waiting join, as the database keeps it.
20
+ *
21
+ * @typedef {object} AcceptOpts
22
+ * @property {string} [role] Role granted: the invite's by default, at most the invite's.
27
23
  */
28
24
 
29
25
  /**
30
- * Internal — a pairing request from an incoming candidate, awaiting the host's
31
- * accept/deny.
32
- *
33
- * @property {boolean} _settled Whether confirm/deny has already run.
26
+ * A join on a `confirm` invite, waiting in the database for a member to accept or deny it.
34
27
  */
35
28
  export class Request {
36
29
  /** @param {RequestOpts} opts */
37
- constructor(opts) {
38
- this.pairing = opts.pairing
39
- this._req = opts.req
40
- this._seed = opts.seed
41
- this._settled = false
42
- this._onsettle = opts.onsettle
43
-
44
- this.invite = opts.invite
45
- this.userData = opts.userData
46
- this.publicKey = opts.req.publicKey
30
+ constructor({ pairing, invite, row }) {
31
+ this.pairing = pairing
32
+ this.invite = invite
33
+ this.id = row.id
34
+ this.identity = row.identity
35
+ /** The role the join asks for: its invite's. */
36
+ this.role = invite.role
37
+ /** @type {Uint8Array} */
38
+ this.writer = hid.decode(row.id)
39
+ /** @private */
40
+ this._reply = row.reply
41
+ /** @private */
42
+ this._answer = null
47
43
  }
48
44
 
49
45
  /**
50
- * Accept the candidate and reveal the resource key. Idempotent.
46
+ * Admit the joiner. Every device of an inviter then replies with the keys. Idempotent.
51
47
  *
52
- * @param {ConfirmOpts} opts
48
+ * @param {AcceptOpts} [opts]
53
49
  * @returns {Promise<void>}
54
50
  */
55
- async confirm({ key, encryptionKey = null, additional = null } = {}) {
56
- if (this._settled) return
57
- if (!key || key.length !== 32) throw CeroError.INVALID('key must be a 32-byte buffer')
58
- if (encryptionKey && encryptionKey.length !== 32) {
59
- throw CeroError.INVALID('encryptionKey must be a 32-byte buffer')
51
+ async accept({ role } = {}) {
52
+ if (this._answer) return this._answer
53
+ const { invite } = this
54
+ if (invite.expires > 0 && Date.now() > invite.expires) throw CeroError.EXPIRED()
55
+ role = role || invite.role
56
+ if (!isRank(role)) {
57
+ throw CeroError.INVALID(`role '${role}' is not a rank (owner, admin, member, reader)`)
60
58
  }
61
- if (additional && !b4a.isBuffer(additional)) {
62
- throw CeroError.INVALID('additional must be a buffer')
59
+ if (!grants(invite.role, role)) {
60
+ throw CeroError.INVALID(`role '${role}' exceeds the invite role '${invite.role}'`)
63
61
  }
64
- this._respond({ status: STATUS_ACCEPTED, reason: '', key, encryptionKey, extra: additional })
62
+ return this._answering(this.pairing.db.call('accept', { id: this.id, role }))
65
63
  }
66
64
 
67
65
  /**
68
- * Reject the candidate with an optional reason. Idempotent.
66
+ * Refuse the joiner, with an optional reason. Idempotent.
69
67
  *
70
68
  * @param {string} [reason]
71
69
  * @returns {Promise<void>}
72
70
  */
73
71
  async deny(reason = '') {
74
- if (this._settled) return
75
- this._respond({
76
- status: STATUS_DENIED,
77
- reason,
78
- key: null,
79
- encryptionKey: null,
80
- extra: null
81
- })
72
+ if (this._answer) return this._answer
73
+ const { db, mailbox } = this.pairing
74
+ const denied = { status: STATUS_DENIED, reason, key: null, encryptionKey: null, epochs: null }
75
+ const denying = async () => {
76
+ await db.call('del-request', { id: this.id })
77
+ await mailbox.send(this._reply, c.encode(Response, denied))
78
+ }
79
+ return this._answering(denying())
82
80
  }
83
81
 
84
- // signed with the per-invite seed
85
- _respond(envelope) {
86
- this._settled = true
87
- this._onsettle()
88
- const data = c.encode(Response, envelope)
89
- const signature = sign(data, keyPair(this._seed).secretKey)
90
- this._req.confirm({
91
- key: this.pairing.topic,
92
- encryptionKey: undefined,
93
- additional: { data, signature }
82
+ // the first answer holds while it is written; refused, the request is answerable again
83
+ /**
84
+ * @private
85
+ * @param {Promise<void>} answer
86
+ */
87
+ _answering(answer) {
88
+ this._answer = answer
89
+ answer.catch(() => {
90
+ this._answer = null
94
91
  })
92
+ return answer
95
93
  }
96
94
  }
package/src/rpc/index.js CHANGED
@@ -9,32 +9,24 @@ export { RPCClient } from './client.js'
9
9
 
10
10
  const EMPTY = b4a.alloc(0)
11
11
 
12
- // fallback envelope encodings when the spec has none
13
- const DEFAULT_ROWS = getEncoding('@cero/rows')
14
- const DEFAULT_CHANGES = getEncoding('@cero/changes')
15
- const DEFAULT_QUERY = getEncoding('@cero/query')
16
- const DEFAULT_CREATE = getEncoding('@cero/create')
12
+ const ROWS = getEncoding('@cero/rows')
13
+ const CREATE = getEncoding('@cero/create')
17
14
 
18
15
  /**
19
16
  * @typedef {object} Spec
20
- * @property {{ encode: (type: string, value: any) => Uint8Array, decode: (type: string, buf: Uint8Array) => any, getEncoding?: (name: string) => any }} schema hyperschema-shaped module.
21
- * @property {{ ns?: string }} [meta] Optional metadata; `ns` controls envelope type fqns.
22
- * @property {any} [rpc] hrpc constructor used by RPCServer/RPCClient.
23
- * @property {Codec} [codec] Filled in by `bindCodec`.
17
+ * @property {{ encode: (type: string, value: unknown) => Uint8Array, decode: (type: string, buf: Uint8Array) => unknown }} schema hyperschema-shaped module.
18
+ * @property {new (stream: import('streamx').Duplex) => object} [rpc] hrpc constructor used by RPCServer/RPCClient.
19
+ * @property {Codec} [codec] Filled in by `bindCodec`.
24
20
  *
25
21
  * @typedef {object} Codec
26
- * @property {(type: string, row: any) => Uint8Array} encodeRow
27
- * @property {(type: string, buf: Uint8Array) => any} decodeRow
28
- * @property {(type: string, rows: any[]) => Uint8Array} encodeRows
29
- * @property {(type: string, changes: Array<{ prev: any, next: any }>) => Uint8Array} encodeChanges
30
- * @property {(type: string, buf: Uint8Array) => Array<{ prev: any, next: any }>} decodeChanges
31
- * @property {(type: string, buf: Uint8Array) => any[]} decodeRows
32
- * @property {(q: any) => Uint8Array} encodeQuery
33
- * @property {(buf: Uint8Array) => any} decodeQuery
34
- * @property {(row: any) => Uint8Array} encodeCreate
35
- * @property {(buf: Uint8Array) => any} decodeCreate
36
- * @property {(handle: any, op: string, data: any) => Uint8Array} encodeAction
37
- * @property {(handle: any, op: string, buf: Uint8Array) => any} decodeAction
22
+ * @property {(type: string, row: Record<string, unknown>) => Uint8Array} encodeRow
23
+ * @property {(type: string, buf: Uint8Array) => Record<string, unknown>} decodeRow
24
+ * @property {(type: string, rows: Record<string, unknown>[]) => Uint8Array} encodeRows
25
+ * @property {(type: string, buf: Uint8Array) => Record<string, unknown>[]} decodeRows
26
+ * @property {(row: Record<string, unknown>) => Uint8Array} encodeCreate
27
+ * @property {(buf: Uint8Array) => Record<string, unknown>} decodeCreate
28
+ * @property {(handle: Record<string, { schema?: string }>, op: string, data: unknown) => Uint8Array} encodeAction
29
+ * @property {(handle: Record<string, { schema?: string }>, op: string, buf: Uint8Array) => unknown} decodeAction
38
30
  */
39
31
 
40
32
  /**
@@ -48,12 +40,6 @@ export function bindCodec(spec) {
48
40
  const schema = spec.schema
49
41
  if (!schema) throw CeroError.REQUIRED('spec.schema')
50
42
 
51
- const ns = spec.meta?.ns
52
- const ROWS = ns ? `@${ns}/rows` : null
53
- const CHANGES = ns ? `@${ns}/changes` : null
54
- const QUERY = ns ? `@${ns}/query` : null
55
- const CREATE = ns ? `@${ns}/create` : null
56
-
57
43
  spec.codec = {
58
44
  encodeRow(type, row) {
59
45
  if (row == null) return EMPTY
@@ -65,61 +51,20 @@ export function bindCodec(spec) {
65
51
  },
66
52
  encodeRows(type, rows) {
67
53
  const data = (rows ?? []).map((r) => schema.encode(type, r))
68
- return encodeEnvelope(schema, ROWS, DEFAULT_ROWS, { data })
54
+ return c.encode(ROWS, { data })
69
55
  },
70
56
  decodeRows(type, buf) {
71
57
  if (!buf || buf.length === 0) return []
72
- const env = decodeEnvelope(schema, ROWS, DEFAULT_ROWS, buf)
73
- const data = env?.data || []
74
- return data.map((b) => schema.decode(type, b))
75
- },
76
- encodeChanges(type, changes) {
77
- const prev = changes.map((x) => (x.prev ? schema.encode(type, x.prev) : EMPTY))
78
- const next = changes.map((x) => (x.next ? schema.encode(type, x.next) : EMPTY))
79
- return encodeEnvelope(schema, CHANGES, DEFAULT_CHANGES, { prev, next })
80
- },
81
- decodeChanges(type, buf) {
82
- if (!buf || buf.length === 0) return []
83
- const env = decodeEnvelope(schema, CHANGES, DEFAULT_CHANGES, buf)
84
- const prev = env?.prev || []
85
- const next = env?.next || []
86
- const out = []
87
- for (let i = 0; i < Math.max(prev.length, next.length); i++) {
88
- out.push({
89
- prev: prev[i]?.length ? schema.decode(type, prev[i]) : null,
90
- next: next[i]?.length ? schema.decode(type, next[i]) : null
91
- })
92
- }
93
- return out
94
- },
95
- encodeQuery(q) {
96
- if (q == null) return encodeEnvelope(schema, QUERY, DEFAULT_QUERY, {})
97
- const { gt, gte, lt, lte, limit, reverse, ...rest } = q
98
- const env = { gt, gte, lt, lte, limit, reverse }
99
- if (Object.keys(rest).length > 0) env.data = rest
100
- return encodeEnvelope(schema, QUERY, DEFAULT_QUERY, env)
101
- },
102
- decodeQuery(buf) {
103
- if (!buf || buf.length === 0) return undefined
104
- const env = decodeEnvelope(schema, QUERY, DEFAULT_QUERY, buf)
105
- const out = {}
106
- // hyperschema fills optional fields with 0/false, so only truthy fields are recovered; limit: 0 is lost
107
- if (env.gt) out.gt = env.gt
108
- if (env.gte) out.gte = env.gte
109
- if (env.lt) out.lt = env.lt
110
- if (env.lte) out.lte = env.lte
111
- if (env.limit) out.limit = env.limit
112
- if (env.reverse) out.reverse = env.reverse
113
- if (env.data) Object.assign(out, env.data)
114
- return Object.keys(out).length === 0 ? undefined : out
58
+ const { data } = c.decode(ROWS, buf)
59
+ return (data || []).map((b) => schema.decode(type, b))
115
60
  },
116
61
  encodeCreate(row) {
117
62
  if (row == null) return EMPTY
118
- return encodeEnvelope(schema, CREATE, DEFAULT_CREATE, row)
63
+ return c.encode(CREATE, row)
119
64
  },
120
65
  decodeCreate(buf) {
121
66
  if (!buf || buf.length === 0) return {}
122
- return decodeEnvelope(schema, CREATE, DEFAULT_CREATE, buf)
67
+ return c.decode(CREATE, buf)
123
68
  },
124
69
  encodeAction(handle, op, data) {
125
70
  const ref = handle?.[op]
@@ -136,23 +81,3 @@ export function bindCodec(spec) {
136
81
  }
137
82
  return spec
138
83
  }
139
-
140
- // the spec's own envelope type first, the built-in @cero encoding as fallback
141
- function encodeEnvelope(schema, fqn, fallback, value) {
142
- if (fqn && schemaHas(schema, fqn)) return schema.encode(fqn, value)
143
- return c.encode(fallback, value)
144
- }
145
-
146
- function decodeEnvelope(schema, fqn, fallback, buf) {
147
- if (fqn && schemaHas(schema, fqn)) return schema.decode(fqn, buf)
148
- return c.decode(fallback, buf)
149
- }
150
-
151
- function schemaHas(schema, name) {
152
- if (typeof schema.getEncoding !== 'function') return false
153
- try {
154
- return schema.getEncoding(name) != null
155
- } catch {
156
- return false
157
- }
158
- }
package/src/rpc/peer.js CHANGED
@@ -11,7 +11,7 @@ import { CeroError } from '../lib/errors.js'
11
11
  */
12
12
  export class RPCPeer extends ReadyResource {
13
13
  /**
14
- * @param {any} ipc Duplex IPC stream (e.g. a socket or pipe).
14
+ * @param {import('streamx').Duplex} ipc Duplex IPC stream (e.g. a socket or pipe).
15
15
  * @param {import('./index.js').Spec} spec Spec object exposing `rpc` and `schema`.
16
16
  */
17
17
  constructor(ipc, spec) {
@@ -22,17 +22,20 @@ export class RPCPeer extends ReadyResource {
22
22
 
23
23
  this.ipc = ipc
24
24
  this.spec = spec
25
+ /** @type {import('framed-stream')} */
25
26
  this.framed = new FramedStream(ipc)
26
27
  this.rpc = new spec.rpc(this.framed)
27
28
  // pause after hrpc attaches its listener, streamx resumes on attach
28
29
  this.framed.pause()
29
30
  }
30
31
 
32
+ /** @private */
31
33
  async _open() {
32
34
  if (!this.spec.codec) bindCodec(this.spec)
33
35
  this.framed.resume()
34
36
  }
35
37
 
38
+ /** @private */
36
39
  async _close() {
37
40
  if (this.framed && !this.framed.destroyed) {
38
41
  try {