@cero-base/core 2.0.0 → 2.1.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.
@@ -7,15 +7,7 @@ import safetyCatch from 'safety-catch'
7
7
  import b4a from 'b4a'
8
8
  import hid from 'hypercore-id-encoding'
9
9
 
10
- import {
11
- NAMESPACE,
12
- SINGLE,
13
- COLLECTION,
14
- ACTION,
15
- ACTIVE,
16
- PASSIVE,
17
- QUERY_RESERVED
18
- } from '../lib/constants.js'
10
+ import { NAMESPACE, SINGLE, COLLECTION, ACTION, QUERY_RESERVED } from '../lib/constants.js'
19
11
  import { genId, subscribe, admission, ownership, filter } from '../lib/utils.js'
20
12
  import { wrap, unwrap } from './envelope.js'
21
13
  import { EpochAutobee, Keyring, loadEpochs } from './encryption.js'
@@ -36,15 +28,31 @@ import { makeDispatcher } from './dispatch.js'
36
28
  * @property {Uint8Array | null} [encryptionKey] Optional encryption key; falls back to identity's key.
37
29
  * @property {Array<{ epoch: number, entropy: Uint8Array }> | null} [epochs] Rotation epochs to prime the keyring with (delivered at join).
38
30
  * @property {Uint8Array | null} [key] Existing autobee key to reopen.
39
- * @property {boolean} [passive] Join discovery server-only (reachable but not searching). Flip at runtime with `setActive`.
31
+ * @property {boolean} [pinned] Always search and announce, outside the network's presence budget. The root.
40
32
  * @property {import('../identity/index.js').KeyPair} [keyPair] This device's writer keypair; a fresh random one by default. Never the identity's, never the database key.
41
- * @property {(err: Error) => void} [onerror] Called when a background after-hook or onApply callback fails, a malformed node is skipped, or the bee errors.
33
+ * @property {(err: Error) => void} [onerror] Called when a node is skipped or refused, or the bee errors.
34
+ *
35
+ * Events: `update` (touched refs, a Set, after each applied batch), `apply` (one per applied
36
+ * op: `{ op, name, row, writerKey, seq }`, local and replicated), `writable`, `unwritable`,
37
+ * `behind` (an op from a newer app version was skipped).
42
38
  *
43
39
  * @typedef {{ data: any | null }} SingleResult
44
40
  * @typedef {{ data: any[], total: number | null, size: number }} ListResult `total` is null when a limited read skipped the full count — pass `{ total: true }` to force it.
45
41
  * @typedef {{ gt?: string, gte?: string, lt?: string, lte?: string, reverse?: boolean, limit?: number, search?: string, fields?: string[], total?: boolean }} Query
46
42
  * @typedef {{ kind: string, verb: string, name: string }} Ref
47
- * @typedef {(ctx: any) => any | Promise<any>} HookFn
43
+ * @typedef {object} HookContext
44
+ * @property {string} op One of `put`, `set`, `del`, or an action name.
45
+ * @property {string} name The ref the op targets.
46
+ * @property {Record<string, unknown> | null} row The incoming row; mutate it in `before` to change what lands.
47
+ * @property {Record<string, unknown> | null} existing The stored row, or null.
48
+ * @property {string | null} id The row id for a `del`.
49
+ * @property {string} memberId The writer's member id.
50
+ * @property {string} role The writer's role.
51
+ * @property {(ref: string | { name: string }, query?: string | Record<string, unknown>) => Promise<{ data: unknown }>} get
52
+ * @property {(ref: string | { name: string }, row: Record<string, unknown>) => Promise<void>} put
53
+ * @property {(ref: string | { name: string }, row: Record<string, unknown>) => Promise<void>} set
54
+ * @property {(ref: string | { name: string }, id?: string) => Promise<void>} del
55
+ * @typedef {(ctx: HookContext) => unknown} HookFn
48
56
  */
49
57
 
