@coze/realtime-api 1.1.1-beta.2 → 1.1.1-beta.4

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.
@@ -0,0 +1,831 @@
1
+ import * as __WEBPACK_EXTERNAL_MODULE__coze_api__ from "@coze/api";
2
+ import * as __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__ from "@volcengine/rtc";
3
+ import * as __WEBPACK_EXTERNAL_MODULE__volcengine_rtc_extension_ainr__ from "@volcengine/rtc/extension-ainr";
4
+ // The require scope
5
+ var __webpack_require__ = {};
6
+ /************************************************************************/ // webpack/runtime/define_property_getters
7
+ (()=>{
8
+ __webpack_require__.d = function(exports, definition) {
9
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
10
+ enumerable: true,
11
+ get: definition[key]
12
+ });
13
+ };
14
+ })();
15
+ // webpack/runtime/has_own_property
16
+ (()=>{
17
+ __webpack_require__.o = function(obj, prop) {
18
+ return Object.prototype.hasOwnProperty.call(obj, prop);
19
+ };
20
+ })();
21
+ // webpack/runtime/make_namespace_object
22
+ (()=>{
23
+ // define __esModule on exports
24
+ __webpack_require__.r = function(exports) {
25
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports, Symbol.toStringTag, {
26
+ value: 'Module'
27
+ });
28
+ Object.defineProperty(exports, '__esModule', {
29
+ value: true
30
+ });
31
+ };
32
+ })();
33
+ /************************************************************************/ // NAMESPACE OBJECT: ./src/utils.ts
34
+ var utils_namespaceObject = {};
35
+ __webpack_require__.r(utils_namespaceObject);
36
+ __webpack_require__.d(utils_namespaceObject, {
37
+ checkDevicePermission: ()=>checkDevicePermission,
38
+ checkPermission: ()=>checkPermission,
39
+ getAudioDevices: ()=>getAudioDevices,
40
+ isScreenShareDevice: ()=>isScreenShareDevice,
41
+ isScreenShareSupported: ()=>isScreenShareSupported,
42
+ sleep: ()=>sleep
43
+ });
44
+ /**
45
+ + * Delays execution for the specified duration
46
+ + * @param milliseconds The time to sleep in milliseconds
47
+ + * @throws {Error} If milliseconds is negative
48
+ + * @returns Promise that resolves after the specified duration
49
+ + */ const sleep = (milliseconds)=>{
50
+ if (milliseconds < 0) throw new Error('Sleep duration must be non-negative');
51
+ return new Promise((resolve)=>setTimeout(resolve, milliseconds));
52
+ };
53
+ /**
54
+ * @deprecated use checkDevicePermission instead
55
+ * Check microphone permission,return boolean
56
+ */ const checkPermission = async function() {
57
+ let { audio = true, video = false } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
58
+ try {
59
+ const result = await __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].enableDevices({
60
+ audio,
61
+ video
62
+ });
63
+ return result.audio;
64
+ } catch (error) {
65
+ console.error('Failed to check device permissions:', error);
66
+ return false;
67
+ }
68
+ };
69
+ /**
70
+ * Checks device permissions for audio and video
71
+ * @param checkVideo Whether to check video permissions (default: false)
72
+ * @returns Promise that resolves with the device permission status
73
+ */ const checkDevicePermission = async function() {
74
+ let checkVideo = arguments.length > 0 && void 0 !== arguments[0] && arguments[0];
75
+ return await __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].enableDevices({
76
+ audio: true,
77
+ video: checkVideo
78
+ });
79
+ };
80
+ /**
81
+ * Get audio devices
82
+ * @returns Promise<AudioDevices> Object containing arrays of audio input and output devices
83
+ */ const getAudioDevices = async function() {
84
+ let { video = false } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
85
+ let devices = [];
86
+ if (video) {
87
+ devices = await __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].enumerateDevices();
88
+ if (isScreenShareSupported()) // @ts-expect-error - add screenShare device to devices
89
+ devices.push({
90
+ deviceId: 'screenShare',
91
+ kind: 'videoinput',
92
+ label: 'Screen Share',
93
+ groupId: 'screenShare'
94
+ });
95
+ } else devices = await [
96
+ ...await __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].enumerateAudioCaptureDevices(),
97
+ ...await __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].enumerateAudioPlaybackDevices()
98
+ ];
99
+ if (!(null == devices ? void 0 : devices.length)) return {
100
+ audioInputs: [],
101
+ audioOutputs: [],
102
+ videoInputs: []
103
+ };
104
+ return {
105
+ audioInputs: devices.filter((i)=>i.deviceId && 'audioinput' === i.kind),
106
+ audioOutputs: devices.filter((i)=>i.deviceId && 'audiooutput' === i.kind),
107
+ videoInputs: devices.filter((i)=>i.deviceId && 'videoinput' === i.kind)
108
+ };
109
+ };
110
+ const isScreenShareDevice = (deviceId)=>'screenShare' === deviceId;
111
+ /**
112
+ * Check if browser supports screen sharing
113
+ * 检查浏览器是否支持屏幕共享
114
+ */ function isScreenShareSupported() {
115
+ var _navigator_mediaDevices, _navigator;
116
+ return !!(null === (_navigator = navigator) || void 0 === _navigator ? void 0 : null === (_navigator_mediaDevices = _navigator.mediaDevices) || void 0 === _navigator_mediaDevices ? void 0 : _navigator_mediaDevices.getDisplayMedia);
117
+ }
118
+ var event_names_EventNames = /*#__PURE__*/ function(EventNames) {
119
+ /**
120
+ * en: All events
121
+ * zh: 所有事件
122
+ */ EventNames["ALL"] = "realtime.event";
123
+ /**
124
+ * en: All client events
125
+ * zh: 所有客户端事件
126
+ */ EventNames["ALL_CLIENT"] = "client.*";
127
+ /**
128
+ * en: All server events
129
+ * zh: 所有服务端事件
130
+ */ EventNames["ALL_SERVER"] = "server.*";
131
+ /**
132
+ * en: Client connected
133
+ * zh: 客户端连接
134
+ */ EventNames["CONNECTED"] = "client.connected";
135
+ /**
136
+ * en: Client connecting
137
+ * zh: 客户端连接中
138
+ */ EventNames["CONNECTING"] = "client.connecting";
139
+ /**
140
+ * en: Client interrupted
141
+ * zh: 客户端中断
142
+ */ EventNames["INTERRUPTED"] = "client.interrupted";
143
+ /**
144
+ * en: Client disconnected
145
+ * zh: 客户端断开
146
+ */ EventNames["DISCONNECTED"] = "client.disconnected";
147
+ /**
148
+ * en: Client audio unmuted
149
+ * zh: 客户端音频未静音
150
+ */ EventNames["AUDIO_UNMUTED"] = "client.audio.unmuted";
151
+ /**
152
+ * en: Client audio muted
153
+ * zh: 客户端音频静音
154
+ */ EventNames["AUDIO_MUTED"] = "client.audio.muted";
155
+ /**
156
+ * en: Client video on
157
+ * zh: 客户端视频开启
158
+ */ EventNames["VIDEO_ON"] = "client.video.on";
159
+ /**
160
+ * en: Client video off
161
+ * zh: 客户端视频关闭
162
+ */ EventNames["VIDEO_OFF"] = "client.video.off";
163
+ /**
164
+ * en: Client video event
165
+ * zh: 客户端视频事件
166
+ */ EventNames["PLAYER_EVENT"] = "client.video.event";
167
+ /**
168
+ * en: Client error
169
+ * zh: 客户端错误
170
+ */ EventNames["ERROR"] = "client.error";
171
+ /**
172
+ * en: Audio noise reduction enabled
173
+ * zh: 抑制平稳噪声
174
+ */ EventNames["SUPPRESS_STATIONARY_NOISE"] = "client.suppress.stationary.noise";
175
+ /**
176
+ * en: Suppress non-stationary noise
177
+ * zh: 抑制非平稳噪声
178
+ */ EventNames["SUPPRESS_NON_STATIONARY_NOISE"] = "client.suppress.non.stationary.noise";
179
+ /**
180
+ * en: Audio input device changed
181
+ * zh: 音频输入设备改变
182
+ */ EventNames["AUDIO_INPUT_DEVICE_CHANGED"] = "client.input.device.changed";
183
+ /**
184
+ * en: Audio output device changed
185
+ * zh: 音频输出设备改变
186
+ */ EventNames["AUDIO_OUTPUT_DEVICE_CHANGED"] = "client.output.device.changed";
187
+ /**
188
+ * en: Video input device changed
189
+ * zh: 视频输入设备改变
190
+ */ EventNames["VIDEO_INPUT_DEVICE_CHANGED"] = "client.video.input.device.changed";
191
+ /**
192
+ * en: Network quality changed
193
+ * zh: 网络质量改变
194
+ */ EventNames["NETWORK_QUALITY"] = "client.network.quality";
195
+ /**
196
+ * en: Bot joined
197
+ * zh: Bot 加入
198
+ */ EventNames["BOT_JOIN"] = "server.bot.join";
199
+ /**
200
+ * en: Bot left
201
+ * zh: Bot 离开
202
+ */ EventNames["BOT_LEAVE"] = "server.bot.leave";
203
+ /**
204
+ * en: Audio speech started
205
+ * zh: 开始说话
206
+ */ EventNames["AUDIO_AGENT_SPEECH_STARTED"] = "server.audio.agent.speech_started";
207
+ /**
208
+ * en: Audio speech stopped
209
+ * zh: 停止说话
210
+ */ EventNames["AUDIO_AGENT_SPEECH_STOPPED"] = "server.audio.agent.speech_stopped";
211
+ /**
212
+ * en: Server error
213
+ * zh: 服务端错误
214
+ */ EventNames["SERVER_ERROR"] = "server.error";
215
+ /**
216
+ * en: User speech started
217
+ * zh: 用户开始说话
218
+ */ EventNames["AUDIO_USER_SPEECH_STARTED"] = "server.audio.user.speech_started";
219
+ /**
220
+ * en: User speech stopped
221
+ * zh: 用户停止说话
222
+ */ EventNames["AUDIO_USER_SPEECH_STOPPED"] = "server.audio.user.speech_stopped";
223
+ /**
224
+ * en: User successfully enters the room
225
+ * zh: 用户成功进入房间后,会收到该事件
226
+ */ EventNames["SESSION_CREATED"] = "server.session.created";
227
+ /**
228
+ * en: Session updated
229
+ * zh: 会话更新
230
+ */ EventNames["SESSION_UPDATE"] = "server.session.update";
231
+ return EventNames;
232
+ }(event_names_EventNames || {});
233
+ /* ESM default export */ const event_names = event_names_EventNames;
234
+ var error_RealtimeError = /*#__PURE__*/ function(RealtimeError) {
235
+ RealtimeError["DEVICE_ACCESS_ERROR"] = "DEVICE_ACCESS_ERROR";
236
+ RealtimeError["STREAM_CREATION_ERROR"] = "STREAM_CREATION_ERROR";
237
+ RealtimeError["CONNECTION_ERROR"] = "CONNECTION_ERROR";
238
+ RealtimeError["DISCONNECTION_ERROR"] = "DISCONNECTION_ERROR";
239
+ RealtimeError["INTERRUPT_ERROR"] = "INTERRUPT_ERROR";
240
+ RealtimeError["EVENT_HANDLER_ERROR"] = "EVENT_HANDLER_ERROR";
241
+ RealtimeError["PERMISSION_DENIED"] = "PERMISSION_DENIED";
242
+ RealtimeError["NETWORK_ERROR"] = "NETWORK_ERROR";
243
+ RealtimeError["INVALID_STATE"] = "INVALID_STATE";
244
+ RealtimeError["CREATE_ROOM_ERROR"] = "CREATE_ROOM_ERROR";
245
+ RealtimeError["PARSE_MESSAGE_ERROR"] = "PARSE_MESSAGE_ERROR";
246
+ RealtimeError["HANDLER_MESSAGE_ERROR"] = "HANDLER_MESSAGE_ERROR";
247
+ return RealtimeError;
248
+ }({});
249
+ class RealtimeAPIError extends Error {
250
+ /**
251
+ * @param code - Error code
252
+ * @param message - Error message
253
+ * @param error - Error object
254
+ */ constructor(code, message, error){
255
+ super(`[${code}] ${message}`);
256
+ this.name = 'RealtimeAPIError';
257
+ this.code = code;
258
+ this.error = error;
259
+ }
260
+ }
261
+ class RealtimeEventHandler {
262
+ clearEventHandlers() {
263
+ this.eventHandlers = {};
264
+ }
265
+ on(eventName, callback) {
266
+ this._log(`on ${eventName} event`);
267
+ this.eventHandlers[eventName] = this.eventHandlers[eventName] || [];
268
+ this.eventHandlers[eventName].push(callback);
269
+ return callback;
270
+ }
271
+ off(eventName, callback) {
272
+ this._log(`off ${eventName} event`);
273
+ const handlers = this.eventHandlers[eventName] || [];
274
+ if (callback) {
275
+ const index = handlers.indexOf(callback);
276
+ if (-1 === index) {
277
+ console.warn(`Could not turn off specified event listener for "${eventName}": not found as a listener`);
278
+ return;
279
+ }
280
+ handlers.splice(index, 1);
281
+ } else delete this.eventHandlers[eventName];
282
+ }
283
+ // eslint-disable-next-line max-params
284
+ _dispatchToHandlers(eventName, event, handlers, prefix) {
285
+ for (const handler of handlers)if (!prefix || eventName.startsWith(prefix)) try {
286
+ handler(eventName, event);
287
+ } catch (e) {
288
+ throw new RealtimeAPIError(error_RealtimeError.HANDLER_MESSAGE_ERROR, `Failed to handle message: ${eventName}`);
289
+ }
290
+ }
291
+ dispatch(eventName, event) {
292
+ let consoleLog = !(arguments.length > 2) || void 0 === arguments[2] || arguments[2];
293
+ if (consoleLog) this._log(`dispatch ${eventName} event`, event);
294
+ const handlers = (this.eventHandlers[eventName] || []).slice();
295
+ this._dispatchToHandlers(eventName, event, handlers);
296
+ const allHandlers = (this.eventHandlers[event_names.ALL] || []).slice();
297
+ this._dispatchToHandlers(eventName, event, allHandlers);
298
+ const allClientHandlers = (this.eventHandlers[event_names.ALL_CLIENT] || []).slice();
299
+ this._dispatchToHandlers(eventName, event, allClientHandlers, 'client.');
300
+ const allServerHandlers = (this.eventHandlers[event_names.ALL_SERVER] || []).slice();
301
+ this._dispatchToHandlers(eventName, event, allServerHandlers, 'server.');
302
+ }
303
+ _log(message, event) {
304
+ if (this._debug) console.log(`[RealtimeClient] ${message}`, event);
305
+ }
306
+ constructor(debug = false){
307
+ this.eventHandlers = {};
308
+ this._debug = debug;
309
+ }
310
+ }
311
+ class EngineClient extends RealtimeEventHandler {
312
+ bindEngineEvents() {
313
+ this.engine.on(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onUserMessageReceived, this.handleMessage);
314
+ this.engine.on(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onUserJoined, this.handleUserJoin);
315
+ this.engine.on(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onUserLeave, this.handleUserLeave);
316
+ this.engine.on(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onError, this.handleEventError);
317
+ this.engine.on(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onNetworkQuality, this.handleNetworkQuality);
318
+ if (this._isSupportVideo) this.engine.on(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onPlayerEvent, this.handlePlayerEvent);
319
+ if (this._debug) {
320
+ this.engine.on(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onLocalAudioPropertiesReport, this.handleLocalAudioPropertiesReport);
321
+ this.engine.on(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onRemoteAudioPropertiesReport, this.handleRemoteAudioPropertiesReport);
322
+ }
323
+ }
324
+ removeEventListener() {
325
+ this.engine.off(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onUserMessageReceived, this.handleMessage);
326
+ this.engine.off(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onUserJoined, this.handleUserJoin);
327
+ this.engine.off(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onUserLeave, this.handleUserLeave);
328
+ this.engine.off(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onError, this.handleEventError);
329
+ this.engine.off(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onNetworkQuality, this.handleNetworkQuality);
330
+ if (this._isSupportVideo) this.engine.off(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onPlayerEvent, this.handlePlayerEvent);
331
+ if (this._debug) {
332
+ this.engine.off(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onLocalAudioPropertiesReport, this.handleLocalAudioPropertiesReport);
333
+ this.engine.off(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].events.onRemoteAudioPropertiesReport, this.handleRemoteAudioPropertiesReport);
334
+ }
335
+ }
336
+ _parseMessage(event) {
337
+ try {
338
+ return JSON.parse(event.message);
339
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
340
+ } catch (e) {
341
+ throw new RealtimeAPIError(error_RealtimeError.PARSE_MESSAGE_ERROR, (null == e ? void 0 : e.message) || 'Unknown error');
342
+ }
343
+ }
344
+ handleMessage(event) {
345
+ try {
346
+ const message = this._parseMessage(event);
347
+ this.dispatch(`server.${message.event_type}`, message);
348
+ } catch (e) {
349
+ if (e instanceof RealtimeAPIError) {
350
+ if (e.code === error_RealtimeError.PARSE_MESSAGE_ERROR) this.dispatch(event_names.ERROR, {
351
+ message: `Failed to parse message: ${event.message}`,
352
+ error: e
353
+ });
354
+ else if (e.code === error_RealtimeError.HANDLER_MESSAGE_ERROR) this.dispatch(event_names.ERROR, {
355
+ message: `Failed to handle message: ${event.message}`,
356
+ error: e
357
+ });
358
+ } else this.dispatch(event_names.ERROR, e);
359
+ }
360
+ }
361
+ handleEventError(e) {
362
+ this.dispatch(event_names.ERROR, e);
363
+ }
364
+ handleUserJoin(event) {
365
+ this.joinUserId = event.userInfo.userId;
366
+ this.dispatch(event_names.BOT_JOIN, event);
367
+ }
368
+ handleUserLeave(event) {
369
+ this.dispatch(event_names.BOT_LEAVE, event);
370
+ }
371
+ handlePlayerEvent(event) {
372
+ this.dispatch(event_names.PLAYER_EVENT, event);
373
+ }
374
+ handleNetworkQuality(uplinkNetworkQuality, downlinkNetworkQuality) {
375
+ this.dispatch(event_names.NETWORK_QUALITY, {
376
+ uplinkNetworkQuality,
377
+ downlinkNetworkQuality
378
+ });
379
+ }
380
+ async joinRoom(options) {
381
+ const { token, roomId, uid, audioMutedDefault, videoOnDefault, isAutoSubscribeAudio } = options;
382
+ try {
383
+ await this.engine.joinRoom(token, roomId, {
384
+ userId: uid
385
+ }, {
386
+ isAutoPublish: !audioMutedDefault,
387
+ isAutoSubscribeAudio,
388
+ isAutoSubscribeVideo: this._isSupportVideo && videoOnDefault
389
+ });
390
+ } catch (e) {
391
+ if (e instanceof Error) throw new RealtimeAPIError(error_RealtimeError.CONNECTION_ERROR, e.message);
392
+ }
393
+ }
394
+ async setAudioInputDevice(deviceId) {
395
+ const devices = await getAudioDevices();
396
+ if (-1 === devices.audioInputs.findIndex((i)=>i.deviceId === deviceId)) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, `Audio input device not found: ${deviceId}`);
397
+ this.engine.stopAudioCapture();
398
+ await this.engine.startAudioCapture(deviceId);
399
+ }
400
+ async setAudioOutputDevice(deviceId) {
401
+ const devices = await getAudioDevices({
402
+ video: false
403
+ });
404
+ if (-1 === devices.audioOutputs.findIndex((i)=>i.deviceId === deviceId)) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, `Audio output device not found: ${deviceId}`);
405
+ await this.engine.setAudioPlaybackDevice(deviceId);
406
+ }
407
+ async setVideoInputDevice(deviceId) {
408
+ let isAutoCapture = !(arguments.length > 1) || void 0 === arguments[1] || arguments[1];
409
+ var _this__videoConfig;
410
+ const devices = await getAudioDevices({
411
+ video: true
412
+ });
413
+ if (-1 === devices.videoInputs.findIndex((i)=>i.deviceId === deviceId)) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, `Video input device not found: ${deviceId}`);
414
+ await this.changeVideoState(false);
415
+ if (isScreenShareDevice(deviceId)) {
416
+ if (this._streamIndex === __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.StreamIndex.STREAM_INDEX_MAIN) this.engine.setLocalVideoPlayer(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.StreamIndex.STREAM_INDEX_MAIN);
417
+ if (isAutoCapture) {
418
+ var _this__videoConfig1;
419
+ this.engine.setVideoSourceType(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.StreamIndex.STREAM_INDEX_SCREEN, __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL);
420
+ await this.engine.startScreenCapture(null === (_this__videoConfig1 = this._videoConfig) || void 0 === _this__videoConfig1 ? void 0 : _this__videoConfig1.screenConfig);
421
+ await this.engine.publishScreen(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.MediaType.VIDEO);
422
+ }
423
+ this._streamIndex = __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.StreamIndex.STREAM_INDEX_SCREEN;
424
+ } else {
425
+ if (this._streamIndex === __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.StreamIndex.STREAM_INDEX_SCREEN) this.engine.setLocalVideoPlayer(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.StreamIndex.STREAM_INDEX_SCREEN);
426
+ if (isAutoCapture) await this.engine.startVideoCapture(deviceId);
427
+ this._streamIndex = __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.StreamIndex.STREAM_INDEX_MAIN;
428
+ }
429
+ this.engine.setLocalVideoPlayer(this._streamIndex, {
430
+ renderDom: (null === (_this__videoConfig = this._videoConfig) || void 0 === _this__videoConfig ? void 0 : _this__videoConfig.renderDom) || 'local-player',
431
+ userId: this._roomUserId
432
+ });
433
+ }
434
+ async createLocalStream(userId, videoConfig) {
435
+ this._roomUserId = userId;
436
+ const devices = await getAudioDevices({
437
+ video: this._isSupportVideo
438
+ });
439
+ if (!devices.audioInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get audio devices');
440
+ if (this._isSupportVideo && !devices.videoInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get video devices');
441
+ await this.engine.startAudioCapture(devices.audioInputs[0].deviceId);
442
+ if (this._isSupportVideo) this.setVideoInputDevice((null == videoConfig ? void 0 : videoConfig.videoInputDeviceId) || devices.videoInputs[0].deviceId, null == videoConfig ? void 0 : videoConfig.videoOnDefault);
443
+ }
444
+ async disconnect() {
445
+ try {
446
+ await this.engine.leaveRoom();
447
+ this.removeEventListener();
448
+ this.clearEventHandlers();
449
+ __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].destroyEngine(this.engine);
450
+ } catch (e) {
451
+ this.dispatch(event_names.ERROR, e);
452
+ throw e;
453
+ }
454
+ }
455
+ async changeAudioState(isMicOn) {
456
+ try {
457
+ if (isMicOn) await this.engine.publishStream(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.MediaType.AUDIO);
458
+ else await this.engine.unpublishStream(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.MediaType.AUDIO);
459
+ } catch (e) {
460
+ this.dispatch(event_names.ERROR, e);
461
+ throw e;
462
+ }
463
+ }
464
+ async changeVideoState(isVideoOn) {
465
+ try {
466
+ if (isVideoOn) {
467
+ if (this._streamIndex === __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.StreamIndex.STREAM_INDEX_MAIN) await this.engine.startVideoCapture();
468
+ else {
469
+ var _this__videoConfig;
470
+ this.engine.setVideoSourceType(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.StreamIndex.STREAM_INDEX_SCREEN, __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL);
471
+ await this.engine.startScreenCapture(null === (_this__videoConfig = this._videoConfig) || void 0 === _this__videoConfig ? void 0 : _this__videoConfig.screenConfig);
472
+ await this.engine.publishScreen(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.MediaType.VIDEO);
473
+ }
474
+ } else if (this._streamIndex === __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.StreamIndex.STREAM_INDEX_MAIN) await this.engine.stopVideoCapture();
475
+ else {
476
+ await this.engine.stopScreenCapture();
477
+ await this.engine.unpublishScreen(__WEBPACK_EXTERNAL_MODULE__volcengine_rtc__.MediaType.VIDEO);
478
+ }
479
+ } catch (e) {
480
+ this.dispatch(event_names.ERROR, e);
481
+ throw e;
482
+ }
483
+ }
484
+ async stop() {
485
+ try {
486
+ const result = await this.engine.sendUserMessage(this.joinUserId, JSON.stringify({
487
+ id: 'event_1',
488
+ event_type: 'conversation.chat.cancel',
489
+ data: {}
490
+ }));
491
+ this._log(`interrupt ${this.joinUserId} ${result}`);
492
+ } catch (e) {
493
+ this.dispatch(event_names.ERROR, e);
494
+ throw e;
495
+ }
496
+ }
497
+ async sendMessage(message) {
498
+ try {
499
+ const result = await this.engine.sendUserMessage(this.joinUserId, JSON.stringify(message));
500
+ this._log(`sendMessage ${this.joinUserId} ${JSON.stringify(message)} ${result}`);
501
+ } catch (e) {
502
+ this.dispatch(event_names.ERROR, e);
503
+ throw e;
504
+ }
505
+ }
506
+ enableAudioPropertiesReport(config) {
507
+ this.engine.enableAudioPropertiesReport(config);
508
+ }
509
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
510
+ handleLocalAudioPropertiesReport(event) {
511
+ var _event__audioPropertiesInfo, _event_;
512
+ if (this._debug && (null === (_event_ = event[0]) || void 0 === _event_ ? void 0 : null === (_event__audioPropertiesInfo = _event_.audioPropertiesInfo) || void 0 === _event__audioPropertiesInfo ? void 0 : _event__audioPropertiesInfo.linearVolume) > 0) console.log('handleLocalAudioPropertiesReport', event);
513
+ }
514
+ handleRemoteAudioPropertiesReport(event) {
515
+ if (this._debug) console.log('handleRemoteAudioPropertiesReport', event);
516
+ }
517
+ async enableAudioNoiseReduction() {
518
+ var _this_engine;
519
+ await (null === (_this_engine = this.engine) || void 0 === _this_engine ? void 0 : _this_engine.setAudioCaptureConfig({
520
+ noiseSuppression: true,
521
+ echoCancellation: true,
522
+ autoGainControl: true
523
+ }));
524
+ }
525
+ async initAIAnsExtension() {
526
+ const AIAnsExtension = new __WEBPACK_EXTERNAL_MODULE__volcengine_rtc_extension_ainr__["default"]();
527
+ await this.engine.registerExtension(AIAnsExtension);
528
+ this._AIAnsExtension = AIAnsExtension;
529
+ }
530
+ changeAIAnsExtension(enable) {
531
+ if (enable) {
532
+ var _this__AIAnsExtension;
533
+ null === (_this__AIAnsExtension = this._AIAnsExtension) || void 0 === _this__AIAnsExtension || _this__AIAnsExtension.enable();
534
+ } else {
535
+ var _this__AIAnsExtension1;
536
+ null === (_this__AIAnsExtension1 = this._AIAnsExtension) || void 0 === _this__AIAnsExtension1 || _this__AIAnsExtension1.disable();
537
+ }
538
+ }
539
+ async startAudioPlaybackDeviceTest() {
540
+ try {
541
+ await this.engine.startAudioPlaybackDeviceTest('audio-test.wav', 200);
542
+ } catch (e) {
543
+ this.dispatch(event_names.ERROR, e);
544
+ throw e;
545
+ }
546
+ }
547
+ stopAudioPlaybackDeviceTest() {
548
+ try {
549
+ this.engine.stopAudioPlaybackDeviceTest();
550
+ } catch (e) {
551
+ this.dispatch(event_names.ERROR, e);
552
+ throw e;
553
+ }
554
+ }
555
+ getRtcEngine() {
556
+ return this.engine;
557
+ }
558
+ // eslint-disable-next-line max-params
559
+ constructor(appId, debug = false, isTestEnv = false, isSupportVideo = false, videoConfig){
560
+ super(debug), this.joinUserId = '', this._AIAnsExtension = null, this._isSupportVideo = false;
561
+ if (isTestEnv) __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].setParameter('ICE_CONFIG_REQUEST_URLS', [
562
+ 'rtc-test.bytedance.com'
563
+ ]);
564
+ this.engine = __WEBPACK_EXTERNAL_MODULE__volcengine_rtc__["default"].createEngine(appId);
565
+ this.handleMessage = this.handleMessage.bind(this);
566
+ this.handleUserJoin = this.handleUserJoin.bind(this);
567
+ this.handleUserLeave = this.handleUserLeave.bind(this);
568
+ this.handleEventError = this.handleEventError.bind(this);
569
+ this.handlePlayerEvent = this.handlePlayerEvent.bind(this);
570
+ this.handleNetworkQuality = this.handleNetworkQuality.bind(this);
571
+ // Debug only
572
+ this.handleLocalAudioPropertiesReport = this.handleLocalAudioPropertiesReport.bind(this);
573
+ this.handleRemoteAudioPropertiesReport = this.handleRemoteAudioPropertiesReport.bind(this);
574
+ this._isSupportVideo = isSupportVideo;
575
+ this._videoConfig = videoConfig;
576
+ }
577
+ }
578
+ // Only use for test
579
+ const TEST_APP_ID = '6705332c79516e015e3e5f0c';
580
+ class RealtimeClient extends RealtimeEventHandler {
581
+ /**
582
+ * en: Establish a connection to the Coze API and join the room
583
+ *
584
+ * zh: 建立与 Coze API 的连接并加入房间
585
+ */ async connect() {
586
+ var _this__config_videoConfig;
587
+ const { botId, conversationId, voiceId, getRoomInfo } = this._config;
588
+ this.dispatch(event_names.CONNECTING, {});
589
+ let roomInfo;
590
+ try {
591
+ // Step1 get token
592
+ if (getRoomInfo) roomInfo = await getRoomInfo();
593
+ else {
594
+ let config;
595
+ if (this._config.videoConfig) config = isScreenShareDevice(this._config.videoConfig.videoInputDeviceId) ? {
596
+ video_config: {
597
+ stream_video_type: 'screen'
598
+ }
599
+ } : {
600
+ video_config: {
601
+ stream_video_type: 'main'
602
+ }
603
+ };
604
+ roomInfo = await this._api.audio.rooms.create({
605
+ bot_id: botId,
606
+ conversation_id: conversationId || void 0,
607
+ voice_id: voiceId && voiceId.length > 0 ? voiceId : void 0,
608
+ connector_id: this._config.connectorId,
609
+ uid: this._config.userId || void 0,
610
+ workflow_id: this._config.workflowId || void 0,
611
+ config
612
+ });
613
+ }
614
+ } catch (error) {
615
+ this.dispatch(event_names.ERROR, error);
616
+ throw new RealtimeAPIError(error_RealtimeError.CREATE_ROOM_ERROR, error instanceof Error ? error.message : 'Unknown error', error);
617
+ }
618
+ this._isTestEnv = TEST_APP_ID === roomInfo.app_id;
619
+ // Step2 create engine
620
+ this._client = new EngineClient(roomInfo.app_id, this._config.debug, this._isTestEnv, this._isSupportVideo, this._config.videoConfig);
621
+ // Step3 bind engine events
622
+ this._client.bindEngineEvents();
623
+ this._client.on(event_names.ALL, (eventName, data)=>{
624
+ this.dispatch(eventName, data, false);
625
+ });
626
+ if (this._config.suppressStationaryNoise) {
627
+ await this._client.enableAudioNoiseReduction();
628
+ this.dispatch(event_names.SUPPRESS_STATIONARY_NOISE, {});
629
+ }
630
+ if (this._config.suppressNonStationaryNoise) try {
631
+ await this._client.initAIAnsExtension();
632
+ this._client.changeAIAnsExtension(true);
633
+ this.dispatch(event_names.SUPPRESS_NON_STATIONARY_NOISE, {});
634
+ } catch (error) {
635
+ console.warn('Config suppressNonStationaryNoise is not supported', error);
636
+ }
637
+ var _this__config_audioMutedDefault, _this__config_videoConfig_videoOnDefault, _this__config_isAutoSubscribeAudio;
638
+ // Step4 join room
639
+ await this._client.joinRoom({
640
+ token: roomInfo.token,
641
+ roomId: roomInfo.room_id,
642
+ uid: roomInfo.uid,
643
+ audioMutedDefault: null !== (_this__config_audioMutedDefault = this._config.audioMutedDefault) && void 0 !== _this__config_audioMutedDefault && _this__config_audioMutedDefault,
644
+ videoOnDefault: null === (_this__config_videoConfig_videoOnDefault = null === (_this__config_videoConfig = this._config.videoConfig) || void 0 === _this__config_videoConfig ? void 0 : _this__config_videoConfig.videoOnDefault) || void 0 === _this__config_videoConfig_videoOnDefault || _this__config_videoConfig_videoOnDefault,
645
+ isAutoSubscribeAudio: null === (_this__config_isAutoSubscribeAudio = this._config.isAutoSubscribeAudio) || void 0 === _this__config_isAutoSubscribeAudio || _this__config_isAutoSubscribeAudio
646
+ });
647
+ // Step5 create local stream
648
+ await this._client.createLocalStream(roomInfo.uid, this._config.videoConfig);
649
+ // step6 set connected and dispatch connected event
650
+ this.isConnected = true;
651
+ this.dispatch(event_names.CONNECTED, {
652
+ roomId: roomInfo.room_id,
653
+ uid: roomInfo.uid,
654
+ token: roomInfo.token,
655
+ appId: roomInfo.app_id
656
+ });
657
+ }
658
+ /**
659
+ * en: Interrupt the current conversation
660
+ *
661
+ * zh: 中断当前对话
662
+ */ async interrupt() {
663
+ var _this__client;
664
+ await (null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.stop());
665
+ this.dispatch(event_names.INTERRUPTED, {});
666
+ }
667
+ /**
668
+ * en: Disconnect from the current session
669
+ *
670
+ * zh: 断开与当前会话的连接
671
+ */ async disconnect() {
672
+ var _this__client;
673
+ await (null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.disconnect());
674
+ this.isConnected = false;
675
+ this._client = null;
676
+ this.dispatch(event_names.DISCONNECTED, {});
677
+ }
678
+ /**
679
+ * en: Send a message to the bot
680
+ *
681
+ * zh: 发送消息给Bot
682
+ */ async sendMessage(message) {
683
+ var _this__client;
684
+ await (null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.sendMessage(message));
685
+ const eventType = 'string' == typeof message.event_type ? message.event_type : 'unknown_event';
686
+ this.dispatch(`client.${eventType}`, message);
687
+ }
688
+ /**
689
+ * en: Enable or disable audio
690
+ *
691
+ * zh: 启用或禁用音频
692
+ */ async setAudioEnable(isEnable) {
693
+ var _this__client;
694
+ await (null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.changeAudioState(isEnable));
695
+ if (isEnable) this.dispatch(event_names.AUDIO_UNMUTED, {});
696
+ else this.dispatch(event_names.AUDIO_MUTED, {});
697
+ }
698
+ async setVideoEnable(isEnable) {
699
+ var _this__client;
700
+ await (null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.changeVideoState(isEnable));
701
+ if (isEnable) this.dispatch(event_names.VIDEO_ON, {});
702
+ else this.dispatch(event_names.VIDEO_OFF, {});
703
+ }
704
+ /**
705
+ * en: Enable audio properties reporting (debug mode only)
706
+ *
707
+ * zh: 启用音频属性报告(仅限调试模式)
708
+ */ enableAudioPropertiesReport(config) {
709
+ if (this._config.debug) {
710
+ var _this__client;
711
+ null === (_this__client = this._client) || void 0 === _this__client || _this__client.enableAudioPropertiesReport(config);
712
+ return true;
713
+ }
714
+ console.warn('enableAudioPropertiesReport is not supported in non-debug mode');
715
+ return false;
716
+ }
717
+ /**
718
+ * en: Start audio playback device test (debug mode only)
719
+ *
720
+ * zh: 开始音频播放设备测试(仅限调试模式)
721
+ */ async startAudioPlaybackDeviceTest() {
722
+ if (this._config.debug) {
723
+ var _this__client;
724
+ await (null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.startAudioPlaybackDeviceTest());
725
+ } else console.warn('startAudioPlaybackDeviceTest is not supported in non-debug mode');
726
+ }
727
+ /**
728
+ * en: Stop audio playback device test (debug mode only)
729
+ *
730
+ * zh: 停止音频播放设备测试(仅限调试模式)
731
+ */ stopAudioPlaybackDeviceTest() {
732
+ if (this._config.debug) {
733
+ var _this__client;
734
+ null === (_this__client = this._client) || void 0 === _this__client || _this__client.stopAudioPlaybackDeviceTest();
735
+ } else console.warn('stopAudioPlaybackDeviceTest is not supported in non-debug mode');
736
+ }
737
+ /**
738
+ * en: Set the audio input device
739
+ *
740
+ * zh: 设置音频输入设备
741
+ */ async setAudioInputDevice(deviceId) {
742
+ var _this__client;
743
+ await (null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.setAudioInputDevice(deviceId));
744
+ this.dispatch(event_names.AUDIO_INPUT_DEVICE_CHANGED, {
745
+ deviceId
746
+ });
747
+ }
748
+ /**
749
+ * en: Set the audio output device
750
+ *
751
+ * zh: 设置音频输出设备
752
+ */ async setAudioOutputDevice(deviceId) {
753
+ var _this__client;
754
+ await (null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.setAudioOutputDevice(deviceId));
755
+ this.dispatch(event_names.AUDIO_OUTPUT_DEVICE_CHANGED, {
756
+ deviceId
757
+ });
758
+ }
759
+ async setVideoInputDevice(deviceId) {
760
+ var _this__client;
761
+ await (null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.setVideoInputDevice(deviceId));
762
+ this.dispatch(event_names.VIDEO_INPUT_DEVICE_CHANGED, {
763
+ deviceId
764
+ });
765
+ }
766
+ /**
767
+ * en: Get the RTC engine instance, for detail visit https://www.volcengine.com/docs/6348/104481
768
+ *
769
+ * zh: 获取 RTC 引擎实例,详情请访问 https://www.volcengine.com/docs/6348/104481
770
+ */ getRtcEngine() {
771
+ var _this__client;
772
+ return null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.getRtcEngine();
773
+ }
774
+ /**
775
+ * Constructor for initializing a RealtimeClient instance.
776
+ *
777
+ * 构造函数,初始化RealtimeClient实例。
778
+ *
779
+ * @param config
780
+ * @param config.accessToken - Required, Access Token. |
781
+ * 必填,Access Token。
782
+ * @param config.botId - Required, Bot Id. |
783
+ * 必填,Bot Id。
784
+ * @param config.voiceId - Optional, Voice Id. |
785
+ * 可选,音色Id。
786
+ * @param config.conversationId - Optional, Conversation Id. |
787
+ * 可选,会话Id。
788
+ * @param config.userId - Optional, User Id. |
789
+ * 可选,用户Id。
790
+ * @param config.baseURL - Optional, defaults to "https://api.coze.cn". |
791
+ * 可选,默认值为 "https://api.coze.cn"。
792
+ * @param config.debug - Optional, defaults to false.
793
+ * 可选,默认值为 false。
794
+ * @param config.allowPersonalAccessTokenInBrowser
795
+ * - Optional, whether to allow personal access tokens in browser environment. |
796
+ * 可选,是否允许在浏览器环境中使用个人访问令牌。
797
+ * @param config.audioMutedDefault - Optional, whether audio is muted by default, defaults to false. |
798
+ * 可选,默认是否静音,默认值为 false。
799
+ * @param config.connectorId - Required, Connector Id. |
800
+ * 必填,渠道 Id。
801
+ * @param config.suppressStationaryNoise - Optional, suppress stationary noise, defaults to false. |
802
+ * 可选,默认是否抑制静态噪声,默认值为 false。
803
+ * @param config.suppressNonStationaryNoise - Optional, suppress non-stationary noise, defaults to false. |
804
+ * 可选,默认是否抑制非静态噪声,默认值为 false。
805
+ * @param config.isAutoSubscribeAudio - Optional, whether to automatically subscribe to bot reply audio streams, defaults to true. |
806
+ * @param config.videoConfig - Optional, Video configuration. |
807
+ * 可选,视频配置。
808
+ * @param config.videoConfig.videoOnDefault - Optional, Whether to turn on video by default, defaults to true. |
809
+ * 可选,默认是否开启视频,默认值为 true。
810
+ * @param config.videoConfig.renderDom - Optional, The DOM element to render the video stream to. |
811
+ * 可选,渲染视频流的 DOM 元素。
812
+ * @param config.videoConfig.videoInputDeviceId - Optional, The device ID of the video input device to use. |
813
+ * 可选,视频输入设备的设备 ID。
814
+ * @param config.videoConfig.screenConfig - Optional, Screen share configuration if videoInputDeviceId is 'screenShare' see https://www.volcengine.com/docs/6348/104481#screenconfig for more details. |
815
+ * 可选,屏幕共享配置,如果 videoInputDeviceId 是 'screenShare',请参考 https://www.volcengine.com/docs/6348/104481#screenconfig 了解更多详情。
816
+ */ constructor(config){
817
+ super(config.debug), this._client = null, this.isConnected = false, this._isTestEnv = false, this._isSupportVideo = false;
818
+ this._config = config;
819
+ var _this__config_baseURL;
820
+ const defaultBaseURL = null !== (_this__config_baseURL = this._config.baseURL) && void 0 !== _this__config_baseURL ? _this__config_baseURL : 'https://api.coze.cn';
821
+ this._config.baseURL = defaultBaseURL;
822
+ // init api
823
+ this._api = new __WEBPACK_EXTERNAL_MODULE__coze_api__.CozeAPI({
824
+ token: this._config.accessToken,
825
+ baseURL: defaultBaseURL,
826
+ allowPersonalAccessTokenInBrowser: this._config.allowPersonalAccessTokenInBrowser
827
+ });
828
+ this._isSupportVideo = !!config.videoConfig;
829
+ }
830
+ }
831
+ export { event_names as EventNames, RealtimeAPIError, RealtimeClient, error_RealtimeError as RealtimeError, utils_namespaceObject as RealtimeUtils };