@realsee/live 0.4.0-beta.6 → 0.5.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -122,8 +122,37 @@
122
122
  class CoreRTC extends Subscribe$1 {
123
123
  }
124
124
 
125
+ /******************************************************************************
126
+ Copyright (c) Microsoft Corporation.
127
+
128
+ Permission to use, copy, modify, and/or distribute this software for any
129
+ purpose with or without fee is hereby granted.
130
+
131
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
132
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
133
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
134
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
135
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
136
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
137
+ PERFORMANCE OF THIS SOFTWARE.
138
+ ***************************************************************************** */
139
+
140
+ function __awaiter$$(thisArg, _arguments, P, generator) {
141
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
142
+ return new (P || (P = Promise))(function (resolve, reject) {
143
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
144
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
145
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
146
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
147
+ });
148
+ }
149
+
125
150
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
126
151
 
152
+ function getDefaultExportFromCjs (x) {
153
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
154
+ }
155
+
127
156
  function getAugmentedNamespace(n) {
128
157
  if (n.__esModule) return n;
129
158
  var a = Object.defineProperty({}, '__esModule', {value: true});
@@ -203,24 +232,21 @@
203
232
  client: null,
204
233
  stream: null,
205
234
  };
206
- this.join = async (options) => {
235
+ this.join = (options) => __awaiter$$(this, void 0, void 0, function* () {
207
236
  var _a;
208
237
  this.emit('joinWillStart');
209
- const createClientOptions = await this._getVoiceSign({
238
+ const createClientOptions = yield this._getVoiceSign({
210
239
  voiceId: options.voiceId,
211
240
  roomId: options.roomId,
212
241
  userId: options.userId,
213
242
  });
214
243
  // 1. 创建client
215
- this._trtc.client = TRTC.createClient({
216
- mode: 'rtc',
217
- ...createClientOptions,
218
- });
244
+ this._trtc.client = TRTC.createClient(Object.assign({ mode: 'rtc' }, createClientOptions));
219
245
  (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.enableAudioVolumeEvaluation();
220
246
  // 2. 订阅事件
221
247
  this._registerRtcEvent();
222
248
  // 3. 加入语音房间
223
- let result = await new Promise((resolve) => {
249
+ let result = yield new Promise((resolve) => {
224
250
  var _a;
225
251
  (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.join({ roomId: Number(options.voiceId) }).then(() => resolve(true)).catch(() => resolve(false));
226
252
  });
@@ -234,12 +260,12 @@
234
260
  video: false,
235
261
  });
236
262
  // 5. 初始化本地流
237
- result = await new Promise((resolve) => {
263
+ result = yield new Promise((resolve) => {
238
264
  var _a;
239
265
  (_a = this._trtc.stream) === null || _a === void 0 ? void 0 : _a.initialize().then(() => resolve(true)).catch(() => resolve(false));
240
266
  });
241
267
  // 6. 发布本地流
242
- result = await new Promise((resolve) => {
268
+ result = yield new Promise((resolve) => {
243
269
  var _a;
244
270
  (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.publish(this._trtc.stream).then(() => resolve(true)).catch(() => resolve(false));
245
271
  });
@@ -247,7 +273,7 @@
247
273
  if (this.joined)
248
274
  this.emit('joined');
249
275
  return result;
250
- };
276
+ });
251
277
  this._handleStreamAdded = (event) => {
252
278
  var _a;
253
279
  const remoteStream = event.stream;
@@ -275,17 +301,17 @@
275
301
  document.body.appendChild(this.$dom);
276
302
  }
277
303
  quit() {
278
- return new Promise(async (resolve) => {
304
+ return new Promise((resolve) => __awaiter$$(this, void 0, void 0, function* () {
279
305
  var _a, _b;
280
306
  this.joined = false;
281
307
  if (this._trtc.stream) {
282
- await ((_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.unpublish(this._trtc.stream));
308
+ yield ((_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.unpublish(this._trtc.stream));
283
309
  this._trtc.stream.stop();
284
310
  this._trtc.stream.close();
285
311
  this._trtc.stream = null;
286
312
  }
287
313
  (_b = this._trtc.client) === null || _b === void 0 ? void 0 : _b.leave().then(() => (this._trtc.client = null)).then(() => resolve(true)).catch(() => resolve(false));
288
- });
314
+ }));
289
315
  }
290
316
  detectMicro() {
291
317
  return new Promise((resolve) => {
@@ -614,7 +640,7 @@
614
640
 
615
641
  });
616
642
 
617
- var LogLevel_1$1 = createCommonjsModule(function (module, exports) {
643
+ var LogLevel_1 = createCommonjsModule(function (module, exports) {
618
644
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
619
645
  // SPDX-License-Identifier: Apache-2.0
620
646
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -631,7 +657,7 @@
631
657
 
632
658
  });
633
659
 
634
- var LogLevel_1 = LogLevel_1$1;
660
+ var LogLevel = /*@__PURE__*/getDefaultExportFromCjs(LogLevel_1);
635
661
 
636
662
  var AsyncScheduler_1 = AsyncScheduler_1$1;
637
663
 
@@ -48328,65 +48354,64 @@
48328
48354
  * @param options
48329
48355
  * @returns
48330
48356
  */
48331
- async join(options) {
48332
- return new Promise(async (success, fail) => {
48333
- var _a;
48334
- this.emit('joinWillStart');
48335
- try {
48336
- // 取签名
48337
- const { sdkAppId, userId, roomId, userSig } = await this._getVoiceSign({
48338
- ...options,
48339
- roomId: options.roomId || 0,
48340
- });
48341
- this.userId = userId;
48342
- const { attendence, vendor_wrapper, } = JSON.parse(decodeURIComponent(userSig));
48343
- // 初始化配置
48344
- const configuration = new build.MeetingSessionConfiguration({
48345
- Meeting: vendor_wrapper,
48346
- }, {
48347
- Attendee: {
48348
- ExternalUserId: attendence.external_user_id,
48349
- AttendeeId: attendence.attendee_id,
48350
- JoinToken: attendence.join_token,
48351
- },
48352
- });
48353
- // 初始化会议会话
48354
- this.meetingSession = new build.DefaultMeetingSession(configuration, this.logger, this.deviceController);
48355
- // 注册事件
48356
- this._registerRtcEvent();
48357
- // 绑定监听器
48358
- this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver);
48359
- this.meetingSession.audioVideo.addObserver(this.audioVideoObserver);
48360
- // 绑定播放器
48361
- this.meetingSession.audioVideo.bindAudioElement(this.$audio);
48362
- const observer = {
48363
- audioVideoDidStart: () => {
48364
- var _a;
48365
- (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeMuteLocalAudio();
48366
- this.joined = true;
48367
- this.emit('joined');
48368
- success(true);
48369
- },
48370
- audioVideoDidStop: () => {
48371
- this.joined = false;
48372
- success(false);
48373
- },
48374
- };
48375
- this.meetingSession.audioVideo.addObserver(observer);
48376
- // 选择语音输入设备
48377
- const audioInputDevices = await this.deviceController.listAudioInputDevices(true);
48378
- const defaultAudioInput = audioInputDevices.find((device) => device.deviceId === 'default');
48379
- const otherAudioInput = audioInputDevices.find((device) => device.deviceId !== '');
48380
- this.audioInput = defaultAudioInput || otherAudioInput;
48381
- await this.meetingSession.audioVideo.chooseVideoInputDevice(null);
48382
- await this.meetingSession.audioVideo.chooseAudioInputDevice(((_a = this.audioInput) === null || _a === void 0 ? void 0 : _a.deviceId) || 'default');
48383
- this.meetingSession.audioVideo.start();
48384
- }
48385
- catch (e) {
48386
- this.emit('error', e);
48387
- this.logger.error(e.message);
48388
- success(false);
48389
- }
48357
+ join(options) {
48358
+ return __awaiter$$(this, void 0, void 0, function* () {
48359
+ return new Promise((success, fail) => __awaiter$$(this, void 0, void 0, function* () {
48360
+ var _a;
48361
+ this.emit('joinWillStart');
48362
+ try {
48363
+ // 取签名
48364
+ const { sdkAppId, userId, roomId, userSig } = yield this._getVoiceSign(Object.assign(Object.assign({}, options), { roomId: options.roomId || 0 }));
48365
+ this.userId = userId;
48366
+ const { attendence, vendor_wrapper, } = JSON.parse(decodeURIComponent(userSig));
48367
+ // 初始化配置
48368
+ const configuration = new build.MeetingSessionConfiguration({
48369
+ Meeting: vendor_wrapper,
48370
+ }, {
48371
+ Attendee: {
48372
+ ExternalUserId: attendence.external_user_id,
48373
+ AttendeeId: attendence.attendee_id,
48374
+ JoinToken: attendence.join_token,
48375
+ },
48376
+ });
48377
+ // 初始化会议会话
48378
+ this.meetingSession = new build.DefaultMeetingSession(configuration, this.logger, this.deviceController);
48379
+ // 注册事件
48380
+ this._registerRtcEvent();
48381
+ // 绑定监听器
48382
+ this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver);
48383
+ this.meetingSession.audioVideo.addObserver(this.audioVideoObserver);
48384
+ // 绑定播放器
48385
+ this.meetingSession.audioVideo.bindAudioElement(this.$audio);
48386
+ const observer = {
48387
+ audioVideoDidStart: () => {
48388
+ var _a;
48389
+ (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeMuteLocalAudio();
48390
+ this.joined = true;
48391
+ this.emit('joined');
48392
+ success(true);
48393
+ },
48394
+ audioVideoDidStop: () => {
48395
+ this.joined = false;
48396
+ success(false);
48397
+ },
48398
+ };
48399
+ this.meetingSession.audioVideo.addObserver(observer);
48400
+ // 选择语音输入设备
48401
+ const audioInputDevices = yield this.deviceController.listAudioInputDevices(true);
48402
+ const defaultAudioInput = audioInputDevices.find((device) => device.deviceId === 'default');
48403
+ const otherAudioInput = audioInputDevices.find((device) => device.deviceId !== '');
48404
+ this.audioInput = defaultAudioInput || otherAudioInput;
48405
+ yield this.meetingSession.audioVideo.chooseVideoInputDevice(null);
48406
+ yield this.meetingSession.audioVideo.chooseAudioInputDevice(((_a = this.audioInput) === null || _a === void 0 ? void 0 : _a.deviceId) || 'default');
48407
+ this.meetingSession.audioVideo.start();
48408
+ }
48409
+ catch (e) {
48410
+ this.emit('error', e);
48411
+ this.logger.error(e.message);
48412
+ success(false);
48413
+ }
48414
+ }));
48390
48415
  });
48391
48416
  }
48392
48417
  quit() {
@@ -48416,36 +48441,40 @@
48416
48441
  (_b = this.meetingSession) === null || _b === void 0 ? void 0 : _b.audioVideo.stop();
48417
48442
  });
48418
48443
  }
48419
- async detectMicro() {
48420
- return new Promise((resolve) => {
48421
- const rule = { audio: true, video: false };
48422
- try {
48423
- navigator.mediaDevices
48424
- .getUserMedia(rule)
48425
- .then(() => resolve(true))
48426
- .catch(() => resolve(false));
48427
- }
48428
- catch (e) {
48429
- this.logger.error(e.message);
48430
- resolve(false);
48431
- }
48444
+ detectMicro() {
48445
+ return __awaiter$$(this, void 0, void 0, function* () {
48446
+ return new Promise((resolve) => {
48447
+ const rule = { audio: true, video: false };
48448
+ try {
48449
+ navigator.mediaDevices
48450
+ .getUserMedia(rule)
48451
+ .then(() => resolve(true))
48452
+ .catch(() => resolve(false));
48453
+ }
48454
+ catch (e) {
48455
+ this.logger.error(e.message);
48456
+ resolve(false);
48457
+ }
48458
+ });
48432
48459
  });
48433
48460
  }
48434
- async toggleMicro(flag) {
48461
+ toggleMicro(flag) {
48435
48462
  var _a, _b, _c;
48436
- if (flag) {
48437
- (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeUnmuteLocalAudio();
48438
- }
48439
- else {
48440
- (_b = this.meetingSession) === null || _b === void 0 ? void 0 : _b.audioVideo.realtimeMuteLocalAudio();
48441
- }
48442
- const muted = (_c = this.meetingSession) === null || _c === void 0 ? void 0 : _c.audioVideo.realtimeIsLocalAudioMuted();
48443
- if (muted !== undefined) {
48444
- return flag !== muted;
48445
- }
48446
- else {
48447
- return false;
48448
- }
48463
+ return __awaiter$$(this, void 0, void 0, function* () {
48464
+ if (flag) {
48465
+ (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeUnmuteLocalAudio();
48466
+ }
48467
+ else {
48468
+ (_b = this.meetingSession) === null || _b === void 0 ? void 0 : _b.audioVideo.realtimeMuteLocalAudio();
48469
+ }
48470
+ const muted = (_c = this.meetingSession) === null || _c === void 0 ? void 0 : _c.audioVideo.realtimeIsLocalAudioMuted();
48471
+ if (muted !== undefined) {
48472
+ return flag !== muted;
48473
+ }
48474
+ else {
48475
+ return false;
48476
+ }
48477
+ });
48449
48478
  }
48450
48479
  shock() {
48451
48480
  throw new Error('Method not implemented.');
@@ -48494,51 +48523,59 @@
48494
48523
  get jsBridge() {
48495
48524
  return this.options.jsBridge;
48496
48525
  }
48497
- async join(options) {
48498
- this.emit('joinWillStart');
48499
- const { sdkAppId, userId, userSig } = await this.options.getVoiceSign(options);
48500
- this.type = options.type;
48501
- const [res, error] = await this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${sdkAppId}&userID=${userId}&roomID=${Number(options.voiceId)}&userSig=${userSig}`);
48502
- if (!res) {
48503
- this.emit('error', error ? error : new Error('加入房间失败:未知异常。'));
48504
- this.joined = false;
48505
- }
48506
- else {
48507
- if (res.code === exports.RTCJoinedInfoCodeEnum.Success) {
48508
- this.emit('joined');
48509
- this.joined = true;
48526
+ join(options) {
48527
+ return __awaiter$$(this, void 0, void 0, function* () {
48528
+ this.emit('joinWillStart');
48529
+ const { sdkAppId, userId, userSig } = yield this.options.getVoiceSign(options);
48530
+ this.type = options.type;
48531
+ const [res, error] = yield this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${sdkAppId}&userID=${userId}&roomID=${Number(options.voiceId)}&userSig=${userSig}`);
48532
+ if (!res) {
48533
+ this.emit('error', error ? error : new Error('加入房间失败:未知异常。'));
48534
+ this.joined = false;
48510
48535
  }
48511
48536
  else {
48512
- this.emit('error', res);
48513
- this.joined = false;
48537
+ if (res.code === exports.RTCJoinedInfoCodeEnum.Success) {
48538
+ this.emit('joined');
48539
+ this.joined = true;
48540
+ }
48541
+ else {
48542
+ this.emit('error', res);
48543
+ this.joined = false;
48544
+ }
48514
48545
  }
48515
- }
48516
- return this.joined;
48546
+ return this.joined;
48547
+ });
48517
48548
  }
48518
- async quit() {
48519
- const [res, error] = await this.jsBridge.callAndBackfeed('live/quit');
48520
- if (res === null) {
48521
- this.emit('error', error ? error : new Error('退出房间失败:未知异常。'));
48522
- }
48523
- this.joined = false;
48524
- return !!res;
48549
+ quit() {
48550
+ return __awaiter$$(this, void 0, void 0, function* () {
48551
+ const [res, error] = yield this.jsBridge.callAndBackfeed('live/quit');
48552
+ if (res === null) {
48553
+ this.emit('error', error ? error : new Error('退出房间失败:未知异常。'));
48554
+ }
48555
+ this.joined = false;
48556
+ return !!res;
48557
+ });
48525
48558
  }
48526
- async detectMicro() {
48527
- const [res, error] = await this.jsBridge.detectMicro();
48528
- if (res === null) {
48529
- this.emit('error', error ? error : new Error('麦克风监测异常!'));
48530
- return false;
48531
- }
48532
- return res;
48559
+ detectMicro() {
48560
+ return __awaiter$$(this, void 0, void 0, function* () {
48561
+ const [res, error] = yield this.jsBridge.detectMicro();
48562
+ if (res === null) {
48563
+ this.emit('error', error ? error : new Error('麦克风监测异常!'));
48564
+ return false;
48565
+ }
48566
+ return res;
48567
+ });
48533
48568
  }
48534
- async toggleMicro(flag) {
48535
- const [res, error] = await this.jsBridge.callAndBackfeed(`live/toggleMicro?flag=${!!flag ? 1 : 0}`);
48536
- if (res === null) {
48537
- this.emit('error', error ? error : new Error('麦克风监测异常!'));
48538
- return false;
48539
- }
48540
- this.micro = res;
48541
- return res;
48569
+ toggleMicro(flag) {
48570
+ return __awaiter$$(this, void 0, void 0, function* () {
48571
+ const [res, error] = yield this.jsBridge.callAndBackfeed(`live/toggleMicro?flag=${!!flag ? 1 : 0}`);
48572
+ if (res === null) {
48573
+ this.emit('error', error ? error : new Error('麦克风监测异常!'));
48574
+ return false;
48575
+ }
48576
+ this.micro = res;
48577
+ return res;
48578
+ });
48542
48579
  }
48543
48580
  shock() {
48544
48581
  this.jsBridge.shock(1);
@@ -48915,7 +48952,14 @@
48915
48952
  const msg = JSON.stringify({
48916
48953
  actionUrl,
48917
48954
  functionName: registerGlobalValue(this.createSchemeLink(scheme), (data) => {
48918
- const d = JSON.parse(data);
48955
+ const d = (() => {
48956
+ try {
48957
+ return JSON.parse(data);
48958
+ }
48959
+ catch (e) {
48960
+ return data;
48961
+ }
48962
+ })();
48919
48963
  res[0] = (() => {
48920
48964
  if (d === 1)
48921
48965
  return true;
@@ -48940,7 +48984,14 @@
48940
48984
  return await new Promise(async (resolve) => {
48941
48985
  const actionUrl = this.createSchemeLink(scheme);
48942
48986
  const _callback = (data) => {
48943
- const d = JSON.parse(data);
48987
+ const d = (() => {
48988
+ try {
48989
+ return JSON.parse(data);
48990
+ }
48991
+ catch (e) {
48992
+ return data;
48993
+ }
48994
+ })();
48944
48995
  const callbackParam = (() => {
48945
48996
  if (d === 1)
48946
48997
  return true;
@@ -48994,7 +49045,9 @@
48994
49045
  const check = () => {
48995
49046
  if (this.worker)
48996
49047
  return resolve(true);
48997
- if ($window.webkit && $window.webkit.messageHandlers && $window.webkit.messageHandlers.realsee) {
49048
+ if ($window.webkit &&
49049
+ $window.webkit.messageHandlers &&
49050
+ $window.webkit.messageHandlers.realsee) {
48998
49051
  const worker = $window.webkit.messageHandlers.realsee;
48999
49052
  worker.postMessage(JSON.stringify({
49000
49053
  type: 'getStaticData',
@@ -49003,8 +49056,8 @@
49003
49056
  this.deviceInfo = JSON.parse(data);
49004
49057
  this.worker = worker;
49005
49058
  return resolve(true);
49006
- })
49007
- })
49059
+ }),
49060
+ }),
49008
49061
  }));
49009
49062
  return;
49010
49063
  }
@@ -49060,7 +49113,14 @@
49060
49113
  const msg = JSON.stringify({
49061
49114
  actionUrl,
49062
49115
  functionName: registerGlobalValue(this.createSchemeLink(scheme), (data) => {
49063
- const d = JSON.parse(data);
49116
+ const d = (() => {
49117
+ try {
49118
+ return JSON.parse(data);
49119
+ }
49120
+ catch (e) {
49121
+ return data;
49122
+ }
49123
+ })();
49064
49124
  res[0] = (() => {
49065
49125
  if (d === 1)
49066
49126
  return true;
@@ -49069,11 +49129,11 @@
49069
49129
  return d;
49070
49130
  })();
49071
49131
  resolve(res);
49072
- })
49132
+ }),
49073
49133
  });
49074
49134
  this.worker.postMessage(JSON.stringify({
49075
49135
  type: 'callAndBackfeed',
49076
- param: msg
49136
+ param: msg,
49077
49137
  }));
49078
49138
  });
49079
49139
  }
@@ -49088,7 +49148,14 @@
49088
49148
  return await new Promise(async (resolve) => {
49089
49149
  const actionUrl = this.createSchemeLink(scheme);
49090
49150
  const _callback = (data) => {
49091
- const d = JSON.parse(data);
49151
+ const d = (() => {
49152
+ try {
49153
+ return JSON.parse(data);
49154
+ }
49155
+ catch (e) {
49156
+ return data;
49157
+ }
49158
+ })();
49092
49159
  const callbackParam = (() => {
49093
49160
  if (d === 1)
49094
49161
  return true;
@@ -49111,7 +49178,7 @@
49111
49178
  };
49112
49179
  const msg = JSON.stringify({
49113
49180
  actionUrl,
49114
- functionName: registerGlobalValue(actionUrl, _callback, false)
49181
+ functionName: registerGlobalValue(actionUrl, _callback, false),
49115
49182
  });
49116
49183
  this.worker.postMessage(JSON.stringify({
49117
49184
  type: 'callAndListen',
@@ -49146,48 +49213,38 @@
49146
49213
  WeappBridgeMessage["alive"] = "I`m alive!";
49147
49214
  })(WeappBridgeMessage || (WeappBridgeMessage = {}));
49148
49215
 
49216
+ const endpoint = 'wss://ws.realsee.com';
49217
+ var defaultWsEndpoint = endpoint;
49218
+
49149
49219
  /**
49150
- * ws的状态
49151
- * 参考https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
49220
+ * 拼接ws链接
49221
+ * @param tpl
49222
+ * @param params
49223
+ * @returns
49152
49224
  */
49153
- var WebSocketState;
49154
- (function (WebSocketState) {
49155
- WebSocketState[WebSocketState["CONNECTING"] = 0] = "CONNECTING";
49156
- WebSocketState[WebSocketState["OPEN"] = 1] = "OPEN";
49157
- WebSocketState[WebSocketState["CLOSING"] = 2] = "CLOSING";
49158
- WebSocketState[WebSocketState["CLOSED"] = 3] = "CLOSED";
49159
- })(WebSocketState || (WebSocketState = {}));
49225
+ const generateWssUrl = (tpl, params) => {
49226
+ const url = Object.keys(params).reduce((res, curr) => res.replace(`{{${curr}}}`, `${params[curr]}`), tpl);
49227
+ return encodeURI(url);
49228
+ };
49229
+ var generateWssUrl$1 = generateWssUrl;
49230
+
49231
+ const isValidKey = (key, object) => key in object;
49232
+ var isValidKey$1 = isValidKey;
49160
49233
 
49161
49234
  /**
49162
- * ws 关闭的原因
49235
+ * 解析参数
49236
+ * @param query
49237
+ * @returns
49163
49238
  */
49164
- const WebSocketCloseOptions = {
49165
- /**
49166
- * 重连关闭
49167
- */
49168
- reconnect: { code: 1000, reason: 'close websocket when reconnecting' },
49169
- /**
49170
- * 主动关闭
49171
- */
49172
- normalClosure: { code: 1000, reason: 'normal closure' },
49173
- /**
49174
- * 强制关闭
49175
- */
49176
- forceClosure: { code: 1000, reason: 'force closure' },
49177
- /**
49178
- * 切换到后台,被微信杀掉,需要重连连接
49179
- */
49180
- interrupted: { code: 1000, reason: 'interrupted' },
49181
- /**
49182
- * 服务端拒绝连接
49183
- */
49184
- streamEndEncountered: { code: 1000, reason: 'stream end encountered' },
49185
- /**
49186
- * 丢失心跳
49187
- * @deprecated
49188
- */
49189
- lostHeartbeat: { code: 1000, reason: 'lost heartbeat' },
49190
- };
49239
+ const parseQuery = (query = '') => query
49240
+ .replace('?', '')
49241
+ .split('&')
49242
+ .map((qs) => {
49243
+ const [k, v] = qs.split('=');
49244
+ return { [k]: decodeURIComponent(v) };
49245
+ })
49246
+ .reduce((result, curr) => ({ ...result, ...curr }), {});
49247
+ var parseQuery$1 = parseQuery;
49191
49248
 
49192
49249
  const EVENT_SYMBOL = '$$REALSEE_JSBRIDGE_EVENT$$';
49193
49250
  function __generateEventIfNotExisted(instance) {
@@ -49302,228 +49359,253 @@
49302
49359
  }
49303
49360
 
49304
49361
  /**
49305
- * ws的事件
49362
+ * 具有鲁棒性的WebSocket封装
49363
+ * 1、自动重连
49364
+ * 2、可根据网络情况进行重连
49306
49365
  */
49307
- var WebSocketEvent;
49308
- (function (WebSocketEvent) {
49309
- WebSocketEvent["open"] = "open";
49310
- WebSocketEvent["close"] = "close";
49311
- WebSocketEvent["error"] = "error";
49312
- WebSocketEvent["message"] = "message";
49313
- })(WebSocketEvent || (WebSocketEvent = {}));
49314
-
49315
- class Ws4Webview extends Subscribe {
49316
- constructor() {
49317
- super(...arguments);
49318
- this._state = null;
49366
+ class RobustWebSocket$1 extends Subscribe {
49367
+ constructor(options) {
49368
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
49369
+ super();
49370
+ this._options = {
49371
+ timeout: 10000,
49372
+ shouldReconnect: (event, ws) => {
49373
+ if (event.code === 1008 || event.code === 1011)
49374
+ return;
49375
+ return [0, 3000, 10000][ws.attempts];
49376
+ },
49377
+ should1000Reconnect: false,
49378
+ ignoreConnectivityEvents: false,
49379
+ automaticOpen: false,
49380
+ };
49381
+ this._attempts = 0;
49382
+ this._reconnects = -1;
49383
+ this._reconnectWhenOnlineAgain = false;
49384
+ this._explicitlyClosed = false;
49385
+ this._connectivityEventsAttached = false;
49319
49386
  /**
49320
- * @description 注册ws接通事件回调
49321
- * @param listener 事件回调函数
49322
- * @param once 是否只执行一次
49323
- * @returns
49387
+ * 清理连接中的请求
49324
49388
  */
49325
- this.onOpen = (listener, once) => once ? this.once(WebSocketEvent.open, listener) : this.on(WebSocketEvent.open, listener);
49389
+ this._clearPendingReconnectIfNeeded = () => {
49390
+ if (this._pendingReconnect) {
49391
+ clearTimeout(this._pendingReconnect);
49392
+ this._pendingReconnect = undefined;
49393
+ }
49394
+ };
49326
49395
  /**
49327
- * @description 注册一次ws接通事件回调
49328
- * @param listener 事件回调函数
49396
+ * 当网页连接上网络进行重连
49397
+ * @param event
49329
49398
  */
49330
- this.onceOpen = (listener) => this.onOpen(listener, true);
49399
+ this._online = (event) => {
49400
+ if (this._reconnectWhenOnlineAgain) {
49401
+ this._clearPendingReconnectIfNeeded();
49402
+ this._reconnect(event);
49403
+ }
49404
+ };
49331
49405
  /**
49332
- * @description 移除ws接通事件回调
49333
- * @param listener 事件回调函数
49334
- * @returns
49406
+ * 当网页断开网络进行关闭
49335
49407
  */
49336
- this.offOpen = (listener) => this.hasListener(WebSocketEvent.open) && this.off(WebSocketEvent.open, listener);
49408
+ this._offline = () => {
49409
+ var _a;
49410
+ this._reconnectWhenOnlineAgain = true;
49411
+ (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.close(1000);
49412
+ };
49337
49413
  /**
49338
- * @description 注册ws消息事件回调
49339
- * @param listener 事件回调函数
49340
- * @param once 是否只执行一次
49341
- * @returns
49414
+ * 解除网络监听事件
49342
49415
  */
49343
- this.onMessage = (listener, once) => once ? this.once(WebSocketEvent.message, listener) : this.on(WebSocketEvent.message, listener);
49416
+ this._detachConnectivityEvents = () => {
49417
+ if (this._connectivityEventsAttached) {
49418
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.removeEventListener('online', this._online);
49419
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.removeEventListener('offline', this._offline);
49420
+ this._connectivityEventsAttached = false;
49421
+ }
49422
+ };
49344
49423
  /**
49345
- * @description 注册一次ws消息事件回调
49346
- * @param listener 事件回调函数
49424
+ * 注册网络监听事件
49347
49425
  */
49348
- this.onceMessage = (listener) => this.onMessage(listener, true);
49426
+ this._attachConnectivityEvents = () => {
49427
+ if (!this._connectivityEventsAttached) {
49428
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.addEventListener('online', this._online);
49429
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.addEventListener('offline', this._offline);
49430
+ this._connectivityEventsAttached = true;
49431
+ }
49432
+ };
49349
49433
  /**
49350
- * @description 移除ws接通事件回调
49351
- * @param listener 事件回调函数
49434
+ * 发送消息
49435
+ * @param data
49352
49436
  * @returns
49353
49437
  */
49354
- this.offMessage = (listener) => this.hasListener(WebSocketEvent.message) && this.off(WebSocketEvent.message, listener);
49438
+ this.send = (data) => { var _a; return (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.send(data); };
49355
49439
  /**
49356
- * @description 注册ws错误事件回调
49357
- * @param listener 事件回调函数
49358
- * @param once 是否只执行一次
49440
+ * 关闭连接
49441
+ * @param code 代码
49442
+ * @param reason 原因
49359
49443
  * @returns
49360
49444
  */
49361
- this.onError = (listener, once) => once ? this.once(WebSocketEvent.error, listener) : this.on(WebSocketEvent.error, listener);
49445
+ this.close = (code, reason) => {
49446
+ var _a;
49447
+ if (typeof code !== 'number') {
49448
+ reason = code;
49449
+ code = 1000;
49450
+ }
49451
+ this._clearPendingReconnectIfNeeded();
49452
+ this._reconnectWhenOnlineAgain = false;
49453
+ this._explicitlyClosed = true;
49454
+ this._detachConnectivityEvents();
49455
+ return (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.close(code, reason);
49456
+ };
49362
49457
  /**
49363
- * @description 注册一次ws消息事件回调
49364
- * @param listener 事件回调函数
49458
+ * 进行ws连接
49365
49459
  */
49366
- this.onceError = (listener) => this.onError(listener, true);
49460
+ this.open = (url) => {
49461
+ var _a, _b;
49462
+ if (url) {
49463
+ this._url = url;
49464
+ }
49465
+ if (((_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.readyState) !== WebSocket.OPEN &&
49466
+ ((_b = this._realWebSocket) === null || _b === void 0 ? void 0 : _b.readyState) !== WebSocket.CONNECTING) {
49467
+ this._clearPendingReconnectIfNeeded();
49468
+ this._reconnectWhenOnlineAgain = false;
49469
+ this._explicitlyClosed = false;
49470
+ this._createWebSocket();
49471
+ }
49472
+ };
49367
49473
  /**
49368
- * @description 移除ws接通事件回调
49369
- * @param listener 事件回调函数
49474
+ * 创建ws连接
49475
+ */
49476
+ this._createWebSocket = () => {
49477
+ var _a, _b, _c;
49478
+ const newUrl = typeof this._url === 'string' ? this._url : (_a = this._url) === null || _a === void 0 ? void 0 : _a.call(this, this);
49479
+ if (!newUrl)
49480
+ return;
49481
+ this._pendingReconnect = undefined;
49482
+ this._realWebSocket = new WebSocket(newUrl, this._protocols || undefined);
49483
+ this._attempts = this._attempts + 1;
49484
+ this.emit('connecting', new CustomEvent('connecting', {
49485
+ detail: { attempts: this._attempts, reconnects: this._reconnects },
49486
+ }));
49487
+ const timeoutCallback = () => {
49488
+ this._connectTimeout = undefined;
49489
+ this._detachConnectivityEvents();
49490
+ this.emit('timeout', new CustomEvent('connecting', {
49491
+ detail: {
49492
+ attempts: this._attempts,
49493
+ reconnects: this._reconnects,
49494
+ },
49495
+ }));
49496
+ };
49497
+ this._connectTimeout = setTimeout(timeoutCallback, (_b = this._options) === null || _b === void 0 ? void 0 : _b.timeout);
49498
+ this._dispatchWebSocketEvent();
49499
+ if (!((_c = this._options) === null || _c === void 0 ? void 0 : _c.ignoreConnectivityEvents)) {
49500
+ this._attachConnectivityEvents();
49501
+ }
49502
+ };
49503
+ /**
49504
+ * 分发ws事件
49505
+ */
49506
+ this._dispatchWebSocketEvent = () => {
49507
+ var _a, _b, _c, _d;
49508
+ (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.addEventListener('open', this._webSocketOpenHandler);
49509
+ (_b = this._realWebSocket) === null || _b === void 0 ? void 0 : _b.addEventListener('close', this._webSocketCloseHandler);
49510
+ (_c = this._realWebSocket) === null || _c === void 0 ? void 0 : _c.addEventListener('error', this._webSocketErrorHandler);
49511
+ (_d = this._realWebSocket) === null || _d === void 0 ? void 0 : _d.addEventListener('message', this._webSocketMessageHandler);
49512
+ };
49513
+ /**
49514
+ * ws连接事件
49370
49515
  * @returns
49371
49516
  */
49372
- this.offError = (listener) => this.hasListener(WebSocketEvent.error) && this.off(WebSocketEvent.error, listener);
49517
+ this._webSocketOpenHandler = (event) => {
49518
+ if (this._connectTimeout) {
49519
+ clearTimeout(this._connectTimeout);
49520
+ this._connectTimeout = undefined;
49521
+ }
49522
+ const reconnects = ++this._reconnects;
49523
+ const attempts = this._attempts;
49524
+ this._attempts = 0;
49525
+ this._reconnectWhenOnlineAgain = false;
49526
+ return this.emit('open', Object.assign(event, { detail: { reconnects, attempts } }));
49527
+ };
49373
49528
  /**
49374
- * @description 注册ws错误事件回调
49375
- * @param listener 事件回调函数
49376
- * @param once 是否只执行一次
49529
+ * ws 关闭事件
49530
+ * @param event
49377
49531
  * @returns
49378
49532
  */
49379
- this.onClose = (listener, once) => once ? this.once(WebSocketEvent.close, listener) : this.on(WebSocketEvent.close, listener);
49533
+ this._webSocketCloseHandler = (event) => {
49534
+ this._reconnect(event);
49535
+ return this.emit('close', event);
49536
+ };
49380
49537
  /**
49381
- * @description 注册一次ws消息事件回调
49382
- * @param listener 事件回调函数
49538
+ * ws 异常
49539
+ * @param event
49540
+ * @returns
49383
49541
  */
49384
- this.onceClose = (listener) => this.onClose(listener, true);
49542
+ this._webSocketErrorHandler = (event) => {
49543
+ return this.emit('error', new CustomEvent('error', { detail: { error: event } }));
49544
+ };
49385
49545
  /**
49386
- * @description 移除ws接通事件回调
49387
- * @param listener 事件回调函数
49546
+ * ws消息
49547
+ * @param event
49388
49548
  * @returns
49389
49549
  */
49390
- this.offClose = (listener) => this.hasListener(WebSocketEvent.close) && this.off(WebSocketEvent.close, listener);
49391
- }
49392
- get readyState() {
49393
- return this._state;
49394
- }
49395
- /**
49396
- * 连接ws
49397
- * @param options
49398
- */
49399
- connect(options) {
49400
- if (this._state === WebSocketState.CONNECTING || this._state === WebSocketState.OPEN)
49401
- return Promise.reject("\u5DF2\u5B58\u5728\u4E00\u4E2A\u8FDE\u63A5\u4E2D\u6216\u6253\u5F00\u72B6\u6001\u7684websocket\u5B9E\u4F8B" /* ErrorMessage.WsAlreadyExists */);
49402
- return new Promise((resolve, reject) => {
49403
- const { url } = options;
49404
- if (!url)
49405
- throw new Error("\u975E\u6CD5\u7684websocket\u94FE\u63A5" /* ErrorMessage.WsUrlInvalid */);
49406
- this._wsOptions = options;
49407
- this._state = WebSocketState.CONNECTING;
49408
- this._wsTask = new WebSocket(url);
49409
- this.registerEventHandler();
49410
- this.handleConnected();
49411
- this.onceOpen(() => resolve(true));
49412
- this.onceError((err) => reject(err));
49413
- });
49550
+ this._webSocketMessageHandler = (event) => {
49551
+ return this.emit('message', event);
49552
+ };
49553
+ if (options) {
49554
+ this.setOptions(options);
49555
+ }
49414
49556
  }
49415
- /**
49416
- * 重连websocket
49417
- * @returns
49418
- */
49419
- async reconnect() {
49420
- this.close(WebSocketCloseOptions.reconnect);
49421
- if (this._wsOptions)
49422
- this.connect(this._wsOptions);
49557
+ get attempts() {
49558
+ return this._attempts;
49423
49559
  }
49424
- /**
49425
- * @description 发送消息
49426
- * @param data 消息体
49427
- */
49428
- send(data) {
49429
- try {
49430
- if (this._wsTask && this.readyState === WebSocketState.OPEN) {
49431
- this._wsTask.send(data);
49432
- }
49433
- else if (this._wsTask && this.readyState === WebSocketState.CONNECTING) {
49434
- this.once(WebSocketEvent.open, () => { var _a; return (_a = this._wsTask) === null || _a === void 0 ? void 0 : _a.send(data); });
49435
- }
49436
- else {
49437
- this.once(WebSocketEvent.open, () => this.send(data));
49438
- this.reconnect();
49439
- }
49560
+ setOptions(options) {
49561
+ if (!options)
49562
+ return;
49563
+ this._url = options.url;
49564
+ this._protocols = options.protocols;
49565
+ const opts = Object.assign(this._options, options.robustOptions || {});
49566
+ if (typeof (opts === null || opts === void 0 ? void 0 : opts.timeout) !== 'number') {
49567
+ throw new Error('timeout must be the number of milliseconds to timeout a connection attempt');
49440
49568
  }
49441
- catch (e) {
49442
- this.once(WebSocketEvent.open, () => this.send(data));
49443
- this.reconnect();
49569
+ if (typeof (opts === null || opts === void 0 ? void 0 : opts.shouldReconnect) !== 'function') {
49570
+ throw new Error('shouldReconnect must be a function that returns the number of milliseconds to wait for a reconnect attempt, or null or undefined to not reconnect.');
49571
+ }
49572
+ this._options = opts;
49573
+ if (this._options.automaticOpen) {
49574
+ this._createWebSocket();
49444
49575
  }
49445
49576
  }
49446
49577
  /**
49447
- * @description 手动关闭ws
49448
- * @param options 关闭ws的配置参数
49449
- */
49450
- close(options) {
49451
- var _a;
49452
- this._state = WebSocketState.CLOSING;
49453
- (_a = this._wsTask) === null || _a === void 0 ? void 0 : _a.close(options.code, options.reason);
49454
- }
49455
- /**
49456
- * 处理连接后的事件绑定
49457
- */
49458
- handleConnected() {
49459
- this.onceOpen(() => (this._state = WebSocketState.OPEN));
49460
- this.onClose(() => (this._state = WebSocketState.CLOSED));
49461
- }
49462
- /**
49463
- * 注册websocket事件
49578
+ * 进行重连
49579
+ * @param event
49580
+ * @returns
49464
49581
  */
49465
- registerEventHandler() {
49582
+ _reconnect(event) {
49466
49583
  var _a, _b, _c, _d;
49467
- (_a = this._wsTask) === null || _a === void 0 ? void 0 : _a.addEventListener(WebSocketEvent.open, (ev) => this.emit(WebSocketEvent.open, ev));
49468
- (_b = this._wsTask) === null || _b === void 0 ? void 0 : _b.addEventListener(WebSocketEvent.message, (result) => {
49469
- let data = result.data;
49470
- try {
49471
- if (typeof result.data === 'string') {
49472
- data = JSON.parse(result.data);
49473
- }
49474
- }
49475
- catch (e) {
49476
- /** 不可序列化的数据不用处理 */
49477
- }
49478
- this.emit(WebSocketEvent.message, data);
49479
- });
49480
- (_c = this._wsTask) === null || _c === void 0 ? void 0 : _c.addEventListener(WebSocketEvent.close, (ev) => this.emit(WebSocketEvent.close, ev));
49481
- (_d = this._wsTask) === null || _d === void 0 ? void 0 : _d.addEventListener(WebSocketEvent.error, (ev) => this.emit(WebSocketEvent.error, ev));
49584
+ if ((!((_a = this._options) === null || _a === void 0 ? void 0 : _a.should1000Reconnect) && event.code === 1000) ||
49585
+ this._explicitlyClosed) {
49586
+ this._attempts = 0;
49587
+ return;
49588
+ }
49589
+ if (((_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _b === void 0 ? void 0 : _b.onLine) === false) {
49590
+ this._reconnectWhenOnlineAgain = true;
49591
+ return;
49592
+ }
49593
+ const delay = (_d = (_c = this._options) === null || _c === void 0 ? void 0 : _c.shouldReconnect) === null || _d === void 0 ? void 0 : _d.call(_c, event, this);
49594
+ if (typeof delay === 'number') {
49595
+ this._pendingReconnect = setTimeout(this._createWebSocket, delay);
49596
+ }
49482
49597
  }
49483
- }
49484
- var Ws4Webview$1 = Ws4Webview;
49485
-
49486
- const endpoint = 'wss://ws.realsee.com';
49487
- var defaultWsEndpoint = endpoint;
49488
-
49489
- /**
49490
- * 拼接ws链接
49491
- * @param tpl
49492
- * @param params
49493
- * @returns
49494
- */
49495
- const generateWssUrl = (tpl, params) => {
49496
- const url = Object.keys(params).reduce((res, curr) => res.replace(`{{${curr}}}`, `${params[curr]}`), tpl);
49497
- return encodeURI(url);
49498
- };
49499
- var generateWssUrl$1 = generateWssUrl;
49500
-
49501
- const isValidKey = (key, object) => key in object;
49502
- var isValidKey$1 = isValidKey;
49503
-
49504
- /**
49505
- * 解析参数
49506
- * @param query
49507
- * @returns
49508
- */
49509
- const parseQuery = (query = '') => query
49510
- .replace('?', '')
49511
- .split('&')
49512
- .map((qs) => {
49513
- const [k, v] = qs.split('=');
49514
- return { [k]: decodeURIComponent(v) };
49515
- })
49516
- .reduce((result, curr) => ({ ...result, ...curr }), {});
49517
- var parseQuery$1 = parseQuery;
49598
+ }
49518
49599
 
49519
- const ws = (() => new Ws4Webview$1())();
49520
49600
  class HybridBridge {
49521
49601
  constructor() {
49602
+ var _a, _b;
49522
49603
  /**
49523
49604
  * @deprecated 兼容旧逻辑
49524
49605
  */
49525
49606
  this._rsWeappBridgeMethodAdapter = {};
49526
- this._forceClose = false;
49607
+ this._ws = new RobustWebSocket$1();
49608
+ this._readyState = 'close';
49527
49609
  /**
49528
49610
  * 进行jsbridge的初始化,即打通ws通道
49529
49611
  * @param timeout 超时计时
@@ -49546,7 +49628,7 @@
49546
49628
  sign: wssig,
49547
49629
  });
49548
49630
  try {
49549
- const result = await ws.connect({ url });
49631
+ const result = await this._open(url);
49550
49632
  if (result) {
49551
49633
  this.initBuiltInHandlers();
49552
49634
  res[0] = await this.waitReady(timeout);
@@ -49560,6 +49642,130 @@
49560
49642
  }
49561
49643
  return res;
49562
49644
  };
49645
+ /**
49646
+ * 内建的处理函数
49647
+ */
49648
+ this.initBuiltInHandlers = () => {
49649
+ this._registerLifecycleHandler();
49650
+ this._registerHeartbeatHandler();
49651
+ this._registerMessageHandler();
49652
+ this._registerBridgeRequestHandler();
49653
+ this._registerReadyHandler();
49654
+ };
49655
+ /**
49656
+ * 进行连接
49657
+ * @param url ws链接
49658
+ * @returns
49659
+ */
49660
+ this._open = (url) => new Promise((resolve) => {
49661
+ const handleOpen = () => {
49662
+ this._receivedMessage(WeappBridgeMessage.ready, () => resolve(true), true);
49663
+ this._ws.once('timeout', () => resolve(false));
49664
+ this.send(WeappBridgeMessage.isReady);
49665
+ };
49666
+ this._ws.once('open', handleOpen);
49667
+ this._ws.open(url);
49668
+ });
49669
+ /**
49670
+ * 注册生命周期回调
49671
+ */
49672
+ this._registerLifecycleHandler = () => {
49673
+ this._ws.on('connecting', () => {
49674
+ console.log('RsWeappBridge connecting');
49675
+ this._readyState = 'connecting';
49676
+ });
49677
+ this._ws.on('open', () => {
49678
+ console.log('RsWeappBridge open');
49679
+ this._readyState = 'open';
49680
+ });
49681
+ this._ws.on('close', () => {
49682
+ this._readyState = 'close';
49683
+ });
49684
+ this._ws.on('error', () => {
49685
+ console.log('RsWeappBridge error');
49686
+ this._readyState = 'close';
49687
+ });
49688
+ this._ws.on('timeout', () => {
49689
+ console.log('RsWeappBridge timeout');
49690
+ this._readyState = 'close';
49691
+ });
49692
+ };
49693
+ /**
49694
+ * 注册心跳的回调
49695
+ * @deprecated 兼容老的容器SDK
49696
+ */
49697
+ this._registerHeartbeatHandler = () => {
49698
+ // 收到ping时回复pong
49699
+ this._receivedMessage(WeappBridgeMessage.ping, () => setTimeout(() => this._ws.send(WeappBridgeMessage.pong), 500));
49700
+ // 收到pong时回复ping
49701
+ this._receivedMessage(WeappBridgeMessage.pong, () => setTimeout(() => this._ws.send(WeappBridgeMessage.ping), 1000));
49702
+ };
49703
+ /**
49704
+ * 当收到某消息时
49705
+ * @param targetMessage 目标消息
49706
+ * @param handler 回调
49707
+ * @param once 是否一次性处理
49708
+ */
49709
+ this._receivedMessage = (targetMessage, handler, once) => {
49710
+ const msgHandler = (evnet) => {
49711
+ if (evnet.data === targetMessage) {
49712
+ handler();
49713
+ if (once) {
49714
+ this._ws.off('message', msgHandler);
49715
+ }
49716
+ }
49717
+ };
49718
+ this._ws.on('message', msgHandler);
49719
+ };
49720
+ /**
49721
+ * 注册准备就绪的回调
49722
+ */
49723
+ this._registerReadyHandler = () => {
49724
+ // 收到就绪询问时回复已就绪
49725
+ this._receivedMessage(WeappBridgeMessage.isReady, () => this._ws.send(WeappBridgeMessage.ready));
49726
+ };
49727
+ /**
49728
+ * 发送消息
49729
+ */
49730
+ this.send = (data) => {
49731
+ this._ws.send(data);
49732
+ };
49733
+ /**
49734
+ * 等待响应
49735
+ * @param timeout 超时计时
49736
+ * @returns
49737
+ */
49738
+ this.waitReady = (timeout = 6000) => {
49739
+ return new Promise((resolve, reject) => {
49740
+ this._receivedMessage(WeappBridgeMessage.ready, () => resolve(true));
49741
+ this.send(WeappBridgeMessage.isReady);
49742
+ setTimeout(() => reject('HybridBridge 初始化超时~'), timeout);
49743
+ });
49744
+ };
49745
+ this._parseMessage = (event) => {
49746
+ try {
49747
+ return JSON.parse(event.data);
49748
+ }
49749
+ catch (e) {
49750
+ return event.data;
49751
+ }
49752
+ };
49753
+ /**
49754
+ * 注册消息投递回调
49755
+ * @deprecated 兼容老方法
49756
+ */
49757
+ this._registerMessageHandler = () => {
49758
+ this._ws.on('message', (event) => {
49759
+ const message = this._parseMessage(event);
49760
+ if (typeof message === 'object') {
49761
+ const { id, command, data } = message;
49762
+ if (command === 'message' &&
49763
+ typeof this._rsWeappBridgeMethodAdapter.bindMessage === 'function') {
49764
+ this._rsWeappBridgeMethodAdapter.bindMessage({ id, data });
49765
+ }
49766
+ }
49767
+ });
49768
+ };
49563
49769
  this.getStaticData = (callbackFunctionName) => {
49564
49770
  this.callAndBackfeed(JSON.stringify({
49565
49771
  actionUrl: 'common/staticData',
@@ -49606,134 +49812,52 @@
49606
49812
  callback(false);
49607
49813
  }
49608
49814
  };
49609
- }
49610
- get isReady() {
49611
- return ws.readyState === WebSocketState.OPEN;
49612
- }
49613
- /**
49614
- * 内建的处理函数
49615
- */
49616
- initBuiltInHandlers() {
49617
- this._registerLifecycleHandler();
49618
- this._registerHeartbeatHandler();
49619
- this._registerMessageHandler();
49620
- this._registerBridgeRequestHandler();
49621
- this._registerReadyHandler();
49622
- }
49623
- /**
49624
- * 注册生命周期回调
49625
- */
49626
- _registerLifecycleHandler() {
49627
- ws.onOpen(() => console.log('RsWeappBridge open'));
49628
- ws.onClose((res) => {
49629
- console.log('RsWeappBridge close');
49630
- if (res.code === 1000) {
49631
- switch ((res.reason + '').toLowerCase()) {
49632
- case WebSocketCloseOptions.lostHeartbeat.reason: {
49633
- // 心跳丢失
49634
- ws.reconnect();
49635
- break;
49636
- }
49637
- // case WebSocketCloseOptions.normalClosure.reason: // 主动关闭
49638
- case WebSocketCloseOptions.interrupted.reason: // 切换到后台,被微信杀掉,需要重连连接
49639
- case WebSocketCloseOptions.streamEndEncountered.reason: // 服务端拒绝连接
49640
- default: {
49641
- if (!this._forceClose) {
49642
- ws.reconnect();
49643
- }
49644
- break;
49815
+ /**
49816
+ * 执行
49817
+ * @param method
49818
+ * @param args
49819
+ * @returns
49820
+ */
49821
+ this.execute = async (method, args) => await this._invokeBridgeMethod(method, args);
49822
+ /**
49823
+ *
49824
+ * @param method
49825
+ * @param args
49826
+ * @returns
49827
+ * @deprecated 兼容老方法
49828
+ */
49829
+ this._invokeBridgeMethod = (method, args) => new Promise((success, fail) => {
49830
+ const id = uuid();
49831
+ const wsBridgeResponsehandler = (event) => {
49832
+ const result = this._parseMessage(event);
49833
+ if (typeof result === 'object') {
49834
+ if (result.method === method && result.id === id) {
49835
+ this._ws.off('message', wsBridgeResponsehandler);
49836
+ result.error ? fail(result.error) : success(result.data);
49645
49837
  }
49646
49838
  }
49647
- }
49648
- if (res.code !== 1000 && !this._forceClose) {
49649
- ws.reconnect();
49650
- }
49651
- if (this._forceClose)
49652
- this._forceClose = false;
49653
- });
49654
- ws.onError((err) => console.error(err));
49655
- }
49656
- /**
49657
- * 注册心跳的回调
49658
- * @deprecated 兼容老的容器SDK
49659
- */
49660
- _registerHeartbeatHandler() {
49661
- // 收到ping时回复pong
49662
- this._receivedMessage(WeappBridgeMessage.ping, () => ws.send(WeappBridgeMessage.pong));
49663
- // 收到pong时回复ping
49664
- this._receivedMessage(WeappBridgeMessage.pong, () => ws.send(WeappBridgeMessage.ping));
49665
- }
49666
- /**
49667
- * 当收到某消息时
49668
- * @param targetMessage 目标消息
49669
- * @param handler 回调
49670
- * @param once 是否一次性处理
49671
- */
49672
- _receivedMessage(targetMessage, handler, once) {
49673
- const msgHandler = (msg) => {
49674
- if (msg === targetMessage) {
49675
- handler();
49676
- if (once) {
49677
- ws.offMessage(msgHandler);
49678
- }
49679
- }
49680
- };
49681
- ws.onMessage(msgHandler);
49682
- }
49683
- /**
49684
- * 强制关闭ws
49685
- * @param options
49686
- */
49687
- forceClose(options) {
49688
- this._forceClose = true;
49689
- ws.close(options);
49690
- }
49691
- /**
49692
- * 注册准备就绪的回调
49693
- */
49694
- _registerReadyHandler() {
49695
- // 收到就绪询问时回复已就绪
49696
- this._receivedMessage(WeappBridgeMessage.isReady, () => ws.send(WeappBridgeMessage.ready));
49697
- }
49698
- /**
49699
- * 发送消息
49700
- */
49701
- send(data) {
49702
- ws.send(data);
49703
- }
49704
- /**
49705
- * 等待响应
49706
- * @param timeout 超时计时
49707
- * @returns
49708
- */
49709
- waitReady(timeout = 6000) {
49710
- return new Promise((resolve, reject) => {
49711
- this._receivedMessage(WeappBridgeMessage.ready, () => resolve(true));
49712
- this.send(WeappBridgeMessage.isReady);
49713
- setTimeout(() => reject('HybridBridge 初始化超时~'), timeout);
49839
+ };
49840
+ this._ws.on('message', wsBridgeResponsehandler);
49841
+ this.send(JSON.stringify({ method, args, id }));
49714
49842
  });
49843
+ if (((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.window) === null || _a === void 0 ? void 0 : _a.__Realsee_WxMini_HybridBridge__) instanceof HybridBridge) {
49844
+ return (_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.window) === null || _b === void 0 ? void 0 : _b.__Realsee_WxMini_HybridBridge__;
49845
+ }
49846
+ if (globalThis === null || globalThis === void 0 ? void 0 : globalThis.window) {
49847
+ globalThis.window.__Realsee_WxMini_HybridBridge__ = this;
49848
+ this.initBuiltInHandlers();
49849
+ }
49715
49850
  }
49716
- /**
49717
- * 注册消息投递回调
49718
- * @deprecated 兼容老方法
49719
- */
49720
- _registerMessageHandler() {
49721
- ws.onMessage((message) => {
49722
- if (typeof message === 'object') {
49723
- const { id, command, data } = message;
49724
- if (command === 'message' &&
49725
- typeof this._rsWeappBridgeMethodAdapter.bindMessage === 'function') {
49726
- this._rsWeappBridgeMethodAdapter.bindMessage({ id, data });
49727
- }
49728
- }
49729
- });
49851
+ get isReady() {
49852
+ return this._readyState === 'open';
49730
49853
  }
49731
49854
  /**
49732
49855
  * 注册bridge方法回调
49733
49856
  * @deprecated 兼容老方法
49734
49857
  */
49735
49858
  _registerBridgeRequestHandler() {
49736
- ws.onMessage(async (request) => {
49859
+ this._ws.on('message', async (event) => {
49860
+ const request = this._parseMessage(event);
49737
49861
  if (typeof request === 'object') {
49738
49862
  const { id, method, args, command } = request;
49739
49863
  if (command === 'request') {
@@ -49786,22 +49910,25 @@
49786
49910
  type: 'callAndBackfeed',
49787
49911
  });
49788
49912
  let timer = null;
49789
- const callback = (message) => {
49790
- const { id, result, errmsg, command } = message;
49791
- if (command === 'rsSchemeResponse' && id === reqId) {
49792
- ws.offMessage(callback);
49793
- if (timer)
49794
- clearTimeout(timer);
49795
- if (errmsg) {
49796
- console.warn(errmsg);
49797
- backfeed(0);
49798
- }
49799
- else {
49800
- backfeed(result);
49913
+ const callback = (event) => {
49914
+ const message = this._parseMessage(event);
49915
+ if (typeof message === 'object') {
49916
+ const { id, result, errmsg, command } = message;
49917
+ if (command === 'rsSchemeResponse' && id === reqId) {
49918
+ this._ws.off('message', callback);
49919
+ if (timer)
49920
+ clearTimeout(timer);
49921
+ if (errmsg) {
49922
+ console.warn(errmsg);
49923
+ backfeed(0);
49924
+ }
49925
+ else {
49926
+ backfeed(result);
49927
+ }
49801
49928
  }
49802
49929
  }
49803
49930
  };
49804
- ws.onMessage(callback);
49931
+ this._ws.on('message', callback);
49805
49932
  this.send(data);
49806
49933
  // 30s超时处理
49807
49934
  timer = globalThis.setTimeout(() => {
@@ -49822,19 +49949,22 @@
49822
49949
  command: 'rsSchemeRequest',
49823
49950
  type: 'callAndListen',
49824
49951
  });
49825
- const callback = (message) => {
49826
- const { id, result, errmsg, command } = message;
49827
- if (command === 'rsSchemeResponse' && id === reqId) {
49828
- if (errmsg) {
49829
- console.warn(errmsg);
49830
- fn(false);
49831
- }
49832
- else {
49833
- fn(result);
49952
+ const callback = (event) => {
49953
+ const message = this._parseMessage(event);
49954
+ if (typeof message === 'object') {
49955
+ const { id, result, errmsg, command } = message;
49956
+ if (command === 'rsSchemeResponse' && id === reqId) {
49957
+ if (errmsg) {
49958
+ console.warn(errmsg);
49959
+ fn(false);
49960
+ }
49961
+ else {
49962
+ fn(result);
49963
+ }
49834
49964
  }
49835
49965
  }
49836
49966
  };
49837
- ws.onMessage(callback);
49967
+ this._ws.on('message', callback);
49838
49968
  this.send(data);
49839
49969
  }
49840
49970
  /**
@@ -49853,23 +49983,26 @@
49853
49983
  command: 'request',
49854
49984
  });
49855
49985
  let timer = null;
49856
- const callback = (message) => {
49857
- const { id, result, error, command } = message;
49858
- if (command === 'response' &&
49859
- id === reqId &&
49860
- message.method === method) {
49861
- ws.offMessage(callback);
49862
- if (timer)
49863
- clearTimeout(timer);
49864
- if (error) {
49865
- fail(error);
49866
- }
49867
- else {
49868
- success(result);
49986
+ const callback = (event) => {
49987
+ const message = this._parseMessage(event);
49988
+ if (typeof message === 'object') {
49989
+ const { id, result, error, command } = message;
49990
+ if (command === 'response' &&
49991
+ id === reqId &&
49992
+ message.method === method) {
49993
+ this._ws.off('message', callback);
49994
+ if (timer)
49995
+ clearTimeout(timer);
49996
+ if (error) {
49997
+ fail(error);
49998
+ }
49999
+ else {
50000
+ success(result);
50001
+ }
49869
50002
  }
49870
50003
  }
49871
50004
  };
49872
- ws.onMessage(callback);
50005
+ this._ws.on('message', callback);
49873
50006
  this.send(data);
49874
50007
  // 30s超时处理
49875
50008
  timer = setTimeout(() => fail('method invoke timeout'), 30000);
@@ -49882,18 +50015,14 @@
49882
50015
  */
49883
50016
  class WxMiniprogramController extends BaseController {
49884
50017
  constructor() {
49885
- super();
50018
+ super(...arguments);
50019
+ this._hybridBridge = new HybridBridge();
49886
50020
  this.initializing = false;
49887
- Promise.resolve().then(async () => {
49888
- try {
49889
- await this.checkBridgeReady();
49890
- }
49891
- catch (error) {
49892
- console.warn(error);
49893
- }
49894
- });
49895
50021
  }
49896
- checkBridgeReady(timeout = 6000) {
50022
+ get hybridBridge() {
50023
+ return this._hybridBridge;
50024
+ }
50025
+ checkBridgeReady(timeout = 60000) {
49897
50026
  if (this.ready)
49898
50027
  return true;
49899
50028
  return new Promise(async (resolve, reject) => {
@@ -49910,12 +50039,11 @@
49910
50039
  }
49911
50040
  else {
49912
50041
  this.initializing = true;
49913
- const hybridBridge = new HybridBridge();
49914
- const [res, error] = await hybridBridge.initialize(timeout);
50042
+ const [res, error] = await this._hybridBridge.initialize(timeout);
49915
50043
  if (!res || error) {
49916
50044
  throw error || new Error('HybridBridge 初始化失败~');
49917
50045
  }
49918
- hybridBridge === null || hybridBridge === void 0 ? void 0 : hybridBridge.getStaticData(registerGlobalValue('HYBRID_BRIDGE_NAME', (data) => {
50046
+ this._hybridBridge.getStaticData(registerGlobalValue('HYBRID_BRIDGE_NAME', (data) => {
49919
50047
  this.deviceInfo = (() => {
49920
50048
  try {
49921
50049
  return JSON.parse(data);
@@ -49924,14 +50052,13 @@
49924
50052
  return data;
49925
50053
  }
49926
50054
  })();
49927
- this.hybridBridge = hybridBridge;
49928
- this.initializing = false;
49929
- return resolve(true);
49930
50055
  }));
50056
+ this.initializing = false;
50057
+ return resolve(true);
49931
50058
  }
49932
50059
  });
49933
50060
  }
49934
- async checkReady(timeout = 6000) {
50061
+ async checkReady(timeout = 60000) {
49935
50062
  const res = [null, null];
49936
50063
  if (this.ready) {
49937
50064
  res[0] = true;
@@ -49947,8 +50074,7 @@
49947
50074
  return res;
49948
50075
  }
49949
50076
  get ready() {
49950
- var _a;
49951
- return !!((_a = this.hybridBridge) === null || _a === void 0 ? void 0 : _a.isReady);
50077
+ return !!this._hybridBridge.isReady;
49952
50078
  }
49953
50079
  get scheme() {
49954
50080
  var _a;
@@ -49990,7 +50116,7 @@
49990
50116
  resolve(res);
49991
50117
  }),
49992
50118
  });
49993
- this.hybridBridge.callAndBackfeed(msg);
50119
+ this._hybridBridge.callAndBackfeed(msg);
49994
50120
  });
49995
50121
  }
49996
50122
  async callAndListen(scheme, callback) {
@@ -50035,7 +50161,7 @@
50035
50161
  actionUrl,
50036
50162
  functionName: registerGlobalValue(actionUrl, _callback, false),
50037
50163
  });
50038
- this.hybridBridge.callAndListen(msg);
50164
+ this._hybridBridge.callAndListen(msg);
50039
50165
  });
50040
50166
  }
50041
50167
  async invoke(method, data) {
@@ -50045,7 +50171,7 @@
50045
50171
  throw readyError;
50046
50172
  }
50047
50173
  else {
50048
- return (await ((_b = (_a = this.hybridBridge).invoke) === null || _b === void 0 ? void 0 : _b.call(_a, method, data)));
50174
+ return (await ((_b = (_a = this._hybridBridge).invoke) === null || _b === void 0 ? void 0 : _b.call(_a, method, data)));
50049
50175
  }
50050
50176
  }
50051
50177
  }
@@ -50359,7 +50485,7 @@
50359
50485
  }
50360
50486
 
50361
50487
  const defaultOptions = {
50362
- timeout: 6000,
50488
+ timeout: 60000,
50363
50489
  };
50364
50490
  /**
50365
50491
  * 小程序 [web-view](https://developers.weixin.qq.com/miniprogram/dev/component/web-view.html) JSBridge。
@@ -50475,10 +50601,12 @@
50475
50601
  }
50476
50602
  const proxyCache = (url) => {
50477
50603
  if (this.webViewType === WebViewTypeEnum.WKWebview) {
50478
- return url.replace(/https*:/, '').replace(/\/\//, 'realseeproxycache://');
50604
+ return url
50605
+ .replace(/https*:/, '')
50606
+ .replace(/\/\//, 'realseeproxycache://');
50479
50607
  }
50480
50608
  else if (this.webViewType === WebViewTypeEnum.WebView) {
50481
- return url + (url.indexOf('?') !== -1 ? '&' : '?') + 'realseeproxycache=1';
50609
+ return (url + (url.indexOf('?') !== -1 ? '&' : '?') + 'realseeproxycache=1');
50482
50610
  }
50483
50611
  return url;
50484
50612
  };
@@ -50487,6 +50615,10 @@
50487
50615
  async invokeNativeApi(method, data) {
50488
50616
  return await this._controller.invoke(method, data);
50489
50617
  }
50618
+ async execute(method, args) {
50619
+ var _a, _b, _c;
50620
+ return await ((_c = (_b = (_a = this._controller) === null || _a === void 0 ? void 0 : _a.hybridBridge) === null || _b === void 0 ? void 0 : _b.execute) === null || _c === void 0 ? void 0 : _c.call(_b, method, args));
50621
+ }
50490
50622
  }
50491
50623
 
50492
50624
  /**
@@ -50504,6 +50636,23 @@
50504
50636
  }
50505
50637
  }
50506
50638
 
50639
+ var LiveState;
50640
+ (function (LiveState) {
50641
+ LiveState[LiveState["NOTINITIALIZED"] = -1] = "NOTINITIALIZED";
50642
+ /**
50643
+ * 正在链接中
50644
+ */
50645
+ LiveState[LiveState["CONNECTING"] = 0] = "CONNECTING";
50646
+ /**
50647
+ * 已经链接并且可以通讯
50648
+ */
50649
+ LiveState[LiveState["OPEN"] = 1] = "OPEN";
50650
+ /**
50651
+ * 连接已关闭或者链接失败
50652
+ */
50653
+ LiveState[LiveState["CLOSED"] = 3] = "CLOSED";
50654
+ })(LiveState || (LiveState = {}));
50655
+
50507
50656
  function appendUri(uri, query) {
50508
50657
  const hasQuery = uri.indexOf('?') !== -1;
50509
50658
  const newQuery = Object.keys(query).reduce((accu, curr, idx) => `${accu}${(idx === 0 && !hasQuery) ? '?' : '&'}${curr}=${query[curr]}`, '');
@@ -50648,611 +50797,1035 @@
50648
50797
  return isDeepEqual(value, other);
50649
50798
  }
50650
50799
 
50651
- class LiveController {
50800
+ /**
50801
+ * 输出格式化日志
50802
+ */
50803
+ // 获取当前时间
50804
+ const getTime = () => {
50805
+ const date = new Date();
50806
+ const year = date.getFullYear();
50807
+ const month = (date.getMonth() + 1).toString().padStart(2, '0'); //月份是从0开始的
50808
+ const day = date.getDate().toString().padStart(2, '0');
50809
+ const hour = date.getHours().toString().padStart(2, '0');
50810
+ const min = date.getMinutes().toString().padStart(2, '0');
50811
+ const sec = date.getSeconds().toString().padStart(2, '0');
50812
+ const ms = date.getMilliseconds();
50813
+ return `[${year}-${month}-${day} ${hour}:${min}:${sec}.${ms}]`;
50814
+ };
50815
+ var LOG_LEVEL;
50816
+ (function (LOG_LEVEL) {
50817
+ LOG_LEVEL["info"] = "INFO";
50818
+ LOG_LEVEL["log"] = "LOG";
50819
+ LOG_LEVEL["error"] = "ERROR";
50820
+ LOG_LEVEL["warn"] = "WARN";
50821
+ })(LOG_LEVEL || (LOG_LEVEL = {}));
50822
+ // 输出日志
50823
+ const echo = (logLevel, args = []) => {
50824
+ args.unshift(`Realsee Live ${getTime()} <${logLevel}> `);
50825
+ switch (logLevel) {
50826
+ case LOG_LEVEL.info:
50827
+ return console.info(...args);
50828
+ case LOG_LEVEL.error:
50829
+ return console.error(...args);
50830
+ case LOG_LEVEL.warn:
50831
+ return console.warn(...args);
50832
+ default:
50833
+ return console.log(...args);
50834
+ }
50835
+ };
50836
+ const log = (...args) => echo(LOG_LEVEL.log, args);
50837
+ const info = (...args) => echo(LOG_LEVEL.info, args);
50838
+ const error = (...args) => echo(LOG_LEVEL.error, args);
50839
+ const warn = (...args) => echo(LOG_LEVEL.warn, args);
50840
+ const logger = {
50841
+ log,
50842
+ info,
50843
+ error,
50844
+ warn,
50845
+ };
50846
+ var logger$1 = logger;
50847
+
50848
+ /**
50849
+ * 具有鲁棒性的WebSocket封装
50850
+ * 1、自动重连
50851
+ * 2、可根据网络情况进行重连
50852
+ */
50853
+ class RobustWebSocket extends Subscribe$1 {
50652
50854
  constructor(options) {
50653
- this.readyState = exports.WebSocketState.NOTINITIALIZED;
50654
- this.canSync = true;
50655
- this.connecting = false;
50656
- this.keyframes = {};
50855
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
50856
+ super();
50857
+ this._options = {
50858
+ timeout: 10000,
50859
+ shouldReconnect: (event, ws) => {
50860
+ if (event.code === 1008 || event.code === 1011)
50861
+ return;
50862
+ return [0, 3000, 10000][ws.attempts];
50863
+ },
50864
+ should1000Reconnect: false,
50865
+ ignoreConnectivityEvents: false,
50866
+ automaticOpen: false,
50867
+ };
50868
+ this._attempts = 0;
50869
+ this._reconnects = -1;
50870
+ this._reconnectWhenOnlineAgain = false;
50871
+ this._explicitlyClosed = false;
50872
+ this._connectivityEventsAttached = false;
50657
50873
  /**
50658
- * 检测 WebSocket.readyState 状态
50874
+ * 清理连接中的请求
50659
50875
  */
50660
- this.checkReadyState = (live) => {
50661
- do {
50662
- if (!this.webSocket) {
50663
- if (this.readyState !== exports.WebSocketState.NOTINITIALIZED) {
50664
- this.readyState = exports.WebSocketState.NOTINITIALIZED;
50665
- live.emit('ws.readyStateUpdate', this.readyState);
50666
- }
50667
- break;
50668
- }
50669
- const readyState = this.webSocket.readyState;
50670
- if (readyState !== this.readyState) {
50671
- this.readyState = readyState;
50672
- live.emit('ws.readyStateUpdate', this.readyState);
50673
- }
50674
- } while (false);
50675
- return this.readyState;
50876
+ this._clearPendingReconnectIfNeeded = () => {
50877
+ if (this._pendingReconnect) {
50878
+ clearTimeout(this._pendingReconnect);
50879
+ this._pendingReconnect = undefined;
50880
+ }
50676
50881
  };
50677
- this.dispose = () => {
50678
- this.disposeWebSocket();
50679
- this.connecting = false;
50680
- if (this.healthCheckId) {
50681
- clearInterval(this.healthCheckId);
50682
- this.healthCheckId = undefined;
50882
+ /**
50883
+ * 当网页连接上网络进行重连
50884
+ * @param event
50885
+ */
50886
+ this._online = (event) => {
50887
+ if (this._reconnectWhenOnlineAgain) {
50888
+ this._clearPendingReconnectIfNeeded();
50889
+ this._reconnect(event);
50683
50890
  }
50684
- return true;
50685
50891
  };
50686
50892
  /**
50687
- * 销毁WebSocket相关依赖。
50893
+ * 当网页断开网络进行关闭
50688
50894
  */
50689
- this.disposeWebSocket = () => {
50690
- if (!this.webSocket)
50691
- return;
50692
- if (this.onEvtOpnListener) {
50693
- this.webSocket.removeEventListener('open', this.onEvtOpnListener);
50694
- this.onEvtOpnListener = undefined;
50895
+ this._offline = () => {
50896
+ var _a;
50897
+ this._reconnectWhenOnlineAgain = true;
50898
+ (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.close(1000);
50899
+ };
50900
+ /**
50901
+ * 解除网络监听事件
50902
+ */
50903
+ this._detachConnectivityEvents = () => {
50904
+ if (this._connectivityEventsAttached) {
50905
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.removeEventListener('online', this._online);
50906
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.removeEventListener('offline', this._offline);
50907
+ this._connectivityEventsAttached = false;
50908
+ }
50909
+ };
50910
+ /**
50911
+ * 注册网络监听事件
50912
+ */
50913
+ this._attachConnectivityEvents = () => {
50914
+ if (!this._connectivityEventsAttached) {
50915
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.addEventListener('online', this._online);
50916
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.addEventListener('offline', this._offline);
50917
+ this._connectivityEventsAttached = true;
50695
50918
  }
50696
- if (this.onEvtMsgListener) {
50697
- this.webSocket.removeEventListener('message', this.onEvtMsgListener);
50698
- this.onEvtMsgListener = undefined;
50919
+ };
50920
+ /**
50921
+ * 发送消息
50922
+ * @param data
50923
+ * @returns
50924
+ */
50925
+ this.send = (data) => { var _a; return (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.send(data); };
50926
+ /**
50927
+ * 关闭连接
50928
+ * @param code 代码
50929
+ * @param reason 原因
50930
+ * @returns
50931
+ */
50932
+ this.close = (code, reason) => {
50933
+ var _a;
50934
+ if (typeof code !== 'number') {
50935
+ reason = code;
50936
+ code = 1000;
50699
50937
  }
50700
- if (this.onEvtErrListener) {
50701
- this.webSocket.removeEventListener('error', this.onEvtErrListener);
50702
- this.onEvtErrListener = undefined;
50938
+ this._clearPendingReconnectIfNeeded();
50939
+ this._reconnectWhenOnlineAgain = false;
50940
+ this._explicitlyClosed = true;
50941
+ this._detachConnectivityEvents();
50942
+ return (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.close(code, reason);
50943
+ };
50944
+ /**
50945
+ * 进行ws连接
50946
+ */
50947
+ this.open = (url) => {
50948
+ var _a, _b;
50949
+ if (url) {
50950
+ this._url = url;
50703
50951
  }
50704
- if (this.onEvtCLEListener) {
50705
- this.webSocket.removeEventListener('close', this.onEvtCLEListener);
50706
- this.onEvtCLEListener = undefined;
50952
+ if (((_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.readyState) !== WebSocket.OPEN &&
50953
+ ((_b = this._realWebSocket) === null || _b === void 0 ? void 0 : _b.readyState) !== WebSocket.CONNECTING) {
50954
+ this._clearPendingReconnectIfNeeded();
50955
+ this._reconnectWhenOnlineAgain = false;
50956
+ this._explicitlyClosed = false;
50957
+ this._createWebSocket();
50707
50958
  }
50708
- this.webSocket.close();
50709
- this.webSocket = undefined;
50710
- return true;
50711
50959
  };
50712
- this.options = Object.assign({ autoConnect: true, healthCheck: 3000 }, options);
50960
+ /**
50961
+ * 创建ws连接
50962
+ */
50963
+ this._createWebSocket = () => {
50964
+ var _a, _b, _c;
50965
+ const newUrl = typeof this._url === 'string' ? this._url : (_a = this._url) === null || _a === void 0 ? void 0 : _a.call(this, this);
50966
+ if (!newUrl)
50967
+ return;
50968
+ this._pendingReconnect = undefined;
50969
+ this._realWebSocket = new WebSocket(newUrl, this._protocols || undefined);
50970
+ this._attempts = this._attempts + 1;
50971
+ this.emit('connecting', new CustomEvent('connecting', {
50972
+ detail: { attempts: this._attempts, reconnects: this._reconnects },
50973
+ }));
50974
+ const timeoutCallback = () => {
50975
+ this._connectTimeout = undefined;
50976
+ this._detachConnectivityEvents();
50977
+ this.emit('timeout', new CustomEvent('connecting', {
50978
+ detail: {
50979
+ attempts: this._attempts,
50980
+ reconnects: this._reconnects,
50981
+ },
50982
+ }));
50983
+ };
50984
+ this._connectTimeout = setTimeout(timeoutCallback, (_b = this._options) === null || _b === void 0 ? void 0 : _b.timeout);
50985
+ this._dispatchWebSocketEvent();
50986
+ if (!((_c = this._options) === null || _c === void 0 ? void 0 : _c.ignoreConnectivityEvents)) {
50987
+ this._attachConnectivityEvents();
50988
+ }
50989
+ };
50990
+ /**
50991
+ * 分发ws事件
50992
+ */
50993
+ this._dispatchWebSocketEvent = () => {
50994
+ var _a, _b, _c, _d;
50995
+ (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.addEventListener('open', this._webSocketOpenHandler);
50996
+ (_b = this._realWebSocket) === null || _b === void 0 ? void 0 : _b.addEventListener('close', this._webSocketCloseHandler);
50997
+ (_c = this._realWebSocket) === null || _c === void 0 ? void 0 : _c.addEventListener('error', this._webSocketErrorHandler);
50998
+ (_d = this._realWebSocket) === null || _d === void 0 ? void 0 : _d.addEventListener('message', this._webSocketMessageHandler);
50999
+ };
51000
+ /**
51001
+ * ws连接事件
51002
+ * @returns
51003
+ */
51004
+ this._webSocketOpenHandler = (event) => {
51005
+ if (this._connectTimeout) {
51006
+ clearTimeout(this._connectTimeout);
51007
+ this._connectTimeout = undefined;
51008
+ }
51009
+ const reconnects = ++this._reconnects;
51010
+ const attempts = this._attempts;
51011
+ this._attempts = 0;
51012
+ this._reconnectWhenOnlineAgain = false;
51013
+ return this.emit('open', Object.assign(event, { detail: { reconnects, attempts } }));
51014
+ };
51015
+ /**
51016
+ * ws 关闭事件
51017
+ * @param event
51018
+ * @returns
51019
+ */
51020
+ this._webSocketCloseHandler = (event) => {
51021
+ this._reconnect(event);
51022
+ return this.emit('close', event);
51023
+ };
51024
+ /**
51025
+ * ws 异常
51026
+ * @param event
51027
+ * @returns
51028
+ */
51029
+ this._webSocketErrorHandler = (event) => {
51030
+ return this.emit('error', new CustomEvent('error', { detail: { error: event } }));
51031
+ };
51032
+ /**
51033
+ * ws消息
51034
+ * @param event
51035
+ * @returns
51036
+ */
51037
+ this._webSocketMessageHandler = (event) => {
51038
+ return this.emit('message', event);
51039
+ };
51040
+ if (options) {
51041
+ this.setOptions(options);
51042
+ }
51043
+ }
51044
+ get attempts() {
51045
+ return this._attempts;
51046
+ }
51047
+ setOptions(options) {
51048
+ if (!options)
51049
+ return;
51050
+ this._url = options.url;
51051
+ this._protocols = options.protocols;
51052
+ const opts = Object.assign(this._options, options.robustOptions || {});
51053
+ if (typeof (opts === null || opts === void 0 ? void 0 : opts.timeout) !== 'number') {
51054
+ throw new Error('timeout must be the number of milliseconds to timeout a connection attempt');
51055
+ }
51056
+ if (typeof (opts === null || opts === void 0 ? void 0 : opts.shouldReconnect) !== 'function') {
51057
+ throw new Error('shouldReconnect must be a function that returns the number of milliseconds to wait for a reconnect attempt, or null or undefined to not reconnect.');
51058
+ }
51059
+ this._options = opts;
51060
+ if (this._options.automaticOpen) {
51061
+ this._createWebSocket();
51062
+ }
50713
51063
  }
50714
51064
  /**
50715
- * 解析数据
50716
- * @param liveMsg
50717
- * @param live
51065
+ * 进行重连
51066
+ * @param event
51067
+ * @returns
50718
51068
  */
50719
- handleMessage(liveMsg, live) {
50720
- var _a, _b, _c;
50721
- const { command, data, frontRequestId, code, message } = liveMsg;
50722
- if (code === 'SUCCESS') {
50723
- switch (command) {
50724
- /**
50725
- * 自己的状态变化
50726
- */
50727
- case exports.Command.SelfUserInfo: {
50728
- const selfInfo = data;
50729
- if (equal(this.selfUserInfo, selfInfo, { deep: true }))
50730
- return;
50731
- this.selfUserInfo = selfInfo;
50732
- live.emit('selfInfoUpdate', this.selfUserInfo, frontRequestId);
50733
- break;
50734
- }
50735
- /**
50736
- * 房间信息变化
50737
- */
50738
- case exports.Command.RoomInfo: {
50739
- const roomInfo = data;
50740
- this.roomInfo = Object.assign({}, roomInfo);
50741
- live.emit('readyKeyframeSync', (roomInfo.last_frame || {}));
50742
- break;
50743
- }
50744
- /**
50745
- * 语音信息变化
50746
- */
50747
- case exports.Command.RTCInfo: {
50748
- const { voice_id: voiceId, type } = data;
50749
- /* 如果已经进入语音房间,则不重复进入 --> "RTCInfo" 指令可能会下发多次 */
50750
- if (live.$RTC.joined) {
50751
- break;
50752
- }
50753
- live.$RTC.join({
50754
- voiceId,
50755
- userId: ((_a = this.selfUserInfo) === null || _a === void 0 ? void 0 : _a.id) || '',
50756
- roomId: (_b = this.roomInfo) === null || _b === void 0 ? void 0 : _b.info.room_code,
50757
- type,
50758
- });
50759
- // 加入房间后 麦克风默认就开启了:需要发个指令。
50760
- live.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserMicroStatus, {
50761
- status: exports.MicroStatus.OPEN,
50762
- });
50763
- break;
50764
- }
50765
- /**
50766
- * 房间用户列表变化
50767
- */
50768
- case exports.Command.UserList: {
50769
- const userList = data;
50770
- this.userList = userList;
50771
- live.emit('userListUpdate', this.userList, frontRequestId);
50772
- break;
50773
- }
50774
- /**
50775
- * 自定义事件广播
50776
- */
50777
- case exports.Command.CustomEvent: {
50778
- const evtMsg = data;
50779
- live.emit('broadcast', evtMsg, frontRequestId);
50780
- break;
50781
- }
50782
- /**
50783
- * 帧数据同步
50784
- */
50785
- case exports.Command.KeyframeSync: {
50786
- const remoteKeyframes = data;
50787
- // 此处做一层 diff,仅跟本地数据不一致的情况下才广播数据。
50788
- const keyframes = Object.keys(remoteKeyframes).reduce((accu, curr) => {
50789
- if (equal(remoteKeyframes[curr], this.keyframes[curr], { deep: true })) {
50790
- return accu;
50791
- }
50792
- const params = [
50793
- remoteKeyframes[curr],
50794
- this.keyframes[curr],
50795
- frontRequestId,
50796
- ];
50797
- const evtName = curr;
50798
- live.keyframes.emit(evtName, ...params);
50799
- this.keyframes[curr] = remoteKeyframes[curr];
50800
- accu[curr] = remoteKeyframes[curr];
50801
- return accu;
50802
- }, {});
50803
- live.emit('keyframes', keyframes, frontRequestId);
50804
- break;
50805
- }
50806
- /**
50807
- * 内置消息
50808
- */
50809
- case exports.Command.BuiltinMsg: {
50810
- const builtinMsg = data;
50811
- live.emit('builtinEvent', builtinMsg);
50812
- if (builtinMsg.event_type === exports.BuiltinEventType.UserChange) {
50813
- live.emit('userChange', builtinMsg);
50814
- }
50815
- if (builtinMsg.event_type === exports.BuiltinEventType.RoomChange) {
50816
- live.emit('roomChange', builtinMsg);
50817
- }
50818
- /**
50819
- * 下发指令自己操作麦克风
50820
- */
50821
- if (builtinMsg.event_type === exports.BuiltinEventType.UserChange &&
50822
- builtinMsg.action === exports.BuiltinActionType.UserMicroStatus) {
50823
- live.toggleMicro(builtinMsg.data.status === exports.MicroStatus.OPEN);
50824
- }
50825
- /**
50826
- * 如果下发指令退出房间,则 关闭麦克风 及 销毁 WebSocket
50827
- */
50828
- if (builtinMsg.event_type === exports.BuiltinEventType.RoomChange &&
50829
- builtinMsg.action === exports.BuiltinActionType.RoomClose) {
50830
- (_c = this.options.rtc) === null || _c === void 0 ? void 0 : _c.quit();
50831
- this.disposeWebSocket();
50832
- }
50833
- break;
50834
- }
50835
- /**
50836
- * 被踢出房间
50837
- */
50838
- case exports.Command.UserKickOut: {
50839
- live.emit('kickOut');
50840
- break;
50841
- }
50842
- /**
50843
- * 其它未知广播
50844
- */
50845
- default: {
50846
- console.warn('unknown command: ', command);
50847
- }
50848
- }
51069
+ _reconnect(event) {
51070
+ var _a, _b, _c, _d;
51071
+ if ((!((_a = this._options) === null || _a === void 0 ? void 0 : _a.should1000Reconnect) && event.code === 1000) ||
51072
+ this._explicitlyClosed) {
51073
+ this._attempts = 0;
51074
+ return;
50849
51075
  }
50850
- else {
50851
- live.emit('error', liveMsg);
51076
+ if (((_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _b === void 0 ? void 0 : _b.onLine) === false) {
51077
+ this._reconnectWhenOnlineAgain = true;
51078
+ return;
51079
+ }
51080
+ const delay = (_d = (_c = this._options) === null || _c === void 0 ? void 0 : _c.shouldReconnect) === null || _d === void 0 ? void 0 : _d.call(_c, event, this);
51081
+ if (typeof delay === 'number') {
51082
+ this._pendingReconnect = setTimeout(this._createWebSocket, delay);
50852
51083
  }
50853
51084
  }
51085
+ }
51086
+
51087
+ class LiveController extends Subscribe$1 {
51088
+ constructor() {
51089
+ super();
51090
+ /**
51091
+ * ws代理器
51092
+ */
51093
+ this._ws = new RobustWebSocket();
51094
+ /**
51095
+ * 带看连接状态
51096
+ */
51097
+ this._state = LiveState.NOTINITIALIZED;
51098
+ /**
51099
+ * 添加事件监听
51100
+ */
51101
+ this._addWebSocketEventListeners = () => {
51102
+ this._ws.on('close', this._handleCloseEvent);
51103
+ this._ws.on('connecting', this._handleConnectingEvent);
51104
+ this._ws.on('error', this._handleErrorEvent);
51105
+ this._ws.on('message', this._handleMessageEvent);
51106
+ this._ws.on('open', this._handleOpenEvent);
51107
+ this._ws.on('timeout', this._handleTimeoutEvent);
51108
+ };
51109
+ /**
51110
+ * 移除事件监听
51111
+ */
51112
+ this._removeWebSocketEventListeners = () => {
51113
+ this._ws.off('close', this._handleCloseEvent);
51114
+ this._ws.off('connecting', this._handleConnectingEvent);
51115
+ this._ws.off('error', this._handleErrorEvent);
51116
+ this._ws.off('message', this._handleMessageEvent);
51117
+ this._ws.off('open', this._handleOpenEvent);
51118
+ this._ws.off('timeout', this._handleTimeoutEvent);
51119
+ };
51120
+ /**
51121
+ * 处理房间关闭事件
51122
+ * @param event
51123
+ */
51124
+ this._handleCloseEvent = (event) => {
51125
+ logger$1.info(`live room closed bacause of ${event.code}-${event.reason || parseWSClsErr(event.code)}`);
51126
+ this.state = LiveState.CLOSED;
51127
+ };
51128
+ /**
51129
+ * 连接中
51130
+ * @param event
51131
+ */
51132
+ this._handleConnectingEvent = (event) => {
51133
+ logger$1.info(`live room is connecting`, event.detail);
51134
+ this.state = LiveState.CONNECTING;
51135
+ };
51136
+ /**
51137
+ * 连接发送异常
51138
+ * @param event
51139
+ */
51140
+ this._handleErrorEvent = (event) => {
51141
+ logger$1.error(`live room error`, event);
51142
+ this.state = LiveState.CLOSED;
51143
+ };
51144
+ /**
51145
+ * 接收到消息
51146
+ * @param event
51147
+ */
51148
+ this._handleMessageEvent = (event) => {
51149
+ // logger.info('live room received message ', event.data);
51150
+ let message = (() => {
51151
+ try {
51152
+ return JSON.parse(event.data);
51153
+ }
51154
+ catch (e) {
51155
+ return event.data;
51156
+ }
51157
+ })();
51158
+ this.emit('message', message);
51159
+ };
51160
+ /**
51161
+ * 连接建立成功
51162
+ * @param event
51163
+ */
51164
+ this._handleOpenEvent = (event) => {
51165
+ logger$1.info('live room open', event.detail);
51166
+ this.state = LiveState.OPEN;
51167
+ };
51168
+ /**
51169
+ * 处理超时
51170
+ * @param event
51171
+ */
51172
+ this._handleTimeoutEvent = (event) => {
51173
+ logger$1.error('live room connect timeout!', event.detail);
51174
+ this.state = LiveState.CLOSED;
51175
+ };
51176
+ /**
51177
+ * 释放资源,释放之后需要重新实例化
51178
+ * @returns
51179
+ */
51180
+ this.dispose = () => __awaiter$$(this, void 0, void 0, function* () {
51181
+ this._removeWebSocketEventListeners();
51182
+ return yield this.close('live room close by controller disposed!');
51183
+ });
51184
+ /**
51185
+ * 开启房间链接
51186
+ * @param url 房间链接
51187
+ * @returns
51188
+ */
51189
+ this.open = (url) => this._ws.open(url);
51190
+ /**
51191
+ * 关闭房间
51192
+ * @param code
51193
+ * @param reason
51194
+ */
51195
+ this.close = (code, reason) => new Promise((resolve) => {
51196
+ this._ws.once('close', () => resolve(true));
51197
+ this._ws.close(code, reason);
51198
+ });
51199
+ this._addWebSocketEventListeners();
51200
+ }
51201
+ set state(state) {
51202
+ const prevState = JSON.parse(JSON.stringify(this._state));
51203
+ this._state = state;
51204
+ this.emit('stateChange', this.state, prevState);
51205
+ }
51206
+ get state() {
51207
+ return this._state;
51208
+ }
50854
51209
  /**
50855
51210
  * 发送数据
50856
51211
  * @param data
50857
51212
  */
50858
- sendMessage(data) {
50859
- if (!this.webSocket)
50860
- return console.warn('WebSocket has not yet been initialized!');
50861
- if (!data)
50862
- return console.warn('WebSocket messages is empty!');
50863
- this.webSocket.send(JSON.stringify(data));
51213
+ sendMessage(data = '') {
51214
+ if (data === undefined || data === null || data === '') {
51215
+ throw new Error('live message is empty!');
51216
+ }
51217
+ if (this.state === LiveState.OPEN) {
51218
+ return this._ws.send(JSON.stringify(data));
51219
+ }
51220
+ else {
51221
+ throw new Error('live has not yet been initialized!');
51222
+ }
50864
51223
  }
50865
51224
  }
50866
51225
 
50867
51226
  const unimplementedGetVoiceSign = (params) => Promise.reject('unimplemented method GetVoiceSign');
50868
- /**
50869
- * 创建 `live` 实例。
50870
- */
50871
- function createLive(options) {
50872
- const liveController = new LiveController(options);
50873
- const createLiveMsg = (command, data = {}, toUserIds) => {
50874
- toUserIds = toUserIds
50875
- ? Array.isArray(toUserIds)
50876
- ? toUserIds
50877
- : [toUserIds]
50878
- : [];
50879
- if (toUserIds)
50880
- data['to_user_ids'] = toUserIds;
50881
- return { command, front_request_id: uuid$1(), data };
50882
- };
50883
- class LiveTpl extends Subscribe$1 {
50884
- constructor() {
50885
- var _a, _b;
50886
- super();
50887
- this.keyframes = new Subscribe$1();
50888
- const jsBridge = (() => {
50889
- if (options.jsBridge)
50890
- return options.jsBridge;
50891
- if (options.useBuiltInJsBridge)
50892
- return new JSBridge();
50893
- return undefined;
50894
- })();
50895
- liveController.options.jsBridge = jsBridge;
50896
- // 没有传rtc实例时
50897
- if (!options.rtc) {
50898
- // 取指定的内部rtc类型
50899
- if (options.rtcType) {
50900
- if (!options.getVoiceSign) {
50901
- throw new Error('GetVoiceSign method must be passed when using built-in RTC instances');
50902
- }
50903
- const getVoiceSign = (_a = options.getVoiceSign) !== null && _a !== void 0 ? _a : unimplementedGetVoiceSign;
50904
- switch (options.rtcType) {
50905
- case exports.RTCType.RealseeVRWebViewRTC: {
50906
- // 内置的 VRWebViewRTC
50907
- if (!jsBridge) {
50908
- throw new Error('JsBridge instance must be passed when using built-in VRWebViewRTC instances');
51227
+ const createLiveMsg = (command, data = {}, toUserIds = []) => ({
51228
+ command,
51229
+ front_request_id: uuid$1(),
51230
+ data: Object.assign(Object.assign({}, data), { to_user_ids: Array.isArray(toUserIds) ? toUserIds : [toUserIds] }),
51231
+ });
51232
+ const _clearLiveInstanceIfNeed = () => {
51233
+ var _a, _b;
51234
+ if (window === null || window === void 0 ? void 0 : window.__Realsee_Live__) {
51235
+ (_b = (_a = window === null || window === void 0 ? void 0 : window.__Realsee_Live__) === null || _a === void 0 ? void 0 : _a.dispose) === null || _b === void 0 ? void 0 : _b.call(_a);
51236
+ window.__Realsee_Live__ = null;
51237
+ }
51238
+ };
51239
+ class Live extends Subscribe$1 {
51240
+ constructor(opts) {
51241
+ var _a;
51242
+ super();
51243
+ /**
51244
+ * 带看的配置
51245
+ */
51246
+ this._options = {};
51247
+ /**
51248
+ * 帧数据监听
51249
+ */
51250
+ this.keyframes = new Subscribe$1();
51251
+ /**
51252
+ * 内置的一些数据
51253
+ */
51254
+ this._buildInData = {
51255
+ keyframes: {},
51256
+ };
51257
+ /**
51258
+ * 根据键值取帧数据
51259
+ * @param key 帧数据的键值
51260
+ * @returns
51261
+ */
51262
+ this.getFramesByKey = (key) => this.snapshot[key];
51263
+ /**
51264
+ * 发送帧数据(需要能够被序列化)
51265
+ * @param key 帧数据键值
51266
+ * @param frame 帧数据本体
51267
+ * @returns
51268
+ */
51269
+ this.sendKeyframe = (key, frame) => {
51270
+ if (this.state !== LiveState.OPEN)
51271
+ return false;
51272
+ this._buildInData.keyframes = Object.assign(Object.assign({}, this._buildInData.keyframes), { [key]: frame });
51273
+ const liveMsg = createLiveMsg(exports.Command.KeyframeSync, this.snapshot);
51274
+ try {
51275
+ this._controller.sendMessage(liveMsg);
51276
+ return true;
51277
+ }
51278
+ catch (e) {
51279
+ logger$1.error(e);
51280
+ return false;
51281
+ }
51282
+ };
51283
+ /**
51284
+ * 带看控制器
51285
+ */
51286
+ this._controller = new LiveController();
51287
+ /**
51288
+ * 添加带看控制的事件监听
51289
+ */
51290
+ this._addLiveControllerEventListeners = () => {
51291
+ this._controller.on('stateChange', this._handleStateChange);
51292
+ this._controller.on('message', this._handleMessage);
51293
+ };
51294
+ /**
51295
+ * 移除带看控制的事件监听
51296
+ */
51297
+ this._removeLiveControllerEventListeners = () => {
51298
+ this._controller.off('stateChange', this._handleStateChange);
51299
+ this._controller.off('message', this._handleMessage);
51300
+ };
51301
+ /**
51302
+ * 带看状态变化
51303
+ * @param state
51304
+ * @returns
51305
+ */
51306
+ this._handleStateChange = (state, prevState) => this.emit('stateChange', state, prevState);
51307
+ this._handleMessage = (liveMsg) => __awaiter$$(this, void 0, void 0, function* () {
51308
+ var _b, _c, _d, _e, _f, _g;
51309
+ if (typeof liveMsg === 'object') {
51310
+ const { command, data, frontRequestId, code, message } = liveMsg;
51311
+ if (code === 'SUCCESS') {
51312
+ switch (command) {
51313
+ /**
51314
+ * 自己的状态变化
51315
+ */
51316
+ case exports.Command.SelfUserInfo: {
51317
+ const selfInfo = data;
51318
+ if (!equal(this.selfInfo, selfInfo, { deep: true })) {
51319
+ this._buildInData.selfInfo = selfInfo;
51320
+ this.emit('selfInfoUpdate', this._buildInData.selfInfo, frontRequestId);
50909
51321
  }
50910
- liveController.options.rtc = new VRWebViewRTC({
50911
- jsBridge,
50912
- getVoiceSign,
50913
- });
50914
51322
  break;
50915
51323
  }
50916
- case exports.RTCType.RealseeBrowserChimeRTC: {
50917
- // 内置的 RealseeBrowserChimeRTC
50918
- liveController.options.rtc = new BrowserRTC4Chime({
50919
- getVoiceSign,
50920
- logLevel: options.__debug__ ? build.LogLevel.DEBUG : build.LogLevel.ERROR,
50921
- });
51324
+ /**
51325
+ * 房间信息变化
51326
+ */
51327
+ case exports.Command.RoomInfo: {
51328
+ const roomInfo = data;
51329
+ this._buildInData.roomInfo = Object.assign({}, roomInfo);
51330
+ this.emit('readyKeyframeSync', (roomInfo.last_frame || {}));
50922
51331
  break;
50923
51332
  }
50924
- case exports.RTCType.RealseeBrowserRTC: {
50925
- // 内置的 RealseeBrowserRTC
50926
- liveController.options.rtc = new BrowserRTC({
50927
- getVoiceSign,
50928
- });
51333
+ /**
51334
+ * 语音信息变化
51335
+ */
51336
+ case exports.Command.RTCInfo: {
51337
+ const { voice_id: voiceId, type } = data;
51338
+ if (!((_b = this.$RTC) === null || _b === void 0 ? void 0 : _b.joined)) {
51339
+ const result = yield ((_c = this.$RTC) === null || _c === void 0 ? void 0 : _c.join({
51340
+ voiceId,
51341
+ userId: ((_d = this.selfInfo) === null || _d === void 0 ? void 0 : _d.id) || '',
51342
+ roomId: (_e = this.roomInfo) === null || _e === void 0 ? void 0 : _e.info.room_code,
51343
+ type,
51344
+ }));
51345
+ if (result) {
51346
+ const status = (_f = this._options.initialMicroStatus) !== null && _f !== void 0 ? _f : exports.MicroStatus.OPEN;
51347
+ yield ((_g = this.$RTC) === null || _g === void 0 ? void 0 : _g.toggleMicro(status === exports.MicroStatus.OPEN));
51348
+ }
51349
+ else {
51350
+ logger$1.error('加入语音房间失败');
51351
+ }
51352
+ }
51353
+ else {
51354
+ logger$1.warn('已加入语音房间,无需重复加入!');
51355
+ }
51356
+ break;
51357
+ }
51358
+ /**
51359
+ * 房间用户列表变化
51360
+ */
51361
+ case exports.Command.UserList: {
51362
+ const userList = data;
51363
+ this._buildInData.userList = userList;
51364
+ this.emit('userListUpdate', this.userList, frontRequestId);
51365
+ break;
51366
+ }
51367
+ /**
51368
+ * 自定义事件广播
51369
+ */
51370
+ case exports.Command.CustomEvent: {
51371
+ const evtMsg = data;
51372
+ this.emit('broadcast', evtMsg, frontRequestId);
51373
+ break;
51374
+ }
51375
+ /**
51376
+ * 帧数据同步
51377
+ */
51378
+ case exports.Command.KeyframeSync: {
51379
+ const remoteKeyframes = data;
51380
+ // 此处做一层 diff,仅跟本地数据不一致的情况下才广播数据。
51381
+ const keyframes = Object.keys(remoteKeyframes).reduce((accu, curr) => {
51382
+ if (equal(remoteKeyframes[curr], this._buildInData.keyframes[curr], {
51383
+ deep: true,
51384
+ })) {
51385
+ return accu;
51386
+ }
51387
+ const params = [
51388
+ remoteKeyframes[curr],
51389
+ this._buildInData.keyframes[curr],
51390
+ frontRequestId,
51391
+ ];
51392
+ const evtName = curr;
51393
+ this.keyframes.emit(evtName, ...params);
51394
+ this._buildInData.keyframes[curr] = remoteKeyframes[curr];
51395
+ accu[curr] = remoteKeyframes[curr];
51396
+ return accu;
51397
+ }, {});
51398
+ this.emit('keyframes', keyframes, frontRequestId);
51399
+ break;
51400
+ }
51401
+ /**
51402
+ * 内置消息
51403
+ */
51404
+ case exports.Command.BuiltinMsg: {
51405
+ const builtinMsg = data;
51406
+ this.emit('builtinEvent', builtinMsg);
51407
+ if (builtinMsg.event_type === exports.BuiltinEventType.UserChange) {
51408
+ this.emit('userChange', builtinMsg);
51409
+ }
51410
+ if (builtinMsg.event_type === exports.BuiltinEventType.RoomChange) {
51411
+ this.emit('roomChange', builtinMsg);
51412
+ }
51413
+ /**
51414
+ * 下发指令自己操作麦克风
51415
+ */
51416
+ if (builtinMsg.event_type === exports.BuiltinEventType.UserChange &&
51417
+ builtinMsg.action === exports.BuiltinActionType.UserMicroStatus) {
51418
+ yield this.toggleMicro(builtinMsg.data.status === exports.MicroStatus.OPEN);
51419
+ }
51420
+ /**
51421
+ * 如果下发指令退出房间,则 关闭麦克风 及 销毁 WebSocket
51422
+ */
51423
+ if (builtinMsg.event_type === exports.BuiltinEventType.RoomChange &&
51424
+ builtinMsg.action === exports.BuiltinActionType.RoomClose) {
51425
+ yield this.exit();
51426
+ }
51427
+ break;
51428
+ }
51429
+ /**
51430
+ * 被踢出房间
51431
+ */
51432
+ case exports.Command.UserKickOut: {
51433
+ this.emit('kickOut');
50929
51434
  break;
50930
51435
  }
51436
+ /**
51437
+ * 其它未知广播
51438
+ */
50931
51439
  default: {
50932
- throw new Error('unknown built-in RTC type');
51440
+ console.warn('unknown command: ', command);
50933
51441
  }
50934
51442
  }
50935
51443
  }
50936
- // 都不满足时取内置
50937
- if (options.useBuiltInRTC) {
50938
- if (!options.getVoiceSign) {
50939
- throw new Error('GetVoiceSign method must be passed when using built-in RTC instances');
50940
- }
50941
- const getVoiceSign = (_b = options.getVoiceSign) !== null && _b !== void 0 ? _b : unimplementedGetVoiceSign;
50942
- if (!jsBridge) {
50943
- throw new Error('jsBridge instance must be passed when using built-in RTC instances');
50944
- }
50945
- // vrwebview 默认
50946
- if ((isRealseeVRWebview && (isAndroid || isIOS)) || isWxMiniProgram) {
50947
- liveController.options.rtc = new VRWebViewRTC({
50948
- jsBridge,
50949
- getVoiceSign,
50950
- });
50951
- }
50952
- else {
50953
- // 其它终端使用
50954
- liveController.options.rtc =
50955
- options.builtInRTCType === exports.BuiltInRTCType.RealseeXChimeRTC
50956
- ? new BrowserRTC4Chime({ getVoiceSign })
50957
- : new BrowserRTC({ getVoiceSign });
50958
- }
51444
+ else {
51445
+ this.emit('error', liveMsg);
50959
51446
  }
50960
51447
  }
50961
- if (!liveController.options.rtc) {
50962
- console.warn('unused rtc');
50963
- }
50964
- // 默认自动连接
50965
- if (liveController.options.url && liveController.options.getTicket) {
50966
- this.connect();
50967
- }
50968
- // 健康检查:WHY --> 在某些WebView特殊场景下 WebSocket.readyState 发生变化时不会出发error\close等事件;
50969
- // 因此,开启一个定时任务监测 WebSocket.readyState 状态的更新
50970
- const healthCheck = ((healthCheck) => {
50971
- if (!healthCheck)
50972
- return 0;
50973
- if (healthCheck === true)
50974
- return 3000;
50975
- const duration = Number(healthCheck);
50976
- if (duration > 0)
50977
- return duration;
50978
- return 3000;
50979
- })(liveController.options.healthCheck);
50980
- if (healthCheck) {
50981
- liveController.healthCheckId = setInterval(() => liveController.checkReadyState(this), healthCheck);
50982
- }
50983
- }
50984
- get options() {
50985
- return Object.freeze(Object.assign({}, liveController.options));
50986
- }
50987
- get readyState() {
50988
- liveController.checkReadyState(this);
50989
- return liveController.readyState;
50990
- }
50991
- get url() {
50992
- var _a;
50993
- return ((_a = liveController.webSocket) === null || _a === void 0 ? void 0 : _a.url) || '';
50994
- }
50995
- get selfInfo() {
50996
- return liveController.selfUserInfo;
50997
- }
50998
- get userList() {
50999
- return liveController.userList || [];
51000
- }
51001
- get snapshot() {
51002
- return liveController.keyframes || {};
51003
- }
51004
- get $RTC() {
51005
- return liveController.options.rtc;
51006
- }
51007
- get jsBridge() {
51008
- return liveController.options.jsBridge;
51009
- }
51010
- async setSelfInfo(userInfo) {
51011
- if (this.readyState !== exports.WebSocketState.OPEN) {
51012
- return new Error('The connection is not open and ready to communicate.');
51013
- }
51014
- try {
51015
- return await this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserInfo, userInfo);
51016
- }
51017
- catch (error) {
51018
- return error;
51448
+ });
51449
+ /**
51450
+ * 清理带看缓存的数据
51451
+ */
51452
+ this._clearLiveData = () => {
51453
+ this._buildInData = { keyframes: {} };
51454
+ };
51455
+ /**
51456
+ * 连接带看
51457
+ * @param options
51458
+ * @returns
51459
+ */
51460
+ this.connect = (options = {}) => __awaiter$$(this, void 0, void 0, function* () {
51461
+ var _h, _j, _k, _l;
51462
+ // 检查 url 和 票据获取接口实现
51463
+ this._options.url = (_j = (_h = options.url) !== null && _h !== void 0 ? _h : this._options.url) !== null && _j !== void 0 ? _j : '';
51464
+ this._options.getTicket = (_k = options.getTicket) !== null && _k !== void 0 ? _k : this._options.getTicket;
51465
+ this._options.initialMicroStatus =
51466
+ (_l = options.rtcMicStatus) !== null && _l !== void 0 ? _l : this._options.initialMicroStatus;
51467
+ if (!/^ws(s):\/\//.test(this._options.url) ||
51468
+ typeof this._options.getTicket !== 'function') {
51469
+ if (!/^ws(s):\/\//.test(this._options.url)) {
51470
+ return new Error('Illegal realsee live room link');
51471
+ }
51472
+ if (typeof this._options.getTicket !== 'function') {
51473
+ return new Error('getTicket muse be function');
51474
+ }
51475
+ return false;
51019
51476
  }
51020
- }
51021
- getFramesByKey(key) {
51022
- return liveController.keyframes[key];
51023
- }
51024
- sendKeyframe(key, frame) {
51025
- if (this.readyState !== exports.WebSocketState.OPEN) {
51026
- return new Error('The connection is not open and ready to communicate.');
51477
+ const { force = false } = options;
51478
+ // 检查是否已有实例在使用
51479
+ const currentState = this.state;
51480
+ if (currentState === LiveState.CONNECTING ||
51481
+ currentState === LiveState.OPEN) {
51482
+ if (force) {
51483
+ try {
51484
+ yield this._controller.close('force close by connect');
51485
+ }
51486
+ catch (e) {
51487
+ console.warn(e);
51488
+ }
51489
+ }
51490
+ else {
51491
+ return new Error('已有Live实例正在连接中,请勿重复连接!');
51492
+ }
51027
51493
  }
51028
- liveController.keyframes[key] = frame;
51029
- const liveMsg = createLiveMsg(exports.Command.KeyframeSync, this.snapshot);
51030
- liveController.sendMessage(liveMsg);
51494
+ // 建立连接
51495
+ this._clearLiveData();
51496
+ const url = appendUri(this._options.url, {
51497
+ ticket: yield this._options.getTicket(),
51498
+ force: Number(!!force),
51499
+ });
51500
+ this._controller.open(url);
51031
51501
  return true;
51032
- }
51033
- broadcast(data, toUserIds, timeout) {
51034
- if (this.readyState !== exports.WebSocketState.OPEN) {
51035
- return new Error('The connection is not open and ready to communicate.');
51502
+ });
51503
+ /**
51504
+ * 退出带看
51505
+ * @returns
51506
+ */
51507
+ this.exit = () => __awaiter$$(this, void 0, void 0, function* () {
51508
+ var _m;
51509
+ this._clearLiveData();
51510
+ try {
51511
+ /** 退出强制关闭语音 */
51512
+ (_m = this.$RTC) === null || _m === void 0 ? void 0 : _m.quit();
51513
+ yield this.updateStatus(exports.BuiltinEventType.RoomChange, exports.BuiltinActionType.RoomClose, {});
51036
51514
  }
51037
- return new Promise((resolve, reject) => {
51038
- const customEvent = createLiveMsg(exports.Command.CustomEvent, data, toUserIds);
51039
- const front_request_id = customEvent.front_request_id;
51040
- liveController.sendMessage(customEvent);
51041
- const timeoutId = timeout
51042
- ? setTimeout(() => {
51043
- reject(new Error('RESPONSE TIMEOUT'));
51044
- this.off('broadcast', broadcast);
51045
- }, timeout)
51046
- : undefined;
51047
- const broadcast = (data, frontRequestId) => {
51048
- if (frontRequestId !== front_request_id)
51049
- return;
51050
- this.off('broadcast', broadcast);
51051
- resolve(data);
51052
- if (timeoutId)
51053
- clearInterval(timeoutId);
51054
- };
51055
- this.on('broadcast', broadcast);
51056
- });
51057
- }
51058
- async updateStatus(evtType, atnType, status, toUserIds) {
51059
- // TODO 统一规则,不能联合类型
51060
- if (this.readyState !== exports.WebSocketState.OPEN) {
51061
- return false;
51515
+ catch (e) {
51516
+ logger$1.warn(e);
51062
51517
  }
51063
- const data = Object.assign({ event_type: evtType, action: atnType }, { data: status });
51064
- const liveMsg = createLiveMsg(exports.Command.BuiltinMsg, data, toUserIds);
51065
- liveController.sendMessage(liveMsg);
51066
- return true;
51067
- }
51518
+ return yield this._controller.close('user exit');
51519
+ });
51520
+ /**
51521
+ * 销毁带看
51522
+ * @returns
51523
+ */
51524
+ this.dispose = () => __awaiter$$(this, void 0, void 0, function* () {
51525
+ this._removeLiveControllerEventListeners();
51526
+ this._clearLiveData();
51527
+ return yield this._controller.dispose();
51528
+ });
51529
+ /**
51530
+ * 设置自己的用户信息
51531
+ * @param userInfo
51532
+ * @returns
51533
+ */
51534
+ this.setSelfInfo = (userInfo) => __awaiter$$(this, void 0, void 0, function* () {
51535
+ return yield this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserInfo, userInfo);
51536
+ });
51068
51537
  // 仅用于用户自己的麦克风控制
51069
- async toggleMicro(microStatus) {
51070
- var _a, _b;
51071
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_own_micro))
51538
+ this.toggleMicro = (microStatus) => __awaiter$$(this, void 0, void 0, function* () {
51539
+ var _o, _p, _q;
51540
+ if (!((_p = (_o = this.selfInfo) === null || _o === void 0 ? void 0 : _o.permission) === null || _p === void 0 ? void 0 : _p.control_own_micro))
51072
51541
  return false;
51073
- await this.$RTC.toggleMicro(microStatus);
51074
- return await this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserMicroStatus, {
51075
- status: microStatus ? exports.MicroStatus.OPEN : exports.MicroStatus.CLOSE,
51076
- }, []);
51077
- }
51078
- async forbidMicro(microStatus, toUserIds) {
51079
- var _a, _b;
51080
- if (liveController.options.canForbidUserMicro &&
51081
- !liveController.options.canForbidUserMicro(toUserIds)) {
51542
+ const result = yield ((_q = this.$RTC) === null || _q === void 0 ? void 0 : _q.toggleMicro(microStatus));
51543
+ if (result) {
51544
+ yield this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserMicroStatus, {
51545
+ status: microStatus ? exports.MicroStatus.OPEN : exports.MicroStatus.CLOSE,
51546
+ }, []);
51547
+ }
51548
+ return result;
51549
+ });
51550
+ /**
51551
+ * 控制别人的麦
51552
+ * @param microStatus
51553
+ * @param toUserIds
51554
+ * @returns
51555
+ */
51556
+ this.forbidMicro = (microStatus, toUserIds) => __awaiter$$(this, void 0, void 0, function* () {
51557
+ var _r, _s;
51558
+ if (typeof this._options.canForbidUserMicro === 'function' &&
51559
+ !this._options.canForbidUserMicro(toUserIds)) {
51082
51560
  return false;
51083
51561
  }
51084
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_other_micro)) {
51562
+ if (!((_s = (_r = this.selfInfo) === null || _r === void 0 ? void 0 : _r.permission) === null || _s === void 0 ? void 0 : _s.control_other_micro)) {
51085
51563
  return false;
51086
51564
  }
51087
- return await this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserMicroStatus, {
51565
+ return yield this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserMicroStatus, {
51088
51566
  status: microStatus,
51089
51567
  }, toUserIds);
51090
- }
51568
+ });
51091
51569
  /**
51092
- * @deprecated 暂不可用
51570
+ * 控制别人的同步全量帧数据权限
51571
+ * @param sync
51572
+ * @param toUserIds
51573
+ * @returns
51093
51574
  */
51094
- async forbidSync(sync, toUserIds) {
51095
- var _a, _b;
51096
- if (liveController.options.canForbidUserSync &&
51097
- !liveController.options.canForbidUserSync(toUserIds)) {
51575
+ this.forbidSync = (sync, toUserIds) => __awaiter$$(this, void 0, void 0, function* () {
51576
+ var _t, _u;
51577
+ if (typeof this._options.canForbidUserSync === 'function' &&
51578
+ !this._options.canForbidUserSync(toUserIds)) {
51098
51579
  return false;
51099
51580
  }
51100
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_other_sync)) {
51581
+ if (!((_u = (_t = this.selfInfo) === null || _t === void 0 ? void 0 : _t.permission) === null || _u === void 0 ? void 0 : _u.control_other_sync)) {
51101
51582
  return false;
51102
51583
  }
51103
- return await this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserPermission, { sync_frame: sync }, toUserIds);
51104
- }
51105
- async kick(toUserIds) {
51106
- var _a, _b;
51107
- if (liveController.options.canForbidUserKick &&
51108
- !liveController.options.canForbidUserKick(toUserIds)) {
51584
+ return yield this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserPermission, { sync_frame: sync }, toUserIds);
51585
+ });
51586
+ /**
51587
+ * 把用户踢出带看
51588
+ * @param toUserIds
51589
+ * @returns
51590
+ */
51591
+ this.kick = (toUserIds) => __awaiter$$(this, void 0, void 0, function* () {
51592
+ var _v, _w;
51593
+ if (typeof this._options.canForbidUserKick === 'function' &&
51594
+ !this._options.canForbidUserKick(toUserIds)) {
51109
51595
  return false;
51110
51596
  }
51111
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.change_other_status)) {
51597
+ if (!((_w = (_v = this.selfInfo) === null || _v === void 0 ? void 0 : _v.permission) === null || _w === void 0 ? void 0 : _w.change_other_status)) {
51112
51598
  return false;
51113
51599
  }
51114
- return await this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserStatus, {
51600
+ return yield this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserStatus, {
51115
51601
  status: 'KICK_OUT',
51116
51602
  }, toUserIds);
51117
- }
51118
- async exit() {
51119
- /** 退出强制关闭语音(?) */
51120
- try {
51121
- this.$RTC.quit();
51122
- await this.updateStatus(exports.BuiltinEventType.RoomChange, exports.BuiltinActionType.RoomClose, {});
51123
- }
51124
- catch (e) {
51125
- console.log(e);
51126
- }
51127
- return liveController.dispose();
51128
- }
51129
- async connect(options = {}) {
51130
- // 连接 WebSocket 前验证麦克风权限
51131
- const microAuth = await this.$RTC.detectMicro();
51132
- if (!microAuth) {
51133
- const error = new Error('系统监测麦克风未授权~');
51134
- this.emit('ws.error', { type: exports.WebSocketErrorType.MicroAuth, error });
51135
- return error;
51136
- }
51137
- // WebSocket 正在连接中,规避重复连接
51138
- if (liveController.connecting) {
51139
- const error = new Error('WebSocket 正在连接中,请勿重复连接 ...');
51140
- this.emit('ws.error', {
51141
- type: exports.WebSocketErrorType.DuplicateConnect,
51142
- error,
51143
- });
51144
- return error;
51145
- }
51146
- // 非强制连接场景下,如果已经完成 WebSocket 连接则不执行后续逻辑
51147
- const { force } = options;
51148
- if (!force) {
51149
- if (this.readyState === exports.WebSocketState.CONNECTING ||
51150
- this.readyState === exports.WebSocketState.OPEN) {
51151
- return true;
51603
+ });
51604
+ this._addLiveControllerEventListeners();
51605
+ this._options = Object.assign({ initialMicroStatus: exports.MicroStatus.OPEN }, opts);
51606
+ // 第一步检查jsbridge
51607
+ this._options.jsBridge = (() => {
51608
+ if (opts.jsBridge)
51609
+ return opts.jsBridge;
51610
+ if (opts.useBuiltInJsBridge)
51611
+ return new JSBridge();
51612
+ return undefined;
51613
+ })();
51614
+ // 第二步检查getVoiceSign
51615
+ this._options.getVoiceSign = (_a = opts.getVoiceSign) !== null && _a !== void 0 ? _a : unimplementedGetVoiceSign;
51616
+ // 第二步检查rtc
51617
+ this._options.rtc = (() => {
51618
+ // 优先取rtc实例
51619
+ if (opts.rtc)
51620
+ return opts.rtc;
51621
+ // 取指定的内部rtc类型
51622
+ if (opts.rtcType) {
51623
+ if (!opts.getVoiceSign) {
51624
+ logger$1.error('GetVoiceSign method must be passed when using built-in RTC instances');
51625
+ }
51626
+ switch (opts.rtcType) {
51627
+ case exports.RTCType.RealseeVRWebViewRTC: {
51628
+ // 内置的 VRWebViewRTC
51629
+ if (this._options.jsBridge) {
51630
+ return new VRWebViewRTC({
51631
+ jsBridge: this._options.jsBridge,
51632
+ getVoiceSign: this._options.getVoiceSign,
51633
+ });
51634
+ }
51635
+ else {
51636
+ logger$1.error('JsBridge instance must be passed when using built-in VRWebViewRTC instances');
51637
+ return undefined;
51638
+ }
51639
+ }
51640
+ case exports.RTCType.RealseeBrowserChimeRTC: {
51641
+ // 内置的 RealseeBrowserChimeRTC
51642
+ return new BrowserRTC4Chime({
51643
+ getVoiceSign: this._options.getVoiceSign,
51644
+ logLevel: opts.__debug__ ? LogLevel.DEBUG : LogLevel.ERROR,
51645
+ });
51646
+ }
51647
+ case exports.RTCType.RealseeBrowserRTC: {
51648
+ // 内置的 RealseeBrowserRTC
51649
+ return new BrowserRTC({
51650
+ getVoiceSign: this._options.getVoiceSign,
51651
+ });
51652
+ }
51653
+ default: {
51654
+ logger$1.error('unknown built-in RTC type');
51655
+ return undefined;
51656
+ }
51152
51657
  }
51153
51658
  }
51154
- // WebSocket URL 逻辑
51155
- if (options.url) {
51156
- liveController.options.url = options.url;
51157
- }
51158
- if (options.getTicket) {
51159
- liveController.options.getTicket = options.getTicket;
51160
- }
51161
- if (!liveController.options.url ||
51162
- !liveController.options.url.startsWith('ws')) {
51163
- const error = new Error(`WebSocket URL 未配置或格式不合法:"${liveController.options.url}"`);
51164
- this.emit('ws.error', { type: exports.WebSocketErrorType.IllegalURL, error });
51165
- return error;
51166
- }
51167
- if (!liveController.options.getTicket) {
51168
- const error = new Error(`getTicket() 未配置!`);
51169
- this.emit('ws.error', { type: exports.WebSocketErrorType.IllegalArgs, error });
51170
- return error;
51171
- }
51172
- // 连接锁
51173
- liveController.connecting = true;
51174
- // 连接前销毁之前绑定的事件
51175
- liveController.disposeWebSocket();
51176
- this.emit('ws.beforeConnect');
51177
- const url = force || options.url || !this.url
51178
- ? appendUri(liveController.options.url, {
51179
- ticket: await liveController.options.getTicket(),
51180
- force: Number(!!force),
51181
- })
51182
- : this.url;
51183
- liveController.webSocket = new WebSocket(url);
51184
- liveController.onEvtOpnListener = () => {
51185
- liveController.checkReadyState(this);
51186
- this.emit('ws.afterConnect');
51187
- };
51188
- liveController.onEvtMsgListener = (evt) => {
51189
- liveController.checkReadyState(this);
51190
- try {
51191
- const liveMsg = parseLiveMsg(evt.data);
51192
- if (liveMsg === false)
51193
- return;
51194
- liveController.handleMessage(liveMsg, this);
51659
+ // 都不满足时取内置
51660
+ if (opts.useBuiltInRTC) {
51661
+ if (!opts.getVoiceSign) {
51662
+ logger$1.error('GetVoiceSign method must be passed when using built-in RTC instances');
51195
51663
  }
51196
- catch (error) {
51197
- // 未知错误
51198
- this.emit('ws.error', {
51199
- type: exports.WebSocketErrorType.Unknown,
51200
- error,
51201
- target: evt,
51202
- });
51664
+ if (this._options.jsBridge) {
51665
+ if ((isRealseeVRWebview && (isAndroid || isIOS)) || isWxMiniProgram) {
51666
+ return new VRWebViewRTC({
51667
+ jsBridge: this._options.jsBridge,
51668
+ getVoiceSign: this._options.getVoiceSign,
51669
+ });
51670
+ }
51671
+ else {
51672
+ // 其它终端使用
51673
+ return opts.builtInRTCType === exports.BuiltInRTCType.RealseeXChimeRTC
51674
+ ? new BrowserRTC4Chime({
51675
+ getVoiceSign: this._options.getVoiceSign,
51676
+ })
51677
+ : new BrowserRTC({ getVoiceSign: this._options.getVoiceSign });
51678
+ }
51203
51679
  }
51204
- };
51205
- liveController.onEvtErrListener = (evt) => {
51206
- live.emit('ws.error', { type: exports.WebSocketErrorType.Error, target: evt });
51207
- liveController.checkReadyState(this);
51208
- };
51209
- liveController.onEvtCLEListener = (evt) => {
51210
- liveController.checkReadyState(this);
51211
- const code = Number(evt.code);
51212
- if (code === 1000)
51213
- return;
51214
- // 异常退出不一定会触发'error'事件,根据 evt.code 一些类型的退出也算是 error 行为
51215
- const errMsg = parseWSClsErr(code);
51216
- live.emit('ws.error', {
51217
- target: evt,
51218
- type: exports.WebSocketErrorType.Close,
51219
- closeError: errMsg,
51220
- });
51221
- };
51222
- liveController.webSocket.addEventListener('open', liveController.onEvtOpnListener);
51223
- liveController.webSocket.addEventListener('message', liveController.onEvtMsgListener);
51224
- liveController.webSocket.addEventListener('error', liveController.onEvtErrListener);
51225
- liveController.webSocket.addEventListener('close', liveController.onEvtCLEListener);
51226
- return await new Promise((resolve, reject) => {
51227
- const success = () => {
51228
- resolve(true);
51229
- liveController.connecting = false;
51230
- this.off('ws.error', fail);
51231
- };
51232
- const fail = (error) => {
51233
- reject(error.error
51234
- ? error.error
51235
- : new Error('WebSocket connection failed!'));
51236
- liveController.connecting = false;
51237
- this.off('ws.afterConnect', success);
51238
- };
51239
- this.once('ws.afterConnect', success);
51240
- this.once('ws.error', fail);
51241
- });
51680
+ else {
51681
+ logger$1.error('jsBridge instance must be passed when using built-in RTC instances');
51682
+ return undefined;
51683
+ }
51684
+ }
51685
+ return undefined;
51686
+ })();
51687
+ if (!this._options.rtc) {
51688
+ logger$1.warn('unused rtc');
51242
51689
  }
51243
- async revoke() {
51244
- return true;
51690
+ // 第三步进行自动连接
51691
+ if (this._options.url && this._options.getTicket) {
51692
+ this.connect();
51693
+ }
51694
+ if (this._options.__debug__) {
51695
+ Object.assign(window, { $liveController: this._controller, $live: this });
51245
51696
  }
51246
51697
  }
51247
- const live = new LiveTpl();
51248
- // 如果是调试环境则将内部状态暴露出来
51249
- if (options.__debug__) {
51250
- Object.assign(live, { __controller__: liveController });
51251
- Object.assign(window, { $live: live });
51698
+ get options() {
51699
+ return Object.freeze(this._options || {});
51700
+ }
51701
+ /**
51702
+ * 带看状态
51703
+ */
51704
+ get state() {
51705
+ return this._controller.state;
51706
+ }
51707
+ /**
51708
+ * 兼容老逻辑
51709
+ * @deprecated 请直接读取 state 属性字段,未来将移除该属性
51710
+ */
51711
+ get readyState() {
51712
+ return this._controller.state;
51713
+ }
51714
+ /**
51715
+ * 获取当前WebSocket连接的URL。(注意:这个是WebSocket连接的完整连接,附带一些query参数)。
51716
+ * @deprecated 带看不需要关注底层ws的相关信息,未来将移除
51717
+ */
51718
+ get url() {
51719
+ return this.options.url;
51720
+ }
51721
+ /**
51722
+ * 获取当前live使用的RTC实例
51723
+ */
51724
+ get $RTC() {
51725
+ return this._options.rtc;
51726
+ }
51727
+ /**
51728
+ * 获取当前live使用的jsBridge实例
51729
+ */
51730
+ get jsBridge() {
51731
+ return this._options.jsBridge;
51732
+ }
51733
+ /**
51734
+ * 当前帧数据快照
51735
+ */
51736
+ get snapshot() {
51737
+ return this._buildInData.keyframes;
51738
+ }
51739
+ /**
51740
+ * 当前用户信息
51741
+ */
51742
+ get selfInfo() {
51743
+ return this._buildInData.selfInfo;
51744
+ }
51745
+ /**
51746
+ * 当前用户列表
51747
+ */
51748
+ get userList() {
51749
+ return this._buildInData.userList || [];
51750
+ }
51751
+ /**
51752
+ * 当前带看房间信息
51753
+ */
51754
+ get roomInfo() {
51755
+ return this._buildInData.roomInfo;
51756
+ }
51757
+ /**
51758
+ * 修改状态
51759
+ * @param evtType
51760
+ * @param atnType
51761
+ * @param status
51762
+ * @param toUserIds
51763
+ * @returns
51764
+ */
51765
+ updateStatus(evtType, atnType, status, toUserIds) {
51766
+ return __awaiter$$(this, void 0, void 0, function* () {
51767
+ if (this.state !== LiveState.OPEN)
51768
+ return false;
51769
+ const data = Object.assign({ event_type: evtType, action: atnType }, { data: status });
51770
+ const liveMsg = createLiveMsg(exports.Command.BuiltinMsg, data, toUserIds);
51771
+ try {
51772
+ this._controller.sendMessage(liveMsg);
51773
+ return true;
51774
+ }
51775
+ catch (e) {
51776
+ logger$1.error(e);
51777
+ return false;
51778
+ }
51779
+ });
51780
+ }
51781
+ /**
51782
+ * 自定义广播
51783
+ * @param request 广播请求的数据
51784
+ * @param toUserIds
51785
+ * @param timeout
51786
+ * @returns
51787
+ */
51788
+ broadcast(request, toUserIds, timeout) {
51789
+ if (this.state !== LiveState.OPEN)
51790
+ return false;
51791
+ return new Promise((resolve, reject) => {
51792
+ const customEvent = createLiveMsg(exports.Command.CustomEvent, request, toUserIds);
51793
+ const front_request_id = customEvent.front_request_id;
51794
+ const timeoutId = timeout
51795
+ ? setTimeout(() => {
51796
+ reject(new Error('RESPONSE TIMEOUT'));
51797
+ this.off('broadcast', broadcastRes);
51798
+ }, timeout)
51799
+ : undefined;
51800
+ const broadcastRes = (data, frontRequestId) => {
51801
+ if (frontRequestId !== front_request_id)
51802
+ return;
51803
+ if (timeoutId)
51804
+ clearTimeout(timeoutId);
51805
+ this.off('broadcast', broadcastRes);
51806
+ resolve(data);
51807
+ };
51808
+ this.on('broadcast', broadcastRes);
51809
+ try {
51810
+ this._controller.sendMessage(customEvent);
51811
+ }
51812
+ catch (e) {
51813
+ reject(e);
51814
+ }
51815
+ });
51252
51816
  }
51253
- return live;
51254
51817
  }
51255
51818
 
51819
+ /**
51820
+ * 创建`Live`实例
51821
+ * @param opts
51822
+ * @returns
51823
+ */
51824
+ const createLive = (opts) => {
51825
+ _clearLiveInstanceIfNeed();
51826
+ return new Live(opts);
51827
+ };
51828
+
51256
51829
  /*
51257
51830
  object-assign
51258
51831
  (c) Sindre Sorhus
@@ -53684,83 +54257,82 @@
53684
54257
  * 创建 {@link LiveReact} 实例,并提供 `React` 技术栈相关工具链。
53685
54258
  */
53686
54259
  function createLiveReact(options) {
53687
- const LiveContext = React.createContext(null);
54260
+ const LiveContext = react.createContext(null);
53688
54261
  const live = createLive(options);
53689
54262
  const jsBridge = live.jsBridge;
53690
- function LiveProvider(props) {
53691
- return (React.createElement(LiveContext.Provider, { value: props.live || live }, props.children));
53692
- }
53693
- function useLiveInstance() {
54263
+ const LiveProvider = (props) => (React.createElement(LiveContext.Provider, { value: live }, props.children));
54264
+ /**
54265
+ * 使用live实例
54266
+ * @returns
54267
+ */
54268
+ const useLiveInstance = () => {
53694
54269
  const context = React.useContext(LiveContext);
53695
54270
  if (!context)
53696
54271
  throw new Error('LiveProvider never found.');
53697
54272
  return context;
53698
- }
54273
+ };
53699
54274
  /**
54275
+ * 不建议这样使用
53700
54276
  * @deprecated
53701
54277
  * @returns
53702
54278
  */
53703
- function unsafe__useLiveInstance() {
53704
- return useLiveInstance();
53705
- }
53706
- function useRTCInstance() {
53707
- const live = useLiveInstance();
53708
- return live.$RTC;
53709
- }
54279
+ const unsafe__useLiveInstance = react.useCallback(() => useLiveInstance(), [useLiveInstance]);
54280
+ /**
54281
+ * 使用rtc实例
54282
+ */
54283
+ const useRTCInstance = react.useCallback(() => useLiveInstance().$RTC, [useLiveInstance]);
53710
54284
  /**
54285
+ * 不建议这样使用
53711
54286
  * @deprecated
53712
54287
  * @returns
53713
54288
  */
53714
- function unsafe__useRTCInstance() {
53715
- return useRTCInstance();
53716
- }
53717
- function useConnect() {
53718
- const live = useLiveInstance();
53719
- return async (options) => await live.connect(options);
53720
- }
53721
- function useCurrentWebSocketUrl() {
53722
- const live = useLiveInstance();
53723
- const [state, setState] = React.useState(undefined);
53724
- React.useEffect(() => {
53725
- const onWSBeforeConnect = () => setState(live.url);
53726
- live.on('ws.beforeConnect', onWSBeforeConnect);
53727
- return () => live.off('ws.beforeConnect', onWSBeforeConnect);
53728
- }, [live]);
53729
- return state;
53730
- }
53731
- function useKeyframeUpdateCallback(name, callback, deps = []) {
54289
+ const unsafe__useRTCInstance = react.useCallback(() => useRTCInstance(), [useRTCInstance]);
54290
+ /**
54291
+ * 带看连接操作
54292
+ */
54293
+ const useConnect = react.useCallback((options) => __awaiter$$(this, void 0, void 0, function* () { return yield useLiveInstance().connect(options); }), []);
54294
+ /**
54295
+ *
54296
+ * @param name
54297
+ * @param callback
54298
+ * @param deps
54299
+ * @returns
54300
+ */
54301
+ function useKeyframeUpdateCallback(key, callback, deps = []) {
53732
54302
  const live = useLiveInstance();
53733
54303
  const dependencyList = [live, name, ...deps];
53734
- const dispose = () => live.keyframes.off(name, callback);
54304
+ const dispose = () => live.keyframes.off(key, callback);
53735
54305
  React.useEffect(() => {
53736
- live.keyframes.on(name, callback);
54306
+ live.keyframes.on(key, callback);
53737
54307
  return dispose;
53738
54308
  }, dependencyList);
53739
54309
  return dispose;
53740
54310
  }
54311
+ /**
54312
+ * 带看的一些操作
54313
+ * @returns
54314
+ */
53741
54315
  function useLiveAction() {
53742
54316
  const live = useLiveInstance();
54317
+ const connect = React.useCallback((options) => __awaiter$$(this, void 0, void 0, function* () { return yield live.connect(options); }), [live]);
53743
54318
  const toggleMicro = React.useCallback((microStatus) => live.toggleMicro(microStatus), [live]);
53744
- const broadcast = React.useCallback((data, toUserIds, timeout = 0) => live.broadcast(data, toUserIds, timeout), [live]);
53745
- const exit = React.useCallback(() => live.exit(), [live]);
53746
- const kick = React.useCallback((toUserIds) => live.kick(toUserIds), [live]);
53747
- const forbidMicro = React.useCallback((micro, toUserIds) => live.forbidMicro(micro, toUserIds), [live]);
53748
- // const forbidSync = React.useCallback(
53749
- // (sync: boolean, toUserIds?: string | string[] | undefined) =>
53750
- // live.forbidSync(sync, toUserIds),
53751
- // [live],
53752
- // );
54319
+ const broadcast = React.useCallback((data, toUserIds, timeout = 0) => __awaiter$$(this, void 0, void 0, function* () { return yield live.broadcast(data, toUserIds, timeout); }), [live]);
54320
+ const exit = React.useCallback(() => __awaiter$$(this, void 0, void 0, function* () { return yield live.exit(); }), [live]);
54321
+ const kick = React.useCallback((toUserIds) => __awaiter$$(this, void 0, void 0, function* () { return yield live.kick(toUserIds); }), [live]);
54322
+ const forbidMicro = React.useCallback((micro, toUserIds = []) => __awaiter$$(this, void 0, void 0, function* () { return yield live.forbidMicro(micro, toUserIds); }), [live]);
54323
+ const forbidSync = React.useCallback((sync, toUserIds = []) => live.forbidSync(sync, toUserIds), [live]);
53753
54324
  const getFramesByKey = React.useCallback((key) => live.getFramesByKey(key), [live]);
53754
54325
  const sendKeyframe = React.useCallback((key, frame) => live.sendKeyframe(key, frame), [live]);
53755
54326
  const setSelfInfo = React.useCallback((userInfo) => live.setSelfInfo(userInfo), [live]);
53756
54327
  const updateStatus = React.useCallback((evtType, atnType, status, toUserIds) => live.updateStatus(evtType, atnType, status, toUserIds), [live]);
53757
54328
  return {
54329
+ connect,
53758
54330
  broadcast,
53759
54331
  exit,
53760
54332
  kick,
53761
54333
  toggleMicro,
53762
54334
  forbidMicro,
53763
- // forbidSync,
54335
+ forbidSync,
53764
54336
  sendKeyframe,
53765
54337
  getFramesByKey,
53766
54338
  setSelfInfo,
@@ -53791,16 +54363,16 @@
53791
54363
  return dispose;
53792
54364
  }
53793
54365
  /**
53794
- * @deprecated
54366
+ * 带看状态
53795
54367
  * @returns
53796
54368
  */
53797
- function useReadyState() {
54369
+ function useLiveState() {
53798
54370
  const live = useLiveInstance();
53799
- const [state, updateState] = React.useState(live.readyState);
54371
+ const [state, updateState] = React.useState(live.state);
53800
54372
  React.useEffect(() => {
53801
- const readyStateUpdate = (readyState) => updateState(readyState);
53802
- live.on('ws.readyStateUpdate', readyStateUpdate);
53803
- return () => live.off('ws.readyStateUpdate', readyStateUpdate);
54373
+ const stateChange = (state) => updateState(state);
54374
+ live.on('stateChange', stateChange);
54375
+ return () => live.off('stateChange', stateChange);
53804
54376
  }, [live]);
53805
54377
  return state;
53806
54378
  }
@@ -53837,12 +54409,12 @@
53837
54409
  live.on('selfInfoUpdate', selfInfoUpdate);
53838
54410
  return () => live.off('selfInfoUpdate', selfInfoUpdate);
53839
54411
  }, [live]);
53840
- const setState = React.useCallback(async (userInfo) => {
53841
- return await live.setSelfInfo(userInfo);
53842
- }, [live]);
54412
+ const setState = React.useCallback((userInfo) => __awaiter$$(this, void 0, void 0, function* () {
54413
+ return yield live.setSelfInfo(userInfo);
54414
+ }), [live]);
53843
54415
  return [state, setState];
53844
54416
  }
53845
- function useSnapshot() {
54417
+ function useKeyframesSnapshot() {
53846
54418
  const live = useLiveInstance();
53847
54419
  const [state, setState] = React.useState(live.snapshot);
53848
54420
  React.useEffect(() => {
@@ -53862,43 +54434,23 @@
53862
54434
  }, [live]);
53863
54435
  return state;
53864
54436
  }
53865
- /**
53866
- *
53867
- * @param name
53868
- * @param callback
53869
- * @param deps
53870
- * @returns
53871
- * @deprecated
53872
- */
53873
- function useWebSocketEventCallback(name, callback, deps = []) {
53874
- const live = useLiveInstance();
53875
- const dispose = () => live.off(name, callback);
53876
- const dependencyList = [live, name, ...deps];
53877
- React.useEffect(() => {
53878
- live.on(name, callback);
53879
- return dispose;
53880
- }, dependencyList);
53881
- return dispose;
53882
- }
53883
54437
  return {
53884
54438
  live,
53885
54439
  jsBridge,
53886
54440
  LiveProvider,
53887
54441
  unsafe__useLiveInstance,
53888
54442
  unsafe__useRTCInstance,
53889
- useCurrentWebSocketUrl,
53890
54443
  useConnect,
53891
54444
  useKeyframe,
53892
54445
  useKeyframeUpdateCallback,
53893
54446
  useLiveAction,
53894
54447
  useLiveEventCallback,
53895
- useReadyState,
54448
+ useLiveState,
53896
54449
  useRTCAction,
53897
54450
  useRTCEventCallback,
53898
54451
  useSelfInfo,
53899
- useSnapshot,
54452
+ useKeyframesSnapshot,
53900
54453
  useUserList,
53901
- useWebSocketEventCallback,
53902
54454
  };
53903
54455
  }
53904
54456