50
58
  /**
@@ -77,7 +85,7 @@ export class Database extends ReadyResource {
77
85
  if (opts.epochs) for (const e of opts.epochs) this.keyring.add(e.stamp, e.entropy, e.epoch)
78
86
  this.rotation = new Rotation(this)
79
87
  this.key = opts.key || null
80
- this.passive = opts.passive === true
88
+ this.pinned = opts.pinned === true
81
89
  this.keyPair = opts.keyPair || Identity.randomKeyPair()
82
90
  if (b4a.equals(this.keyPair.publicKey, this.identity.publicKey)) {
83
91
  throw CeroError.INVALID('the identity keypair is never a writer — use a device keypair')
@@ -86,16 +94,17 @@ export class Database extends ReadyResource {
86
94
  this._onerror = opts.onerror || safetyCatch
87
95
  this.bee = null
88
96
  this.dispatcher = null
89
- this._discovery = null
97
+ this._presence = null
90
98
  this._txChain = null
91
99
 
92
100
  this._before = new Map()
93
101
  this._after = new Map()
94
- this._updaters = new Map()
95
- this._observers = new Set()
102
+ this._hooking = 0
96
103
  this._verbs = verbMap(this.refs)
97
104
  this._touched = new Set()
98
105
  this._seq = 0
106
+ // every watch and changes stream is an 'update' listener
107
+ this.setMaxListeners(0)
99
108
  this.txQueue = null
100
109
  }
101
110
 
@@ -134,7 +143,11 @@ export class Database extends ReadyResource {
134
143
  routes: this.routes,
135
144
  onerror: this._onerror,
136
145
  key: () => this.key,
137
- onepoch: (row) => this.rotation.learn(row)
146
+ onepoch: (row) => this.rotation.learn(row),
147
+ hooks: (phase, op) => this._hooks(phase, op),
148
+ inHook: (fn) => this._inHook(fn),
149
+ touch: (name) => this._touched.add(name),
150
+ read: (view, name, query) => this._read(view, name, query)
138
151
  })
139
152
 
140
153
  const known = !!this.key
@@ -155,15 +168,13 @@ export class Database extends ReadyResource {
155
168
 
156
169
  // a fresh db has no key until boot mints it
157
170
  if (this.network && !known) this._joinSwarm(this.bee, this.bee.discoveryKey)
158
- if (replayed) this.emit('rebuild')
159
171
  }
160
172
 
161
173
  async _close() {
162
174
  this.rotation.close()
163
- if (this._discovery) {
164
- // unannounce in the background, the DHT round-trip would block close for seconds
165
- this._discovery.destroy().catch(safetyCatch)
166
- this._discovery = null
175
+ if (this._presence) {
176
+ this._presence.remove()
177
+ this._presence = null
167
178
  }
168
179
  if (this.bee) {
169
180
  // detach first, else the closed bee replicates into every new connection
@@ -174,19 +185,20 @@ export class Database extends ReadyResource {
174
185
  }
175
186
 
176
187
  /**
177
- * Flip announce mode at runtime — passive stays reachable (server) but
178
- * stops actively looking (client). Cheap; use it to demote idle rooms.
188
+ * `true` ranks this database as just touched, `false` takes it out of the swarm until the
189
+ * next update lands in it.
179
190
  *
180
191
  * @param {boolean} active
181
- * @returns {Promise<void>}
182
192
  */
