@realsee/live 0.4.0-beta.4 → 0.4.0-beta.7

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.
@@ -1,9 +1,99 @@
1
1
  import JSBridge from '@realsee/jsbridge-x';
2
- import { DefaultModality, ConsoleLogger, LogLevel, DefaultDeviceController, MeetingSessionConfiguration, DefaultMeetingSession, MeetingSessionStatusCode } from 'amazon-chime-sdk-js';
2
+ import { DefaultModality, ConsoleLogger, LogLevel, DefaultDeviceController, MeetingSessionStatusCode, MeetingSessionConfiguration, DefaultMeetingSession } from 'amazon-chime-sdk-js';
3
3
  import TRTC from 'trtc-js-sdk';
4
4
  import React from 'react';
5
5
 
6
- const EVENT_SYMBOL = Symbol('$$REALSEE_LIVE_EVENT$$');
6
+ /******************************************************************************
7
+ Copyright (c) Microsoft Corporation.
8
+
9
+ Permission to use, copy, modify, and/or distribute this software for any
10
+ purpose with or without fee is hereby granted.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
13
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
14
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
15
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
16
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
17
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
18
+ PERFORMANCE OF THIS SOFTWARE.
19
+ ***************************************************************************** */
20
+ /* global Reflect, Promise */
21
+
22
+ var extendStatics = function(d, b) {
23
+ extendStatics = Object.setPrototypeOf ||
24
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
26
+ return extendStatics(d, b);
27
+ };
28
+
29
+ function __extends(d, b) {
30
+ if (typeof b !== "function" && b !== null)
31
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
32
+ extendStatics(d, b);
33
+ function __() { this.constructor = d; }
34
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35
+ }
36
+
37
+ var __assign = function() {
38
+ __assign = Object.assign || function __assign(t) {
39
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
40
+ s = arguments[i];
41
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
42
+ }
43
+ return t;
44
+ };
45
+ return __assign.apply(this, arguments);
46
+ };
47
+
48
+ function __awaiter(thisArg, _arguments, P, generator) {
49
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
50
+ return new (P || (P = Promise))(function (resolve, reject) {
51
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
52
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
53
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
54
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
55
+ });
56
+ }
57
+
58
+ function __generator(thisArg, body) {
59
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
60
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
61
+ function verb(n) { return function (v) { return step([n, v]); }; }
62
+ function step(op) {
63
+ if (f) throw new TypeError("Generator is already executing.");
64
+ while (_) try {
65
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
66
+ if (y = 0, t) op = [op[0] & 2, t.value];
67
+ switch (op[0]) {
68
+ case 0: case 1: t = op; break;
69
+ case 4: _.label++; return { value: op[1], done: false };
70
+ case 5: _.label++; y = op[1]; op = [0]; continue;
71
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
72
+ default:
73
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
74
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
75
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
76
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
77
+ if (t[2]) _.ops.pop();
78
+ _.trys.pop(); continue;
79
+ }
80
+ op = body.call(thisArg, _);
81
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
82
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
83
+ }
84
+ }
85
+
86
+ function __spreadArray(to, from, pack) {
87
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
88
+ if (ar || !(i in from)) {
89
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
90
+ ar[i] = from[i];
91
+ }
92
+ }
93
+ return to.concat(ar || Array.prototype.slice.call(from));
94
+ }
95
+
96
+ var EVENT_SYMBOL = Symbol('$$REALSEE_LIVE_EVENT$$');
7
97
  function __generateEventIfNotExisted(instance) {
8
98
  if (!instance[EVENT_SYMBOL]) {
9
99
  instance[EVENT_SYMBOL] = {};
@@ -26,15 +116,17 @@ function __removeEventIfNotExisted(instance) {
26
116
  * }>()
27
117
  * ```
28
118
  */
29
- class Subscribe {
119
+ var Subscribe = /** @class */ (function () {
120
+ function Subscribe() {
121
+ }
30
122
  /**
31
123
  * 判断是否注册了事件
32
124
  * @param name 事件类型
33
125
  */
34
- hasListener(name) {
35
- const events = __generateEventIfNotExisted(this);
126
+ Subscribe.prototype.hasListener = function (name) {
127
+ var events = __generateEventIfNotExisted(this);
36
128
  return events && events[name] && events[name].length > 0;
37
- }
129
+ };
38
130
  /**
39
131
  * 注册事件
40
132
  * @param name 事件类型
@@ -44,13 +136,14 @@ class Subscribe {
44
136
  * @template K 预设的监听事件名称
45
137
  * @template C 回调函数函数上下文
46
138
  */
47
- on(name, callback, once) {
48
- const events = __generateEventIfNotExisted(this);
139
+ Subscribe.prototype.on = function (name, callback, once) {
140
+ var _this = this;
141
+ var events = __generateEventIfNotExisted(this);
49
142
  if (!events[name])
50
143
  events[name] = [];
51
144
  events[name].push([callback, once || false]);
52
- return () => this.off(name, callback);
53
- }
145
+ return function () { return _this.off(name, callback); };
146
+ };
54
147
  /**
55
148
  * 注册事件(是否只执行一次)
56
149
  * @param name 事件类型
@@ -59,9 +152,9 @@ class Subscribe {
59
152
  * @template K 预设的监听事件名称
60
153
  * @template C 回调函数函数上下文
61
154
  */
62
- once(name, callback) {
155
+ Subscribe.prototype.once = function (name, callback) {
63
156
  return this.on(name, callback, true);
64
- }
157
+ };
65
158
  /**
66
159
  * 解除事件
67
160
  *
@@ -71,19 +164,19 @@ class Subscribe {
71
164
  * @param callback 事件回调函数
72
165
  * @template K 预设的监听事件名称
73
166
  */
74
- off(name, callback) {
167
+ Subscribe.prototype.off = function (name, callback) {
75
168
  if (name === undefined) {
76
169
  __removeEventIfNotExisted(this);
77
170
  return;
78
171
  }
79
- const events = __generateEventIfNotExisted(this);
172
+ var events = __generateEventIfNotExisted(this);
80
173
  if (!events[name])
81
174
  events[name] = [];
82
175
  if (callback === undefined) {
83
176
  events[name].length = 0;
84
177
  return;
85
178
  }
86
- let index = 0;
179
+ var index = 0;
87
180
  for (; index < events[name].length; index++) {
88
181
  if (events[name][index][0] === callback)
89
182
  break;
@@ -91,7 +184,7 @@ class Subscribe {
91
184
  if (index < events[name].length) {
92
185
  events[name].splice(index, 1);
93
186
  }
94
- }
187
+ };
95
188
  /**
96
189
  * 触发事件
97
190
  * @param name 事件类型
@@ -99,27 +192,38 @@ class Subscribe {
99
192
  * @returns canceled 是否被触发取消
100
193
  * @template K 预设的监听事件名称
101
194
  */
102
- emit(name, ...data) {
103
- let canceled = false;
104
- const events = __generateEventIfNotExisted(this);
105
- const event = events[name] || [];
106
- for (let one of event.slice()) {
107
- const [callback, once = false] = one;
108
- const result = callback(...data);
195
+ Subscribe.prototype.emit = function (name) {
196
+ var data = [];
197
+ for (var _i = 1; _i < arguments.length; _i++) {
198
+ data[_i - 1] = arguments[_i];
199
+ }
200
+ var canceled = false;
201
+ var events = __generateEventIfNotExisted(this);
202
+ var event = events[name] || [];
203
+ for (var _a = 0, _b = event.slice(); _a < _b.length; _a++) {
204
+ var one = _b[_a];
205
+ var callback = one[0], _c = one[1], once = _c === void 0 ? false : _c;
206
+ var result = callback.apply(void 0, data);
109
207
  if (once)
110
208
  this.off(name, callback);
111
209
  if (result === false)
112
210
  canceled = true;
113
211
  }
114
212
  return canceled;
115
- }
116
- }
213
+ };
214
+ return Subscribe;
215
+ }());
117
216
 
118
217
  /**
119
218
  * rtc 基础抽象类
120
219
  */
121
- class CoreRTC extends Subscribe {
122
- }
220
+ var CoreRTC = /** @class */ (function (_super) {
221
+ __extends(CoreRTC, _super);
222
+ function CoreRTC() {
223
+ return _super !== null && _super.apply(this, arguments) || this;
224
+ }
225
+ return CoreRTC;
226
+ }(Subscribe));
123
227
 
124
228
  /**
125
229
  * rtc 类型
@@ -159,202 +263,231 @@ function uuid() {
159
263
  S4()).toLowerCase();
160
264
  }
161
265
 
162
- class BrowserRTC extends CoreRTC {
163
- constructor(options) {
164
- super();
165
- this.type = RTCType.RealseeBrowserRTC;
166
- this.joined = false;
167
- this.micro = false;
168
- this.voiceId = '';
169
- this._getVoiceSign = () => {
266
+ var BrowserRTC = /** @class */ (function (_super) {
267
+ __extends(BrowserRTC, _super);
268
+ function BrowserRTC(options) {
269
+ var _this = _super.call(this) || this;
270
+ _this.type = RTCType.RealseeBrowserRTC;
271
+ _this.joined = false;
272
+ _this.micro = false;
273
+ _this.voiceId = '';
274
+ _this._getVoiceSign = function () {
170
275
  throw new Error('方法 getVoiceSign 未实现');
171
276
  };
172
- this.$dom = document.createElement('div');
173
- this._trtc = {
277
+ _this.$dom = document.createElement('div');
278
+ _this._trtc = {
174
279
  client: null,
175
280
  stream: null,
176
281
  };
177
- this.join = async (options) => {
282
+ _this.join = function (options) { return __awaiter(_this, void 0, void 0, function () {
283
+ var createClientOptions, result;
284
+ var _this = this;
178
285
  var _a;
179
- this.emit('joinWillStart');
180
- const createClientOptions = await this._getVoiceSign({
181
- voiceId: options.voiceId,
182
- roomId: options.roomId,
183
- userId: options.userId,
184
- });
185
- // 1. 创建client
186
- this._trtc.client = TRTC.createClient({
187
- mode: 'rtc',
188
- ...createClientOptions,
189
- });
190
- (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.enableAudioVolumeEvaluation();
191
- // 2. 订阅事件
192
- this._registerRtcEvent();
193
- // 3. 加入语音房间
194
- let result = await new Promise((resolve) => {
195
- var _a;
196
- (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.join({ roomId: Number(options.voiceId) }).then(() => resolve(true)).catch(() => resolve(false));
197
- });
198
- this.joined = result;
199
- if (!result)
200
- return false; // 进房失败
201
- // 4. 创建本地流
202
- this._trtc.stream = TRTC.createStream({
203
- userId: createClientOptions.userId,
204
- audio: true,
205
- video: false,
206
- });
207
- // 5. 初始化本地流
208
- result = await new Promise((resolve) => {
209
- var _a;
210
- (_a = this._trtc.stream) === null || _a === void 0 ? void 0 : _a.initialize().then(() => resolve(true)).catch(() => resolve(false));
211
- });
212
- // 6. 发布本地流
213
- result = await new Promise((resolve) => {
214
- var _a;
215
- (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.publish(this._trtc.stream).then(() => resolve(true)).catch(() => resolve(false));
286
+ return __generator(this, function (_b) {
287
+ switch (_b.label) {
288
+ case 0:
289
+ this.emit('joinWillStart');
290
+ return [4 /*yield*/, this._getVoiceSign({
291
+ voiceId: options.voiceId,
292
+ roomId: options.roomId,
293
+ userId: options.userId,
294
+ })];
295
+ case 1:
296
+ createClientOptions = _b.sent();
297
+ // 1. 创建client
298
+ this._trtc.client = TRTC.createClient(__assign({ mode: 'rtc' }, createClientOptions));
299
+ (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.enableAudioVolumeEvaluation();
300
+ // 2. 订阅事件
301
+ this._registerRtcEvent();
302
+ return [4 /*yield*/, new Promise(function (resolve) {
303
+ var _a;
304
+ (_a = _this._trtc.client) === null || _a === void 0 ? void 0 : _a.join({ roomId: Number(options.voiceId) }).then(function () { return resolve(true); }).catch(function () { return resolve(false); });
305
+ })];
306
+ case 2:
307
+ result = _b.sent();
308
+ this.joined = result;
309
+ if (!result)
310
+ return [2 /*return*/, false]; // 进房失败
311
+ // 4. 创建本地流
312
+ this._trtc.stream = TRTC.createStream({
313
+ userId: createClientOptions.userId,
314
+ audio: true,
315
+ video: false,
316
+ });
317
+ return [4 /*yield*/, new Promise(function (resolve) {
318
+ var _a;
319
+ (_a = _this._trtc.stream) === null || _a === void 0 ? void 0 : _a.initialize().then(function () { return resolve(true); }).catch(function () { return resolve(false); });
320
+ })];
321
+ case 3:
322
+ // 5. 初始化本地流
323
+ result = _b.sent();
324
+ return [4 /*yield*/, new Promise(function (resolve) {
325
+ var _a;
326
+ (_a = _this._trtc.client) === null || _a === void 0 ? void 0 : _a.publish(_this._trtc.stream).then(function () { return resolve(true); }).catch(function () { return resolve(false); });
327
+ })];
328
+ case 4:
329
+ // 6. 发布本地流
330
+ result = _b.sent();
331
+ this.joined = result;
332
+ if (this.joined)
333
+ this.emit('joined');
334
+ return [2 /*return*/, result];
335
+ }
216
336
  });
217
- this.joined = result;
218
- if (this.joined)
219
- this.emit('joined');
220
- return result;
221
- };
222
- this._handleStreamAdded = (event) => {
337
+ }); };
338
+ _this._handleStreamAdded = function (event) {
223
339
  var _a;
224
- const remoteStream = event.stream;
340
+ var remoteStream = event.stream;
225
341
  console.log('远端流增加: ' + remoteStream.getId());
226
342
  //订阅远端流
227
- (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.subscribe(remoteStream);
343
+ (_a = _this._trtc.client) === null || _a === void 0 ? void 0 : _a.subscribe(remoteStream);
228
344
  };
229
- this._handleStreamSubscribed = (event) => {
230
- const remoteStream = event.stream;
345
+ _this._handleStreamSubscribed = function (event) {
346
+ var remoteStream = event.stream;
231
347
  console.log('远端流订阅成功:' + remoteStream.getId());
232
- const playId = remoteStream.getId();
233
- const domId = `rs-rtc-remote_stream-${playId}`;
234
- const dom = document.createElement('div');
348
+ var playId = remoteStream.getId();
349
+ var domId = "rs-rtc-remote_stream-".concat(playId);
350
+ var dom = document.createElement('div');
235
351
  dom.id = domId;
236
- this.$dom.appendChild(dom);
352
+ _this.$dom.appendChild(dom);
237
353
  // 播放远端流
238
354
  remoteStream.play(domId);
239
355
  };
240
- this._getVoiceSign = options.getVoiceSign;
241
- this._initParentDom();
356
+ _this._getVoiceSign = options.getVoiceSign;
357
+ _this._initParentDom();
358
+ return _this;
242
359
  }
243
- _initParentDom() {
244
- this.$dom.id = `rs-rtc-${uuid()}`;
360
+ BrowserRTC.prototype._initParentDom = function () {
361
+ this.$dom.id = "rs-rtc-".concat(uuid());
245
362
  this.$dom.style.display = 'none';
246
363
  document.body.appendChild(this.$dom);
247
- }
248
- quit() {
249
- return new Promise(async (resolve) => {
364
+ };
365
+ BrowserRTC.prototype.quit = function () {
366
+ var _this = this;
367
+ return new Promise(function (resolve) { return __awaiter(_this, void 0, void 0, function () {
368
+ var _this = this;
250
369
  var _a, _b;
251
- this.joined = false;
252
- if (this._trtc.stream) {
253
- await ((_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.unpublish(this._trtc.stream));
254
- this._trtc.stream.stop();
255
- this._trtc.stream.close();
256
- this._trtc.stream = null;
257
- }
258
- (_b = this._trtc.client) === null || _b === void 0 ? void 0 : _b.leave().then(() => (this._trtc.client = null)).then(() => resolve(true)).catch(() => resolve(false));
259
- });
260
- }
261
- detectMicro() {
262
- return new Promise((resolve) => {
263
- const rule = { audio: true, video: false };
370
+ return __generator(this, function (_c) {
371
+ switch (_c.label) {
372
+ case 0:
373
+ this.joined = false;
374
+ if (!this._trtc.stream) return [3 /*break*/, 2];
375
+ return [4 /*yield*/, ((_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.unpublish(this._trtc.stream))];
376
+ case 1:
377
+ _c.sent();
378
+ this._trtc.stream.stop();
379
+ this._trtc.stream.close();
380
+ this._trtc.stream = null;
381
+ _c.label = 2;
382
+ case 2:
383
+ (_b = this._trtc.client) === null || _b === void 0 ? void 0 : _b.leave().then(function () { return (_this._trtc.client = null); }).then(function () { return resolve(true); }).catch(function () { return resolve(false); });
384
+ return [2 /*return*/];
385
+ }
386
+ });
387
+ }); });
388
+ };
389
+ BrowserRTC.prototype.detectMicro = function () {
390
+ return new Promise(function (resolve) {
391
+ var rule = { audio: true, video: false };
264
392
  try {
265
393
  navigator.mediaDevices
266
394
  .getUserMedia(rule)
267
- .then(() => resolve(true))
268
- .catch(() => resolve(false));
395
+ .then(function () { return resolve(true); })
396
+ .catch(function () { return resolve(false); });
269
397
  }
270
398
  catch (e) {
271
399
  console.error(e);
272
400
  resolve(false);
273
401
  }
274
402
  });
275
- }
276
- toggleMicro(flag) {
403
+ };
404
+ BrowserRTC.prototype.toggleMicro = function (flag) {
277
405
  var _a, _b, _c, _d;
278
406
  return Promise.resolve((flag
279
407
  ? (_b = (_a = this._trtc) === null || _a === void 0 ? void 0 : _a.stream) === null || _b === void 0 ? void 0 : _b.unmuteAudio()
280
408
  : (_d = (_c = this._trtc) === null || _c === void 0 ? void 0 : _c.stream) === null || _d === void 0 ? void 0 : _d.muteAudio()) || false);
281
- }
282
- shock() {
409
+ };
410
+ BrowserRTC.prototype.shock = function () {
283
411
  throw new Error('Method not implemented.');
284
- }
285
- _registerRtcEvent() {
412
+ };
413
+ BrowserRTC.prototype._registerRtcEvent = function () {
414
+ var _this = this;
286
415
  var _a, _b, _c, _d;
287
416
  (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.on('stream-added', this._handleStreamAdded);
288
417
  (_b = this._trtc.client) === null || _b === void 0 ? void 0 : _b.on('stream-subscribed', this._handleStreamSubscribed);
289
- (_c = this._trtc.client) === null || _c === void 0 ? void 0 : _c.on('audio-volume', (event) => this.emit('userVolumes', [
290
- { userId: event.userId, audioVolume: event.audioVolume },
291
- ]));
292
- (_d = this._trtc.client) === null || _d === void 0 ? void 0 : _d.on('error', (event) => this.emit('error', event));
293
- }
294
- }
418
+ (_c = this._trtc.client) === null || _c === void 0 ? void 0 : _c.on('audio-volume', function (event) {
419
+ return _this.emit('userVolumes', [
420
+ { userId: event.userId, audioVolume: event.audioVolume },
421
+ ]);
422
+ });
423
+ (_d = this._trtc.client) === null || _d === void 0 ? void 0 : _d.on('error', function (event) { return _this.emit('error', event); });
424
+ };
425
+ return BrowserRTC;
426
+ }(CoreRTC));
295
427
 
296
428
  /**
297
429
  * amazon-chime-sdk-js 适配的rtc实现
298
430
  */
299
- class BrowserRTC4Chime extends CoreRTC {
300
- constructor(options) {
301
- super();
302
- this.type = RTCType.RealseeBrowserChimeRTC;
303
- this.joined = false;
304
- this.micro = false;
305
- this.voiceId = '';
306
- this.userId = '';
307
- this.deviceChangeObserver = {};
308
- this.audioVideoObserver = {};
309
- this._getVoiceSign = () => {
431
+ var BrowserRTC4Chime = /** @class */ (function (_super) {
432
+ __extends(BrowserRTC4Chime, _super);
433
+ function BrowserRTC4Chime(options) {
434
+ var _this = _super.call(this) || this;
435
+ _this.type = RTCType.RealseeBrowserChimeRTC;
436
+ _this.joined = false;
437
+ _this.micro = false;
438
+ _this.voiceId = '';
439
+ _this.userId = '';
440
+ _this.deviceChangeObserver = {};
441
+ _this.audioVideoObserver = {};
442
+ _this._getVoiceSign = function () {
310
443
  throw new Error('方法 getVoiceSign 未实现');
311
444
  };
312
- this.$dom = document.createElement('div');
313
- this.$audio = document.createElement('audio');
445
+ _this.$dom = document.createElement('div');
446
+ _this.$audio = document.createElement('audio');
314
447
  /**
315
448
  * 对audio标签初始化
316
449
  */
317
- this._initDom = () => {
318
- this.$audio.id = `rs-rtc-${uuid()}`;
319
- this.$dom.id = `rs-rtc-${uuid()}`;
320
- this.$dom.appendChild(this.$audio);
321
- document.body.appendChild(this.$dom);
450
+ _this._initDom = function () {
451
+ _this.$audio.id = "rs-rtc-".concat(uuid());
452
+ _this.$dom.id = "rs-rtc-".concat(uuid());
453
+ _this.$dom.appendChild(_this.$audio);
454
+ document.body.appendChild(_this.$dom);
322
455
  };
323
456
  /**
324
457
  * 初始化事件监听器
325
458
  */
326
- this.initObservers = () => {
459
+ _this.initObservers = function () {
327
460
  // 输入输出设备变化的监听器
328
- this.deviceChangeObserver = {
329
- audioInputsChanged: (freshAudioInputDeviceList) => {
461
+ _this.deviceChangeObserver = {
462
+ audioInputsChanged: function (freshAudioInputDeviceList) {
330
463
  // An array of MediaDeviceInfo objects
331
- freshAudioInputDeviceList === null || freshAudioInputDeviceList === void 0 ? void 0 : freshAudioInputDeviceList.forEach((mediaDeviceInfo) => {
332
- this.logger.info(`Device ID: ${mediaDeviceInfo.deviceId} Microphone: ${mediaDeviceInfo.label}`);
464
+ freshAudioInputDeviceList === null || freshAudioInputDeviceList === void 0 ? void 0 : freshAudioInputDeviceList.forEach(function (mediaDeviceInfo) {
465
+ _this.logger.info("Device ID: ".concat(mediaDeviceInfo.deviceId, " Microphone: ").concat(mediaDeviceInfo.label));
333
466
  });
334
467
  },
335
- audioOutputsChanged: (freshAudioOutputDeviceList) => {
336
- this.logger.info(`Audio outputs updated: ${freshAudioOutputDeviceList}`);
468
+ audioOutputsChanged: function (freshAudioOutputDeviceList) {
469
+ _this.logger.info("Audio outputs updated: ".concat(freshAudioOutputDeviceList));
337
470
  },
338
- videoInputsChanged: (freshVideoInputDeviceList) => {
339
- this.logger.info(`Video inputs updated: ${freshVideoInputDeviceList}`);
471
+ videoInputsChanged: function (freshVideoInputDeviceList) {
472
+ _this.logger.info("Video inputs updated: ".concat(freshVideoInputDeviceList));
340
473
  },
341
- audioInputMuteStateChanged: (device, muted) => {
342
- this.logger.info(`Device ${device.toString()} ${muted ? 'is muted in hardware' : 'is not muted'}`);
474
+ audioInputMuteStateChanged: function (device, muted) {
475
+ _this.logger.info("Device ".concat(device.toString(), " ").concat(muted ? 'is muted in hardware' : 'is not muted'));
343
476
  },
344
477
  };
345
478
  // 流变化监听器
346
- this.audioVideoObserver = {
347
- audioVideoDidStart: () => {
348
- this.logger.info('Started');
479
+ _this.audioVideoObserver = {
480
+ audioVideoDidStart: function () {
481
+ _this.logger.info('Started');
349
482
  },
350
- audioVideoDidStop: (sessionStatus) => {
483
+ audioVideoDidStop: function (sessionStatus) {
351
484
  // See the "Stopping a session" section for details.
352
- this.logger.info(`Stopped with a session status code: ${sessionStatus.statusCode()}`);
485
+ _this.logger.info("Stopped with a session status code: ".concat(sessionStatus.statusCode()));
353
486
  },
354
- audioVideoDidStartConnecting: (reconnecting) => {
487
+ audioVideoDidStartConnecting: function (reconnecting) {
355
488
  if (reconnecting) {
356
489
  // e.g. the WiFi connection is dropped.
357
- this.logger.info('Attempting to reconnect');
490
+ _this.logger.info('Attempting to reconnect');
358
491
  }
359
492
  },
360
493
  };
@@ -362,15 +495,15 @@ class BrowserRTC4Chime extends CoreRTC {
362
495
  /**
363
496
  * 注册rtc事件
364
497
  */
365
- this._registerRtcEvent = () => {
498
+ _this._registerRtcEvent = function () {
366
499
  var _a, _b, _c, _d, _e, _f;
367
- const presentAttendeeId = ((_c = (_b = (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.configuration) === null || _b === void 0 ? void 0 : _b.credentials) === null || _c === void 0 ? void 0 : _c.attendeeId) || '';
500
+ var presentAttendeeId = ((_c = (_b = (_a = _this.meetingSession) === null || _a === void 0 ? void 0 : _a.configuration) === null || _b === void 0 ? void 0 : _b.credentials) === null || _c === void 0 ? void 0 : _c.attendeeId) || '';
368
501
  if (presentAttendeeId) {
369
502
  // 处理音量变化
370
- const roster = new Map();
371
- const getUserVolumes = () => {
372
- const result = [];
373
- roster.forEach((v, k) => {
503
+ var roster_1 = new Map();
504
+ var getUserVolumes_1 = function () {
505
+ var result = [];
506
+ roster_1.forEach(function (v, k) {
374
507
  result.push({
375
508
  userId: v.userId,
376
509
  volume: v.muted || v.signalStrength === 0 || !Boolean(v.volume)
@@ -380,175 +513,208 @@ class BrowserRTC4Chime extends CoreRTC {
380
513
  });
381
514
  return result;
382
515
  };
383
- (_d = this.meetingSession) === null || _d === void 0 ? void 0 : _d.audioVideo.realtimeSubscribeToAttendeeIdPresence((presentAttendeeId, present, externalUserId) => {
516
+ (_d = _this.meetingSession) === null || _d === void 0 ? void 0 : _d.audioVideo.realtimeSubscribeToAttendeeIdPresence(function (presentAttendeeId, present, externalUserId) {
384
517
  var _a;
385
518
  if (!present) {
386
- roster.delete(presentAttendeeId);
387
- this.emit('userVolumes', getUserVolumes());
519
+ roster_1.delete(presentAttendeeId);
520
+ _this.emit('userVolumes', getUserVolumes_1());
388
521
  return;
389
522
  }
390
- (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeSubscribeToVolumeIndicator(presentAttendeeId, (attendeeId, volume, muted, signalStrength) => {
391
- const baseAttendeeId = new DefaultModality(attendeeId).base();
523
+ (_a = _this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeSubscribeToVolumeIndicator(presentAttendeeId, function (attendeeId, volume, muted, signalStrength) {
524
+ var baseAttendeeId = new DefaultModality(attendeeId).base();
392
525
  if (baseAttendeeId !== attendeeId) {
393
526
  // Optional: Do not include the content attendee (attendee-id#content) in the roster.
394
527
  // See the "Screen and content share" section for details.
395
528
  return;
396
529
  }
397
- roster.set(attendeeId, {
530
+ roster_1.set(attendeeId, {
398
531
  userId: externalUserId || attendeeId,
399
- volume,
400
- muted,
401
- signalStrength,
532
+ volume: volume,
533
+ muted: muted,
534
+ signalStrength: signalStrength,
402
535
  });
403
- this.emit('userVolumes', getUserVolumes());
536
+ _this.emit('userVolumes', getUserVolumes_1());
404
537
  });
405
538
  });
406
539
  // 弱网
407
- (_e = this.meetingSession) === null || _e === void 0 ? void 0 : _e.audioVideo.realtimeSubscribeToVolumeIndicator(presentAttendeeId, (attendeeId, volume, muted, signalStrength) => {
408
- const baseAttendeeId = new DefaultModality(attendeeId).base();
540
+ (_e = _this.meetingSession) === null || _e === void 0 ? void 0 : _e.audioVideo.realtimeSubscribeToVolumeIndicator(presentAttendeeId, function (attendeeId, volume, muted, signalStrength) {
541
+ var baseAttendeeId = new DefaultModality(attendeeId).base();
409
542
  if (baseAttendeeId === attendeeId) {
410
543
  if (signalStrength !== null && signalStrength !== 1) {
411
- this.emit('weakNetwork');
544
+ _this.emit('weakNetwork');
412
545
  }
413
546
  }
414
547
  });
415
548
  // 报错
416
- (_f = this.meetingSession) === null || _f === void 0 ? void 0 : _f.audioVideo.realtimeSubscribeToFatalError((error) => this.emit('error', error));
549
+ (_f = _this.meetingSession) === null || _f === void 0 ? void 0 : _f.audioVideo.realtimeSubscribeToFatalError(function (error) { return _this.emit('error', error); });
417
550
  }
418
551
  };
419
552
  // 挂载签名钩子
420
- this._getVoiceSign = options.getVoiceSign;
421
- this._initDom();
422
- this.logger = new ConsoleLogger('WebRTCLogger', options.logLevel || LogLevel.OFF);
423
- this.deviceController = new DefaultDeviceController(this.logger);
424
- this.initObservers();
553
+ _this._getVoiceSign = options.getVoiceSign;
554
+ _this._initDom();
555
+ _this.logger = new ConsoleLogger('WebRTCLogger', options.logLevel || LogLevel.OFF);
556
+ _this.deviceController = new DefaultDeviceController(_this.logger);
557
+ _this.initObservers();
558
+ return _this;
425
559
  }
426
560
  /**
427
561
  * 加入语音会议
428
562
  * @param options
429
563
  * @returns
430
564
  */
431
- async join(options) {
432
- return new Promise(async (success, fail) => {
433
- var _a;
434
- this.emit('joinWillStart');
435
- try {
436
- // 取签名
437
- const { sdkAppId, userId, roomId, userSig } = await this._getVoiceSign({
438
- ...options,
439
- roomId: options.roomId || 0,
440
- });
441
- this.userId = userId;
442
- const { attendence, vendor_wrapper, } = JSON.parse(decodeURIComponent(userSig));
443
- // 初始化配置
444
- const configuration = new MeetingSessionConfiguration({
445
- Meeting: vendor_wrapper,
446
- }, {
447
- Attendee: {
448
- ExternalUserId: attendence.external_user_id,
449
- AttendeeId: attendence.attendee_id,
450
- JoinToken: attendence.join_token,
451
- },
452
- });
453
- // 初始化会议会话
454
- this.meetingSession = new DefaultMeetingSession(configuration, this.logger, this.deviceController);
455
- // 注册事件
456
- this._registerRtcEvent();
457
- // 绑定监听器
458
- this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver);
459
- this.meetingSession.audioVideo.addObserver(this.audioVideoObserver);
460
- // 绑定播放器
461
- this.meetingSession.audioVideo.bindAudioElement(this.$audio);
462
- const observer = {
463
- audioVideoDidStart: () => {
464
- var _a;
465
- (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeMuteLocalAudio();
466
- this.joined = true;
467
- this.emit('joined');
468
- success(true);
469
- },
470
- audioVideoDidStop: () => {
471
- this.joined = false;
472
- success(false);
473
- },
474
- };
475
- this.meetingSession.audioVideo.addObserver(observer);
476
- // 选择语音输入设备
477
- const audioInputDevices = await this.deviceController.listAudioInputDevices(true);
478
- const defaultAudioInput = audioInputDevices.find((device) => device.deviceId === 'default');
479
- const otherAudioInput = audioInputDevices.find((device) => device.deviceId !== '');
480
- this.audioInput = defaultAudioInput || otherAudioInput;
481
- await this.meetingSession.audioVideo.chooseVideoInputDevice(null);
482
- await this.meetingSession.audioVideo.chooseAudioInputDevice(((_a = this.audioInput) === null || _a === void 0 ? void 0 : _a.deviceId) || 'default');
483
- this.meetingSession.audioVideo.start();
484
- }
485
- catch (e) {
486
- this.emit('error', e);
487
- this.logger.error(e.message);
488
- success(false);
489
- }
565
+ BrowserRTC4Chime.prototype.join = function (options) {
566
+ return __awaiter(this, void 0, void 0, function () {
567
+ var _this = this;
568
+ return __generator(this, function (_a) {
569
+ return [2 /*return*/, new Promise(function (success, fail) { return __awaiter(_this, void 0, void 0, function () {
570
+ var _a, userId, userSig, _b, attendence, vendor_wrapper, configuration, observer, audioInputDevices, defaultAudioInput, otherAudioInput, e_1;
571
+ var _this = this;
572
+ var _c;
573
+ return __generator(this, function (_d) {
574
+ switch (_d.label) {
575
+ case 0:
576
+ this.emit('joinWillStart');
577
+ _d.label = 1;
578
+ case 1:
579
+ _d.trys.push([1, 6, , 7]);
580
+ return [4 /*yield*/, this._getVoiceSign(__assign(__assign({}, options), { roomId: options.roomId || 0 }))];
581
+ case 2:
582
+ _a = _d.sent(), userId = _a.userId, userSig = _a.userSig;
583
+ this.userId = userId;
584
+ _b = JSON.parse(decodeURIComponent(userSig)), attendence = _b.attendence, vendor_wrapper = _b.vendor_wrapper;
585
+ configuration = new MeetingSessionConfiguration({
586
+ Meeting: vendor_wrapper,
587
+ }, {
588
+ Attendee: {
589
+ ExternalUserId: attendence.external_user_id,
590
+ AttendeeId: attendence.attendee_id,
591
+ JoinToken: attendence.join_token,
592
+ },
593
+ });
594
+ // 初始化会议会话
595
+ this.meetingSession = new DefaultMeetingSession(configuration, this.logger, this.deviceController);
596
+ // 注册事件
597
+ this._registerRtcEvent();
598
+ // 绑定监听器
599
+ this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver);
600
+ this.meetingSession.audioVideo.addObserver(this.audioVideoObserver);
601
+ // 绑定播放器
602
+ this.meetingSession.audioVideo.bindAudioElement(this.$audio);
603
+ observer = {
604
+ audioVideoDidStart: function () {
605
+ var _a;
606
+ (_a = _this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeMuteLocalAudio();
607
+ _this.joined = true;
608
+ _this.emit('joined');
609
+ success(true);
610
+ },
611
+ audioVideoDidStop: function () {
612
+ _this.joined = false;
613
+ success(false);
614
+ },
615
+ };
616
+ this.meetingSession.audioVideo.addObserver(observer);
617
+ return [4 /*yield*/, this.deviceController.listAudioInputDevices(true)];
618
+ case 3:
619
+ audioInputDevices = _d.sent();
620
+ defaultAudioInput = audioInputDevices.find(function (device) { return device.deviceId === 'default'; });
621
+ otherAudioInput = audioInputDevices.find(function (device) { return device.deviceId !== ''; });
622
+ this.audioInput = defaultAudioInput || otherAudioInput;
623
+ return [4 /*yield*/, this.meetingSession.audioVideo.chooseVideoInputDevice(null)];
624
+ case 4:
625
+ _d.sent();
626
+ return [4 /*yield*/, this.meetingSession.audioVideo.chooseAudioInputDevice(((_c = this.audioInput) === null || _c === void 0 ? void 0 : _c.deviceId) || 'default')];
627
+ case 5:
628
+ _d.sent();
629
+ this.meetingSession.audioVideo.start();
630
+ return [3 /*break*/, 7];
631
+ case 6:
632
+ e_1 = _d.sent();
633
+ this.emit('error', e_1);
634
+ this.logger.error(e_1.message);
635
+ success(false);
636
+ return [3 /*break*/, 7];
637
+ case 7: return [2 /*return*/];
638
+ }
639
+ });
640
+ }); })];
641
+ });
490
642
  });
491
- }
492
- quit() {
493
- return new Promise((success, fail) => {
643
+ };
644
+ BrowserRTC4Chime.prototype.quit = function () {
645
+ var _this = this;
646
+ if (!this.joined)
647
+ return Promise.resolve(true);
648
+ return new Promise(function (success, fail) {
494
649
  var _a, _b;
495
- this.joined = false;
496
- const observer = {
497
- audioVideoDidStop: (sessionStatus) => {
498
- const sessionStatusCode = sessionStatus.statusCode();
650
+ _this.joined = false;
651
+ var observer = {
652
+ audioVideoDidStop: function (sessionStatus) {
653
+ var sessionStatusCode = sessionStatus.statusCode();
499
654
  if (sessionStatusCode === MeetingSessionStatusCode.Left) {
500
655
  /*
501
656
  - You called meetingSession.audioVideo.stop().
502
657
  - When closing a browser window or page, Chime SDK attempts to leave the session.
503
658
  */
504
- this.logger.info('You left the session');
659
+ _this.logger.info('You left the session');
505
660
  success(true);
506
661
  }
507
662
  else {
508
- this.logger.info(`Stopped with a session status code: ${sessionStatusCode}`);
663
+ _this.logger.info("Stopped with a session status code: ".concat(sessionStatusCode));
509
664
  success(true);
510
665
  }
511
666
  },
512
667
  };
513
- (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.addObserver(observer);
514
- (_b = this.meetingSession) === null || _b === void 0 ? void 0 : _b.audioVideo.stop();
668
+ (_a = _this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.addObserver(observer);
669
+ (_b = _this.meetingSession) === null || _b === void 0 ? void 0 : _b.audioVideo.stop();
515
670
  });
516
- }
517
- async detectMicro() {
518
- return new Promise((resolve) => {
519
- const rule = { audio: true, video: false };
520
- try {
521
- navigator.mediaDevices
522
- .getUserMedia(rule)
523
- .then(() => resolve(true))
524
- .catch(() => resolve(false));
525
- }
526
- catch (e) {
527
- this.logger.error(e.message);
528
- resolve(false);
529
- }
671
+ };
672
+ BrowserRTC4Chime.prototype.detectMicro = function () {
673
+ return __awaiter(this, void 0, void 0, function () {
674
+ var _this = this;
675
+ return __generator(this, function (_a) {
676
+ return [2 /*return*/, new Promise(function (resolve) {
677
+ var rule = { audio: true, video: false };
678
+ try {
679
+ navigator.mediaDevices
680
+ .getUserMedia(rule)
681
+ .then(function () { return resolve(true); })
682
+ .catch(function () { return resolve(false); });
683
+ }
684
+ catch (e) {
685
+ _this.logger.error(e.message);
686
+ resolve(false);
687
+ }
688
+ })];
689
+ });
530
690
  });
531
- }
532
- async toggleMicro(flag) {
691
+ };
692
+ BrowserRTC4Chime.prototype.toggleMicro = function (flag) {
533
693
  var _a, _b, _c;
534
- if (flag) {
535
- (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeUnmuteLocalAudio();
536
- }
537
- else {
538
- (_b = this.meetingSession) === null || _b === void 0 ? void 0 : _b.audioVideo.realtimeMuteLocalAudio();
539
- }
540
- const muted = (_c = this.meetingSession) === null || _c === void 0 ? void 0 : _c.audioVideo.realtimeIsLocalAudioMuted();
541
- if (muted !== undefined) {
542
- return flag !== muted;
543
- }
544
- else {
545
- return false;
546
- }
547
- }
548
- shock() {
694
+ return __awaiter(this, void 0, void 0, function () {
695
+ var muted;
696
+ return __generator(this, function (_d) {
697
+ if (flag) {
698
+ (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeUnmuteLocalAudio();
699
+ }
700
+ else {
701
+ (_b = this.meetingSession) === null || _b === void 0 ? void 0 : _b.audioVideo.realtimeMuteLocalAudio();
702
+ }
703
+ muted = (_c = this.meetingSession) === null || _c === void 0 ? void 0 : _c.audioVideo.realtimeIsLocalAudioMuted();
704
+ if (muted !== undefined) {
705
+ return [2 /*return*/, flag !== muted];
706
+ }
707
+ else {
708
+ return [2 /*return*/, false];
709
+ }
710
+ });
711
+ });
712
+ };
713
+ BrowserRTC4Chime.prototype.shock = function () {
549
714
  throw new Error('Method not implemented.');
550
- }
551
- }
715
+ };
716
+ return BrowserRTC4Chime;
717
+ }(CoreRTC));
552
718
 
553
719
  /**
554
720
  * rtc加入返回值code枚举
@@ -573,75 +739,122 @@ var RTCJoinedInfoCodeEnum;
573
739
  RTCJoinedInfoCodeEnum[RTCJoinedInfoCodeEnum["NoMicroPermission"] = 3] = "NoMicroPermission";
574
740
  })(RTCJoinedInfoCodeEnum || (RTCJoinedInfoCodeEnum = {}));
575
741
 
576
- class VRWebViewRTC extends CoreRTC {
577
- constructor({ jsBridge, getVoiceSign }) {
578
- super();
579
- this.type = RTCType.RealseeVRWebViewRTC;
580
- this.joined = false;
581
- this.micro = false;
582
- this.voiceId = '';
583
- this.options = { jsBridge, getVoiceSign };
584
- this.jsBridge.callAndListen('live/userVolumes', (userVolumes) => {
585
- this.emit('userVolumes', userVolumes);
742
+ var VRWebViewRTC = /** @class */ (function (_super) {
743
+ __extends(VRWebViewRTC, _super);
744
+ function VRWebViewRTC(_a) {
745
+ var jsBridge = _a.jsBridge, getVoiceSign = _a.getVoiceSign;
746
+ var _this = _super.call(this) || this;
747
+ _this.type = RTCType.RealseeVRWebViewRTC;
748
+ _this.joined = false;
749
+ _this.micro = false;
750
+ _this.voiceId = '';
751
+ _this.options = { jsBridge: jsBridge, getVoiceSign: getVoiceSign };
752
+ _this.jsBridge.callAndListen('live/userVolumes', function (userVolumes) {
753
+ _this.emit('userVolumes', userVolumes);
586
754
  });
587
- this.jsBridge.callAndListen('live/weakNetwork', (weakNetwork) => {
755
+ _this.jsBridge.callAndListen('live/weakNetwork', function (weakNetwork) {
588
756
  if (weakNetwork)
589
- this.emit('weakNetwork');
757
+ _this.emit('weakNetwork');
590
758
  });
759
+ return _this;
591
760
  }
592
- get jsBridge() {
593
- return this.options.jsBridge;
594
- }
595
- async join(options) {
596
- this.emit('joinWillStart');
597
- const { sdkAppId, userId, userSig } = await this.options.getVoiceSign(options);
598
- this.type = options.type;
599
- const [res, error] = await this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${sdkAppId}&userID=${userId}&roomID=${Number(options.voiceId)}&userSig=${userSig}`);
600
- if (!res) {
601
- this.emit('error', error ? error : new Error('加入房间失败:未知异常。'));
602
- this.joined = false;
603
- }
604
- else {
605
- if (res.code === RTCJoinedInfoCodeEnum.Success) {
606
- this.emit('joined');
607
- this.joined = true;
608
- }
609
- else {
610
- this.emit('error', res);
611
- this.joined = false;
612
- }
613
- }
614
- return this.joined;
615
- }
616
- async quit() {
617
- const [res, error] = await this.jsBridge.callAndBackfeed('live/quit');
618
- if (res === null) {
619
- this.emit('error', error ? error : new Error('退出房间失败:未知异常。'));
620
- }
621
- this.joined = false;
622
- return !!res;
623
- }
624
- async detectMicro() {
625
- const [res, error] = await this.jsBridge.detectMicro();
626
- if (res === null) {
627
- this.emit('error', error ? error : new Error('麦克风监测异常!'));
628
- return false;
629
- }
630
- return res;
631
- }
632
- async toggleMicro(flag) {
633
- const [res, error] = await this.jsBridge.callAndBackfeed(`live/toggleMicro?flag=${!!flag ? 1 : 0}`);
634
- if (res === null) {
635
- this.emit('error', error ? error : new Error('麦克风监测异常!'));
636
- return false;
637
- }
638
- this.micro = res;
639
- return res;
640
- }
641
- shock() {
761
+ Object.defineProperty(VRWebViewRTC.prototype, "jsBridge", {
762
+ get: function () {
763
+ return this.options.jsBridge;
764
+ },
765
+ enumerable: false,
766
+ configurable: true
767
+ });
768
+ VRWebViewRTC.prototype.join = function (options) {
769
+ return __awaiter(this, void 0, void 0, function () {
770
+ var _a, sdkAppId, userId, userSig, _b, res, error;
771
+ return __generator(this, function (_c) {
772
+ switch (_c.label) {
773
+ case 0:
774
+ this.emit('joinWillStart');
775
+ return [4 /*yield*/, this.options.getVoiceSign(options)];
776
+ case 1:
777
+ _a = _c.sent(), sdkAppId = _a.sdkAppId, userId = _a.userId, userSig = _a.userSig;
778
+ this.type = options.type;
779
+ return [4 /*yield*/, this.jsBridge.callAndBackfeed("live/join?sdkAppID=".concat(sdkAppId, "&userID=").concat(userId, "&roomID=").concat(Number(options.voiceId), "&userSig=").concat(userSig))];
780
+ case 2:
781
+ _b = _c.sent(), res = _b[0], error = _b[1];
782
+ if (!res) {
783
+ this.emit('error', error ? error : new Error('加入房间失败:未知异常。'));
784
+ this.joined = false;
785
+ }
786
+ else {
787
+ if (res.code === RTCJoinedInfoCodeEnum.Success) {
788
+ this.emit('joined');
789
+ this.joined = true;
790
+ }
791
+ else {
792
+ this.emit('error', res);
793
+ this.joined = false;
794
+ }
795
+ }
796
+ return [2 /*return*/, this.joined];
797
+ }
798
+ });
799
+ });
800
+ };
801
+ VRWebViewRTC.prototype.quit = function () {
802
+ return __awaiter(this, void 0, void 0, function () {
803
+ var _a, res, error;
804
+ return __generator(this, function (_b) {
805
+ switch (_b.label) {
806
+ case 0: return [4 /*yield*/, this.jsBridge.callAndBackfeed('live/quit')];
807
+ case 1:
808
+ _a = _b.sent(), res = _a[0], error = _a[1];
809
+ if (res === null) {
810
+ this.emit('error', error ? error : new Error('退出房间失败:未知异常。'));
811
+ }
812
+ this.joined = false;
813
+ return [2 /*return*/, !!res];
814
+ }
815
+ });
816
+ });
817
+ };
818
+ VRWebViewRTC.prototype.detectMicro = function () {
819
+ return __awaiter(this, void 0, void 0, function () {
820
+ var _a, res, error;
821
+ return __generator(this, function (_b) {
822
+ switch (_b.label) {
823
+ case 0: return [4 /*yield*/, this.jsBridge.detectMicro()];
824
+ case 1:
825
+ _a = _b.sent(), res = _a[0], error = _a[1];
826
+ if (res === null) {
827
+ this.emit('error', error ? error : new Error('麦克风监测异常!'));
828
+ return [2 /*return*/, false];
829
+ }
830
+ return [2 /*return*/, res];
831
+ }
832
+ });
833
+ });
834
+ };
835
+ VRWebViewRTC.prototype.toggleMicro = function (flag) {
836
+ return __awaiter(this, void 0, void 0, function () {
837
+ var _a, res, error;
838
+ return __generator(this, function (_b) {
839
+ switch (_b.label) {
840
+ case 0: return [4 /*yield*/, this.jsBridge.callAndBackfeed("live/toggleMicro?flag=".concat(!!flag ? 1 : 0))];
841
+ case 1:
842
+ _a = _b.sent(), res = _a[0], error = _a[1];
843
+ if (res === null) {
844
+ this.emit('error', error ? error : new Error('麦克风监测异常!'));
845
+ return [2 /*return*/, false];
846
+ }
847
+ this.micro = res;
848
+ return [2 /*return*/, res];
849
+ }
850
+ });
851
+ });
852
+ };
853
+ VRWebViewRTC.prototype.shock = function () {
642
854
  this.jsBridge.shock(1);
643
- }
644
- }
855
+ };
856
+ return VRWebViewRTC;
857
+ }(CoreRTC));
645
858
 
