@realsee/live 0.5.0-alpha.1 → 0.5.0-alpha.10

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.
@@ -48512,9 +48512,12 @@
48512
48512
  this.micro = false;
48513
48513
  this.voiceId = '';
48514
48514
  this.options = { jsBridge, getVoiceSign };
48515
- this.jsBridge.callAndListen('live/userVolumes', (userVolumes) => {
48516
- this.emit('userVolumes', userVolumes);
48517
- });
48515
+ // TO-DO: 在微信小程序下有个音量上报的BUG会导致消息体过大从而jsbridge异常断开
48516
+ if (this.jsBridge.webViewType !== 'WxMiniProgramWebView') {
48517
+ this.jsBridge.callAndListen('live/userVolumes', (userVolumes) => {
48518
+ this.emit('userVolumes', userVolumes);
48519
+ });
48520
+ }
48518
48521
  this.jsBridge.callAndListen('live/weakNetwork', (weakNetwork) => {
48519
48522
  if (weakNetwork)
48520
48523
  this.emit('weakNetwork');
@@ -48525,25 +48528,37 @@
48525
48528
  }
48526
48529
  join(options) {
48527
48530
  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;
48535
- }
48536
- else {
48537
- if (res.code === exports.RTCJoinedInfoCodeEnum.Success) {
48538
- this.emit('joined');
48539
- this.joined = true;
48531
+ try {
48532
+ this.emit('joinWillStart');
48533
+ const { sdkAppId, userId, userSig } = yield this.options.getVoiceSign(options);
48534
+ if (!(Boolean(sdkAppId) && Boolean(userId) && Boolean(userSig))) {
48535
+ this.emit('error', new Error('加入房间失败:rtc 签名请求异常'));
48536
+ this.joined = false;
48537
+ return this.joined;
48540
48538
  }
48541
- else {
48542
- this.emit('error', res);
48539
+ this.type = options.type;
48540
+ const [res, error] = yield this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${sdkAppId}&userID=${userId}&roomID=${Number(options.voiceId)}&userSig=${userSig}`);
48541
+ if (!res) {
48542
+ this.emit('error', error ? error : new Error('加入房间失败:未知异常。'));
48543
48543
  this.joined = false;
48544
48544
  }
48545
+ else {
48546
+ if (res.code === exports.RTCJoinedInfoCodeEnum.Success) {
48547
+ this.emit('joined');
48548
+ this.joined = true;
48549
+ }
48550
+ else {
48551
+ this.emit('error', res);
48552
+ this.joined = false;
48553
+ }
48554
+ }
48555
+ return this.joined;
48556
+ }
48557
+ catch (e) {
48558
+ this.emit('error', new Error('加入房间失败:' + e.message));
48559
+ this.joined = false;
48560
+ return this.joined;
48545
48561
  }
48546
- return this.joined;
48547
48562
  });
48548
48563
  }
48549
48564
  quit() {
@@ -48689,6 +48704,23 @@
48689
48704
  }
48690
48705
  }
48691
48706
 
48707
+ exports.LiveState = void 0;
48708
+ (function (LiveState) {
48709
+ LiveState[LiveState["NOTINITIALIZED"] = -1] = "NOTINITIALIZED";
48710
+ /**
48711
+ * 正在链接中
48712
+ */
48713
+ LiveState[LiveState["CONNECTING"] = 0] = "CONNECTING";
48714
+ /**
48715
+ * 已经链接并且可以通讯
48716
+ */
48717
+ LiveState[LiveState["OPEN"] = 1] = "OPEN";
48718
+ /**
48719
+ * 连接已关闭或者链接失败
48720
+ */
48721
+ LiveState[LiveState["CLOSED"] = 3] = "CLOSED";
48722
+ })(exports.LiveState || (exports.LiveState = {}));
48723
+
48692
48724
  /**
48693
48725
  * 用户当前状态枚举。
48694
48726
  */
@@ -49213,38 +49245,48 @@
49213
49245
  WeappBridgeMessage["alive"] = "I`m alive!";
49214
49246
  })(WeappBridgeMessage || (WeappBridgeMessage = {}));
49215
49247
 
49216
- const endpoint = 'wss://ws.realsee.com';
49217
- var defaultWsEndpoint = endpoint;
49218
-
49219
49248
  /**
49220
- * 拼接ws链接
49221
- * @param tpl
49222
- * @param params
49223
- * @returns
49249
+ * ws的状态
49250
+ * 参考https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
49224
49251
  */
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;
49252
+ var WebSocketState;
49253
+ (function (WebSocketState) {
49254
+ WebSocketState[WebSocketState["CONNECTING"] = 0] = "CONNECTING";
49255
+ WebSocketState[WebSocketState["OPEN"] = 1] = "OPEN";
49256
+ WebSocketState[WebSocketState["CLOSING"] = 2] = "CLOSING";
49257
+ WebSocketState[WebSocketState["CLOSED"] = 3] = "CLOSED";
49258
+ })(WebSocketState || (WebSocketState = {}));
49233
49259
 
49234
49260
  /**
49235
- * 解析参数
49236
- * @param query
49237
- * @returns
49261
+ * ws 关闭的原因
49238
49262
  */
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;
49263
+ const WebSocketCloseOptions = {
49264
+ /**
49265
+ * 重连关闭
49266
+ */
49267
+ reconnect: { code: 1000, reason: 'close websocket when reconnecting' },
49268
+ /**
49269
+ * 主动关闭
49270
+ */
49271
+ normalClosure: { code: 1000, reason: 'normal closure' },
49272
+ /**
49273
+ * 强制关闭
49274
+ */
49275
+ forceClosure: { code: 1000, reason: 'force closure' },
49276
+ /**
49277
+ * 切换到后台,被微信杀掉,需要重连连接
49278
+ */
49279
+ interrupted: { code: 1000, reason: 'interrupted' },
49280
+ /**
49281
+ * 服务端拒绝连接
49282
+ */
49283
+ streamEndEncountered: { code: 1000, reason: 'stream end encountered' },
49284
+ /**
49285
+ * 丢失心跳
49286
+ * @deprecated
49287
+ */
49288
+ lostHeartbeat: { code: 1000, reason: 'lost heartbeat' },
49289
+ };
49248
49290
 
49249
49291
  const EVENT_SYMBOL = '$$REALSEE_JSBRIDGE_EVENT$$';
49250
49292
  function __generateEventIfNotExisted(instance) {
@@ -49359,253 +49401,228 @@
49359
49401
  }
49360
49402
 
49361
49403
  /**
49362
- * 具有鲁棒性的WebSocket封装
49363
- * 1、自动重连
49364
- * 2、可根据网络情况进行重连
49404
+ * ws的事件
49365
49405
  */
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;
49406
+ var WebSocketEvent;
49407
+ (function (WebSocketEvent) {
49408
+ WebSocketEvent["open"] = "open";
49409
+ WebSocketEvent["close"] = "close";
49410
+ WebSocketEvent["error"] = "error";
49411
+ WebSocketEvent["message"] = "message";
49412
+ })(WebSocketEvent || (WebSocketEvent = {}));
49413
+
49414
+ class Ws4Webview extends Subscribe {
49415
+ constructor() {
49416
+ super(...arguments);
49417
+ this._state = null;
49386
49418
  /**
49387
- * 清理连接中的请求
49419
+ * @description 注册ws接通事件回调
49420
+ * @param listener 事件回调函数
49421
+ * @param once 是否只执行一次
49422
+ * @returns
49388
49423
  */
49389
- this._clearPendingReconnectIfNeeded = () => {
49390
- if (this._pendingReconnect) {
49391
- clearTimeout(this._pendingReconnect);
49392
- this._pendingReconnect = undefined;
49393
- }
49394
- };
49424
+ this.onOpen = (listener, once) => once ? this.once(WebSocketEvent.open, listener) : this.on(WebSocketEvent.open, listener);
49395
49425
  /**
49396
- * 当网页连接上网络进行重连
49397
- * @param event
49426
+ * @description 注册一次ws接通事件回调
49427
+ * @param listener 事件回调函数
49398
49428
  */
49399
- this._online = (event) => {
49400
- if (this._reconnectWhenOnlineAgain) {
49401
- this._clearPendingReconnectIfNeeded();
49402
- this._reconnect(event);
49403
- }
49404
- };
49429
+ this.onceOpen = (listener) => this.onOpen(listener, true);
49405
49430
  /**
49406
- * 当网页断开网络进行关闭
49431
+ * @description 移除ws接通事件回调
49432
+ * @param listener 事件回调函数
49433
+ * @returns
49407
49434
  */
49408
- this._offline = () => {
49409
- var _a;
49410
- this._reconnectWhenOnlineAgain = true;
49411
- (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.close(1000);
49412
- };
49435
+ this.offOpen = (listener) => this.hasListener(WebSocketEvent.open) && this.off(WebSocketEvent.open, listener);
49413
49436
  /**
49414
- * 解除网络监听事件
49437
+ * @description 注册ws消息事件回调
49438
+ * @param listener 事件回调函数
49439
+ * @param once 是否只执行一次
49440
+ * @returns
49415
49441
  */
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
- };
49442
+ this.onMessage = (listener, once) => once ? this.once(WebSocketEvent.message, listener) : this.on(WebSocketEvent.message, listener);
49423
49443
  /**
49424
- * 注册网络监听事件
49444
+ * @description 注册一次ws消息事件回调
49445
+ * @param listener 事件回调函数
49425
49446
  */
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
- };
49447
+ this.onceMessage = (listener) => this.onMessage(listener, true);
49433
49448
  /**
49434
- * 发送消息
49435
- * @param data
49449
+ * @description 移除ws接通事件回调
49450
+ * @param listener 事件回调函数
49436
49451
  * @returns
49437
49452
  */
49438
- this.send = (data) => { var _a; return (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.send(data); };
49453
+ this.offMessage = (listener) => this.hasListener(WebSocketEvent.message) && this.off(WebSocketEvent.message, listener);
49439
49454
  /**
49440
- * 关闭连接
49441
- * @param code 代码
49442
- * @param reason 原因
49455
+ * @description 注册ws错误事件回调
49456
+ * @param listener 事件回调函数
49457
+ * @param once 是否只执行一次
49443
49458
  * @returns
49444
49459
  */
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
- };
49457
- /**
49458
- * 进行ws连接
49459
- */
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
- };
49473
- /**
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
- };
49460
+ this.onError = (listener, once) => once ? this.once(WebSocketEvent.error, listener) : this.on(WebSocketEvent.error, listener);
49503
49461
  /**
49504
- * 分发ws事件
49462
+ * @description 注册一次ws消息事件回调
49463
+ * @param listener 事件回调函数
49505
49464
  */
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
- };
49465
+ this.onceError = (listener) => this.onError(listener, true);
49513
49466
  /**
49514
- * ws连接事件
49467
+ * @description 移除ws接通事件回调
49468
+ * @param listener 事件回调函数
49515
49469
  * @returns
49516
49470
  */
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
- };
49471
+ this.offError = (listener) => this.hasListener(WebSocketEvent.error) && this.off(WebSocketEvent.error, listener);
49528
49472
  /**
49529
- * ws 关闭事件
49530
- * @param event
49473
+ * @description 注册ws错误事件回调
49474
+ * @param listener 事件回调函数
49475
+ * @param once 是否只执行一次
49531
49476
  * @returns
49532
49477
  */
49533
- this._webSocketCloseHandler = (event) => {
49534
- this._reconnect(event);
49535
- return this.emit('close', event);
49536
- };
49478
+ this.onClose = (listener, once) => once ? this.once(WebSocketEvent.close, listener) : this.on(WebSocketEvent.close, listener);
49537
49479
  /**
49538
- * ws 异常
49539
- * @param event
49540
- * @returns
49480
+ * @description 注册一次ws消息事件回调
49481
+ * @param listener 事件回调函数
49541
49482
  */
49542
- this._webSocketErrorHandler = (event) => {
49543
- return this.emit('error', new CustomEvent('error', { detail: { error: event } }));
49544
- };
49483
+ this.onceClose = (listener) => this.onClose(listener, true);
49545
49484
  /**
49546
- * ws消息
49547
- * @param event
49485
+ * @description 移除ws接通事件回调
49486
+ * @param listener 事件回调函数
49548
49487
  * @returns
49549
49488
  */
49550
- this._webSocketMessageHandler = (event) => {
49551
- return this.emit('message', event);
49552
- };
49553
- if (options) {
49554
- this.setOptions(options);
49555
- }
49489
+ this.offClose = (listener) => this.hasListener(WebSocketEvent.close) && this.off(WebSocketEvent.close, listener);
49556
49490
  }
