@realsee/live 0.4.0-beta.5 → 0.4.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,56 +1250,56 @@ 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
  }
1059
1277
  return true;
1060
1278
  };
1061
1279
  /**
1062
1280
  * 销毁WebSocket相关依赖。
1063
1281
  */
1064
- this.disposeWebSocket = () => {
1065
- if (!this.webSocket)
1282
+ this.disposeWebSocket = function () {
1283
+ if (!_this.webSocket)
1066
1284
  return;
1067
- if (this.onEvtOpnListener) {
1068
- this.webSocket.removeEventListener('open', this.onEvtOpnListener);
1069
- this.onEvtOpnListener = undefined;
1285
+ if (_this.onEvtOpnListener) {
1286
+ _this.webSocket.removeEventListener('open', _this.onEvtOpnListener);
1287
+ _this.onEvtOpnListener = undefined;
1070
1288
  }
1071
- if (this.onEvtMsgListener) {
1072
- this.webSocket.removeEventListener('message', this.onEvtMsgListener);
1073
- this.onEvtMsgListener = undefined;
1289
+ if (_this.onEvtMsgListener) {
1290
+ _this.webSocket.removeEventListener('message', _this.onEvtMsgListener);
1291
+ _this.onEvtMsgListener = undefined;
1074
1292
  }
1075
- if (this.onEvtErrListener) {
1076
- this.webSocket.removeEventListener('error', this.onEvtErrListener);
1077
- this.onEvtErrListener = undefined;
1293
+ if (_this.onEvtErrListener) {
1294
+ _this.webSocket.removeEventListener('error', _this.onEvtErrListener);
1295
+ _this.onEvtErrListener = undefined;
1078
1296
  }
1079
- if (this.onEvtCLEListener) {
1080
- this.webSocket.removeEventListener('close', this.onEvtCLEListener);
1081
- this.onEvtCLEListener = undefined;
1297
+ if (_this.onEvtCLEListener) {
1298
+ _this.webSocket.removeEventListener('close', _this.onEvtCLEListener);
1299
+ _this.onEvtCLEListener = undefined;
1082
1300
  }
1083
- this.webSocket.close();
1084
- this.webSocket = undefined;
1301
+ _this.webSocket.close();
1302
+ _this.webSocket = undefined;
1085
1303
  return true;
1086
1304
  };
1087
1305
  this.options = Object.assign({ autoConnect: true, healthCheck: 3000 }, options);
@@ -1091,16 +1309,17 @@ class LiveController {
1091
1309
  * @param liveMsg
1092
1310
  * @param live
1093
1311
  */
1094
- handleMessage(liveMsg, live) {
1312
+ LiveController.prototype.handleMessage = function (liveMsg, live) {
1313
+ var _this = this;
1095
1314
  var _a, _b, _c;
1096
- const { command, data, frontRequestId, code, message } = liveMsg;
1315
+ var command = liveMsg.command, data = liveMsg.data, frontRequestId = liveMsg.frontRequestId, code = liveMsg.code;
1097
1316
  if (code === 'SUCCESS') {
1098
1317
  switch (command) {
1099
1318
  /**
1100
1319
  * 自己的状态变化
1101
1320
  */
1102
1321
  case Command.SelfUserInfo: {
1103
- const selfInfo = data;
1322
+ var selfInfo = data;
1104
1323
  if (equal(this.selfUserInfo, selfInfo, { deep: true }))
1105
1324
  return;
1106
1325
  this.selfUserInfo = selfInfo;
@@ -1111,7 +1330,7 @@ class LiveController {
1111
1330
  * 房间信息变化
1112
1331
  */
1113
1332
  case Command.RoomInfo: {
1114
- const roomInfo = data;
1333
+ var roomInfo = data;
1115
1334
  this.roomInfo = Object.assign({}, roomInfo);
1116
1335
  live.emit('readyKeyframeSync', (roomInfo.last_frame || {}));
1117
1336
  break;
@@ -1120,16 +1339,16 @@ class LiveController {
1120
1339
  * 语音信息变化
1121
1340
  */
1122
1341
  case Command.RTCInfo: {
1123
- const { voice_id: voiceId, type } = data;
1342
+ var _d = data, voiceId = _d.voice_id, type = _d.type;
1124
1343
  /* 如果已经进入语音房间,则不重复进入 --> "RTCInfo" 指令可能会下发多次 */
1125
1344
  if (live.$RTC.joined) {
1126
1345
  break;
1127
1346
  }
1128
1347
  live.$RTC.join({
1129
- voiceId,
1348
+ voiceId: voiceId,
1130
1349
  userId: ((_a = this.selfUserInfo) === null || _a === void 0 ? void 0 : _a.id) || '',
1131
1350
  roomId: (_b = this.roomInfo) === null || _b === void 0 ? void 0 : _b.info.room_code,
1132
- type,
1351
+ type: type,
1133
1352
  });
1134
1353
  // 加入房间后 麦克风默认就开启了:需要发个指令。
1135
1354
  live.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserMicroStatus, {
@@ -1141,7 +1360,7 @@ class LiveController {
1141
1360
  * 房间用户列表变化
1142
1361
  */
1143
1362
  case Command.UserList: {
1144
- const userList = data;
1363
+ var userList = data;
1145
1364
  this.userList = userList;
1146
1365
  live.emit('userListUpdate', this.userList, frontRequestId);
1147
1366
  break;
@@ -1150,7 +1369,7 @@ class LiveController {
1150
1369
  * 自定义事件广播
1151
1370
  */
1152
1371
  case Command.CustomEvent: {
1153
- const evtMsg = data;
1372
+ var evtMsg = data;
1154
1373
  live.emit('broadcast', evtMsg, frontRequestId);
1155
1374
  break;
1156
1375
  }
@@ -1158,21 +1377,22 @@ class LiveController {
1158
1377
  * 帧数据同步
1159
1378
  */
1160
1379
  case Command.KeyframeSync: {
1161
- const remoteKeyframes = data;
1380
+ var remoteKeyframes_1 = data;
1162
1381
  // 此处做一层 diff,仅跟本地数据不一致的情况下才广播数据。
1163
- const keyframes = Object.keys(remoteKeyframes).reduce((accu, curr) => {
1164
- 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 })) {
1165
1385
  return accu;
1166
1386
  }
1167
- const params = [
1168
- remoteKeyframes[curr],
1169
- this.keyframes[curr],
1387
+ var params = [
1388
+ remoteKeyframes_1[curr],
1389
+ _this.keyframes[curr],
1170
1390
  frontRequestId,
1171
1391
  ];
1172
- const evtName = curr;
1173
- live.keyframes.emit(evtName, ...params);
1174
- this.keyframes[curr] = remoteKeyframes[curr];
1175
- 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];
1176
1396
  return accu;
1177
1397
  }, {});
1178
1398
  live.emit('keyframes', keyframes, frontRequestId);
@@ -1182,7 +1402,7 @@ class LiveController {
1182
1402
  * 内置消息
1183
1403
  */
1184
1404
  case Command.BuiltinMsg: {
1185
- const builtinMsg = data;
1405
+ var builtinMsg = data;
1186
1406
  live.emit('builtinEvent', builtinMsg);
1187
1407
  if (builtinMsg.event_type === BuiltinEventType.UserChange) {
1188
1408
  live.emit('userChange', builtinMsg);
@@ -1225,27 +1445,31 @@ class LiveController {
1225
1445
  else {
1226
1446
  live.emit('error', liveMsg);
1227
1447
  }
1228
- }
1448
+ };
1229
1449
  /**
1230
1450
  * 发送数据
1231
1451
  * @param data
1232
1452
  */
1233
- sendMessage(data) {
1453
+ LiveController.prototype.sendMessage = function (data) {
1234
1454
  if (!this.webSocket)
1235
1455
  return console.warn('WebSocket has not yet been initialized!');
1236
1456
  if (!data)
1237
1457
  return console.warn('WebSocket messages is empty!');
1238
1458
  this.webSocket.send(JSON.stringify(data));
1239
- }
1240
- }
1459
+ };
1460
+ return LiveController;
1461
+ }());
1241
1462
 
1242
- const unimplementedGetVoiceSign = (params) => Promise.reject('unimplemented method GetVoiceSign');
1463
+ var unimplementedGetVoiceSign = function (params) {
1464
+ return Promise.reject('unimplemented method GetVoiceSign');
1465
+ };
1243
1466
  /**
1244
1467
  * 创建 `live` 实例。
1245
1468
  */
1246
1469
  function createLive(options) {
1247
- const liveController = new LiveController(options);
1248
- const createLiveMsg = (command, data = {}, toUserIds) => {
1470
+ var liveController = new LiveController(options);
1471
+ var createLiveMsg = function (command, data, toUserIds) {
1472
+ if (data === void 0) { data = {}; }
1249
1473
  toUserIds = toUserIds
1250
1474
  ? Array.isArray(toUserIds)
1251
1475
  ? toUserIds
@@ -1253,14 +1477,16 @@ function createLive(options) {
1253
1477
  : [];
1254
1478
  if (toUserIds)
1255
1479
  data['to_user_ids'] = toUserIds;
1256
- return { command, front_request_id: uuid(), data };
1480
+ return { command: command, front_request_id: uuid(), data: data };
1257
1481
  };
1258
- class LiveTpl extends Subscribe {
1259
- constructor() {
1482
+ var LiveTpl = /** @class */ (function (_super) {
1483
+ __extends(LiveTpl, _super);
1484
+ function LiveTpl() {
1485
+ var _this = this;
1260
1486
  var _a, _b;
1261
- super();
1262
- this.keyframes = new Subscribe();
1263
- const jsBridge = (() => {
1487
+ _this = _super.call(this) || this;
1488
+ _this.keyframes = new Subscribe();
1489
+ var jsBridge = (function () {
1264
1490
  if (options.jsBridge)
1265
1491
  return options.jsBridge;
1266
1492
  if (options.useBuiltInJsBridge)
@@ -1275,7 +1501,7 @@ function createLive(options) {
1275
1501
  if (!options.getVoiceSign) {
1276
1502
  throw new Error('GetVoiceSign method must be passed when using built-in RTC instances');
1277
1503
  }
1278
- const getVoiceSign = (_a = options.getVoiceSign) !== null && _a !== void 0 ? _a : unimplementedGetVoiceSign;
1504
+ var getVoiceSign = (_a = options.getVoiceSign) !== null && _a !== void 0 ? _a : unimplementedGetVoiceSign;
1279
1505
  switch (options.rtcType) {
1280
1506
  case RTCType.RealseeVRWebViewRTC: {
1281
1507
  // 内置的 VRWebViewRTC
@@ -1283,15 +1509,15 @@ function createLive(options) {
1283
1509
  throw new Error('JsBridge instance must be passed when using built-in VRWebViewRTC instances');
1284
1510
  }
1285
1511
  liveController.options.rtc = new VRWebViewRTC({
1286
- jsBridge,
1287
- getVoiceSign,
1512
+ jsBridge: jsBridge,
1513
+ getVoiceSign: getVoiceSign,
1288
1514
  });
1289
1515
  break;
1290
1516
  }
1291
1517
  case RTCType.RealseeBrowserChimeRTC: {
1292
1518
  // 内置的 RealseeBrowserChimeRTC
1293
1519
  liveController.options.rtc = new BrowserRTC4Chime({
1294
- getVoiceSign,
1520
+ getVoiceSign: getVoiceSign,
1295
1521
  logLevel: options.__debug__ ? LogLevel.DEBUG : LogLevel.ERROR,
1296
1522
  });
1297
1523
  break;
@@ -1299,7 +1525,7 @@ function createLive(options) {
1299
1525
  case RTCType.RealseeBrowserRTC: {
1300
1526
  // 内置的 RealseeBrowserRTC
1301
1527
  liveController.options.rtc = new BrowserRTC({
1302
- getVoiceSign,
1528
+ getVoiceSign: getVoiceSign,
1303
1529
  });
1304
1530
  break;
1305
1531
  }
@@ -1313,23 +1539,23 @@ function createLive(options) {
1313
1539
  if (!options.getVoiceSign) {
1314
1540
  throw new Error('GetVoiceSign method must be passed when using built-in RTC instances');
1315
1541
  }
1316
- const getVoiceSign = (_b = options.getVoiceSign) !== null && _b !== void 0 ? _b : unimplementedGetVoiceSign;
1542
+ var getVoiceSign = (_b = options.getVoiceSign) !== null && _b !== void 0 ? _b : unimplementedGetVoiceSign;
1317
1543
  if (!jsBridge) {
1318
1544
  throw new Error('jsBridge instance must be passed when using built-in RTC instances');
1319
1545
  }
1320
1546
  // vrwebview 默认
1321
1547
  if ((isRealseeVRWebview && (isAndroid || isIOS)) || isWxMiniProgram) {
1322
1548
  liveController.options.rtc = new VRWebViewRTC({
1323
- jsBridge,
1324
- getVoiceSign,
1549
+ jsBridge: jsBridge,
1550
+ getVoiceSign: getVoiceSign,
1325
1551
  });
1326
1552
  }
1327
1553
  else {
1328
1554
  // 其它终端使用
1329
1555
  liveController.options.rtc =
1330
1556
  options.builtInRTCType === BuiltInRTCType.RealseeXChimeRTC
1331
- ? new BrowserRTC4Chime({ getVoiceSign })
1332
- : new BrowserRTC({ getVoiceSign });
1557
+ ? new BrowserRTC4Chime({ getVoiceSign: getVoiceSign })
1558
+ : new BrowserRTC({ getVoiceSign: getVoiceSign });
1333
1559
  }
1334
1560
  }
1335
1561
  }
@@ -1338,283 +1564,407 @@ function createLive(options) {
1338
1564
  }
1339
1565
  // 默认自动连接
1340
1566
  if (liveController.options.url && liveController.options.getTicket) {
1341
- this.connect();
1567
+ _this.connect();
1342
1568
  }
1343
1569
  // 健康检查:WHY --> 在某些WebView特殊场景下 WebSocket.readyState 发生变化时不会出发error\close等事件;
1344
1570
  // 因此,开启一个定时任务监测 WebSocket.readyState 状态的更新
1345
- const healthCheck = ((healthCheck) => {
1571
+ var healthCheck = (function (healthCheck) {
1346
1572
  if (!healthCheck)
1347
1573
  return 0;
1348
1574
  if (healthCheck === true)
1349
1575
  return 3000;
1350
- const duration = Number(healthCheck);
1576
+ var duration = Number(healthCheck);
1351
1577
  if (duration > 0)
1352
1578
  return duration;
1353
1579
  return 3000;
1354
1580
  })(liveController.options.healthCheck);
1355
1581
  if (healthCheck) {
1356
- liveController.healthCheckId = setInterval(() => liveController.checkReadyState(this), healthCheck);
1357
- }
1358
- }
1359
- get options() {
1360
- return Object.freeze(Object.assign({}, liveController.options));
1361
- }
1362
- get readyState() {
1363
- liveController.checkReadyState(this);
1364
- return liveController.readyState;
1365
- }
1366
- get url() {
1367
- var _a;
1368
- return ((_a = liveController.webSocket) === null || _a === void 0 ? void 0 : _a.url) || '';
1369
- }
1370
- get selfInfo() {
1371
- return liveController.selfUserInfo;
1372
- }
1373
- get userList() {
1374
- return liveController.userList || [];
1375
- }
1376
- get snapshot() {
1377
- return liveController.keyframes || {};
1378
- }
1379
- get $RTC() {
1380
- return liveController.options.rtc;
1381
- }
1382
- get jsBridge() {
1383
- return liveController.options.jsBridge;
1384
- }
1385
- async setSelfInfo(userInfo) {
1386
- if (this.readyState !== WebSocketState.OPEN) {
1387
- return new Error('The connection is not open and ready to communicate.');
1388
- }
1389
- try {
1390
- return await this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserInfo, userInfo);
1391
- }
1392
- catch (error) {
1393
- return error;
1582
+ liveController.healthCheckId = setInterval(function () { return liveController.checkReadyState(_this); }, healthCheck);
1394
1583
  }
1584
+ return _this;
1395
1585
  }
1396
- 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) {
1397
1667
  return liveController.keyframes[key];
1398
- }
1399
- sendKeyframe(key, frame) {
1668
+ };
1669
+ LiveTpl.prototype.sendKeyframe = function (key, frame) {
1400
1670
  if (this.readyState !== WebSocketState.OPEN) {
1401
1671
  return new Error('The connection is not open and ready to communicate.');
1402
1672
  }
1403
1673
  liveController.keyframes[key] = frame;
1404
- const liveMsg = createLiveMsg(Command.KeyframeSync, this.snapshot);
1674
+ var liveMsg = createLiveMsg(Command.KeyframeSync, this.snapshot);
1405
1675
  liveController.sendMessage(liveMsg);
1406
1676
  return true;
1407
- }
1408
- broadcast(data, toUserIds, timeout) {
1677
+ };
1678
+ LiveTpl.prototype.broadcast = function (data, toUserIds, timeout) {
1679
+ var _this = this;
1409
1680
  if (this.readyState !== WebSocketState.OPEN) {
1410
1681
  return new Error('The connection is not open and ready to communicate.');
1411
1682
  }
1412
- return new Promise((resolve, reject) => {
1413
- const customEvent = createLiveMsg(Command.CustomEvent, data, toUserIds);
1414
- 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;
1415
1686
  liveController.sendMessage(customEvent);
1416
- const timeoutId = timeout
1417
- ? setTimeout(() => {
1687
+ var timeoutId = timeout
1688
+ ? setTimeout(function () {
1418
1689
  reject(new Error('RESPONSE TIMEOUT'));
1419
- this.off('broadcast', broadcast);
1690
+ _this.off('broadcast', broadcast);
1420
1691
  }, timeout)
1421
1692
  : undefined;
1422
- const broadcast = (data, frontRequestId) => {
1693
+ var broadcast = function (data, frontRequestId) {
1423
1694
  if (frontRequestId !== front_request_id)
1424
1695
  return;
1425
- this.off('broadcast', broadcast);
1696
+ _this.off('broadcast', broadcast);
1426
1697
  resolve(data);
1427
1698
  if (timeoutId)
1428
1699
  clearInterval(timeoutId);
1429
1700
  };
1430
- this.on('broadcast', broadcast);
1701
+ _this.on('broadcast', broadcast);
1431
1702
  });
1432
- }
1433
- async updateStatus(evtType, atnType, status, toUserIds) {
1434
- // TODO 统一规则,不能联合类型
1435
- if (this.readyState !== WebSocketState.OPEN) {
1436
- return false;
1437
- }
1438
- const data = Object.assign({ event_type: evtType, action: atnType }, { data: status });
1439
- const liveMsg = createLiveMsg(Command.BuiltinMsg, data, toUserIds);
1440
- liveController.sendMessage(liveMsg);
1441
- return true;
1442
- }
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
+ };
1443
1719
  // 仅用于用户自己的麦克风控制
1444
- async toggleMicro(microStatus) {
1720
+ LiveTpl.prototype.toggleMicro = function (microStatus) {
1445
1721
  var _a, _b;
1446
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_own_micro))
1447
- return false;
1448
- await this.$RTC.toggleMicro(microStatus);
1449
- return await this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserMicroStatus, {
1450
- status: microStatus ? MicroStatus.OPEN : MicroStatus.CLOSE,
1451
- }, []);
1452
- }
1453
- 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) {
1454
1740
  var _a, _b;
1455
- if (liveController.options.canForbidUserMicro &&
1456
- !liveController.options.canForbidUserMicro(toUserIds)) {
1457
- return false;
1458
- }
1459
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_other_micro)) {
1460
- return false;
1461
- }
1462
- return await this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserMicroStatus, {
1463
- status: microStatus,
1464
- }, toUserIds);
1465
- }
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
+ };
1466
1760
  /**
1467
1761
  * @deprecated 暂不可用
1468
1762
  */
1469
- async forbidSync(sync, toUserIds) {
1763
+ LiveTpl.prototype.forbidSync = function (sync, toUserIds) {
1470
1764
  var _a, _b;
1471
- if (liveController.options.canForbidUserSync &&
1472
- !liveController.options.canForbidUserSync(toUserIds)) {
1473
- return false;
1474
- }
1475
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_other_sync)) {
1476
- return false;
1477
- }
1478
- return await this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserPermission, { sync_frame: sync }, toUserIds);
1479
- }
1480
- 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) {
1481
1783
  var _a, _b;
1482
- if (liveController.options.canForbidUserKick &&
1483
- !liveController.options.canForbidUserKick(toUserIds)) {
1484
- return false;
1485
- }
1486
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.change_other_status)) {
1487
- return false;
1488
- }
1489
- return await this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserStatus, {
1490
- status: 'KICK_OUT',
1491
- }, toUserIds);
1492
- }
1493
- async exit() {
1494
- /** 退出强制关闭语音(?) */
1495
- await this.$RTC.quit();
1496
- await this.updateStatus(BuiltinEventType.RoomChange, BuiltinActionType.RoomClose, {});
1497
- return liveController.dispose();
1498
- }
1499
- async connect(options = {}) {
1500
- // 连接 WebSocket 前验证麦克风权限
1501
- const microAuth = await this.$RTC.detectMicro();
1502
- if (!microAuth) {
1503
- const error = new Error('系统监测麦克风未授权~');
1504
- this.emit('ws.error', { type: WebSocketErrorType.MicroAuth, error });
1505
- return error;
1506
- }
1507
- // WebSocket 正在连接中,规避重复连接
1508
- if (liveController.connecting) {
1509
- const error = new Error('WebSocket 正在连接中,请勿重复连接 ...');
1510
- this.emit('ws.error', {
1511
- type: WebSocketErrorType.DuplicateConnect,
1512
- 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
+ }
1513
1800
  });
1514
- return error;
1515
- }
1516
- // 非强制连接场景下,如果已经完成 WebSocket 连接则不执行后续逻辑
1517
- const { force } = options;
1518
- if (!force) {
1519
- if (this.readyState === WebSocketState.CONNECTING ||
1520
- this.readyState === WebSocketState.OPEN) {
1521
- return true;
1522
- }
1523
- }
1524
- // WebSocket URL 逻辑
1525
- if (options.url) {
1526
- liveController.options.url = options.url;
1527
- }
1528
- if (options.getTicket) {
1529
- liveController.options.getTicket = options.getTicket;
1530
- }
1531
- if (!liveController.options.url ||
1532
- !liveController.options.url.startsWith('ws')) {
1533
- const error = new Error(`WebSocket URL 未配置或格式不合法:"${liveController.options.url}"`);
1534
- this.emit('ws.error', { type: WebSocketErrorType.IllegalURL, error });
1535
- return error;
1536
- }
1537
- if (!liveController.options.getTicket) {
1538
- const error = new Error(`getTicket() 未配置!`);
1539
- this.emit('ws.error', { type: WebSocketErrorType.IllegalArgs, error });
1540
- return error;
1541
- }
1542
- // 连接锁
1543
- liveController.connecting = true;
1544
- // 连接前销毁之前绑定的事件
1545
- liveController.disposeWebSocket();
1546
- this.emit('ws.beforeConnect');
1547
- const url = force || options.url || !this.url
1548
- ? appendUri(liveController.options.url, {
1549
- ticket: await liveController.options.getTicket(),
1550
- force: Number(!!force),
1551
- })
1552
- : this.url;
1553
- liveController.webSocket = new WebSocket(url);
1554
- liveController.onEvtOpnListener = () => {
1555
- liveController.checkReadyState(this);
1556
- this.emit('ws.afterConnect');
1557
- };
1558
- liveController.onEvtMsgListener = (evt) => {
1559
- liveController.checkReadyState(this);
1560
- try {
1561
- const liveMsg = parseLiveMsg(evt.data);
1562
- if (liveMsg === false)
1563
- return;
1564
- liveController.handleMessage(liveMsg, this);
1565
- }
1566
- catch (error) {
1567
- // 未知错误
1568
- this.emit('ws.error', {
1569
- type: WebSocketErrorType.Unknown,
1570
- error,
1571
- target: evt,
1572
- });
1573
- }
1574
- };
1575
- liveController.onEvtErrListener = (evt) => {
1576
- live.emit('ws.error', { type: WebSocketErrorType.Error, target: evt });
1577
- liveController.checkReadyState(this);
1578
- };
1579
- liveController.onEvtCLEListener = (evt) => {
1580
- liveController.checkReadyState(this);
1581
- const code = Number(evt.code);
1582
- if (code === 1000)
1583
- return;
1584
- // 异常退出不一定会触发'error'事件,根据 evt.code 一些类型的退出也算是 error 行为
1585
- const errMsg = parseWSClsErr(code);
1586
- live.emit('ws.error', {
1587
- target: evt,
1588
- type: WebSocketErrorType.Close,
1589
- 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
+ }
1590
1821
  });
1591
- };
1592
- liveController.webSocket.addEventListener('open', liveController.onEvtOpnListener);
1593
- liveController.webSocket.addEventListener('message', liveController.onEvtMsgListener);
1594
- liveController.webSocket.addEventListener('error', liveController.onEvtErrListener);
1595
- liveController.webSocket.addEventListener('close', liveController.onEvtCLEListener);
1596
- return await new Promise((resolve, reject) => {
1597
- const success = () => {
1598
- resolve(true);
1599
- liveController.connecting = false;
1600
- this.off('ws.error', fail);
1601
- };
1602
- const fail = (error) => {
1603
- reject(error.error
1604
- ? error.error
1605
- : new Error('WebSocket connection failed!'));
1606
- liveController.connecting = false;
1607
- this.off('ws.afterConnect', success);
1608
- };
1609
- this.once('ws.afterConnect', success);
1610
- this.once('ws.error', fail);
1611
1822
  });
1612
- }
1613
- async revoke() {
1614
- return true;
1615
- }
1616
- }
1617
- 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();
1618
1968
  // 如果是调试环境则将内部状态暴露出来
1619
1969
  if (options.__debug__) {
1620
1970
  Object.assign(live, { __controller__: liveController });
@@ -1627,14 +1977,14 @@ function createLive(options) {
1627
1977
  * 创建 {@link LiveReact} 实例,并提供 `React` 技术栈相关工具链。
1628
1978
  */
1629
1979
  function createLiveReact(options) {
1630
- const LiveContext = React.createContext(null);
1631
- const live = createLive(options);
1632
- const jsBridge = live.jsBridge;
1980
+ var LiveContext = React.createContext(null);
1981
+ var live = createLive(options);
1982
+ var jsBridge = live.jsBridge;
1633
1983
  function LiveProvider(props) {
1634
1984
  return (React.createElement(LiveContext.Provider, { value: props.live || live }, props.children));
1635
1985
  }
1636
1986
  function useLiveInstance() {
1637
- const context = React.useContext(LiveContext);
1987
+ var context = React.useContext(LiveContext);
1638
1988
  if (!context)
1639
1989
  throw new Error('LiveProvider never found.');
1640
1990
  return context;
@@ -1647,7 +1997,7 @@ function createLiveReact(options) {
1647
1997
  return useLiveInstance();
1648
1998
  }
1649
1999
  function useRTCInstance() {
1650
- const live = useLiveInstance();
2000
+ var live = useLiveInstance();
1651
2001
  return live.$RTC;
1652
2002
  }
1653
2003
  /**
@@ -1658,76 +2008,93 @@ function createLiveReact(options) {
1658
2008
  return useRTCInstance();
1659
2009
  }
1660
2010
  function useConnect() {
1661
- const live = useLiveInstance();
1662
- 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
+ }); }); };
1663
2019
  }
1664
2020
  function useCurrentWebSocketUrl() {
1665
- const live = useLiveInstance();
1666
- const [state, setState] = React.useState(undefined);
1667
- React.useEffect(() => {
1668
- 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); };
1669
2025
  live.on('ws.beforeConnect', onWSBeforeConnect);
1670
- return () => live.off('ws.beforeConnect', onWSBeforeConnect);
2026
+ return function () { return live.off('ws.beforeConnect', onWSBeforeConnect); };
1671
2027
  }, [live]);
1672
2028
  return state;
1673
2029
  }
1674
- function useKeyframeUpdateCallback(name, callback, deps = []) {
1675
- const live = useLiveInstance();
1676
- const dependencyList = [live, name, ...deps];
1677
- const dispose = () => live.keyframes.off(name, callback);
1678
- 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 () {
1679
2036
  live.keyframes.on(name, callback);
1680
2037
  return dispose;
1681
2038
  }, dependencyList);
1682
2039
  return dispose;
1683
2040
  }
1684
2041
  function useLiveAction() {
1685
- const live = useLiveInstance();
1686
- const toggleMicro = React.useCallback((microStatus) => live.toggleMicro(microStatus), [live]);
1687
- const broadcast = React.useCallback((data, toUserIds, timeout = 0) => live.broadcast(data, toUserIds, timeout), [live]);
1688
- const exit = React.useCallback(() => live.exit(), [live]);
1689
- const kick = React.useCallback((toUserIds) => live.kick(toUserIds), [live]);
1690
- 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]);
1691
2053
  // const forbidSync = React.useCallback(
1692
2054
  // (sync: boolean, toUserIds?: string | string[] | undefined) =>
1693
2055
  // live.forbidSync(sync, toUserIds),
1694
2056
  // [live],
1695
2057
  // );
1696
- const getFramesByKey = React.useCallback((key) => live.getFramesByKey(key), [live]);
1697
- const sendKeyframe = React.useCallback((key, frame) => live.sendKeyframe(key, frame), [live]);
1698
- const setSelfInfo = React.useCallback((userInfo) => live.setSelfInfo(userInfo), [live]);
1699
- 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]);
1700
2064
  return {
1701
- broadcast,
1702
- exit,
1703
- kick,
1704
- toggleMicro,
1705
- forbidMicro,
2065
+ broadcast: broadcast,
2066
+ exit: exit,
2067
+ kick: kick,
2068
+ toggleMicro: toggleMicro,
2069
+ forbidMicro: forbidMicro,
1706
2070
  // forbidSync,
1707
- sendKeyframe,
1708
- getFramesByKey,
1709
- setSelfInfo,
1710
- updateStatus,
2071
+ sendKeyframe: sendKeyframe,
2072
+ getFramesByKey: getFramesByKey,
2073
+ setSelfInfo: setSelfInfo,
2074
+ updateStatus: updateStatus,
1711
2075
  };
1712
2076
  }
1713
2077
  function useKeyframe(key) {
1714
- const live = useLiveInstance();
1715
- const [state, updateState] = React.useState(live.getFramesByKey(key));
1716
- React.useEffect(() => {
1717
- const onUpdate = (nextKeyframes) => updateState(nextKeyframes);
1718
- const evtName = key;
1719
- 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;
1720
2086
  live.keyframes.on(evtName, callback);
1721
- return () => live.keyframes.off(evtName, callback);
2087
+ return function () { return live.keyframes.off(evtName, callback); };
1722
2088
  }, [live]);
1723
- const setState = React.useCallback((frame) => live.sendKeyframe(key, frame), [live]);
2089
+ var setState = React.useCallback(function (frame) { return live.sendKeyframe(key, frame); }, [live]);
1724
2090
  return [state, setState];
1725
2091
  }
1726
- function useLiveEventCallback(name, callback, deps = []) {
1727
- const live = useLiveInstance();
1728
- const dispose = () => live.off(name, callback);
1729
- const dependencyList = [live, name, ...deps];
1730
- 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 () {
1731
2098
  live.on(name, callback);
1732
2099
  return dispose;
1733
2100
  }, dependencyList);
@@ -1738,70 +2105,81 @@ function createLiveReact(options) {
1738
2105
  * @returns
1739
2106
  */
1740
2107
  function useReadyState() {
1741
- const live = useLiveInstance();
1742
- const [state, updateState] = React.useState(live.readyState);
1743
- React.useEffect(() => {
1744
- 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
+ };
1745
2114
  live.on('ws.readyStateUpdate', readyStateUpdate);
1746
- return () => live.off('ws.readyStateUpdate', readyStateUpdate);
2115
+ return function () { return live.off('ws.readyStateUpdate', readyStateUpdate); };
1747
2116
  }, [live]);
1748
2117
  return state;
1749
2118
  }
1750
2119
  function useRTCAction() {
1751
- const live = useLiveInstance();
1752
- const join = React.useCallback((options) => live.$RTC.join(options), [live]);
1753
- const quit = React.useCallback(() => live.$RTC.quit(), [live]);
1754
- const shock = React.useCallback(() => { var _a, _b; return (_b = (_a = live.$RTC).shock) === null || _b === void 0 ? void 0 : _b.call(_a); }, [live]);
1755
- const toggleMicro = React.useCallback((flag) => live.$RTC.toggleMicro(flag), [live]);
1756
- 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]);
1757
2126
  return {
1758
- join,
1759
- quit,
1760
- shock,
1761
- toggleMicro,
1762
- detectMicro,
2127
+ join: join,
2128
+ quit: quit,
2129
+ shock: shock,
2130
+ toggleMicro: toggleMicro,
2131
+ detectMicro: detectMicro,
1763
2132
  };
1764
2133
  }
1765
- function useRTCEventCallback(name, callback, deps = []) {
1766
- const live = useLiveInstance();
1767
- const dispose = () => live.$RTC.off(name, callback);
1768
- const dependencyList = [live, name, ...deps];
1769
- 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 () {
1770
2140
  live.$RTC.on(name, callback);
1771
2141
  return dispose;
1772
2142
  }, dependencyList);
1773
2143
  return dispose;
1774
2144
  }
1775
2145
  function useSelfInfo() {
1776
- const live = useLiveInstance();
1777
- const [state, updateState] = React.useState(live.selfInfo || {});
1778
- const selfInfoUpdate = (userInfo) => updateState(userInfo);
1779
- 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 () {
1780
2153
  live.on('selfInfoUpdate', selfInfoUpdate);
1781
- return () => live.off('selfInfoUpdate', selfInfoUpdate);
1782
- }, [live]);
1783
- const setState = React.useCallback(async (userInfo) => {
1784
- return await live.setSelfInfo(userInfo);
2154
+ return function () { return live.off('selfInfoUpdate', selfInfoUpdate); };
1785
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]);
1786
2164
  return [state, setState];
1787
2165
  }
1788
2166
  function useSnapshot() {
1789
- const live = useLiveInstance();
1790
- const [state, setState] = React.useState(live.snapshot);
1791
- React.useEffect(() => {
1792
- 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); };
1793
2171
  live.on('keyframes', onKeyframes);
1794
- return () => live.off('keyframes', onKeyframes);
2172
+ return function () { return live.off('keyframes', onKeyframes); };
1795
2173
  });
1796
2174
  return state;
1797
2175
  }
1798
2176
  function useUserList() {
1799
- const live = useLiveInstance();
1800
- const [state, updateState] = React.useState(live.userList);
1801
- const userListUpdate = (userList) => updateState(userList);
1802
- 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 () {
1803
2181
  live.on('userListUpdate', userListUpdate);
1804
- return () => live.off('userListUpdate', userListUpdate);
2182
+ return function () { return live.off('userListUpdate', userListUpdate); };
1805
2183
  }, [live]);
1806
2184
  return state;
1807
2185
  }
@@ -1813,35 +2191,36 @@ function createLiveReact(options) {
1813
2191
  * @returns
1814
2192
  * @deprecated
1815
2193
  */
1816
- function useWebSocketEventCallback(name, callback, deps = []) {
1817
- const live = useLiveInstance();
1818
- const dispose = () => live.off(name, callback);
1819
- const dependencyList = [live, name, ...deps];
1820
- 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 () {
1821
2200
  live.on(name, callback);
1822
2201
  return dispose;
1823
2202
  }, dependencyList);
1824
2203
  return dispose;
1825
2204
  }
1826
2205
  return {
1827
- live,
1828
- jsBridge,
1829
- LiveProvider,
1830
- unsafe__useLiveInstance,
1831
- unsafe__useRTCInstance,
1832
- useCurrentWebSocketUrl,
1833
- useConnect,
1834
- useKeyframe,
1835
- useKeyframeUpdateCallback,
1836
- useLiveAction,
1837
- useLiveEventCallback,
1838
- useReadyState,
1839
- useRTCAction,
1840
- useRTCEventCallback,
1841
- useSelfInfo,
1842
- useSnapshot,
1843
- useUserList,
1844
- 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,
1845
2224
  };
1846
2225
  }
1847
2226