@siebly/kraken-api 0.0.9

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/LICENSE.md +7 -0
  2. package/README.md +624 -0
  3. package/dist/cjs/DerivativesClient.d.ts +657 -0
  4. package/dist/cjs/DerivativesClient.js +726 -0
  5. package/dist/cjs/DerivativesClient.js.map +1 -0
  6. package/dist/cjs/InstitutionalClient.d.ts +183 -0
  7. package/dist/cjs/InstitutionalClient.js +266 -0
  8. package/dist/cjs/InstitutionalClient.js.map +1 -0
  9. package/dist/cjs/PartnerClient.d.ts +257 -0
  10. package/dist/cjs/PartnerClient.js +344 -0
  11. package/dist/cjs/PartnerClient.js.map +1 -0
  12. package/dist/cjs/SpotClient.d.ts +547 -0
  13. package/dist/cjs/SpotClient.js +607 -0
  14. package/dist/cjs/SpotClient.js.map +1 -0
  15. package/dist/cjs/WebsocketAPIClient.d.ts +95 -0
  16. package/dist/cjs/WebsocketAPIClient.js +136 -0
  17. package/dist/cjs/WebsocketAPIClient.js.map +1 -0
  18. package/dist/cjs/WebsocketClient.d.ts +120 -0
  19. package/dist/cjs/WebsocketClient.js +669 -0
  20. package/dist/cjs/WebsocketClient.js.map +1 -0
  21. package/dist/cjs/index.d.ts +24 -0
  22. package/dist/cjs/index.js +41 -0
  23. package/dist/cjs/index.js.map +1 -0
  24. package/dist/cjs/lib/BaseRestClient.d.ts +66 -0
  25. package/dist/cjs/lib/BaseRestClient.js +548 -0
  26. package/dist/cjs/lib/BaseRestClient.js.map +1 -0
  27. package/dist/cjs/lib/BaseWSClient.d.ts +230 -0
  28. package/dist/cjs/lib/BaseWSClient.js +935 -0
  29. package/dist/cjs/lib/BaseWSClient.js.map +1 -0
  30. package/dist/cjs/lib/misc-util.d.ts +1 -0
  31. package/dist/cjs/lib/misc-util.js +7 -0
  32. package/dist/cjs/lib/misc-util.js.map +1 -0
  33. package/dist/cjs/lib/requestUtils.d.ts +68 -0
  34. package/dist/cjs/lib/requestUtils.js +82 -0
  35. package/dist/cjs/lib/requestUtils.js.map +1 -0
  36. package/dist/cjs/lib/webCryptoAPI.d.ts +15 -0
  37. package/dist/cjs/lib/webCryptoAPI.js +85 -0
  38. package/dist/cjs/lib/webCryptoAPI.js.map +1 -0
  39. package/dist/cjs/lib/websocket/WsStore.d.ts +75 -0
  40. package/dist/cjs/lib/websocket/WsStore.js +303 -0
  41. package/dist/cjs/lib/websocket/WsStore.js.map +1 -0
  42. package/dist/cjs/lib/websocket/WsStore.types.d.ts +51 -0
  43. package/dist/cjs/lib/websocket/WsStore.types.js +14 -0
  44. package/dist/cjs/lib/websocket/WsStore.types.js.map +1 -0
  45. package/dist/cjs/lib/websocket/logger.d.ts +7 -0
  46. package/dist/cjs/lib/websocket/logger.js +16 -0
  47. package/dist/cjs/lib/websocket/logger.js.map +1 -0
  48. package/dist/cjs/lib/websocket/rest-client-cache.d.ts +22 -0
  49. package/dist/cjs/lib/websocket/rest-client-cache.js +66 -0
  50. package/dist/cjs/lib/websocket/rest-client-cache.js.map +1 -0
  51. package/dist/cjs/lib/websocket/websocket-util.d.ts +76 -0
  52. package/dist/cjs/lib/websocket/websocket-util.js +59 -0
  53. package/dist/cjs/lib/websocket/websocket-util.js.map +1 -0
  54. package/dist/cjs/package.json +3 -0
  55. package/dist/cjs/types/request/derivatives.types.d.ts +186 -0
  56. package/dist/cjs/types/request/derivatives.types.js +6 -0
  57. package/dist/cjs/types/request/derivatives.types.js.map +1 -0
  58. package/dist/cjs/types/request/institutional.types.d.ts +313 -0
  59. package/dist/cjs/types/request/institutional.types.js +4 -0
  60. package/dist/cjs/types/request/institutional.types.js.map +1 -0
  61. package/dist/cjs/types/request/partner.types.d.ts +291 -0
  62. package/dist/cjs/types/request/partner.types.js +4 -0
  63. package/dist/cjs/types/request/partner.types.js.map +1 -0
  64. package/dist/cjs/types/request/spot.types.d.ts +324 -0
  65. package/dist/cjs/types/request/spot.types.js +6 -0
  66. package/dist/cjs/types/request/spot.types.js.map +1 -0
  67. package/dist/cjs/types/request/wsapi.types.d.ts +90 -0
  68. package/dist/cjs/types/request/wsapi.types.js +6 -0
  69. package/dist/cjs/types/request/wsapi.types.js.map +1 -0
  70. package/dist/cjs/types/response/derivatives.types.d.ts +712 -0
  71. package/dist/cjs/types/response/derivatives.types.js +6 -0
  72. package/dist/cjs/types/response/derivatives.types.js.map +1 -0
  73. package/dist/cjs/types/response/institutional.types.d.ts +318 -0
  74. package/dist/cjs/types/response/institutional.types.js +4 -0
  75. package/dist/cjs/types/response/institutional.types.js.map +1 -0
  76. package/dist/cjs/types/response/partner.types.d.ts +332 -0
  77. package/dist/cjs/types/response/partner.types.js +4 -0
  78. package/dist/cjs/types/response/partner.types.js.map +1 -0
  79. package/dist/cjs/types/response/shared.types.d.ts +27 -0
  80. package/dist/cjs/types/response/shared.types.js +3 -0
  81. package/dist/cjs/types/response/shared.types.js.map +1 -0
  82. package/dist/cjs/types/response/spot.types.d.ts +590 -0
  83. package/dist/cjs/types/response/spot.types.js +6 -0
  84. package/dist/cjs/types/response/spot.types.js.map +1 -0
  85. package/dist/cjs/types/response/ws.d.ts +11 -0
  86. package/dist/cjs/types/response/ws.js +3 -0
  87. package/dist/cjs/types/response/ws.js.map +1 -0
  88. package/dist/cjs/types/response/wsapi.types.d.ts +44 -0
  89. package/dist/cjs/types/response/wsapi.types.js +6 -0
  90. package/dist/cjs/types/response/wsapi.types.js.map +1 -0
  91. package/dist/cjs/types/websockets/ws-api.d.ts +71 -0
  92. package/dist/cjs/types/websockets/ws-api.js +18 -0
  93. package/dist/cjs/types/websockets/ws-api.js.map +1 -0
  94. package/dist/cjs/types/websockets/ws-events.d.ts +11 -0
  95. package/dist/cjs/types/websockets/ws-events.js +11 -0
  96. package/dist/cjs/types/websockets/ws-events.js.map +1 -0
  97. package/dist/cjs/types/websockets/ws-general.d.ts +67 -0
  98. package/dist/cjs/types/websockets/ws-general.js +3 -0
  99. package/dist/cjs/types/websockets/ws-general.js.map +1 -0
  100. package/dist/cjs/types/websockets/ws-subscriptions.d.ts +11 -0
  101. package/dist/cjs/types/websockets/ws-subscriptions.js +31 -0
  102. package/dist/cjs/types/websockets/ws-subscriptions.js.map +1 -0
  103. package/dist/mjs/DerivativesClient.d.ts +657 -0
  104. package/dist/mjs/DerivativesClient.js +722 -0
  105. package/dist/mjs/DerivativesClient.js.map +1 -0
  106. package/dist/mjs/InstitutionalClient.d.ts +183 -0
  107. package/dist/mjs/InstitutionalClient.js +262 -0
  108. package/dist/mjs/InstitutionalClient.js.map +1 -0
  109. package/dist/mjs/PartnerClient.d.ts +257 -0
  110. package/dist/mjs/PartnerClient.js +340 -0
  111. package/dist/mjs/PartnerClient.js.map +1 -0
  112. package/dist/mjs/SpotClient.d.ts +547 -0
  113. package/dist/mjs/SpotClient.js +603 -0
  114. package/dist/mjs/SpotClient.js.map +1 -0
  115. package/dist/mjs/WebsocketAPIClient.d.ts +95 -0
  116. package/dist/mjs/WebsocketAPIClient.js +132 -0
  117. package/dist/mjs/WebsocketAPIClient.js.map +1 -0
  118. package/dist/mjs/WebsocketClient.d.ts +120 -0
  119. package/dist/mjs/WebsocketClient.js +665 -0
  120. package/dist/mjs/WebsocketClient.js.map +1 -0
  121. package/dist/mjs/index.d.ts +24 -0
  122. package/dist/mjs/index.js +25 -0
  123. package/dist/mjs/index.js.map +1 -0
  124. package/dist/mjs/lib/BaseRestClient.d.ts +66 -0
  125. package/dist/mjs/lib/BaseRestClient.js +541 -0
  126. package/dist/mjs/lib/BaseRestClient.js.map +1 -0
  127. package/dist/mjs/lib/BaseWSClient.d.ts +230 -0
  128. package/dist/mjs/lib/BaseWSClient.js +928 -0
  129. package/dist/mjs/lib/BaseWSClient.js.map +1 -0
  130. package/dist/mjs/lib/misc-util.d.ts +1 -0
  131. package/dist/mjs/lib/misc-util.js +4 -0
  132. package/dist/mjs/lib/misc-util.js.map +1 -0
  133. package/dist/mjs/lib/requestUtils.d.ts +68 -0
  134. package/dist/mjs/lib/requestUtils.js +76 -0
  135. package/dist/mjs/lib/requestUtils.js.map +1 -0
  136. package/dist/mjs/lib/webCryptoAPI.d.ts +15 -0
  137. package/dist/mjs/lib/webCryptoAPI.js +80 -0
  138. package/dist/mjs/lib/webCryptoAPI.js.map +1 -0
  139. package/dist/mjs/lib/websocket/WsStore.d.ts +75 -0
  140. package/dist/mjs/lib/websocket/WsStore.js +298 -0
  141. package/dist/mjs/lib/websocket/WsStore.js.map +1 -0
  142. package/dist/mjs/lib/websocket/WsStore.types.d.ts +51 -0
  143. package/dist/mjs/lib/websocket/WsStore.types.js +11 -0
  144. package/dist/mjs/lib/websocket/WsStore.types.js.map +1 -0
  145. package/dist/mjs/lib/websocket/logger.d.ts +7 -0
  146. package/dist/mjs/lib/websocket/logger.js +13 -0
  147. package/dist/mjs/lib/websocket/logger.js.map +1 -0
  148. package/dist/mjs/lib/websocket/rest-client-cache.d.ts +22 -0
  149. package/dist/mjs/lib/websocket/rest-client-cache.js +62 -0
  150. package/dist/mjs/lib/websocket/rest-client-cache.js.map +1 -0
  151. package/dist/mjs/lib/websocket/websocket-util.d.ts +76 -0
  152. package/dist/mjs/lib/websocket/websocket-util.js +54 -0
  153. package/dist/mjs/lib/websocket/websocket-util.js.map +1 -0
  154. package/dist/mjs/package.json +3 -0
  155. package/dist/mjs/types/request/derivatives.types.d.ts +186 -0
  156. package/dist/mjs/types/request/derivatives.types.js +5 -0
  157. package/dist/mjs/types/request/derivatives.types.js.map +1 -0
  158. package/dist/mjs/types/request/institutional.types.d.ts +313 -0
  159. package/dist/mjs/types/request/institutional.types.js +3 -0
  160. package/dist/mjs/types/request/institutional.types.js.map +1 -0
  161. package/dist/mjs/types/request/partner.types.d.ts +291 -0
  162. package/dist/mjs/types/request/partner.types.js +3 -0
  163. package/dist/mjs/types/request/partner.types.js.map +1 -0
  164. package/dist/mjs/types/request/spot.types.d.ts +324 -0
  165. package/dist/mjs/types/request/spot.types.js +5 -0
  166. package/dist/mjs/types/request/spot.types.js.map +1 -0
  167. package/dist/mjs/types/request/wsapi.types.d.ts +90 -0
  168. package/dist/mjs/types/request/wsapi.types.js +5 -0
  169. package/dist/mjs/types/request/wsapi.types.js.map +1 -0
  170. package/dist/mjs/types/response/derivatives.types.d.ts +712 -0
  171. package/dist/mjs/types/response/derivatives.types.js +5 -0
  172. package/dist/mjs/types/response/derivatives.types.js.map +1 -0
  173. package/dist/mjs/types/response/institutional.types.d.ts +318 -0
  174. package/dist/mjs/types/response/institutional.types.js +3 -0
  175. package/dist/mjs/types/response/institutional.types.js.map +1 -0
  176. package/dist/mjs/types/response/partner.types.d.ts +332 -0
  177. package/dist/mjs/types/response/partner.types.js +3 -0
  178. package/dist/mjs/types/response/partner.types.js.map +1 -0
  179. package/dist/mjs/types/response/shared.types.d.ts +27 -0
  180. package/dist/mjs/types/response/shared.types.js +2 -0
  181. package/dist/mjs/types/response/shared.types.js.map +1 -0
  182. package/dist/mjs/types/response/spot.types.d.ts +590 -0
  183. package/dist/mjs/types/response/spot.types.js +5 -0
  184. package/dist/mjs/types/response/spot.types.js.map +1 -0
  185. package/dist/mjs/types/response/ws.d.ts +11 -0
  186. package/dist/mjs/types/response/ws.js +2 -0
  187. package/dist/mjs/types/response/ws.js.map +1 -0
  188. package/dist/mjs/types/response/wsapi.types.d.ts +44 -0
  189. package/dist/mjs/types/response/wsapi.types.js +5 -0
  190. package/dist/mjs/types/response/wsapi.types.js.map +1 -0
  191. package/dist/mjs/types/websockets/ws-api.d.ts +71 -0
  192. package/dist/mjs/types/websockets/ws-api.js +15 -0
  193. package/dist/mjs/types/websockets/ws-api.js.map +1 -0
  194. package/dist/mjs/types/websockets/ws-events.d.ts +11 -0
  195. package/dist/mjs/types/websockets/ws-events.js +8 -0
  196. package/dist/mjs/types/websockets/ws-events.js.map +1 -0
  197. package/dist/mjs/types/websockets/ws-general.d.ts +67 -0
  198. package/dist/mjs/types/websockets/ws-general.js +2 -0
  199. package/dist/mjs/types/websockets/ws-general.js.map +1 -0
  200. package/dist/mjs/types/websockets/ws-subscriptions.d.ts +11 -0
  201. package/dist/mjs/types/websockets/ws-subscriptions.js +28 -0
  202. package/dist/mjs/types/websockets/ws-subscriptions.js.map +1 -0
  203. package/llms.txt +10925 -0
  204. package/package.json +89 -0