49557
- get attempts() {
49558
- return this._attempts;
49491
+ get readyState() {
49492
+ return this._state;
49559
49493
  }
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');
49568
- }
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.');
49494
+ /**
49495
+ * 连接ws
49496
+ * @param options
49497
+ */
49498
+ connect(options) {
49499
+ if (this._state === WebSocketState.CONNECTING || this._state === WebSocketState.OPEN)
49500
+ return Promise.reject("\u5DF2\u5B58\u5728\u4E00\u4E2A\u8FDE\u63A5\u4E2D\u6216\u6253\u5F00\u72B6\u6001\u7684websocket\u5B9E\u4F8B" /* ErrorMessage.WsAlreadyExists */);
49501
+ return new Promise((resolve, reject) => {
49502
+ const { url } = options;
49503
+ if (!url)
49504
+ throw new Error("\u975E\u6CD5\u7684websocket\u94FE\u63A5" /* ErrorMessage.WsUrlInvalid */);
49505
+ this._wsOptions = options;
49506
+ this._state = WebSocketState.CONNECTING;
49507
+ this._wsTask = new WebSocket(url);
49508
+ this.registerEventHandler();
49509
+ this.handleConnected();
49510
+ this.onceOpen(() => resolve(true));
49511
+ this.onceError((err) => reject(err));
49512
+ });
49513
+ }
49514
+ /**
49515
+ * 重连websocket
49516
+ * @returns
49517
+ */
49518
+ async reconnect() {
49519
+ this.close(WebSocketCloseOptions.reconnect);
49520
+ if (this._wsOptions)
49521
+ this.connect(this._wsOptions);
49522
+ }
49523
+ /**
49524
+ * @description 发送消息
49525
+ * @param data 消息体
49526
+ */
49527
+ send(data) {
49528
+ try {
49529
+ if (this._wsTask && this.readyState === WebSocketState.OPEN) {
49530
+ this._wsTask.send(data);
49531
+ }
49532
+ else if (this._wsTask && this.readyState === WebSocketState.CONNECTING) {
49533
+ this.once(WebSocketEvent.open, () => { var _a; return (_a = this._wsTask) === null || _a === void 0 ? void 0 : _a.send(data); });
49534
+ }
49535
+ else {
49536
+ this.once(WebSocketEvent.open, () => this.send(data));
49537
+ this.reconnect();
49538
+ }
49571
49539
  }
49572
- this._options = opts;
49573
- if (this._options.automaticOpen) {
49574
- this._createWebSocket();
49540
+ catch (e) {
49541
+ this.once(WebSocketEvent.open, () => this.send(data));
49542
+ this.reconnect();
49575
49543
  }
49576
49544
  }
49577
49545
  /**
49578
- * 进行重连
49579
- * @param event
49580
- * @returns
49546
+ * @description 手动关闭ws
49547
+ * @param options 关闭ws的配置参数
49548
+ */
49549
+ close(options) {
49550
+ var _a;
49551
+ this._state = WebSocketState.CLOSING;
49552
+ (_a = this._wsTask) === null || _a === void 0 ? void 0 : _a.close(options.code, options.reason);
49553
+ }
49554
+ /**
49555
+ * 处理连接后的事件绑定
49556
+ */
49557
+ handleConnected() {
49558
+ this.onceOpen(() => (this._state = WebSocketState.OPEN));
49559
+ this.onClose(() => (this._state = WebSocketState.CLOSED));
49560
+ }
49561
+ /**
49562
+ * 注册websocket事件
49581
49563
  */
49582
- _reconnect(event) {
49564
+ registerEventHandler() {
49583
49565
  var _a, _b, _c, _d;
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
- }
49566
+ (_a = this._wsTask) === null || _a === void 0 ? void 0 : _a.addEventListener(WebSocketEvent.open, (ev) => this.emit(WebSocketEvent.open, ev));
49567
+ (_b = this._wsTask) === null || _b === void 0 ? void 0 : _b.addEventListener(WebSocketEvent.message, (result) => {
49568
+ let data = result.data;
49569
+ try {
49570
+ if (typeof result.data === 'string') {
49571
+ data = JSON.parse(result.data);
49572
+ }
49573
+ }
49574
+ catch (e) {
49575
+ /** 不可序列化的数据不用处理 */
49576
+ }
49577
+ this.emit(WebSocketEvent.message, data);
49578
+ });
49579
+ (_c = this._wsTask) === null || _c === void 0 ? void 0 : _c.addEventListener(WebSocketEvent.close, (ev) => this.emit(WebSocketEvent.close, ev));
49580
+ (_d = this._wsTask) === null || _d === void 0 ? void 0 : _d.addEventListener(WebSocketEvent.error, (ev) => this.emit(WebSocketEvent.error, ev));
49597
49581
  }
49598
- }
49582
+ }
49583
+ var Ws4Webview$1 = Ws4Webview;
49584
+
49585
+ const endpoint = 'wss://ws.realsee.com';
49586
+ var defaultWsEndpoint = endpoint;
49587
+
49588
+ /**
49589
+ * 拼接ws链接
49590
+ * @param tpl
49591
+ * @param params
49592
+ * @returns
49593
+ */
49594
+ const generateWssUrl = (tpl, params) => {
49595
+ const url = Object.keys(params).reduce((res, curr) => res.replace(`{{${curr}}}`, `${params[curr]}`), tpl);
49596
+ return encodeURI(url);
49597
+ };
49598
+ var generateWssUrl$1 = generateWssUrl;
49599
+
49600
+ const isValidKey = (key, object) => key in object;
49601
+ var isValidKey$1 = isValidKey;
49602
+
49603
+ /**
49604
+ * 解析参数
49605
+ * @param query
49606
+ * @returns
49607
+ */
49608
+ const parseQuery = (query = '') => query
49609
+ .replace('?', '')
49610
+ .split('&')
49611
+ .map((qs) => {
49612
+ const [k, v] = qs.split('=');
49613
+ return { [k]: decodeURIComponent(v) };
49614
+ })
49615
+ .reduce((result, curr) => ({ ...result, ...curr }), {});
49616
+ var parseQuery$1 = parseQuery;
49599
49617
 