183
- async setActive(active) {
184
- if (!this._discovery) return
185
- await (active ? this._discovery.activate() : this._discovery.deactivate())
193
+ setActive(active) {
194
+ if (!this._presence) return
195
+ if (active) this._presence.touch()
196
+ else this._presence.off()
186
197
  }
187
198
 
188
199
  /**
189
- * Register a pre-op hook. Returning `false` from `fn` aborts the op.
200
+ * Register a pre-op hook. It runs at apply on every peer, inside the op's transaction;
201
+ * returning `false` (or throwing) refuses the op everywhere.
190
202
  *
191
203
  * @param {string} op
192
204
  * @param {HookFn} fn
@@ -197,7 +209,8 @@ export class Database extends ReadyResource {
197
209
  }
198
210
 
199
211
  /**
200
- * Register a post-op hook, fired after the write succeeds.
212
+ * Register a post-op hook. It runs at apply on every peer, in the op's transaction, so it
213
+ * may write derived rows through `ctx.put` / `ctx.set` / `ctx.del`.
201
214
  *
202
215
  * @param {string} op
203
216
  * @param {HookFn} fn
@@ -207,31 +220,6 @@ export class Database extends ReadyResource {
207
220
  return addHook(this._after, op, fn)
208
221
  }
209
222
 
210
- /**
211
- * Subscribe to local apply notifications. Fires whenever the view updates;
212
- * pass `scope` (a ref name) to fire only when that ref was touched.
213
- *
214
- * @param {() => void} fn
215
- * @param {string} [scope]
216
- * @returns {() => void} disposer
217
- */
218
- onUpdate(fn, scope) {
219
- this._updaters.set(fn, scope || null)
220
- return () => this._updaters.delete(fn)
221
- }
222
-
223
- /**
224
- * Observe every applied op — local AND replicated (apply processes the merged log).
225
- *
226
- * @param {(event: { op: string, name: string, row: any, writerKey: any, seq: number }) => void} fn
227
- * @returns {() => void} disposer
228
- */
229
- onApply(fn) {
230
- if (typeof fn !== 'function') return () => {}
231
- this._observers.add(fn)
232
- return () => this._observers.delete(fn)
233
- }
234
-
235
223
  /**
236
224
  * Insert (or overwrite by id) a row, stamping `id`/`createdAt`/`updatedAt`.
237
225
  *
@@ -243,7 +231,7 @@ export class Database extends ReadyResource {
243
231
  const ref = this._prepare(name, row)
244
232
  const ts = Date.now()
245
233
  const stored = { createdAt: ts, updatedAt: ts, ...row, id: row.id || genId() }
246
- return this._done('put', await this._append('put', name, stored, `add-${ref.verb}`))
234
+ return this._done(await this._append(stored, `add-${ref.verb}`))
247
235
  }
248
236
 
249
237
  /**
@@ -255,7 +243,7 @@ export class Database extends ReadyResource {
255
243
  * @returns {Promise<SingleResult | null>}
256
244
  */
257
245
  async set(name, row, opts) {
258
- return this._done('set', await this.tx((tx) => tx._merge(name, row, opts)))
246
+ return this._done(await this.tx((tx) => tx._merge(name, row, opts)))
259
247
  }
260
248
 
261
249
  /**
@@ -268,12 +256,9 @@ export class Database extends ReadyResource {
268
256
  async del(name, id) {
269
257
  this.guard()
270
258
  const ref = this.ref(name)
271
- const ctx = { op: 'del', name, id }
272
- if ((await this._runBefore('del', ctx)) === false) return null
273
259
  // singles have no id, the dummy one just satisfies the shared del-by-id encoding
274
260
  const payload = ref.kind === SINGLE ? { id: '' } : { id }
275
261
  await this.write([[`del-${ref.verb}`, payload]])
276
- await this._runAfter('del', ctx)
277
262
  }
278
263
 
279
264
  /**
@@ -378,36 +363,28 @@ export class Database extends ReadyResource {
378
363
  */
379
364
  async get(name, query) {
380
365
  this.guard()
366
+ return this._read(this.view, name, query)
367
+ }
368
+
369
+ // the same read against any view: hooks read the transaction they run in
370
+ async _read(view, name, query) {
381
371
  const ref = this.ref(name)
382
372
  const col = this.col(ref)
383
373
 
384
374
  if (ref.kind === SINGLE) {
385
- return { data: await this.view.findOne(col, {}) }
375
+ return { data: await view.findOne(col, {}) }
386
376
  }
387
377
 
388
378
  if (typeof query === 'string') {
389
- return { data: await this.view.get(col, { id: query }) }
379
+ return { data: await view.get(col, { id: query }) }
390
380
  }
391
381
 
392
382
  const { path, range, rest, sorted } = this._plan(name, query)
393
- const rows = await this.view.find(path, range).toArray()
383
+ const rows = await view.find(path, range).toArray()
394
384
  if (!sorted) rows.sort(byIndex)
395
- const data = filter(rows, rest)
396
- return { data, total: await this._total(path, range, rows, query), size: data.length }
397
- }
398
-
399
- /**
400
- * Number of rows that match `query` (or total if omitted).
401
- *
402
- * @param {string} name
403
- * @param {Query} [query]
404
- * @returns {Promise<{ data: number }>}
405
- */
406
- async count(name, query) {
407
- this.guard()
408
- this.ref(name)
409
- const { path, range, rest } = this._plan(name, query)
410
- return { data: filter(await this.view.find(path, range).toArray(), rest).length }
385
+ const matched = filter(rows, { ...rest, limit: undefined })
386
+ const data = rest.limit === undefined ? matched : matched.slice(0, rest.limit)
387
+ return { data, total: await this._total(view, path, range, matched, query), size: data.length }
411
388
  }
412
389
 
413
390
  /**
@@ -422,7 +399,7 @@ export class Database extends ReadyResource {
422
399
  this.guard()
423
400
  return subscribe({
424
401
  get: () => this.get(name, query),
425
- watch: (fn) => this.onUpdate(fn, name)
402
+ watch: (fn) => this.onUpdate(name, fn)
426
403
  })
427
404
  }
428
405
 
@@ -461,14 +438,23 @@ export class Database extends ReadyResource {
461
438
  updatedAt: ts
462
439
  }
463
440
  ]
464
- if (!recovering) {
465
- await this.write([['add-writer', writer], device])
466
- } else {
441
+ if (recovering) {
467
442
  await this._backfilled(timeout)
468
443
  await this._optimistic(this.spec.dispatch.encode(`@${this.ns}/add-writer`, writer), {
469
444
  timeout
470
445
  })
471
446
  await this.write([device])
447
+ } else {
448
+ // one batch: a writer is never on the log without its member row
449
+ const member = {
450
+ id: this.identity.id,
451
+ key: this.writerKey,
452
+ role: 'owner',
453
+ name: name || null,
454
+ createdAt: ts,
455
+ updatedAt: ts
456
+ }
457
+ await this.write([['add-writer', writer], ['add-member', member], device])
472
458
  }
473
459
  return { id: this.writerKey, writer: this.keyPair }
474
460
  }
@@ -519,13 +505,15 @@ export class Database extends ReadyResource {
519
505
  }
520
506
 
521
507
  /**
522
- * Add a peer's writer key to the indexer set.
508
+ * Admit a device as a writer for `memberId`, an existing member. Omit it to
509
+ * admit another device of this identity.
523
510
  *
524
511
  * @param {Uint8Array} publicKey
512
+ * @param {string} [memberId]
525
513
  * @returns {Promise<void>}
526
514
  */
527
- async addWriter(publicKey) {
528
- return this._admit('add-writer', 'addWriter', publicKey)
515
+ async addWriter(publicKey, memberId) {
516
+ return this._admit('add-writer', publicKey, memberId)
529
517
  }
530
518
 
531
519
  /**
@@ -535,7 +523,7 @@ export class Database extends ReadyResource {
535
523
  * @returns {Promise<void>}
536
524
  */
537
525
  async removeWriter(publicKey) {
538
- return this._admit('del-writer', 'removeWriter', publicKey)
526
+ return this._admit('del-writer', publicKey)
539
527
  }
540
528
 
541
529
  /**
@@ -544,6 +532,9 @@ export class Database extends ReadyResource {
544
532
  * @returns {void}
545
533
  */
546
534
  guard() {
535
+ if (this._hooking) {
536
+ throw CeroError.INVALID('operators are not available inside a hook, use ctx.put / ctx.get')
537
+ }
547
538
  if (this.closing || this.closed) throw CeroError.CLOSED('Database')
548
539
  if (!this.bee) throw CeroError.NOT_READY('Database', 'db')
549
540
  }
@@ -648,48 +639,49 @@ export class Database extends ReadyResource {
648
639
  ready.push(version === 0 ? node : { ...node, value: body })
649
640
  }
650
641
  const result = await this.dispatcher.apply(ready, view, host)
651
- if (this._updaters.size || this._observers.size) this._notify(ready)
642
+ this._notify(ready)
652
643
  return result
653
644
  }
654
645
 
646
+ // 'update' carries the refs the batch touched; '*' means any, so a scoped watcher can skip
655
647
  async _update(db) {
656
648
  await db.update()
657
649
  const touched = this._touched
658
650
  this._touched = new Set()
659
- const all = touched.size === 0 || touched.has('*')
660
- for (const [fn, scope] of this._updaters) {
661
- if (all || !scope || touched.has(scope)) fn()
662
- }
663
- this.emit('update')
651
+ this.emit('update', touched.size === 0 ? new Set(['*']) : touched)
652
+ this._presence?.touch()
664
653
  }
665
654
 
666
- // a writer swap re-opens the bee on the SAME topic, join first so destroy is a detach
655
+ // a writer swap re-opens the bee on the same topic, so the slot is the same one
667
656
  _joinSwarm(bee, discoveryKey) {
668
657
  this.network.attach(bee)
669
- const prev = this._discovery
670
- this._discovery = this.network.join(discoveryKey, {
671
- mode: this.passive ? PASSIVE : ACTIVE
672
- })
673
- if (prev) prev.destroy().catch(safetyCatch)
658
+ this._presence = this.network.presence.add(discoveryKey, { pinned: this.pinned })
674
659
  }
675
660
 
676
- async _runBefore(op, ctx) {
677
- for (const fn of this._before.get(op) || []) {
678
- if ((await fn(ctx)) === false) return false
679
- }
680
- this.emit(`before:${op}`, ctx)
681
- return true
661
+ // wrapped so an operator called from inside a hook fails instead of appending its own op
662
+ _hooks(phase, op) {
663
+ const fns = (phase === 'before' ? this._before : this._after).get(op)
664
+ return fns?.length ? fns.map((fn) => this._inHook(fn)) : NO_HOOKS
682
665
  }
683
666
 
684
- async _runAfter(op, ctx) {
685
- for (const fn of this._after.get(op) || []) {
667
+ _inHook(fn) {
668
+ return async (ctx) => {
669
+ this._hooking++
686
670
  try {
687
- await fn(ctx)
688
- } catch (err) {
689
- this._onerror(err)
671
+ return await fn(ctx)
672
+ } finally {
673
+ this._hooking--
690
674
  }
691
675
  }
692
- this.emit(`after:${op}`, ctx)
676
+ }
677
+
678
+ // an 'update' listener for one ref; the disposer detaches it
679
+ onUpdate(name, fn) {
680
+ const tick = (touched) => {
681
+ if (touched.has('*') || touched.has(name)) fn()
682
+ }
683
+ this.on('update', tick)
684
+ return () => this.off('update', tick)
693
685
  }
694
686
 
695
687
  // '@cero/set-messages' → { op: 'set', name: 'messages' }; an action has no dash
@@ -701,8 +693,9 @@ export class Database extends ReadyResource {
701
693
  return { op: verb.slice(0, dash), name: verb.slice(dash + 1), value }
702
694
  }
703
695
 
704
- // which refs the batch touched, for scoped update ticks, and one event per op
696
+ // marks the refs a batch touched and emits 'apply' per op, local and replicated alike
705
697
  _notify(nodes) {
698
+ const listened = this.listenerCount('apply') > 0
706
699
  for (const node of nodes) {
707
700
  let op
708
701
  try {
@@ -715,21 +708,14 @@ export class Database extends ReadyResource {
715
708
  const ref = this._verbs.get(op.name)
716
709
  // an action's route handler writes wherever it wants, widen to all
717
710
  this._touched.add(ref && this.refs[ref].kind !== ACTION ? ref : '*')
718
- if (!this._observers.size) continue
719
- const event = {
711
+ if (!listened) continue
712
+ this.emit('apply', {
720
713
  op: op.op,
721
714
  name: op.name,
722
715
  row: op.value,
723
716
  writerKey: node.key,
724
717
  seq: this._seq++
725
- }
726
- for (const fn of this._observers) {
727
- try {
728
- fn(event)
729
- } catch (err) {
730
- this._onerror(err)
731
- }
732
- }
718
+ })
733
719
  }
734
720
  }
735
721
 
@@ -741,7 +727,7 @@ export class Database extends ReadyResource {
741
727
  const stored = { ...existing, ...row, createdAt: existing?.createdAt ?? ts, updatedAt: ts }
742
728
  if (ref.kind === COLLECTION && !stored.id) stored.id = genId()
743
729
  const insert = ref.kind === COLLECTION && upsert && !BESPOKE.has(ref.verb)
744
- return this._append('set', name, stored, `${insert ? 'add' : 'set'}-${ref.verb}`)
730
+ return this._append(stored, `${insert ? 'add' : 'set'}-${ref.verb}`)
745
731
  }
746
732
 
747
733
  _prepare(name, row) {
@@ -751,18 +737,13 @@ export class Database extends ReadyResource {
751
737
  return ref
752
738
  }
753
739
 
754
- async _append(op, name, stored, verb) {
755
- const ctx = { op, name, row: stored }
756
- if ((await this._runBefore(op, ctx)) === false) return null
757
- await this.write([[verb, ctx.row]])
758
- return ctx
740
+ async _append(stored, verb) {
741
+ await this.write([[verb, stored]])
742
+ return { row: stored }
759
743
  }
760
744
 
761
- async _done(op, ctx) {
762
- if (!ctx) return null
763
- const result = { data: ctx.row }
764
- await this._runAfter(op, { ...ctx, result })
765
- return result
745
+ _done(ctx) {
746
+ return ctx ? { data: ctx.row } : null
766
747
  }
767
748
 
768
749
  // ops from a newer app version: emit behind once per version, the marker survives restarts
@@ -784,6 +765,7 @@ export class Database extends ReadyResource {
784
765
  view: tx,
785
766
  key: this.writerKey,
786
767
  dbKey: this.key,
768
+ seed: crypto.hash([this.writerKey, value]),
787
769
  dryRun: true
788
770
  })
789
771
  }
@@ -827,12 +809,12 @@ export class Database extends ReadyResource {
827
809
  return { path: col, range: {}, rest, sorted: false }
828
810
  }
829
811
 
830
- // rows before the in-memory pass; unknown once a pushed-down limit filled the page
831
- async _total(path, range, rows, query) {
832
- if (range.limit === undefined || rows.length < range.limit) return rows.length
812
+ // matched rows; unknown once a pushed-down limit filled the page
813
+ async _total(view, path, range, matched, query) {
814
+ if (range.limit === undefined || matched.length < range.limit) return matched.length
833
815
  if (!query?.total) return null
834
816
  const { limit, reverse, ...bounds } = range
835
- return (await this.view.find(path, bounds).toArray()).length
817
+ return (await view.find(path, bounds).toArray()).length
836
818
  }
837
819
 
838
820
  // an append by a core not yet admitted: apply verifies the signature and admits it
@@ -872,14 +854,11 @@ export class Database extends ReadyResource {
872
854
  }
873
855
  }
874
856
 
875
- async _admit(verb, hook, publicKey) {
857
+ async _admit(verb, publicKey, memberId) {
876
858
  this.guard()
877
859
  if (!b4a.isBuffer(publicKey)) throw CeroError.INVALID('publicKey must be a buffer')
878
- const ctx = { op: hook, publicKey }
879
- if ((await this._runBefore(hook, ctx)) === false) return
880
860
  const writer = Hypercore.key({ version: this.store.manifestVersion, signers: [{ publicKey }] })
881
- await this.write([[verb, this._admission(writer)]])
882
- await this._runAfter(hook, ctx)
861
+ await this.write([[verb, { ...this._admission(writer), memberId }]])
883
862
  }
884
863
  }
885
864
 
@@ -891,6 +870,8 @@ function bounded(promise, ms = 2000) {
891
870
  ])
892
871
  }
893
872
 
873
+ const NO_HOOKS = []
874
+
894
875
  function addHook(map, op, fn) {
895
876
  if (typeof fn !== 'function') throw CeroError.INVALID('hook fn must be a function')
896
877
  let arr = map.get(op)
@@ -15,6 +15,7 @@ import c from 'compact-encoding'
15
15
  import { ACTIVE, PASSIVE } from '../lib/constants.js'
16
16
  import { CeroError } from '../lib/errors.js'
17
17
  import { Discovery } from './discovery.js'
18
+ import { Presence } from './presence.js'
18
19
 
19
20
  export function channelTopic(topic, channel) {
20
21
  return channel ? hash([topic, b4a.from(channel)]) : topic
@@ -30,6 +31,7 @@ export function channelTopic(topic, channel) {
30
31
  * @property {string} [channel] Optional network-isolation label; only same-channel peers meet.
31
32
  * @property {any} [store] Corestore; required for mirrors (blind peers replicate its cores).
32
33
  * @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys; each attached room/blob core is mirrored through them for offline sync.
34
+ * @property {{ active?: number, announced?: number, idle?: number }} [presence] Swarm budget for attached databases: how many search, how many only announce, and the idle ms before the rest leave.
33
35
  *
34
36
  * @typedef {{ replicate: (stream: any) => any }} Replicable
35
37
  */
@@ -48,7 +50,8 @@ export class Network extends ReadyResource {
48
50
  backoffs,
49
51
  channel,
50
52
  store,
51
- mirrors
53
+ mirrors,
54
+ presence
52
55
  } = {}) {
53
56
  super()
54
57
  this.identity = identity || null
@@ -62,6 +65,7 @@ export class Network extends ReadyResource {
62
65
 
63
66
  this._swarm = null
64
67
  this.wakeup = new ProtomuxWakeup()
68
+ this.presence = new Presence(this, presence)
65
69
 
66
70
  this.info = null
67
71
  this._peerInfo = new Map()
@@ -137,6 +141,7 @@ export class Network extends ReadyResource {
137
141
  this._injected.clear()
138
142
 
139
143
  // stop discovery now, never await the DHT unannounce round-trips
144
+ this.presence.close()
140
145
  for (const d of [...this._discoveries]) d.destroy().catch(safetyCatch)
141
146
  this._discoveries.clear()
142
147