@zero-server/sdk 0.9.6 → 0.9.8

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 (94) hide show
  1. package/README.md +54 -53
  2. package/index.js +116 -4
  3. package/lib/app.js +22 -22
  4. package/lib/auth/authorize.js +11 -11
  5. package/lib/auth/enrollment.js +5 -5
  6. package/lib/auth/jwt.js +9 -9
  7. package/lib/auth/oauth.js +1 -1
  8. package/lib/auth/session.js +5 -5
  9. package/lib/auth/trustedDevice.js +2 -2
  10. package/lib/auth/twoFactor.js +11 -11
  11. package/lib/auth/webauthn.js +6 -6
  12. package/lib/body/json.js +1 -1
  13. package/lib/body/raw.js +1 -1
  14. package/lib/body/rawBuffer.js +1 -1
  15. package/lib/body/text.js +1 -1
  16. package/lib/body/urlencoded.js +3 -3
  17. package/lib/cli.js +43 -28
  18. package/lib/cluster.js +3 -3
  19. package/lib/debug.js +10 -10
  20. package/lib/env/index.js +11 -11
  21. package/lib/errors.js +131 -16
  22. package/lib/fetch/index.js +1 -1
  23. package/lib/grpc/call.js +14 -14
  24. package/lib/grpc/client.js +4 -4
  25. package/lib/grpc/codec.js +7 -7
  26. package/lib/grpc/credentials.js +2 -2
  27. package/lib/grpc/frame.js +2 -2
  28. package/lib/grpc/health.js +3 -3
  29. package/lib/grpc/index.js +3 -3
  30. package/lib/grpc/metadata.js +3 -3
  31. package/lib/grpc/proto.js +5 -5
  32. package/lib/grpc/reflection.js +2 -2
  33. package/lib/grpc/server.js +3 -3
  34. package/lib/grpc/status.js +2 -2
  35. package/lib/grpc/watch.js +1 -1
  36. package/lib/http/request.js +13 -13
  37. package/lib/http/response.js +2 -2
  38. package/lib/lifecycle.js +5 -5
  39. package/lib/middleware/compress.js +4 -4
  40. package/lib/observe/health.js +1 -1
  41. package/lib/observe/index.js +1 -1
  42. package/lib/observe/logger.js +3 -3
  43. package/lib/observe/metrics.js +4 -4
  44. package/lib/observe/tracing.js +4 -4
  45. package/lib/orm/adapters/json.js +1 -1
  46. package/lib/orm/adapters/memory.js +2 -2
  47. package/lib/orm/adapters/mongo.js +2 -2
  48. package/lib/orm/adapters/mysql.js +2 -2
  49. package/lib/orm/adapters/postgres.js +2 -2
  50. package/lib/orm/adapters/sqlite.js +3 -3
  51. package/lib/orm/audit.js +1 -1
  52. package/lib/orm/index.js +7 -7
  53. package/lib/orm/migrate.js +1 -1
  54. package/lib/orm/model.js +15 -15
  55. package/lib/orm/procedures.js +1 -1
  56. package/lib/orm/profiler.js +1 -1
  57. package/lib/orm/query.js +9 -9
  58. package/lib/orm/schema.js +1 -1
  59. package/lib/orm/seed/data/person.js +1 -1
  60. package/lib/orm/seed/fake.js +10 -10
  61. package/lib/orm/seed/index.js +4 -4
  62. package/lib/orm/seed/rng.js +1 -1
  63. package/lib/orm/snapshot.js +3 -3
  64. package/lib/orm/tenancy.js +6 -6
  65. package/lib/orm/views.js +1 -1
  66. package/lib/router/index.js +9 -9
  67. package/lib/webrtc/bot.js +405 -0
  68. package/lib/webrtc/cli.js +182 -0
  69. package/lib/webrtc/cluster.js +338 -0
  70. package/lib/webrtc/e2ee.js +274 -0
  71. package/lib/webrtc/ice.js +363 -0
  72. package/lib/webrtc/index.js +212 -0
  73. package/lib/webrtc/joinToken.js +171 -0
  74. package/lib/webrtc/observe.js +260 -0
  75. package/lib/webrtc/peer.js +143 -0
  76. package/lib/webrtc/room.js +184 -0
  77. package/lib/webrtc/sdp.js +503 -0
  78. package/lib/webrtc/sfu/index.js +251 -0
  79. package/lib/webrtc/sfu/livekit.js +304 -0
  80. package/lib/webrtc/sfu/mediasoup.js +357 -0
  81. package/lib/webrtc/sfu/memory.js +221 -0
  82. package/lib/webrtc/signaling.js +590 -0
  83. package/lib/webrtc/stun.js +484 -0
  84. package/lib/webrtc/turn/codec.js +370 -0
  85. package/lib/webrtc/turn/credentials.js +156 -0
  86. package/lib/webrtc/turn/server.js +648 -0
  87. package/package.json +2 -2
  88. package/types/body.d.ts +82 -14
  89. package/types/cli.d.ts +40 -2
  90. package/types/index.d.ts +19 -6
  91. package/types/middleware.d.ts +18 -72
  92. package/types/orm.d.ts +4 -13
  93. package/types/request.d.ts +3 -3
  94. package/types/webrtc.d.ts +501 -0