49618
+ const ws = (() => new Ws4Webview$1())();
49600
49619
  class HybridBridge {
49601
49620
  constructor() {
49602
- var _a, _b;
49603
49621
  /**
49604
49622
  * @deprecated 兼容旧逻辑
49605
49623
  */
49606
49624
  this._rsWeappBridgeMethodAdapter = {};
49607
- this._ws = new RobustWebSocket$1();
49608
- this._readyState = 'close';
49625
+ this._forceClose = false;
49609
49626
  /**
49610
49627
  * 进行jsbridge的初始化,即打通ws通道
49611
49628
  * @param timeout 超时计时
@@ -49628,7 +49645,7 @@
49628
49645
  sign: wssig,
49629
49646
  });
49630
49647
  try {
49631
- const result = await this._open(url);
49648
+ const result = await ws.connect({ url });
49632
49649
  if (result) {
49633
49650
  this.initBuiltInHandlers();
49634
49651
  res[0] = await this.waitReady(timeout);
@@ -49642,130 +49659,6 @@
49642
49659
  }
49643
49660
  return res;
49644
49661
  };
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
- };
49769
49662
  this.getStaticData = (callbackFunctionName) => {
49770
49663
  this.callAndBackfeed(JSON.stringify({
49771
49664
  actionUrl: 'common/staticData',
@@ -49812,52 +49705,134 @@
49812
49705
  callback(false);
49813
49706
  }
49814
49707
  };
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);
49708
+ }
49709
+ get isReady() {
49710
+ return ws.readyState === WebSocketState.OPEN;
49711
+ }
49712
+ /**
49713
+ * 内建的处理函数
49714
+ */
49715
+ initBuiltInHandlers() {
49716
+ this._registerLifecycleHandler();
49717
+ this._registerHeartbeatHandler();
49718
+ this._registerMessageHandler();
49719
+ this._registerBridgeRequestHandler();
49720
+ this._registerReadyHandler();
49721
+ }
49722
+ /**
49723
+ * 注册生命周期回调
49724
+ */
49725
+ _registerLifecycleHandler() {
49726
+ ws.onOpen(() => console.log('RsWeappBridge open'));
49727
+ ws.onClose((res) => {
49728
+ console.log('RsWeappBridge close');
49729
+ if (res.code === 1000) {
49730
+ switch ((res.reason + '').toLowerCase()) {
49731
+ case WebSocketCloseOptions.lostHeartbeat.reason: {
49732
+ // 心跳丢失
49733
+ ws.reconnect();
49734
+ break;
49735
+ }
49736
+ // case WebSocketCloseOptions.normalClosure.reason: // 主动关闭
49737
+ case WebSocketCloseOptions.interrupted.reason: // 切换到后台,被微信杀掉,需要重连连接
49738
+ case WebSocketCloseOptions.streamEndEncountered.reason: // 服务端拒绝连接
49739
+ default: {
49740
+ if (!this._forceClose) {
49741
+ ws.reconnect();
49742
+ }
49743
+ break;
49837
49744
  }
49838
49745
  }
49839
- };
49840
- this._ws.on('message', wsBridgeResponsehandler);
49841
- this.send(JSON.stringify({ method, args, id }));
49746
+ }
49747
+ if (res.code !== 1000 && !this._forceClose) {
49748
+ ws.reconnect();
49749
+ }
49750
+ if (this._forceClose)
49751
+ this._forceClose = false;
49842
49752
  });
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
- }
49753
+ ws.onError((err) => console.error(err));
49850
49754
  }
