@cero-base/cero 3.5.0 → 3.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -9
- package/package.json +14 -2
- package/src/build/index.js +6 -1
- package/src/build/schemas.js +25 -0
- package/src/extensions/calls.js +929 -0
- package/src/extensions/index.js +3 -1
- package/src/extensions/pulse.js +33 -0
- package/src/handle/index.js +17 -9
- package/src/index.js +15 -11
- package/src/lib/line.js +41 -0
- package/src/lib/media.js +309 -0
- package/src/lib/operators.js +108 -7
- package/src/lib/pulse-ui.js +5 -0
- package/src/lib/pulse.js +505 -0
- package/src/lib/refs.js +3 -3
- package/src/push/firebase.js +1 -1
- package/src/push/index.js +25 -19
- package/src/rpc/client.js +215 -2
- package/src/rpc/server.js +30 -3
- package/types/build/schemas.d.ts +22 -0
- package/types/extensions/calls.d.ts +218 -0
- package/types/extensions/index.d.ts +15 -4
- package/types/extensions/pulse.d.ts +11 -0
- package/types/handle/index.d.ts +9 -0
- package/types/index.d.ts +9 -2
- package/types/lib/line.d.ts +28 -0
- package/types/lib/media.d.ts +171 -0
- package/types/lib/operators.d.ts +64 -7
- package/types/lib/pulse-ui.d.ts +1 -0
- package/types/lib/pulse.d.ts +11 -0
- package/types/lib/refs.d.ts +5 -5
- package/types/push/firebase.d.ts +1 -1
- package/types/push/index.d.ts +8 -6
- package/types/rpc/client.d.ts +20 -3
- package/types/rpc/server.d.ts +6 -0
package/src/extensions/index.js
CHANGED
|
@@ -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
|
+
}
|
package/src/handle/index.js
CHANGED
|
@@ -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
|
|
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)
|
package/src/index.js
CHANGED
|
@@ -49,13 +49,14 @@ export { t, schema } from './lib/spec.js'
|
|
|
49
49
|
* @property {(remotePublicKey: Uint8Array, payload: unknown) => boolean} [firewall] Incoming-connection filter: `true` refuses the connection.
|
|
50
50
|
* @property {string} [channel] Optional network-isolation label; only same-channel peers connect.
|
|
51
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.
|
|
52
|
-
* @property {{ active?: number, idle?: number }} [presence] How many handles
|
|
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.
|
|
53
53
|
* @property {(err: Error) => void} [onerror] Where background errors go; the console without one.
|
|
54
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.
|
|
55
55
|
* @property {number} [recoveryTimeout] Max wait to find another device and be admitted, in ms. Defaults to 30000.
|
|
56
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.
|
|
57
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.
|
|
58
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.
|
|
59
60
|
*/
|
|
60
61
|
|
|
61
62
|
/**
|
|
@@ -82,6 +83,7 @@ async function start(dir, spec, opts = {}) {
|
|
|
82
83
|
let store = null
|
|
83
84
|
let local = null
|
|
84
85
|
let network = null
|
|
86
|
+
let mailbox = null
|
|
85
87
|
let discovery = null
|
|
86
88
|
let bluetooth = null
|
|
87
89
|
let me = null
|
|
@@ -155,10 +157,16 @@ async function start(dir, spec, opts = {}) {
|
|
|
155
157
|
presence: opts.presence,
|
|
156
158
|
onerror
|
|
157
159
|
})
|
|
158
|
-
|
|
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()
|
|
159
167
|
// the link first: who this device is comes with the reply
|
|
160
168
|
const linked = linking
|
|
161
|
-
? await ask(local,
|
|
169
|
+
? await ask(local, mailbox, spec, { ...opts, writer: keyPair, timeout }, pending)
|
|
162
170
|
: null
|
|
163
171
|
const identity = linked ? linked.identity : resolved.identity
|
|
164
172
|
// the radio before the pointer read: a phrase recovers from a device in range, no internet
|
|
@@ -183,6 +191,7 @@ async function start(dir, spec, opts = {}) {
|
|
|
183
191
|
discovery,
|
|
184
192
|
identity,
|
|
185
193
|
network,
|
|
194
|
+
mailbox,
|
|
186
195
|
spec,
|
|
187
196
|
opts,
|
|
188
197
|
dir,
|
|
@@ -233,6 +242,7 @@ async function start(dir, spec, opts = {}) {
|
|
|
233
242
|
await me?.store.close().catch(safetyCatch)
|
|
234
243
|
await discovery?.destroy().catch(safetyCatch)
|
|
235
244
|
await bluetooth?.close().catch(safetyCatch)
|
|
245
|
+
await mailbox?.close().catch(safetyCatch)
|
|
236
246
|
await network?.close().catch(safetyCatch)
|
|
237
247
|
await local?.close().catch(safetyCatch)
|
|
238
248
|
await store?.close().catch(safetyCatch)
|
|
@@ -378,7 +388,7 @@ async function pendingLink(local) {
|
|
|
378
388
|
|
|
379
389
|
// the root's join: this device, bare, knocks with the invite and waits for a device of the identity
|
|
380
390
|
// to let it in. What it learns is kept in its joins row, so a killed launch resumes it
|
|
381
|
-
async function ask(local,
|
|
391
|
+
async function ask(local, mailbox, spec, { invite, writer, onrequest, timeout, signal }, pending) {
|
|
382
392
|
const parsed = Invite.parse(invite ?? pending.invite)
|
|
383
393
|
if (parsed.data?.byteLength !== 32) throw CeroError.INVALID_INVITE('not a device invite')
|
|
384
394
|
const secret = pending?.device ?? Identity.randomKeyPair().secretKey
|
|
@@ -397,11 +407,7 @@ async function ask(local, network, spec, { invite, writer, onrequest, timeout, s
|
|
|
397
407
|
? { ...row, epochs: row.epochs ? c.decode(epochEntries, row.epochs) : [] }
|
|
398
408
|
: null
|
|
399
409
|
if (!reply) {
|
|
400
|
-
const { store } = network
|
|
401
|
-
const inbox = box(local.store, 'inbox')
|
|
402
|
-
const outbox = box(local.store, 'outbox')
|
|
403
|
-
const mailbox = new Mailbox(network, { inbox, outbox })
|
|
404
|
-
await mailbox.ready()
|
|
410
|
+
const { store } = mailbox.network
|
|
405
411
|
try {
|
|
406
412
|
const signers = [{ publicKey: writer.publicKey }]
|
|
407
413
|
onrequest?.(hid.encode(Hypercore.key({ version: store.manifestVersion, signers })))
|
|
@@ -425,8 +431,6 @@ async function ask(local, network, spec, { invite, writer, onrequest, timeout, s
|
|
|
425
431
|
// an expired invite leaves no join a later launch could resume
|
|
426
432
|
if (err.code === 'EXPIRED') await local.store.del('joins', row.id)
|
|
427
433
|
throw err
|
|
428
|
-
} finally {
|
|
429
|
-
await mailbox.close()
|
|
430
434
|
}
|
|
431
435
|
}
|
|
432
436
|
// the chain the accepting device wrote ends at this device, under the identity the invite named
|
package/src/lib/line.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** The lanes a mute names. */
|
|
2
|
+
export const LANES = ['audio', 'video']
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The lanes a stream starts off: a kind it has no track of turned on. With no stream, none: what
|
|
6
|
+
* a device with no WebRTC says of its lanes is its own.
|
|
7
|
+
*
|
|
8
|
+
* @param {MediaStream | null} stream
|
|
9
|
+
* @returns {string[]}
|
|
10
|
+
*/
|
|
11
|
+
export function muted(stream) {
|
|
12
|
+
if (!stream) return []
|
|
13
|
+
const tracks = { audio: stream.getAudioTracks(), video: stream.getVideoTracks() }
|
|
14
|
+
return LANES.filter((lane) => !tracks[lane].some((track) => track.enabled))
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const REFS = {
|
|
18
|
+
peers: { kind: 'collection', type: 'line-peer' },
|
|
19
|
+
_lanes: { kind: 'single', type: 'line-lanes' },
|
|
20
|
+
_ports: { kind: 'collection', type: 'line-port' }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @typedef {import('./spec.js').Spec} Spec
|
|
25
|
+
* @typedef {Pick<Spec, 'schema' | 'codec'> & { meta: { refs: Record<string, import('./spec.js').RefInfo> } }} Wire
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* What a line carries across RPC: its refs are computed on the device, and cross in the encodings
|
|
30
|
+
* of its room's spec, through the same get and watch a handle's refs use.
|
|
31
|
+
*
|
|
32
|
+
* @param {Spec} spec The room's.
|
|
33
|
+
* @returns {Wire}
|
|
34
|
+
*/
|
|
35
|
+
export function wire({ meta, schema, codec }) {
|
|
36
|
+
const refs = {}
|
|
37
|
+
for (const [name, { kind, type }] of Object.entries(REFS)) {
|
|
38
|
+
refs[name] = { kind, live: true, schema: `@${meta.ns}/${type}` }
|
|
39
|
+
}
|
|
40
|
+
return { meta: { refs }, schema, codec }
|
|
41
|
+
}
|
package/src/lib/media.js
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
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
|
+
* How long a connection may stay unconnected before the side that offers starts it over: from its
|
|
13
|
+
* offer, and from a drop. A lost offer or answer heals at the first.
|
|
14
|
+
*/
|
|
15
|
+
export const durations = { deadline: 5000, grace: 2000 }
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @typedef {object} Bindings The WebRTC a line's media runs on: `react-native-webrtc`, or a window's own.
|
|
19
|
+
* @property {typeof RTCPeerConnection} RTCPeerConnection
|
|
20
|
+
* @property {typeof MediaStream} MediaStream
|
|
21
|
+
*
|
|
22
|
+
* @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.
|
|
23
|
+
* @property {{ id: string, audio: boolean, video: boolean, screen: boolean } | null} self
|
|
24
|
+
* @property {Array<{ id: string, port: number, seq?: number, type?: Signal['type'], sdp?: string }>} peers
|
|
25
|
+
*
|
|
26
|
+
* @typedef {{ type: 'offer' | 'answer', sdp: string }} Signal A WebRTC description.
|
|
27
|
+
*
|
|
28
|
+
* @typedef {object} Conn
|
|
29
|
+
* @property {string} id
|
|
30
|
+
* @property {number} port
|
|
31
|
+
* @property {RTCPeerConnection} pc
|
|
32
|
+
* @property {boolean} offerer
|
|
33
|
+
* @property {RTCRtpTransceiver[] | null} lanes
|
|
34
|
+
* @property {boolean} heard A description from the other side reached it.
|
|
35
|
+
* @property {{ stream: MediaStream, screen: MediaStream } | null} streams
|
|
36
|
+
* @property {boolean} closed
|
|
37
|
+
* @property {Promise<void> | null} turn
|
|
38
|
+
* @property {ReturnType<typeof setTimeout> | null} timer When the side that offers starts it over, unless connected by then.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The bindings to run on: the ones given, else the window's.
|
|
43
|
+
*
|
|
44
|
+
* @param {Bindings | null} [webrtc]
|
|
45
|
+
* @returns {Bindings | null}
|
|
46
|
+
*/
|
|
47
|
+
export function bindings(webrtc) {
|
|
48
|
+
if (webrtc) return webrtc
|
|
49
|
+
return typeof globalThis.RTCPeerConnection === 'function' ? globalThis : null
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* A line's WebRTC: one connection per device on the call, its media through the worker's local port
|
|
54
|
+
* for that device, so no ICE server is needed.
|
|
55
|
+
*/
|
|
56
|
+
export class Media {
|
|
57
|
+
/**
|
|
58
|
+
* @param {Bindings} webrtc
|
|
59
|
+
* @param {{ send: (id: string, port: number, data: Signal) => void, onchange: () => void, onerror: (err: Error) => void }} opts `send` a signal to the device on `port`.
|
|
60
|
+
*/
|
|
61
|
+
constructor(webrtc, { send, onchange, onerror }) {
|
|
62
|
+
this.webrtc = webrtc
|
|
63
|
+
/** @type {MediaStream | null} The camera and microphone. */
|
|
64
|
+
this.camera = null
|
|
65
|
+
/** @type {MediaStream | null} */
|
|
66
|
+
this.screen = null
|
|
67
|
+
this.muted = { audio: false, video: false }
|
|
68
|
+
this.closed = false
|
|
69
|
+
/** @private */
|
|
70
|
+
this._send = send
|
|
71
|
+
/** @private */
|
|
72
|
+
this._onchange = onchange
|
|
73
|
+
/** @private */
|
|
74
|
+
this._onerror = onerror
|
|
75
|
+
/** @private */
|
|
76
|
+
this._self = ''
|
|
77
|
+
// the last description taken from each device
|
|
78
|
+
/** @private @type {Map<string, number>} */
|
|
79
|
+
this._taken = new Map()
|
|
80
|
+
// this device's lanes as its row shows them
|
|
81
|
+
/** @private @type {Bridge['self']} */
|
|
82
|
+
this._row = null
|
|
83
|
+
/** @private @type {Map<string, Conn>} */
|
|
84
|
+
this._conns = new Map()
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Take the worker's side as it is now: a new port rebuilds that device's connection, and the
|
|
89
|
+
* description a device sent last is applied once.
|
|
90
|
+
*
|
|
91
|
+
* @param {Bridge} bridge
|
|
92
|
+
* @returns {void}
|
|
93
|
+
*/
|
|
94
|
+
update({ self, peers }) {
|
|
95
|
+
if (this.closed || !self) return
|
|
96
|
+
this._self = self.id
|
|
97
|
+
// a lane goes out only while this device's row shows it on, whoever turned it off
|
|
98
|
+
const moved = LANES.some((lane) => this._row?.[lane] !== self[lane])
|
|
99
|
+
this._row = self
|
|
100
|
+
if (moved) for (const conn of this._conns.values()) this._attach(conn, [0, 1, 2])
|
|
101
|
+
const ports = new Map(peers.map(({ id, port }) => [id, port]))
|
|
102
|
+
for (const [id, conn] of this._conns) if (ports.get(id) !== conn.port) this._drop(conn)
|
|
103
|
+
for (const [id, port] of ports) if (!this._conns.has(id)) this._open(id, port)
|
|
104
|
+
for (const { id, seq, type, sdp } of peers) {
|
|
105
|
+
// taken once, however often the worker's side is read
|
|
106
|
+
if (!(seq > (this._taken.get(id) ?? 0))) continue
|
|
107
|
+
this._taken.set(id, seq)
|
|
108
|
+
this._route(this._conns.get(id), { type, sdp })
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* What a device shows: its media only while connected, its screen only while its row shares one.
|
|
114
|
+
*
|
|
115
|
+
* @param {string} id
|
|
116
|
+
* @param {boolean} sharing
|
|
117
|
+
* @returns {{ stream: MediaStream | null, screen: MediaStream | null, connected: boolean }}
|
|
118
|
+
*/
|
|
119
|
+
entry(id, sharing) {
|
|
120
|
+
const conn = this._conns.get(id)
|
|
121
|
+
const connected = !!conn?.streams && conn.pc.connectionState === 'connected'
|
|
122
|
+
return {
|
|
123
|
+
stream: connected ? conn.streams.stream : null,
|
|
124
|
+
screen: connected && sharing ? conn.streams.screen : null,
|
|
125
|
+
connected
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** @param {MediaStream | null} stream The camera and microphone, or none. */
|
|
130
|
+
share(stream) {
|
|
131
|
+
this.camera = stream
|
|
132
|
+
// a mute holds on the new tracks; one the app turned off is never turned on here, only by an unmute
|
|
133
|
+
for (const lane of ['audio', 'video']) {
|
|
134
|
+
if (this.muted[lane]) for (const track of tracks(stream, lane)) track.enabled = false
|
|
135
|
+
}
|
|
136
|
+
for (const conn of this._conns.values()) this._attach(conn, [0, 1])
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** @param {MediaStream | null} stream A screen, or none. */
|
|
140
|
+
present(stream) {
|
|
141
|
+
this.screen = stream
|
|
142
|
+
for (const conn of this._conns.values()) this._attach(conn, [2])
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* @param {'audio' | 'video'} lane
|
|
147
|
+
* @param {boolean} on
|
|
148
|
+
*/
|
|
149
|
+
lane(lane, on) {
|
|
150
|
+
this.muted[lane] = !on
|
|
151
|
+
for (const track of tracks(this.camera, lane)) track.enabled = on
|
|
152
|
+
for (const conn of this._conns.values()) this._attach(conn, [LANES.indexOf(lane)])
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
close() {
|
|
156
|
+
this.closed = true
|
|
157
|
+
for (const conn of this._conns.values()) this._drop(conn)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** @private */
|
|
161
|
+
_open(id, port) {
|
|
162
|
+
const was = this._conns.get(id)
|
|
163
|
+
if (was) this._drop(was)
|
|
164
|
+
const pc = new this.webrtc.RTCPeerConnection(CONFIG)
|
|
165
|
+
/** @type {Conn} */
|
|
166
|
+
const conn = {
|
|
167
|
+
id,
|
|
168
|
+
port,
|
|
169
|
+
pc,
|
|
170
|
+
offerer: this._self > id,
|
|
171
|
+
lanes: null,
|
|
172
|
+
heard: false,
|
|
173
|
+
streams: null,
|
|
174
|
+
closed: false,
|
|
175
|
+
turn: null,
|
|
176
|
+
timer: null
|
|
177
|
+
}
|
|
178
|
+
pc.addEventListener('connectionstatechange', () => this._state(conn))
|
|
179
|
+
this._conns.set(id, conn)
|
|
180
|
+
if (conn.offerer) {
|
|
181
|
+
conn.lanes = KINDS.map((kind) => pc.addTransceiver(kind, { direction: 'sendrecv' }))
|
|
182
|
+
this._attach(conn, [0, 1, 2])
|
|
183
|
+
this._turn(conn, () => this._describe(conn, () => pc.createOffer()))
|
|
184
|
+
this._due(conn, durations.deadline)
|
|
185
|
+
}
|
|
186
|
+
this._onchange()
|
|
187
|
+
return conn
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// decided as it arrives, so the signals after it reach the connection it chose
|
|
191
|
+
/** @private */
|
|
192
|
+
_route(conn, data) {
|
|
193
|
+
const { type } = data
|
|
194
|
+
if (type === 'offer') {
|
|
195
|
+
// the other side started over
|
|
196
|
+
if (conn.heard) conn = this._open(conn.id, conn.port)
|
|
197
|
+
conn.heard = true
|
|
198
|
+
} else if (type === 'answer') {
|
|
199
|
+
if (conn.heard) return
|
|
200
|
+
conn.heard = true
|
|
201
|
+
}
|
|
202
|
+
this._turn(conn, () => this._take(conn, data))
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** @private */
|
|
206
|
+
async _take(conn, { type, sdp }) {
|
|
207
|
+
await conn.pc.setRemoteDescription({ type, sdp: route(sdp, conn.port) })
|
|
208
|
+
if (type !== 'offer') return
|
|
209
|
+
conn.lanes = laned(conn.pc.getTransceivers())
|
|
210
|
+
if (!conn.lanes) throw new Error('an offer carries a microphone, a camera and a screen lane')
|
|
211
|
+
for (const transceiver of conn.lanes) transceiver.direction = 'sendrecv'
|
|
212
|
+
this._attach(conn, [0, 1, 2])
|
|
213
|
+
await this._describe(conn, () => conn.pc.createAnswer())
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** @private */
|
|
217
|
+
async _describe(conn, make) {
|
|
218
|
+
await conn.pc.setLocalDescription(await make())
|
|
219
|
+
const { type, sdp } = conn.pc.localDescription
|
|
220
|
+
this._send(conn.id, conn.port, { type, sdp })
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** @private */
|
|
224
|
+
_attach(conn, lanes) {
|
|
225
|
+
if (!conn.lanes) return
|
|
226
|
+
for (const i of lanes) {
|
|
227
|
+
const track = this._track(LANES[i])
|
|
228
|
+
conn.lanes[i].sender.replaceTrack(track).catch((err) => conn.closed || this._onerror(err))
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** @private */
|
|
233
|
+
_track(lane) {
|
|
234
|
+
if (!this._row?.[lane]) return null
|
|
235
|
+
if (lane === 'screen') return tracks(this.screen, 'video')[0] ?? null
|
|
236
|
+
return this.muted[lane] ? null : (tracks(this.camera, lane)[0] ?? null)
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// not connected by then, the side that offers starts over, and the other rebuilds on its offer
|
|
240
|
+
/** @private */
|
|
241
|
+
_due(conn, ms) {
|
|
242
|
+
clearTimeout(conn.timer)
|
|
243
|
+
conn.timer = setTimeout(() => {
|
|
244
|
+
if (!conn.closed && conn.pc.connectionState !== 'connected') this._open(conn.id, conn.port)
|
|
245
|
+
}, ms)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** @private */
|
|
249
|
+
_state(conn) {
|
|
250
|
+
const state = conn.pc.connectionState
|
|
251
|
+
// lost on a port that did not move: the side that offers starts over, the other rebuilds on its offer
|
|
252
|
+
if (state === 'failed' && conn.offerer && !conn.closed) {
|
|
253
|
+
this._open(conn.id, conn.port)
|
|
254
|
+
return
|
|
255
|
+
}
|
|
256
|
+
if (state === 'connected') clearTimeout(conn.timer)
|
|
257
|
+
if (state === 'disconnected' && conn.offerer && !conn.closed) {
|
|
258
|
+
this._due(conn, durations.grace)
|
|
259
|
+
}
|
|
260
|
+
if (conn.pc.connectionState === 'connected' && !conn.streams) {
|
|
261
|
+
const [audio, video, screen] = conn.lanes.map((transceiver) => transceiver.receiver.track)
|
|
262
|
+
const { MediaStream } = this.webrtc
|
|
263
|
+
conn.streams = { stream: new MediaStream([audio, video]), screen: new MediaStream([screen]) }
|
|
264
|
+
}
|
|
265
|
+
this._onchange()
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** @private */
|
|
269
|
+
_turn(conn, fn) {
|
|
270
|
+
conn.turn = inTurn(conn.turn, fn).catch((err) => conn.closed || this._onerror(err))
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// closed before another takes its port: its probes must not reach the next one
|
|
274
|
+
/** @private */
|
|
275
|
+
_drop(conn) {
|
|
276
|
+
conn.closed = true
|
|
277
|
+
clearTimeout(conn.timer)
|
|
278
|
+
if (this._conns.get(conn.id) === conn) this._conns.delete(conn.id)
|
|
279
|
+
conn.pc.close()
|
|
280
|
+
this._onchange()
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// an offer's lanes by mid, or null when they are not the three in their order
|
|
285
|
+
function laned(transceivers) {
|
|
286
|
+
const lanes = KINDS.map((kind, i) =>
|
|
287
|
+
transceivers.find((t) => t.mid === String(i) && t.receiver.track?.kind === kind)
|
|
288
|
+
)
|
|
289
|
+
return transceivers.length === KINDS.length && lanes.every(Boolean) ? lanes : null
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function tracks(stream, lane) {
|
|
293
|
+
if (!stream) return []
|
|
294
|
+
return lane === 'audio' ? stream.getAudioTracks() : stream.getVideoTracks()
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// the other device is reached through this host's port for it, its own addresses are never tried
|
|
298
|
+
function route(sdp, port) {
|
|
299
|
+
const parsed = parse(sdp)
|
|
300
|
+
for (const media of parsed.media) {
|
|
301
|
+
media.port = port
|
|
302
|
+
media.connection = { version: 4, ip: HOST }
|
|
303
|
+
if (media.rtcp) media.rtcp = { port, netType: 'IN', ipVer: 4, address: HOST }
|
|
304
|
+
media.candidates = [
|
|
305
|
+
{ foundation: '1', component: 1, transport: 'udp', priority: 1, ip: HOST, port, type: 'host' }
|
|
306
|
+
]
|
|
307
|
+
}
|
|
308
|
+
return write(parsed)
|
|
309
|
+
}
|