@cero-base/cero 3.4.1 → 3.6.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,6 +7,8 @@ import * as operators from '../lib/operators.js'
7
7
 
8
8
  export * from './profile-sync.js'
9
9
  export * from './handle-sync.js'
10
+ export * from './pulse.js'
11
+ export { calls } from './calls.js'
10
12
 
11
13
  // everything an extension module needs, light enough for the UI bundle the spec pulls it into
12
14
  export { t, schema }
@@ -16,7 +18,7 @@ export const cero = { t, schema, ...operators }
16
18
  /**
17
19
  * @typedef {object} Extension
18
20
  * @property {string} [name]
19
- * @property {Record<string, object>} [schema] Refs to add, or `t.extend` on a builtin, nested by handle type like the app schema.
21
+ * @property {Record<string, object> | ((types: string[]) => Record<string, object>)} [schema] Refs to add, or `t.extend` on a builtin, nested by handle type like the app schema; a function gets the app's handle types and returns them.
20
22
  * @property {(me: import('../handle/index.js').Context) => void | (() => void) | Promise<void | (() => void)>} [setup] Runs before the root opens; a returned function runs on close.
21
23
  */
22
24
 
@@ -0,0 +1,33 @@
1
+ import { t } from '../lib/spec.js'
2
+
3
+ /**
4
+ * Hear through a pulse service when another device writes in a handle you are in, closed here too,
5
+ * and wake that handle so it syncs, without the app opening it. A best effort: a notice may come
6
+ * late or twice. Declares `local.pulses`, a row per handle id: `heard`, the local time a write from
7
+ * another device last landed here, 0 before the first; and what pulse keeps for itself: `told`,
8
+ * `owed`, `since` and `epoch`.
9
+ *
10
+ * @param {string | Uint8Array} [key] The service's public key, as it prints it. The build needs none.
11
+ * @returns {import('./index.js').Extension}
12
+ */
13
+ export function pulse(key) {
14
+ return {
15
+ name: 'pulse',
16
+ schema: {
17
+ local: {
18
+ pulses: t.collection({
19
+ told: t.uint,
20
+ heard: t.uint,
21
+ owed: t.bool,
22
+ since: t.uint,
23
+ epoch: t.uint
24
+ })
25
+ }
26
+ },
27
+ async setup(me) {
28
+ // the worker's runtime; a UI bundle resolves a stand-in, so the client and its DHT stay out of it
29
+ const { follow } = await import('@cero-base/cero/internal/pulse')
30
+ return follow(me, key)
31
+ }
32
+ }
33
+ }
@@ -16,7 +16,7 @@ import { Invite } from '@cero-base/core/invite'
16
16
  import { Mailbox } from '@cero-base/core/mailbox'
17
17
  import { seal, unseal, decodeAddress } from '../lib/mail.js'
18
18
  import hid from 'hypercore-id-encoding'
19
- import { admission, onAbort, filter, can, WRITE } from '@cero-base/core/utils'
19
+ import { admission, onAbort, filter, can, inTurn, WRITE } from '@cero-base/core/utils'
20
20
  import { CeroError } from '@cero-base/core/errors'
21
21
  import { Blobs } from '@cero-base/core/blobs'
22
22
  import { decodeId, servedType } from '@cero-base/core/blobs/codec'
@@ -25,7 +25,6 @@ import { FileServer } from '@cero-base/core/blobs/server'
25
25
  import { KEEP_OPEN, LOOKS, NS, PASSES, REFUSALS, SPENT, TIMEOUT } from '../lib/constants.js'
26
26
 
27
27
  import { Ref } from '../lib/refs.js'
28
- import { box } from '../local/index.js'
29
28
  import { extensionsOf } from '../extensions/index.js'
30
29
 
31
30
  export { Ref } from '../lib/refs.js'
@@ -43,6 +42,7 @@ export { Ref } from '../lib/refs.js'
43
42
  * @property {import('corestore')} [store] Pre-existing Corestore. Falls back to `parent.store.store`.