49851
- get isReady() {
49852
- return this._readyState === 'open';
49755
+ /**
49756
+ * 注册心跳的回调
49757
+ * @deprecated 兼容老的容器SDK
49758
+ */
49759
+ _registerHeartbeatHandler() {
49760
+ // 收到ping时回复pong
49761
+ this._receivedMessage(WeappBridgeMessage.ping, () => ws.send(WeappBridgeMessage.pong));
49762
+ // 收到pong时回复ping
49763
+ this._receivedMessage(WeappBridgeMessage.pong, () => ws.send(WeappBridgeMessage.ping));
49764
+ }
49765
+ /**
49766
+ * 当收到某消息时
49767
+ * @param targetMessage 目标消息
49768
+ * @param handler 回调
49769
+ * @param once 是否一次性处理
49770
+ */
49771
+ _receivedMessage(targetMessage, handler, once) {
49772
+ const msgHandler = (msg) => {
49773
+ if (msg === targetMessage) {
49774
+ handler();
49775
+ if (once) {
49776
+ ws.offMessage(msgHandler);
49777
+ }
49778
+ }
49779
+ };
49780
+ ws.onMessage(msgHandler);
49781
+ }
49782
+ /**
49783
+ * 强制关闭ws
49784
+ * @param options
49785
+ */
49786
+ forceClose(options) {
49787
+ this._forceClose = true;
49788
+ ws.close(options);
49789
+ }
49790
+ /**
49791
+ * 注册准备就绪的回调
49792
+ */
49793
+ _registerReadyHandler() {
49794
+ // 收到就绪询问时回复已就绪
49795
+ this._receivedMessage(WeappBridgeMessage.isReady, () => ws.send(WeappBridgeMessage.ready));
49796
+ }
49797
+ /**
49798
+ * 发送消息
49799
+ */
49800
+ send(data) {
49801
+ ws.send(data);
49802
+ }
49803
+ /**
49804
+ * 等待响应
49805
+ * @param timeout 超时计时
49806
+ * @returns
49807
+ */
49808
+ waitReady(timeout = 6000) {
49809
+ return new Promise((resolve, reject) => {
49810
+ this._receivedMessage(WeappBridgeMessage.ready, () => resolve(true));
49811
+ this.send(WeappBridgeMessage.isReady);
49812
+ setTimeout(() => reject('HybridBridge 初始化超时~'), timeout);
49813
+ });
49814
+ }
49815
+ /**
49816
+ * 注册消息投递回调
49817
+ * @deprecated 兼容老方法
49818
+ */
49819
+ _registerMessageHandler() {
49820
+ ws.onMessage((message) => {
49821
+ if (typeof message === 'object') {
49822
+ const { id, command, data } = message;
49823
+ if (command === 'message' &&
49824
+ typeof this._rsWeappBridgeMethodAdapter.bindMessage === 'function') {
49825
+ this._rsWeappBridgeMethodAdapter.bindMessage({ id, data });
49826
+ }
49827
+ }
49828
+ });
49853
49829
  }
49854
49830
  /**
49855
49831
  * 注册bridge方法回调
49856
49832
  * @deprecated 兼容老方法
49857
49833
  */
49858
49834
  _registerBridgeRequestHandler() {
49859
- this._ws.on('message', async (event) => {
49860
- const request = this._parseMessage(event);
49835
+ ws.onMessage(async (request) => {
49861
49836
  if (typeof request === 'object') {
49862
49837
  const { id, method, args, command } = request;
49863
49838
  if (command === 'request') {
@@ -49910,25 +49885,22 @@
49910
49885
  type: 'callAndBackfeed',
49911
49886
  });
49912
49887
  let timer = null;
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
- }
49888
+ const callback = (message) => {
49889
+ const { id, result, errmsg, command } = message;
49890
+ if (command === 'rsSchemeResponse' && id === reqId) {
49891
+ ws.offMessage(callback);
49892
+ if (timer)
49893
+ clearTimeout(timer);
49894
+ if (errmsg) {
49895
+ console.warn(errmsg);
49896
+ backfeed(0);
49897
+ }
49898
+ else {
49899
+ backfeed(result);
49928
49900
  }
49929
49901
  }
49930
49902
  };
49931
- this._ws.on('message', callback);
49903
+ ws.onMessage(callback);
49932
49904
  this.send(data);
49933
49905
  // 30s超时处理
49934
49906
  timer = globalThis.setTimeout(() => {
@@ -49949,22 +49921,19 @@
49949
49921
  command: 'rsSchemeRequest',
49950
49922
  type: 'callAndListen',
49951
49923
  });
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
- }
49924
+ const callback = (message) => {
49925
+ const { id, result, errmsg, command } = message;
49926
+ if (command === 'rsSchemeResponse' && id === reqId) {
49927
+ if (errmsg) {
49928
+ console.warn(errmsg);
49929
+ fn(false);
49930
+ }
49931
+ else {
49932
+ fn(result);
49964
49933
  }
49965
49934
  }
49966
49935
  };
49967
- this._ws.on('message', callback);
49936
+ ws.onMessage(callback);
49968
49937
  this.send(data);
49969
49938
  }
49970
49939
  /**
@@ -49983,26 +49952,23 @@
49983
49952
  command: 'request',
49984
49953
  });
49985
49954
  let timer = null;
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
- }
49955
+ const callback = (message) => {
49956
+ const { id, result, error, command } = message;
49957
+ if (command === 'response' &&
49958
+ id === reqId &&
49959
+ message.method === method) {
49960
+ ws.offMessage(callback);
49961
+ if (timer)
49962
+ clearTimeout(timer);
49963
+ if (error) {
49964
+ fail(error);
49965
+ }
49966
+ else {
49967
+ success(result);
50002
49968
  }
50003
49969
  }
50004
49970
  };
50005
- this._ws.on('message', callback);
49971
+ ws.onMessage(callback);
50006
49972
  this.send(data);
50007
49973
  // 30s超时处理
50008
49974
  timer = setTimeout(() => fail('method invoke timeout'), 30000);
@@ -50015,14 +49981,18 @@
50015
49981
  */
50016
49982
  class WxMiniprogramController extends BaseController {
50017
49983
  constructor() {
50018
- super(...arguments);
50019
- this._hybridBridge = new HybridBridge();
49984
+ super();
50020
49985
  this.initializing = false;
49986
+ Promise.resolve().then(async () => {
49987
+ try {
49988
+ await this.checkBridgeReady();
49989
+ }
49990
+ catch (error) {
49991
+ console.warn(error);
49992
+ }
49993
+ });
50021
49994
  }
50022
- get hybridBridge() {
50023
- return this._hybridBridge;
50024
- }
50025
- checkBridgeReady(timeout = 60000) {
49995
+ checkBridgeReady(timeout = 6000) {
50026
49996
  if (this.ready)
50027
49997
  return true;
50028
49998
  return new Promise(async (resolve, reject) => {
@@ -50039,11 +50009,12 @@
50039
50009
  }
50040
50010
  else {
50041
50011
  this.initializing = true;
50042
- const [res, error] = await this._hybridBridge.initialize(timeout);
50012
+ const hybridBridge = new HybridBridge();
50013
+ const [res, error] = await hybridBridge.initialize(timeout);
50043
50014
  if (!res || error) {
50044
50015
  throw error || new Error('HybridBridge 初始化失败~');
50045
50016
  }
50046
- this._hybridBridge.getStaticData(registerGlobalValue('HYBRID_BRIDGE_NAME', (data) => {
50017
+ hybridBridge === null || hybridBridge === void 0 ? void 0 : hybridBridge.getStaticData(registerGlobalValue('HYBRID_BRIDGE_NAME', (data) => {
50047
50018
  this.deviceInfo = (() => {
50048
50019
  try {
50049
50020
  return JSON.parse(data);
@@ -50052,13 +50023,14 @@
50052
50023
  return data;
50053
50024
  }
50054
50025
  })();
50026
+ this.hybridBridge = hybridBridge;
50027
+ this.initializing = false;
50028
+ return resolve(true);
50055
50029
  }));
50056
- this.initializing = false;
50057
- return resolve(true);
50058
50030
  }
50059
50031
  });
50060
50032
  }
50061
- async checkReady(timeout = 60000) {
50033
+ async checkReady(timeout = 6000) {
50062
50034
  const res = [null, null];
50063
50035
  if (this.ready) {
50064
50036
  res[0] = true;
@@ -50074,7 +50046,8 @@
50074
50046
  return res;
50075
50047
  }
50076
50048
  get ready() {
50077
- return !!this._hybridBridge.isReady;
50049
+ var _a;
50050
+ return !!((_a = this.hybridBridge) === null || _a === void 0 ? void 0 : _a.isReady);
50078
50051
  }
50079
50052
  get scheme() {
50080
50053
  var _a;
@@ -50116,7 +50089,7 @@
50116
50089
  resolve(res);
50117
50090
  }),
50118
50091
  });
50119
- this._hybridBridge.callAndBackfeed(msg);
50092
+ this.hybridBridge.callAndBackfeed(msg);
50120
50093
  });
50121
50094
  }
50122
50095
  async callAndListen(scheme, callback) {
@@ -50161,7 +50134,7 @@
50161
50134
  actionUrl,
50162
50135
  functionName: registerGlobalValue(actionUrl, _callback, false),
50163
50136
  });
50164
- this._hybridBridge.callAndListen(msg);
50137
+ this.hybridBridge.callAndListen(msg);
50165
50138
  });
