@webex/calling 3.12.0-next.4 → 3.12.0-next.41

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.
Files changed (204) hide show
  1. package/dist/CallingClient/CallingClient.js +463 -205
  2. package/dist/CallingClient/CallingClient.js.map +1 -1
  3. package/dist/CallingClient/CallingClient.test.js +170 -77
  4. package/dist/CallingClient/CallingClient.test.js.map +1 -1
  5. package/dist/CallingClient/calling/call.js +589 -445
  6. package/dist/CallingClient/calling/call.js.map +1 -1
  7. package/dist/CallingClient/calling/call.test.js +695 -445
  8. package/dist/CallingClient/calling/call.test.js.map +1 -1
  9. package/dist/CallingClient/calling/callManager.js +53 -30
  10. package/dist/CallingClient/calling/callManager.js.map +1 -1
  11. package/dist/CallingClient/calling/callManager.test.js +35 -0
  12. package/dist/CallingClient/calling/callManager.test.js.map +1 -1
  13. package/dist/CallingClient/calling/types.js +2 -0
  14. package/dist/CallingClient/calling/types.js.map +1 -1
  15. package/dist/CallingClient/constants.js +25 -3
  16. package/dist/CallingClient/constants.js.map +1 -1
  17. package/dist/CallingClient/line/index.js +4 -1
  18. package/dist/CallingClient/line/index.js.map +1 -1
  19. package/dist/CallingClient/line/line.test.js +16 -1
  20. package/dist/CallingClient/line/line.test.js.map +1 -1
  21. package/dist/CallingClient/registration/register.js +712 -406
  22. package/dist/CallingClient/registration/register.js.map +1 -1
  23. package/dist/CallingClient/registration/register.test.js +202 -21
  24. package/dist/CallingClient/registration/register.test.js.map +1 -1
  25. package/dist/CallingClient/registration/types.js.map +1 -1
  26. package/dist/CallingClient/registration/webWorker.js +41 -104
  27. package/dist/CallingClient/registration/webWorker.js.map +1 -1
  28. package/dist/CallingClient/registration/webWorker.test.js +39 -153
  29. package/dist/CallingClient/registration/webWorker.test.js.map +1 -1
  30. package/dist/CallingClient/registration/webWorkerStr.js +1 -1
  31. package/dist/CallingClient/registration/webWorkerStr.js.map +1 -1
  32. package/dist/CallingClient/utils/constants.js +46 -0
  33. package/dist/CallingClient/utils/constants.js.map +1 -0
  34. package/dist/CallingClient/utils/index.js +63 -0
  35. package/dist/CallingClient/utils/index.js.map +1 -0
  36. package/dist/CallingClient/utils/mobiusSocketMapper.js +122 -0
  37. package/dist/CallingClient/utils/mobiusSocketMapper.js.map +1 -0
  38. package/dist/CallingClient/utils/mobiusSocketMapper.test.js +211 -0
  39. package/dist/CallingClient/utils/mobiusSocketMapper.test.js.map +1 -0
  40. package/dist/CallingClient/utils/request.js +354 -0
  41. package/dist/CallingClient/utils/request.js.map +1 -0
  42. package/dist/CallingClient/utils/request.test.js +881 -0
  43. package/dist/CallingClient/utils/request.test.js.map +1 -0
  44. package/dist/CallingClient/utils/types.js +7 -0
  45. package/dist/CallingClient/utils/types.js.map +1 -0
  46. package/dist/CallingClient/utils/wsFeatureFlag.js +70 -0
  47. package/dist/CallingClient/utils/wsFeatureFlag.js.map +1 -0
  48. package/dist/CallingClient/utils/wsFeatureFlag.test.js +139 -0
  49. package/dist/CallingClient/utils/wsFeatureFlag.test.js.map +1 -0
  50. package/dist/Contacts/ContactsClient.js +13 -11
  51. package/dist/Contacts/ContactsClient.js.map +1 -1
  52. package/dist/Contacts/ContactsClient.test.js +3 -8
  53. package/dist/Contacts/ContactsClient.test.js.map +1 -1
  54. package/dist/Events/types.js +1 -11
  55. package/dist/Events/types.js.map +1 -1
  56. package/dist/Metrics/index.js +63 -2
  57. package/dist/Metrics/index.js.map +1 -1
  58. package/dist/Metrics/index.test.js +357 -1
  59. package/dist/Metrics/index.test.js.map +1 -1
  60. package/dist/Metrics/types.js +19 -1
  61. package/dist/Metrics/types.js.map +1 -1
  62. package/dist/SDKConnector/types.js.map +1 -1
  63. package/dist/common/Utils.js +138 -44
  64. package/dist/common/Utils.js.map +1 -1
  65. package/dist/common/testUtil.js +8 -4
  66. package/dist/common/testUtil.js.map +1 -1
  67. package/dist/common/types.js +2 -0
  68. package/dist/common/types.js.map +1 -1
  69. package/dist/mobius-socket/config.js +24 -0
  70. package/dist/mobius-socket/config.js.map +1 -0
  71. package/dist/mobius-socket/errors.js +143 -0
  72. package/dist/mobius-socket/errors.js.map +1 -0
  73. package/dist/mobius-socket/errors.test.js +20 -0
  74. package/dist/mobius-socket/errors.test.js.map +1 -0
  75. package/dist/mobius-socket/index.js +57 -0
  76. package/dist/mobius-socket/index.js.map +1 -0
  77. package/dist/mobius-socket/mobius-socket-events.test.js +492 -0
  78. package/dist/mobius-socket/mobius-socket-events.test.js.map +1 -0
  79. package/dist/mobius-socket/mobius-socket.js +841 -0
  80. package/dist/mobius-socket/mobius-socket.js.map +1 -0
  81. package/dist/mobius-socket/mobius-socket.test.js +1845 -0
  82. package/dist/mobius-socket/mobius-socket.test.js.map +1 -0
  83. package/dist/mobius-socket/socket/constants.js +55 -0
  84. package/dist/mobius-socket/socket/constants.js.map +1 -0
  85. package/dist/mobius-socket/socket/index.js +15 -0
  86. package/dist/mobius-socket/socket/index.js.map +1 -0
  87. package/dist/mobius-socket/socket/socket-base.js +604 -0
  88. package/dist/mobius-socket/socket/socket-base.js.map +1 -0
  89. package/dist/mobius-socket/socket/socket.js +19 -0
  90. package/dist/mobius-socket/socket/socket.js.map +1 -0
  91. package/dist/mobius-socket/socket/socket.shim.js +26 -0
  92. package/dist/mobius-socket/socket/socket.shim.js.map +1 -0
  93. package/dist/mobius-socket/socket/types.js +7 -0
  94. package/dist/mobius-socket/socket/types.js.map +1 -0
  95. package/dist/mobius-socket/socket.test.js +727 -0
  96. package/dist/mobius-socket/socket.test.js.map +1 -0
  97. package/dist/mobius-socket/test/mocha-helpers.js +23 -0
  98. package/dist/mobius-socket/test/mocha-helpers.js.map +1 -0
  99. package/dist/mobius-socket/test/promise-tick.js +28 -0
  100. package/dist/mobius-socket/test/promise-tick.js.map +1 -0
  101. package/dist/mobius-socket/types.js +7 -0
  102. package/dist/mobius-socket/types.js.map +1 -0
  103. package/dist/module/CallingClient/CallingClient.js +141 -10
  104. package/dist/module/CallingClient/calling/call.js +177 -61
  105. package/dist/module/CallingClient/calling/callManager.js +27 -7
  106. package/dist/module/CallingClient/calling/types.js +2 -0
  107. package/dist/module/CallingClient/constants.js +21 -0
  108. package/dist/module/CallingClient/line/index.js +2 -2
  109. package/dist/module/CallingClient/registration/register.js +234 -62
  110. package/dist/module/CallingClient/registration/webWorker.js +42 -61
  111. package/dist/module/CallingClient/registration/webWorkerStr.js +47 -82
  112. package/dist/module/CallingClient/utils/constants.js +30 -0
  113. package/dist/module/CallingClient/utils/index.js +5 -0
  114. package/dist/module/CallingClient/utils/mobiusSocketMapper.js +72 -0
  115. package/dist/module/CallingClient/utils/request.js +165 -0
  116. package/dist/module/CallingClient/utils/types.js +1 -0
  117. package/dist/module/CallingClient/utils/wsFeatureFlag.js +41 -0
  118. package/dist/module/Contacts/ContactsClient.js +1 -1
  119. package/dist/module/Events/types.js +0 -10
  120. package/dist/module/Metrics/index.js +48 -1
  121. package/dist/module/Metrics/types.js +18 -0
  122. package/dist/module/common/Utils.js +52 -12
  123. package/dist/module/common/testUtil.js +5 -1
  124. package/dist/module/common/types.js +2 -0
  125. package/dist/module/mobius-socket/config.js +15 -0
  126. package/dist/module/mobius-socket/errors.js +58 -0
  127. package/dist/module/mobius-socket/index.js +24 -0
  128. package/dist/module/mobius-socket/mobius-socket.js +589 -0
  129. package/dist/module/mobius-socket/socket/constants.js +26 -0
  130. package/dist/module/mobius-socket/socket/index.js +4 -0
  131. package/dist/module/mobius-socket/socket/socket-base.js +368 -0
  132. package/dist/module/mobius-socket/socket/socket.js +9 -0
  133. package/dist/module/mobius-socket/socket/socket.shim.js +12 -0
  134. package/dist/module/mobius-socket/socket/types.js +1 -0
  135. package/dist/module/mobius-socket/types.js +1 -0
  136. package/dist/types/CallingClient/CallingClient.d.ts +7 -0
  137. package/dist/types/CallingClient/CallingClient.d.ts.map +1 -1
  138. package/dist/types/CallingClient/calling/call.d.ts +12 -0
  139. package/dist/types/CallingClient/calling/call.d.ts.map +1 -1
  140. package/dist/types/CallingClient/calling/callManager.d.ts +3 -2
  141. package/dist/types/CallingClient/calling/callManager.d.ts.map +1 -1
  142. package/dist/types/CallingClient/calling/types.d.ts +34 -9
  143. package/dist/types/CallingClient/calling/types.d.ts.map +1 -1
  144. package/dist/types/CallingClient/constants.d.ts +21 -0
  145. package/dist/types/CallingClient/constants.d.ts.map +1 -1
  146. package/dist/types/CallingClient/line/index.d.ts +1 -1
  147. package/dist/types/CallingClient/line/index.d.ts.map +1 -1
  148. package/dist/types/CallingClient/registration/register.d.ts +7 -1
  149. package/dist/types/CallingClient/registration/register.d.ts.map +1 -1
  150. package/dist/types/CallingClient/registration/types.d.ts +4 -2
  151. package/dist/types/CallingClient/registration/types.d.ts.map +1 -1
  152. package/dist/types/CallingClient/registration/webWorker.d.ts.map +1 -1
  153. package/dist/types/CallingClient/registration/webWorkerStr.d.ts +1 -1
  154. package/dist/types/CallingClient/registration/webWorkerStr.d.ts.map +1 -1
  155. package/dist/types/CallingClient/utils/constants.d.ts +30 -0
  156. package/dist/types/CallingClient/utils/constants.d.ts.map +1 -0
  157. package/dist/types/CallingClient/utils/index.d.ts +6 -0
  158. package/dist/types/CallingClient/utils/index.d.ts.map +1 -0
  159. package/dist/types/CallingClient/utils/mobiusSocketMapper.d.ts +5 -0
  160. package/dist/types/CallingClient/utils/mobiusSocketMapper.d.ts.map +1 -0
  161. package/dist/types/CallingClient/utils/request.d.ts +24 -0
  162. package/dist/types/CallingClient/utils/request.d.ts.map +1 -0
  163. package/dist/types/CallingClient/utils/types.d.ts +29 -0
  164. package/dist/types/CallingClient/utils/types.d.ts.map +1 -0
  165. package/dist/types/CallingClient/utils/wsFeatureFlag.d.ts +4 -0
  166. package/dist/types/CallingClient/utils/wsFeatureFlag.d.ts.map +1 -0
  167. package/dist/types/Events/types.d.ts +4 -11
  168. package/dist/types/Events/types.d.ts.map +1 -1
  169. package/dist/types/Metrics/index.d.ts.map +1 -1
  170. package/dist/types/Metrics/types.d.ts +19 -2
  171. package/dist/types/Metrics/types.d.ts.map +1 -1
  172. package/dist/types/SDKConnector/types.d.ts +24 -0
  173. package/dist/types/SDKConnector/types.d.ts.map +1 -1
  174. package/dist/types/common/Utils.d.ts +9 -2
  175. package/dist/types/common/Utils.d.ts.map +1 -1
  176. package/dist/types/common/testUtil.d.ts +4 -1
  177. package/dist/types/common/testUtil.d.ts.map +1 -1
  178. package/dist/types/common/types.d.ts +3 -0
  179. package/dist/types/common/types.d.ts.map +1 -1
  180. package/dist/types/mobius-socket/config.d.ts +17 -0
  181. package/dist/types/mobius-socket/config.d.ts.map +1 -0
  182. package/dist/types/mobius-socket/errors.d.ts +32 -0
  183. package/dist/types/mobius-socket/errors.d.ts.map +1 -0
  184. package/dist/types/mobius-socket/index.d.ts +14 -0
  185. package/dist/types/mobius-socket/index.d.ts.map +1 -0
  186. package/dist/types/mobius-socket/mobius-socket.d.ts +48 -0
  187. package/dist/types/mobius-socket/mobius-socket.d.ts.map +1 -0
  188. package/dist/types/mobius-socket/socket/constants.d.ts +27 -0
  189. package/dist/types/mobius-socket/socket/constants.d.ts.map +1 -0
  190. package/dist/types/mobius-socket/socket/index.d.ts +5 -0
  191. package/dist/types/mobius-socket/socket/index.d.ts.map +1 -0
  192. package/dist/types/mobius-socket/socket/socket-base.d.ts +43 -0
  193. package/dist/types/mobius-socket/socket/socket-base.d.ts.map +1 -0
  194. package/dist/types/mobius-socket/socket/socket.d.ts +6 -0
  195. package/dist/types/mobius-socket/socket/socket.d.ts.map +1 -0
  196. package/dist/types/mobius-socket/socket/socket.shim.d.ts +6 -0
  197. package/dist/types/mobius-socket/socket/socket.shim.d.ts.map +1 -0
  198. package/dist/types/mobius-socket/socket/types.d.ts +61 -0
  199. package/dist/types/mobius-socket/socket/types.d.ts.map +1 -0
  200. package/dist/types/mobius-socket/types.d.ts +21 -0
  201. package/dist/types/mobius-socket/types.d.ts.map +1 -0
  202. package/package.json +20 -5
  203. package/src/mobius-socket/socket/socket.shim.ts +22 -0
  204. package/src/mobius-socket/socket/socket.ts +14 -0