@@ -0,0 +1,251 @@
1
+ /**
2
+ * @module webrtc/sfu
3
+ * @description Pluggable Selective Forwarding Unit (SFU) adapter interface.
4
+ * The signaling hub stays media-agnostic; the adapter owns routers,
5
+ * transports, producers, and consumers. Ships with `MemorySfuAdapter`,
6
+ * `MediasoupSfuAdapter`, and `LiveKitSfuAdapter`. Subclass `SfuAdapter`
7
+ * for custom backends.
8
+ *
9
+ * @example | Select an adapter at boot via env
10
+ * const { loadSfuAdapter } = require('@zero-server/webrtc');
11
+ * const sfu = loadSfuAdapter(process.env.SFU_BACKEND || 'memory', {
12
+ * // adapter-specific options forwarded verbatim
13
+ * workerSettings: { logLevel: 'warn' },
14
+ * });
15
+ *
16
+ * sfu.onEvent((event, payload) => log.debug({ event, payload }, 'sfu'));
17
+ *
18
+ * @example | Wire an SFU into the signaling hub per room
19
+ * const router = await sfu.createRouter({ room: 'lobby' });
20
+ *
21
+ * hub.on('join', async ({ peer, room }) => {
22
+ * if (room.name !== 'lobby') return;
23
+ * const transport = await sfu.createTransport(router, peer);
24
+ * peer.send('sfu-transport', { iceParameters: transport.iceParameters });
25
+ * });
26
+ */
27
+ 'use strict';
28
+
29
+ const { WebRTCError } = require('../../errors');
30
+
31
+ /**
32
+ * Base class every SFU adapter inherits from. Subclasses MUST override
33
+ * every async method; the default implementations throw
34
+ * `WEBRTC_SFU_NOT_IMPLEMENTED` so partial adapters fail loudly.
35
+ *
36
+ * The interface is intentionally tiny so a backend can be written in a
37
+ * single file:
38
+ *
39
+ * @example | Skeleton adapter
40
+ * class MyAdapter extends SfuAdapter {
41
+ * async createRouter(opts) { return { id: cuid(), opts }; }
42
+ * async createTransport(router, peer) { return { id: cuid(), router, peer }; }
43
+ * async produce(transport, kind, rtp) {
44
+ * const id = cuid();
45
+ * this._emit('producer-new', { id, kind, transportId: transport.id });
46
+ * return { id, kind };
47
+ * }
48
+ * async consume(transport, producerId, _rtpCaps) {
49
+ * return { id: cuid(), producerId, transportId: transport.id };
50
+ * }
51
+ * async pauseProducer(id) { this._emit('producer-pause', { id }); }
52
+ * async resumeProducer(id) { this._emit('producer-resume', { id }); }
53
+ * async closeRouter(id) { this._emit('router-close', { id }); }
54
+ * async stats(_scope) { return { ts: Date.now() }; }
55
+ * }
56
+ *
57
+ * @example | Subscribe to adapter events
58
+ * const off = sfu.onEvent((event, payload) => {
59
+ * if (event === 'producer-new') metrics.producers.inc();
60
+ * if (event === 'producer-pause') log.info({ id: payload.id }, 'paused');
61
+ * });
62
+ * // later: off();
63
+ */
64
+ class SfuAdapter
65
+ {
66
+ constructor()
67
+ {
68
+ this._handlers = new Set();
69
+ }
70
+
71
+ /** Override to create a routing context for a single room. */
72
+ async createRouter(_opts)
73
+ {
74
+ throw new WebRTCError('SfuAdapter.createRouter() not implemented', { code: 'WEBRTC_SFU_NOT_IMPLEMENTED' });
75
+ }
76
+
77
+ /** Override to allocate a WebRTC transport for a peer in a router. */
78
+ async createTransport(_router, _peer)
79
+ {
80
+ throw new WebRTCError('SfuAdapter.createTransport() not implemented', { code: 'WEBRTC_SFU_NOT_IMPLEMENTED' });
81
+ }
82
+
83
+ /** Override to bind a producer ('audio' | 'video') to a transport. */
84
+ async produce(_transport, _kind, _rtpParams)
85
+ {
86
+ throw new WebRTCError('SfuAdapter.produce() not implemented', { code: 'WEBRTC_SFU_NOT_IMPLEMENTED' });
87
+ }
88
+
89
+ /** Override to bind a consumer of `producerId` to a transport. */
90
+ async consume(_transport, _producerId, _rtpCaps)
91
+ {
92
+ throw new WebRTCError('SfuAdapter.consume() not implemented', { code: 'WEBRTC_SFU_NOT_IMPLEMENTED' });
93
+ }
94
+
95
+ /** Override to pause a producer (mute upstream forwarding). */
96
+ async pauseProducer(_producerId)
97
+ {
98
+ throw new WebRTCError('SfuAdapter.pauseProducer() not implemented', { code: 'WEBRTC_SFU_NOT_IMPLEMENTED' });
99
+ }
100
+
101
+ /** Override to resume a previously paused producer. */
102
+ async resumeProducer(_producerId)
103
+ {
104
+ throw new WebRTCError('SfuAdapter.resumeProducer() not implemented', { code: 'WEBRTC_SFU_NOT_IMPLEMENTED' });
105
+ }
106
+
107
+ /** Override to close a router and cascade-close its transports. */
108
+ async closeRouter(_routerId)
109
+ {
110
+ throw new WebRTCError('SfuAdapter.closeRouter() not implemented', { code: 'WEBRTC_SFU_NOT_IMPLEMENTED' });
111
+ }
112
+
113
+ /** Override to return adapter stats; `scope` may be a routerId/transportId. */
114
+ async stats(_scope)
115
+ {
116
+ throw new WebRTCError('SfuAdapter.stats() not implemented', { code: 'WEBRTC_SFU_NOT_IMPLEMENTED' });
117
+ }
118
+
119
+ /**
120
+ * Register a handler invoked as `(event, payload)` for adapter-level
121
+ * events ('producer-new', 'producer-pause', 'consumer-new',
122
+ * 'transport-close', 'router-close', etc.).
123
+ *
124
+ * Returns an unsubscribe function.
125
+ */
126
+ onEvent(handler)
127
+ {
128
+ if (typeof handler !== 'function')
129
+ {
130
+ throw new WebRTCError('onEvent() handler must be a function', { code: 'WEBRTC_SFU_INVALID_HANDLER' });
131
+ }
132
+ this._handlers.add(handler);
133
+ return () => this._handlers.delete(handler);
134
+ }
135
+
136
+ /** Emit `event` with `payload` to every registered handler. */
137
+ _emit(event, payload)
138
+ {
139
+ for (const fn of this._handlers)
140
+ {
141
+ try { fn(event, payload); }
142
+ catch (_) { /* swallow handler errors so adapters keep running */ }
143
+ }
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Lazy-load and instantiate an SFU adapter.
149
+ *
150
+ * @param {object|string} spec - one of:
151
+ * - an object exposing the SfuAdapter contract (returned as-is),
152
+ * - 'memory' | 'mediasoup' | 'livekit' | adapter package id.
153
+ * @param {object} [opts] - constructor options forwarded to the adapter.
154
+ * @returns {SfuAdapter}
155
+ *
156
+ * @example | Built-in adapter by name
157
+ * const sfu = loadSfuAdapter('mediasoup', {
158
+ * numWorkers: 4,
159
+ * workerSettings: { rtcMinPort: 40000, rtcMaxPort: 49999 },
160
+ * });
161
+ *
162
+ * @example | Pre-constructed instance (e.g. shared singleton in tests)
163
+ * const fake = new MemorySfuAdapter();
164
+ * const sfu = loadSfuAdapter(fake);
165
+ * expect(sfu).toBe(fake);
166
+ *
167
+ * @example | Third-party adapter package
168
+ * // npm i @acme/zero-server-sfu-janus
169
+ * const sfu = loadSfuAdapter('@acme/zero-server-sfu-janus', { wsUrl: 'ws://janus/ws' });
170
+ */
171
+ function loadSfuAdapter(spec, opts)
172
+ {
173
+ if (spec && typeof spec === 'object' && typeof spec.createRouter === 'function')
174
+ {
175
+ return spec;
176
+ }
177
+ if (typeof spec !== 'string' || spec.length === 0)
178
+ {
179
+ throw new WebRTCError(
180
+ 'loadSfuAdapter() requires an adapter instance or a name (memory|mediasoup|livekit|<package>)',
181
+ { code: 'WEBRTC_SFU_INVALID_SPEC' },
182
+ );
183
+ }
184
+
185
+ if (spec === 'memory')
186
+ {
187
+ const { MemorySfuAdapter } = require('./memory');
188
+ return new MemorySfuAdapter(opts);
189
+ }
190
+ if (spec === 'mediasoup')
191
+ {
192
+ const Ctor = _tryRequireAdapter('./mediasoup', 'mediasoup');
193
+ return new Ctor(opts);
194
+ }
195
+ if (spec === 'livekit')
196
+ {
197
+ const Ctor = _tryRequireAdapter('./livekit', 'livekit-server-sdk');
198
+ return new Ctor(opts);
199
+ }
200
+
201
+ // External adapter package - must export `default` or a class.
202
+ let mod;
203
+ try { mod = require(spec); }
204
+ catch (err)
205
+ {
206
+ throw new WebRTCError(
207
+ `SFU adapter package '${spec}' is not installed: ${err.message}`,
208
+ { code: 'WEBRTC_SFU_NOT_INSTALLED', cause: err },
209
+ );
210
+ }
211
+ const Ctor = mod && (mod.default || mod);
212
+ if (typeof Ctor !== 'function')
213
+ {
214
+ throw new WebRTCError(
215
+ `SFU adapter package '${spec}' does not export a class or default constructor`,
216
+ { code: 'WEBRTC_SFU_INVALID_PACKAGE' },
217
+ );
218
+ }
219
+ return new Ctor(opts);
220
+ }
221
+
222
+ /**
223
+ * @private
224
+ * Try to load a built-in adapter module; surface a clean install message
225
+ * when the wrapped peerDependency is missing.
226
+ */
227
+ function _tryRequireAdapter(localPath, peerPkg)
228
+ {
229
+ let mod;
230
+ try { mod = require(localPath); }
231
+ catch (err)
232
+ {
233
+ throw new WebRTCError(
234
+ `SFU adapter '${peerPkg}' requires the '${peerPkg}' peerDependency: npm install ${peerPkg}`,
235
+ { code: 'WEBRTC_SFU_NOT_INSTALLED', cause: err },
236
+ );
237
+ }
238
+ // The wrapper itself tries `require(peerPkg)`; rethrow with the install
239
+ // hint if construction fails for that reason.
240
+ const Ctor = mod && (mod.default || Object.values(mod).find((v) => typeof v === 'function'));
241
+ if (typeof Ctor !== 'function')
242
+ {
243
+ throw new WebRTCError(
244
+ `SFU adapter module '${localPath}' did not export a constructor`,
245
+ { code: 'WEBRTC_SFU_INVALID_ADAPTER' },
246
+ );
247
+ }
248
+ return Ctor;
249
+ }
250
+
251
+ module.exports = { SfuAdapter, loadSfuAdapter };
@@ -0,0 +1,304 @@
1
+ /**
2
+ * @module webrtc/sfu/livekit
3
+ * @description LiveKit-backed SFU adapter (peerDependency on
4
+ * `livekit-server-sdk`). Maps the `SfuAdapter` contract onto LiveKit's
5
+ * remote media plane: `createTransport` mints an AccessToken, mute/close
6
+ * delegate to `RoomServiceClient`, and produce/consume are local
7
+ * bookkeeping while LiveKit handles media client-side.
8
+ *
9
+ * @example | Cloud LiveKit project
10
+ * // npm install livekit-server-sdk
11
+ * const { LiveKitSfuAdapter } = require('@zero-server/webrtc');
12
+ * const sfu = new LiveKitSfuAdapter({
13
+ * host: 'https://my-project.livekit.cloud',
14
+ * apiKey: process.env.LIVEKIT_API_KEY,
15
+ * apiSecret: process.env.LIVEKIT_API_SECRET,
16
+ * tokenTtl: '30m',
17
+ * });
18
+ *
19
+ * @example | Self-hosted LiveKit + handing the JWT to a browser
20
+ * const router = await sfu.createRouter({ room: 'standup' });
21
+ * const transport = await sfu.createTransport(router, {
22
+ * id: peer.id,
23
+ * user: { id: peer.user.id, name: peer.user.name },
24
+ * });
25
+ * peer.send('livekit', { url: transport.url, token: transport.token });
26
+ *
27
+ * @example | Mute a noisy publisher (REST passthrough)
28
+ * await sfu.pauseProducer(producer.id);
29
+ * // adapter records the producerId; if it was registered with a
30
+ * // { room, identity, trackSid } hint it issues
31
+ * // RoomServiceClient.mutePublishedTrack() against LiveKit.
32
+ */
33
+ 'use strict';
34
+
35
+ const { SfuAdapter } = require('./index');
36
+ const { WebRTCError } = require('../../errors');
37
+
38
+ const DEFAULT_TOKEN_TTL = '1h';
39
+
40
+ class LiveKitSfuAdapter extends SfuAdapter
41
+ {
42
+ /**
43
+ * @param {object} opts
44
+ * @param {string} opts.url LiveKit server URL (wss://...).
45
+ * @param {string} opts.apiKey LiveKit API key.
46
+ * @param {string} opts.apiSecret LiveKit API secret.
47
+ * @param {object} [opts.livekit] Injected `livekit-server-sdk` module (testing).
48
+ * @param {object} [opts.client] Pre-built `RoomServiceClient` (testing).
49
+ * @param {object} [opts.defaultRoomOpts] Forwarded to `createRoom()` when fields are missing.
50
+ * @param {object} [opts.defaultGrants] Default `{canPublish, canSubscribe, ...}` for minted tokens.
51
+ * @param {string} [opts.tokenTtl='1h'] AccessToken TTL.
52
+ */
53
+ constructor(opts)
54
+ {
55
+ super();
56
+ const o = opts || {};
57
+ if (!o.url || !o.apiKey || !o.apiSecret)
58
+ {
59
+ throw new WebRTCError(
60
+ 'LiveKitSfuAdapter requires { url, apiKey, apiSecret }',
61
+ { code: 'WEBRTC_SFU_INVALID_CONFIG' },
62
+ );
63
+ }
64
+ this._livekit = o.livekit || _tryRequireLivekit();
65
+ this._url = o.url;
66
+ this._apiKey = o.apiKey;
67
+ this._apiSecret = o.apiSecret;
68
+ this._defaultRoomOpts = o.defaultRoomOpts || {};
69
+ this._defaultGrants = o.defaultGrants || { canPublish: true, canSubscribe: true };
70
+ this._tokenTtl = o.tokenTtl || DEFAULT_TOKEN_TTL;
71
+
72
+ this._client = o.client || new this._livekit.RoomServiceClient(this._url, this._apiKey, this._apiSecret);
73
+
74
+ this._rooms = new Map(); // routerId -> { name, opts }
75
+ this._transports = new Map(); // transportId -> { identity, room, token }
76
+ this._producers = new Map(); // producerId -> { kind, transportId, room, identity, trackSid? }
77
+ this._consumers = new Map(); // consumerId -> { producerId, transportId }
78
+
79
+ this._idSeq = 0;
80
+ }
81
+
82
+ _nextId(prefix)
83
+ {
84
+ this._idSeq += 1;
85
+ return `${prefix}-${this._idSeq}`;
86
+ }
87
+
88
+ /**
89
+ * Create a LiveKit room. `opts.name` overrides the auto-generated name.
90
+ * Returns a router handle whose `id` is the room name.
91
+ */
92
+ async createRouter(opts)
93
+ {
94
+ const o = { ...this._defaultRoomOpts, ...(opts || {}) };
95
+ const name = o.name || this._nextId('room');
96
+ const room = await this._client.createRoom({ ...o, name });
97
+ const id = room && room.name ? room.name : name;
98
+ this._rooms.set(id, { name: id, opts: o, native: room });
99
+ this._emit('router-new', { routerId: id });
100
+ return { id, routerId: id, name: id, _native: room };
101
+ }
102
+
103
+ /**
104
+ * Mint an AccessToken for `peer` to join the LiveKit room. Returns
105
+ * a transport handle containing the JWT and URL the peer hands to
106
+ * the LiveKit client SDK.
107
+ */
108
+ async createTransport(router, peer)
109
+ {
110
+ const routerId = router && router.id;
111
+ const room = routerId && this._rooms.get(routerId);
112
+ if (!room)
113
+ {
114
+ throw new WebRTCError('createTransport: unknown router', { code: 'WEBRTC_SFU_NO_ROUTER' });
115
+ }
116
+ const identity = (peer && peer.id) || this._nextId('peer');
117
+ const at = new this._livekit.AccessToken(this._apiKey, this._apiSecret, {
118
+ identity,
119
+ ttl: this._tokenTtl,
120
+ name: (peer && peer.name) || identity,
121
+ });
122
+ at.addGrant({ roomJoin: true, room: routerId, ...this._defaultGrants });
123
+ const token = await at.toJwt();
124
+ const id = this._nextId('transport');
125
+ const handle = {
126
+ id,
127
+ transportId: id,
128
+ routerId,
129
+ peer: peer || null,
130
+ identity,
131
+ url: this._url,
132
+ token,
133
+ };
134
+ this._transports.set(id, handle);
135
+ this._emit('transport-new', { transportId: id, routerId, peerId: identity });
136
+ return handle;
137
+ }
138
+
139
+ async produce(transport, kind, rtpParameters)
140
+ {
141
+ if (kind !== 'audio' && kind !== 'video')
142
+ {
143
+ throw new WebRTCError('produce: kind must be "audio" or "video"', { code: 'WEBRTC_SFU_INVALID_KIND' });
144
+ }
145
+ const t = transport && this._transports.get(transport.id);
146
+ if (!t)
147
+ {
148
+ throw new WebRTCError('produce: unknown transport', { code: 'WEBRTC_SFU_NO_TRANSPORT' });
149
+ }
150
+ const id = this._nextId('producer');
151
+ const trackSid = (rtpParameters && rtpParameters.trackSid) || null;
152
+ const p = {
153
+ id, producerId: id, transportId: t.id, kind,
154
+ room: t.routerId, identity: t.identity, trackSid,
155
+ rtpParameters: rtpParameters || {}, paused: false,
156
+ };
157
+ this._producers.set(id, p);
158
+ this._emit('producer-new', { producerId: id, transportId: t.id, kind });
159
+ return p;
160
+ }
161
+
162
+ async consume(transport, producerId, rtpCapabilities)
163
+ {
164
+ const t = transport && this._transports.get(transport.id);
165
+ if (!t)
166
+ {
167
+ throw new WebRTCError('consume: unknown transport', { code: 'WEBRTC_SFU_NO_TRANSPORT' });
168
+ }
169
+ const prod = this._producers.get(producerId);
170
+ if (!prod)
171
+ {
172
+ throw new WebRTCError('consume: unknown producer', { code: 'WEBRTC_SFU_NO_PRODUCER' });
173
+ }
174
+ const id = this._nextId('consumer');
175
+ const c = {
176
+ id, consumerId: id, transportId: t.id, producerId,
177
+ kind: prod.kind, rtpParameters: prod.rtpParameters,
178
+ rtpCapabilities: rtpCapabilities || {},
179
+ };
180
+ this._consumers.set(id, c);
181
+ this._emit('consumer-new', { consumerId: id, transportId: t.id, producerId });
182
+ return c;
183
+ }
184
+
185
+ async pauseProducer(producerId)
186
+ {
187
+ const p = this._producers.get(producerId);
188
+ if (!p)
189
+ {
190
+ throw new WebRTCError('pauseProducer: unknown producer', { code: 'WEBRTC_SFU_NO_PRODUCER' });
191
+ }
192
+ if (p.trackSid && typeof this._client.mutePublishedTrack === 'function')
193
+ {
194
+ await this._client.mutePublishedTrack(p.room, p.identity, p.trackSid, true);
195
+ }
196
+ p.paused = true;
197
+ this._emit('producer-pause', { producerId });
198
+ }
199
+
200
+ async resumeProducer(producerId)
201
+ {
202
+ const p = this._producers.get(producerId);
203
+ if (!p)
204
+ {
205
+ throw new WebRTCError('resumeProducer: unknown producer', { code: 'WEBRTC_SFU_NO_PRODUCER' });
206
+ }
207
+ if (p.trackSid && typeof this._client.mutePublishedTrack === 'function')
208
+ {
209
+ await this._client.mutePublishedTrack(p.room, p.identity, p.trackSid, false);
210
+ }
211
+ p.paused = false;
212
+ this._emit('producer-resume', { producerId });
213
+ }
214
+
215
+ async closeRouter(routerId)
216
+ {
217
+ const room = this._rooms.get(routerId);
218
+ if (!room) return;
219
+ try { await this._client.deleteRoom(routerId); }
220
+ catch (err)
221
+ {
222
+ this._emit('router-close-error', { routerId, error: err && err.message });
223
+ }
224
+ // Drop every producer / consumer / transport that belonged to this room.
225
+ for (const [pid, p] of this._producers)
226
+ {
227
+ if (p.room === routerId)
228
+ {
229
+ this._producers.delete(pid);
230
+ this._emit('producer-close', { producerId: pid, reason: 'router-close' });
231
+ }
232
+ }
233
+ for (const [cid, c] of this._consumers)
234
+ {
235
+ const t = this._transports.get(c.transportId);
236
+ if (t && t.routerId === routerId)
237
+ {
238
+ this._consumers.delete(cid);
239
+ this._emit('consumer-close', { consumerId: cid, reason: 'router-close' });
240
+ }
241
+ }
242
+ for (const [tid, t] of this._transports)
243
+ {
244
+ if (t.routerId === routerId)
245
+ {
246
+ this._transports.delete(tid);
247
+ this._emit('transport-close', { transportId: tid, reason: 'router-close' });
248
+ }
249
+ }
250
+ this._rooms.delete(routerId);
251
+ this._emit('router-close', { routerId });
252
+ }
253
+
254
+ async stats(scope)
255
+ {
256
+ if (scope && this._rooms.has(scope))
257
+ {
258
+ let participants = null;
259
+ if (typeof this._client.listParticipants === 'function')
260
+ {
261
+ try { participants = await this._client.listParticipants(scope); }
262
+ catch (_) { participants = null; }
263
+ }
264
+ return { kind: 'router', routerId: scope, participants };
265
+ }
266
+ if (scope && this._transports.has(scope))
267
+ {
268
+ const t = this._transports.get(scope);
269
+ return { kind: 'transport', transportId: scope, routerId: t.routerId, identity: t.identity };
270
+ }
271
+ let rooms = null;
272
+ if (typeof this._client.listRooms === 'function')
273
+ {
274
+ try { rooms = await this._client.listRooms(); }
275
+ catch (_) { rooms = null; }
276
+ }
277
+ return {
278
+ kind: 'global',
279
+ routers: this._rooms.size,
280
+ transports: this._transports.size,
281
+ producers: this._producers.size,
282
+ consumers: this._consumers.size,
283
+ rooms,
284
+ };
285
+ }
286
+ }
287
+
288
+ /**
289
+ * @private
290
+ * Try to `require('livekit-server-sdk')`; throw a clean install hint when missing.
291
+ */
292
+ function _tryRequireLivekit()
293
+ {
294
+ try { return require('livekit-server-sdk'); }
295
+ catch (err)
296
+ {
297
+ throw new WebRTCError(
298
+ "SFU adapter 'livekit' requires the 'livekit-server-sdk' peerDependency: npm install livekit-server-sdk",
299
+ { code: 'WEBRTC_SFU_NOT_INSTALLED', cause: err },
300
+ );
301
+ }
302
+ }
303
+
304
+ module.exports = { LiveKitSfuAdapter };