50166
50139
  }
50167
50140
  async invoke(method, data) {
@@ -50171,7 +50144,7 @@
50171
50144
  throw readyError;
50172
50145
  }
50173
50146
  else {
50174
- return (await ((_b = (_a = this._hybridBridge).invoke) === null || _b === void 0 ? void 0 : _b.call(_a, method, data)));
50147
+ return (await ((_b = (_a = this.hybridBridge).invoke) === null || _b === void 0 ? void 0 : _b.call(_a, method, data)));
50175
50148
  }
50176
50149
  }
50177
50150
  }
@@ -50485,7 +50458,7 @@
50485
50458
  }
50486
50459
 
50487
50460
  const defaultOptions = {
50488
- timeout: 60000,
50461
+ timeout: 6000,
50489
50462
  };
50490
50463
  /**
50491
50464
  * 小程序 [web-view](https://developers.weixin.qq.com/miniprogram/dev/component/web-view.html) JSBridge。
@@ -50601,12 +50574,10 @@
50601
50574
  }
50602
50575
  const proxyCache = (url) => {
50603
50576
  if (this.webViewType === WebViewTypeEnum.WKWebview) {
50604
- return url
50605
- .replace(/https*:/, '')
50606
- .replace(/\/\//, 'realseeproxycache://');
50577
+ return url.replace(/https*:/, '').replace(/\/\//, 'realseeproxycache://');
50607
50578
  }
50608
50579
  else if (this.webViewType === WebViewTypeEnum.WebView) {
50609
- return (url + (url.indexOf('?') !== -1 ? '&' : '?') + 'realseeproxycache=1');
50580
+ return url + (url.indexOf('?') !== -1 ? '&' : '?') + 'realseeproxycache=1';
50610
50581
  }
50611
50582
  return url;
50612
50583
  };
@@ -50615,10 +50586,6 @@
50615
50586
  async invokeNativeApi(method, data) {
50616
50587
  return await this._controller.invoke(method, data);
50617
50588
  }
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
- }
50622
50589
  }
50623
50590
 
50624
50591
  /**
@@ -50636,23 +50603,6 @@
50636
50603
  }
50637
50604
  }
50638
50605
 
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
-
50656
50606
  function appendUri(uri, query) {
50657
50607
  const hasQuery = uri.indexOf('?') !== -1;
50658
50608
  const newQuery = Object.keys(query).reduce((accu, curr, idx) => `${accu}${(idx === 0 && !hasQuery) ? '?' : '&'}${curr}=${query[curr]}`, '');
@@ -50854,6 +50804,7 @@
50854
50804
  constructor(options) {
50855
50805
  // eslint-disable-next-line @typescript-eslint/no-unsafe-call
50856
50806
  super();
50807
+ this._readyState = exports.WebSocketState.NOTINITIALIZED;
50857
50808
  this._options = {
50858
50809
  timeout: 10000,
50859
50810
  shouldReconnect: (event, ws) => {
@@ -50870,6 +50821,43 @@
50870
50821
  this._reconnectWhenOnlineAgain = false;
50871
50822
  this._explicitlyClosed = false;
50872
50823
  this._connectivityEventsAttached = false;
50824
+ /**
50825
+ * 做一个健康检查
50826
+ */
50827
+ this._healthCheck = () => __awaiter$$(this, void 0, void 0, function* () {
50828
+ if (this._realWebSocket &&
50829
+ this._realWebSocket.readyState !== this._readyState) {
50830
+ this._readyState = this._realWebSocket.readyState;
50831
+ // 太惨了,断网的时候,ws不会直接closed,而是处于closing的状态
50832
+ if (this._readyState === exports.WebSocketState.CLOSING) {
50833
+ this.emit('closing');
50834
+ }
50835
+ }
50836
+ yield new Promise((resolve) => setTimeout(resolve, 2000));
50837
+ this._heathCheckTimer = requestAnimationFrame(this._healthCheck);
50838
+ });
50839
+ /**
50840
+ * 清理健康检查
50841
+ */
50842
+ this._clearHeathCheckIfNeed = () => {
50843
+ if (this._heathCheckTimer) {
50844
+ cancelAnimationFrame(this._heathCheckTimer);
50845
+ this._heathCheckTimer = undefined;
50846
+ }
50847
+ };
50848
+ /**
50849
+ * 开启健康检查
50850
+ */
50851
+ this._startHealthCheck = () => {
50852
+ this._clearHeathCheckIfNeed();
50853
+ this._heathCheckTimer = requestAnimationFrame(this._healthCheck);
50854
+ };
50855
+ /**
50856
+ * 停止健康检查
50857
+ */
50858
+ this._stopHealthCheck = () => {
50859
+ this._clearHeathCheckIfNeed();
50860
+ };
50873
50861
  /**
50874
50862
  * 清理连接中的请求
50875
50863
  */