44
43
  * @property {Spec} [spec] Built cero spec.
45
44
  * @property {Local} [local] Root only, and required there: the device store for handle keypairs and mail.
45
+ * @property {Mailbox} [mailbox] Root only: the device's mailbox, its boxes in `local`, open before the network.
46
46
  * @property {import('hypercore-storage')} [storage] Owned HypercoreStorage to close on shutdown.
47
47
  * @property {{ destroy(): Promise<void> }} [discovery] Owned identity discovery to destroy on shutdown.
48
48
  * @property {string} [dir] Data directory (root handles only).
@@ -99,15 +99,9 @@ export class Handle extends ReadyResource {
99
99
  this.parent = parent
100
100
 
101
101
  this.local = opts.local || null
102
- // one per device: the root's, its boxes in the local store
102
+ // one per device: the root's
103
103
  /** @type {Mailbox} */
104
- this.mailbox = parent
105
- ? parent.root.mailbox
106
- : new Mailbox(network, {
107
- inbox: box(this.local.store, 'inbox'),
108
- outbox: box(this.local.store, 'outbox'),
109
- onerror: (err) => this._onerror(err)
110
- })
104
+ this.mailbox = parent ? parent.root.mailbox : opts.mailbox
111
105
  /** @private */
112
106
  this._storage = opts.storage || null
113
107
  /** @private */
@@ -192,6 +186,9 @@ export class Handle extends ReadyResource {
192
186
  this._tellers = parent ? null : []
193
187
  /** @private */
194
188
  this._retell = false
189
+ // the device's calls, when the calls() extension runs
190
+ /** @private @type {import('../extensions/calls.js').Calls | null} */
191
+ this._calls = null
195
192
 
196
193
  this.store = new Database({
197
194
  store: store,
@@ -362,6 +359,8 @@ export class Handle extends ReadyResource {
362
359
  async _close() {
363
360
  // a write that raced a suspend holds the close until the storage resumes, once a suspend still running settled
364
361
  if (this._sus) await this._sus.resume()
362
+ // a call is left while the room can still write it
363
+ await this.root._calls?.hangup(this).catch(this._onerror)
365
364
  this.root._coreKeys.delete(b4a.toHex(this.store.key))
366
365
  if (this._blobs?.key) this.root._coreKeys.delete(b4a.toHex(this._blobs.key))
367
366
  for (const b of this._epochBlobs?.values() || []) {
@@ -476,6 +475,8 @@ export class Handle extends ReadyResource {
476
475
  // accepting on the root links the device: this one attests its key
477
476
  /** @private */
478
477
  async _answer(id, { accept, role, reason }) {
478
+ // a ring is the room's own row in me.local.rings
479
+ if (!accept && id === this.id && this.root._calls) return this.root._calls.deny(this, reason)
479
480
  if (!accept) return this._pair.deny(id, reason)
480
481
  if (this.parent) return this._pair.accept(id, { role })
481
482
  const { data: row } = await this.store.get('requests', id)
@@ -488,6 +489,13 @@ export class Handle extends ReadyResource {
488
489
  return this.store.rotate()
489
490
  }
490
491
 
492
+ /** @private */
493
+ _dial(opts) {
494
+ const calls = this.root._calls
495
+ if (!calls) throw CeroError.INVALID('dial needs the calls() extension in the build')
496
+ return calls.dial(this, opts)
497
+ }
498
+
491
499
  /** @private */
492
500
  _removed(id) {
493
501
  return this.store.removed(id)
@@ -711,7 +719,7 @@ export class Handle extends ReadyResource {
711
719
  return this._sus
712
720
  }
713
721
 
714
- // true ranks a handle as just used, false takes it off the swarm until something lands in it
722
+ // true ranks a handle as just used, false ranks it last until something lands in it
715
723
  /** @private */
716
724
  _active(on) {
717
725
  this.store.setActive(on)
@@ -833,7 +841,7 @@ export class Handle extends ReadyResource {
833
841
  for (const child of queued.children) await this._topic(child).catch(this._onerror)
834
842
  }
835
843
  }
836
- this._indexing = (this._indexing ?? Promise.resolve()).then(run, run)
844
+ this._indexing = inTurn(this._indexing, run)
837
845
  return this._indexing
838
846
  }
839
847
 
@@ -842,7 +850,7 @@ export class Handle extends ReadyResource {
842
850
  /** @private */
843
851
  _seal(child) {
844
852
  const run = () => this._topic(child, true)
845
- this._indexing = (this._indexing ?? Promise.resolve()).then(run, run)
853
+ this._indexing = inTurn(this._indexing, run)
846
854
  return this._indexing
847
855
  }
848
856
 
@@ -2307,9 +2315,9 @@ export class Handle extends ReadyResource {
2307
2315
  if (row?.epochs) await child.store.learn(c.decode(epochEntries, row.epochs))
2308
2316
  }
2309
2317
  const touches = (name) => (touched) => touched.has('*') || touched.has(name)
2310
- const onepoch = () => save().catch(this._onerror)
2311
- // a room that closed under the read says nothing
2318
+ // a store that closed under the read or the write says nothing: the next open carries them
2312
2319
  const report = (err) => err.code === 'CLOSED' || this._onerror(err)
2320
+ const onepoch = () => save().catch(report)
2313
2321
  const onroot = (touched) => touches('handles')(touched) && read().catch(report)
2314
2322
  const onchild = (touched) => touches('epochs')(touched) && read().catch(report)
2315
2323
  child.store.on('epoch', onepoch)
@@ -2323,7 +2331,7 @@ export class Handle extends ReadyResource {
2323
2331
  this.store.off('epoch', onepoch)
2324
2332
  })
2325
2333
  // one that rotated before it is carried, as a room made while the root owes a rotation
2326
- if (child.store.keyring.seq > 0) read().then(save).catch(this._onerror)
2334
+ if (child.store.keyring.seq > 0) read().then(save).catch(report)
2327
2335
  }
2328
2336
 
2329
2337
  // before(me.room.notes, fn): on every handle open now and every one opened later
package/src/index.js CHANGED
@@ -47,16 +47,16 @@ export { t, schema } from './lib/spec.js'
47
47
  * @property {Array<{ host: string, port: number }>} [bootstrap] Custom DHT bootstrap nodes.
48
48
  * @property {Array<string | Uint8Array>} [relayThrough] Blind relay public keys. Two devices that cannot connect direct, as on mobile carriers, connect through one; the relay forwards encrypted bytes and reads nothing. Direct connections stay direct.
49
49
  * @property {(remotePublicKey: Uint8Array, payload: unknown) => boolean} [firewall] Incoming-connection filter: `true` refuses the connection.
50
- * @property {number[]} [backoffs] Swarm reconnect backoff tiers in ms (testing/tuning).
51
50
  * @property {string} [channel] Optional network-isolation label; only same-channel peers connect.
52
51
  * @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys. Handles and files are mirrored through them so peers sync even when never online at the same time. Mirrors hold only encrypted blocks — they never read your data.
53
- * @property {{ active?: number, announced?: number, idle?: number }} [presence] How many handles search, how many only announce, and the idle ms before the rest leave the swarm.
52
+ * @property {{ active?: number, idle?: number, known?: number, connections?: number }} [presence] How many handles search and announce at once besides the ones in use, the ms one stays on after its last use, how many devices a handle keeps to dial by their keys, and how many connections the device keeps at once.
54
53
  * @property {(err: Error) => void} [onerror] Where background errors go; the console without one.
55
54
  * @property {number} [keepOpen] How many handles stay open after their last close, for a reopen; one more closes the least recently used, 0 closes at once. Defaults to 16.
56
55
  * @property {number} [recoveryTimeout] Max wait to find another device and be admitted, in ms. Defaults to 30000.
57
56
  * @property {Uint8Array} [storageKey] 32-byte key encrypting local key material (master seed, device keypairs) at rest. Source it from the OS keychain — cero never stores it.
58
57
  * @property {import('./extensions/index.js').Extension[]} [extensions] The extensions this instance runs, instead of the ones the spec carries. Build with the same list.
59
58
  * @property {{ on?: boolean, topic?: string, backend?: object | null, maxOutbound?: number, maxInbound?: number, pipe?: 'l2cap' | 'gatt' }} [bluetooth] Bluetooth at start: `on` (off by default) and `topic` (the default one, else the channel's own); the app turns the radio on and off with `cero.nearby`, and nothing is stored. `maxOutbound`/`maxInbound` cap concurrent outbound links and inbound sessions. `pipe` picks the data pipe, `'l2cap'` (default, faster) or `'gatt'`; both peers must match. `backend` injects a bare-bluetooth-shaped backend (tests); with none on the host, `status.nearby` reads `'unsupported'`.
59
+ * @property {import('./lib/media.js').Bindings} [webrtc] The WebRTC calls run their media on where Cero runs in the UI itself; a window's own without it, none in a worker.
60
60
  */
61
61
 
62
62
  /**
@@ -83,6 +83,7 @@ async function start(dir, spec, opts = {}) {
83
83
  let store = null
84
84
  let local = null
85
85
  let network = null
86
+ let mailbox = null
86
87
  let discovery = null
87
88
  let bluetooth = null
88
89
  let me = null
@@ -150,17 +151,22 @@ async function start(dir, spec, opts = {}) {
150
151
  bootstrap: opts.bootstrap,
151
152
  relayThrough: opts.relayThrough,
152
153
  firewall: opts.firewall,
153
- backoffs: opts.backoffs,
154
154
  channel: opts.channel,
155
155
  store,
156
156
  mirrors: opts.mirrors,
157
157
  presence: opts.presence,
158
158
  onerror
159
159
  })
160
- await network.ready()
160
+ // it readies the network once what its inbox left to erase is erased
161
+ mailbox = new Mailbox(network, {
162
+ inbox: box(local.store, 'inbox'),
163
+ outbox: box(local.store, 'outbox'),
164
+ onerror
165
+ })
166
+ await mailbox.ready()
161
167
  // the link first: who this device is comes with the reply
162
168
  const linked = linking
163
- ? await ask(local, network, spec, { ...opts, writer: keyPair, timeout }, pending)
169
+ ? await ask(local, mailbox, spec, { ...opts, writer: keyPair, timeout }, pending)
164
170
  : null
165
171
  const identity = linked ? linked.identity : resolved.identity
166
172
  // the radio before the pointer read: a phrase recovers from a device in range, no internet
@@ -185,6 +191,7 @@ async function start(dir, spec, opts = {}) {
185
191
  discovery,
186
192
  identity,
187
193
  network,
194
+ mailbox,
188
195
  spec,
189
196
  opts,
190
197
  dir,
@@ -235,6 +242,7 @@ async function start(dir, spec, opts = {}) {
235
242
  await me?.store.close().catch(safetyCatch)
236
243
  await discovery?.destroy().catch(safetyCatch)
237
244
  await bluetooth?.close().catch(safetyCatch)
245
+ await mailbox?.close().catch(safetyCatch)
238
246
  await network?.close().catch(safetyCatch)
239
247
  await local?.close().catch(safetyCatch)
240
248
  await store?.close().catch(safetyCatch)
@@ -380,7 +388,7 @@ async function pendingLink(local) {
380
388
 
381
389
  // the root's join: this device, bare, knocks with the invite and waits for a device of the identity
382
390
  // to let it in. What it learns is kept in its joins row, so a killed launch resumes it
383
- async function ask(local, network, spec, { invite, writer, onrequest, timeout, signal }, pending) {
391
+ async function ask(local, mailbox, spec, { invite, writer, onrequest, timeout, signal }, pending) {
384
392
  const parsed = Invite.parse(invite ?? pending.invite)
385
393
  if (parsed.data?.byteLength !== 32) throw CeroError.INVALID_INVITE('not a device invite')
386
394
  const secret = pending?.device ?? Identity.randomKeyPair().secretKey
@@ -399,11 +407,7 @@ async function ask(local, network, spec, { invite, writer, onrequest, timeout, s
399
407
  ? { ...row, epochs: row.epochs ? c.decode(epochEntries, row.epochs) : [] }
400
408
  : null
401
409
  if (!reply) {
402
- const { store } = network
403
- const inbox = box(local.store, 'inbox')
404
- const outbox = box(local.store, 'outbox')
405
- const mailbox = new Mailbox(network, { inbox, outbox })
406
- await mailbox.ready()
410
+ const { store } = mailbox.network
407
411
  try {
408
412
  const signers = [{ publicKey: writer.publicKey }]
409
413
  onrequest?.(hid.encode(Hypercore.key({ version: store.manifestVersion, signers })))
@@ -427,8 +431,6 @@ async function ask(local, network, spec, { invite, writer, onrequest, timeout, s
427
431
  // an expired invite leaves no join a later launch could resume
428
432
  if (err.code === 'EXPIRED') await local.store.del('joins', row.id)
429
433
  throw err
430
- } finally {
431
- await mailbox.close()
432
434
  }
433
435
  }
434
436
  // the chain the accepting device wrote ends at this device, under the identity the invite named
@@ -0,0 +1,28 @@
1
+ /** The lanes a mute names. */
2
+ export const LANES = ['audio', 'video']
3
+
4
+ const REFS = {
5
+ peers: { kind: 'collection', type: 'line-peer' },
6
+ _lanes: { kind: 'single', type: 'line-lanes' },
7
+ _ports: { kind: 'collection', type: 'line-port' }
8
+ }
9
+
10
+ /**
11
+ * @typedef {import('./spec.js').Spec} Spec
12
+ * @typedef {Pick<Spec, 'schema' | 'codec'> & { meta: { refs: Record<string, import('./spec.js').RefInfo> } }} Wire
13
+ */
14
+
15
+ /**
16
+ * What a line carries across RPC: its refs are computed on the device, and cross in the encodings
17
+ * of its room's spec, through the same get and watch a handle's refs use.
18
+ *
19
+ * @param {Spec} spec The room's.
20
+ * @returns {Wire}
21
+ */
22
+ export function wire({ meta, schema, codec }) {
23
+ const refs = {}
24
+ for (const [name, { kind, type }] of Object.entries(REFS)) {
25
+ refs[name] = { kind, live: true, schema: `@${meta.ns}/${type}` }
26
+ }
27
+ return { meta: { refs }, schema, codec }
28
+ }
@@ -0,0 +1,285 @@
1
+ import { parse, write } from 'sdp-transform'
2
+ import { inTurn } from '@cero-base/core/utils'
3
+
4
+ const HOST = '127.0.0.1'
5
+ // max-bundle: an offer sends from one local port from the start, so the worker follows one sender
6
+ const CONFIG = { iceServers: [], rtcpMuxPolicy: 'require', bundlePolicy: 'max-bundle' }
7
+ // by mid, in the order the offerer adds them
8
+ const LANES = ['audio', 'video', 'screen']
9
+ const KINDS = ['audio', 'video', 'video']
10
+
11
+ /**
12
+ * @typedef {object} Bindings The WebRTC a line's media runs on: `react-native-webrtc`, or a window's own.
13
+ * @property {typeof RTCPeerConnection} RTCPeerConnection
14
+ * @property {typeof MediaStream} MediaStream
15
+ *
16
+ * @typedef {object} Bridge The worker's side of a line: this device's lanes once its row is read, and the local port of each other device with the description it sent last.
17
+ * @property {{ id: string, audio: boolean, video: boolean, screen: boolean } | null} self
18
+ * @property {Array<{ id: string, port: number, seq?: number, type?: Signal['type'], sdp?: string }>} peers
19
+ *
20
+ * @typedef {{ type: 'offer' | 'answer', sdp: string }} Signal A WebRTC description.
21
+ *
22
+ * @typedef {object} Conn
23
+ * @property {string} id
24
+ * @property {number} port
25
+ * @property {RTCPeerConnection} pc
26
+ * @property {boolean} offerer
27
+ * @property {RTCRtpTransceiver[] | null} lanes
28
+ * @property {boolean} heard A description from the other side reached it.
29
+ * @property {{ stream: MediaStream, screen: MediaStream } | null} streams
30
+ * @property {boolean} closed
31
+ * @property {Promise<void> | null} turn
32
+ */
33
+
34
+ /**
35
+ * The bindings to run on: the ones given, else the window's.
36
+ *
37
+ * @param {Bindings | null} [webrtc]
38
+ * @returns {Bindings | null}
39
+ */
40
+ export function bindings(webrtc) {
41
+ if (webrtc) return webrtc
42
+ return typeof globalThis.RTCPeerConnection === 'function' ? globalThis : null
43
+ }
44
+
45
+ /**
46
+ * A line's WebRTC: one connection per device on the call, its media through the worker's local port
47
+ * for that device, so no ICE server is needed.
48
+ */
49
+ export class Media {
50
+ /**
51
+ * @param {Bindings} webrtc
52
+ * @param {{ send: (id: string, port: number, data: Signal) => void, onchange: () => void, onerror: (err: Error) => void }} opts `send` a signal to the device on `port`.
53
+ */
54
+ constructor(webrtc, { send, onchange, onerror }) {
55
+ this.webrtc = webrtc
56
+ /** @type {MediaStream | null} The camera and microphone. */
57
+ this.camera = null
58
+ /** @type {MediaStream | null} */
59
+ this.screen = null
60
+ this.muted = { audio: false, video: false }
61
+ this.closed = false
62
+ /** @private */
63
+ this._send = send
64
+ /** @private */
65
+ this._onchange = onchange
66
+ /** @private */
67
+ this._onerror = onerror
68
+ /** @private */
69
+ this._self = ''
70
+ // the last description taken from each device
71
+ /** @private @type {Map<string, number>} */
72
+ this._taken = new Map()
73
+ // this device's lanes as its row shows them
74
+ /** @private @type {Bridge['self']} */
75
+ this._row = null
76
+ /** @private @type {Map<string, Conn>} */
77
+ this._conns = new Map()
78
+ }
79
+
80
+ /**
81
+ * Take the worker's side as it is now: a new port rebuilds that device's connection, and the
82
+ * description a device sent last is applied once.
83
+ *
84
+ * @param {Bridge} bridge
85
+ * @returns {void}
86
+ */
87
+ update({ self, peers }) {
88
+ if (this.closed || !self) return
89
+ this._self = self.id
90
+ // a lane goes out only while this device's row shows it on, whoever turned it off
91
+ const moved = LANES.some((lane) => this._row?.[lane] !== self[lane])
92
+ this._row = self
93
+ if (moved) for (const conn of this._conns.values()) this._attach(conn, [0, 1, 2])
94
+ const ports = new Map(peers.map(({ id, port }) => [id, port]))
95
+ for (const [id, conn] of this._conns) if (ports.get(id) !== conn.port) this._drop(conn)
96
+ for (const [id, port] of ports) if (!this._conns.has(id)) this._open(id, port)
97
+ for (const { id, seq, type, sdp } of peers) {
98
+ // taken once, however often the worker's side is read
99
+ if (!(seq > (this._taken.get(id) ?? 0))) continue
100
+ this._taken.set(id, seq)
101
+ this._route(this._conns.get(id), { type, sdp })
102
+ }
103
+ }
104
+
105
+ /**
106
+ * What a device shows: its media only while connected, its screen only while its row shares one.
107
+ *
108
+ * @param {string} id
109
+ * @param {boolean} sharing
110
+ * @returns {{ stream: MediaStream | null, screen: MediaStream | null, connected: boolean }}
111
+ */
112
+ entry(id, sharing) {
113
+ const conn = this._conns.get(id)
114
+ const connected = !!conn?.streams && conn.pc.connectionState === 'connected'
115
+ return {
116
+ stream: connected ? conn.streams.stream : null,
117
+ screen: connected && sharing ? conn.streams.screen : null,
118
+ connected
119
+ }
120
+ }
121
+
122
+ /** @param {MediaStream | null} stream The camera and microphone, or none. */
123
+ share(stream) {
124
+ this.camera = stream
125
+ // a mute holds on the new tracks; one the app turned off is never turned on here, only by an unmute
126
+ for (const lane of ['audio', 'video']) {
127
+ if (this.muted[lane]) for (const track of tracks(stream, lane)) track.enabled = false
128
+ }
129
+ for (const conn of this._conns.values()) this._attach(conn, [0, 1])
130
+ }
131
+
132
+ /** @param {MediaStream | null} stream A screen, or none. */
133
+ present(stream) {
134
+ this.screen = stream
135
+ for (const conn of this._conns.values()) this._attach(conn, [2])
136
+ }
137
+
138
+ /**
139
+ * @param {'audio' | 'video'} lane
140
+ * @param {boolean} on
141
+ */
142
+ lane(lane, on) {
143
+ this.muted[lane] = !on
144
+ for (const track of tracks(this.camera, lane)) track.enabled = on
145
+ for (const conn of this._conns.values()) this._attach(conn, [LANES.indexOf(lane)])
146
+ }
147
+
148
+ close() {
149
+ this.closed = true
150
+ for (const conn of this._conns.values()) this._drop(conn)
151
+ }
152
+
153
+ /** @private */
154
+ _open(id, port) {
155
+ const was = this._conns.get(id)
156
+ if (was) this._drop(was)
157
+ const pc = new this.webrtc.RTCPeerConnection(CONFIG)
158
+ /** @type {Conn} */
159
+ const conn = {
160
+ id,
161
+ port,
162
+ pc,
163
+ offerer: this._self > id,
164
+ lanes: null,
165
+ heard: false,
166
+ streams: null,
167
+ closed: false,
168
+ turn: null
169
+ }
170
+ pc.addEventListener('connectionstatechange', () => this._state(conn))
171
+ this._conns.set(id, conn)
172
+ if (conn.offerer) {
173
+ conn.lanes = KINDS.map((kind) => pc.addTransceiver(kind, { direction: 'sendrecv' }))
174
+ this._attach(conn, [0, 1, 2])
175
+ this._turn(conn, () => this._describe(conn, () => pc.createOffer()))
176
+ }
177
+ this._onchange()
178
+ return conn
179
+ }
180
+
181
+ // decided as it arrives, so the signals after it reach the connection it chose
182
+ /** @private */
183
+ _route(conn, data) {
184
+ const { type } = data
185
+ if (type === 'offer') {
186
+ // the other side started over
187
+ if (conn.heard) conn = this._open(conn.id, conn.port)
188
+ conn.heard = true
189
+ } else if (type === 'answer') {
190
+ if (conn.heard) return
191
+ conn.heard = true
192
+ }
193
+ this._turn(conn, () => this._take(conn, data))
194
+ }
195
+
196
+ /** @private */
197
+ async _take(conn, { type, sdp }) {
198
+ await conn.pc.setRemoteDescription({ type, sdp: route(sdp, conn.port) })
199
+ if (type !== 'offer') return
200
+ conn.lanes = laned(conn.pc.getTransceivers())
201
+ if (!conn.lanes) throw new Error('an offer carries a microphone, a camera and a screen lane')
202
+ for (const transceiver of conn.lanes) transceiver.direction = 'sendrecv'
203
+ this._attach(conn, [0, 1, 2])
204
+ await this._describe(conn, () => conn.pc.createAnswer())
205
+ }
206
+
207
+ /** @private */
208
+ async _describe(conn, make) {
209
+ await conn.pc.setLocalDescription(await make())
210
+ const { type, sdp } = conn.pc.localDescription
211
+ this._send(conn.id, conn.port, { type, sdp })
212
+ }
213
+
214
+ /** @private */
215
+ _attach(conn, lanes) {
216
+ if (!conn.lanes) return
217
+ for (const i of lanes) {
218
+ const track = this._track(LANES[i])
219
+ conn.lanes[i].sender.replaceTrack(track).catch((err) => conn.closed || this._onerror(err))
220
+ }
221
+ }
222
+
223
+ /** @private */
224
+ _track(lane) {
225
+ if (!this._row?.[lane]) return null
226
+ if (lane === 'screen') return tracks(this.screen, 'video')[0] ?? null
227
+ return this.muted[lane] ? null : (tracks(this.camera, lane)[0] ?? null)
228
+ }
229
+
230
+ /** @private */
231
+ _state(conn) {
232
+ // lost on a port that did not move: the side that offers starts over, the other rebuilds on its offer
233
+ if (conn.pc.connectionState === 'failed' && conn.offerer && !conn.closed) {
234
+ this._open(conn.id, conn.port)
235
+ return
236
+ }
237
+ if (conn.pc.connectionState === 'connected' && !conn.streams) {
238
+ const [audio, video, screen] = conn.lanes.map((transceiver) => transceiver.receiver.track)
239
+ const { MediaStream } = this.webrtc
240
+ conn.streams = { stream: new MediaStream([audio, video]), screen: new MediaStream([screen]) }
241
+ }
242
+ this._onchange()
243
+ }
244
+
245
+ /** @private */
246
+ _turn(conn, fn) {
247
+ conn.turn = inTurn(conn.turn, fn).catch((err) => conn.closed || this._onerror(err))
248
+ }
249
+
250
+ // closed before another takes its port: its probes must not reach the next one
251
+ /** @private */
252
+ _drop(conn) {
253
+ conn.closed = true
254
+ if (this._conns.get(conn.id) === conn) this._conns.delete(conn.id)
255
+ conn.pc.close()
256
+ this._onchange()
257
+ }
258
+ }
259
+
260
+ // an offer's lanes by mid, or null when they are not the three in their order
261
+ function laned(transceivers) {
262
+ const lanes = KINDS.map((kind, i) =>
263
+ transceivers.find((t) => t.mid === String(i) && t.receiver.track?.kind === kind)
264
+ )
265
+ return transceivers.length === KINDS.length && lanes.every(Boolean) ? lanes : null
266
+ }
267
+
268
+ function tracks(stream, lane) {
269
+ if (!stream) return []
270
+ return lane === 'audio' ? stream.getAudioTracks() : stream.getVideoTracks()
271
+ }
272
+
273
+ // the other device is reached through this host's port for it, its own addresses are never tried
274
+ function route(sdp, port) {
275
+ const parsed = parse(sdp)
276
+ for (const media of parsed.media) {
277
+ media.port = port
278
+ media.connection = { version: 4, ip: HOST }
279
+ if (media.rtcp) media.rtcp = { port, netType: 'IN', ipVer: 4, address: HOST }
280
+ media.candidates = [
281
+ { foundation: '1', component: 1, transport: 'udp', priority: 1, ip: HOST, port, type: 'host' }
282
+ ]
283
+ }
284
+ return write(parsed)
285
+ }