646
859
  /**
647
860
  * WebSocket 通信指令
@@ -726,8 +939,8 @@ var MicroStatus;
726
939
  */
727
940
  function parseLiveMsg(jsonTxt) {
728
941
  try {
729
- const msg = JSON.parse(jsonTxt);
730
- const resMsg = {
942
+ var msg = JSON.parse(jsonTxt);
943
+ var resMsg_1 = {
731
944
  code: msg.code,
732
945
  message: msg.message,
733
946
  command: msg.command,
@@ -738,11 +951,11 @@ function parseLiveMsg(jsonTxt) {
738
951
  triggerUserID: msg.trigger_user_id,
739
952
  data: msg.data || {},
740
953
  };
741
- const undefinedKeys = Object.keys(resMsg).filter((key) => resMsg[key] === undefined);
954
+ var undefinedKeys = Object.keys(resMsg_1).filter(function (key) { return resMsg_1[key] === undefined; });
742
955
  if (undefinedKeys.length > 0) {
743
- console.warn(`推送数据格式异常:${undefinedKeys.join(" ")} 值不存在!`);
956
+ console.warn("\u63A8\u9001\u6570\u636E\u683C\u5F0F\u5F02\u5E38\uFF1A".concat(undefinedKeys.join(" "), " \u503C\u4E0D\u5B58\u5728\uFF01"));
744
957
  }
745
- return resMsg;
958
+ return resMsg_1;
746
959
  }
747
960
  catch (error) {
748
961
  // notcare? 过滤掉所有不符合规范的数据
@@ -880,16 +1093,19 @@ function parseWSClsErr(code) {
880
1093
  }
881
1094
 
882
1095
  function appendUri(uri, query) {
883
- const hasQuery = uri.indexOf('?') !== -1;
884
- const newQuery = Object.keys(query).reduce((accu, curr, idx) => `${accu}${(idx === 0 && !hasQuery) ? '?' : '&'}${curr}=${query[curr]}`, '');
1096
+ if (query === void 0) { query = {}; }
1097
+ var hasQuery = uri.indexOf('?') !== -1;
1098
+ var newQuery = Object.keys(query).reduce(function (accu, curr, idx) {
1099
+ return "".concat(accu).concat((idx === 0 && !hasQuery) ? '?' : '&').concat(curr, "=").concat(query[curr]);
1100
+ }, '');
885
1101
  return uri + newQuery;
886
1102
  }
887
1103
 
888
- const userAgent = globalThis.navigator.userAgent;
889
- const isAndroid = /android/gi.test(userAgent);
890
- const isIOS = /iPhone|iPad\s+OS/gi.test(userAgent);
891
- const isWxMiniProgram = /MicroMessenger/gi.test(userAgent) && /miniProgram/gi.test(userAgent);
892
- const isRealseeVRWebview = /realsee/gi.test(userAgent);
1104
+ var userAgent = globalThis.navigator.userAgent;
1105
+ var isAndroid = /android/gi.test(userAgent);
1106
+ var isIOS = /iPhone|iPad\s+OS/gi.test(userAgent);
1107
+ var isWxMiniProgram = /MicroMessenger/gi.test(userAgent) && /miniProgram/gi.test(userAgent);
1108
+ var isRealseeVRWebview = /realsee/gi.test(userAgent);
893
1109
 
894
1110
  /**
895
1111
  * 判断是否是真实的对象类型
@@ -921,12 +1137,12 @@ function baseIsEqual(value, other) {
921
1137
  * @returns
922
1138
  */
923
1139
  function objEqualShallow(value, other) {
924
- const valueProps = Object.getOwnPropertyNames(value);
925
- const otherProps = Object.getOwnPropertyNames(other);
1140
+ var valueProps = Object.getOwnPropertyNames(value);
1141
+ var otherProps = Object.getOwnPropertyNames(other);
926
1142
  if (valueProps.length !== otherProps.length)
927
1143
  return false;
928
- for (let i = 0, len = valueProps.length; i < len; i++) {
929
- const propName = valueProps[i];
1144
+ for (var i = 0, len = valueProps.length; i < len; i++) {
1145
+ var propName = valueProps[i];
930
1146
  if (!baseIsEqual(value[propName], other[propName]))
931
1147
  return false;
932
1148
  }
@@ -941,7 +1157,7 @@ function objEqualShallow(value, other) {
941
1157
  function arrayEqualShallow(value, other) {
942
1158
  if (value.length !== other.length)
943
1159
  return false;
944
- for (let i = 0, len = value.length; i < len; i++) {
1160
+ for (var i = 0, len = value.length; i < len; i++) {
945
1161
  if (!baseIsEqual(value[i], other[i]))
946
1162
  return false;
947
1163
  }
@@ -986,7 +1202,7 @@ function isDeepEqual(value, other) {
986
1202
  function arrayEqualDeep(value, other) {
987
1203
  if (value.length !== other.length)
988
1204
  return false;
989
- for (let i = 0, len = value.length; i < len; i++) {
1205
+ for (var i = 0, len = value.length; i < len; i++) {
990
1206
  if (!isDeepEqual(value[i], other[i]))
991
1207
  return false;
992
1208
  }
@@ -999,12 +1215,12 @@ function arrayEqualDeep(value, other) {
999
1215
  * @returns
1000
1216
  */
1001
1217
  function objEqualDeep(value, other) {
1002
- const valueProps = Object.getOwnPropertyNames(value);
1003
- const otherProps = Object.getOwnPropertyNames(other);
1218
+ var valueProps = Object.getOwnPropertyNames(value);
1219
+ var otherProps = Object.getOwnPropertyNames(other);
1004
1220
  if (valueProps.length !== otherProps.length)
1005
1221
  return false;
1006
- for (let i = 0, len = valueProps.length; i < len; i++) {
1007
- const propName = valueProps[i];
1222
+ for (var i = 0, len = valueProps.length; i < len; i++) {
1223
+ var propName = valueProps[i];
1008
1224
  if (!isDeepEqual(value[propName], other[propName]))
1009
1225
  return false;
1010
1226
  }
@@ -1018,13 +1234,15 @@ function objEqualDeep(value, other) {
1018
1234
  * @returns {boolean} 是否相等。
1019
1235
  */
1020
1236
  function equal(value, other, opt) {
1237
+ if (opt === void 0) { opt = { deep: false }; }
1021
1238
  if (!opt.deep)
1022
1239
  return isShallowEqual(value, other);
1023
1240
  return isDeepEqual(value, other);
1024
1241
  }
1025
1242
 
1026
- class LiveController {
1027
- constructor(options) {
1243
+ var LiveController = /** @class */ (function () {
1244
+ function LiveController(options) {
1245
+ var _this = this;
1028
1246
  this.readyState = WebSocketState.NOTINITIALIZED;
1029
1247
  this.canSync = true;
1030
1248
  this.connecting = false;
@@ -1032,55 +1250,57 @@ class LiveController {
1032
1250
  /**
1033
1251
  * 检测 WebSocket.readyState 状态
1034
1252
  */
1035
- this.checkReadyState = (live) => {
1253
+ this.checkReadyState = function (live) {
1036
1254
  do {
1037
- if (!this.webSocket) {
1038
- if (this.readyState !== WebSocketState.NOTINITIALIZED) {
1039
- this.readyState = WebSocketState.NOTINITIALIZED;
1040
- live.emit('ws.readyStateUpdate', this.readyState);
1255
+ if (!_this.webSocket) {
1256
+ if (_this.readyState !== WebSocketState.NOTINITIALIZED) {
1257
+ _this.readyState = WebSocketState.NOTINITIALIZED;
1258
+ live.emit('ws.readyStateUpdate', _this.readyState);
1041
1259
  }
1042
1260
  break;
1043
1261
  }
1044
- const readyState = this.webSocket.readyState;
1045
- if (readyState !== this.readyState) {
1046
- this.readyState = readyState;
1047
- live.emit('ws.readyStateUpdate', this.readyState);
1262
+ var readyState = _this.webSocket.readyState;
1263
+ if (readyState !== _this.readyState) {
1264
+ _this.readyState = readyState;
1265
+ live.emit('ws.readyStateUpdate', _this.readyState);
1048
1266
  }
1049
1267
  } while (false);
1050
- return this.readyState;
1268
+ return _this.readyState;
1051
1269
  };
1052
- this.dispose = () => {
1053
- this.disposeWebSocket();
1054
- this.connecting = false;
1055
- if (this.healthCheckId) {
1056
- clearInterval(this.healthCheckId);
1057
- this.healthCheckId = undefined;
1270
+ this.dispose = function () {
1271
+ _this.disposeWebSocket();
1272
+ _this.connecting = false;
1273
+ if (_this.healthCheckId) {
1274
+ clearInterval(_this.healthCheckId);
1275
+ _this.healthCheckId = undefined;
1058
1276
  }
1277
+ return true;
1059
1278
  };
1060
1279
  /**
1061
1280
  * 销毁WebSocket相关依赖。
1062
1281
  */
1063
- this.disposeWebSocket = () => {
1064
- if (!this.webSocket)
1282
+ this.disposeWebSocket = function () {
1283
+ if (!_this.webSocket)
1065
1284
  return;
1066
- if (this.onEvtOpnListener) {
1067
- this.webSocket.removeEventListener('open', this.onEvtOpnListener);
1068
- this.onEvtOpnListener = undefined;
1285
+ if (_this.onEvtOpnListener) {
1286
+ _this.webSocket.removeEventListener('open', _this.onEvtOpnListener);
1287
+ _this.onEvtOpnListener = undefined;
1069
1288
  }
1070
- if (this.onEvtMsgListener) {
1071
- this.webSocket.removeEventListener('message', this.onEvtMsgListener);
1072
- this.onEvtMsgListener = undefined;
1289
+ if (_this.onEvtMsgListener) {
1290
+ _this.webSocket.removeEventListener('message', _this.onEvtMsgListener);
1291
+ _this.onEvtMsgListener = undefined;
1073
1292
  }
1074
- if (this.onEvtErrListener) {
1075
- this.webSocket.removeEventListener('error', this.onEvtErrListener);
1076
- this.onEvtErrListener = undefined;
1293
+ if (_this.onEvtErrListener) {
1294
+ _this.webSocket.removeEventListener('error', _this.onEvtErrListener);
1295
+ _this.onEvtErrListener = undefined;
1077
1296
  }
1078
- if (this.onEvtCLEListener) {
1079
- this.webSocket.removeEventListener('close', this.onEvtCLEListener);
1080
- this.onEvtCLEListener = undefined;
1297
+ if (_this.onEvtCLEListener) {
1298
+ _this.webSocket.removeEventListener('close', _this.onEvtCLEListener);
1299
+ _this.onEvtCLEListener = undefined;
1081
1300
  }
1082
- this.webSocket.close();
1083
- this.webSocket = undefined;
1301
+ _this.webSocket.close();
1302
+ _this.webSocket = undefined;
1303
+ return true;
1084
1304
  };
1085
1305
  this.options = Object.assign({ autoConnect: true, healthCheck: 3000 }, options);
1086
1306
  }
@@ -1089,16 +1309,17 @@ class LiveController {
1089
1309
  * @param liveMsg
1090
1310
  * @param live
1091
1311
  */
1092
- handleMessage(liveMsg, live) {
1312
+ LiveController.prototype.handleMessage = function (liveMsg, live) {
1313
+ var _this = this;
1093
1314
  var _a, _b, _c;
1094
- const { command, data, frontRequestId, code, message } = liveMsg;
1315
+ var command = liveMsg.command, data = liveMsg.data, frontRequestId = liveMsg.frontRequestId, code = liveMsg.code;
1095
1316
  if (code === 'SUCCESS') {
1096
1317
  switch (command) {
1097
1318
  /**
1098
1319
  * 自己的状态变化
1099
1320
  */
1100
1321
  case Command.SelfUserInfo: {
1101
- const selfInfo = data;
1322
+ var selfInfo = data;
1102
1323
  if (equal(this.selfUserInfo, selfInfo, { deep: true }))
1103
1324
  return;
1104
1325
  this.selfUserInfo = selfInfo;
@@ -1109,7 +1330,7 @@ class LiveController {
1109
1330
  * 房间信息变化
1110
1331
  */
1111
1332
  case Command.RoomInfo: {
1112
- const roomInfo = data;
1333
+ var roomInfo = data;
1113
1334
  this.roomInfo = Object.assign({}, roomInfo);
1114
1335
  live.emit('readyKeyframeSync', (roomInfo.last_frame || {}));
1115
1336
  break;
@@ -1118,16 +1339,16 @@ class LiveController {
1118
1339
  * 语音信息变化
1119
1340
  */
1120
1341
  case Command.RTCInfo: {
1121
- const { voice_id: voiceId, type } = data;
1342
+ var _d = data, voiceId = _d.voice_id, type = _d.type;
1122
1343
  /* 如果已经进入语音房间,则不重复进入 --> "RTCInfo" 指令可能会下发多次 */
1123
1344
  if (live.$RTC.joined) {
1124
1345
  break;
1125
1346
  }
1126
1347
  live.$RTC.join({
1127
- voiceId,
1348
+ voiceId: voiceId,
1128
1349
  userId: ((_a = this.selfUserInfo) === null || _a === void 0 ? void 0 : _a.id) || '',
1129
1350
  roomId: (_b = this.roomInfo) === null || _b === void 0 ? void 0 : _b.info.room_code,
1130
- type,
1351
+ type: type,
1131
1352
  });
1132
1353
  // 加入房间后 麦克风默认就开启了:需要发个指令。
1133
1354
  live.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserMicroStatus, {
@@ -1139,7 +1360,7 @@ class LiveController {
1139
1360
  * 房间用户列表变化
1140
1361
  */
1141
1362
  case Command.UserList: {
1142
- const userList = data;
1363
+ var userList = data;
1143
1364
  this.userList = userList;
1144
1365
  live.emit('userListUpdate', this.userList, frontRequestId);
1145
1366
  break;
@@ -1148,7 +1369,7 @@ class LiveController {
1148
1369
  * 自定义事件广播
1149
1370
  */
1150
1371
  case Command.CustomEvent: {
1151
- const evtMsg = data;
1372
+ var evtMsg = data;
1152
1373
  live.emit('broadcast', evtMsg, frontRequestId);
1153
1374
  break;
1154
1375
  }
@@ -1156,21 +1377,22 @@ class LiveController {
1156
1377
  * 帧数据同步
1157
1378
  */
1158
1379
  case Command.KeyframeSync: {
1159
- const remoteKeyframes = data;
1380
+ var remoteKeyframes_1 = data;
1160
1381
  // 此处做一层 diff,仅跟本地数据不一致的情况下才广播数据。
1161
- const keyframes = Object.keys(remoteKeyframes).reduce((accu, curr) => {
1162
- if (equal(remoteKeyframes[curr], this.keyframes[curr], { deep: true })) {
1382
+ var keyframes = Object.keys(remoteKeyframes_1).reduce(function (accu, curr) {
1383
+ var _a;
1384
+ if (equal(remoteKeyframes_1[curr], _this.keyframes[curr], { deep: true })) {
1163
1385
  return accu;
1164
1386
  }
1165
- const params = [
1166
- remoteKeyframes[curr],
1167
- this.keyframes[curr],
1387
+ var params = [
1388
+ remoteKeyframes_1[curr],
1389
+ _this.keyframes[curr],
1168
1390
  frontRequestId,
1169
1391
  ];
1170
- const evtName = curr;
1171
- live.keyframes.emit(evtName, ...params);
1172
- this.keyframes[curr] = remoteKeyframes[curr];
1173
- accu[curr] = remoteKeyframes[curr];
1392
+ var evtName = curr;
1393
+ (_a = live.keyframes).emit.apply(_a, __spreadArray([evtName], params, false));
1394
+ _this.keyframes[curr] = remoteKeyframes_1[curr];
1395
+ accu[curr] = remoteKeyframes_1[curr];
1174
1396
  return accu;
1175
1397
  }, {});
1176
1398
  live.emit('keyframes', keyframes, frontRequestId);
@@ -1180,7 +1402,7 @@ class LiveController {
1180
1402
  * 内置消息
1181
1403
  */
1182
1404
  case Command.BuiltinMsg: {
1183
- const builtinMsg = data;
1405
+ var builtinMsg = data;
1184
1406
  live.emit('builtinEvent', builtinMsg);
1185
1407
  if (builtinMsg.event_type === BuiltinEventType.UserChange) {
1186
1408
  live.emit('userChange', builtinMsg);
@@ -1223,27 +1445,31 @@ class LiveController {
1223
1445
  else {
1224
1446
  live.emit('error', liveMsg);
1225
1447
  }
1226
- }
1448
+ };
1227
1449
  /**
1228
1450
  * 发送数据
1229
1451
  * @param data
1230
1452
  */
1231
- sendMessage(data) {
1453
+ LiveController.prototype.sendMessage = function (data) {
1232
1454
  if (!this.webSocket)
1233
1455
  return console.warn('WebSocket has not yet been initialized!');
1234
1456
  if (!data)
1235
1457
  return console.warn('WebSocket messages is empty!');
1236
1458
  this.webSocket.send(JSON.stringify(data));
1237
- }
1238
- }
1459
+ };
1460
+ return LiveController;
1461
+ }());
1239
1462
 
1240
- const unimplementedGetVoiceSign = (params) => Promise.reject('unimplemented method GetVoiceSign');
1463
+ var unimplementedGetVoiceSign = function (params) {
1464
+ return Promise.reject('unimplemented method GetVoiceSign');
1465
+ };
1241
1466
  /**
1242
1467
  * 创建 `live` 实例。
1243
1468
  */
1244
1469
  function createLive(options) {
1245
- const liveController = new LiveController(options);
1246
- const createLiveMsg = (command, data = {}, toUserIds) => {
1470
+ var liveController = new LiveController(options);
1471
+ var createLiveMsg = function (command, data, toUserIds) {
1472
+ if (data === void 0) { data = {}; }
1247
1473
  toUserIds = toUserIds
1248
1474
  ? Array.isArray(toUserIds)
1249
1475
  ? toUserIds
@@ -1251,14 +1477,16 @@ function createLive(options) {
1251
1477
  : [];
1252
1478
  if (toUserIds)
1253
1479
  data['to_user_ids'] = toUserIds;
1254
- return { command, front_request_id: uuid(), data };
1480
+ return { command: command, front_request_id: uuid(), data: data };
1255
1481
  };
1256
- class LiveTpl extends Subscribe {
1257
- constructor() {
1482
+ var LiveTpl = /** @class */ (function (_super) {
1483
+ __extends(LiveTpl, _super);
1484
+ function LiveTpl() {
1485
+ var _this = this;
1258
1486
  var _a, _b;
1259
- super();
1260
- this.keyframes = new Subscribe();
1261
- const jsBridge = (() => {
1487
+ _this = _super.call(this) || this;
1488
+ _this.keyframes = new Subscribe();
1489
+ var jsBridge = (function () {
1262
1490
  if (options.jsBridge)
1263
1491
  return options.jsBridge;
1264
1492
  if (options.useBuiltInJsBridge)
@@ -1273,7 +1501,7 @@ function createLive(options) {
1273
1501
  if (!options.getVoiceSign) {
1274
1502
  throw new Error('GetVoiceSign method must be passed when using built-in RTC instances');
1275
1503
  }
1276
- const getVoiceSign = (_a = options.getVoiceSign) !== null && _a !== void 0 ? _a : unimplementedGetVoiceSign;
1504
+ var getVoiceSign = (_a = options.getVoiceSign) !== null && _a !== void 0 ? _a : unimplementedGetVoiceSign;
1277
1505
  switch (options.rtcType) {
1278
1506
  case RTCType.RealseeVRWebViewRTC: {
1279
1507
  // 内置的 VRWebViewRTC
@@ -1281,15 +1509,15 @@ function createLive(options) {
1281
1509
  throw new Error('JsBridge instance must be passed when using built-in VRWebViewRTC instances');
1282
1510
  }
1283
1511
  liveController.options.rtc = new VRWebViewRTC({
1284
- jsBridge,
1285
- getVoiceSign,
1512
+ jsBridge: jsBridge,
1513
+ getVoiceSign: getVoiceSign,
1286
1514
  });
1287
1515
  break;
1288
1516
  }
1289
1517
  case RTCType.RealseeBrowserChimeRTC: {
1290
1518
  // 内置的 RealseeBrowserChimeRTC
1291
1519
  liveController.options.rtc = new BrowserRTC4Chime({
1292
- getVoiceSign,
1520
+ getVoiceSign: getVoiceSign,
1293
1521
  logLevel: options.__debug__ ? LogLevel.DEBUG : LogLevel.ERROR,
1294
1522
  });
1295
1523
  break;
@@ -1297,7 +1525,7 @@ function createLive(options) {
1297
1525
  case RTCType.RealseeBrowserRTC: {
1298
1526
  // 内置的 RealseeBrowserRTC
1299
1527
  liveController.options.rtc = new BrowserRTC({
1300
- getVoiceSign,
1528
+ getVoiceSign: getVoiceSign,
1301
1529
  });
1302
1530
  break;
1303
1531
  }
@@ -1311,23 +1539,23 @@ function createLive(options) {
1311
1539
  if (!options.getVoiceSign) {
1312
1540
  throw new Error('GetVoiceSign method must be passed when using built-in RTC instances');
1313
1541
  }
1314
- const getVoiceSign = (_b = options.getVoiceSign) !== null && _b !== void 0 ? _b : unimplementedGetVoiceSign;
1542
+ var getVoiceSign = (_b = options.getVoiceSign) !== null && _b !== void 0 ? _b : unimplementedGetVoiceSign;
1315
1543
  if (!jsBridge) {
1316
1544
  throw new Error('jsBridge instance must be passed when using built-in RTC instances');
1317
1545
  }
1318
1546
  // vrwebview 默认
1319
1547
  if ((isRealseeVRWebview && (isAndroid || isIOS)) || isWxMiniProgram) {
1320
1548
  liveController.options.rtc = new VRWebViewRTC({
1321
- jsBridge,
1322
- getVoiceSign,
1549
+ jsBridge: jsBridge,
1550
+ getVoiceSign: getVoiceSign,
1323
1551
  });
1324
1552
  }
1325
1553
  else {
1326
1554
  // 其它终端使用
1327
1555
  liveController.options.rtc =
1328
1556
  options.builtInRTCType === BuiltInRTCType.RealseeXChimeRTC
1329
- ? new BrowserRTC4Chime({ getVoiceSign })
1330
- : new BrowserRTC({ getVoiceSign });
1557
+ ? new BrowserRTC4Chime({ getVoiceSign: getVoiceSign })
1558
+ : new BrowserRTC({ getVoiceSign: getVoiceSign });
1331
1559
  }
1332
1560
  }
1333
1561
  }
@@ -1336,282 +1564,407 @@ function createLive(options) {
1336
1564
  }
1337
1565
  // 默认自动连接
1338
1566
  if (liveController.options.url && liveController.options.getTicket) {
1339
- this.connect();
1567
+ _this.connect();
1340
1568
  }
1341
1569
  // 健康检查:WHY --> 在某些WebView特殊场景下 WebSocket.readyState 发生变化时不会出发error\close等事件;
1342
1570
  // 因此,开启一个定时任务监测 WebSocket.readyState 状态的更新
1343
- const healthCheck = ((healthCheck) => {
1571
+ var healthCheck = (function (healthCheck) {
1344
1572
  if (!healthCheck)
1345
1573
  return 0;
1346
1574
  if (healthCheck === true)
1347
1575
  return 3000;
1348
- const duration = Number(healthCheck);
1576
+ var duration = Number(healthCheck);
1349
1577
  if (duration > 0)
1350
1578
  return duration;
1351
1579
  return 3000;
1352
1580
  })(liveController.options.healthCheck);
1353
1581
  if (healthCheck) {
1354
- liveController.healthCheckId = setInterval(() => liveController.checkReadyState(this), healthCheck);
1355
- }
1356
- }
1357
- get options() {
1358
- return Object.freeze(Object.assign({}, liveController.options));
1359
- }
1360
- get readyState() {
1361
- liveController.checkReadyState(this);
1362
- return liveController.readyState;
1363
- }
1364
- get url() {
1365
- var _a;
1366
- return ((_a = liveController.webSocket) === null || _a === void 0 ? void 0 : _a.url) || '';
1367
- }
1368
- get selfInfo() {
1369
- return liveController.selfUserInfo;
1370
- }
1371
- get userList() {
1372
- return liveController.userList || [];
1373
- }
1374
- get snapshot() {
1375
- return liveController.keyframes || {};
1376
- }
1377
- get $RTC() {
1378
- return liveController.options.rtc;
1379
- }
1380
- get jsBridge() {
1381
- return liveController.options.jsBridge;
1382
- }
1383
- async setSelfInfo(userInfo) {
1384
- if (this.readyState !== WebSocketState.OPEN) {
1385
- return new Error('The connection is not open and ready to communicate.');
1386
- }
1387
- try {
1388
- return await this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserInfo, userInfo);
1389
- }
1390
- catch (error) {
1391
- return error;
1582
+ liveController.healthCheckId = setInterval(function () { return liveController.checkReadyState(_this); }, healthCheck);
1392
1583
  }
1584
+ return _this;
1393
1585
  }
1394
- getFramesByKey(key) {
1586
+ Object.defineProperty(LiveTpl.prototype, "options", {
1587
+ get: function () {
1588
+ return Object.freeze(Object.assign({}, liveController.options));
1589
+ },
1590
+ enumerable: false,
1591
+ configurable: true
1592
+ });
1593
+ Object.defineProperty(LiveTpl.prototype, "readyState", {
1594
+ get: function () {
1595
+ liveController.checkReadyState(this);
1596
+ return liveController.readyState;
1597
+ },
1598
+ enumerable: false,
1599
+ configurable: true
1600
+ });
1601
+ Object.defineProperty(LiveTpl.prototype, "url", {
1602
+ get: function () {
1603
+ var _a;
1604
+ return ((_a = liveController.webSocket) === null || _a === void 0 ? void 0 : _a.url) || '';
1605
+ },
1606
+ enumerable: false,
1607
+ configurable: true
1608
+ });
1609
+ Object.defineProperty(LiveTpl.prototype, "selfInfo", {
1610
+ get: function () {
1611
+ return liveController.selfUserInfo;
1612
+ },
1613
+ enumerable: false,
1614
+ configurable: true
1615
+ });
1616
+ Object.defineProperty(LiveTpl.prototype, "userList", {
1617
+ get: function () {
1618
+ return liveController.userList || [];
1619
+ },
1620
+ enumerable: false,
1621
+ configurable: true
1622
+ });
1623
+ Object.defineProperty(LiveTpl.prototype, "snapshot", {
1624
+ get: function () {
1625
+ return liveController.keyframes || {};
1626
+ },
1627
+ enumerable: false,
1628
+ configurable: true
1629
+ });
1630
+ Object.defineProperty(LiveTpl.prototype, "$RTC", {
1631
+ get: function () {
1632
+ return liveController.options.rtc;
1633
+ },
1634
+ enumerable: false,
1635
+ configurable: true
1636
+ });
1637
+ Object.defineProperty(LiveTpl.prototype, "jsBridge", {
1638
+ get: function () {
1639
+ return liveController.options.jsBridge;
1640
+ },
1641
+ enumerable: false,
1642
+ configurable: true
1643
+ });
1644
+ LiveTpl.prototype.setSelfInfo = function (userInfo) {
1645
+ return __awaiter(this, void 0, void 0, function () {
1646
+ var error_1;
1647
+ return __generator(this, function (_a) {
1648
+ switch (_a.label) {
1649
+ case 0:
1650
+ if (this.readyState !== WebSocketState.OPEN) {
1651
+ return [2 /*return*/, new Error('The connection is not open and ready to communicate.')];
1652
+ }
1653
+ _a.label = 1;
1654
+ case 1:
1655
+ _a.trys.push([1, 3, , 4]);
1656
+ return [4 /*yield*/, this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserInfo, userInfo)];
1657
+ case 2: return [2 /*return*/, _a.sent()];
1658
+ case 3:
1659
+ error_1 = _a.sent();
1660
+ return [2 /*return*/, error_1];
1661
+ case 4: return [2 /*return*/];
1662
+ }
1663
+ });
1664
+ });
1665
+ };
1666
+ LiveTpl.prototype.getFramesByKey = function (key) {
1395
1667
  return liveController.keyframes[key];
1396
- }
1397
- sendKeyframe(key, frame) {
1668
+ };
1669
+ LiveTpl.prototype.sendKeyframe = function (key, frame) {
1398
1670
  if (this.readyState !== WebSocketState.OPEN) {
1399
1671
  return new Error('The connection is not open and ready to communicate.');
1400
1672
  }
1401
1673
  liveController.keyframes[key] = frame;
1402
- const liveMsg = createLiveMsg(Command.KeyframeSync, this.snapshot);
1674
+ var liveMsg = createLiveMsg(Command.KeyframeSync, this.snapshot);
1403
1675
  liveController.sendMessage(liveMsg);
1404
1676
  return true;
1405
- }
1406
- broadcast(data, toUserIds, timeout) {
1677
+ };
1678
+ LiveTpl.prototype.broadcast = function (data, toUserIds, timeout) {
1679
+ var _this = this;
1407
1680
  if (this.readyState !== WebSocketState.OPEN) {
1408
1681
  return new Error('The connection is not open and ready to communicate.');
1409
1682
  }
1410
- return new Promise((resolve, reject) => {
1411
- const customEvent = createLiveMsg(Command.CustomEvent, data, toUserIds);
1412
- const front_request_id = customEvent.front_request_id;
1683
+ return new Promise(function (resolve, reject) {
1684
+ var customEvent = createLiveMsg(Command.CustomEvent, data, toUserIds);
1685
+ var front_request_id = customEvent.front_request_id;
1413
1686
  liveController.sendMessage(customEvent);
1414
- const timeoutId = timeout
1415
- ? setTimeout(() => {
1687
+ var timeoutId = timeout
1688
+ ? setTimeout(function () {
1416
1689
  reject(new Error('RESPONSE TIMEOUT'));
1417
- this.off('broadcast', broadcast);
1690
+ _this.off('broadcast', broadcast);
1418
1691
  }, timeout)
1419
1692
  : undefined;
1420
- const broadcast = (data, frontRequestId) => {
1693
+ var broadcast = function (data, frontRequestId) {
1421
1694
  if (frontRequestId !== front_request_id)
1422
1695
  return;
1423
- this.off('broadcast', broadcast);
1696
+ _this.off('broadcast', broadcast);
1424
1697
  resolve(data);
1425
1698
  if (timeoutId)
1426
1699
  clearInterval(timeoutId);
1427
1700
  };
1428
- this.on('broadcast', broadcast);
1701
+ _this.on('broadcast', broadcast);
1429
1702
  });
1430
- }
1431
- async updateStatus(evtType, atnType, status, toUserIds) {
1432
- // TODO 统一规则,不能联合类型
1433
- if (this.readyState !== WebSocketState.OPEN) {
1434
- return false;
1435
- }
1436
- const data = Object.assign({ event_type: evtType, action: atnType }, { data: status });
1437
- const liveMsg = createLiveMsg(Command.BuiltinMsg, data, toUserIds);
1438
- liveController.sendMessage(liveMsg);
1439
- return true;
1440
- }
1703
+ };
1704
+ LiveTpl.prototype.updateStatus = function (evtType, atnType, status, toUserIds) {
1705
+ return __awaiter(this, void 0, void 0, function () {
1706
+ var data, liveMsg;
1707
+ return __generator(this, function (_a) {
1708
+ // TODO 统一规则,不能联合类型
1709
+ if (this.readyState !== WebSocketState.OPEN) {
1710
+ return [2 /*return*/, false];
1711
+ }
1712
+ data = Object.assign({ event_type: evtType, action: atnType }, { data: status });
1713
+ liveMsg = createLiveMsg(Command.BuiltinMsg, data, toUserIds);
1714
+ liveController.sendMessage(liveMsg);
1715
+ return [2 /*return*/, true];
1716
+ });
1717
+ });
1718
+ };
1441
1719
  // 仅用于用户自己的麦克风控制
1442
- async toggleMicro(microStatus) {
1720
+ LiveTpl.prototype.toggleMicro = function (microStatus) {
1443
1721
  var _a, _b;
1444
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_own_micro))
1445
- return false;
1446
- await this.$RTC.toggleMicro(microStatus);
1447
- return await this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserMicroStatus, {
1448
- status: microStatus ? MicroStatus.OPEN : MicroStatus.CLOSE,
1449
- }, []);
1450
- }
1451
- async forbidMicro(microStatus, toUserIds) {
1722
+ return __awaiter(this, void 0, void 0, function () {
1723
+ return __generator(this, function (_c) {
1724
+ switch (_c.label) {
1725
+ case 0:
1726
+ if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_own_micro))
1727
+ return [2 /*return*/, false];
1728
+ return [4 /*yield*/, this.$RTC.toggleMicro(microStatus)];
1729
+ case 1:
1730
+ _c.sent();
1731
+ return [4 /*yield*/, this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserMicroStatus, {
1732
+ status: microStatus ? MicroStatus.OPEN : MicroStatus.CLOSE,
1733
+ }, [])];
1734
+ case 2: return [2 /*return*/, _c.sent()];
1735
+ }
1736
+ });
1737
+ });
1738
+ };
1739
+ LiveTpl.prototype.forbidMicro = function (microStatus, toUserIds) {
1452
1740
  var _a, _b;
1453
- if (liveController.options.canForbidUserMicro &&
1454
- !liveController.options.canForbidUserMicro(toUserIds)) {
1455
- return false;
1456
- }
1457
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_other_micro)) {
1458
- return false;
1459
- }
1460
- return await this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserMicroStatus, {
1461
- status: microStatus,
1462
- }, toUserIds);
1463
- }
1741
+ return __awaiter(this, void 0, void 0, function () {
1742
+ return __generator(this, function (_c) {
1743
+ switch (_c.label) {
1744
+ case 0:
1745
+ if (liveController.options.canForbidUserMicro &&
1746
+ !liveController.options.canForbidUserMicro(toUserIds)) {
1747
+ return [2 /*return*/, false];
1748
+ }
1749
+ if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_other_micro)) {
1750
+ return [2 /*return*/, false];
1751
+ }
1752
+ return [4 /*yield*/, this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserMicroStatus, {
1753
+ status: microStatus,
1754
+ }, toUserIds)];
1755
+ case 1: return [2 /*return*/, _c.sent()];
1756
+ }
1757
+ });
1758
+ });
1759
+ };
1464
1760
  /**
1465
1761
  * @deprecated 暂不可用
1466
1762
  */
1467
- async forbidSync(sync, toUserIds) {
1763
+ LiveTpl.prototype.forbidSync = function (sync, toUserIds) {
1468
1764
  var _a, _b;
1469
- if (liveController.options.canForbidUserSync &&
1470
- !liveController.options.canForbidUserSync(toUserIds)) {
1471
- return false;
1472
- }
1473
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_other_sync)) {
1474
- return false;
1475
- }
1476
- return await this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserPermission, { sync_frame: sync }, toUserIds);
1477
- }
1478
- async kick(toUserIds) {
1765
+ return __awaiter(this, void 0, void 0, function () {
1766
+ return __generator(this, function (_c) {
1767
+ switch (_c.label) {
1768
+ case 0:
1769
+ if (liveController.options.canForbidUserSync &&
1770
+ !liveController.options.canForbidUserSync(toUserIds)) {
1771
+ return [2 /*return*/, false];
1772
+ }
1773
+ if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_other_sync)) {
1774
+ return [2 /*return*/, false];
1775
+ }
1776
+ return [4 /*yield*/, this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserPermission, { sync_frame: sync }, toUserIds)];
1777
+ case 1: return [2 /*return*/, _c.sent()];
1778
+ }
1779
+ });
1780
+ });
1781
+ };
1782
+ LiveTpl.prototype.kick = function (toUserIds) {
1479
1783
  var _a, _b;
1480
- if (liveController.options.canForbidUserKick &&
1481
- !liveController.options.canForbidUserKick(toUserIds)) {
1482
- return false;
1483
- }
1484
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.change_other_status)) {
1485
- return false;
1486
- }
1487
- return await this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserStatus, {
1488
- status: 'KICK_OUT',
1489
- }, toUserIds);
1490
- }
1491
- async exit() {
1492
- /** 退出强制关闭语音(?) */
1493
- await this.$RTC.quit();
1494
- return await this.updateStatus(BuiltinEventType.RoomChange, BuiltinActionType.RoomClose, {});
1495
- }
1496
- async connect(options = {}) {
1497
- // 连接 WebSocket 前验证麦克风权限
1498
- const microAuth = await this.$RTC.detectMicro();
1499
- if (!microAuth) {
1500
- const error = new Error('系统监测麦克风未授权~');
1501
- this.emit('ws.error', { type: WebSocketErrorType.MicroAuth, error });
1502
- return error;
1503
- }
1504
- // WebSocket 正在连接中,规避重复连接
1505
- if (liveController.connecting) {
1506
- const error = new Error('WebSocket 正在连接中,请勿重复连接 ...');
1507
- this.emit('ws.error', {
1508
- type: WebSocketErrorType.DuplicateConnect,
1509
- error,
1784
+ return __awaiter(this, void 0, void 0, function () {
1785
+ return __generator(this, function (_c) {
1786
+ switch (_c.label) {
1787
+ case 0:
1788
+ if (liveController.options.canForbidUserKick &&
1789
+ !liveController.options.canForbidUserKick(toUserIds)) {
1790
+ return [2 /*return*/, false];
1791
+ }
1792
+ if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.change_other_status)) {
1793
+ return [2 /*return*/, false];
1794
+ }
1795
+ return [4 /*yield*/, this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserStatus, {
1796
+ status: 'KICK_OUT',
1797
+ }, toUserIds)];
1798
+ case 1: return [2 /*return*/, _c.sent()];
1799
+ }
1510
1800
  });
1511
- return error;
1512
- }
1513
- // 非强制连接场景下,如果已经完成 WebSocket 连接则不执行后续逻辑
1514
- const { force } = options;
1515
- if (!force) {
1516
- if (this.readyState === WebSocketState.CONNECTING ||
1517
- this.readyState === WebSocketState.OPEN) {
1518
- return true;
1519
- }
1520
- }
1521
- // WebSocket URL 逻辑
1522
- if (options.url) {
1523
- liveController.options.url = options.url;
1524
- }
1525
- if (options.getTicket) {
1526
- liveController.options.getTicket = options.getTicket;
1527
- }
1528
- if (!liveController.options.url ||
1529
- !liveController.options.url.startsWith('ws')) {
1530
- const error = new Error(`WebSocket URL 未配置或格式不合法:"${liveController.options.url}"`);
1531
- this.emit('ws.error', { type: WebSocketErrorType.IllegalURL, error });
1532
- return error;
1533
- }
1534
- if (!liveController.options.getTicket) {
1535
- const error = new Error(`getTicket() 未配置!`);
1536
- this.emit('ws.error', { type: WebSocketErrorType.IllegalArgs, error });
1537
- return error;
1538
- }
1539
- // 连接锁
1540
- liveController.connecting = true;
1541
- // 连接前销毁之前绑定的事件
1542
- liveController.disposeWebSocket();
1543
- this.emit('ws.beforeConnect');
1544
- const url = force || options.url || !this.url
1545
- ? appendUri(liveController.options.url, {
1546
- ticket: await liveController.options.getTicket(),
1547
- force: Number(!!force),
1548
- })
1549
- : this.url;
1550
- liveController.webSocket = new WebSocket(url);
1551
- liveController.onEvtOpnListener = () => {
1552
- liveController.checkReadyState(this);
1553
- this.emit('ws.afterConnect');
1554
- };
1555
- liveController.onEvtMsgListener = (evt) => {
1556
- liveController.checkReadyState(this);
1557
- try {
1558
- const liveMsg = parseLiveMsg(evt.data);
1559
- if (liveMsg === false)
1560
- return;
1561
- liveController.handleMessage(liveMsg, this);
1562
- }
1563
- catch (error) {
1564
- // 未知错误
1565
- this.emit('ws.error', {
1566
- type: WebSocketErrorType.Unknown,
1567
- error,
1568
- target: evt,
1569
- });
1570
- }
1571
- };
1572
- liveController.onEvtErrListener = (evt) => {
1573
- live.emit('ws.error', { type: WebSocketErrorType.Error, target: evt });
1574
- liveController.checkReadyState(this);
1575
- };
1576
- liveController.onEvtCLEListener = (evt) => {
1577
- liveController.checkReadyState(this);
1578
- const code = Number(evt.code);
1579
- if (code === 1000)
1580
- return;
1581
- // 异常退出不一定会触发'error'事件,根据 evt.code 一些类型的退出也算是 error 行为
1582
- const errMsg = parseWSClsErr(code);
1583
- live.emit('ws.error', {
1584
- target: evt,
1585
- type: WebSocketErrorType.Close,
1586
- closeError: errMsg,
1801
+ });
1802
+ };
1803
+ LiveTpl.prototype.exit = function () {
1804
+ return __awaiter(this, void 0, void 0, function () {
1805
+ var e_1;
1806
+ return __generator(this, function (_a) {
1807
+ switch (_a.label) {
1808
+ case 0:
1809
+ _a.trys.push([0, 2, , 3]);
1810
+ this.$RTC.quit();
1811
+ return [4 /*yield*/, this.updateStatus(BuiltinEventType.RoomChange, BuiltinActionType.RoomClose, {})];
1812
+ case 1:
1813
+ _a.sent();
1814
+ return [3 /*break*/, 3];
1815
+ case 2:
1816
+ e_1 = _a.sent();
1817
+ console.log(e_1);
1818
+ return [3 /*break*/, 3];
1819
+ case 3: return [2 /*return*/, liveController.dispose()];
1820
+ }
1587
1821
  });
1588
- };
1589
- liveController.webSocket.addEventListener('open', liveController.onEvtOpnListener);
1590
- liveController.webSocket.addEventListener('message', liveController.onEvtMsgListener);
1591
- liveController.webSocket.addEventListener('error', liveController.onEvtErrListener);
1592
- liveController.webSocket.addEventListener('close', liveController.onEvtCLEListener);
1593
- return await new Promise((resolve, reject) => {
1594
- const success = () => {
1595
- resolve(true);
1596
- liveController.connecting = false;
1597
- this.off('ws.error', fail);
1598
- };
1599
- const fail = (error) => {
1600
- reject(error.error
1601
- ? error.error
1602
- : new Error('WebSocket connection failed!'));
1603
- liveController.connecting = false;
1604
- this.off('ws.afterConnect', success);
1605
- };
1606
- this.once('ws.afterConnect', success);
1607
- this.once('ws.error', fail);
1608
1822
  });
1609
- }
1610
- async revoke() {
1611
- return true;
1612
- }
1613
- }
1614
- const live = new LiveTpl();
1823
+ };
1824
+ LiveTpl.prototype.connect = function (options) {
1825
+ if (options === void 0) { options = {}; }
1826
+ return __awaiter(this, void 0, void 0, function () {
1827
+ var microAuth, error, error, force, error, error, url, _a, _b, _c;
1828
+ var _d;
1829
+ var _this = this;
1830
+ return __generator(this, function (_e) {
1831
+ switch (_e.label) {
1832
+ case 0: return [4 /*yield*/, this.$RTC.detectMicro()];
1833
+ case 1:
1834
+ microAuth = _e.sent();
1835
+ if (!microAuth) {
1836
+ error = new Error('系统监测麦克风未授权~');
1837
+ this.emit('ws.error', { type: WebSocketErrorType.MicroAuth, error: error });
1838
+ return [2 /*return*/, error];
1839
+ }
1840
+ // WebSocket 正在连接中,规避重复连接
1841
+ if (liveController.connecting) {
1842
+ error = new Error('WebSocket 正在连接中,请勿重复连接 ...');
1843
+ this.emit('ws.error', {
1844
+ type: WebSocketErrorType.DuplicateConnect,
1845
+ error: error,
1846
+ });
1847
+ return [2 /*return*/, error];
1848
+ }
1849
+ force = options.force;
1850
+ if (!force) {
1851
+ if (this.readyState === WebSocketState.CONNECTING ||
1852
+ this.readyState === WebSocketState.OPEN) {
1853
+ return [2 /*return*/, true];
1854
+ }
1855
+ }
1856
+ // WebSocket URL 逻辑
1857
+ if (options.url) {
1858
+ liveController.options.url = options.url;
1859
+ }
1860
+ if (options.getTicket) {
1861
+ liveController.options.getTicket = options.getTicket;
1862
+ }
1863
+ if (!liveController.options.url ||
1864
+ !liveController.options.url.startsWith('ws')) {
1865
+ error = new Error("WebSocket URL \u672A\u914D\u7F6E\u6216\u683C\u5F0F\u4E0D\u5408\u6CD5\uFF1A\"".concat(liveController.options.url, "\""));
1866
+ this.emit('ws.error', { type: WebSocketErrorType.IllegalURL, error: error });
1867
+ return [2 /*return*/, error];
1868
+ }
1869
+ if (!liveController.options.getTicket) {
1870
+ error = new Error("getTicket() \u672A\u914D\u7F6E!");
1871
+ this.emit('ws.error', { type: WebSocketErrorType.IllegalArgs, error: error });
1872
+ return [2 /*return*/, error];
1873
+ }
1874
+ // 连接锁
1875
+ liveController.connecting = true;
1876
+ // 连接前销毁之前绑定的事件
1877
+ liveController.disposeWebSocket();
1878
+ this.emit('ws.beforeConnect');
1879
+ if (!(force || options.url || !this.url)) return [3 /*break*/, 3];
1880
+ _b = appendUri;
1881
+ _c = [liveController.options.url];
1882
+ _d = {};
1883
+ return [4 /*yield*/, liveController.options.getTicket()];
1884
+ case 2:
1885
+ _a = _b.apply(void 0, _c.concat([(_d.ticket = _e.sent(),
1886
+ _d.force = Number(!!force),
1887
+ _d)]));
1888
+ return [3 /*break*/, 4];
1889
+ case 3:
1890
+ _a = this.url;
1891
+ _e.label = 4;
1892
+ case 4:
1893
+ url = _a;
1894
+ liveController.webSocket = new WebSocket(url);
1895
+ liveController.onEvtOpnListener = function () {
1896
+ liveController.checkReadyState(_this);
1897
+ _this.emit('ws.afterConnect');
1898
+ };
1899
+ liveController.onEvtMsgListener = function (evt) {
1900
+ liveController.checkReadyState(_this);
1901
+ try {
1902
+ var liveMsg = parseLiveMsg(evt.data);
1903
+ if (liveMsg === false)
1904
+ return;
1905
+ liveController.handleMessage(liveMsg, _this);
1906
+ }
1907
+ catch (error) {
1908
+ // 未知错误
1909
+ _this.emit('ws.error', {
1910
+ type: WebSocketErrorType.Unknown,
1911
+ error: error,
1912
+ target: evt,
1913
+ });
1914
+ }
1915
+ };
1916
+ liveController.onEvtErrListener = function (evt) {
1917
+ live.emit('ws.error', { type: WebSocketErrorType.Error, target: evt });
1918
+ liveController.checkReadyState(_this);
1919
+ };
1920
+ liveController.onEvtCLEListener = function (evt) {
1921
+ liveController.checkReadyState(_this);
1922
+ var code = Number(evt.code);
1923
+ if (code === 1000)
1924
+ return;
1925
+ // 异常退出不一定会触发'error'事件,根据 evt.code 一些类型的退出也算是 error 行为
1926
+ var errMsg = parseWSClsErr(code);
1927
+ live.emit('ws.error', {
1928
+ target: evt,
1929
+ type: WebSocketErrorType.Close,
1930
+ closeError: errMsg,
1931
+ });
1932
+ };
1933
+ liveController.webSocket.addEventListener('open', liveController.onEvtOpnListener);
1934
+ liveController.webSocket.addEventListener('message', liveController.onEvtMsgListener);
1935
+ liveController.webSocket.addEventListener('error', liveController.onEvtErrListener);
1936
+ liveController.webSocket.addEventListener('close', liveController.onEvtCLEListener);
1937
+ return [4 /*yield*/, new Promise(function (resolve, reject) {
1938
+ var success = function () {
1939
+ resolve(true);
1940
+ liveController.connecting = false;
1941
+ _this.off('ws.error', fail);
1942
+ };
1943
+ var fail = function (error) {
1944
+ reject(error.error
1945
+ ? error.error
1946
+ : new Error('WebSocket connection failed!'));
1947
+ liveController.connecting = false;
1948
+ _this.off('ws.afterConnect', success);
1949
+ };
1950
+ _this.once('ws.afterConnect', success);
1951
+ _this.once('ws.error', fail);
1952
+ })];
1953
+ case 5: return [2 /*return*/, _e.sent()];
1954
+ }
1955
+ });
1956
+ });
1957
+ };
1958
+ LiveTpl.prototype.revoke = function () {
1959
+ return __awaiter(this, void 0, void 0, function () {
1960
+ return __generator(this, function (_a) {
1961
+ return [2 /*return*/, true];
1962
+ });
1963
+ });
1964
+ };
1965
+ return LiveTpl;
1966
+ }(Subscribe));
1967
+ var live = new LiveTpl();
1615
1968
  // 如果是调试环境则将内部状态暴露出来
1616
1969
  if (options.__debug__) {
1617
1970
  Object.assign(live, { __controller__: liveController });
@@ -1624,14 +1977,14 @@ function createLive(options) {
1624
1977
  * 创建 {@link LiveReact} 实例,并提供 `React` 技术栈相关工具链。
1625
1978
  */
1626
1979
  function createLiveReact(options) {
1627
- const LiveContext = React.createContext(null);
1628
- const live = createLive(options);
1629
- const jsBridge = live.jsBridge;
1980
+ var LiveContext = React.createContext(null);
1981
+ var live = createLive(options);
1982
+ var jsBridge = live.jsBridge;
1630
1983
  function LiveProvider(props) {
1631
1984
  return (React.createElement(LiveContext.Provider, { value: props.live || live }, props.children));
1632
1985
  }
1633
1986
  function useLiveInstance() {
1634
- const context = React.useContext(LiveContext);
1987
+ var context = React.useContext(LiveContext);
1635
1988
  if (!context)
1636
1989
  throw new Error('LiveProvider never found.');
1637
1990
  return context;
@@ -1644,7 +1997,7 @@ function createLiveReact(options) {
1644
1997
  return useLiveInstance();
1645
1998
  }
1646
1999
  function useRTCInstance() {
1647
- const live = useLiveInstance();
2000
+ var live = useLiveInstance();
1648
2001
  return live.$RTC;
1649
2002
  }
1650
2003
  /**
@@ -1655,76 +2008,93 @@ function createLiveReact(options) {
1655
2008
  return useRTCInstance();
1656
2009
  }
1657
2010
  function useConnect() {
1658
- const live = useLiveInstance();
1659
- return async (options) => await live.connect(options);
2011
+ var _this = this;
2012
+ var live = useLiveInstance();
2013
+ return function (options) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
2014
+ switch (_a.label) {
2015
+ case 0: return [4 /*yield*/, live.connect(options)];
2016
+ case 1: return [2 /*return*/, _a.sent()];
2017
+ }
2018
+ }); }); };
1660
2019
  }
1661
2020
  function useCurrentWebSocketUrl() {
1662
- const live = useLiveInstance();
1663
- const [state, setState] = React.useState(undefined);
1664
- React.useEffect(() => {
1665
- const onWSBeforeConnect = () => setState(live.url);
2021
+ var live = useLiveInstance();
2022
+ var _a = React.useState(undefined), state = _a[0], setState = _a[1];
2023
+ React.useEffect(function () {
2024
+ var onWSBeforeConnect = function () { return setState(live.url); };
1666
2025
  live.on('ws.beforeConnect', onWSBeforeConnect);
1667
- return () => live.off('ws.beforeConnect', onWSBeforeConnect);
2026
+ return function () { return live.off('ws.beforeConnect', onWSBeforeConnect); };
1668
2027
  }, [live]);
1669
2028
  return state;
1670
2029
  }
1671
- function useKeyframeUpdateCallback(name, callback, deps = []) {
1672
- const live = useLiveInstance();
1673
- const dependencyList = [live, name, ...deps];
1674
- const dispose = () => live.keyframes.off(name, callback);
1675
- React.useEffect(() => {
2030
+ function useKeyframeUpdateCallback(name, callback, deps) {
2031
+ if (deps === void 0) { deps = []; }
2032
+ var live = useLiveInstance();
2033
+ var dependencyList = __spreadArray([live, name], deps, true);
2034
+ var dispose = function () { return live.keyframes.off(name, callback); };
2035
+ React.useEffect(function () {
1676
2036
  live.keyframes.on(name, callback);
1677
2037
  return dispose;
1678
2038
  }, dependencyList);
1679
2039
  return dispose;
1680
2040
  }
1681
2041
  function useLiveAction() {
1682
- const live = useLiveInstance();
1683
- const toggleMicro = React.useCallback((microStatus) => live.toggleMicro(microStatus), [live]);
1684
- const broadcast = React.useCallback((data, toUserIds, timeout = 0) => live.broadcast(data, toUserIds, timeout), [live]);
1685
- const exit = React.useCallback(() => live.exit(), [live]);
1686
- const kick = React.useCallback((toUserIds) => live.kick(toUserIds), [live]);
1687
- const forbidMicro = React.useCallback((micro, toUserIds) => live.forbidMicro(micro, toUserIds), [live]);
2042
+ var live = useLiveInstance();
2043
+ var toggleMicro = React.useCallback(function (microStatus) { return live.toggleMicro(microStatus); }, [live]);
2044
+ var broadcast = React.useCallback(function (data, toUserIds, timeout) {
2045
+ if (timeout === void 0) { timeout = 0; }
2046
+ return live.broadcast(data, toUserIds, timeout);
2047
+ }, [live]);
2048
+ var exit = React.useCallback(function () { return live.exit(); }, [live]);
2049
+ var kick = React.useCallback(function (toUserIds) { return live.kick(toUserIds); }, [live]);
2050
+ var forbidMicro = React.useCallback(function (micro, toUserIds) {
2051
+ return live.forbidMicro(micro, toUserIds);
2052
+ }, [live]);
1688
2053
  // const forbidSync = React.useCallback(
1689
2054
  // (sync: boolean, toUserIds?: string | string[] | undefined) =>
1690
2055
  // live.forbidSync(sync, toUserIds),
1691
2056
  // [live],
1692
2057
  // );
1693
- const getFramesByKey = React.useCallback((key) => live.getFramesByKey(key), [live]);
1694
- const sendKeyframe = React.useCallback((key, frame) => live.sendKeyframe(key, frame), [live]);
1695
- const setSelfInfo = React.useCallback((userInfo) => live.setSelfInfo(userInfo), [live]);
1696
- const updateStatus = React.useCallback((evtType, atnType, status, toUserIds) => live.updateStatus(evtType, atnType, status, toUserIds), [live]);
2058
+ var getFramesByKey = React.useCallback(function (key) { return live.getFramesByKey(key); }, [live]);
2059
+ var sendKeyframe = React.useCallback(function (key, frame) {
2060
+ return live.sendKeyframe(key, frame);
2061
+ }, [live]);
2062
+ var setSelfInfo = React.useCallback(function (userInfo) { return live.setSelfInfo(userInfo); }, [live]);
2063
+ var updateStatus = React.useCallback(function (evtType, atnType, status, toUserIds) { return live.updateStatus(evtType, atnType, status, toUserIds); }, [live]);
1697
2064
  return {
1698
- broadcast,
1699
- exit,
1700
- kick,
1701
- toggleMicro,
1702
- forbidMicro,
2065
+ broadcast: broadcast,
2066
+ exit: exit,
2067
+ kick: kick,
2068
+ toggleMicro: toggleMicro,
2069
+ forbidMicro: forbidMicro,
1703
2070
  // forbidSync,
1704
- sendKeyframe,
1705
- getFramesByKey,
1706
- setSelfInfo,
1707
- updateStatus,
2071
+ sendKeyframe: sendKeyframe,
2072
+ getFramesByKey: getFramesByKey,
2073
+ setSelfInfo: setSelfInfo,
2074
+ updateStatus: updateStatus,
1708
2075
  };
1709
2076
  }
1710
2077
  function useKeyframe(key) {
1711
- const live = useLiveInstance();
1712
- const [state, updateState] = React.useState(live.getFramesByKey(key));
1713
- React.useEffect(() => {
1714
- const onUpdate = (nextKeyframes) => updateState(nextKeyframes);
1715
- const evtName = key;
1716
- const callback = onUpdate;
2078
+ var live = useLiveInstance();
2079
+ var _a = React.useState(live.getFramesByKey(key)), state = _a[0], updateState = _a[1];
2080
+ React.useEffect(function () {
2081
+ var onUpdate = function (nextKeyframes) {
2082
+ return updateState(nextKeyframes);
2083
+ };
2084
+ var evtName = key;
2085
+ var callback = onUpdate;
1717
2086
  live.keyframes.on(evtName, callback);
1718
- return () => live.keyframes.off(evtName, callback);
2087
+ return function () { return live.keyframes.off(evtName, callback); };
1719
2088
  }, [live]);
1720
- const setState = React.useCallback((frame) => live.sendKeyframe(key, frame), [live]);
2089
+ var setState = React.useCallback(function (frame) { return live.sendKeyframe(key, frame); }, [live]);
1721
2090
  return [state, setState];
1722
2091
  }
1723
- function useLiveEventCallback(name, callback, deps = []) {
1724
- const live = useLiveInstance();
1725
- const dispose = () => live.off(name, callback);
1726
- const dependencyList = [live, name, ...deps];
1727
- React.useEffect(() => {
2092
+ function useLiveEventCallback(name, callback, deps) {
2093
+ if (deps === void 0) { deps = []; }
2094
+ var live = useLiveInstance();
2095
+ var dispose = function () { return live.off(name, callback); };
2096
+ var dependencyList = __spreadArray([live, name], deps, true);
2097
+ React.useEffect(function () {
1728
2098
  live.on(name, callback);
1729
2099
  return dispose;
1730
2100
  }, dependencyList);
@@ -1735,70 +2105,81 @@ function createLiveReact(options) {
1735
2105
  * @returns
1736
2106
  */
1737
2107
  function useReadyState() {
1738
- const live = useLiveInstance();
1739
- const [state, updateState] = React.useState(live.readyState);
1740
- React.useEffect(() => {
1741
- const readyStateUpdate = (readyState) => updateState(readyState);
2108
+ var live = useLiveInstance();
2109
+ var _a = React.useState(live.readyState), state = _a[0], updateState = _a[1];
2110
+ React.useEffect(function () {
2111
+ var readyStateUpdate = function (readyState) {
2112
+ return updateState(readyState);
2113
+ };
1742
2114
  live.on('ws.readyStateUpdate', readyStateUpdate);
1743
- return () => live.off('ws.readyStateUpdate', readyStateUpdate);
2115
+ return function () { return live.off('ws.readyStateUpdate', readyStateUpdate); };
1744
2116
  }, [live]);
1745
2117
  return state;
1746
2118
  }
1747
2119
  function useRTCAction() {
1748
- const live = useLiveInstance();
1749
- const join = React.useCallback((options) => live.$RTC.join(options), [live]);
1750
- const quit = React.useCallback(() => live.$RTC.quit(), [live]);
1751
- const shock = React.useCallback(() => { var _a, _b; return (_b = (_a = live.$RTC).shock) === null || _b === void 0 ? void 0 : _b.call(_a); }, [live]);
1752
- const toggleMicro = React.useCallback((flag) => live.$RTC.toggleMicro(flag), [live]);
1753
- const detectMicro = React.useCallback(() => live.$RTC.detectMicro(), [live]);
2120
+ var live = useLiveInstance();
2121
+ var join = React.useCallback(function (options) { return live.$RTC.join(options); }, [live]);
2122
+ var quit = React.useCallback(function () { return live.$RTC.quit(); }, [live]);
2123
+ var shock = React.useCallback(function () { var _a, _b; return (_b = (_a = live.$RTC).shock) === null || _b === void 0 ? void 0 : _b.call(_a); }, [live]);
2124
+ var toggleMicro = React.useCallback(function (flag) { return live.$RTC.toggleMicro(flag); }, [live]);
2125
+ var detectMicro = React.useCallback(function () { return live.$RTC.detectMicro(); }, [live]);
1754
2126
  return {
1755
- join,
1756
- quit,
1757
- shock,
1758
- toggleMicro,
1759
- detectMicro,
2127
+ join: join,
2128
+ quit: quit,
2129
+ shock: shock,
2130
+ toggleMicro: toggleMicro,
2131
+ detectMicro: detectMicro,
1760
2132
  };
1761
2133
  }
1762
- function useRTCEventCallback(name, callback, deps = []) {
1763
- const live = useLiveInstance();
1764
- const dispose = () => live.$RTC.off(name, callback);
1765
- const dependencyList = [live, name, ...deps];
1766
- React.useEffect(() => {
2134
+ function useRTCEventCallback(name, callback, deps) {
2135
+ if (deps === void 0) { deps = []; }
2136
+ var live = useLiveInstance();
2137
+ var dispose = function () { return live.$RTC.off(name, callback); };
2138
+ var dependencyList = __spreadArray([live, name], deps, true);
2139
+ React.useEffect(function () {
1767
2140
  live.$RTC.on(name, callback);
1768
2141
  return dispose;
1769
2142
  }, dependencyList);
1770
2143
  return dispose;
1771
2144
  }
1772
2145
  function useSelfInfo() {
1773
- const live = useLiveInstance();
1774
- const [state, updateState] = React.useState(live.selfInfo || {});
1775
- const selfInfoUpdate = (userInfo) => updateState(userInfo);
1776
- React.useEffect(() => {
2146
+ var _this = this;
2147
+ var live = useLiveInstance();
2148
+ var _a = React.useState(live.selfInfo || {}), state = _a[0], updateState = _a[1];
2149
+ var selfInfoUpdate = function (userInfo) {
2150
+ return updateState(userInfo);
2151
+ };
2152
+ React.useEffect(function () {
1777
2153
  live.on('selfInfoUpdate', selfInfoUpdate);
1778
- return () => live.off('selfInfoUpdate', selfInfoUpdate);
1779
- }, [live]);
1780
- const setState = React.useCallback(async (userInfo) => {
1781
- return await live.setSelfInfo(userInfo);
2154
+ return function () { return live.off('selfInfoUpdate', selfInfoUpdate); };
1782
2155
  }, [live]);
2156
+ var setState = React.useCallback(function (userInfo) { return __awaiter(_this, void 0, void 0, function () {
2157
+ return __generator(this, function (_a) {
2158
+ switch (_a.label) {
2159
+ case 0: return [4 /*yield*/, live.setSelfInfo(userInfo)];
2160
+ case 1: return [2 /*return*/, _a.sent()];
2161
+ }
2162
+ });
2163
+ }); }, [live]);
1783
2164
  return [state, setState];
1784
2165
  }
1785
2166
  function useSnapshot() {
1786
- const live = useLiveInstance();
1787
- const [state, setState] = React.useState(live.snapshot);
1788
- React.useEffect(() => {
1789
- const onKeyframes = (keyframes) => setState(keyframes);
2167
+ var live = useLiveInstance();
2168
+ var _a = React.useState(live.snapshot), state = _a[0], setState = _a[1];
2169
+ React.useEffect(function () {
2170
+ var onKeyframes = function (keyframes) { return setState(keyframes); };
1790
2171
  live.on('keyframes', onKeyframes);
1791
- return () => live.off('keyframes', onKeyframes);
2172
+ return function () { return live.off('keyframes', onKeyframes); };
1792
2173
  });
1793
2174
  return state;
1794
2175
  }
1795
2176
  function useUserList() {
1796
- const live = useLiveInstance();
1797
- const [state, updateState] = React.useState(live.userList);
1798
- const userListUpdate = (userList) => updateState(userList);
1799
- React.useEffect(() => {
2177
+ var live = useLiveInstance();
2178
+ var _a = React.useState(live.userList), state = _a[0], updateState = _a[1];
2179
+ var userListUpdate = function (userList) { return updateState(userList); };
2180
+ React.useEffect(function () {
1800
2181
  live.on('userListUpdate', userListUpdate);
1801
- return () => live.off('userListUpdate', userListUpdate);
2182
+ return function () { return live.off('userListUpdate', userListUpdate); };
1802
2183
  }, [live]);
1803
2184
  return state;
1804
2185
  }
@@ -1810,35 +2191,36 @@ function createLiveReact(options) {
1810
2191
  * @returns
1811
2192
  * @deprecated
1812
2193
  */
1813
- function useWebSocketEventCallback(name, callback, deps = []) {
1814
- const live = useLiveInstance();
1815
- const dispose = () => live.off(name, callback);
1816
- const dependencyList = [live, name, ...deps];
1817
- React.useEffect(() => {
2194
+ function useWebSocketEventCallback(name, callback, deps) {
2195
+ if (deps === void 0) { deps = []; }
2196
+ var live = useLiveInstance();
2197
+ var dispose = function () { return live.off(name, callback); };
2198
+ var dependencyList = __spreadArray([live, name], deps, true);
2199
+ React.useEffect(function () {
1818
2200
  live.on(name, callback);
1819
2201
  return dispose;
1820
2202
  }, dependencyList);
1821
2203
  return dispose;
1822
2204
  }
1823
2205
  return {
1824
- live,
1825
- jsBridge,
1826
- LiveProvider,
1827
- unsafe__useLiveInstance,
1828
- unsafe__useRTCInstance,
1829
- useCurrentWebSocketUrl,
1830
- useConnect,
1831
- useKeyframe,
1832
- useKeyframeUpdateCallback,
1833
- useLiveAction,
1834
- useLiveEventCallback,
1835
- useReadyState,
1836
- useRTCAction,
1837
- useRTCEventCallback,
1838
- useSelfInfo,
1839
- useSnapshot,
1840
- useUserList,
1841
- useWebSocketEventCallback,
2206
+ live: live,
2207
+ jsBridge: jsBridge,
2208
+ LiveProvider: LiveProvider,
2209
+ unsafe__useLiveInstance: unsafe__useLiveInstance,
2210
+ unsafe__useRTCInstance: unsafe__useRTCInstance,
2211
+ useCurrentWebSocketUrl: useCurrentWebSocketUrl,
2212
+ useConnect: useConnect,
2213
+ useKeyframe: useKeyframe,
2214
+ useKeyframeUpdateCallback: useKeyframeUpdateCallback,
2215
+ useLiveAction: useLiveAction,
2216
+ useLiveEventCallback: useLiveEventCallback,
2217
+ useReadyState: useReadyState,
2218
+ useRTCAction: useRTCAction,
2219
+ useRTCEventCallback: useRTCEventCallback,
2220
+ useSelfInfo: useSelfInfo,
2221
+ useSnapshot: useSnapshot,
2222
+ useUserList: useUserList,
2223
+ useWebSocketEventCallback: useWebSocketEventCallback,
1842
2224
  };
1843
2225
  }
1844
2226