@@ -50895,7 +50883,7 @@
50895
50883
  this._offline = () => {
50896
50884
  var _a;
50897
50885
  this._reconnectWhenOnlineAgain = true;
50898
- (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.close(1000);
50886
+ (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.close(1000, 'offline');
50899
50887
  };
50900
50888
  /**
50901
50889
  * 解除网络监听事件
@@ -50922,7 +50910,12 @@
50922
50910
  * @param data
50923
50911
  * @returns
50924
50912
  */
50925
- this.send = (data) => { var _a; return (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.send(data); };
50913
+ this.send = (data) => {
50914
+ var _a, _b, _c;
50915
+ if (((_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.readyState) === ((_b = this._realWebSocket) === null || _b === void 0 ? void 0 : _b.OPEN)) {
50916
+ (_c = this._realWebSocket) === null || _c === void 0 ? void 0 : _c.send(data);
50917
+ }
50918
+ };
50926
50919
  /**
50927
50920
  * 关闭连接
50928
50921
  * @param code 代码
@@ -50966,6 +50959,7 @@
50966
50959
  if (!newUrl)
50967
50960
  return;
50968
50961
  this._pendingReconnect = undefined;
50962
+ this._removeWebSocketEvent();
50969
50963
  this._realWebSocket = new WebSocket(newUrl, this._protocols || undefined);
50970
50964
  this._attempts = this._attempts + 1;
50971
50965
  this.emit('connecting', new CustomEvent('connecting', {
@@ -50987,6 +50981,16 @@
50987
50981
  this._attachConnectivityEvents();
50988
50982
  }
50989
50983
  };
50984
+ /**
50985
+ * 断开ws事件
50986
+ */
50987
+ this._removeWebSocketEvent = () => {
50988
+ var _a, _b, _c, _d;
50989
+ (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.removeEventListener('open', this._webSocketOpenHandler);
50990
+ (_b = this._realWebSocket) === null || _b === void 0 ? void 0 : _b.removeEventListener('close', this._webSocketCloseHandler);
50991
+ (_c = this._realWebSocket) === null || _c === void 0 ? void 0 : _c.removeEventListener('error', this._webSocketErrorHandler);
50992
+ (_d = this._realWebSocket) === null || _d === void 0 ? void 0 : _d.removeEventListener('message', this._webSocketMessageHandler);
50993
+ };
50990
50994
  /**
50991
50995
  * 分发ws事件
50992
50996
  */
@@ -51010,6 +51014,7 @@
51010
51014
  const attempts = this._attempts;
51011
51015
  this._attempts = 0;
51012
51016
  this._reconnectWhenOnlineAgain = false;
51017
+ this._startHealthCheck();
51013
51018
  return this.emit('open', Object.assign(event, { detail: { reconnects, attempts } }));
51014
51019
  };
51015
51020
  /**
@@ -51019,6 +51024,7 @@
51019
51024
  */
51020
51025
  this._webSocketCloseHandler = (event) => {
51021
51026
  this._reconnect(event);
51027
+ this._stopHealthCheck();
51022
51028
  return this.emit('close', event);
51023
51029
  };
51024
51030
  /**
@@ -51040,6 +51046,7 @@
51040
51046
  if (options) {
51041
51047
  this.setOptions(options);
51042
51048
  }
51049
+ this._startHealthCheck();
51043
51050
  }
51044
51051
  get attempts() {
51045
51052
  return this._attempts;
@@ -51090,16 +51097,20 @@
51090
51097
  /**
51091
51098
  * ws代理器
51092
51099
  */
51093
- this._ws = new RobustWebSocket();
51100
+ this._ws = new RobustWebSocket({
51101
+ url: '',
51102
+ robustOptions: { timeout: 180000 },
51103
+ });
51094
51104
  /**
51095
51105
  * 带看连接状态
51096
51106
  */
51097
- this._state = LiveState.NOTINITIALIZED;
51107
+ this._state = exports.LiveState.NOTINITIALIZED;
51098
51108
  /**
51099
51109
  * 添加事件监听
51100
51110
  */
51101
51111
  this._addWebSocketEventListeners = () => {
51102
51112
  this._ws.on('close', this._handleCloseEvent);
51113
+ this._ws.on('closing', this._handleClosingEvent);
51103
51114
  this._ws.on('connecting', this._handleConnectingEvent);
51104
51115
  this._ws.on('error', this._handleErrorEvent);
51105
51116
  this._ws.on('message', this._handleMessageEvent);
@@ -51111,6 +51122,7 @@
51111
51122
  */
51112
51123
  this._removeWebSocketEventListeners = () => {
51113
51124
  this._ws.off('close', this._handleCloseEvent);
51125
+ this._ws.off('closing', this._handleClosingEvent);
51114
51126
  this._ws.off('connecting', this._handleConnectingEvent);
51115
51127
  this._ws.off('error', this._handleErrorEvent);
51116
51128
  this._ws.off('message', this._handleMessageEvent);
@@ -51123,15 +51135,23 @@
51123
51135
  */
51124
51136
  this._handleCloseEvent = (event) => {
51125
51137
  logger$1.info(`live room closed bacause of ${event.code}-${event.reason || parseWSClsErr(event.code)}`);
51126
- this.state = LiveState.CLOSED;
51138
+ this.state = exports.LiveState.CLOSED;
51139
+ };
51140
+ /**
51141
+ * 处理房间正在关闭事件(这个时候可能是断网了)
51142
+ */
51143
+ this._handleClosingEvent = () => {
51144
+ var _a;
51145
+ logger$1.info(`live room is closing, onLine:`, (_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _a === void 0 ? void 0 : _a.onLine);
51146
+ this.state = exports.LiveState.CLOSED;
51127
51147
  };
51128
51148
  /**
51129
51149
  * 连接中
51130
51150
  * @param event
51131
51151
  */
51132
- this._handleConnectingEvent = (event) => {
51133
- logger$1.info(`live room is connecting`, event.detail);
51134
- this.state = LiveState.CONNECTING;
51152
+ this._handleConnectingEvent = () => {
51153
+ logger$1.info(`live room is connecting`);
51154
+ this.state = exports.LiveState.CONNECTING;
51135
51155
  };
51136
51156
  /**
51137
51157
  * 连接发送异常
@@ -51139,7 +51159,7 @@
51139
51159
  */
51140
51160
  this._handleErrorEvent = (event) => {
51141
51161
  logger$1.error(`live room error`, event);
51142
- this.state = LiveState.CLOSED;
51162
+ this.state = exports.LiveState.CLOSED;
51143
51163
  };
51144
51164
  /**
51145
51165
  * 接收到消息
@@ -51163,7 +51183,10 @@
51163
51183
  */
51164
51184
  this._handleOpenEvent = (event) => {
51165
51185
  logger$1.info('live room open', event.detail);
51166
- this.state = LiveState.OPEN;
51186
+ this.state = exports.LiveState.OPEN;
51187
+ if (event.detail.reconnects > 0) {
51188
+ this.emit('reconnected', event.detail);
51189
+ }
51167
51190
  };
51168
51191
  /**
51169
51192
  * 处理超时
@@ -51171,7 +51194,7 @@
51171
51194
  */
51172
51195
  this._handleTimeoutEvent = (event) => {
51173
51196
  logger$1.error('live room connect timeout!', event.detail);
51174
- this.state = LiveState.CLOSED;
51197
+ this.state = exports.LiveState.CLOSED;
51175
51198
  };
51176
51199
  /**
51177
51200
  * 释放资源,释放之后需要重新实例化
@@ -51214,7 +51237,7 @@
51214
51237
  if (data === undefined || data === null || data === '') {
51215
51238
  throw new Error('live message is empty!');
51216
51239
  }
51217
- if (this.state === LiveState.OPEN) {
51240
+ if (this.state === exports.LiveState.OPEN) {
51218
51241
  return this._ws.send(JSON.stringify(data));
51219
51242
  }
51220
51243
  else {
@@ -51267,7 +51290,7 @@
51267
51290
  * @returns
51268
51291
  */
51269
51292
  this.sendKeyframe = (key, frame) => {
51270
- if (this.state !== LiveState.OPEN)
51293
+ if (this.state !== exports.LiveState.OPEN)
51271
51294
  return false;
51272
51295
  this._buildInData.keyframes = Object.assign(Object.assign({}, this._buildInData.keyframes), { [key]: frame });
51273
51296
  const liveMsg = createLiveMsg(exports.Command.KeyframeSync, this.snapshot);
@@ -51304,6 +51327,10 @@
51304
51327
  * @returns
51305
51328
  */
51306
51329
  this._handleStateChange = (state, prevState) => this.emit('stateChange', state, prevState);
51330
+ /**
51331
+ * 消息接收
51332
+ * @param liveMsg
51333
+ */
51307
51334
  this._handleMessage = (liveMsg) => __awaiter$$(this, void 0, void 0, function* () {
51308
51335
  var _b, _c, _d, _e, _f, _g;
51309
51336
  if (typeof liveMsg === 'object') {
@@ -51335,6 +51362,7 @@
51335
51362
  */
51336
51363
  case exports.Command.RTCInfo: {
51337
51364
  const { voice_id: voiceId, type } = data;
51365
+ this._buildInData.rtcInfo = { voiceId, type };
51338
51366
  if (!((_b = this.$RTC) === null || _b === void 0 ? void 0 : _b.joined)) {
51339
51367
  const result = yield ((_c = this.$RTC) === null || _c === void 0 ? void 0 : _c.join({
51340
51368
  voiceId,
@@ -51475,10 +51503,17 @@
51475
51503
  return false;
51476
51504
  }
51477
51505
  const { force = false } = options;
51506
+ // 检测一下麦克风权限,hack
51507
+ if (this._options.rtc && this._options.jsBridge) {
51508
+ const res = yield this._options.jsBridge.detectMicro();
51509
+ if (!res) {
51510
+ return new Error('Failed to obtain microphone authorization');
51511
+ }
51512
+ }
51478
51513
  // 检查是否已有实例在使用
51479
51514
  const currentState = this.state;
51480
- if (currentState === LiveState.CONNECTING ||
51481
- currentState === LiveState.OPEN) {
51515
+ if (currentState === exports.LiveState.CONNECTING ||
51516
+ currentState === exports.LiveState.OPEN) {
51482
51517
  if (force) {
51483
51518
  try {
51484
51519
  yield this._controller.close('force close by connect');
@@ -51764,7 +51799,7 @@
51764
51799
  */
51765
51800
  updateStatus(evtType, atnType, status, toUserIds) {
51766
51801
  return __awaiter$$(this, void 0, void 0, function* () {
51767
- if (this.state !== LiveState.OPEN)
51802
+ if (this.state !== exports.LiveState.OPEN)
51768
51803
  return false;
51769
51804
  const data = Object.assign({ event_type: evtType, action: atnType }, { data: status });
51770
51805
  const liveMsg = createLiveMsg(exports.Command.BuiltinMsg, data, toUserIds);
@@ -51786,7 +51821,7 @@
51786
51821
  * @returns
51787
51822
  */
51788
51823
  broadcast(request, toUserIds, timeout) {
51789
- if (this.state !== LiveState.OPEN)
51824
+ if (this.state !== exports.LiveState.OPEN)
51790
51825
  return false;
51791
51826
  return new Promise((resolve, reject) => {
51792
51827
  const customEvent = createLiveMsg(exports.Command.CustomEvent, request, toUserIds);
@@ -54276,21 +54311,21 @@
54276
54311
  * @deprecated
54277
54312
  * @returns
54278
54313
  */
54279
- const unsafe__useLiveInstance = react.useCallback(() => useLiveInstance(), [useLiveInstance]);
54314
+ const unsafe__useLiveInstance = () => useLiveInstance();
54280
54315
  /**
54281
54316
  * 使用rtc实例
54282
54317
  */
54283
- const useRTCInstance = react.useCallback(() => useLiveInstance().$RTC, [useLiveInstance]);
54318
+ const useRTCInstance = () => useLiveInstance().$RTC;
54284
54319
  /**
54285
54320
  * 不建议这样使用
54286
54321
  * @deprecated
54287
54322
  * @returns
54288
54323
  */
54289
- const unsafe__useRTCInstance = react.useCallback(() => useRTCInstance(), [useRTCInstance]);
54324
+ const unsafe__useRTCInstance = () => useRTCInstance();
54290
54325
  /**
54291
54326
  * 带看连接操作
54292
54327
  */
54293
- const useConnect = react.useCallback((options) => __awaiter$$(this, void 0, void 0, function* () { return yield useLiveInstance().connect(options); }), []);
54328
+ const useConnect = (options) => __awaiter$$(this, void 0, void 0, function* () { return yield useLiveInstance().connect(options); });
54294
54329
  /**
54295
54330
  *
54296
54331
  * @param name