@@ -0,0 +1,841 @@
1
+ "use strict";
2
+
3
+ var _Reflect$construct = require("@babel/runtime-corejs2/core-js/reflect/construct");
4
+ var _Object$keys = require("@babel/runtime-corejs2/core-js/object/keys");
5
+ var _Object$getOwnPropertySymbols = require("@babel/runtime-corejs2/core-js/object/get-own-property-symbols");
6
+ var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs2/core-js/object/get-own-property-descriptor");
7
+ var _Object$getOwnPropertyDescriptors = require("@babel/runtime-corejs2/core-js/object/get-own-property-descriptors");
8
+ var _Object$defineProperties = require("@babel/runtime-corejs2/core-js/object/define-properties");
9
+ var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
10
+ var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
11
+ _Object$defineProperty(exports, "__esModule", {
12
+ value: true
13
+ });
14
+ exports.default = void 0;
15
+ var _regenerator = _interopRequireDefault(require("@babel/runtime-corejs2/regenerator"));
16
+ var _map = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/map"));
17
+ var _isArray = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/array/is-array"));
18
+ var _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/promise"));
19
+ var _stringify = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/json/stringify"));
20
+ var _now = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/date/now"));
21
+ var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/asyncToGenerator"));
22
+ var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/slicedToArray"));
23
+ var _typeof2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/typeof"));
24
+ var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/classCallCheck"));
25
+ var _createClass2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/createClass"));
26
+ var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/possibleConstructorReturn"));
27
+ var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/getPrototypeOf"));
28
+ var _get2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/get"));
29
+ var _inherits2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/inherits"));
30
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/defineProperty"));
31
+ var _events = require("events");
32
+ var _backoff = _interopRequireDefault(require("backoff"));
33
+ var _socket = _interopRequireDefault(require("./socket"));
34
+ var _errors = require("./errors");
35
+ var _constants = require("./socket/constants");
36
+ function ownKeys(e, r) { var t = _Object$keys(e); if (_Object$getOwnPropertySymbols) { var o = _Object$getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return _Object$getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
37
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : _Object$getOwnPropertyDescriptors ? _Object$defineProperties(e, _Object$getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { _Object$defineProperty(e, r, _Object$getOwnPropertyDescriptor(t, r)); }); } return e; }
38
+ function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? _Reflect$construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
39
+ function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(_Reflect$construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
40
+ function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; } /*!
41
+ * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file
42
+ */ // @ts-ignore - backoff library does not have type definitions
43
+ var normalReconnectReasons = ['idle', 'done (forced)'];
44
+ var MOBIUS_SOCKET_NAMESPACE = 'MobiusSocket';
45
+ var TOKEN_REFRESH_INTERVAL_MS = 1 * 60 * 60 * 1000; // 1 hour
46
+
47
+ // Extended Socket type with dynamic properties
48
+
49
+ function normalizeMobiusAuthToken(token) {
50
+ return token.replace(/^Bearer\s+/i, '');
51
+ }
52
+ var MobiusSocket = /*#__PURE__*/function (_EventEmitter) {
53
+ function MobiusSocket(webex) {
54
+ var _this;
55
+ var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
56
+ (0, _classCallCheck2.default)(this, MobiusSocket);
57
+ _this = _callSuper(this, MobiusSocket);
58
+ (0, _defineProperty2.default)(_this, "webex", void 0);
59
+ (0, _defineProperty2.default)(_this, "config", void 0);
60
+ (0, _defineProperty2.default)(_this, "logger", void 0);
61
+ (0, _defineProperty2.default)(_this, "connected", void 0);
62
+ (0, _defineProperty2.default)(_this, "connecting", void 0);
63
+ (0, _defineProperty2.default)(_this, "hasEverConnected", void 0);
64
+ (0, _defineProperty2.default)(_this, "socket", void 0);
65
+ (0, _defineProperty2.default)(_this, "backoffCall", void 0);
66
+ // backoff library has no types
67
+ (0, _defineProperty2.default)(_this, "shutdownSwitchoverBackoffCall", void 0);
68
+ // backoff library has no types
69
+ (0, _defineProperty2.default)(_this, "seenAsyncEventIds", void 0);
70
+ (0, _defineProperty2.default)(_this, "connectPromise", void 0);
71
+ (0, _defineProperty2.default)(_this, "socketUrl", void 0);
72
+ (0, _defineProperty2.default)(_this, "tokenRefreshTimer", void 0);
73
+ (0, _defineProperty2.default)(_this, "tokenRefreshInFlight", void 0);
74
+ if (!webex) {
75
+ throw new Error('A Webex instance is required when initializing MobiusSocket');
76
+ }
77
+ _this.webex = webex;
78
+ _this.config = config;
79
+ _this.logger = webex.logger || console;
80
+ _this.connected = false;
81
+ _this.connecting = false;
82
+ _this.hasEverConnected = false;
83
+ _this.socket = undefined;
84
+ _this.backoffCall = undefined;
85
+ _this.shutdownSwitchoverBackoffCall = undefined;
86
+ _this.seenAsyncEventIds = new _map.default();
87
+ _this.connectPromise = undefined;
88
+ _this.tokenRefreshTimer = undefined;
89
+ _this.tokenRefreshInFlight = undefined;
90
+ return _this;
91
+ }
92
+ (0, _inherits2.default)(MobiusSocket, _EventEmitter);
93
+ return (0, _createClass2.default)(MobiusSocket, [{
94
+ key: "off",
95
+ value: function off(eventName, listener) {
96
+ if (listener) {
97
+ return _superPropGet(MobiusSocket, "off", this, 3)([eventName, listener]);
98
+ }
99
+ this.removeAllListeners(eventName);
100
+ return this;
101
+ }
102
+
103
+ /**
104
+ * Attach event listeners to a socket.
105
+ * @param socket - The socket to attach listeners to
106
+ */
107
+ }, {
108
+ key: "attachSocketEventListeners",
109
+ value: function attachSocketEventListeners(socket) {
110
+ var _this2 = this;
111
+ socket.on('close', function (event) {
112
+ return _this2.onclose(event, socket);
113
+ });
114
+ socket.on('message', function (event) {
115
+ return _this2.onmessage(event);
116
+ });
117
+ }
118
+
119
+ /**
120
+ * Tracks a newly seen async_event ID and reports whether a duplicate should be suppressed.
121
+ * @param envelope - Parsed websocket message envelope
122
+ * @returns True when the event has already been seen
123
+ */
124
+ }, {
125
+ key: "trackAsyncEventAndShouldSuppressDuplicate",
126
+ value: function trackAsyncEventAndShouldSuppressDuplicate(envelope) {
127
+ if ((envelope === null || envelope === void 0 ? void 0 : envelope.type) !== 'async_event' || !envelope.eventId) {
128
+ return false;
129
+ }
130
+ if (this.seenAsyncEventIds.has(envelope.eventId)) {
131
+ // Refresh recency so frequently retransmitted eventIds stay protected longer.
132
+ // This deletion and setting again makes the data recent since javascript map maintains order as well
133
+ var previousValue = this.seenAsyncEventIds.get(envelope.eventId) || true;
134
+ this.seenAsyncEventIds.delete(envelope.eventId);
135
+ this.seenAsyncEventIds.set(envelope.eventId, previousValue);
136
+ this.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": duplicate async_event suppressed, eventId=").concat(envelope.eventId));
137
+ return true;
138
+ }
139
+ this.logger.log("".concat(MOBIUS_SOCKET_NAMESPACE, ": tracking async_event, eventId=").concat(envelope.eventId));
140
+ this.seenAsyncEventIds.set(envelope.eventId, true);
141
+ if (this.config.dedupCacheMaxSize && this.seenAsyncEventIds.size > this.config.dedupCacheMaxSize) {
142
+ var oldestEventId = this.seenAsyncEventIds.keys().next().value || '';
143
+ this.seenAsyncEventIds.delete(oldestEventId);
144
+ this.logger.log("".concat(MOBIUS_SOCKET_NAMESPACE, ": evicted oldest async_event from dedup cache, eventId=").concat(oldestEventId));
145
+ }
146
+ return false;
147
+ }
148
+
149
+ /**
150
+ * Handle imminent shutdown by establishing a new connection while keeping
151
+ * the current one alive (make-before-break).
152
+ * Idempotent: will no-op if already in progress.
153
+ */
154
+ }, {
155
+ key: "handleImminentShutdown",
156
+ value: function handleImminentShutdown() {
157
+ var _this3 = this;
158
+ var oldSocket = this.socket;
159
+ try {
160
+ if (this.shutdownSwitchoverBackoffCall) {
161
+ this.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": [shutdown] switchover already in progress"));
162
+ return;
163
+ }
164
+ this.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": [shutdown] switchover start"));
165
+ this.connectWithBackoff(undefined, {
166
+ isShutdownSwitchover: true,
167
+ attemptOptions: {
168
+ isShutdownSwitchover: true,
169
+ onSuccess: function onSuccess(newSocket, webSocketUrl) {
170
+ _this3.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": [shutdown] switchover connected, url: ").concat(webSocketUrl));
171
+
172
+ // Promote the new socket now that the switchover succeeded
173
+ newSocket.connecting = false;
174
+ newSocket.connected = true;
175
+ _this3.socket = newSocket;
176
+ _this3.connected = true;
177
+ _this3.emitEvent('event:mobius_shutdown_switchover_complete', {
178
+ url: webSocketUrl
179
+ });
180
+ if (oldSocket) {
181
+ _this3.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": [shutdown] old socket retained; server will close with 4001"));
182
+ }
183
+ }
184
+ }
185
+ }).then(function () {
186
+ _this3.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": [shutdown] switchover completed successfully"));
187
+ }).catch(function (err) {
188
+ _this3.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": [shutdown] switchover exhausted retries; will fall back to normal reconnection: "), err);
189
+ _this3.emitEvent('event:mobius_shutdown_switchover_failed', {
190
+ reason: err
191
+ });
192
+ });
193
+ } catch (e) {
194
+ this.logger.error("".concat(MOBIUS_SOCKET_NAMESPACE, ": [shutdown] error during switchover"), e);
195
+ this.shutdownSwitchoverBackoffCall = undefined;
196
+ this.emitEvent('event:mobius_shutdown_switchover_failed', {
197
+ reason: e
198
+ });
199
+ }
200
+ }
201
+
202
+ /**
203
+ * Get the websocket URL for the currently connected socket.
204
+ * @returns The connected websocket URL, or undefined when not connected
205
+ */
206
+ }, {
207
+ key: "getConnectedWebSocketUrl",
208
+ value: function getConnectedWebSocketUrl() {
209
+ var _this$socket;
210
+ if (!((_this$socket = this.socket) !== null && _this$socket !== void 0 && _this$socket.connected)) {
211
+ return undefined;
212
+ }
213
+ return this.socket.url;
214
+ }
215
+
216
+ /**
217
+ * Sends a websocket request and resolves when the matching response arrives.
218
+ * @param payload - The websocket request payload
219
+ * @param options - Additional request options
220
+ * @returns Promise that resolves with the socket response
221
+ */
222
+ }, {
223
+ key: "sendWssRequest",
224
+ value: function sendWssRequest(payload) {
225
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
226
+ if (!payload || (0, _typeof2.default)(payload) !== 'object' || (0, _isArray.default)(payload)) {
227
+ return _promise.default.reject(new Error('`payload` is required'));
228
+ }
229
+ if (!this.socket || !this.socket.connected) {
230
+ return _promise.default.reject(new Error('Mobius socket is not connected'));
231
+ }
232
+ return this.socket.sendRequest(payload, {
233
+ timeout: options.timeout
234
+ });
235
+ }
236
+
237
+ /**
238
+ * Check if the socket is connected.
239
+ * @returns True if connected
240
+ */
241
+ }, {
242
+ key: "isConnected",
243
+ value: function isConnected() {
244
+ return this.connected;
245
+ }
246
+
247
+ /**
248
+ * Connect to Mobius.
249
+ * @param webSocketUrl - Optional websocket URL override. Falls back to the device websocket URL
250
+ * @returns Promise that resolves when connection flow completes
251
+ */
252
+ }, {
253
+ key: "connect",
254
+ value: function connect(webSocketUrl) {
255
+ var _this$socket2,
256
+ _this$socket3,
257
+ _this$webex$internal$,
258
+ _this$webex$internal$2,
259
+ _this4 = this;
260
+ if (this.connectPromise) {
261
+ this.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": connection already in progress, returning existing promise"));
262
+ return this.connectPromise;
263
+ }
264
+ if ((_this$socket2 = this.socket) !== null && _this$socket2 !== void 0 && _this$socket2.connected || (_this$socket3 = this.socket) !== null && _this$socket3 !== void 0 && _this$socket3.connecting) {
265
+ this.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": already connected, will not connect again"));
266
+ return _promise.default.resolve();
267
+ }
268
+
269
+ // Treat a connect() call that targets a different Mobius websocket URL
270
+ // as a fresh initial connection for retry purposes.
271
+ if (webSocketUrl && this.socketUrl && webSocketUrl !== this.socketUrl) {
272
+ this.hasEverConnected = false;
273
+ }
274
+
275
+ // Cache the caller-provided URL for reconnect
276
+ if (webSocketUrl) {
277
+ this.socketUrl = webSocketUrl;
278
+ }
279
+ this.connecting = true;
280
+ this.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": starting connection attempt").concat(Number(this.config.initialConnectionMaxRetries) === 0 && !this.hasEverConnected ? ' (initial retries disabled)' : ''));
281
+ var connectPromise = _promise.default.resolve(this.webex.internal.device.registered || ((_this$webex$internal$ = (_this$webex$internal$2 = this.webex.internal.device).register) === null || _this$webex$internal$ === void 0 ? void 0 : _this$webex$internal$.call(_this$webex$internal$2))).then(function () {
282
+ _this4.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": connecting"));
283
+ return _this4.connectWithBackoff(_this4.socketUrl);
284
+ }).finally(function () {
285
+ _this4.connectPromise = undefined;
286
+ });
287
+ this.connectPromise = connectPromise;
288
+ return connectPromise;
289
+ }
290
+
291
+ /**
292
+ * Disconnect the Mobius socket.
293
+ * @param options - Optional websocket close options (code, reason)
294
+ * @returns Promise that resolves after disconnect cleanup and close handling complete
295
+ */
296
+ }, {
297
+ key: "disconnect",
298
+ value: function disconnect(options) {
299
+ var _this5 = this;
300
+ this.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, "#disconnect: connecting state: ").concat(this.connecting, ",\n connected state: ").concat(this.connected, ", socket exists: ").concat(!!this.socket, ",\n options: ").concat((0, _stringify.default)(options)));
301
+ if (this.backoffCall) {
302
+ this.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": aborting connection"));
303
+ this.backoffCall.abort();
304
+ this.backoffCall = undefined;
305
+ }
306
+ if (this.shutdownSwitchoverBackoffCall) {
307
+ this.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": aborting shutdown switchover connection"));
308
+ this.shutdownSwitchoverBackoffCall.abort();
309
+ this.shutdownSwitchoverBackoffCall = undefined;
310
+ }
311
+ this.connectPromise = undefined;
312
+ this.seenAsyncEventIds.clear();
313
+ if (!this.socket) {
314
+ this.connected = false;
315
+ this.stopTokenRefreshTimer();
316
+ return _promise.default.resolve();
317
+ }
318
+ this.socket.removeAllListeners('message');
319
+ this.socket.connecting = false;
320
+ this.socket.connected = false;
321
+ return _promise.default.resolve(this.socket.close(options || undefined)).finally(function () {
322
+ _this5.connected = false;
323
+ _this5.stopTokenRefreshTimer();
324
+ });
325
+ }
326
+ }, {
327
+ key: "prepareUrl",
328
+ value: function prepareUrl(webSocketUrl) {
329
+ if (!webSocketUrl) {
330
+ // TODO: Circle back to this logic when mobius implements the shutdown switchover
331
+ webSocketUrl = this.webex.internal.device.webSocketUrl || '';
332
+ }
333
+ return _promise.default.resolve(webSocketUrl);
334
+ }
335
+ }, {
336
+ key: "attemptConnection",
337
+ value: function attemptConnection(socketUrl, callback) {
338
+ var _this6 = this;
339
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
340
+ var _options$isShutdownSw = options.isShutdownSwitchover,
341
+ isShutdownSwitchover = _options$isShutdownSw === void 0 ? false : _options$isShutdownSw,
342
+ _options$attemptOptio = options.attemptOptions,
343
+ attemptOptions = _options$attemptOptio === void 0 ? {} : _options$attemptOptio;
344
+ var _attemptOptions$onSuc = attemptOptions.onSuccess,
345
+ onSuccess = _attemptOptions$onSuc === void 0 ? null : _attemptOptions$onSuc;
346
+ var socket = new _socket.default();
347
+ socket.connecting = true;
348
+ var newWSUrl;
349
+ this.attachSocketEventListeners(socket);
350
+ var backoffCall = isShutdownSwitchover ? this.shutdownSwitchoverBackoffCall : this.backoffCall;
351
+
352
+ // Check appropriate backoff call based on connection type
353
+ if (!backoffCall) {
354
+ var mode = isShutdownSwitchover ? 'switchover backoff call' : 'backoffCall';
355
+ var msg = "".concat(MOBIUS_SOCKET_NAMESPACE, ": prevent socket open when ").concat(mode, " no longer defined");
356
+ var err = new Error(msg);
357
+ this.logger.info(msg);
358
+ // Call the callback with the error before rejecting
359
+ callback(err);
360
+ return _promise.default.reject(err);
361
+ }
362
+
363
+ // For shutdown switchover, don't set socket yet (make-before-break)
364
+ // For normal connection, set socket before opening to allow disconnect() to close it
365
+ if (!isShutdownSwitchover) {
366
+ this.socket = socket;
367
+ }
368
+ return this.prepareAndOpenSocket(socket, socketUrl, isShutdownSwitchover).then(function (webSocketUrl) {
369
+ newWSUrl = webSocketUrl;
370
+ _this6.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": ").concat(isShutdownSwitchover ? '[shutdown] switchover' : '', " connected to mobius socket, success, url: ").concat(newWSUrl));
371
+
372
+ // Custom success handler for shutdown switchover
373
+ if (onSuccess) {
374
+ onSuccess(socket, webSocketUrl);
375
+ callback();
376
+ return _promise.default.resolve();
377
+ }
378
+
379
+ // Default behavior for normal connection
380
+ callback();
381
+ return _promise.default.resolve();
382
+ }).catch(function (reason) {
383
+ // For shutdown, simpler error handling - just callback for retry
384
+ if (isShutdownSwitchover) {
385
+ _this6.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": [shutdown] switchover attempt failed"), reason);
386
+ return callback(reason);
387
+ }
388
+
389
+ // Normal connection error handling
390
+ var backoffCallNormal = _this6.backoffCall;
391
+ // Suppress connection errors that appear to be network related (code 1006).
392
+ if (reason.code !== 1006 && backoffCallNormal && (backoffCallNormal === null || backoffCallNormal === void 0 ? void 0 : backoffCallNormal.getNumRetries()) > 0) {
393
+ _this6.emitEvent('connection_failed', reason, {
394
+ retries: backoffCallNormal === null || backoffCallNormal === void 0 ? void 0 : backoffCallNormal.getNumRetries()
395
+ });
396
+ }
397
+ _this6.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": connection attempt failed"), reason, (backoffCallNormal === null || backoffCallNormal === void 0 ? void 0 : backoffCallNormal.getNumRetries()) === 0 ? reason.stack : '');
398
+
399
+ // UnknownResponse is produced by IE for any 4XXX; treat it like a bad
400
+ // web socket url and let WDM handle the token checking
401
+ if (reason instanceof _errors.UnknownResponse) {
402
+ var _this6$webex$internal, _this6$webex$internal2;
403
+ _this6.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": received unknown response code, refreshing device registration"));
404
+ return (_this6$webex$internal = (_this6$webex$internal2 = _this6.webex.internal.device).refresh) === null || _this6$webex$internal === void 0 ? void 0 : _this6$webex$internal.call(_this6$webex$internal2).then(function () {
405
+ return callback(reason);
406
+ });
407
+ }
408
+ // NotAuthorized implies expired token
409
+ if (reason instanceof _errors.NotAuthorized) {
410
+ var _this6$webex$credenti, _this6$webex$credenti2;
411
+ _this6.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": received authorization error, reauthorizing"));
412
+ return (_this6$webex$credenti = (_this6$webex$credenti2 = _this6.webex.credentials).refresh) === null || _this6$webex$credenti === void 0 ? void 0 : _this6$webex$credenti.call(_this6$webex$credenti2, {
413
+ force: true
414
+ }).then(function () {
415
+ return callback(reason);
416
+ });
417
+ }
418
+ if (reason instanceof _errors.BadRequest || reason instanceof _errors.Forbidden) {
419
+ _this6.logger.warn("".concat(MOBIUS_SOCKET_NAMESPACE, ": received unrecoverable response from ").concat(MOBIUS_SOCKET_NAMESPACE));
420
+ backoffCallNormal === null || backoffCallNormal === void 0 ? void 0 : backoffCallNormal.abort();
421
+ return callback(reason);
422
+ }
423
+ return callback(reason);
424
+ }).catch(function (reason) {
425
+ _this6.logger.error("".concat(MOBIUS_SOCKET_NAMESPACE, ": failed to handle connection failure"), reason);
426
+ callback(reason);
427
+ });
428
+ }
429
+ }, {
430
+ key: "prepareAndOpenSocket",
431
+ value: function prepareAndOpenSocket(socket, socketUrl) {
432
+ var _this7 = this;
433
+ var isShutdownSwitchover = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
434
+ var logPrefix = isShutdownSwitchover ? '[shutdown] switchover' : 'connection';
435
+ return _promise.default.all([this.prepareUrl(socketUrl), this.webex.credentials.getUserToken()]).then(function (_ref) {
436
+ var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
437
+ webSocketUrl = _ref2[0],
438
+ token = _ref2[1];
439
+ var options = {
440
+ forceCloseDelay: _this7.config.forceCloseDelay,
441
+ wssResponseTimeout: _this7.config.wssResponseTimeout,
442
+ token: normalizeMobiusAuthToken(token.toString()),
443
+ refreshToken: function refreshToken() {
444
+ return _this7.refreshToken();
445
+ },
446
+ trackingId: "".concat(_this7.webex.sessionId, "_").concat((0, _now.default)()),
447
+ logger: _this7.logger
448
+ };
449
+ if (_this7.webex.config.defaultMobiusSocketOptions) {
450
+ var customOptionsMsg = isShutdownSwitchover ? 'setting custom options for switchover' : 'setting custom options';
451
+ _this7.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": ").concat(customOptionsMsg));
452
+ options = _objectSpread(_objectSpread({}, options), _this7.webex.config.defaultMobiusSocketOptions);
453
+ }
454
+
455
+ // Only promote the socket reference for normal connections.
456
+ // Shutdown switchover keeps the old socket active until the new one succeeds.
457
+ if (!isShutdownSwitchover) {
458
+ _this7.socket = socket;
459
+ }
460
+ _this7.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, " ").concat(logPrefix, " url: ").concat(webSocketUrl));
461
+ return socket.open(webSocketUrl, options).then(function () {
462
+ return webSocketUrl;
463
+ });
464
+ });
465
+ }
466
+ }, {
467
+ key: "connectWithBackoff",
468
+ value: function connectWithBackoff(webSocketUrl) {
469
+ var _this8 = this;
470
+ var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
471
+ var _context$isShutdownSw = context.isShutdownSwitchover,
472
+ isShutdownSwitchover = _context$isShutdownSw === void 0 ? false : _context$isShutdownSw,
473
+ _context$attemptOptio = context.attemptOptions,
474
+ attemptOptions = _context$attemptOptio === void 0 ? {} : _context$attemptOptio;
475
+ return new _promise.default(function (resolve, reject) {
476
+ var call;
477
+ var isInitialConnect = !isShutdownSwitchover && !_this8.hasEverConnected;
478
+ var initialRetryLimit = _this8.config.initialConnectionMaxRetries == null ? null : Number(_this8.config.initialConnectionMaxRetries);
479
+ var isInitialConnectWithoutRetries = isInitialConnect && initialRetryLimit === 0;
480
+ var onComplete = function onComplete(err) {
481
+ if (isShutdownSwitchover) {
482
+ _this8.shutdownSwitchoverBackoffCall = undefined;
483
+ } else {
484
+ _this8.backoffCall = undefined;
485
+ }
486
+ if (err) {
487
+ var msg = isShutdownSwitchover ? "[shutdown] switchover failed after ".concat(call.getNumRetries(), " retries") : "failed to connect after ".concat(call.getNumRetries(), " retries");
488
+ _this8.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": ").concat(msg, "; ").concat(err));
489
+ // Only mutate socket flags for normal connections.
490
+ // During shutdown switchover, this.socket is the old live socket — don't touch it.
491
+ if (!isShutdownSwitchover && _this8.socket) {
492
+ _this8.socket.connecting = false;
493
+ _this8.socket.connected = false;
494
+ }
495
+ return reject(err);
496
+ }
497
+
498
+ // For normal connections, mark the socket as connected.
499
+ // Shutdown switchover promotion is handled by the onSuccess callback.
500
+ if (!isShutdownSwitchover && _this8.socket) {
501
+ _this8.socket.connecting = false;
502
+ _this8.socket.connected = true;
503
+ }
504
+ if (!isShutdownSwitchover) {
505
+ _this8.connecting = false;
506
+ _this8.connected = true;
507
+ _this8.hasEverConnected = true;
508
+ _this8.startTokenRefreshTimer();
509
+ _this8.emitEvent('online');
510
+ }
511
+ return resolve();
512
+ };
513
+ // eslint-disable-next-line prefer-reflect
514
+ call = _backoff.default.call(function (callback) {
515
+ var attemptNum = call.getNumRetries();
516
+ var attemptLogPrefix = isShutdownSwitchover ? '[shutdown] switchover' : 'connection';
517
+ _this8.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": executing ").concat(attemptLogPrefix, " attempt ").concat(attemptNum));
518
+ _this8.attemptConnection(webSocketUrl, callback, attemptOptions);
519
+ }, function (err) {
520
+ return onComplete(err);
521
+ });
522
+ call.setStrategy(new _backoff.default.ExponentialStrategy({
523
+ initialDelay: _this8.config.backoffTimeReset,
524
+ maxDelay: _this8.config.backoffTimeMax
525
+ }));
526
+ if (isInitialConnectWithoutRetries) {
527
+ call.retryIf(function () {
528
+ return false;
529
+ });
530
+ } else if (isInitialConnect && initialRetryLimit !== null && initialRetryLimit > 0) {
531
+ call.failAfter(initialRetryLimit);
532
+ } else if (_this8.config.maxRetries) {
533
+ call.failAfter(_this8.config.maxRetries);
534
+ }
535
+
536
+ // Store backoff call reference BEFORE starting (so it's available in attemptConnection)
537
+ if (isShutdownSwitchover) {
538
+ _this8.shutdownSwitchoverBackoffCall = call;
539
+ } else {
540
+ _this8.backoffCall = call;
541
+ }
542
+ call.on('abort', function () {
543
+ var msg = isShutdownSwitchover ? 'Shutdown Switchover' : 'Connection';
544
+ _this8.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": ").concat(msg, " aborted"));
545
+ reject(new Error("MobiusSocket ".concat(msg, " Aborted")));
546
+ });
547
+ call.on('callback', function (err) {
548
+ if (err) {
549
+ if (isInitialConnectWithoutRetries) {
550
+ _this8.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": initial connect failed; retries already disabled"));
551
+ return;
552
+ }
553
+ var number = call.getNumRetries();
554
+ var delay = Math.min(call.strategy_.nextBackoffDelay_, _this8.config.backoffTimeMax || Infinity);
555
+ var callbackLogPrefix = isShutdownSwitchover ? '[shutdown] switchover' : '';
556
+ _this8.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": ").concat(callbackLogPrefix, " failed to connect; attempting retry ").concat(number + 1, " in ").concat(delay, " ms"));
557
+ /* istanbul ignore if */
558
+ if (process.env.NODE_ENV === 'development') {
559
+ _this8.logger.debug("".concat(MOBIUS_SOCKET_NAMESPACE, ": "), err, err.stack);
560
+ }
561
+ return;
562
+ }
563
+ _this8.logger.info("".concat(MOBIUS_SOCKET_NAMESPACE, ": connected"));
564
+ });
565
+ call.start();
566
+ });
567
+ }
568
+
569
+ /**
570
+ * Safely emits an event, catching and logging any errors from event handlers.
571
+ * @param eventName - The name of the event to emit
572
+ * @param args - Arguments to pass to event handlers
573
+ */
574
+ }, {
575
+ key: "emitEvent",
576
+ value: function emitEvent(eventName) {
577
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
578
+ args[_key - 1] = arguments[_key];
579
+ }
580
+ try {
581
+ if (!eventName) {
582
+ return;
583
+ }
584
+ this.emit.apply(this, [eventName].concat(args));
585
+ } catch (error) {
586
+ // Safely handle errors without causing additional issues during cleanup
587
+ this.logger.error("".concat(MOBIUS_SOCKET_NAMESPACE, ": error occurred in event handler:"), error, ' with args: ', [eventName].concat(args));
588
+ }
589
+ }
590
+
591
+ /**
592
+ * Starts a periodic timer to refresh the authentication token.
593
+ * Token refresh occurs every hour while connected.
594
+ */
595
+ }, {
596
+ key: "startTokenRefreshTimer",
597
+ value: function startTokenRefreshTimer() {
598
+ var _this9 = this;
599
+ if (this.tokenRefreshTimer || !this.connected) {
600
+ return;
601
+ }
602
+ this.tokenRefreshTimer = setInterval(function () {
603
+ _this9.refreshToken().catch(function (error) {
604
+ _this9.logger.error("".concat(MOBIUS_SOCKET_NAMESPACE, ": periodic token refresh failed"), error);
605
+ });
606
+ }, TOKEN_REFRESH_INTERVAL_MS);
607
+ }
608
+
609
+ /**
610
+ * Stops the periodic token refresh timer.
611
+ */
612
+ }, {
613
+ key: "stopTokenRefreshTimer",
614
+ value: function stopTokenRefreshTimer() {
615
+ if (!this.tokenRefreshTimer) {
616
+ return;
617
+ }
618
+ clearInterval(this.tokenRefreshTimer);
619
+ this.tokenRefreshTimer = undefined;
620
+ }
621
+
622
+ /**
623
+ * Refreshes the authentication token and re-authenticates the socket connection.
624
+ * @returns Promise that resolves when token refresh and re-authentication complete
625
+ */
626
+ }, {
627
+ key: "refreshToken",
628
+ value: function refreshToken() {
629
+ var _this$webex$credentia,
630
+ _this$webex$credentia2,
631
+ _this$webex$credentia3,
632
+ _this0 = this;
633
+ if (this.tokenRefreshInFlight) {
634
+ return this.tokenRefreshInFlight;
635
+ }
636
+ if (!this.connected) {
637
+ this.stopTokenRefreshTimer();
638
+ return _promise.default.resolve();
639
+ }
640
+ var tokenPromise = this.webex.credentials.canRefresh ? (_this$webex$credentia = (_this$webex$credentia2 = this.webex.credentials).refresh) === null || _this$webex$credentia === void 0 ? void 0 : (_this$webex$credentia3 = _this$webex$credentia.call(_this$webex$credentia2, {
641
+ force: true
642
+ })) === null || _this$webex$credentia3 === void 0 ? void 0 : _this$webex$credentia3.then(function () {
643
+ return _this0.webex.credentials.getUserToken();
644
+ }) : this.webex.credentials.getUserToken();
645
+ this.tokenRefreshInFlight = tokenPromise.then(function (token) {
646
+ var _this0$socket;
647
+ if (!token) {
648
+ throw new Error('Mobius token refresh did not return a token');
649
+ }
650
+ var refreshedToken = normalizeMobiusAuthToken(token.toString());
651
+ if (!((_this0$socket = _this0.socket) !== null && _this0$socket !== void 0 && _this0$socket.connected)) {
652
+ _this0.logger.warn("".concat(MOBIUS_SOCKET_NAMESPACE, ": socket is not connected, skipping token refresh"));
653
+ return undefined;
654
+ }
655
+ return _this0.socket.refresh(refreshedToken);
656
+ }).catch(function (error) {
657
+ _this0.logger.error("".concat(MOBIUS_SOCKET_NAMESPACE, ": failed to refresh/re-auth Mobius socket"), error);
658
+ throw error;
659
+ }).finally(function () {
660
+ _this0.tokenRefreshInFlight = undefined;
661
+ });
662
+ return this.tokenRefreshInFlight;
663
+ }
664
+ }, {
665
+ key: "onclose",
666
+ value: function () {
667
+ var _onclose = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee(event, sourceSocket) {
668
+ var _this1 = this,
669
+ _this$socket4;
670
+ var loggerContext, reason, socketUrl, isActiveSocket, _t, _t2;
671
+ return _regenerator.default.wrap(function (_context) {
672
+ while (1) switch (_context.prev = _context.next) {
673
+ case 0:
674
+ loggerContext = {
675
+ file: 'mobius-socket.ts',
676
+ method: 'onclose'
677
+ };
678
+ _context.prev = 1;
679
+ reason = event.reason && event.reason.toLowerCase();
680
+ isActiveSocket = sourceSocket === this.socket;
681
+ if (sourceSocket) {
682
+ socketUrl = sourceSocket.url;
683
+ }
684
+
685
+ // Only tear down state if the currently active socket closed
686
+ if (isActiveSocket) {
687
+ if (this.socket) {
688
+ this.socket.removeAllListeners();
689
+ this.socket = undefined;
690
+ this.emitEvent('offline', event);
691
+ }
692
+ this.connecting = false;
693
+ this.connected = false;
694
+ this.stopTokenRefreshTimer();
695
+ } else {
696
+ // Old socket closed; do not flip connection state
697
+ this.logger.info("[shutdown] non-active socket closed, code=".concat(event.code), loggerContext);
698
+ // Clean up listeners from old socket now that it's closed
699
+ if (sourceSocket) {
700
+ sourceSocket.removeAllListeners();
701
+ }
702
+ }
703
+ _t = event.code;
704
+ _context.next = _t === 1003 ? 2 : _t === 4000 ? 3 : _t === 4001 ? 4 : _t === 1000 ? 5 : _t === 1001 ? 5 : _t === 1005 ? 6 : _t === 1006 ? 6 : _t === 1011 ? 6 : _t === 1012 ? 6 : _t === 3050 ? 7 : _t === 4401 ? 8 : _t === 4403 ? 8 : _t === 4404 ? 8 : _t === 4429 ? 11 : 12;
705
+ break;
706
+ case 2:
707
+ this.logger.info("service rejected last message; will not reconnect: ".concat(event.reason), loggerContext);
708
+ if (isActiveSocket) this.emitEvent('offline.permanent', event);
709
+ return _context.abrupt("continue", 13);
710
+ case 3:
711
+ this.logger.info("socket replaced; will not reconnect", loggerContext);
712
+ if (isActiveSocket) this.emitEvent('offline.replaced', event);
713
+ return _context.abrupt("continue", 13);
714
+ case 4:
715
+ // Handle the same way we do for registration.down event from Mobius.
716
+ this.logger.info("socket closed with 4001; will not reconnect", loggerContext);
717
+ this.emitEvent('event:async_event', _constants.MOBIUS_SOCKET_4001_EVENT);
718
+ return _context.abrupt("continue", 13);
719
+ case 5:
720
+ this.logger.info("socket disconnected; ".concat(event.reason), loggerContext);
721
+ if (isActiveSocket) this.emitEvent('offline.permanent', event);
722
+ return _context.abrupt("continue", 13);
723
+ case 6:
724
+ this.logger.info("socket disconnected; reconnecting", loggerContext);
725
+ if (isActiveSocket) {
726
+ this.emitEvent('offline.transient', event);
727
+ this.reconnect(socketUrl);
728
+ }
729
+ return _context.abrupt("continue", 13);
730
+ case 7:
731
+ if (reason && normalReconnectReasons.includes(reason)) {
732
+ this.logger.info("socket disconnected; reconnecting", loggerContext);
733
+ if (isActiveSocket) {
734
+ this.emitEvent('offline.transient', event);
735
+ this.reconnect(socketUrl);
736
+ }
737
+ } else {
738
+ this.logger.info("socket disconnected; will not reconnect: ".concat(event.reason), loggerContext);
739
+ if (isActiveSocket) this.emitEvent('offline.permanent', event);
740
+ }
741
+ return _context.abrupt("continue", 13);
742
+ case 8:
743
+ this.logger.error("onclose, statusCode=".concat(event.code), loggerContext);
744
+ _context.next = 9;
745
+ return this.refreshToken().catch(function (error) {
746
+ _this1.logger.error("".concat(MOBIUS_SOCKET_NAMESPACE, ": periodic token refresh failed"), error);
747
+ });
748
+ case 9:
749
+ _context.next = 10;
750
+ return this.reconnect((_this$socket4 = this.socket) === null || _this$socket4 === void 0 ? void 0 : _this$socket4.url);
751
+ case 10:
752
+ return _context.abrupt("continue", 13);
753
+ case 11:
754
+ // Silently ignore too many requests
755
+ this.logger.error("too many requests, statusCode=".concat(event.code), loggerContext);
756
+ return _context.abrupt("continue", 13);
757
+ case 12:
758
+ this.logger.info("socket disconnected unexpectedly; will not reconnect", loggerContext);
759
+ if (isActiveSocket) this.emitEvent('offline.permanent', event);
760
+ case 13:
761
+ _context.next = 15;
762
+ break;
763
+ case 14:
764
+ _context.prev = 14;
765
+ _t2 = _context["catch"](1);
766
+ this.logger.error("error occurred in close handler", _t2, loggerContext);
767
+ case 15:
768
+ case "end":
769
+ return _context.stop();
770
+ }
771
+ }, _callee, this, [[1, 14]]);
772
+ }));
773
+ function onclose(_x, _x2) {
774
+ return _onclose.apply(this, arguments);
775
+ }
776
+ return onclose;
777
+ }()
778
+ }, {
779
+ key: "onmessage",
780
+ value: function onmessage(event) {
781
+ var loggerContext = {
782
+ file: 'mobius-socket.ts',
783
+ method: 'onmessage'
784
+ };
785
+ var envelope = event.data;
786
+ this.logger.debug("message envelope: ", envelope, loggerContext);
787
+
788
+ // Handle shutdown message shape: { type: 'shutdown' }
789
+ if (envelope && envelope.type === 'shutdown') {
790
+ this.logger.info("[shutdown] imminent shutdown message received", loggerContext);
791
+ this.emitEvent('event:mobius_shutdown_imminent', envelope); // This is not yet not implemented, keeping for future support
792
+
793
+ this.handleImminentShutdown();
794
+ return _promise.default.resolve();
795
+ }
796
+ if (this.trackAsyncEventAndShouldSuppressDuplicate(envelope)) {
797
+ return _promise.default.resolve();
798
+ }
799
+
800
+ // Emit event:<type> for typed messages (e.g., register.response)
801
+ if (envelope.type) {
802
+ this.emitEvent("event:".concat(envelope.type), envelope);
803
+ }
804
+
805
+ // Use data/payload if present, otherwise treat the envelope itself as the data (flat format)
806
+ var data = envelope.data || envelope;
807
+
808
+ // Support both Mobius-enveloped (data.eventType) and flat (eventType) formats
809
+ var eventType = (data === null || data === void 0 ? void 0 : data.eventType) || envelope.eventType;
810
+ if (!eventType) {
811
+ this.emitEvent('event', envelope);
812
+ return _promise.default.resolve();
813
+ }
814
+ try {
815
+ // TODO: Remove if event:namespace is not required
816
+ this.emitEvent('event', envelope);
817
+ var _eventType$split = eventType.split('.'),
818
+ _eventType$split2 = (0, _slicedToArray2.default)(_eventType$split, 1),
819
+ namespace = _eventType$split2[0];
820
+ this.emitEvent("event:".concat(namespace), envelope);
821
+ if (namespace !== eventType) {
822
+ this.emitEvent("event:".concat(eventType), envelope);
823
+ }
824
+ } catch (reason) {
825
+ this.logger.error("error occurred processing socket message", reason, loggerContext);
826
+ }
827
+ return _promise.default.resolve();
828
+ }
829
+ }, {
830
+ key: "reconnect",
831
+ value: function reconnect(webSocketUrl) {
832
+ this.logger.info("reconnecting", {
833
+ file: 'mobius-socket.ts',
834
+ method: 'reconnect'
835
+ });
836
+ return this.connect(webSocketUrl || this.socketUrl);
837
+ }
838
+ }]);
839
+ }(_events.EventEmitter);
840
+ var _default = exports.default = MobiusSocket;
841
+ //# sourceMappingURL=mobius-socket.js.map