@@ -0,0 +1,935 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.BaseWebsocketClient = void 0;
7
+ const events_1 = require("events");
8
+ const isomorphic_ws_1 = __importDefault(require("isomorphic-ws"));
9
+ const ws_events_js_1 = require("../types/websockets/ws-events.js");
10
+ const webCryptoAPI_js_1 = require("./webCryptoAPI.js");
11
+ const logger_js_1 = require("./websocket/logger.js");
12
+ const websocket_util_js_1 = require("./websocket/websocket-util.js");
13
+ const WsStore_js_1 = require("./websocket/WsStore.js");
14
+ const WsStore_types_js_1 = require("./websocket/WsStore.types.js");
15
+ /**
16
+ * Appends wsKey and isWSAPIResponse to all events.
17
+ * Some events are arrays, this handles that nested scenario too.
18
+ */
19
+ function getFinalEmittable(emittable, wsKey, isWSAPIResponse) {
20
+ if (Array.isArray(emittable)) {
21
+ return emittable.map((subEvent) => getFinalEmittable(subEvent, wsKey, isWSAPIResponse));
22
+ }
23
+ if (Array.isArray(emittable.event)) {
24
+ // Some topics just emit an array.
25
+ // This is consistent with how it was before the WS API upgrade:
26
+ return emittable.event.map((subEvent) => getFinalEmittable(subEvent, wsKey, isWSAPIResponse));
27
+ // const { event, ...others } = emittable;
28
+ // return {
29
+ // ...others,
30
+ // event: event.map((subEvent) =>
31
+ // getFinalEmittable(subEvent, wsKey, isWSAPIResponse),
32
+ // ),
33
+ // };
34
+ }
35
+ if (emittable.event) {
36
+ return {
37
+ ...emittable.event,
38
+ wsKey: wsKey,
39
+ isWSAPIResponse: !!isWSAPIResponse,
40
+ };
41
+ }
42
+ return {
43
+ ...emittable,
44
+ wsKey: wsKey,
45
+ isWSAPIResponse: !!isWSAPIResponse,
46
+ };
47
+ }
48
+ /**
49
+ * Users can conveniently pass topics as strings or objects (object has topic name + optional params).
50
+ *
51
+ * This method normalises topics into objects (object has topic name + optional params).
52
+ */
53
+ function getNormalisedTopicRequests(wsTopicRequests) {
54
+ const normalisedTopicRequests = [];
55
+ for (const wsTopicRequest of wsTopicRequests) {
56
+ // passed as string, convert to object
57
+ if (typeof wsTopicRequest === 'string') {
58
+ const topicRequest = {
59
+ topic: wsTopicRequest,
60
+ payload: undefined,
61
+ };
62
+ normalisedTopicRequests.push(topicRequest);
63
+ continue;
64
+ }
65
+ // already a normalised object, thanks to user
66
+ normalisedTopicRequests.push(wsTopicRequest);
67
+ }
68
+ return normalisedTopicRequests;
69
+ }
70
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
71
+ class BaseWebsocketClient extends events_1.EventEmitter {
72
+ wsStore;
73
+ logger;
74
+ options;
75
+ wsApiRequestId = 0;
76
+ timeOffsetMs = 0;
77
+ WS_LOGGER_CATEGORY;
78
+ constructor(options, logger) {
79
+ super();
80
+ this.logger = logger || logger_js_1.DefaultLogger;
81
+ this.WS_LOGGER_CATEGORY = {
82
+ category: options?.wsLoggerCategory || 'WsClient',
83
+ };
84
+ this.wsStore = new WsStore_js_1.WsStore(this.logger);
85
+ this.options = {
86
+ pongTimeout: 5000,
87
+ pingInterval: 10000,
88
+ reconnectTimeout: 500,
89
+ recvWindow: 5000,
90
+ // Requires a confirmation "response" from the ws connection before assuming it is ready
91
+ requireConnectionReadyConfirmation: false,
92
+ // Automatically auth after opening a connection?
93
+ authPrivateConnectionsOnConnect: false,
94
+ // Automatically include auth/sign/token with every WS request.
95
+ // Automatically handled during getWsRequestEvents.
96
+ authPrivateRequests: true,
97
+ // Automatically re-auth WS API, if we were auth'd before and get reconnected
98
+ reauthWSAPIOnReconnect: true,
99
+ // Whether to use native heartbeats (depends on the exchange)
100
+ useNativeHeartbeats: true,
101
+ ...options,
102
+ };
103
+ // Check Web Crypto API support when credentials are provided and no custom sign function is used
104
+ if (this.options.apiKey &&
105
+ this.options.apiSecret &&
106
+ !this.options.customSignMessageFn) {
107
+ (0, webCryptoAPI_js_1.checkWebCryptoAPISupported)();
108
+ }
109
+ }
110
+ isPrivateWsKey(wsKey) {
111
+ return this.getPrivateWSKeys().includes(wsKey);
112
+ }
113
+ /** Returns auto-incrementing request ID, used to track promise references for async requests */
114
+ getNewRequestId() {
115
+ return ++this.wsApiRequestId;
116
+ }
117
+ getTimeOffsetMs() {
118
+ return this.timeOffsetMs;
119
+ }
120
+ setTimeOffsetMs(newOffset) {
121
+ this.timeOffsetMs = newOffset;
122
+ }
123
+ /**
124
+ * Don't call directly! Use subscribe() instead!
125
+ *
126
+ * Subscribe to one or more topics on a WS connection (identified by WS Key).
127
+ *
128
+ * - Topics are automatically cached
129
+ * - Connections are automatically opened, if not yet connected
130
+ * - Authentication is automatically handled
131
+ * - Topics are automatically resubscribed to, if something happens to the connection, unless you call unsubsribeTopicsForWsKey(topics, key).
132
+ *
133
+ * @param wsTopicRequests array of topics to subscribe to
134
+ * @param wsKey ws key referring to the ws connection these topics should be subscribed on
135
+ */
136
+ async subscribeTopicsForWsKey(wsTopicRequests, wsKey) {
137
+ const normalisedTopicRequests = getNormalisedTopicRequests(wsTopicRequests);
138
+ // Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically
139
+ for (const topic of normalisedTopicRequests) {
140
+ this.wsStore.addTopic(wsKey, topic);
141
+ }
142
+ const isConnected = this.wsStore.isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTED);
143
+ const isConnectionInProgress = this.wsStore.isConnectionAttemptInProgress(wsKey);
144
+ // start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect
145
+ if (!isConnected && !isConnectionInProgress) {
146
+ return this.connect(wsKey);
147
+ }
148
+ // Subscribe should happen automatically once connected, nothing to do here after topics are added to wsStore.
149
+ if (!isConnected) {
150
+ /**
151
+ * Are we in the process of connection? Nothing to send yet.
152
+ */
153
+ this.logger.trace('WS not connected - requests queued for retry once connected.', {
154
+ ...this.WS_LOGGER_CATEGORY,
155
+ wsKey,
156
+ wsTopicRequests,
157
+ });
158
+ return isConnectionInProgress;
159
+ }
160
+ // We're connected. Check if auth is needed and if already authenticated
161
+ const isPrivateConnection = this.isPrivateWsKey(wsKey);
162
+ const isAuthenticated = this.wsStore.get(wsKey)?.isAuthenticated;
163
+ if (isPrivateConnection && !isAuthenticated) {
164
+ /**
165
+ * If not authenticated yet and auth is required, don't request topics yet.
166
+ *
167
+ * Auth should already automatically be in progress, so no action needed from here. Topics will automatically subscribe post-auth success.
168
+ */
169
+ this.logger.trace('WS connected but not authenticated yet - awaiting auth before subscribing');
170
+ return false;
171
+ }
172
+ // Finally, request subscription to topics if the connection is healthy and ready
173
+ return this.requestSubscribeTopics(wsKey, normalisedTopicRequests);
174
+ }
175
+ async unsubscribeTopicsForWsKey(wsTopicRequests, wsKey) {
176
+ const normalisedTopicRequests = getNormalisedTopicRequests(wsTopicRequests);
177
+ // Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically
178
+ for (const topic of normalisedTopicRequests) {
179
+ this.wsStore.deleteTopic(wsKey, topic);
180
+ }
181
+ const isConnected = this.wsStore.isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTED);
182
+ // If not connected, don't need to do anything.
183
+ // Removing the topic from the store is enough to stop it from being resubscribed to on reconnect.
184
+ if (!isConnected) {
185
+ return;
186
+ }
187
+ // We're connected. Check if auth is needed and if already authenticated
188
+ const isPrivateConnection = this.isPrivateWsKey(wsKey);
189
+ const isAuthenticated = this.wsStore.get(wsKey)?.isAuthenticated;
190
+ if (isPrivateConnection && !isAuthenticated) {
191
+ /**
192
+ * If not authenticated yet and auth is required, don't need to do anything.
193
+ * We don't subscribe to topics until auth is complete anyway.
194
+ */
195
+ return;
196
+ }
197
+ // Finally, request subscription to topics if the connection is healthy and ready
198
+ return this.requestUnsubscribeTopics(wsKey, normalisedTopicRequests);
199
+ }
200
+ /**
201
+ * Splits topic requests into two groups, public & private topic requests
202
+ */
203
+ sortTopicRequestsIntoPublicPrivate(wsTopicRequests, wsKey) {
204
+ const publicTopicRequests = [];
205
+ const privateTopicRequests = [];
206
+ for (const topic of wsTopicRequests) {
207
+ if (this.isPrivateTopicRequest(topic, wsKey)) {
208
+ privateTopicRequests.push(topic);
209
+ }
210
+ else {
211
+ publicTopicRequests.push(topic);
212
+ }
213
+ }
214
+ return {
215
+ publicReqs: publicTopicRequests,
216
+ privateReqs: privateTopicRequests,
217
+ };
218
+ }
219
+ /** Get the WsStore that tracks websockets & topics */
220
+ getWsStore() {
221
+ return this.wsStore;
222
+ }
223
+ close(wsKey, force) {
224
+ this.logger.info('Closing connection', {
225
+ ...this.WS_LOGGER_CATEGORY,
226
+ wsKey,
227
+ });
228
+ this.setWsState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CLOSING);
229
+ this.clearTimers(wsKey);
230
+ const ws = this.getWs(wsKey);
231
+ ws?.close();
232
+ if (force) {
233
+ (0, websocket_util_js_1.safeTerminateWs)(ws, false);
234
+ }
235
+ }
236
+ closeAll(force) {
237
+ const keys = this.wsStore.getKeys();
238
+ this.logger.info(`Closing all ws connections: ${keys}`);
239
+ keys.forEach((key) => {
240
+ this.close(key, force);
241
+ });
242
+ }
243
+ isConnected(wsKey) {
244
+ return this.wsStore.isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTED);
245
+ }
246
+ /**
247
+ * Request connection to a specific websocket, instead of waiting for automatic connection.
248
+ */
249
+ async connect(wsKey, customUrl, throwOnError) {
250
+ try {
251
+ if (this.wsStore.isWsOpen(wsKey)) {
252
+ this.logger.error('Refused to connect to ws with existing active connection', { ...this.WS_LOGGER_CATEGORY, wsKey });
253
+ return { wsKey, ws: this.wsStore.getWs(wsKey) };
254
+ }
255
+ if (
256
+ // Important: don't check for RECONNECTING here, or this clashes with reconnectWithDelay()!
257
+ this.wsStore.isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTING)) {
258
+ this.logger.error('Refused to connect to ws, connection attempt already active', { ...this.WS_LOGGER_CATEGORY, wsKey });
259
+ return this.wsStore.getConnectionInProgressPromise(wsKey)?.promise;
260
+ }
261
+ if (!this.wsStore.getConnectionState(wsKey) ||
262
+ this.wsStore.isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.INITIAL)) {
263
+ this.setWsState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTING);
264
+ }
265
+ if (!this.wsStore.getConnectionInProgressPromise(wsKey)) {
266
+ this.wsStore.createConnectionInProgressPromise(wsKey, false);
267
+ }
268
+ try {
269
+ const url = customUrl || (await this.getWsUrl(wsKey));
270
+ const ws = this.connectToWsUrl(url, wsKey);
271
+ this.wsStore.setWs(wsKey, ws);
272
+ }
273
+ catch (e) {
274
+ this.logger.error('Exception fetching WS URL', e);
275
+ throw e;
276
+ }
277
+ }
278
+ catch (err) {
279
+ const canRetry = this.parseWsError('Connection failed', err, wsKey);
280
+ if (canRetry) {
281
+ this.reconnectWithDelay(wsKey, this.options.reconnectTimeout);
282
+ }
283
+ else {
284
+ this.logger.info('Preventing retry due to error type to prevent deadlock');
285
+ }
286
+ if (throwOnError) {
287
+ throw err;
288
+ }
289
+ }
290
+ return this.wsStore.getConnectionInProgressPromise(wsKey)?.promise;
291
+ }
292
+ connectToWsUrl(url, wsKey) {
293
+ this.logger.trace(`Opening WS connection to URL: ${url}`, {
294
+ ...this.WS_LOGGER_CATEGORY,
295
+ wsKey,
296
+ });
297
+ const { protocols = [], ...wsOptions } = this.options.wsOptions || {};
298
+ const ws = new isomorphic_ws_1.default(url, protocols, wsOptions);
299
+ ws.onopen = (event) => this.onWsOpen(event, wsKey, url, ws);
300
+ ws.onmessage = (event) => this.onWsMessage(event, wsKey, ws);
301
+ ws.onerror = (event) => this.parseWsError('WebSocket onWsError', event, wsKey);
302
+ ws.onclose = (event) => this.onWsClose(event, wsKey);
303
+ //
304
+ if (this.options.useNativeHeartbeats) {
305
+ if (typeof ws.on === 'function') {
306
+ ws.on('ping', (event) => this.onWsPing(event, wsKey, ws, 'frame'));
307
+ ws.on('pong', (event) => this.onWsPong(event, wsKey, 'frame'));
308
+ }
309
+ }
310
+ ws.wsKey = wsKey;
311
+ return ws;
312
+ }
313
+ parseWsError(context, error, wsKey) {
314
+ if (this.wsStore.isConnectionAttemptInProgress(wsKey)) {
315
+ this.setWsState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.ERROR);
316
+ }
317
+ // Allow retry by default (in some places that call this). Prevent deadloop in hard failure (401)
318
+ let canRetry = true;
319
+ if (!error.message) {
320
+ this.logger.error(`${context} due to unexpected error: `, error);
321
+ this.emit('response', { ...error, wsKey });
322
+ this.emit('exception', { ...error, wsKey });
323
+ return canRetry;
324
+ }
325
+ switch (error.message) {
326
+ case 'Unexpected server response: 401':
327
+ this.logger.error(`${context} due to 401 authorization failure.`, {
328
+ ...this.WS_LOGGER_CATEGORY,
329
+ wsKey,
330
+ });
331
+ canRetry = false;
332
+ break;
333
+ default:
334
+ if (error?.code === 'ENOTFOUND') {
335
+ this.logger.error(`${context} due to lookup exception: "${error?.msg || error?.message || error}"`, {
336
+ ...this.WS_LOGGER_CATEGORY,
337
+ wsKey,
338
+ error,
339
+ connectionState: this.wsStore.getConnectionState(wsKey),
340
+ });
341
+ canRetry = true;
342
+ break;
343
+ }
344
+ if (error?.code === 401) {
345
+ this.logger.error(`${context} due to 401 authorization failure.`, {
346
+ ...this.WS_LOGGER_CATEGORY,
347
+ wsKey,
348
+ });
349
+ canRetry = false;
350
+ break;
351
+ }
352
+ if (this.wsStore.getConnectionState(wsKey) !==
353
+ WsStore_types_js_1.WsConnectionStateEnum.CLOSING) {
354
+ this.logger.error(`${context} due to unexpected response error: "${error?.msg || error?.message || error}"`, { ...this.WS_LOGGER_CATEGORY, wsKey, error });
355
+ canRetry = true;
356
+ }
357
+ else {
358
+ this.logger.info(`${wsKey} socket forcefully closed. Will not reconnect.`);
359
+ }
360
+ break;
361
+ }
362
+ this.emit('response', { ...error, wsKey });
363
+ this.emit('exception', { ...error, wsKey });
364
+ return canRetry;
365
+ }
366
+ /** Get a signature, build the auth request and send it */
367
+ async sendAuthRequest(wsKey, eventToAuth) {
368
+ try {
369
+ this.logger.trace('Sending auth request...', {
370
+ ...this.WS_LOGGER_CATEGORY,
371
+ wsKey,
372
+ eventToAuth,
373
+ });
374
+ await this.assertIsConnected(wsKey);
375
+ // If not required, this won't return anything
376
+ const request = await this.getWsAuthRequestEvent(wsKey, eventToAuth);
377
+ if (!request) {
378
+ // Short-circuit this for the next time it's called
379
+ const wsState = this.wsStore.get(wsKey, true);
380
+ wsState.isAuthenticated = true;
381
+ return;
382
+ }
383
+ if (!this.wsStore.getAuthenticationInProgressPromise(wsKey)) {
384
+ this.wsStore.createAuthenticationInProgressPromise(wsKey, false);
385
+ }
386
+ if (request === 'waitForEvent') {
387
+ return this.wsStore.getAuthenticationInProgressPromise(wsKey)?.promise;
388
+ }
389
+ this.tryWsSend(wsKey, typeof request === 'string' ? request : JSON.stringify(request));
390
+ return this.wsStore.getAuthenticationInProgressPromise(wsKey)?.promise;
391
+ }
392
+ catch (e) {
393
+ this.logger.trace(e, { ...this.WS_LOGGER_CATEGORY, wsKey });
394
+ }
395
+ }
396
+ reconnectWithDelay(wsKey, connectionDelayMs) {
397
+ this.clearTimers(wsKey);
398
+ if (!this.wsStore.isConnectionAttemptInProgress(wsKey)) {
399
+ this.setWsState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.RECONNECTING);
400
+ }
401
+ this.logger.info('Reconnecting to websocket with delay...', {
402
+ ...this.WS_LOGGER_CATEGORY,
403
+ wsKey,
404
+ connectionDelayMs,
405
+ });
406
+ if (this.wsStore.get(wsKey)?.activeReconnectTimer) {
407
+ this.clearReconnectTimer(wsKey);
408
+ }
409
+ this.wsStore.get(wsKey, true).activeReconnectTimer = setTimeout(() => {
410
+ this.clearReconnectTimer(wsKey);
411
+ // Some streams need a specialist reconnection workflow.
412
+ // E.g. the user data stream can't just be reconnected as is.
413
+ if (this.isCustomReconnectionNeeded(wsKey)) {
414
+ this.wsStore.delete(wsKey);
415
+ return this.triggerCustomReconnectionWorkflow(wsKey);
416
+ }
417
+ this.logger.info('Reconnecting to websocket', {
418
+ ...this.WS_LOGGER_CATEGORY,
419
+ wsKey,
420
+ });
421
+ this.connect(wsKey);
422
+ }, connectionDelayMs);
423
+ }
424
+ ping(wsKey) {
425
+ if (this.wsStore.get(wsKey, true).activePongTimer) {
426
+ return;
427
+ }
428
+ this.clearPongTimer(wsKey);
429
+ this.logger.trace('Sending ping', { ...this.WS_LOGGER_CATEGORY, wsKey });
430
+ const ws = this.wsStore.get(wsKey, true).ws;
431
+ if (!ws) {
432
+ this.logger.error(`Unable to send ping for wsKey "${wsKey}" - no connection found`);
433
+ return;
434
+ }
435
+ this.sendPingEvent(wsKey, ws);
436
+ this.wsStore.get(wsKey, true).activePongTimer = setTimeout(() => this.executeReconnectableClose(wsKey, 'Pong timeout'), this.options.pongTimeout);
437
+ }
438
+ /**
439
+ * Closes a connection, if it's even open. If open, this will trigger a reconnect asynchronously.
440
+ * If closed, trigger a reconnect immediately
441
+ */
442
+ executeReconnectableClose(wsKey, reason) {
443
+ this.logger.info(`${reason} - closing socket to reconnect`, {
444
+ ...this.WS_LOGGER_CATEGORY,
445
+ wsKey,
446
+ reason,
447
+ });
448
+ const wasOpen = this.wsStore.isWsOpen(wsKey);
449
+ this.clearPingTimer(wsKey);
450
+ this.clearPongTimer(wsKey);
451
+ const ws = this.getWs(wsKey);
452
+ if (ws) {
453
+ ws.close();
454
+ (0, websocket_util_js_1.safeTerminateWs)(ws, false);
455
+ }
456
+ if (!wasOpen) {
457
+ this.logger.info(`${reason} - socket already closed - trigger immediate reconnect`, {
458
+ ...this.WS_LOGGER_CATEGORY,
459
+ wsKey,
460
+ reason,
461
+ });
462
+ this.reconnectWithDelay(wsKey, this.options.reconnectTimeout);
463
+ }
464
+ }
465
+ clearTimers(wsKey) {
466
+ this.clearPingTimer(wsKey);
467
+ this.clearPongTimer(wsKey);
468
+ this.clearReconnectTimer(wsKey);
469
+ }
470
+ // Send a ping at intervals
471
+ clearPingTimer(wsKey) {
472
+ const wsState = this.wsStore.get(wsKey);
473
+ if (wsState?.activePingTimer) {
474
+ clearInterval(wsState.activePingTimer);
475
+ wsState.activePingTimer = undefined;
476
+ }
477
+ }
478
+ // Expect a pong within a time limit
479
+ clearPongTimer(wsKey) {
480
+ const wsState = this.wsStore.get(wsKey);
481
+ if (wsState?.activePongTimer) {
482
+ clearTimeout(wsState.activePongTimer);
483
+ wsState.activePongTimer = undefined;
484
+ // this.logger.trace(`Cleared pong timeout for "${wsKey}"`);
485
+ }
486
+ else {
487
+ // this.logger.trace(`No active pong timer for "${wsKey}"`);
488
+ }
489
+ }
490
+ clearReconnectTimer(wsKey) {
491
+ const wsState = this.wsStore.get(wsKey);
492
+ if (wsState?.activeReconnectTimer) {
493
+ clearTimeout(wsState.activeReconnectTimer);
494
+ wsState.activeReconnectTimer = undefined;
495
+ }
496
+ }
497
+ /**
498
+ * Returns a list of string events that can be individually sent upstream to complete subscribing/unsubscribing/etc to these topics
499
+ *
500
+ * If events are an object, these should be stringified (`return JSON.stringify(event);`)
501
+ * Each event returned by this will be sent one at a time
502
+ *
503
+ * Events are automatically split into smaller batches, by this method, if needed.
504
+ */
505
+ async getWsOperationEventsForTopics(topics, wsKey, operation) {
506
+ if (!topics.length) {
507
+ return [];
508
+ }
509
+ // Events that are ready to send (usually stringified JSON)
510
+ const requestEvents = [];
511
+ const maxTopicsPerEvent = this.getMaxTopicsPerSubscribeEvent(wsKey);
512
+ if (maxTopicsPerEvent &&
513
+ maxTopicsPerEvent !== null &&
514
+ topics.length > maxTopicsPerEvent) {
515
+ for (let i = 0; i < topics.length; i += maxTopicsPerEvent) {
516
+ const batch = topics.slice(i, i + maxTopicsPerEvent);
517
+ const subscribeRequestEvents = await this.getWsRequestEvents(wsKey, operation, batch);
518
+ requestEvents.push(...subscribeRequestEvents);
519
+ }
520
+ return requestEvents;
521
+ }
522
+ const subscribeRequestEvents = await this.getWsRequestEvents(wsKey, operation, topics);
523
+ return subscribeRequestEvents;
524
+ }
525
+ /**
526
+ * Simply builds and sends subscribe events for a list of topics for a ws key
527
+ *
528
+ * @private Use the `subscribe(topics)` or `subscribeTopicsForWsKey(topics, wsKey)` method to subscribe to topics. Send WS message to subscribe to topics.
529
+ */
530
+ async requestSubscribeTopics(wsKey, wsTopicRequests) {
531
+ if (!wsTopicRequests.length) {
532
+ return;
533
+ }
534
+ // Automatically splits requests into smaller batches, if needed
535
+ const subscribeWsMessages = await this.getWsOperationEventsForTopics(wsTopicRequests, wsKey, 'subscribe');
536
+ this.logger.trace(`Subscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`);
537
+ for (const midflightRequest of subscribeWsMessages) {
538
+ const wsMessage = midflightRequest.requestEvent;
539
+ this.logger.trace(`Sending batch via message: "${JSON.stringify(wsMessage)}", cached with key "${midflightRequest.requestKey}"`);
540
+ try {
541
+ this.tryWsSend(wsKey, JSON.stringify(wsMessage), true);
542
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
543
+ }
544
+ catch (e) {
545
+ throw e;
546
+ }
547
+ }
548
+ this.logger.trace(`Finished subscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`);
549
+ }
550
+ /**
551
+ * Simply builds and sends unsubscribe events for a list of topics for a ws key
552
+ *
553
+ * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics.
554
+ */
555
+ async requestUnsubscribeTopics(wsKey, wsTopicRequests) {
556
+ if (!wsTopicRequests.length) {
557
+ return;
558
+ }
559
+ const subscribeWsMessages = await this.getWsOperationEventsForTopics(wsTopicRequests, wsKey, 'unsubscribe');
560
+ this.logger.trace(`Unsubscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches. Events: "${JSON.stringify(wsTopicRequests)}"`);
561
+ for (const midflightRequest of subscribeWsMessages) {
562
+ const wsMessage = midflightRequest.requestEvent;
563
+ this.logger.trace(`Sending batch via message: "${wsMessage}"`);
564
+ try {
565
+ this.tryWsSend(wsKey, JSON.stringify(wsMessage));
566
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
567
+ }
568
+ catch (e) {
569
+ throw e;
570
+ }
571
+ }
572
+ this.logger.trace(`Finished unsubscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`);
573
+ }
574
+ /**
575
+ * Try sending a string event on a WS connection (identified by the WS Key)
576
+ */
577
+ tryWsSend(wsKey, wsMessage, throwExceptions) {
578
+ try {
579
+ this.logger.trace('Sending upstream ws message: ', {
580
+ ...this.WS_LOGGER_CATEGORY,
581
+ wsMessage,
582
+ wsKey,
583
+ });
584
+ if (!wsKey) {
585
+ throw new Error('Cannot send message due to no known websocket for this wsKey');
586
+ }
587
+ const ws = this.getWs(wsKey);
588
+ if (!ws) {
589
+ throw new Error(`${wsKey} socket not connected yet, call "connectAll()" first then try again when the "open" event arrives`);
590
+ }
591
+ ws.send(wsMessage);
592
+ }
593
+ catch (e) {
594
+ this.logger.error('Failed to send WS message', {
595
+ ...this.WS_LOGGER_CATEGORY,
596
+ wsMessage,
597
+ wsKey,
598
+ exception: e,
599
+ });
600
+ if (throwExceptions) {
601
+ throw e;
602
+ }
603
+ }
604
+ }
605
+ async onWsOpen(event, wsKey, url, ws) {
606
+ const didReconnectSuccessfully = this.wsStore.isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.RECONNECTING) || this.wsStore.isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.ERROR);
607
+ const isFreshConnectionAttempt = this.wsStore.isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTING);
608
+ if (isFreshConnectionAttempt) {
609
+ this.logger.info('Websocket connected', {
610
+ ...this.WS_LOGGER_CATEGORY,
611
+ wsKey,
612
+ });
613
+ this.emit('open', { wsKey, event, wsUrl: url, ws });
614
+ }
615
+ else {
616
+ this.logger.info('Websocket reconnected', {
617
+ ...this.WS_LOGGER_CATEGORY,
618
+ wsKey,
619
+ didReconnectSuccessfully,
620
+ });
621
+ this.emit('reconnected', {
622
+ wsKey,
623
+ event,
624
+ wsUrl: url,
625
+ ws,
626
+ });
627
+ }
628
+ this.setWsState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTED);
629
+ this.logger.trace('Enabled ping timer', {
630
+ ...this.WS_LOGGER_CATEGORY,
631
+ wsKey,
632
+ });
633
+ this.wsStore.get(wsKey, true).activePingTimer = setInterval(() => this.ping(wsKey), this.options.pingInterval);
634
+ if (!this.options.requireConnectionReadyConfirmation) {
635
+ return await this.onWsReadyForEvents(wsKey);
636
+ }
637
+ else {
638
+ this.resolveConnectionInProgressPromise(wsKey);
639
+ }
640
+ this.wsStore.removeConnectingInProgressPromise(wsKey);
641
+ }
642
+ resolveConnectionInProgressPromise(wsKey) {
643
+ try {
644
+ // Resolve & cleanup deferred "connection attempt in progress" promise
645
+ const connectionInProgressPromise = this.wsStore.getConnectionInProgressPromise(wsKey);
646
+ if (connectionInProgressPromise?.resolve) {
647
+ connectionInProgressPromise.resolve({
648
+ wsKey,
649
+ ws: this.wsStore.getWs(wsKey),
650
+ });
651
+ }
652
+ }
653
+ catch (e) {
654
+ this.logger.error('Exception trying to resolve "connectionInProgress" promise');
655
+ }
656
+ }
657
+ /**
658
+ * Called automatically once a connection is ready.
659
+ * - Some exchanges are ready immediately after the connections open.
660
+ * - Some exchanges send an event to confirm the connection is ready for us.
661
+ *
662
+ * This method is called to act when the connection is ready. Use `requireConnectionReadyConfirmation` to control how this is called.
663
+ */
664
+ async onWsReadyForEvents(wsKey) {
665
+ this.resolveConnectionInProgressPromise(wsKey);
666
+ this.wsStore.removeConnectingInProgressPromise(wsKey);
667
+ // Some websockets require an auth packet to be sent after opening the connection
668
+ if (this.authPrivateConnectionsOnConnect(wsKey)) {
669
+ await this.assertIsAuthenticated(wsKey);
670
+ }
671
+ // Reconnect to topics known before it connected
672
+ const { privateReqs, publicReqs } = this.sortTopicRequestsIntoPublicPrivate([...this.wsStore.getTopics(wsKey)], wsKey);
673
+ // Request sub to public topics, if any
674
+ try {
675
+ await this.requestSubscribeTopics(wsKey, publicReqs);
676
+ }
677
+ catch (e) {
678
+ this.logger.error(`onWsOpen(): exception in public requestSubscribeTopics(${wsKey}): `, publicReqs, e);
679
+ }
680
+ // Request sub to private topics, if auth on connect isn't needed
681
+ if (!this.authPrivateConnectionsOnConnect(wsKey)) {
682
+ try {
683
+ this.requestSubscribeTopics(wsKey, privateReqs);
684
+ }
685
+ catch (e) {
686
+ this.logger.error(`onWsOpen(): exception in private requestSubscribeTopics(${wsKey}: `, privateReqs, e);
687
+ }
688
+ }
689
+ }
690
+ /**
691
+ * Handle subscription to private topics _after_ authentication successfully completes asynchronously.
692
+ *
693
+ * Only used for exchanges that require auth before sending private topic subscription requests
694
+ */
695
+ onWsAuthenticated(wsKey, event) {
696
+ const wsState = this.wsStore.get(wsKey, true);
697
+ wsState.isAuthenticated = true;
698
+ // Resolve & cleanup deferred "auth attempt in progress" promise
699
+ try {
700
+ const inProgressPromise = this.wsStore.getAuthenticationInProgressPromise(wsKey);
701
+ if (inProgressPromise?.resolve) {
702
+ inProgressPromise.resolve({
703
+ wsKey,
704
+ event,
705
+ ws: wsState.ws,
706
+ });
707
+ }
708
+ }
709
+ catch (e) {
710
+ this.logger.error('Exception trying to resolve "authenticationInProgress" promise', e);
711
+ }
712
+ // Remove before continuing, in case there's more requests queued
713
+ this.wsStore.removeAuthenticationInProgressPromise(wsKey);
714
+ if (this.authPrivateConnectionsOnConnect(wsKey)) {
715
+ const topics = [...this.wsStore.getTopics(wsKey)];
716
+ const privateTopics = topics.filter((topic) => this.isPrivateTopicRequest(topic, wsKey));
717
+ if (privateTopics.length) {
718
+ this.subscribeTopicsForWsKey(privateTopics, wsKey);
719
+ }
720
+ }
721
+ if (event?.isWSAPI) {
722
+ wsState.didAuthWSAPI = true;
723
+ if (event?.WSAPIAuthChannel) {
724
+ wsState.WSAPIAuthChannel = event.WSAPIAuthChannel;
725
+ }
726
+ }
727
+ }
728
+ onWsPing(event, wsKey, ws, source) {
729
+ this.logger.trace(`Received PING ${source}`, {
730
+ ...this.WS_LOGGER_CATEGORY,
731
+ wsKey,
732
+ event,
733
+ source,
734
+ });
735
+ this.sendPongEvent(wsKey, ws);
736
+ }
737
+ onWsPong(event, wsKey, source) {
738
+ this.logger.trace(`Received PONG ${source}`, {
739
+ ...this.WS_LOGGER_CATEGORY,
740
+ wsKey,
741
+ event: event?.data,
742
+ source,
743
+ });
744
+ // Necessary when native heartbeats are used
745
+ this.clearPongTimer(wsKey);
746
+ return;
747
+ }
748
+ onWsMessage(event, wsKey, ws) {
749
+ try {
750
+ // console.log('onMessageRaw: ', (event as any).data);
751
+ // any message can clear the pong timer - wouldn't get a message if the ws wasn't working
752
+ this.clearPongTimer(wsKey);
753
+ if (this.isWsPong(event)) {
754
+ return this.onWsPong(event, wsKey, 'event');
755
+ }
756
+ if (this.isWsPing(event)) {
757
+ return this.onWsPing(event, wsKey, ws, 'event');
758
+ }
759
+ if ((0, ws_events_js_1.isMessageEvent)(event)) {
760
+ const data = event.data;
761
+ const dataType = event.type;
762
+ const emittableEvents = this.resolveEmittableEvents(wsKey, event);
763
+ if (!emittableEvents.length) {
764
+ // console.log(`raw event: `, { data, dataType, emittableEvents });
765
+ this.logger.error('Unhandled/unrecognised ws event message - returned no emittable data', {
766
+ ...this.WS_LOGGER_CATEGORY,
767
+ message: data || 'no message',
768
+ dataType,
769
+ event,
770
+ wsKey,
771
+ });
772
+ return this.emit('message', { ...event, wsKey });
773
+ }
774
+ for (const emittable of emittableEvents) {
775
+ if (this.isWsPong(emittable) || emittable.eventType === 'pong') {
776
+ this.logger.trace('Received pong2', {
777
+ ...this.WS_LOGGER_CATEGORY,
778
+ wsKey,
779
+ data,
780
+ });
781
+ continue;
782
+ }
783
+ this.logger.trace('getFinalEmittable()->pre(): ', JSON.stringify(emittable));
784
+ const emittableFinalEvent = getFinalEmittable(emittable, wsKey, emittable.isWSAPIResponse);
785
+ if (emittable.eventType === 'connectionReady') {
786
+ this.logger.trace('Successfully connected - connection ready for events', {
787
+ ...this.WS_LOGGER_CATEGORY,
788
+ wsKey,
789
+ emittable,
790
+ });
791
+ const wsState = this.wsStore.get(wsKey);
792
+ if (wsState && !this.authPrivateConnectionsOnConnect(wsKey)) {
793
+ wsState.isAuthenticated = true;
794
+ }
795
+ this.emit('response', emittableFinalEvent);
796
+ this.onWsReadyForEvents(wsKey);
797
+ continue;
798
+ }
799
+ // Not used for kraken. At least for spot, auth is included per req during subscribe
800
+ if (emittable.eventType === 'connectionReadyForAuth') {
801
+ this.logger.trace('Ready for auth - requesting auth submission...', {
802
+ ...this.WS_LOGGER_CATEGORY,
803
+ wsKey,
804
+ });
805
+ this.sendAuthRequest(wsKey, emittable.event);
806
+ continue;
807
+ }
808
+ // Not used for kraken. At least for spot, auth is included per req during subscribe
809
+ if (emittable.eventType === 'authenticated') {
810
+ this.logger.trace('Successfully authenticated', {
811
+ ...this.WS_LOGGER_CATEGORY,
812
+ wsKey,
813
+ emittable,
814
+ });
815
+ this.emit(emittable.eventType, emittableFinalEvent);
816
+ this.onWsAuthenticated(wsKey, emittable.event);
817
+ continue;
818
+ }
819
+ // Other event types are automatically emitted here
820
+ this.logger.trace(`onWsMessage().emit(${emittable.eventType})`, emittableFinalEvent);
821
+ try {
822
+ this.emit(emittable.eventType, emittableFinalEvent);
823
+ }
824
+ catch (e) {
825
+ this.logger.error(`Exception in onWsMessage().emit(${emittable.eventType}) handler:`, e);
826
+ }
827
+ // this.logger.trace(
828
+ // `onWsMessage().emit(${emittable.eventType}).done()`,
829
+ // emittableFinalEvent,
830
+ // );
831
+ }
832
+ return;
833
+ }
834
+ this.logger.error('Unhandled/unrecognised ws event message - unexpected message format', {
835
+ ...this.WS_LOGGER_CATEGORY,
836
+ message: event || 'no message',
837
+ event,
838
+ wsKey,
839
+ });
840
+ }
841
+ catch (e) {
842
+ this.logger.error('Failed to parse ws event message', {
843
+ ...this.WS_LOGGER_CATEGORY,
844
+ error: e,
845
+ event,
846
+ wsKey,
847
+ });
848
+ }
849
+ }
850
+ onWsClose(event, wsKey) {
851
+ this.logger.info('Websocket connection closed', {
852
+ ...this.WS_LOGGER_CATEGORY,
853
+ wsKey,
854
+ });
855
+ const wsState = this.wsStore.get(wsKey, true);
856
+ wsState.isAuthenticated = false;
857
+ const wsConnectionState = this.wsStore.getConnectionState(wsKey);
858
+ if (wsConnectionState !== WsStore_types_js_1.WsConnectionStateEnum.CLOSING) {
859
+ // unintentional close, attempt recovery
860
+ this.logger.trace(`onWsClose(${wsKey}): rejecting all deferred promises...`);
861
+ // clean up any pending promises for this connection
862
+ this.getWsStore().rejectAllDeferredPromises(wsKey, 'connection lost, reconnecting');
863
+ // this.clearTopicsPendingSubscriptions(wsKey, true, 'WS Closed');
864
+ this.setWsState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.INITIAL);
865
+ this.reconnectWithDelay(wsKey, this.options.reconnectTimeout);
866
+ this.emit('reconnecting', { wsKey, event });
867
+ }
868
+ else {
869
+ // intentional close - clean up
870
+ // clean up any pending promises for this connection
871
+ this.logger.trace(`onWsClose(${wsKey}): rejecting all deferred promises...`);
872
+ this.getWsStore().rejectAllDeferredPromises(wsKey, 'disconnected');
873
+ this.setWsState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.INITIAL);
874
+ // This was an intentional close, delete all state for this connection, as if it never existed:
875
+ this.wsStore.delete(wsKey);
876
+ this.emit('close', { wsKey, event });
877
+ }
878
+ }
879
+ getWs(wsKey) {
880
+ return this.wsStore.getWs(wsKey);
881
+ }
882
+ setWsState(wsKey, state) {
883
+ this.wsStore.setConnectionState(wsKey, state);
884
+ }
885
+ /**
886
+ * Promise-driven method to assert that a ws has successfully connected (will await until connection is open)
887
+ */
888
+ async assertIsConnected(wsKey) {
889
+ const isConnected = this.getWsStore().isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTED);
890
+ if (isConnected) {
891
+ return true;
892
+ }
893
+ const inProgressPromise = this.getWsStore().getConnectionInProgressPromise(wsKey);
894
+ // Already in progress? Await shared promise and retry
895
+ if (inProgressPromise) {
896
+ this.logger.trace('assertIsConnected(): awaiting...');
897
+ await inProgressPromise.promise;
898
+ this.logger.trace('assertIsConnected(): awaiting...connected!');
899
+ return;
900
+ }
901
+ // Start connection, it should automatically store/return a promise.
902
+ this.logger.trace('assertIsConnected(): connecting...');
903
+ await this.connect(wsKey);
904
+ this.logger.trace('assertIsConnected(): connecting...newly connected!');
905
+ }
906
+ /**
907
+ * Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed)
908
+ */
909
+ async assertIsAuthenticated(wsKey) {
910
+ const isConnected = this.getWsStore().isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTED);
911
+ if (!isConnected) {
912
+ this.logger.trace('assertIsAuthenticated(): connecting...');
913
+ await this.assertIsConnected(wsKey);
914
+ }
915
+ const inProgressPromise = this.getWsStore().getAuthenticationInProgressPromise(wsKey);
916
+ // Already in progress? Await shared promise and retry
917
+ if (inProgressPromise) {
918
+ this.logger.trace('assertIsAuthenticated(): awaiting...');
919
+ await inProgressPromise.promise;
920
+ this.logger.trace('assertIsAuthenticated(): authenticated!');
921
+ return;
922
+ }
923
+ const isAuthenticated = this.wsStore.get(wsKey)?.isAuthenticated;
924
+ if (isAuthenticated) {
925
+ this.logger.trace('assertIsAuthenticated(): ok');
926
+ return;
927
+ }
928
+ // Start authentication, it should automatically store/return a promise.
929
+ this.logger.trace('assertIsAuthenticated(): authenticating...');
930
+ await this.sendAuthRequest(wsKey);
931
+ this.logger.trace('assertIsAuthenticated(): newly authenticated!');
932
+ }
933
+ }
934
+ exports.BaseWebsocketClient = BaseWebsocketClient;
935
+ //# sourceMappingURL=BaseWSClient.js.map