@binance/common 1.2.6 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,1637 +1,1625 @@
1
- // src/utils.ts
2
1
  import crypto from "crypto";
3
2
  import fs from "fs";
4
3
  import https from "https";
5
- import { platform, arch } from "os";
4
+ import { JSONParse } from "json-with-bigint";
5
+ import { arch, platform } from "os";
6
6
  import globalAxios from "axios";
7
- var signerCache = /* @__PURE__ */ new WeakMap();
7
+ import { EventEmitter } from "events";
8
+ import WebSocketClient from "ws";
9
+
10
+ //#region src/utils.ts
11
+ /**
12
+ * A weak cache for storing RequestSigner instances based on configuration parameters.
13
+ *
14
+ * @remarks
15
+ * Uses a WeakMap to cache and reuse RequestSigner instances for configurations with
16
+ * apiSecret, privateKey, and privateKeyPassphrase, allowing efficient memory management.
17
+ */
18
+ let signerCache = /* @__PURE__ */ new WeakMap();
19
+ /**
20
+ * Represents a request signer for generating signatures using HMAC-SHA256 or asymmetric key signing.
21
+ *
22
+ * Supports two signing methods:
23
+ * 1. HMAC-SHA256 using an API secret
24
+ * 2. Asymmetric signing using RSA or ED25519 private keys
25
+ *
26
+ * @throws {Error} If neither API secret nor private key is provided, or if the private key is invalid
27
+ */
8
28
  var RequestSigner = class {
9
- constructor(configuration) {
10
- if (configuration.apiSecret && !configuration.privateKey) {
11
- this.apiSecret = configuration.apiSecret;
12
- return;
13
- }
14
- if (configuration.privateKey) {
15
- let privateKey = configuration.privateKey;
16
- if (typeof privateKey === "string" && fs.existsSync(privateKey)) {
17
- privateKey = fs.readFileSync(privateKey, "utf-8");
18
- }
19
- const keyInput = { key: privateKey };
20
- if (configuration.privateKeyPassphrase && typeof configuration.privateKeyPassphrase === "string") {
21
- keyInput.passphrase = configuration.privateKeyPassphrase;
22
- }
23
- try {
24
- this.keyObject = crypto.createPrivateKey(keyInput);
25
- this.keyType = this.keyObject.asymmetricKeyType;
26
- } catch {
27
- throw new Error(
28
- "Invalid private key. Please provide a valid RSA or ED25519 private key."
29
- );
30
- }
31
- return;
32
- }
33
- throw new Error("Either 'apiSecret' or 'privateKey' must be provided for signed requests.");
34
- }
35
- sign(queryParams) {
36
- const params = buildQueryString(queryParams);
37
- if (this.apiSecret)
38
- return crypto.createHmac("sha256", this.apiSecret).update(params).digest("hex");
39
- if (this.keyObject && this.keyType) {
40
- const data = Buffer.from(params);
41
- if (this.keyType === "rsa")
42
- return crypto.sign("RSA-SHA256", data, this.keyObject).toString("base64");
43
- if (this.keyType === "ed25519")
44
- return crypto.sign(null, data, this.keyObject).toString("base64");
45
- throw new Error("Unsupported private key type. Must be RSA or ED25519.");
46
- }
47
- throw new Error("Signer is not properly initialized.");
48
- }
29
+ constructor(configuration) {
30
+ if (configuration.apiSecret && !configuration.privateKey) {
31
+ this.apiSecret = configuration.apiSecret;
32
+ return;
33
+ }
34
+ if (configuration.privateKey) {
35
+ let privateKey = configuration.privateKey;
36
+ if (typeof privateKey === "string" && fs.existsSync(privateKey)) privateKey = fs.readFileSync(privateKey, "utf-8");
37
+ const keyInput = { key: privateKey };
38
+ if (configuration.privateKeyPassphrase && typeof configuration.privateKeyPassphrase === "string") keyInput.passphrase = configuration.privateKeyPassphrase;
39
+ try {
40
+ this.keyObject = crypto.createPrivateKey(keyInput);
41
+ this.keyType = this.keyObject.asymmetricKeyType;
42
+ } catch {
43
+ throw new Error("Invalid private key. Please provide a valid RSA or ED25519 private key.");
44
+ }
45
+ return;
46
+ }
47
+ throw new Error("Either 'apiSecret' or 'privateKey' must be provided for signed requests.");
48
+ }
49
+ sign(queryParams) {
50
+ const params = buildQueryString(queryParams);
51
+ if (this.apiSecret) return crypto.createHmac("sha256", this.apiSecret).update(params).digest("hex");
52
+ if (this.keyObject && this.keyType) {
53
+ const data = Buffer.from(params);
54
+ if (this.keyType === "rsa") return crypto.sign("RSA-SHA256", data, this.keyObject).toString("base64");
55
+ if (this.keyType === "ed25519") return crypto.sign(null, data, this.keyObject).toString("base64");
56
+ throw new Error("Unsupported private key type. Must be RSA or ED25519.");
57
+ }
58
+ throw new Error("Signer is not properly initialized.");
59
+ }
49
60
  };
50
- var clearSignerCache = function() {
51
- signerCache = /* @__PURE__ */ new WeakMap();
61
+ /**
62
+ * Resets the signer cache to a new empty WeakMap.
63
+ *
64
+ * This function clears the existing signer cache, creating a fresh WeakMap
65
+ * to store RequestSigner instances associated with configuration objects.
66
+ */
67
+ const clearSignerCache = function() {
68
+ signerCache = /* @__PURE__ */ new WeakMap();
52
69
  };
70
+ /**
71
+ * Serializes a value to a string representation.
72
+ *
73
+ * - If the value is `null` or `undefined`, returns an empty string.
74
+ * - If the value is an array or a non-null object, returns its JSON string representation.
75
+ * - Otherwise, converts the value to a string using `String()`.
76
+ *
77
+ * @param value - The value to serialize.
78
+ * @returns The serialized string representation of the value.
79
+ */
53
80
  function serializeValue(value) {
54
- if (value === null || value === void 0) return "";
55
- if (Array.isArray(value) || typeof value === "object" && value !== null)
56
- return JSON.stringify(value);
57
- return String(value);
81
+ if (value === null || value === void 0) return "";
82
+ if (Array.isArray(value) || typeof value === "object" && value !== null) return JSON.stringify(value);
83
+ return String(value);
58
84
  }
85
+ /**
86
+ * Builds a URL query string from the given parameters object.
87
+ *
88
+ * Iterates over the key-value pairs in the `params` object, serializes each value,
89
+ * and encodes it for use in a URL. Only keys with non-null and non-undefined values
90
+ * are included in the resulting query string.
91
+ *
92
+ * @param params - An object containing key-value pairs to be serialized into a query string.
93
+ * @returns A URL-encoded query string representing the provided parameters.
94
+ */
59
95
  function buildQueryString(params) {
60
- if (!params) return "";
61
- const pairs = [];
62
- Object.entries(params).forEach(([key, value]) => {
63
- if (value !== null && value !== void 0) {
64
- const serializedValue = serializeValue(value);
65
- pairs.push(`${key}=${encodeURIComponent(serializedValue)}`);
66
- }
67
- });
68
- return pairs.join("&");
96
+ if (!params) return "";
97
+ const pairs = [];
98
+ Object.entries(params).forEach(([key, value]) => {
99
+ if (value !== null && value !== void 0) {
100
+ const serializedValue = serializeValue(value);
101
+ pairs.push(`${key}=${encodeURIComponent(serializedValue)}`);
102
+ }
103
+ });
104
+ return pairs.join("&");
69
105
  }
106
+ /**
107
+ * Generates a random string of 16 hexadecimal characters.
108
+ *
109
+ * @returns A random string of 16 hexadecimal characters.
110
+ */
70
111
  function randomString() {
71
- return crypto.randomBytes(16).toString("hex");
112
+ return crypto.randomBytes(16).toString("hex");
72
113
  }
114
+ /**
115
+ * Validates the provided time unit string and returns it if it is either 'MILLISECOND' or 'MICROSECOND'.
116
+ *
117
+ * @param timeUnit - The time unit string to be validated.
118
+ * @returns The validated time unit string, or `undefined` if the input is falsy.
119
+ * @throws {Error} If the time unit is not 'MILLISECOND' or 'MICROSECOND'.
120
+ */
73
121
  function validateTimeUnit(timeUnit) {
74
- if (!timeUnit) {
75
- return;
76
- } else if (timeUnit !== TimeUnit.MILLISECOND && timeUnit !== TimeUnit.MICROSECOND && timeUnit !== TimeUnit.millisecond && timeUnit !== TimeUnit.microsecond) {
77
- throw new Error("timeUnit must be either 'MILLISECOND' or 'MICROSECOND'");
78
- }
79
- return timeUnit;
122
+ if (!timeUnit) return;
123
+ else if (timeUnit !== TimeUnit.MILLISECOND && timeUnit !== TimeUnit.MICROSECOND && timeUnit !== TimeUnit.millisecond && timeUnit !== TimeUnit.microsecond) throw new Error("timeUnit must be either 'MILLISECOND' or 'MICROSECOND'");
124
+ return timeUnit;
80
125
  }
126
+ /**
127
+ * Delays the execution of the current function for the specified number of milliseconds.
128
+ *
129
+ * @param ms - The number of milliseconds to delay the function.
130
+ * @returns A Promise that resolves after the specified delay.
131
+ */
81
132
  async function delay(ms) {
82
- return new Promise((resolve) => setTimeout(resolve, ms));
133
+ return new Promise((resolve) => setTimeout(resolve, ms));
83
134
  }
135
+ /**
136
+ * Generates the current timestamp in milliseconds.
137
+ *
138
+ * @returns The current timestamp in milliseconds.
139
+ */
84
140
  function getTimestamp() {
85
- return Date.now();
141
+ return Date.now();
86
142
  }
87
- var getSignature = function(configuration, queryParams) {
88
- let signer = signerCache.get(configuration);
89
- if (!signer) {
90
- signer = new RequestSigner(configuration);
91
- signerCache.set(configuration, signer);
92
- }
93
- return signer.sign(queryParams);
143
+ /**
144
+ * Generates a signature for the given configuration and query parameters using a cached request signer.
145
+ *
146
+ * @param configuration - Configuration object containing API secret, private key, and optional passphrase.
147
+ * @param queryParams - The query parameters to be signed.
148
+ * @returns A string representing the generated signature.
149
+ */
150
+ const getSignature = function(configuration, queryParams) {
151
+ let signer = signerCache.get(configuration);
152
+ if (!signer) {
153
+ signer = new RequestSigner(configuration);
154
+ signerCache.set(configuration, signer);
155
+ }
156
+ return signer.sign(queryParams);
94
157
  };
95
- var assertParamExists = function(functionName, paramName, paramValue) {
96
- if (paramValue === null || paramValue === void 0) {
97
- throw new RequiredError(
98
- paramName,
99
- `Required parameter ${paramName} was null or undefined when calling ${functionName}.`
100
- );
101
- }
158
+ /**
159
+ * Asserts that a function parameter exists and is not null or undefined.
160
+ *
161
+ * @param functionName - The name of the function that the parameter belongs to.
162
+ * @param paramName - The name of the parameter to check.
163
+ * @param paramValue - The value of the parameter to check.
164
+ * @throws {RequiredError} If the parameter is null or undefined.
165
+ */
166
+ const assertParamExists = function(functionName, paramName, paramValue) {
167
+ if (paramValue === null || paramValue === void 0) throw new RequiredError(paramName, `Required parameter ${paramName} was null or undefined when calling ${functionName}.`);
102
168
  };
169
+ /**
170
+ * Sets the search parameters of a given URL object based on the provided key-value pairs.
171
+ * Only parameters with non-null and non-undefined values are included.
172
+ * Values are serialized using the `serializeValue` function before being set.
173
+ *
174
+ * @param url - The URL object whose search parameters will be updated.
175
+ * @param params - An object containing key-value pairs to be set as search parameters.
176
+ */
103
177
  function setSearchParams(url, params) {
104
- const searchParams = new URLSearchParams();
105
- Object.entries(params).forEach(([key, value]) => {
106
- if (value !== null && value !== void 0) {
107
- const serializedValue = serializeValue(value);
108
- searchParams.set(key, serializedValue);
109
- }
110
- });
111
- url.search = searchParams.toString();
178
+ const searchParams = new URLSearchParams();
179
+ Object.entries(params).forEach(([key, value]) => {
180
+ if (value !== null && value !== void 0) {
181
+ const serializedValue = serializeValue(value);
182
+ searchParams.set(key, serializedValue);
183
+ }
184
+ });
185
+ url.search = searchParams.toString();
112
186
  }
113
- var toPathString = function(url) {
114
- return url.pathname + url.search + url.hash;
187
+ /**
188
+ * Converts a URL object to a full path string, including pathname, search parameters, and hash.
189
+ *
190
+ * @param url The URL object to convert to a path string.
191
+ * @returns A complete path string representation of the URL.
192
+ */
193
+ const toPathString = function(url) {
194
+ return url.pathname + url.search + url.hash;
115
195
  };
196
+ /**
197
+ * Normalizes scientific notation numbers in an object or array to a fixed number of decimal places.
198
+ *
199
+ * This function recursively processes objects, arrays, and numbers, converting scientific notation
200
+ * to a fixed decimal representation. Non-numeric values are left unchanged.
201
+ *
202
+ * @template T The type of the input object or value
203
+ * @param obj The object, array, or value to normalize
204
+ * @returns A new object or value with scientific notation numbers normalized
205
+ */
116
206
  function normalizeScientificNumbers(obj) {
117
- if (Array.isArray(obj)) {
118
- return obj.map((item) => normalizeScientificNumbers(item));
119
- } else if (typeof obj === "object" && obj !== null) {
120
- const result = {};
121
- for (const key of Object.keys(obj)) {
122
- result[key] = normalizeScientificNumbers(obj[key]);
123
- }
124
- return result;
125
- } else if (typeof obj === "number") {
126
- if (!Number.isFinite(obj)) return obj;
127
- const abs = Math.abs(obj);
128
- if (abs === 0 || abs >= 1e-6 && abs < 1e21) return String(obj);
129
- const isNegative = obj < 0;
130
- const [rawMantissa, rawExponent] = abs.toExponential().split("e");
131
- const exponent = +rawExponent;
132
- const digits = rawMantissa.replace(".", "");
133
- if (exponent < 0) {
134
- const zeros = "0".repeat(Math.abs(exponent) - 1);
135
- return (isNegative ? "-" : "") + "0." + zeros + digits;
136
- } else {
137
- const pad = exponent - (digits.length - 1);
138
- if (pad >= 0) {
139
- return (isNegative ? "-" : "") + digits + "0".repeat(pad);
140
- } else {
141
- const point = digits.length + pad;
142
- return (isNegative ? "-" : "") + digits.slice(0, point) + "." + digits.slice(point);
143
- }
144
- }
145
- } else {
146
- return obj;
147
- }
207
+ if (Array.isArray(obj)) return obj.map((item) => normalizeScientificNumbers(item));
208
+ else if (typeof obj === "object" && obj !== null) {
209
+ const result = {};
210
+ for (const key of Object.keys(obj)) result[key] = normalizeScientificNumbers(obj[key]);
211
+ return result;
212
+ } else if (typeof obj === "number") {
213
+ if (!Number.isFinite(obj)) return obj;
214
+ const abs = Math.abs(obj);
215
+ if (abs === 0 || abs >= 1e-6 && abs < 1e21) return String(obj);
216
+ const isNegative = obj < 0;
217
+ const [rawMantissa, rawExponent] = abs.toExponential().split("e");
218
+ const exponent = +rawExponent;
219
+ const digits = rawMantissa.replace(".", "");
220
+ if (exponent < 0) {
221
+ const zeros = "0".repeat(Math.abs(exponent) - 1);
222
+ return (isNegative ? "-" : "") + "0." + zeros + digits;
223
+ } else {
224
+ const pad = exponent - (digits.length - 1);
225
+ if (pad >= 0) return (isNegative ? "-" : "") + digits + "0".repeat(pad);
226
+ else {
227
+ const point = digits.length + pad;
228
+ return (isNegative ? "-" : "") + digits.slice(0, point) + "." + digits.slice(point);
229
+ }
230
+ }
231
+ } else return obj;
148
232
  }
149
- var shouldRetryRequest = function(error, method, retriesLeft) {
150
- const isRetriableMethod = ["GET", "DELETE"].includes(method ?? "");
151
- const isRetriableStatus = [500, 502, 503, 504].includes(
152
- error?.response?.status ?? 0
153
- );
154
- return (retriesLeft ?? 0) > 0 && isRetriableMethod && (isRetriableStatus || !error?.response);
233
+ /**
234
+ * Determines whether a request should be retried based on the provided error.
235
+ *
236
+ * This function checks the HTTP method, response status, and number of retries left to determine if a request should be retried.
237
+ *
238
+ * @param error The error object to check.
239
+ * @param method The HTTP method of the request (optional).
240
+ * @param retriesLeft The number of retries left (optional).
241
+ * @returns `true` if the request should be retried, `false` otherwise.
242
+ */
243
+ const shouldRetryRequest = function(error, method, retriesLeft) {
244
+ const isRetriableMethod = ["GET", "DELETE"].includes(method ?? "");
245
+ const isRetriableStatus = [
246
+ 500,
247
+ 502,
248
+ 503,
249
+ 504
250
+ ].includes(error?.response?.status ?? 0);
251
+ return (retriesLeft ?? 0) > 0 && isRetriableMethod && (isRetriableStatus || !error?.response);
155
252
  };
156
- var httpRequestFunction = async function(axiosArgs, configuration) {
157
- const axiosRequestArgs = {
158
- ...axiosArgs.options,
159
- url: (globalAxios.defaults?.baseURL ? "" : configuration?.basePath ?? "") + axiosArgs.url
160
- };
161
- if (configuration?.keepAlive && !configuration?.baseOptions?.httpsAgent)
162
- axiosRequestArgs.httpsAgent = new https.Agent({ keepAlive: true });
163
- if (configuration?.compression)
164
- axiosRequestArgs.headers = {
165
- ...axiosRequestArgs.headers,
166
- "Accept-Encoding": "gzip, deflate, br"
167
- };
168
- const retries = configuration?.retries ?? 0;
169
- const backoff = configuration?.backoff ?? 0;
170
- let attempt = 0;
171
- let lastError;
172
- while (attempt <= retries) {
173
- try {
174
- const response = await globalAxios.request({
175
- ...axiosRequestArgs,
176
- responseType: "text"
177
- });
178
- const rateLimits = parseRateLimitHeaders(response.headers);
179
- return {
180
- data: async () => {
181
- try {
182
- return JSON.parse(response.data);
183
- } catch (err) {
184
- throw new Error(`Failed to parse JSON response: ${err}`);
185
- }
186
- },
187
- status: response.status,
188
- headers: response.headers,
189
- rateLimits
190
- };
191
- } catch (error) {
192
- attempt++;
193
- const axiosError = error;
194
- if (shouldRetryRequest(
195
- axiosError,
196
- axiosRequestArgs?.method?.toUpperCase(),
197
- retries - attempt
198
- )) {
199
- await delay(backoff * attempt);
200
- } else {
201
- if (axiosError.response && axiosError.response.status) {
202
- const status = axiosError.response?.status;
203
- const responseData = axiosError.response.data;
204
- let data = {};
205
- if (responseData && responseData !== null) {
206
- if (typeof responseData === "string" && responseData !== "")
207
- try {
208
- data = JSON.parse(responseData);
209
- } catch {
210
- data = {};
211
- }
212
- else if (typeof responseData === "object")
213
- data = responseData;
214
- }
215
- const errorMsg = data.msg;
216
- switch (status) {
217
- case 400:
218
- throw new BadRequestError(errorMsg);
219
- case 401:
220
- throw new UnauthorizedError(errorMsg);
221
- case 403:
222
- throw new ForbiddenError(errorMsg);
223
- case 404:
224
- throw new NotFoundError(errorMsg);
225
- case 418:
226
- throw new RateLimitBanError(errorMsg);
227
- case 429:
228
- throw new TooManyRequestsError(errorMsg);
229
- default:
230
- if (status >= 500 && status < 600)
231
- throw new ServerError(`Server error: ${status}`, status);
232
- throw new ConnectorClientError(errorMsg);
233
- }
234
- } else {
235
- if (retries > 0 && attempt >= retries)
236
- lastError = new Error(`Request failed after ${retries} retries`);
237
- else lastError = new NetworkError("Network error or request timeout.");
238
- break;
239
- }
240
- }
241
- }
242
- }
243
- throw lastError;
253
+ /**
254
+ * Performs an HTTP request using the provided Axios instance and configuration.
255
+ *
256
+ * This function handles retries, rate limit handling, and error handling for the HTTP request.
257
+ *
258
+ * @param axiosArgs The request arguments to be passed to Axios.
259
+ * @param configuration The configuration options for the request.
260
+ * @returns A Promise that resolves to the API response, including the data and rate limit headers.
261
+ */
262
+ const httpRequestFunction = async function(axiosArgs, configuration) {
263
+ const axiosRequestArgs = {
264
+ ...axiosArgs.options,
265
+ url: (globalAxios.defaults?.baseURL ? "" : configuration?.basePath ?? "") + axiosArgs.url
266
+ };
267
+ if (configuration?.keepAlive && !configuration?.baseOptions?.httpsAgent) axiosRequestArgs.httpsAgent = new https.Agent({ keepAlive: true });
268
+ if (configuration?.compression) axiosRequestArgs.headers = {
269
+ ...axiosRequestArgs.headers,
270
+ "Accept-Encoding": "gzip, deflate, br"
271
+ };
272
+ const retries = configuration?.retries ?? 0;
273
+ const backoff = configuration?.backoff ?? 0;
274
+ let attempt = 0;
275
+ let lastError;
276
+ while (attempt <= retries) try {
277
+ const response = await globalAxios.request({
278
+ ...axiosRequestArgs,
279
+ responseType: "text"
280
+ });
281
+ const rateLimits = parseRateLimitHeaders(response.headers);
282
+ return {
283
+ data: async () => {
284
+ try {
285
+ return JSONParse(response.data);
286
+ } catch (err) {
287
+ throw new Error(`Failed to parse JSON response: ${err}`);
288
+ }
289
+ },
290
+ status: response.status,
291
+ headers: response.headers,
292
+ rateLimits
293
+ };
294
+ } catch (error) {
295
+ attempt++;
296
+ const axiosError = error;
297
+ if (shouldRetryRequest(axiosError, axiosRequestArgs?.method?.toUpperCase(), retries - attempt)) await delay(backoff * attempt);
298
+ else if (axiosError.response && axiosError.response.status) {
299
+ const status = axiosError.response?.status;
300
+ const responseData = axiosError.response.data;
301
+ let data = {};
302
+ if (responseData && responseData !== null) {
303
+ if (typeof responseData === "string" && responseData !== "") try {
304
+ data = JSONParse(responseData);
305
+ } catch {
306
+ data = {};
307
+ }
308
+ else if (typeof responseData === "object") data = responseData;
309
+ }
310
+ const errorMsg = data.msg;
311
+ switch (status) {
312
+ case 400: throw new BadRequestError(errorMsg);
313
+ case 401: throw new UnauthorizedError(errorMsg);
314
+ case 403: throw new ForbiddenError(errorMsg);
315
+ case 404: throw new NotFoundError(errorMsg);
316
+ case 418: throw new RateLimitBanError(errorMsg);
317
+ case 429: throw new TooManyRequestsError(errorMsg);
318
+ default:
319
+ if (status >= 500 && status < 600) throw new ServerError(`Server error: ${status}`, status);
320
+ throw new ConnectorClientError(errorMsg);
321
+ }
322
+ } else {
323
+ if (retries > 0 && attempt >= retries) lastError = /* @__PURE__ */ new Error(`Request failed after ${retries} retries`);
324
+ else lastError = new NetworkError("Network error or request timeout.");
325
+ break;
326
+ }
327
+ }
328
+ throw lastError;
244
329
  };
245
- var parseRateLimitHeaders = function(headers) {
246
- const rateLimits = [];
247
- const parseIntervalDetails = (key) => {
248
- const match = key.match(/x-mbx-used-weight-(\d+)([smhd])|x-mbx-order-count-(\d+)([smhd])/i);
249
- if (!match) return null;
250
- const intervalNum = parseInt(match[1] || match[3], 10);
251
- const intervalLetter = (match[2] || match[4])?.toUpperCase();
252
- let interval;
253
- switch (intervalLetter) {
254
- case "S":
255
- interval = "SECOND";
256
- break;
257
- case "M":
258
- interval = "MINUTE";
259
- break;
260
- case "H":
261
- interval = "HOUR";
262
- break;
263
- case "D":
264
- interval = "DAY";
265
- break;
266
- default:
267
- return null;
268
- }
269
- return { interval, intervalNum };
270
- };
271
- for (const [key, value] of Object.entries(headers)) {
272
- const normalizedKey = key.toLowerCase();
273
- if (value === void 0) continue;
274
- if (normalizedKey.startsWith("x-mbx-used-weight-")) {
275
- const details = parseIntervalDetails(normalizedKey);
276
- if (details) {
277
- rateLimits.push({
278
- rateLimitType: "REQUEST_WEIGHT",
279
- interval: details.interval,
280
- intervalNum: details.intervalNum,
281
- count: parseInt(value, 10)
282
- });
283
- }
284
- } else if (normalizedKey.startsWith("x-mbx-order-count-")) {
285
- const details = parseIntervalDetails(normalizedKey);
286
- if (details) {
287
- rateLimits.push({
288
- rateLimitType: "ORDERS",
289
- interval: details.interval,
290
- intervalNum: details.intervalNum,
291
- count: parseInt(value, 10)
292
- });
293
- }
294
- }
295
- }
296
- if (headers["retry-after"]) {
297
- const retryAfter = parseInt(headers["retry-after"], 10);
298
- for (const limit of rateLimits) {
299
- limit.retryAfter = retryAfter;
300
- }
301
- }
302
- return rateLimits;
330
+ /**
331
+ * Parses the rate limit headers from the Axios response headers and returns an array of `RestApiRateLimit` objects.
332
+ *
333
+ * @param headers - The Axios response headers.
334
+ * @returns An array of `RestApiRateLimit` objects containing the parsed rate limit information.
335
+ */
336
+ const parseRateLimitHeaders = function(headers) {
337
+ const rateLimits = [];
338
+ const parseIntervalDetails = (key) => {
339
+ const match = key.match(/x-mbx-used-weight-(\d+)([smhd])|x-mbx-order-count-(\d+)([smhd])/i);
340
+ if (!match) return null;
341
+ const intervalNum = parseInt(match[1] || match[3], 10);
342
+ const intervalLetter = (match[2] || match[4])?.toUpperCase();
343
+ let interval;
344
+ switch (intervalLetter) {
345
+ case "S":
346
+ interval = "SECOND";
347
+ break;
348
+ case "M":
349
+ interval = "MINUTE";
350
+ break;
351
+ case "H":
352
+ interval = "HOUR";
353
+ break;
354
+ case "D":
355
+ interval = "DAY";
356
+ break;
357
+ default: return null;
358
+ }
359
+ return {
360
+ interval,
361
+ intervalNum
362
+ };
363
+ };
364
+ for (const [key, value] of Object.entries(headers)) {
365
+ const normalizedKey = key.toLowerCase();
366
+ if (value === void 0) continue;
367
+ if (normalizedKey.startsWith("x-mbx-used-weight-")) {
368
+ const details = parseIntervalDetails(normalizedKey);
369
+ if (details) rateLimits.push({
370
+ rateLimitType: "REQUEST_WEIGHT",
371
+ interval: details.interval,
372
+ intervalNum: details.intervalNum,
373
+ count: parseInt(value, 10)
374
+ });
375
+ } else if (normalizedKey.startsWith("x-mbx-order-count-")) {
376
+ const details = parseIntervalDetails(normalizedKey);
377
+ if (details) rateLimits.push({
378
+ rateLimitType: "ORDERS",
379
+ interval: details.interval,
380
+ intervalNum: details.intervalNum,
381
+ count: parseInt(value, 10)
382
+ });
383
+ }
384
+ }
385
+ if (headers["retry-after"]) {
386
+ const retryAfter = parseInt(headers["retry-after"], 10);
387
+ for (const limit of rateLimits) limit.retryAfter = retryAfter;
388
+ }
389
+ return rateLimits;
303
390
  };
304
- var sendRequest = function(configuration, endpoint, method, params = {}, timeUnit, options = {}) {
305
- const localVarUrlObj = new URL(endpoint, configuration?.basePath);
306
- const localVarRequestOptions = {
307
- method,
308
- ...configuration?.baseOptions
309
- };
310
- const localVarQueryParameter = { ...normalizeScientificNumbers(params) };
311
- if (options.isSigned) {
312
- const timestamp = getTimestamp();
313
- localVarQueryParameter["timestamp"] = timestamp;
314
- const signature = getSignature(configuration, localVarQueryParameter);
315
- if (signature) {
316
- localVarQueryParameter["signature"] = signature;
317
- }
318
- }
319
- setSearchParams(localVarUrlObj, localVarQueryParameter);
320
- if (timeUnit && localVarRequestOptions.headers) {
321
- const _timeUnit = validateTimeUnit(timeUnit);
322
- localVarRequestOptions.headers = {
323
- ...localVarRequestOptions.headers,
324
- "X-MBX-TIME-UNIT": _timeUnit
325
- };
326
- }
327
- return httpRequestFunction(
328
- {
329
- url: toPathString(localVarUrlObj),
330
- options: localVarRequestOptions
331
- },
332
- configuration
333
- );
391
+ /**
392
+ * Generic function to send a request with optional API key and signature.
393
+ * @param endpoint - The API endpoint to call.
394
+ * @param method - HTTP method to use (GET, POST, DELETE, etc.).
395
+ * @param params - Query parameters for the request.
396
+ * @param timeUnit - The time unit for the request.
397
+ * @param options - Additional request options (isSigned).
398
+ * @returns A promise resolving to the response data object.
399
+ */
400
+ const sendRequest = function(configuration, endpoint, method, params = {}, timeUnit, options = {}) {
401
+ const localVarUrlObj = new URL(endpoint, configuration?.basePath);
402
+ const localVarRequestOptions = {
403
+ method,
404
+ ...configuration?.baseOptions
405
+ };
406
+ const localVarQueryParameter = { ...normalizeScientificNumbers(params) };
407
+ if (options.isSigned) {
408
+ localVarQueryParameter["timestamp"] = getTimestamp();
409
+ const signature = getSignature(configuration, localVarQueryParameter);
410
+ if (signature) localVarQueryParameter["signature"] = signature;
411
+ }
412
+ setSearchParams(localVarUrlObj, localVarQueryParameter);
413
+ if (timeUnit && localVarRequestOptions.headers) {
414
+ const _timeUnit = validateTimeUnit(timeUnit);
415
+ localVarRequestOptions.headers = {
416
+ ...localVarRequestOptions.headers,
417
+ "X-MBX-TIME-UNIT": _timeUnit
418
+ };
419
+ }
420
+ return httpRequestFunction({
421
+ url: toPathString(localVarUrlObj),
422
+ options: localVarRequestOptions
423
+ }, configuration);
334
424
  };
425
+ /**
426
+ * Removes any null, undefined, or empty string values from the provided object.
427
+ *
428
+ * @param obj - The object to remove empty values from.
429
+ * @returns A new object with empty values removed.
430
+ */
335
431
  function removeEmptyValue(obj) {
336
- if (!(obj instanceof Object)) return {};
337
- return Object.fromEntries(
338
- Object.entries(obj).filter(
339
- ([, value]) => value !== null && value !== void 0 && value !== ""
340
- )
341
- );
432
+ if (!(obj instanceof Object)) return {};
433
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => value !== null && value !== void 0 && value !== ""));
342
434
  }
435
+ /**
436
+ * Sorts the properties of the provided object in alphabetical order and returns a new object with the sorted properties.
437
+ *
438
+ * @param obj - The object to be sorted.
439
+ * @returns A new object with the properties sorted in alphabetical order.
440
+ */
343
441
  function sortObject(obj) {
344
- return Object.keys(obj).sort().reduce((res, key) => {
345
- res[key] = obj[key];
346
- return res;
347
- }, {});
442
+ return Object.keys(obj).sort().reduce((res, key) => {
443
+ res[key] = obj[key];
444
+ return res;
445
+ }, {});
348
446
  }
447
+ /**
448
+ * Replaces placeholders in the format <field> with corresponding values from the provided variables object.
449
+ *
450
+ * @param {string} str - The input string containing placeholders.
451
+ * @param {Object} variables - An object where keys correspond to placeholder names and values are the replacements.
452
+ * @returns {string} - The resulting string with placeholders replaced by their corresponding values.
453
+ */
349
454
  function replaceWebsocketStreamsPlaceholders(str, variables) {
350
- const normalizedVariables = Object.keys(variables).reduce(
351
- (acc, key) => {
352
- const normalizedKey = key.toLowerCase().replace(/[-_]/g, "");
353
- acc[normalizedKey] = variables[key];
354
- return acc;
355
- },
356
- {}
357
- );
358
- return str.replace(/(@)?<([^>]+)>/g, (match, precedingAt, fieldName) => {
359
- const normalizedFieldName = fieldName.toLowerCase().replace(/[-_]/g, "");
360
- if (Object.prototype.hasOwnProperty.call(normalizedVariables, normalizedFieldName) && normalizedVariables[normalizedFieldName] != null) {
361
- const value = normalizedVariables[normalizedFieldName];
362
- switch (normalizedFieldName) {
363
- case "symbol":
364
- case "windowsize":
365
- return value.toLowerCase();
366
- case "updatespeed":
367
- return `@${value}`;
368
- default:
369
- return (precedingAt || "") + value;
370
- }
371
- }
372
- return "";
373
- });
455
+ const normalizedVariables = Object.keys(variables).reduce((acc, key) => {
456
+ const normalizedKey = key.toLowerCase().replace(/[-_]/g, "");
457
+ acc[normalizedKey] = variables[key];
458
+ return acc;
459
+ }, {});
460
+ return str.replace(/(@)?<([^>]+)>/g, (match, precedingAt, fieldName) => {
461
+ const normalizedFieldName = fieldName.toLowerCase().replace(/[-_]/g, "");
462
+ if (Object.prototype.hasOwnProperty.call(normalizedVariables, normalizedFieldName) && normalizedVariables[normalizedFieldName] != null) {
463
+ const value = normalizedVariables[normalizedFieldName];
464
+ switch (normalizedFieldName) {
465
+ case "symbol":
466
+ case "windowsize": return value.toLowerCase();
467
+ case "updatespeed": return `@${value}`;
468
+ default: return (precedingAt || "") + value;
469
+ }
470
+ }
471
+ return "";
472
+ });
374
473
  }
474
+ /**
475
+ * Generates a standardized user agent string for the application.
476
+ *
477
+ * @param {string} packageName - The name of the package/application.
478
+ * @param {string} packageVersion - The version of the package/application.
479
+ * @returns {string} A formatted user agent string including package details, Node.js version, platform, and architecture.
480
+ */
375
481
  function buildUserAgent(packageName, packageVersion) {
376
- return `${packageName}/${packageVersion} (Node.js/${process.version}; ${platform()}; ${arch()})`;
482
+ return `${packageName}/${packageVersion} (Node.js/${process.version}; ${platform()}; ${arch()})`;
377
483
  }
484
+ /**
485
+ * Builds a WebSocket API message with optional authentication and signature.
486
+ *
487
+ * @param {ConfigurationWebsocketAPI} configuration - The WebSocket API configuration.
488
+ * @param {string} method - The method name for the WebSocket message.
489
+ * @param {WebsocketSendMsgOptions} payload - The payload data to be sent.
490
+ * @param {WebsocketSendMsgConfig} options - Configuration options for message sending.
491
+ * @param {boolean} [skipAuth=false] - Flag to skip authentication if needed.
492
+ * @returns {Object} A structured WebSocket message with id, method, and params.
493
+ */
378
494
  function buildWebsocketAPIMessage(configuration, method, payload, options, skipAuth = false) {
379
- const id = payload.id && /^[0-9a-f]{32}$/.test(payload.id) ? payload.id : randomString();
380
- delete payload.id;
381
- let params = normalizeScientificNumbers(removeEmptyValue(payload));
382
- if ((options.withApiKey || options.isSigned) && !skipAuth) params.apiKey = configuration.apiKey;
383
- if (options.isSigned) {
384
- params.timestamp = getTimestamp();
385
- params = sortObject(params);
386
- if (!skipAuth) params.signature = getSignature(configuration, params);
387
- }
388
- return { id, method, params };
495
+ const id = payload.id && /^[0-9a-f]{32}$/.test(payload.id) ? payload.id : randomString();
496
+ delete payload.id;
497
+ let params = normalizeScientificNumbers(removeEmptyValue(payload));
498
+ if ((options.withApiKey || options.isSigned) && !skipAuth) params.apiKey = configuration.apiKey;
499
+ if (options.isSigned) {
500
+ params.timestamp = getTimestamp();
501
+ params = sortObject(params);
502
+ if (!skipAuth) params.signature = getSignature(configuration, params);
503
+ }
504
+ return {
505
+ id,
506
+ method,
507
+ params
508
+ };
389
509
  }
510
+ /**
511
+ * Sanitizes a header value by checking for and preventing carriage return and line feed characters.
512
+ *
513
+ * @param {string | string[]} value - The header value or array of header values to sanitize.
514
+ * @returns {string | string[]} The sanitized header value(s).
515
+ * @throws {Error} If the header value contains CR/LF characters.
516
+ */
390
517
  function sanitizeHeaderValue(value) {
391
- const sanitizeOne = (v) => {
392
- if (/\r|\n/.test(v)) throw new Error(`Invalid header value (contains CR/LF): "${v}"`);
393
- return v;
394
- };
395
- return Array.isArray(value) ? value.map(sanitizeOne) : sanitizeOne(value);
518
+ const sanitizeOne = (v) => {
519
+ if (/\r|\n/.test(v)) throw new Error(`Invalid header value (contains CR/LF): "${v}"`);
520
+ return v;
521
+ };
522
+ return Array.isArray(value) ? value.map(sanitizeOne) : sanitizeOne(value);
396
523
  }
524
+ /**
525
+ * Parses and sanitizes custom headers, filtering out forbidden headers.
526
+ *
527
+ * @param {Record<string, string | string[]>} headers - The input headers to be parsed.
528
+ * @returns {Record<string, string | string[]>} A new object with sanitized and allowed headers.
529
+ * @description Removes forbidden headers like 'host', 'authorization', and 'cookie',
530
+ * and sanitizes remaining header values to prevent injection of carriage return or line feed characters.
531
+ */
397
532
  function parseCustomHeaders(headers) {
398
- if (!headers || Object.keys(headers).length === 0) return {};
399
- const forbidden = /* @__PURE__ */ new Set(["host", "authorization", "cookie", ":method", ":path"]);
400
- const parsedHeaders = {};
401
- for (const [rawName, rawValue] of Object.entries(headers || {})) {
402
- const name = rawName.trim();
403
- if (forbidden.has(name.toLowerCase())) {
404
- Logger.getInstance().warn(`Dropping forbidden header: ${name}`);
405
- continue;
406
- }
407
- try {
408
- parsedHeaders[name] = sanitizeHeaderValue(rawValue);
409
- } catch {
410
- continue;
411
- }
412
- }
413
- return parsedHeaders;
533
+ if (!headers || Object.keys(headers).length === 0) return {};
534
+ const forbidden = new Set([
535
+ "host",
536
+ "authorization",
537
+ "cookie",
538
+ ":method",
539
+ ":path"
540
+ ]);
541
+ const parsedHeaders = {};
542
+ for (const [rawName, rawValue] of Object.entries(headers || {})) {
543
+ const name = rawName.trim();
544
+ if (forbidden.has(name.toLowerCase())) {
545
+ Logger.getInstance().warn(`Dropping forbidden header: ${name}`);
546
+ continue;
547
+ }
548
+ try {
549
+ parsedHeaders[name] = sanitizeHeaderValue(rawValue);
550
+ } catch {
551
+ continue;
552
+ }
553
+ }
554
+ return parsedHeaders;
414
555
  }
415
556
 
416
- // src/configuration.ts
557
+ //#endregion
558
+ //#region src/configuration.ts
417
559
  var ConfigurationRestAPI = class {
418
- constructor(param = { apiKey: "" }) {
419
- this.apiKey = param.apiKey;
420
- this.apiSecret = param.apiSecret;
421
- this.basePath = param.basePath;
422
- this.keepAlive = param.keepAlive ?? true;
423
- this.compression = param.compression ?? true;
424
- this.retries = param.retries ?? 3;
425
- this.backoff = param.backoff ?? 1e3;
426
- this.privateKey = param.privateKey;
427
- this.privateKeyPassphrase = param.privateKeyPassphrase;
428
- this.timeUnit = param.timeUnit;
429
- this.baseOptions = {
430
- timeout: param.timeout ?? 1e3,
431
- proxy: param.proxy && {
432
- host: param.proxy.host,
433
- port: param.proxy.port,
434
- ...param.proxy.protocol && { protocol: param.proxy.protocol },
435
- ...param.proxy.auth && { auth: param.proxy.auth }
436
- },
437
- httpsAgent: param.httpsAgent ?? false,
438
- headers: {
439
- ...parseCustomHeaders(param.customHeaders || {}),
440
- "Content-Type": "application/json",
441
- "X-MBX-APIKEY": param.apiKey
442
- }
443
- };
444
- }
560
+ constructor(param = { apiKey: "" }) {
561
+ this.apiKey = param.apiKey;
562
+ this.apiSecret = param.apiSecret;
563
+ this.basePath = param.basePath;
564
+ this.keepAlive = param.keepAlive ?? true;
565
+ this.compression = param.compression ?? true;
566
+ this.retries = param.retries ?? 3;
567
+ this.backoff = param.backoff ?? 1e3;
568
+ this.privateKey = param.privateKey;
569
+ this.privateKeyPassphrase = param.privateKeyPassphrase;
570
+ this.timeUnit = param.timeUnit;
571
+ this.baseOptions = {
572
+ timeout: param.timeout ?? 1e3,
573
+ proxy: param.proxy && {
574
+ host: param.proxy.host,
575
+ port: param.proxy.port,
576
+ ...param.proxy.protocol && { protocol: param.proxy.protocol },
577
+ ...param.proxy.auth && { auth: param.proxy.auth }
578
+ },
579
+ httpsAgent: param.httpsAgent ?? false,
580
+ headers: {
581
+ ...parseCustomHeaders(param.customHeaders || {}),
582
+ "Content-Type": "application/json",
583
+ "X-MBX-APIKEY": param.apiKey
584
+ }
585
+ };
586
+ }
445
587
  };
446
- var ConfigurationWebsocketAPI2 = class {
447
- constructor(param = { apiKey: "" }) {
448
- this.apiKey = param.apiKey;
449
- this.apiSecret = param.apiSecret;
450
- this.wsURL = param.wsURL;
451
- this.timeout = param.timeout ?? 5e3;
452
- this.reconnectDelay = param.reconnectDelay ?? 5e3;
453
- this.compression = param.compression ?? true;
454
- this.agent = param.agent ?? false;
455
- this.mode = param.mode ?? "single";
456
- this.poolSize = param.poolSize ?? 1;
457
- this.privateKey = param.privateKey;
458
- this.privateKeyPassphrase = param.privateKeyPassphrase;
459
- this.timeUnit = param.timeUnit;
460
- this.autoSessionReLogon = param.autoSessionReLogon ?? true;
461
- }
588
+ var ConfigurationWebsocketAPI = class {
589
+ constructor(param = { apiKey: "" }) {
590
+ this.apiKey = param.apiKey;
591
+ this.apiSecret = param.apiSecret;
592
+ this.wsURL = param.wsURL;
593
+ this.timeout = param.timeout ?? 5e3;
594
+ this.reconnectDelay = param.reconnectDelay ?? 5e3;
595
+ this.compression = param.compression ?? true;
596
+ this.agent = param.agent ?? false;
597
+ this.mode = param.mode ?? "single";
598
+ this.poolSize = param.poolSize ?? 1;
599
+ this.privateKey = param.privateKey;
600
+ this.privateKeyPassphrase = param.privateKeyPassphrase;
601
+ this.timeUnit = param.timeUnit;
602
+ this.autoSessionReLogon = param.autoSessionReLogon ?? true;
603
+ }
462
604
  };
463
605
  var ConfigurationWebsocketStreams = class {
464
- constructor(param = {}) {
465
- this.wsURL = param.wsURL;
466
- this.reconnectDelay = param.reconnectDelay ?? 5e3;
467
- this.compression = param.compression ?? true;
468
- this.agent = param.agent ?? false;
469
- this.mode = param.mode ?? "single";
470
- this.poolSize = param.poolSize ?? 1;
471
- this.timeUnit = param.timeUnit;
472
- }
606
+ constructor(param = {}) {
607
+ this.wsURL = param.wsURL;
608
+ this.reconnectDelay = param.reconnectDelay ?? 5e3;
609
+ this.compression = param.compression ?? true;
610
+ this.agent = param.agent ?? false;
611
+ this.mode = param.mode ?? "single";
612
+ this.poolSize = param.poolSize ?? 1;
613
+ this.timeUnit = param.timeUnit;
614
+ }
473
615
  };
474
616
 
475
- // src/constants.ts
476
- var TimeUnit = {
477
- MILLISECOND: "MILLISECOND",
478
- millisecond: "millisecond",
479
- MICROSECOND: "MICROSECOND",
480
- microsecond: "microsecond"
617
+ //#endregion
618
+ //#region src/constants.ts
619
+ const TimeUnit = {
620
+ MILLISECOND: "MILLISECOND",
621
+ millisecond: "millisecond",
622
+ MICROSECOND: "MICROSECOND",
623
+ microsecond: "microsecond"
481
624
  };
482
- var ALGO_REST_API_PROD_URL = "https://api.binance.com";
483
- var C2C_REST_API_PROD_URL = "https://api.binance.com";
484
- var CONVERT_REST_API_PROD_URL = "https://api.binance.com";
485
- var COPY_TRADING_REST_API_PROD_URL = "https://api.binance.com";
486
- var CRYPTO_LOAN_REST_API_PROD_URL = "https://api.binance.com";
487
- var DERIVATIVES_TRADING_COIN_FUTURES_REST_API_PROD_URL = "https://dapi.binance.com";
488
- var DERIVATIVES_TRADING_COIN_FUTURES_REST_API_TESTNET_URL = "https://testnet.binancefuture.com";
489
- var DERIVATIVES_TRADING_COIN_FUTURES_WS_API_PROD_URL = "wss://ws-dapi.binance.com/ws-dapi/v1";
490
- var DERIVATIVES_TRADING_COIN_FUTURES_WS_API_TESTNET_URL = "wss://testnet.binancefuture.com/ws-dapi/v1";
491
- var DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_PROD_URL = "wss://dstream.binance.com";
492
- var DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_TESTNET_URL = "wss://dstream.binancefuture.com";
493
- var DERIVATIVES_TRADING_USDS_FUTURES_REST_API_PROD_URL = "https://fapi.binance.com";
494
- var DERIVATIVES_TRADING_USDS_FUTURES_REST_API_TESTNET_URL = "https://testnet.binancefuture.com";
495
- var DERIVATIVES_TRADING_USDS_FUTURES_WS_API_PROD_URL = "wss://ws-fapi.binance.com/ws-fapi/v1";
496
- var DERIVATIVES_TRADING_USDS_FUTURES_WS_API_TESTNET_URL = "wss://testnet.binancefuture.com/ws-fapi/v1";
497
- var DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_PROD_URL = "wss://fstream.binance.com";
498
- var DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_TESTNET_URL = "wss://stream.binancefuture.com";
499
- var DERIVATIVES_TRADING_OPTIONS_REST_API_PROD_URL = "https://eapi.binance.com";
500
- var DERIVATIVES_TRADING_OPTIONS_WS_STREAMS_PROD_URL = "wss://nbstream.binance.com/eoptions";
501
- var DERIVATIVES_TRADING_PORTFOLIO_MARGIN_REST_API_PROD_URL = "https://papi.binance.com";
502
- var DERIVATIVES_TRADING_PORTFOLIO_MARGIN_REST_API_TESTNET_URL = "https://testnet.binancefuture.com";
503
- var DERIVATIVES_TRADING_PORTFOLIO_MARGIN_WS_STREAMS_PROD_URL = "wss://fstream.binance.com/pm";
504
- var DERIVATIVES_TRADING_PORTFOLIO_MARGIN_WS_STREAMS_TESTNET_URL = "wss://fstream.binancefuture.com/pm";
505
- var DERIVATIVES_TRADING_PORTFOLIO_MARGIN_PRO_REST_API_PROD_URL = "https://api.binance.com";
506
- var DERIVATIVES_TRADING_PORTFOLIO_MARGIN_PRO_WS_STREAMS_PROD_URL = "wss://fstream.binance.com/pm-classic";
507
- var DUAL_INVESTMENT_REST_API_PROD_URL = "https://api.binance.com";
508
- var FIAT_REST_API_PROD_URL = "https://api.binance.com";
509
- var GIFT_CARD_REST_API_PROD_URL = "https://api.binance.com";
510
- var MARGIN_TRADING_REST_API_PROD_URL = "https://api.binance.com";
511
- var MARGIN_TRADING_WS_STREAMS_PROD_URL = "wss://stream.binance.com:9443";
512
- var MARGIN_TRADING_RISK_WS_STREAMS_PROD_URL = "wss://margin-stream.binance.com";
513
- var MINING_REST_API_PROD_URL = "https://api.binance.com";
514
- var NFT_REST_API_PROD_URL = "https://api.binance.com";
515
- var PAY_REST_API_PROD_URL = "https://api.binance.com";
516
- var REBATE_REST_API_PROD_URL = "https://api.binance.com";
517
- var SIMPLE_EARN_REST_API_PROD_URL = "https://api.binance.com";
518
- var SPOT_REST_API_PROD_URL = "https://api.binance.com";
519
- var SPOT_REST_API_TESTNET_URL = "https://testnet.binance.vision";
520
- var SPOT_WS_API_PROD_URL = "wss://ws-api.binance.com:443/ws-api/v3";
521
- var SPOT_WS_API_TESTNET_URL = "wss://ws-api.testnet.binance.vision/ws-api/v3";
522
- var SPOT_WS_STREAMS_PROD_URL = "wss://stream.binance.com:9443";
523
- var SPOT_WS_STREAMS_TESTNET_URL = "wss://stream.testnet.binance.vision";
524
- var SPOT_REST_API_MARKET_URL = "https://data-api.binance.vision";
525
- var SPOT_WS_STREAMS_MARKET_URL = "wss://data-stream.binance.vision";
526
- var STAKING_REST_API_PROD_URL = "https://api.binance.com";
527
- var SUB_ACCOUNT_REST_API_PROD_URL = "https://api.binance.com";
528
- var VIP_LOAN_REST_API_PROD_URL = "https://api.binance.com";
529
- var WALLET_REST_API_PROD_URL = "https://api.binance.com";
625
+ const ALGO_REST_API_PROD_URL = "https://api.binance.com";
626
+ const C2C_REST_API_PROD_URL = "https://api.binance.com";
627
+ const CONVERT_REST_API_PROD_URL = "https://api.binance.com";
628
+ const COPY_TRADING_REST_API_PROD_URL = "https://api.binance.com";
629
+ const CRYPTO_LOAN_REST_API_PROD_URL = "https://api.binance.com";
630
+ const DERIVATIVES_TRADING_COIN_FUTURES_REST_API_PROD_URL = "https://dapi.binance.com";
631
+ const DERIVATIVES_TRADING_COIN_FUTURES_REST_API_TESTNET_URL = "https://testnet.binancefuture.com";
632
+ const DERIVATIVES_TRADING_COIN_FUTURES_WS_API_PROD_URL = "wss://ws-dapi.binance.com/ws-dapi/v1";
633
+ const DERIVATIVES_TRADING_COIN_FUTURES_WS_API_TESTNET_URL = "wss://testnet.binancefuture.com/ws-dapi/v1";
634
+ const DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_PROD_URL = "wss://dstream.binance.com";
635
+ const DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_TESTNET_URL = "wss://dstream.binancefuture.com";
636
+ const DERIVATIVES_TRADING_USDS_FUTURES_REST_API_PROD_URL = "https://fapi.binance.com";
637
+ const DERIVATIVES_TRADING_USDS_FUTURES_REST_API_TESTNET_URL = "https://testnet.binancefuture.com";
638
+ const DERIVATIVES_TRADING_USDS_FUTURES_WS_API_PROD_URL = "wss://ws-fapi.binance.com/ws-fapi/v1";
639
+ const DERIVATIVES_TRADING_USDS_FUTURES_WS_API_TESTNET_URL = "wss://testnet.binancefuture.com/ws-fapi/v1";
640
+ const DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_PROD_URL = "wss://fstream.binance.com";
641
+ const DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_TESTNET_URL = "wss://stream.binancefuture.com";
642
+ const DERIVATIVES_TRADING_OPTIONS_REST_API_PROD_URL = "https://eapi.binance.com";
643
+ const DERIVATIVES_TRADING_OPTIONS_WS_STREAMS_PROD_URL = "wss://nbstream.binance.com/eoptions";
644
+ const DERIVATIVES_TRADING_PORTFOLIO_MARGIN_REST_API_PROD_URL = "https://papi.binance.com";
645
+ const DERIVATIVES_TRADING_PORTFOLIO_MARGIN_REST_API_TESTNET_URL = "https://testnet.binancefuture.com";
646
+ const DERIVATIVES_TRADING_PORTFOLIO_MARGIN_WS_STREAMS_PROD_URL = "wss://fstream.binance.com/pm";
647
+ const DERIVATIVES_TRADING_PORTFOLIO_MARGIN_WS_STREAMS_TESTNET_URL = "wss://fstream.binancefuture.com/pm";
648
+ const DERIVATIVES_TRADING_PORTFOLIO_MARGIN_PRO_REST_API_PROD_URL = "https://api.binance.com";
649
+ const DERIVATIVES_TRADING_PORTFOLIO_MARGIN_PRO_WS_STREAMS_PROD_URL = "wss://fstream.binance.com/pm-classic";
650
+ const DUAL_INVESTMENT_REST_API_PROD_URL = "https://api.binance.com";
651
+ const FIAT_REST_API_PROD_URL = "https://api.binance.com";
652
+ const GIFT_CARD_REST_API_PROD_URL = "https://api.binance.com";
653
+ const MARGIN_TRADING_REST_API_PROD_URL = "https://api.binance.com";
654
+ const MARGIN_TRADING_WS_STREAMS_PROD_URL = "wss://stream.binance.com:9443";
655
+ const MARGIN_TRADING_RISK_WS_STREAMS_PROD_URL = "wss://margin-stream.binance.com";
656
+ const MINING_REST_API_PROD_URL = "https://api.binance.com";
657
+ const NFT_REST_API_PROD_URL = "https://api.binance.com";
658
+ const PAY_REST_API_PROD_URL = "https://api.binance.com";
659
+ const REBATE_REST_API_PROD_URL = "https://api.binance.com";
660
+ const SIMPLE_EARN_REST_API_PROD_URL = "https://api.binance.com";
661
+ const SPOT_REST_API_PROD_URL = "https://api.binance.com";
662
+ const SPOT_REST_API_TESTNET_URL = "https://testnet.binance.vision";
663
+ const SPOT_WS_API_PROD_URL = "wss://ws-api.binance.com:443/ws-api/v3";
664
+ const SPOT_WS_API_TESTNET_URL = "wss://ws-api.testnet.binance.vision/ws-api/v3";
665
+ const SPOT_WS_STREAMS_PROD_URL = "wss://stream.binance.com:9443";
666
+ const SPOT_WS_STREAMS_TESTNET_URL = "wss://stream.testnet.binance.vision";
667
+ const SPOT_REST_API_MARKET_URL = "https://data-api.binance.vision";
668
+ const SPOT_WS_STREAMS_MARKET_URL = "wss://data-stream.binance.vision";
669
+ const STAKING_REST_API_PROD_URL = "https://api.binance.com";
670
+ const SUB_ACCOUNT_REST_API_PROD_URL = "https://api.binance.com";
671
+ const VIP_LOAN_REST_API_PROD_URL = "https://api.binance.com";
672
+ const WALLET_REST_API_PROD_URL = "https://api.binance.com";
530
673
 
531
- // src/errors.ts
532
- var ConnectorClientError = class _ConnectorClientError extends Error {
533
- constructor(msg) {
534
- super(msg || "An unexpected error occurred.");
535
- Object.setPrototypeOf(this, _ConnectorClientError.prototype);
536
- this.name = "ConnectorClientError";
537
- }
674
+ //#endregion
675
+ //#region src/errors.ts
676
+ /**
677
+ * Represents an error that occurred in the Connector client.
678
+ * @param msg - An optional error message.
679
+ */
680
+ var ConnectorClientError = class ConnectorClientError extends Error {
681
+ constructor(msg) {
682
+ super(msg || "An unexpected error occurred.");
683
+ Object.setPrototypeOf(this, ConnectorClientError.prototype);
684
+ this.name = "ConnectorClientError";
685
+ }
538
686
  };
539
- var RequiredError = class _RequiredError extends Error {
540
- constructor(field, msg) {
541
- super(msg || `Required parameter ${field} was null or undefined.`);
542
- this.field = field;
543
- Object.setPrototypeOf(this, _RequiredError.prototype);
544
- this.name = "RequiredError";
545
- }
687
+ /**
688
+ * Represents an error that occurs when a required parameter is missing or undefined.
689
+ * @param field - The name of the missing parameter.
690
+ * @param msg - An optional error message.
691
+ */
692
+ var RequiredError = class RequiredError extends Error {
693
+ constructor(field, msg) {
694
+ super(msg || `Required parameter ${field} was null or undefined.`);
695
+ this.field = field;
696
+ Object.setPrototypeOf(this, RequiredError.prototype);
697
+ this.name = "RequiredError";
698
+ }
546
699
  };
547
- var UnauthorizedError = class _UnauthorizedError extends Error {
548
- constructor(msg) {
549
- super(msg || "Unauthorized access. Authentication required.");
550
- Object.setPrototypeOf(this, _UnauthorizedError.prototype);
551
- this.name = "UnauthorizedError";
552
- }
700
+ /**
701
+ * Represents an error that occurs when a client is unauthorized to access a resource.
702
+ * @param msg - An optional error message.
703
+ */
704
+ var UnauthorizedError = class UnauthorizedError extends Error {
705
+ constructor(msg) {
706
+ super(msg || "Unauthorized access. Authentication required.");
707
+ Object.setPrototypeOf(this, UnauthorizedError.prototype);
708
+ this.name = "UnauthorizedError";
709
+ }
553
710
  };
554
- var ForbiddenError = class _ForbiddenError extends Error {
555
- constructor(msg) {
556
- super(msg || "Access to the requested resource is forbidden.");
557
- Object.setPrototypeOf(this, _ForbiddenError.prototype);
558
- this.name = "ForbiddenError";
559
- }
711
+ /**
712
+ * Represents an error that occurs when a resource is forbidden to the client.
713
+ * @param msg - An optional error message.
714
+ */
715
+ var ForbiddenError = class ForbiddenError extends Error {
716
+ constructor(msg) {
717
+ super(msg || "Access to the requested resource is forbidden.");
718
+ Object.setPrototypeOf(this, ForbiddenError.prototype);
719
+ this.name = "ForbiddenError";
720
+ }
560
721
  };
561
- var TooManyRequestsError = class _TooManyRequestsError extends Error {
562
- constructor(msg) {
563
- super(msg || "Too many requests. You are being rate-limited.");
564
- Object.setPrototypeOf(this, _TooManyRequestsError.prototype);
565
- this.name = "TooManyRequestsError";
566
- }
722
+ /**
723
+ * Represents an error that occurs when client is doing too many requests.
724
+ * @param msg - An optional error message.
725
+ */
726
+ var TooManyRequestsError = class TooManyRequestsError extends Error {
727
+ constructor(msg) {
728
+ super(msg || "Too many requests. You are being rate-limited.");
729
+ Object.setPrototypeOf(this, TooManyRequestsError.prototype);
730
+ this.name = "TooManyRequestsError";
731
+ }
567
732
  };
568
- var RateLimitBanError = class _RateLimitBanError extends Error {
569
- constructor(msg) {
570
- super(msg || "The IP address has been banned for exceeding rate limits.");
571
- Object.setPrototypeOf(this, _RateLimitBanError.prototype);
572
- this.name = "RateLimitBanError";
573
- }
733
+ /**
734
+ * Represents an error that occurs when client's IP has been banned.
735
+ * @param msg - An optional error message.
736
+ */
737
+ var RateLimitBanError = class RateLimitBanError extends Error {
738
+ constructor(msg) {
739
+ super(msg || "The IP address has been banned for exceeding rate limits.");
740
+ Object.setPrototypeOf(this, RateLimitBanError.prototype);
741
+ this.name = "RateLimitBanError";
742
+ }
574
743
  };
575
- var ServerError = class _ServerError extends Error {
576
- constructor(msg, statusCode) {
577
- super(msg || "An internal server error occurred.");
578
- this.statusCode = statusCode;
579
- Object.setPrototypeOf(this, _ServerError.prototype);
580
- this.name = "ServerError";
581
- }
744
+ /**
745
+ * Represents an error that occurs when there is an internal server error.
746
+ * @param msg - An optional error message.
747
+ * @param statusCode - An optional HTTP status code associated with the error.
748
+ */
749
+ var ServerError = class ServerError extends Error {
750
+ constructor(msg, statusCode) {
751
+ super(msg || "An internal server error occurred.");
752
+ this.statusCode = statusCode;
753
+ Object.setPrototypeOf(this, ServerError.prototype);
754
+ this.name = "ServerError";
755
+ }
582
756
  };
583
- var NetworkError = class _NetworkError extends Error {
584
- constructor(msg) {
585
- super(msg || "A network error occurred.");
586
- Object.setPrototypeOf(this, _NetworkError.prototype);
587
- this.name = "NetworkError";
588
- }
757
+ /**
758
+ * Represents an error that occurs when a network error occurs.
759
+ * @param msg - An optional error message.
760
+ */
761
+ var NetworkError = class NetworkError extends Error {
762
+ constructor(msg) {
763
+ super(msg || "A network error occurred.");
764
+ Object.setPrototypeOf(this, NetworkError.prototype);
765
+ this.name = "NetworkError";
766
+ }
589
767
  };
590
- var NotFoundError = class _NotFoundError extends Error {
591
- constructor(msg) {
592
- super(msg || "The requested resource was not found.");
593
- Object.setPrototypeOf(this, _NotFoundError.prototype);
594
- this.name = "NotFoundError";
595
- }
768
+ /**
769
+ * Represents an error that occurs when the requested resource was not found.
770
+ * @param msg - An optional error message.
771
+ */
772
+ var NotFoundError = class NotFoundError extends Error {
773
+ constructor(msg) {
774
+ super(msg || "The requested resource was not found.");
775
+ Object.setPrototypeOf(this, NotFoundError.prototype);
776
+ this.name = "NotFoundError";
777
+ }
596
778
  };
597
- var BadRequestError = class _BadRequestError extends Error {
598
- constructor(msg) {
599
- super(msg || "The request was invalid or cannot be otherwise served.");
600
- Object.setPrototypeOf(this, _BadRequestError.prototype);
601
- this.name = "BadRequestError";
602
- }
779
+ /**
780
+ * Represents an error that occurs when a request is invalid or cannot be otherwise served.
781
+ * @param msg - An optional error message.
782
+ */
783
+ var BadRequestError = class BadRequestError extends Error {
784
+ constructor(msg) {
785
+ super(msg || "The request was invalid or cannot be otherwise served.");
786
+ Object.setPrototypeOf(this, BadRequestError.prototype);
787
+ this.name = "BadRequestError";
788
+ }
603
789
  };
604
790
 
605
- // src/logger.ts
606
- var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
607
- LogLevel2["NONE"] = "";
608
- LogLevel2["DEBUG"] = "debug";
609
- LogLevel2["INFO"] = "info";
610
- LogLevel2["WARN"] = "warn";
611
- LogLevel2["ERROR"] = "error";
612
- return LogLevel2;
613
- })(LogLevel || {});
614
- var Logger = class _Logger {
615
- constructor() {
616
- this.minLogLevel = "info" /* INFO */;
617
- this.levelsOrder = [
618
- "" /* NONE */,
619
- "debug" /* DEBUG */,
620
- "info" /* INFO */,
621
- "warn" /* WARN */,
622
- "error" /* ERROR */
623
- ];
624
- const envLevel = process.env.LOG_LEVEL?.toLowerCase();
625
- this.minLogLevel = envLevel && this.isValidLogLevel(envLevel) ? envLevel : "info" /* INFO */;
626
- }
627
- static getInstance() {
628
- if (!_Logger.instance) _Logger.instance = new _Logger();
629
- return _Logger.instance;
630
- }
631
- setMinLogLevel(level) {
632
- if (!this.isValidLogLevel(level)) throw new Error(`Invalid log level: ${level}`);
633
- this.minLogLevel = level;
634
- }
635
- isValidLogLevel(level) {
636
- return this.levelsOrder.includes(level);
637
- }
638
- log(level, ...message) {
639
- if (level === "" /* NONE */ || !this.allowLevelLog(level)) return;
640
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
641
- console[level](`[${timestamp}] [${level.toLowerCase()}]`, ...message);
642
- }
643
- allowLevelLog(level) {
644
- if (!this.isValidLogLevel(level)) throw new Error(`Invalid log level: ${level}`);
645
- const currentLevelIndex = this.levelsOrder.indexOf(level);
646
- const minLevelIndex = this.levelsOrder.indexOf(this.minLogLevel);
647
- return currentLevelIndex >= minLevelIndex;
648
- }
649
- debug(...message) {
650
- this.log("debug" /* DEBUG */, ...message);
651
- }
652
- info(...message) {
653
- this.log("info" /* INFO */, ...message);
654
- }
655
- warn(...message) {
656
- this.log("warn" /* WARN */, ...message);
657
- }
658
- error(...message) {
659
- this.log("error" /* ERROR */, ...message);
660
- }
791
+ //#endregion
792
+ //#region src/logger.ts
793
+ let LogLevel = /* @__PURE__ */ function(LogLevel$1) {
794
+ LogLevel$1["NONE"] = "";
795
+ LogLevel$1["DEBUG"] = "debug";
796
+ LogLevel$1["INFO"] = "info";
797
+ LogLevel$1["WARN"] = "warn";
798
+ LogLevel$1["ERROR"] = "error";
799
+ return LogLevel$1;
800
+ }({});
801
+ var Logger = class Logger {
802
+ constructor() {
803
+ this.minLogLevel = LogLevel.INFO;
804
+ this.levelsOrder = [
805
+ LogLevel.NONE,
806
+ LogLevel.DEBUG,
807
+ LogLevel.INFO,
808
+ LogLevel.WARN,
809
+ LogLevel.ERROR
810
+ ];
811
+ const envLevel = process.env.LOG_LEVEL?.toLowerCase();
812
+ this.minLogLevel = envLevel && this.isValidLogLevel(envLevel) ? envLevel : LogLevel.INFO;
813
+ }
814
+ static getInstance() {
815
+ if (!Logger.instance) Logger.instance = new Logger();
816
+ return Logger.instance;
817
+ }
818
+ setMinLogLevel(level) {
819
+ if (!this.isValidLogLevel(level)) throw new Error(`Invalid log level: ${level}`);
820
+ this.minLogLevel = level;
821
+ }
822
+ isValidLogLevel(level) {
823
+ return this.levelsOrder.includes(level);
824
+ }
825
+ log(level, ...message) {
826
+ if (level === LogLevel.NONE || !this.allowLevelLog(level)) return;
827
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
828
+ console[level](`[${timestamp}] [${level.toLowerCase()}]`, ...message);
829
+ }
830
+ allowLevelLog(level) {
831
+ if (!this.isValidLogLevel(level)) throw new Error(`Invalid log level: ${level}`);
832
+ return this.levelsOrder.indexOf(level) >= this.levelsOrder.indexOf(this.minLogLevel);
833
+ }
834
+ debug(...message) {
835
+ this.log(LogLevel.DEBUG, ...message);
836
+ }
837
+ info(...message) {
838
+ this.log(LogLevel.INFO, ...message);
839
+ }
840
+ warn(...message) {
841
+ this.log(LogLevel.WARN, ...message);
842
+ }
843
+ error(...message) {
844
+ this.log(LogLevel.ERROR, ...message);
845
+ }
661
846
  };
662
847
 
663
- // src/websocket.ts
664
- import { EventEmitter } from "events";
665
- import WebSocketClient from "ws";
848
+ //#endregion
849
+ //#region src/websocket.ts
666
850
  var WebsocketEventEmitter = class {
667
- constructor() {
668
- this.eventEmitter = new EventEmitter();
669
- }
670
- /* eslint-disable @typescript-eslint/no-explicit-any */
671
- on(event, listener) {
672
- this.eventEmitter.on(event, listener);
673
- }
674
- /* eslint-disable @typescript-eslint/no-explicit-any */
675
- off(event, listener) {
676
- this.eventEmitter.off(event, listener);
677
- }
678
- /* eslint-disable @typescript-eslint/no-explicit-any */
679
- emit(event, ...args) {
680
- this.eventEmitter.emit(event, ...args);
681
- }
851
+ constructor() {
852
+ this.eventEmitter = new EventEmitter();
853
+ }
854
+ on(event, listener) {
855
+ this.eventEmitter.on(event, listener);
856
+ }
857
+ off(event, listener) {
858
+ this.eventEmitter.off(event, listener);
859
+ }
860
+ emit(event, ...args) {
861
+ this.eventEmitter.emit(event, ...args);
862
+ }
682
863
  };
683
- var WebsocketCommon = class _WebsocketCommon extends WebsocketEventEmitter {
684
- constructor(configuration, connectionPool = []) {
685
- super();
686
- this.configuration = configuration;
687
- this.connectionQueue = [];
688
- this.queueProcessing = false;
689
- this.connectionTimers = /* @__PURE__ */ new Map();
690
- this.roundRobinIndex = 0;
691
- this.logger = Logger.getInstance();
692
- this.connectionPool = connectionPool;
693
- this.mode = this.configuration?.mode ?? "single";
694
- this.poolSize = this.mode === "pool" && this.configuration?.poolSize ? this.configuration.poolSize : 1;
695
- if (!connectionPool || connectionPool.length === 0) this.initializePool(this.poolSize);
696
- }
697
- static {
698
- this.MAX_CONNECTION_DURATION = 23 * 60 * 60 * 1e3;
699
- }
700
- /**
701
- * Initializes the WebSocket connection pool by creating a specified number of connection objects
702
- * and adding them to the `connectionPool` array. Each connection object has the following properties:
703
- * - `closeInitiated`: a boolean indicating whether the connection has been closed
704
- * - `reconnectionPending`: a boolean indicating whether a reconnection is pending
705
- * - `pendingRequests`: a Map that tracks pending requests for the connection
706
- * @param size - The number of connection objects to create and add to the pool.
707
- * @returns void
708
- */
709
- initializePool(size) {
710
- for (let i = 0; i < size; i++) {
711
- this.connectionPool.push({
712
- id: randomString(),
713
- closeInitiated: false,
714
- reconnectionPending: false,
715
- renewalPending: false,
716
- pendingRequests: /* @__PURE__ */ new Map(),
717
- pendingSubscriptions: []
718
- });
719
- }
720
- }
721
- /**
722
- * Retrieves available WebSocket connections based on the connection mode and readiness.
723
- * In 'single' mode, returns the first connection in the pool.
724
- * In 'pool' mode, filters and returns connections that are ready for use.
725
- * @param allowNonEstablishedWebsockets - Optional flag to include non-established WebSocket connections.
726
- * @returns An array of available WebSocket connections.
727
- */
728
- getAvailableConnections(allowNonEstablishedWebsockets = false) {
729
- if (this.mode === "single") return [this.connectionPool[0]];
730
- const availableConnections = this.connectionPool.filter(
731
- (connection) => this.isConnectionReady(connection, allowNonEstablishedWebsockets)
732
- );
733
- return availableConnections;
734
- }
735
- /**
736
- * Gets a WebSocket connection from the pool or single connection.
737
- * If the connection mode is 'single', it returns the first connection in the pool.
738
- * If the connection mode is 'pool', it returns an available connection from the pool,
739
- * using a round-robin selection strategy. If no available connections are found, it throws an error.
740
- * @param allowNonEstablishedWebsockets - A boolean indicating whether to allow connections that are not established.
741
- * @returns {WebsocketConnection} The selected WebSocket connection.
742
- */
743
- getConnection(allowNonEstablishedWebsockets = false) {
744
- const availableConnections = this.getAvailableConnections(allowNonEstablishedWebsockets);
745
- if (availableConnections.length === 0) {
746
- throw new Error("No available Websocket connections are ready.");
747
- }
748
- const selectedConnection = availableConnections[this.roundRobinIndex % availableConnections.length];
749
- this.roundRobinIndex = (this.roundRobinIndex + 1) % availableConnections.length;
750
- return selectedConnection;
751
- }
752
- /**
753
- * Checks if the provided WebSocket connection is ready for use.
754
- * A connection is considered ready if it is open, has no pending reconnection, and has not been closed.
755
- * @param connection - The WebSocket connection to check.
756
- * @param allowNonEstablishedWebsockets - An optional flag to allow non-established WebSocket connections.
757
- * @returns `true` if the connection is ready, `false` otherwise.
758
- */
759
- isConnectionReady(connection, allowNonEstablishedWebsockets = false) {
760
- return (allowNonEstablishedWebsockets || connection.ws?.readyState === WebSocketClient.OPEN) && !connection.reconnectionPending && !connection.closeInitiated;
761
- }
762
- /**
763
- * Schedules a timer for a WebSocket connection and tracks it
764
- * @param connection WebSocket client instance
765
- * @param callback Function to execute when timer triggers
766
- * @param delay Time in milliseconds before callback execution
767
- * @param type Timer type ('timeout' or 'interval')
768
- * @returns Timer handle
769
- */
770
- scheduleTimer(connection, callback, delay2, type = "timeout") {
771
- let timers = this.connectionTimers.get(connection);
772
- if (!timers) {
773
- timers = /* @__PURE__ */ new Set();
774
- this.connectionTimers.set(connection, timers);
775
- }
776
- const timerRecord = { type };
777
- const wrappedTimeout = () => {
778
- try {
779
- callback();
780
- } finally {
781
- timers.delete(timerRecord);
782
- }
783
- };
784
- let timer;
785
- if (type === "timeout") timer = setTimeout(wrappedTimeout, delay2);
786
- else timer = setInterval(callback, delay2);
787
- timerRecord.timer = timer;
788
- timers.add(timerRecord);
789
- return timer;
790
- }
791
- /**
792
- * Clears all timers associated with a WebSocket connection.
793
- * @param connection - The WebSocket client instance to clear timers for.
794
- * @returns void
795
- */
796
- clearTimers(connection) {
797
- const timers = this.connectionTimers.get(connection);
798
- if (timers) {
799
- timers.forEach(({ timer, type }) => {
800
- if (type === "timeout") clearTimeout(timer);
801
- else if (type === "interval") clearInterval(timer);
802
- });
803
- this.connectionTimers.delete(connection);
804
- }
805
- }
806
- /**
807
- * Processes the connection queue, reconnecting or renewing connections as needed.
808
- * This method is responsible for iterating through the connection queue and initiating
809
- * the reconnection or renewal process for each connection in the queue. It throttles
810
- * the queue processing to avoid overwhelming the server with too many connection
811
- * requests at once.
812
- * @param throttleRate - The time in milliseconds to wait between processing each
813
- * connection in the queue.
814
- * @returns A Promise that resolves when the queue has been fully processed.
815
- */
816
- async processQueue(throttleRate = 1e3) {
817
- if (this.queueProcessing) return;
818
- this.queueProcessing = true;
819
- while (this.connectionQueue.length > 0) {
820
- const { connection, url, isRenewal } = this.connectionQueue.shift();
821
- this.initConnect(url, isRenewal, connection);
822
- await delay(throttleRate);
823
- }
824
- this.queueProcessing = false;
825
- }
826
- /**
827
- * Enqueues a reconnection or renewal for a WebSocket connection.
828
- * This method adds the connection, URL, and renewal flag to the connection queue,
829
- * and then calls the `processQueue` method to initiate the reconnection or renewal
830
- * process.
831
- * @param connection - The WebSocket connection to reconnect or renew.
832
- * @param url - The URL to use for the reconnection or renewal.
833
- * @param isRenewal - A flag indicating whether this is a renewal (true) or a reconnection (false).
834
- */
835
- enqueueReconnection(connection, url, isRenewal) {
836
- this.connectionQueue.push({ connection, url, isRenewal });
837
- this.processQueue();
838
- }
839
- /**
840
- * Gracefully closes a WebSocket connection after pending requests complete.
841
- * This method waits for any pending requests to complete before closing the connection.
842
- * It sets up a timeout to force-close the connection after 30 seconds if the pending requests
843
- * do not complete. Once all pending requests are completed, the connection is closed.
844
- * @param connectionToClose - The WebSocket client instance to close.
845
- * @param WebsocketConnectionToClose - The WebSocket connection to close.
846
- * @param connection - The WebSocket connection to close.
847
- * @returns Promise that resolves when the connection is closed.
848
- */
849
- async closeConnectionGracefully(WebsocketConnectionToClose, connection) {
850
- if (!WebsocketConnectionToClose || !connection) return;
851
- this.logger.debug(
852
- `Waiting for pending requests to complete before disconnecting websocket on connection ${connection.id}.`
853
- );
854
- const closePromise = new Promise((resolve) => {
855
- this.scheduleTimer(
856
- WebsocketConnectionToClose,
857
- () => {
858
- this.logger.warn(
859
- `Force-closing websocket connection after 30 seconds on connection ${connection.id}.`
860
- );
861
- resolve();
862
- },
863
- 3e4
864
- );
865
- this.scheduleTimer(
866
- WebsocketConnectionToClose,
867
- () => {
868
- if (connection.pendingRequests.size === 0) {
869
- this.logger.debug(
870
- `All pending requests completed, closing websocket connection on connection ${connection.id}.`
871
- );
872
- resolve();
873
- }
874
- },
875
- 1e3,
876
- "interval"
877
- );
878
- });
879
- await closePromise;
880
- this.logger.info(`Closing Websocket connection on connection ${connection.id}.`);
881
- WebsocketConnectionToClose.close();
882
- this.cleanup(WebsocketConnectionToClose);
883
- }
884
- /**
885
- * Attempts to re-establish a session for a WebSocket connection.
886
- * If a session logon request exists and the connection is not already logged on,
887
- * it sends an authentication request and updates the connection's logged-on status.
888
- * @param connection - The WebSocket connection to re-authenticate.
889
- * @private
890
- */
891
- async sessionReLogon(connection) {
892
- const req = connection.sessionLogonReq;
893
- if (req && !connection.isSessionLoggedOn) {
894
- const data = buildWebsocketAPIMessage(
895
- this.configuration,
896
- req.method,
897
- req.payload,
898
- req.options
899
- );
900
- this.logger.debug(`Session re-logon on connection ${connection.id}`, data);
901
- try {
902
- await this.send(
903
- JSON.stringify(data),
904
- data.id,
905
- true,
906
- this.configuration.timeout,
907
- connection
908
- );
909
- this.logger.debug(
910
- `Session re-logon on connection ${connection.id} was successful.`
911
- );
912
- connection.isSessionLoggedOn = true;
913
- } catch (err) {
914
- this.logger.error(`Session re-logon on connection ${connection.id} failed:`, err);
915
- }
916
- }
917
- }
918
- /**
919
- * Cleans up WebSocket connection resources.
920
- * Removes all listeners and clears any associated timers for the provided WebSocket client.
921
- * @param ws - The WebSocket client to clean up.
922
- * @returns void
923
- */
924
- cleanup(ws) {
925
- if (ws) {
926
- ws.removeAllListeners();
927
- this.clearTimers(ws);
928
- }
929
- }
930
- /**
931
- * Handles incoming WebSocket messages
932
- * @param data Raw message data received
933
- * @param connection Websocket connection
934
- */
935
- onMessage(data, connection) {
936
- this.emit("message", data.toString(), connection);
937
- }
938
- /**
939
- * Handles the opening of a WebSocket connection.
940
- * @param url - The URL of the WebSocket server.
941
- * @param targetConnection - The WebSocket connection being opened.
942
- * @param oldWSConnection - The WebSocket client instance associated with the old connection.
943
- */
944
- onOpen(url, targetConnection, oldWSConnection) {
945
- this.logger.info(
946
- `Connected to the Websocket Server with id ${targetConnection.id}: ${url}`
947
- );
948
- if (targetConnection.renewalPending) {
949
- targetConnection.renewalPending = false;
950
- this.closeConnectionGracefully(oldWSConnection, targetConnection);
951
- } else if (targetConnection.closeInitiated) {
952
- this.closeConnectionGracefully(targetConnection.ws, targetConnection);
953
- } else {
954
- targetConnection.reconnectionPending = false;
955
- this.emit("open", this);
956
- }
957
- this.sessionReLogon(targetConnection);
958
- }
959
- /**
960
- * Returns the URL to use when reconnecting.
961
- * Derived classes should override this to provide dynamic URLs.
962
- * @param defaultURL The URL originally passed during the first connection.
963
- * @param targetConnection The WebSocket connection being connected.
964
- * @returns The URL to reconnect to.
965
- */
966
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
967
- getReconnectURL(defaultURL, targetConnection) {
968
- return defaultURL;
969
- }
970
- /**
971
- * Connects all WebSocket connections in the pool
972
- * @param url - The Websocket server URL.
973
- * @returns A promise that resolves when all connections are established.
974
- */
975
- async connectPool(url) {
976
- const connectPromises = this.connectionPool.map(
977
- (connection) => new Promise((resolve, reject) => {
978
- this.initConnect(url, false, connection);
979
- connection.ws?.on("open", () => resolve());
980
- connection.ws?.on("error", (err) => reject(err));
981
- connection.ws?.on(
982
- "close",
983
- () => reject(new Error("Connection closed unexpectedly."))
984
- );
985
- })
986
- );
987
- await Promise.all(connectPromises);
988
- }
989
- /**
990
- * Creates a new WebSocket client instance.
991
- * @param url - The URL to connect to.
992
- * @returns A new WebSocket client instance.
993
- */
994
- createWebSocket(url) {
995
- const wsClientOptions = {
996
- perMessageDeflate: this.configuration?.compression,
997
- agent: this.configuration?.agent
998
- };
999
- if (this.configuration.userAgent)
1000
- wsClientOptions.headers = { "User-Agent": this.configuration.userAgent };
1001
- return new WebSocketClient(url, wsClientOptions);
1002
- }
1003
- /**
1004
- * Initializes a WebSocket connection.
1005
- * @param url - The Websocket server URL.
1006
- * @param isRenewal - Whether this is a connection renewal.
1007
- * @param connection - An optional WebSocket connection to use.
1008
- * @returns The WebSocket connection.
1009
- */
1010
- initConnect(url, isRenewal = false, connection) {
1011
- const targetConnection = connection || this.getConnection();
1012
- if (targetConnection.renewalPending && isRenewal) {
1013
- this.logger.warn(
1014
- `Connection renewal with id ${targetConnection.id} is already in progress`
1015
- );
1016
- return;
1017
- }
1018
- if (targetConnection.ws && targetConnection.ws.readyState === WebSocketClient.OPEN && !isRenewal) {
1019
- this.logger.warn(`Connection with id ${targetConnection.id} already exists`);
1020
- return;
1021
- }
1022
- const ws = this.createWebSocket(url);
1023
- this.logger.info(
1024
- `Establishing Websocket connection with id ${targetConnection.id} to: ${url}`
1025
- );
1026
- if (isRenewal) targetConnection.renewalPending = true;
1027
- else targetConnection.ws = ws;
1028
- targetConnection.isSessionLoggedOn = false;
1029
- this.scheduleTimer(
1030
- ws,
1031
- () => {
1032
- this.logger.info(`Renewing Websocket connection with id ${targetConnection.id}`);
1033
- targetConnection.isSessionLoggedOn = false;
1034
- this.enqueueReconnection(
1035
- targetConnection,
1036
- this.getReconnectURL(url, targetConnection),
1037
- true
1038
- );
1039
- },
1040
- _WebsocketCommon.MAX_CONNECTION_DURATION
1041
- );
1042
- ws.on("open", () => {
1043
- const oldWSConnection = targetConnection.ws;
1044
- if (targetConnection.renewalPending) targetConnection.ws = ws;
1045
- this.onOpen(url, targetConnection, oldWSConnection);
1046
- });
1047
- ws.on("message", (data) => {
1048
- this.onMessage(data.toString(), targetConnection);
1049
- });
1050
- ws.on("ping", () => {
1051
- this.logger.debug("Received PING from server");
1052
- this.emit("ping");
1053
- ws.pong();
1054
- this.logger.debug("Responded PONG to server's PING message");
1055
- });
1056
- ws.on("pong", () => {
1057
- this.logger.debug("Received PONG from server");
1058
- this.emit("pong");
1059
- });
1060
- ws.on("error", (err) => {
1061
- this.logger.error("Received error from server");
1062
- this.logger.error(err);
1063
- this.emit("error", err);
1064
- });
1065
- ws.on("close", (closeEventCode, reason) => {
1066
- this.emit("close", closeEventCode, reason);
1067
- if (!targetConnection.closeInitiated && !isRenewal) {
1068
- this.cleanup(ws);
1069
- this.logger.warn(
1070
- `Connection with id ${targetConnection.id} closed due to ${closeEventCode}: ${reason}`
1071
- );
1072
- this.scheduleTimer(
1073
- ws,
1074
- () => {
1075
- this.logger.info(
1076
- `Reconnecting conection with id ${targetConnection.id} to the server.`
1077
- );
1078
- targetConnection.isSessionLoggedOn = false;
1079
- targetConnection.reconnectionPending = true;
1080
- this.enqueueReconnection(
1081
- targetConnection,
1082
- this.getReconnectURL(url, targetConnection),
1083
- false
1084
- );
1085
- },
1086
- this.configuration?.reconnectDelay ?? 5e3
1087
- );
1088
- }
1089
- });
1090
- return targetConnection;
1091
- }
1092
- /**
1093
- * Checks if the WebSocket connection is currently open.
1094
- * @param connection - An optional WebSocket connection to check. If not provided, the entire connection pool is checked.
1095
- * @returns `true` if the connection is open, `false` otherwise.
1096
- */
1097
- isConnected(connection) {
1098
- const connectionPool = connection ? [connection] : this.connectionPool;
1099
- return connectionPool.some((connection2) => this.isConnectionReady(connection2));
1100
- }
1101
- /**
1102
- * Disconnects from the WebSocket server.
1103
- * If there is no active connection, a warning is logged.
1104
- * Otherwise, all connections in the connection pool are closed gracefully,
1105
- * and a message is logged indicating that the connection has been disconnected.
1106
- * @returns A Promise that resolves when all connections have been closed.
1107
- * @throws Error if the WebSocket client is not set.
1108
- */
1109
- async disconnect() {
1110
- if (!this.isConnected()) this.logger.warn("No connection to close.");
1111
- else {
1112
- this.connectionPool.forEach((connection) => {
1113
- connection.closeInitiated = true;
1114
- connection.isSessionLoggedOn = false;
1115
- connection.sessionLogonReq = void 0;
1116
- });
1117
- const disconnectPromises = this.connectionPool.map(
1118
- (connection) => this.closeConnectionGracefully(connection.ws, connection)
1119
- );
1120
- await Promise.all(disconnectPromises);
1121
- this.logger.info("Disconnected with Binance Websocket Server");
1122
- }
1123
- }
1124
- /**
1125
- * Sends a ping message to all connected Websocket servers in the pool.
1126
- * If no connections are ready, a warning is logged.
1127
- * For each active connection, the ping message is sent, and debug logs provide details.
1128
- * @throws Error if a Websocket client is not set for a connection.
1129
- */
1130
- pingServer() {
1131
- const connectedConnections = this.connectionPool.filter(
1132
- (connection) => this.isConnected(connection)
1133
- );
1134
- if (connectedConnections.length === 0) {
1135
- this.logger.warn("Ping only can be sent when connection is ready.");
1136
- return;
1137
- }
1138
- this.logger.debug("Sending PING to all connected Websocket servers.");
1139
- connectedConnections.forEach((connection) => {
1140
- if (connection.ws) {
1141
- connection.ws.ping();
1142
- this.logger.debug(`PING sent to connection with id ${connection.id}`);
1143
- } else {
1144
- this.logger.error("WebSocket Client not set for a connection.");
1145
- }
1146
- });
1147
- }
1148
- /**
1149
- * Sends a payload through the WebSocket connection.
1150
- * @param payload - Message to send.
1151
- * @param id - Optional request identifier.
1152
- * @param promiseBased - Whether to return a promise.
1153
- * @param timeout - Timeout duration in milliseconds.
1154
- * @param connection - The WebSocket connection to use.
1155
- * @returns A promise if `promiseBased` is true, void otherwise.
1156
- * @throws Error if not connected or WebSocket client is not set.
1157
- */
1158
- send(payload, id, promiseBased = true, timeout = 5e3, connection) {
1159
- if (!this.isConnected(connection)) {
1160
- const errorMsg = "Unable to send message \u2014 connection is not available.";
1161
- this.logger.warn(errorMsg);
1162
- if (promiseBased) return Promise.reject(new Error(errorMsg));
1163
- else throw new Error(errorMsg);
1164
- }
1165
- const connectionToUse = connection ?? this.getConnection();
1166
- if (!connectionToUse.ws) {
1167
- const errorMsg = "Websocket Client not set";
1168
- this.logger.error(errorMsg);
1169
- if (promiseBased) return Promise.reject(new Error(errorMsg));
1170
- else throw new Error(errorMsg);
1171
- }
1172
- connectionToUse.ws.send(payload);
1173
- if (promiseBased) {
1174
- return new Promise((resolve, reject) => {
1175
- if (!id) return reject(new Error("id is required for promise-based sending."));
1176
- const timeoutHandle = setTimeout(() => {
1177
- if (connectionToUse.pendingRequests.has(id)) {
1178
- connectionToUse.pendingRequests.delete(id);
1179
- reject(new Error(`Request timeout for id: ${id}`));
1180
- }
1181
- }, timeout);
1182
- connectionToUse.pendingRequests.set(id, {
1183
- resolve: (v) => {
1184
- clearTimeout(timeoutHandle);
1185
- resolve(v);
1186
- },
1187
- reject: (e) => {
1188
- clearTimeout(timeoutHandle);
1189
- reject(e);
1190
- }
1191
- });
1192
- });
1193
- }
1194
- }
864
+ var WebsocketCommon = class WebsocketCommon extends WebsocketEventEmitter {
865
+ static {
866
+ this.MAX_CONNECTION_DURATION = 1380 * 60 * 1e3;
867
+ }
868
+ constructor(configuration, connectionPool = []) {
869
+ super();
870
+ this.configuration = configuration;
871
+ this.connectionQueue = [];
872
+ this.queueProcessing = false;
873
+ this.connectionTimers = /* @__PURE__ */ new Map();
874
+ this.roundRobinIndex = 0;
875
+ this.logger = Logger.getInstance();
876
+ this.connectionPool = connectionPool;
877
+ this.mode = this.configuration?.mode ?? "single";
878
+ this.poolSize = this.mode === "pool" && this.configuration?.poolSize ? this.configuration.poolSize : 1;
879
+ if (!connectionPool || connectionPool.length === 0) this.initializePool(this.poolSize);
880
+ }
881
+ /**
882
+ * Initializes the WebSocket connection pool by creating a specified number of connection objects
883
+ * and adding them to the `connectionPool` array. Each connection object has the following properties:
884
+ * - `closeInitiated`: a boolean indicating whether the connection has been closed
885
+ * - `reconnectionPending`: a boolean indicating whether a reconnection is pending
886
+ * - `pendingRequests`: a Map that tracks pending requests for the connection
887
+ * @param size - The number of connection objects to create and add to the pool.
888
+ * @returns void
889
+ */
890
+ initializePool(size) {
891
+ for (let i = 0; i < size; i++) this.connectionPool.push({
892
+ id: randomString(),
893
+ closeInitiated: false,
894
+ reconnectionPending: false,
895
+ renewalPending: false,
896
+ pendingRequests: /* @__PURE__ */ new Map(),
897
+ pendingSubscriptions: []
898
+ });
899
+ }
900
+ /**
901
+ * Retrieves available WebSocket connections based on the connection mode and readiness.
902
+ * In 'single' mode, returns the first connection in the pool.
903
+ * In 'pool' mode, filters and returns connections that are ready for use.
904
+ * @param allowNonEstablishedWebsockets - Optional flag to include non-established WebSocket connections.
905
+ * @returns An array of available WebSocket connections.
906
+ */
907
+ getAvailableConnections(allowNonEstablishedWebsockets = false) {
908
+ if (this.mode === "single") return [this.connectionPool[0]];
909
+ return this.connectionPool.filter((connection) => this.isConnectionReady(connection, allowNonEstablishedWebsockets));
910
+ }
911
+ /**
912
+ * Gets a WebSocket connection from the pool or single connection.
913
+ * If the connection mode is 'single', it returns the first connection in the pool.
914
+ * If the connection mode is 'pool', it returns an available connection from the pool,
915
+ * using a round-robin selection strategy. If no available connections are found, it throws an error.
916
+ * @param allowNonEstablishedWebsockets - A boolean indicating whether to allow connections that are not established.
917
+ * @returns {WebsocketConnection} The selected WebSocket connection.
918
+ */
919
+ getConnection(allowNonEstablishedWebsockets = false) {
920
+ const availableConnections = this.getAvailableConnections(allowNonEstablishedWebsockets);
921
+ if (availableConnections.length === 0) throw new Error("No available Websocket connections are ready.");
922
+ const selectedConnection = availableConnections[this.roundRobinIndex % availableConnections.length];
923
+ this.roundRobinIndex = (this.roundRobinIndex + 1) % availableConnections.length;
924
+ return selectedConnection;
925
+ }
926
+ /**
927
+ * Checks if the provided WebSocket connection is ready for use.
928
+ * A connection is considered ready if it is open, has no pending reconnection, and has not been closed.
929
+ * @param connection - The WebSocket connection to check.
930
+ * @param allowNonEstablishedWebsockets - An optional flag to allow non-established WebSocket connections.
931
+ * @returns `true` if the connection is ready, `false` otherwise.
932
+ */
933
+ isConnectionReady(connection, allowNonEstablishedWebsockets = false) {
934
+ return (allowNonEstablishedWebsockets || connection.ws?.readyState === WebSocketClient.OPEN) && !connection.reconnectionPending && !connection.closeInitiated;
935
+ }
936
+ /**
937
+ * Schedules a timer for a WebSocket connection and tracks it
938
+ * @param connection WebSocket client instance
939
+ * @param callback Function to execute when timer triggers
940
+ * @param delay Time in milliseconds before callback execution
941
+ * @param type Timer type ('timeout' or 'interval')
942
+ * @returns Timer handle
943
+ */
944
+ scheduleTimer(connection, callback, delay$1, type = "timeout") {
945
+ let timers = this.connectionTimers.get(connection);
946
+ if (!timers) {
947
+ timers = /* @__PURE__ */ new Set();
948
+ this.connectionTimers.set(connection, timers);
949
+ }
950
+ const timerRecord = { type };
951
+ const wrappedTimeout = () => {
952
+ try {
953
+ callback();
954
+ } finally {
955
+ timers.delete(timerRecord);
956
+ }
957
+ };
958
+ let timer;
959
+ if (type === "timeout") timer = setTimeout(wrappedTimeout, delay$1);
960
+ else timer = setInterval(callback, delay$1);
961
+ timerRecord.timer = timer;
962
+ timers.add(timerRecord);
963
+ return timer;
964
+ }
965
+ /**
966
+ * Clears all timers associated with a WebSocket connection.
967
+ * @param connection - The WebSocket client instance to clear timers for.
968
+ * @returns void
969
+ */
970
+ clearTimers(connection) {
971
+ const timers = this.connectionTimers.get(connection);
972
+ if (timers) {
973
+ timers.forEach(({ timer, type }) => {
974
+ if (type === "timeout") clearTimeout(timer);
975
+ else if (type === "interval") clearInterval(timer);
976
+ });
977
+ this.connectionTimers.delete(connection);
978
+ }
979
+ }
980
+ /**
981
+ * Processes the connection queue, reconnecting or renewing connections as needed.
982
+ * This method is responsible for iterating through the connection queue and initiating
983
+ * the reconnection or renewal process for each connection in the queue. It throttles
984
+ * the queue processing to avoid overwhelming the server with too many connection
985
+ * requests at once.
986
+ * @param throttleRate - The time in milliseconds to wait between processing each
987
+ * connection in the queue.
988
+ * @returns A Promise that resolves when the queue has been fully processed.
989
+ */
990
+ async processQueue(throttleRate = 1e3) {
991
+ if (this.queueProcessing) return;
992
+ this.queueProcessing = true;
993
+ while (this.connectionQueue.length > 0) {
994
+ const { connection, url, isRenewal } = this.connectionQueue.shift();
995
+ this.initConnect(url, isRenewal, connection);
996
+ await delay(throttleRate);
997
+ }
998
+ this.queueProcessing = false;
999
+ }
1000
+ /**
1001
+ * Enqueues a reconnection or renewal for a WebSocket connection.
1002
+ * This method adds the connection, URL, and renewal flag to the connection queue,
1003
+ * and then calls the `processQueue` method to initiate the reconnection or renewal
1004
+ * process.
1005
+ * @param connection - The WebSocket connection to reconnect or renew.
1006
+ * @param url - The URL to use for the reconnection or renewal.
1007
+ * @param isRenewal - A flag indicating whether this is a renewal (true) or a reconnection (false).
1008
+ */
1009
+ enqueueReconnection(connection, url, isRenewal) {
1010
+ this.connectionQueue.push({
1011
+ connection,
1012
+ url,
1013
+ isRenewal
1014
+ });
1015
+ this.processQueue();
1016
+ }
1017
+ /**
1018
+ * Gracefully closes a WebSocket connection after pending requests complete.
1019
+ * This method waits for any pending requests to complete before closing the connection.
1020
+ * It sets up a timeout to force-close the connection after 30 seconds if the pending requests
1021
+ * do not complete. Once all pending requests are completed, the connection is closed.
1022
+ * @param connectionToClose - The WebSocket client instance to close.
1023
+ * @param WebsocketConnectionToClose - The WebSocket connection to close.
1024
+ * @param connection - The WebSocket connection to close.
1025
+ * @returns Promise that resolves when the connection is closed.
1026
+ */
1027
+ async closeConnectionGracefully(WebsocketConnectionToClose, connection) {
1028
+ if (!WebsocketConnectionToClose || !connection) return;
1029
+ this.logger.debug(`Waiting for pending requests to complete before disconnecting websocket on connection ${connection.id}.`);
1030
+ await new Promise((resolve) => {
1031
+ this.scheduleTimer(WebsocketConnectionToClose, () => {
1032
+ this.logger.warn(`Force-closing websocket connection after 30 seconds on connection ${connection.id}.`);
1033
+ resolve();
1034
+ }, 3e4);
1035
+ this.scheduleTimer(WebsocketConnectionToClose, () => {
1036
+ if (connection.pendingRequests.size === 0) {
1037
+ this.logger.debug(`All pending requests completed, closing websocket connection on connection ${connection.id}.`);
1038
+ resolve();
1039
+ }
1040
+ }, 1e3, "interval");
1041
+ });
1042
+ this.logger.info(`Closing Websocket connection on connection ${connection.id}.`);
1043
+ WebsocketConnectionToClose.close();
1044
+ this.cleanup(WebsocketConnectionToClose);
1045
+ }
1046
+ /**
1047
+ * Attempts to re-establish a session for a WebSocket connection.
1048
+ * If a session logon request exists and the connection is not already logged on,
1049
+ * it sends an authentication request and updates the connection's logged-on status.
1050
+ * @param connection - The WebSocket connection to re-authenticate.
1051
+ * @private
1052
+ */
1053
+ async sessionReLogon(connection) {
1054
+ const req = connection.sessionLogonReq;
1055
+ if (req && !connection.isSessionLoggedOn) {
1056
+ const data = buildWebsocketAPIMessage(this.configuration, req.method, req.payload, req.options);
1057
+ this.logger.debug(`Session re-logon on connection ${connection.id}`, data);
1058
+ try {
1059
+ await this.send(JSON.stringify(data), data.id, true, this.configuration.timeout, connection);
1060
+ this.logger.debug(`Session re-logon on connection ${connection.id} was successful.`);
1061
+ connection.isSessionLoggedOn = true;
1062
+ } catch (err) {
1063
+ this.logger.error(`Session re-logon on connection ${connection.id} failed:`, err);
1064
+ }
1065
+ }
1066
+ }
1067
+ /**
1068
+ * Cleans up WebSocket connection resources.
1069
+ * Removes all listeners and clears any associated timers for the provided WebSocket client.
1070
+ * @param ws - The WebSocket client to clean up.
1071
+ * @returns void
1072
+ */
1073
+ cleanup(ws) {
1074
+ if (ws) {
1075
+ ws.removeAllListeners();
1076
+ this.clearTimers(ws);
1077
+ }
1078
+ }
1079
+ /**
1080
+ * Handles incoming WebSocket messages
1081
+ * @param data Raw message data received
1082
+ * @param connection Websocket connection
1083
+ */
1084
+ onMessage(data, connection) {
1085
+ this.emit("message", data.toString(), connection);
1086
+ }
1087
+ /**
1088
+ * Handles the opening of a WebSocket connection.
1089
+ * @param url - The URL of the WebSocket server.
1090
+ * @param targetConnection - The WebSocket connection being opened.
1091
+ * @param oldWSConnection - The WebSocket client instance associated with the old connection.
1092
+ */
1093
+ onOpen(url, targetConnection, oldWSConnection) {
1094
+ this.logger.info(`Connected to the Websocket Server with id ${targetConnection.id}: ${url}`);
1095
+ if (targetConnection.renewalPending) {
1096
+ targetConnection.renewalPending = false;
1097
+ this.closeConnectionGracefully(oldWSConnection, targetConnection);
1098
+ } else if (targetConnection.closeInitiated) this.closeConnectionGracefully(targetConnection.ws, targetConnection);
1099
+ else {
1100
+ targetConnection.reconnectionPending = false;
1101
+ this.emit("open", this);
1102
+ }
1103
+ this.sessionReLogon(targetConnection);
1104
+ }
1105
+ /**
1106
+ * Returns the URL to use when reconnecting.
1107
+ * Derived classes should override this to provide dynamic URLs.
1108
+ * @param defaultURL The URL originally passed during the first connection.
1109
+ * @param targetConnection The WebSocket connection being connected.
1110
+ * @returns The URL to reconnect to.
1111
+ */
1112
+ getReconnectURL(defaultURL, targetConnection) {
1113
+ return defaultURL;
1114
+ }
1115
+ /**
1116
+ * Connects all WebSocket connections in the pool
1117
+ * @param url - The Websocket server URL.
1118
+ * @returns A promise that resolves when all connections are established.
1119
+ */
1120
+ async connectPool(url) {
1121
+ const connectPromises = this.connectionPool.map((connection) => new Promise((resolve, reject) => {
1122
+ this.initConnect(url, false, connection);
1123
+ connection.ws?.on("open", () => resolve());
1124
+ connection.ws?.on("error", (err) => reject(err));
1125
+ connection.ws?.on("close", () => reject(/* @__PURE__ */ new Error("Connection closed unexpectedly.")));
1126
+ }));
1127
+ await Promise.all(connectPromises);
1128
+ }
1129
+ /**
1130
+ * Creates a new WebSocket client instance.
1131
+ * @param url - The URL to connect to.
1132
+ * @returns A new WebSocket client instance.
1133
+ */
1134
+ createWebSocket(url) {
1135
+ const wsClientOptions = {
1136
+ perMessageDeflate: this.configuration?.compression,
1137
+ agent: this.configuration?.agent
1138
+ };
1139
+ if (this.configuration.userAgent) wsClientOptions.headers = { "User-Agent": this.configuration.userAgent };
1140
+ return new WebSocketClient(url, wsClientOptions);
1141
+ }
1142
+ /**
1143
+ * Initializes a WebSocket connection.
1144
+ * @param url - The Websocket server URL.
1145
+ * @param isRenewal - Whether this is a connection renewal.
1146
+ * @param connection - An optional WebSocket connection to use.
1147
+ * @returns The WebSocket connection.
1148
+ */
1149
+ initConnect(url, isRenewal = false, connection) {
1150
+ const targetConnection = connection || this.getConnection();
1151
+ if (targetConnection.renewalPending && isRenewal) {
1152
+ this.logger.warn(`Connection renewal with id ${targetConnection.id} is already in progress`);
1153
+ return;
1154
+ }
1155
+ if (targetConnection.ws && targetConnection.ws.readyState === WebSocketClient.OPEN && !isRenewal) {
1156
+ this.logger.warn(`Connection with id ${targetConnection.id} already exists`);
1157
+ return;
1158
+ }
1159
+ const ws = this.createWebSocket(url);
1160
+ this.logger.info(`Establishing Websocket connection with id ${targetConnection.id} to: ${url}`);
1161
+ if (isRenewal) targetConnection.renewalPending = true;
1162
+ else targetConnection.ws = ws;
1163
+ targetConnection.isSessionLoggedOn = false;
1164
+ this.scheduleTimer(ws, () => {
1165
+ this.logger.info(`Renewing Websocket connection with id ${targetConnection.id}`);
1166
+ targetConnection.isSessionLoggedOn = false;
1167
+ this.enqueueReconnection(targetConnection, this.getReconnectURL(url, targetConnection), true);
1168
+ }, WebsocketCommon.MAX_CONNECTION_DURATION);
1169
+ ws.on("open", () => {
1170
+ const oldWSConnection = targetConnection.ws;
1171
+ if (targetConnection.renewalPending) targetConnection.ws = ws;
1172
+ this.onOpen(url, targetConnection, oldWSConnection);
1173
+ });
1174
+ ws.on("message", (data) => {
1175
+ this.onMessage(data.toString(), targetConnection);
1176
+ });
1177
+ ws.on("ping", () => {
1178
+ this.logger.debug("Received PING from server");
1179
+ this.emit("ping");
1180
+ ws.pong();
1181
+ this.logger.debug("Responded PONG to server's PING message");
1182
+ });
1183
+ ws.on("pong", () => {
1184
+ this.logger.debug("Received PONG from server");
1185
+ this.emit("pong");
1186
+ });
1187
+ ws.on("error", (err) => {
1188
+ this.logger.error("Received error from server");
1189
+ this.logger.error(err);
1190
+ this.emit("error", err);
1191
+ });
1192
+ ws.on("close", (closeEventCode, reason) => {
1193
+ this.emit("close", closeEventCode, reason);
1194
+ if (!targetConnection.closeInitiated && !isRenewal) {
1195
+ this.cleanup(ws);
1196
+ this.logger.warn(`Connection with id ${targetConnection.id} closed due to ${closeEventCode}: ${reason}`);
1197
+ this.scheduleTimer(ws, () => {
1198
+ this.logger.info(`Reconnecting conection with id ${targetConnection.id} to the server.`);
1199
+ targetConnection.isSessionLoggedOn = false;
1200
+ targetConnection.reconnectionPending = true;
1201
+ this.enqueueReconnection(targetConnection, this.getReconnectURL(url, targetConnection), false);
1202
+ }, this.configuration?.reconnectDelay ?? 5e3);
1203
+ }
1204
+ });
1205
+ return targetConnection;
1206
+ }
1207
+ /**
1208
+ * Checks if the WebSocket connection is currently open.
1209
+ * @param connection - An optional WebSocket connection to check. If not provided, the entire connection pool is checked.
1210
+ * @returns `true` if the connection is open, `false` otherwise.
1211
+ */
1212
+ isConnected(connection) {
1213
+ return (connection ? [connection] : this.connectionPool).some((connection$1) => this.isConnectionReady(connection$1));
1214
+ }
1215
+ /**
1216
+ * Disconnects from the WebSocket server.
1217
+ * If there is no active connection, a warning is logged.
1218
+ * Otherwise, all connections in the connection pool are closed gracefully,
1219
+ * and a message is logged indicating that the connection has been disconnected.
1220
+ * @returns A Promise that resolves when all connections have been closed.
1221
+ * @throws Error if the WebSocket client is not set.
1222
+ */
1223
+ async disconnect() {
1224
+ if (!this.isConnected()) this.logger.warn("No connection to close.");
1225
+ else {
1226
+ this.connectionPool.forEach((connection) => {
1227
+ connection.closeInitiated = true;
1228
+ connection.isSessionLoggedOn = false;
1229
+ connection.sessionLogonReq = void 0;
1230
+ });
1231
+ const disconnectPromises = this.connectionPool.map((connection) => this.closeConnectionGracefully(connection.ws, connection));
1232
+ await Promise.all(disconnectPromises);
1233
+ this.logger.info("Disconnected with Binance Websocket Server");
1234
+ }
1235
+ }
1236
+ /**
1237
+ * Sends a ping message to all connected Websocket servers in the pool.
1238
+ * If no connections are ready, a warning is logged.
1239
+ * For each active connection, the ping message is sent, and debug logs provide details.
1240
+ * @throws Error if a Websocket client is not set for a connection.
1241
+ */
1242
+ pingServer() {
1243
+ const connectedConnections = this.connectionPool.filter((connection) => this.isConnected(connection));
1244
+ if (connectedConnections.length === 0) {
1245
+ this.logger.warn("Ping only can be sent when connection is ready.");
1246
+ return;
1247
+ }
1248
+ this.logger.debug("Sending PING to all connected Websocket servers.");
1249
+ connectedConnections.forEach((connection) => {
1250
+ if (connection.ws) {
1251
+ connection.ws.ping();
1252
+ this.logger.debug(`PING sent to connection with id ${connection.id}`);
1253
+ } else this.logger.error("WebSocket Client not set for a connection.");
1254
+ });
1255
+ }
1256
+ /**
1257
+ * Sends a payload through the WebSocket connection.
1258
+ * @param payload - Message to send.
1259
+ * @param id - Optional request identifier.
1260
+ * @param promiseBased - Whether to return a promise.
1261
+ * @param timeout - Timeout duration in milliseconds.
1262
+ * @param connection - The WebSocket connection to use.
1263
+ * @returns A promise if `promiseBased` is true, void otherwise.
1264
+ * @throws Error if not connected or WebSocket client is not set.
1265
+ */
1266
+ send(payload, id, promiseBased = true, timeout = 5e3, connection) {
1267
+ if (!this.isConnected(connection)) {
1268
+ const errorMsg = "Unable to send message — connection is not available.";
1269
+ this.logger.warn(errorMsg);
1270
+ if (promiseBased) return Promise.reject(new Error(errorMsg));
1271
+ else throw new Error(errorMsg);
1272
+ }
1273
+ const connectionToUse = connection ?? this.getConnection();
1274
+ if (!connectionToUse.ws) {
1275
+ const errorMsg = "Websocket Client not set";
1276
+ this.logger.error(errorMsg);
1277
+ if (promiseBased) return Promise.reject(new Error(errorMsg));
1278
+ else throw new Error(errorMsg);
1279
+ }
1280
+ connectionToUse.ws.send(payload);
1281
+ if (promiseBased) return new Promise((resolve, reject) => {
1282
+ if (!id) return reject(/* @__PURE__ */ new Error("id is required for promise-based sending."));
1283
+ const timeoutHandle = setTimeout(() => {
1284
+ if (connectionToUse.pendingRequests.has(id)) {
1285
+ connectionToUse.pendingRequests.delete(id);
1286
+ reject(/* @__PURE__ */ new Error(`Request timeout for id: ${id}`));
1287
+ }
1288
+ }, timeout);
1289
+ connectionToUse.pendingRequests.set(id, {
1290
+ resolve: (v) => {
1291
+ clearTimeout(timeoutHandle);
1292
+ resolve(v);
1293
+ },
1294
+ reject: (e) => {
1295
+ clearTimeout(timeoutHandle);
1296
+ reject(e);
1297
+ }
1298
+ });
1299
+ });
1300
+ }
1195
1301
  };
1196
1302
  var WebsocketAPIBase = class extends WebsocketCommon {
1197
- constructor(configuration, connectionPool = []) {
1198
- super(configuration, connectionPool);
1199
- this.isConnecting = false;
1200
- this.streamCallbackMap = /* @__PURE__ */ new Map();
1201
- this.logger = Logger.getInstance();
1202
- this.configuration = configuration;
1203
- }
1204
- /**
1205
- * Prepares the WebSocket URL by adding optional timeUnit parameter
1206
- * @param wsUrl The base WebSocket URL
1207
- * @returns The formatted WebSocket URL with parameters
1208
- */
1209
- prepareURL(wsUrl) {
1210
- let url = wsUrl;
1211
- if (this?.configuration.timeUnit) {
1212
- try {
1213
- const _timeUnit = validateTimeUnit(this.configuration.timeUnit);
1214
- url = `${url}${url.includes("?") ? "&" : "?"}timeUnit=${_timeUnit}`;
1215
- } catch (err) {
1216
- this.logger.error(err);
1217
- }
1218
- }
1219
- return url;
1220
- }
1221
- /**
1222
- * Processes incoming WebSocket messages
1223
- * @param data The raw message data received
1224
- */
1225
- onMessage(data, connection) {
1226
- try {
1227
- const message = JSON.parse(data);
1228
- const { id, status } = message;
1229
- if (id && connection.pendingRequests.has(id)) {
1230
- const request = connection.pendingRequests.get(id);
1231
- connection.pendingRequests.delete(id);
1232
- if (status && status >= 400) {
1233
- request?.reject(message.error);
1234
- } else {
1235
- const response = {
1236
- data: message.result ?? message.response,
1237
- ...message.rateLimits && { rateLimits: message.rateLimits }
1238
- };
1239
- request?.resolve(response);
1240
- }
1241
- } else if ("event" in message && "e" in message["event"] && this.streamCallbackMap.size > 0) {
1242
- this.streamCallbackMap.forEach(
1243
- (callbacks) => callbacks.forEach((callback) => callback(message["event"]))
1244
- );
1245
- } else {
1246
- this.logger.warn("Received response for unknown or timed-out request:", message);
1247
- }
1248
- } catch (error) {
1249
- this.logger.error("Failed to parse WebSocket message:", data, error);
1250
- }
1251
- super.onMessage(data, connection);
1252
- }
1253
- /**
1254
- * Establishes a WebSocket connection to Binance
1255
- * @returns Promise that resolves when connection is established
1256
- * @throws Error if connection times out
1257
- */
1258
- connect() {
1259
- if (this.isConnected()) {
1260
- this.logger.info("WebSocket connection already established");
1261
- return Promise.resolve();
1262
- }
1263
- return new Promise((resolve, reject) => {
1264
- if (this.isConnecting) return;
1265
- this.isConnecting = true;
1266
- const timeout = setTimeout(() => {
1267
- this.isConnecting = false;
1268
- reject(new Error("Websocket connection timed out"));
1269
- }, 1e4);
1270
- this.connectPool(this.prepareURL(this.configuration.wsURL)).then(() => {
1271
- this.isConnecting = false;
1272
- resolve();
1273
- }).catch((error) => {
1274
- this.isConnecting = false;
1275
- reject(error);
1276
- }).finally(() => {
1277
- clearTimeout(timeout);
1278
- });
1279
- });
1280
- }
1281
- async sendMessage(method, payload = {}, options = {}) {
1282
- if (!this.isConnected()) {
1283
- throw new Error("Not connected");
1284
- }
1285
- const isSessionReq = options.isSessionLogon || options.isSessionLogout;
1286
- const connections = isSessionReq ? this.getAvailableConnections() : [this.getConnection()];
1287
- const skipAuth = isSessionReq ? false : this.configuration.autoSessionReLogon && connections[0].isSessionLoggedOn;
1288
- const data = buildWebsocketAPIMessage(
1289
- this.configuration,
1290
- method,
1291
- payload,
1292
- options,
1293
- skipAuth
1294
- );
1295
- this.logger.debug("Send message to Binance WebSocket API Server:", data);
1296
- const responses = await Promise.all(
1297
- connections.map(
1298
- (connection) => this.send(
1299
- JSON.stringify(data),
1300
- data.id,
1301
- true,
1302
- this.configuration.timeout,
1303
- connection
1304
- )
1305
- )
1306
- );
1307
- if (isSessionReq && this.configuration.autoSessionReLogon) {
1308
- connections.forEach((connection) => {
1309
- if (options.isSessionLogon) {
1310
- connection.isSessionLoggedOn = true;
1311
- connection.sessionLogonReq = { method, payload, options };
1312
- } else {
1313
- connection.isSessionLoggedOn = false;
1314
- connection.sessionLogonReq = void 0;
1315
- }
1316
- });
1317
- }
1318
- return connections.length === 1 && !isSessionReq ? responses[0] : responses;
1319
- }
1303
+ constructor(configuration, connectionPool = []) {
1304
+ super(configuration, connectionPool);
1305
+ this.isConnecting = false;
1306
+ this.streamCallbackMap = /* @__PURE__ */ new Map();
1307
+ this.logger = Logger.getInstance();
1308
+ this.configuration = configuration;
1309
+ }
1310
+ /**
1311
+ * Prepares the WebSocket URL by adding optional timeUnit parameter
1312
+ * @param wsUrl The base WebSocket URL
1313
+ * @returns The formatted WebSocket URL with parameters
1314
+ */
1315
+ prepareURL(wsUrl) {
1316
+ let url = wsUrl;
1317
+ if (this?.configuration.timeUnit) try {
1318
+ const _timeUnit = validateTimeUnit(this.configuration.timeUnit);
1319
+ url = `${url}${url.includes("?") ? "&" : "?"}timeUnit=${_timeUnit}`;
1320
+ } catch (err) {
1321
+ this.logger.error(err);
1322
+ }
1323
+ return url;
1324
+ }
1325
+ /**
1326
+ * Processes incoming WebSocket messages
1327
+ * @param data The raw message data received
1328
+ */
1329
+ onMessage(data, connection) {
1330
+ try {
1331
+ const message = JSONParse(data);
1332
+ const { id, status } = message;
1333
+ if (id && connection.pendingRequests.has(id)) {
1334
+ const request = connection.pendingRequests.get(id);
1335
+ connection.pendingRequests.delete(id);
1336
+ if (status && status >= 400) request?.reject(message.error);
1337
+ else {
1338
+ const response = {
1339
+ data: message.result ?? message.response,
1340
+ ...message.rateLimits && { rateLimits: message.rateLimits }
1341
+ };
1342
+ request?.resolve(response);
1343
+ }
1344
+ } else if ("event" in message && "e" in message["event"] && this.streamCallbackMap.size > 0) this.streamCallbackMap.forEach((callbacks) => callbacks.forEach((callback) => callback(message["event"])));
1345
+ else this.logger.warn("Received response for unknown or timed-out request:", message);
1346
+ } catch (error) {
1347
+ this.logger.error("Failed to parse WebSocket message:", data, error);
1348
+ }
1349
+ super.onMessage(data, connection);
1350
+ }
1351
+ /**
1352
+ * Establishes a WebSocket connection to Binance
1353
+ * @returns Promise that resolves when connection is established
1354
+ * @throws Error if connection times out
1355
+ */
1356
+ connect() {
1357
+ if (this.isConnected()) {
1358
+ this.logger.info("WebSocket connection already established");
1359
+ return Promise.resolve();
1360
+ }
1361
+ return new Promise((resolve, reject) => {
1362
+ if (this.isConnecting) return;
1363
+ this.isConnecting = true;
1364
+ const timeout = setTimeout(() => {
1365
+ this.isConnecting = false;
1366
+ reject(/* @__PURE__ */ new Error("Websocket connection timed out"));
1367
+ }, 1e4);
1368
+ this.connectPool(this.prepareURL(this.configuration.wsURL)).then(() => {
1369
+ this.isConnecting = false;
1370
+ resolve();
1371
+ }).catch((error) => {
1372
+ this.isConnecting = false;
1373
+ reject(error);
1374
+ }).finally(() => {
1375
+ clearTimeout(timeout);
1376
+ });
1377
+ });
1378
+ }
1379
+ async sendMessage(method, payload = {}, options = {}) {
1380
+ if (!this.isConnected()) throw new Error("Not connected");
1381
+ const isSessionReq = options.isSessionLogon || options.isSessionLogout;
1382
+ const connections = isSessionReq ? this.getAvailableConnections() : [this.getConnection()];
1383
+ const skipAuth = isSessionReq ? false : this.configuration.autoSessionReLogon && connections[0].isSessionLoggedOn;
1384
+ const data = buildWebsocketAPIMessage(this.configuration, method, payload, options, skipAuth);
1385
+ this.logger.debug("Send message to Binance WebSocket API Server:", data);
1386
+ const responses = await Promise.all(connections.map((connection) => this.send(JSON.stringify(data), data.id, true, this.configuration.timeout, connection)));
1387
+ if (isSessionReq && this.configuration.autoSessionReLogon) connections.forEach((connection) => {
1388
+ if (options.isSessionLogon) {
1389
+ connection.isSessionLoggedOn = true;
1390
+ connection.sessionLogonReq = {
1391
+ method,
1392
+ payload,
1393
+ options
1394
+ };
1395
+ } else {
1396
+ connection.isSessionLoggedOn = false;
1397
+ connection.sessionLogonReq = void 0;
1398
+ }
1399
+ });
1400
+ return connections.length === 1 && !isSessionReq ? responses[0] : responses;
1401
+ }
1320
1402
  };
1321
1403
  var WebsocketStreamsBase = class extends WebsocketCommon {
1322
- constructor(configuration, connectionPool = []) {
1323
- super(configuration, connectionPool);
1324
- this.streamConnectionMap = /* @__PURE__ */ new Map();
1325
- this.streamCallbackMap = /* @__PURE__ */ new Map();
1326
- this.logger = Logger.getInstance();
1327
- this.configuration = configuration;
1328
- this.wsURL = configuration.wsURL;
1329
- }
1330
- /**
1331
- * Formats the WebSocket URL for a given stream or streams.
1332
- * @param streams - Array of stream names to include in the URL.
1333
- * @returns The formatted WebSocket URL with the provided streams.
1334
- */
1335
- prepareURL(streams = []) {
1336
- let url = `${this.wsURL}/stream?streams=${streams.join("/")}`;
1337
- if (this.configuration?.timeUnit) {
1338
- try {
1339
- const _timeUnit = validateTimeUnit(this.configuration.timeUnit);
1340
- url = `${url}${url.includes("?") ? "&" : "?"}timeUnit=${_timeUnit}`;
1341
- } catch (err) {
1342
- this.logger.error(err);
1343
- }
1344
- }
1345
- return url;
1346
- }
1347
- /**
1348
- * Formats the WebSocket URL with stream and configuration parameters to be used for reconnection.
1349
- * @param url - The base WebSocket URL.
1350
- * @param targetConnection - The target WebSocket connection.
1351
- * @returns The formatted WebSocket URL with streams and optional parameters.
1352
- */
1353
- getReconnectURL(url, targetConnection) {
1354
- const streams = Array.from(this.streamConnectionMap.keys()).filter(
1355
- (stream) => this.streamConnectionMap.get(stream) === targetConnection
1356
- );
1357
- return this.prepareURL(streams);
1358
- }
1359
- /**
1360
- * Handles subscription to streams and assigns them to specific connections
1361
- * @param streams Array of stream names to subscribe to
1362
- * @returns Map of connections to streams
1363
- */
1364
- handleStreamAssignment(streams) {
1365
- const connectionStreamMap = /* @__PURE__ */ new Map();
1366
- streams.forEach((stream) => {
1367
- if (!this.streamCallbackMap.has(stream)) this.streamCallbackMap.set(stream, /* @__PURE__ */ new Set());
1368
- let connection = this.streamConnectionMap.get(stream);
1369
- if (!connection || connection.closeInitiated || connection.reconnectionPending) {
1370
- connection = this.getConnection(true);
1371
- this.streamConnectionMap.set(stream, connection);
1372
- }
1373
- if (!connectionStreamMap.has(connection)) connectionStreamMap.set(connection, []);
1374
- connectionStreamMap.get(connection)?.push(stream);
1375
- });
1376
- return connectionStreamMap;
1377
- }
1378
- /**
1379
- * Sends a subscription payload for specified streams on a given connection.
1380
- * @param connection The WebSocket connection to use for sending the subscription.
1381
- * @param streams The streams to subscribe to.
1382
- * @param id Optional ID for the subscription.
1383
- */
1384
- sendSubscriptionPayload(connection, streams, id) {
1385
- const payload = {
1386
- method: "SUBSCRIBE",
1387
- params: streams,
1388
- id: id && /^[0-9a-f]{32}$/.test(id) ? id : randomString()
1389
- };
1390
- this.logger.debug("SUBSCRIBE", payload);
1391
- this.send(JSON.stringify(payload), void 0, false, 0, connection);
1392
- }
1393
- /**
1394
- * Processes pending subscriptions for a given connection.
1395
- * Sends all queued subscriptions in a single payload.
1396
- * @param connection The WebSocket connection to process.
1397
- */
1398
- processPendingSubscriptions(connection) {
1399
- if (connection.pendingSubscriptions && connection.pendingSubscriptions.length > 0) {
1400
- this.logger.info("Processing queued subscriptions for connection");
1401
- this.sendSubscriptionPayload(connection, connection.pendingSubscriptions);
1402
- connection.pendingSubscriptions = [];
1403
- }
1404
- }
1405
- /**
1406
- * Handles incoming WebSocket messages, parsing the data and invoking the appropriate callback function.
1407
- * If the message contains a stream name that is registered in the `streamCallbackMap`, the corresponding
1408
- * callback function is called with the message data.
1409
- * If the message cannot be parsed, an error is logged.
1410
- * @param data The raw WebSocket message data.
1411
- * @param connection The WebSocket connection that received the message.
1412
- */
1413
- onMessage(data, connection) {
1414
- try {
1415
- const parsedData = JSON.parse(data);
1416
- const streamName = parsedData?.stream;
1417
- if (streamName && this.streamCallbackMap.has(streamName))
1418
- this.streamCallbackMap.get(streamName)?.forEach((callback) => callback(parsedData.data));
1419
- } catch (error) {
1420
- this.logger.error("Failed to parse WebSocket message:", data, error);
1421
- }
1422
- super.onMessage(data, connection);
1423
- }
1424
- /**
1425
- * Called when the WebSocket connection is opened.
1426
- * Processes any pending subscriptions for the target connection.
1427
- * @param url The URL of the WebSocket connection.
1428
- * @param targetConnection The WebSocket connection that was opened.
1429
- * @param oldConnection The previous WebSocket connection, if any.
1430
- */
1431
- onOpen(url, targetConnection, oldWSConnection) {
1432
- this.processPendingSubscriptions(targetConnection);
1433
- super.onOpen(url, targetConnection, oldWSConnection);
1434
- }
1435
- /**
1436
- * Connects to the WebSocket server and subscribes to the specified streams.
1437
- * This method returns a Promise that resolves when the connection is established,
1438
- * or rejects with an error if the connection fails to be established within 10 seconds.
1439
- * @param stream - A single stream name or an array of stream names to subscribe to.
1440
- * @returns A Promise that resolves when the connection is established.
1441
- */
1442
- connect(stream = []) {
1443
- const streams = Array.isArray(stream) ? stream : [stream];
1444
- return new Promise((resolve, reject) => {
1445
- const timeout = setTimeout(() => {
1446
- reject(new Error("Websocket connection timed out"));
1447
- }, 1e4);
1448
- this.connectPool(this.prepareURL(streams)).then(() => resolve()).catch((error) => reject(error)).finally(() => clearTimeout(timeout));
1449
- });
1450
- }
1451
- /**
1452
- * Disconnects the WebSocket connection and clears the stream callback map.
1453
- * This method is called to clean up the connection and associated resources.
1454
- */
1455
- async disconnect() {
1456
- this.streamCallbackMap.clear();
1457
- this.streamConnectionMap.clear();
1458
- super.disconnect();
1459
- }
1460
- /**
1461
- * Subscribes to one or multiple WebSocket streams
1462
- * Handles both single and pool modes
1463
- * @param stream Single stream name or array of stream names to subscribe to
1464
- * @param id Optional subscription ID
1465
- * @returns void
1466
- */
1467
- subscribe(stream, id) {
1468
- const streams = (Array.isArray(stream) ? stream : [stream]).filter(
1469
- (stream2) => !this.streamConnectionMap.has(stream2)
1470
- );
1471
- const connectionStreamMap = this.handleStreamAssignment(streams);
1472
- connectionStreamMap.forEach((streams2, connection) => {
1473
- if (!this.isConnected(connection)) {
1474
- this.logger.info(
1475
- `Connection ${connection.id} is not ready. Queuing subscription for streams: ${streams2}`
1476
- );
1477
- connection.pendingSubscriptions?.push(...streams2);
1478
- return;
1479
- }
1480
- this.sendSubscriptionPayload(connection, streams2, id);
1481
- });
1482
- }
1483
- /**
1484
- * Unsubscribes from one or multiple WebSocket streams
1485
- * Handles both single and pool modes
1486
- * @param stream Single stream name or array of stream names to unsubscribe from
1487
- * @param id Optional unsubscription ID
1488
- * @returns void
1489
- */
1490
- unsubscribe(stream, id) {
1491
- const streams = Array.isArray(stream) ? stream : [stream];
1492
- streams.forEach((stream2) => {
1493
- const connection = this.streamConnectionMap.get(stream2);
1494
- if (!connection || !connection.ws || !this.isConnected(connection)) {
1495
- this.logger.warn(`Stream ${stream2} not associated with an active connection.`);
1496
- return;
1497
- }
1498
- if (!this.streamCallbackMap.has(stream2) || this.streamCallbackMap.get(stream2)?.size === 0) {
1499
- const payload = {
1500
- method: "UNSUBSCRIBE",
1501
- params: [stream2],
1502
- id: id && /^[0-9a-f]{32}$/.test(id) ? id : randomString()
1503
- };
1504
- this.logger.debug("UNSUBSCRIBE", payload);
1505
- this.send(JSON.stringify(payload), void 0, false, 0, connection);
1506
- this.streamConnectionMap.delete(stream2);
1507
- this.streamCallbackMap.delete(stream2);
1508
- }
1509
- });
1510
- }
1511
- /**
1512
- * Checks if the specified stream is currently subscribed.
1513
- * @param stream - The name of the stream to check.
1514
- * @returns `true` if the stream is currently subscribed, `false` otherwise.
1515
- */
1516
- isSubscribed(stream) {
1517
- return this.streamConnectionMap.has(stream);
1518
- }
1404
+ constructor(configuration, connectionPool = []) {
1405
+ super(configuration, connectionPool);
1406
+ this.streamConnectionMap = /* @__PURE__ */ new Map();
1407
+ this.streamCallbackMap = /* @__PURE__ */ new Map();
1408
+ this.logger = Logger.getInstance();
1409
+ this.configuration = configuration;
1410
+ this.wsURL = configuration.wsURL;
1411
+ }
1412
+ /**
1413
+ * Formats the WebSocket URL for a given stream or streams.
1414
+ * @param streams - Array of stream names to include in the URL.
1415
+ * @returns The formatted WebSocket URL with the provided streams.
1416
+ */
1417
+ prepareURL(streams = []) {
1418
+ let url = `${this.wsURL}/stream?streams=${streams.join("/")}`;
1419
+ if (this.configuration?.timeUnit) try {
1420
+ const _timeUnit = validateTimeUnit(this.configuration.timeUnit);
1421
+ url = `${url}${url.includes("?") ? "&" : "?"}timeUnit=${_timeUnit}`;
1422
+ } catch (err) {
1423
+ this.logger.error(err);
1424
+ }
1425
+ return url;
1426
+ }
1427
+ /**
1428
+ * Formats the WebSocket URL with stream and configuration parameters to be used for reconnection.
1429
+ * @param url - The base WebSocket URL.
1430
+ * @param targetConnection - The target WebSocket connection.
1431
+ * @returns The formatted WebSocket URL with streams and optional parameters.
1432
+ */
1433
+ getReconnectURL(url, targetConnection) {
1434
+ const streams = Array.from(this.streamConnectionMap.keys()).filter((stream) => this.streamConnectionMap.get(stream) === targetConnection);
1435
+ return this.prepareURL(streams);
1436
+ }
1437
+ /**
1438
+ * Handles subscription to streams and assigns them to specific connections
1439
+ * @param streams Array of stream names to subscribe to
1440
+ * @returns Map of connections to streams
1441
+ */
1442
+ handleStreamAssignment(streams) {
1443
+ const connectionStreamMap = /* @__PURE__ */ new Map();
1444
+ streams.forEach((stream) => {
1445
+ if (!this.streamCallbackMap.has(stream)) this.streamCallbackMap.set(stream, /* @__PURE__ */ new Set());
1446
+ let connection = this.streamConnectionMap.get(stream);
1447
+ if (!connection || connection.closeInitiated || connection.reconnectionPending) {
1448
+ connection = this.getConnection(true);
1449
+ this.streamConnectionMap.set(stream, connection);
1450
+ }
1451
+ if (!connectionStreamMap.has(connection)) connectionStreamMap.set(connection, []);
1452
+ connectionStreamMap.get(connection)?.push(stream);
1453
+ });
1454
+ return connectionStreamMap;
1455
+ }
1456
+ /**
1457
+ * Sends a subscription payload for specified streams on a given connection.
1458
+ * @param connection The WebSocket connection to use for sending the subscription.
1459
+ * @param streams The streams to subscribe to.
1460
+ * @param id Optional ID for the subscription.
1461
+ */
1462
+ sendSubscriptionPayload(connection, streams, id) {
1463
+ const payload = {
1464
+ method: "SUBSCRIBE",
1465
+ params: streams,
1466
+ id: id && /^[0-9a-f]{32}$/.test(id) ? id : randomString()
1467
+ };
1468
+ this.logger.debug("SUBSCRIBE", payload);
1469
+ this.send(JSON.stringify(payload), void 0, false, 0, connection);
1470
+ }
1471
+ /**
1472
+ * Processes pending subscriptions for a given connection.
1473
+ * Sends all queued subscriptions in a single payload.
1474
+ * @param connection The WebSocket connection to process.
1475
+ */
1476
+ processPendingSubscriptions(connection) {
1477
+ if (connection.pendingSubscriptions && connection.pendingSubscriptions.length > 0) {
1478
+ this.logger.info("Processing queued subscriptions for connection");
1479
+ this.sendSubscriptionPayload(connection, connection.pendingSubscriptions);
1480
+ connection.pendingSubscriptions = [];
1481
+ }
1482
+ }
1483
+ /**
1484
+ * Handles incoming WebSocket messages, parsing the data and invoking the appropriate callback function.
1485
+ * If the message contains a stream name that is registered in the `streamCallbackMap`, the corresponding
1486
+ * callback function is called with the message data.
1487
+ * If the message cannot be parsed, an error is logged.
1488
+ * @param data The raw WebSocket message data.
1489
+ * @param connection The WebSocket connection that received the message.
1490
+ */
1491
+ onMessage(data, connection) {
1492
+ try {
1493
+ const parsedData = JSONParse(data);
1494
+ const streamName = parsedData?.stream;
1495
+ if (streamName && this.streamCallbackMap.has(streamName)) this.streamCallbackMap.get(streamName)?.forEach((callback) => callback(parsedData.data));
1496
+ } catch (error) {
1497
+ this.logger.error("Failed to parse WebSocket message:", data, error);
1498
+ }
1499
+ super.onMessage(data, connection);
1500
+ }
1501
+ /**
1502
+ * Called when the WebSocket connection is opened.
1503
+ * Processes any pending subscriptions for the target connection.
1504
+ * @param url The URL of the WebSocket connection.
1505
+ * @param targetConnection The WebSocket connection that was opened.
1506
+ * @param oldConnection The previous WebSocket connection, if any.
1507
+ */
1508
+ onOpen(url, targetConnection, oldWSConnection) {
1509
+ this.processPendingSubscriptions(targetConnection);
1510
+ super.onOpen(url, targetConnection, oldWSConnection);
1511
+ }
1512
+ /**
1513
+ * Connects to the WebSocket server and subscribes to the specified streams.
1514
+ * This method returns a Promise that resolves when the connection is established,
1515
+ * or rejects with an error if the connection fails to be established within 10 seconds.
1516
+ * @param stream - A single stream name or an array of stream names to subscribe to.
1517
+ * @returns A Promise that resolves when the connection is established.
1518
+ */
1519
+ connect(stream = []) {
1520
+ const streams = Array.isArray(stream) ? stream : [stream];
1521
+ return new Promise((resolve, reject) => {
1522
+ const timeout = setTimeout(() => {
1523
+ reject(/* @__PURE__ */ new Error("Websocket connection timed out"));
1524
+ }, 1e4);
1525
+ this.connectPool(this.prepareURL(streams)).then(() => resolve()).catch((error) => reject(error)).finally(() => clearTimeout(timeout));
1526
+ });
1527
+ }
1528
+ /**
1529
+ * Disconnects the WebSocket connection and clears the stream callback map.
1530
+ * This method is called to clean up the connection and associated resources.
1531
+ */
1532
+ async disconnect() {
1533
+ this.streamCallbackMap.clear();
1534
+ this.streamConnectionMap.clear();
1535
+ super.disconnect();
1536
+ }
1537
+ /**
1538
+ * Subscribes to one or multiple WebSocket streams
1539
+ * Handles both single and pool modes
1540
+ * @param stream Single stream name or array of stream names to subscribe to
1541
+ * @param id Optional subscription ID
1542
+ * @returns void
1543
+ */
1544
+ subscribe(stream, id) {
1545
+ const streams = (Array.isArray(stream) ? stream : [stream]).filter((stream$1) => !this.streamConnectionMap.has(stream$1));
1546
+ this.handleStreamAssignment(streams).forEach((streams$1, connection) => {
1547
+ if (!this.isConnected(connection)) {
1548
+ this.logger.info(`Connection ${connection.id} is not ready. Queuing subscription for streams: ${streams$1}`);
1549
+ connection.pendingSubscriptions?.push(...streams$1);
1550
+ return;
1551
+ }
1552
+ this.sendSubscriptionPayload(connection, streams$1, id);
1553
+ });
1554
+ }
1555
+ /**
1556
+ * Unsubscribes from one or multiple WebSocket streams
1557
+ * Handles both single and pool modes
1558
+ * @param stream Single stream name or array of stream names to unsubscribe from
1559
+ * @param id Optional unsubscription ID
1560
+ * @returns void
1561
+ */
1562
+ unsubscribe(stream, id) {
1563
+ (Array.isArray(stream) ? stream : [stream]).forEach((stream$1) => {
1564
+ const connection = this.streamConnectionMap.get(stream$1);
1565
+ if (!connection || !connection.ws || !this.isConnected(connection)) {
1566
+ this.logger.warn(`Stream ${stream$1} not associated with an active connection.`);
1567
+ return;
1568
+ }
1569
+ if (!this.streamCallbackMap.has(stream$1) || this.streamCallbackMap.get(stream$1)?.size === 0) {
1570
+ const payload = {
1571
+ method: "UNSUBSCRIBE",
1572
+ params: [stream$1],
1573
+ id: id && /^[0-9a-f]{32}$/.test(id) ? id : randomString()
1574
+ };
1575
+ this.logger.debug("UNSUBSCRIBE", payload);
1576
+ this.send(JSON.stringify(payload), void 0, false, 0, connection);
1577
+ this.streamConnectionMap.delete(stream$1);
1578
+ this.streamCallbackMap.delete(stream$1);
1579
+ }
1580
+ });
1581
+ }
1582
+ /**
1583
+ * Checks if the specified stream is currently subscribed.
1584
+ * @param stream - The name of the stream to check.
1585
+ * @returns `true` if the stream is currently subscribed, `false` otherwise.
1586
+ */
1587
+ isSubscribed(stream) {
1588
+ return this.streamConnectionMap.has(stream);
1589
+ }
1519
1590
  };
1591
+ /**
1592
+ * Creates a WebSocket stream handler for managing stream subscriptions and callbacks.
1593
+ *
1594
+ * @template T The type of data expected in the stream messages
1595
+ * @param {WebsocketAPIBase | WebsocketStreamsBase} websocketBase The WebSocket base instance
1596
+ * @param {string} streamOrId The stream identifier
1597
+ * @param {string} [id] Optional additional identifier
1598
+ * @returns {WebsocketStream<T>} A stream handler with methods to register callbacks and unsubscribe
1599
+ */
1520
1600
  function createStreamHandler(websocketBase, streamOrId, id) {
1521
- if (websocketBase instanceof WebsocketStreamsBase) websocketBase.subscribe(streamOrId, id);
1522
- let registeredCallback;
1523
- return {
1524
- on: (event, callback) => {
1525
- if (event === "message") {
1526
- registeredCallback = (data) => {
1527
- Promise.resolve(callback(data)).catch((err) => {
1528
- websocketBase.logger.error(`Error in stream callback: ${err}`);
1529
- });
1530
- };
1531
- const callbackSet = websocketBase.streamCallbackMap.get(streamOrId) ?? /* @__PURE__ */ new Set();
1532
- callbackSet.add(registeredCallback);
1533
- websocketBase.streamCallbackMap.set(streamOrId, callbackSet);
1534
- }
1535
- },
1536
- unsubscribe: () => {
1537
- if (registeredCallback)
1538
- websocketBase.streamCallbackMap.get(streamOrId)?.delete(registeredCallback);
1539
- if (websocketBase instanceof WebsocketStreamsBase)
1540
- websocketBase.unsubscribe(streamOrId, id);
1541
- }
1542
- };
1601
+ if (websocketBase instanceof WebsocketStreamsBase) websocketBase.subscribe(streamOrId, id);
1602
+ let registeredCallback;
1603
+ return {
1604
+ on: (event, callback) => {
1605
+ if (event === "message") {
1606
+ registeredCallback = (data) => {
1607
+ Promise.resolve(callback(data)).catch((err) => {
1608
+ websocketBase.logger.error(`Error in stream callback: ${err}`);
1609
+ });
1610
+ };
1611
+ const callbackSet = websocketBase.streamCallbackMap.get(streamOrId) ?? /* @__PURE__ */ new Set();
1612
+ callbackSet.add(registeredCallback);
1613
+ websocketBase.streamCallbackMap.set(streamOrId, callbackSet);
1614
+ }
1615
+ },
1616
+ unsubscribe: () => {
1617
+ if (registeredCallback) websocketBase.streamCallbackMap.get(streamOrId)?.delete(registeredCallback);
1618
+ if (websocketBase instanceof WebsocketStreamsBase) websocketBase.unsubscribe(streamOrId, id);
1619
+ }
1620
+ };
1543
1621
  }
1544
- export {
1545
- ALGO_REST_API_PROD_URL,
1546
- BadRequestError,
1547
- C2C_REST_API_PROD_URL,
1548
- CONVERT_REST_API_PROD_URL,
1549
- COPY_TRADING_REST_API_PROD_URL,
1550
- CRYPTO_LOAN_REST_API_PROD_URL,
1551
- ConfigurationRestAPI,
1552
- ConfigurationWebsocketAPI2 as ConfigurationWebsocketAPI,
1553
- ConfigurationWebsocketStreams,
1554
- ConnectorClientError,
1555
- DERIVATIVES_TRADING_COIN_FUTURES_REST_API_PROD_URL,
1556
- DERIVATIVES_TRADING_COIN_FUTURES_REST_API_TESTNET_URL,
1557
- DERIVATIVES_TRADING_COIN_FUTURES_WS_API_PROD_URL,
1558
- DERIVATIVES_TRADING_COIN_FUTURES_WS_API_TESTNET_URL,
1559
- DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_PROD_URL,
1560
- DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_TESTNET_URL,
1561
- DERIVATIVES_TRADING_OPTIONS_REST_API_PROD_URL,
1562
- DERIVATIVES_TRADING_OPTIONS_WS_STREAMS_PROD_URL,
1563
- DERIVATIVES_TRADING_PORTFOLIO_MARGIN_PRO_REST_API_PROD_URL,
1564
- DERIVATIVES_TRADING_PORTFOLIO_MARGIN_PRO_WS_STREAMS_PROD_URL,
1565
- DERIVATIVES_TRADING_PORTFOLIO_MARGIN_REST_API_PROD_URL,
1566
- DERIVATIVES_TRADING_PORTFOLIO_MARGIN_REST_API_TESTNET_URL,
1567
- DERIVATIVES_TRADING_PORTFOLIO_MARGIN_WS_STREAMS_PROD_URL,
1568
- DERIVATIVES_TRADING_PORTFOLIO_MARGIN_WS_STREAMS_TESTNET_URL,
1569
- DERIVATIVES_TRADING_USDS_FUTURES_REST_API_PROD_URL,
1570
- DERIVATIVES_TRADING_USDS_FUTURES_REST_API_TESTNET_URL,
1571
- DERIVATIVES_TRADING_USDS_FUTURES_WS_API_PROD_URL,
1572
- DERIVATIVES_TRADING_USDS_FUTURES_WS_API_TESTNET_URL,
1573
- DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_PROD_URL,
1574
- DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_TESTNET_URL,
1575
- DUAL_INVESTMENT_REST_API_PROD_URL,
1576
- FIAT_REST_API_PROD_URL,
1577
- ForbiddenError,
1578
- GIFT_CARD_REST_API_PROD_URL,
1579
- LogLevel,
1580
- Logger,
1581
- MARGIN_TRADING_REST_API_PROD_URL,
1582
- MARGIN_TRADING_RISK_WS_STREAMS_PROD_URL,
1583
- MARGIN_TRADING_WS_STREAMS_PROD_URL,
1584
- MINING_REST_API_PROD_URL,
1585
- NFT_REST_API_PROD_URL,
1586
- NetworkError,
1587
- NotFoundError,
1588
- PAY_REST_API_PROD_URL,
1589
- REBATE_REST_API_PROD_URL,
1590
- RateLimitBanError,
1591
- RequiredError,
1592
- SIMPLE_EARN_REST_API_PROD_URL,
1593
- SPOT_REST_API_MARKET_URL,
1594
- SPOT_REST_API_PROD_URL,
1595
- SPOT_REST_API_TESTNET_URL,
1596
- SPOT_WS_API_PROD_URL,
1597
- SPOT_WS_API_TESTNET_URL,
1598
- SPOT_WS_STREAMS_MARKET_URL,
1599
- SPOT_WS_STREAMS_PROD_URL,
1600
- SPOT_WS_STREAMS_TESTNET_URL,
1601
- STAKING_REST_API_PROD_URL,
1602
- SUB_ACCOUNT_REST_API_PROD_URL,
1603
- ServerError,
1604
- TimeUnit,
1605
- TooManyRequestsError,
1606
- UnauthorizedError,
1607
- VIP_LOAN_REST_API_PROD_URL,
1608
- WALLET_REST_API_PROD_URL,
1609
- WebsocketAPIBase,
1610
- WebsocketCommon,
1611
- WebsocketEventEmitter,
1612
- WebsocketStreamsBase,
1613
- assertParamExists,
1614
- buildQueryString,
1615
- buildUserAgent,
1616
- buildWebsocketAPIMessage,
1617
- clearSignerCache,
1618
- createStreamHandler,
1619
- delay,
1620
- getSignature,
1621
- getTimestamp,
1622
- httpRequestFunction,
1623
- normalizeScientificNumbers,
1624
- parseCustomHeaders,
1625
- parseRateLimitHeaders,
1626
- randomString,
1627
- removeEmptyValue,
1628
- replaceWebsocketStreamsPlaceholders,
1629
- sanitizeHeaderValue,
1630
- sendRequest,
1631
- setSearchParams,
1632
- shouldRetryRequest,
1633
- sortObject,
1634
- toPathString,
1635
- validateTimeUnit
1636
- };
1622
+
1623
+ //#endregion
1624
+ export { ALGO_REST_API_PROD_URL, BadRequestError, C2C_REST_API_PROD_URL, CONVERT_REST_API_PROD_URL, COPY_TRADING_REST_API_PROD_URL, CRYPTO_LOAN_REST_API_PROD_URL, ConfigurationRestAPI, ConfigurationWebsocketAPI, ConfigurationWebsocketStreams, ConnectorClientError, DERIVATIVES_TRADING_COIN_FUTURES_REST_API_PROD_URL, DERIVATIVES_TRADING_COIN_FUTURES_REST_API_TESTNET_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_API_PROD_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_API_TESTNET_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_PROD_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_TESTNET_URL, DERIVATIVES_TRADING_OPTIONS_REST_API_PROD_URL, DERIVATIVES_TRADING_OPTIONS_WS_STREAMS_PROD_URL, DERIVATIVES_TRADING_PORTFOLIO_MARGIN_PRO_REST_API_PROD_URL, DERIVATIVES_TRADING_PORTFOLIO_MARGIN_PRO_WS_STREAMS_PROD_URL, DERIVATIVES_TRADING_PORTFOLIO_MARGIN_REST_API_PROD_URL, DERIVATIVES_TRADING_PORTFOLIO_MARGIN_REST_API_TESTNET_URL, DERIVATIVES_TRADING_PORTFOLIO_MARGIN_WS_STREAMS_PROD_URL, DERIVATIVES_TRADING_PORTFOLIO_MARGIN_WS_STREAMS_TESTNET_URL, DERIVATIVES_TRADING_USDS_FUTURES_REST_API_PROD_URL, DERIVATIVES_TRADING_USDS_FUTURES_REST_API_TESTNET_URL, DERIVATIVES_TRADING_USDS_FUTURES_WS_API_PROD_URL, DERIVATIVES_TRADING_USDS_FUTURES_WS_API_TESTNET_URL, DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_PROD_URL, DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_TESTNET_URL, DUAL_INVESTMENT_REST_API_PROD_URL, FIAT_REST_API_PROD_URL, ForbiddenError, GIFT_CARD_REST_API_PROD_URL, LogLevel, Logger, MARGIN_TRADING_REST_API_PROD_URL, MARGIN_TRADING_RISK_WS_STREAMS_PROD_URL, MARGIN_TRADING_WS_STREAMS_PROD_URL, MINING_REST_API_PROD_URL, NFT_REST_API_PROD_URL, NetworkError, NotFoundError, PAY_REST_API_PROD_URL, REBATE_REST_API_PROD_URL, RateLimitBanError, RequiredError, SIMPLE_EARN_REST_API_PROD_URL, SPOT_REST_API_MARKET_URL, SPOT_REST_API_PROD_URL, SPOT_REST_API_TESTNET_URL, SPOT_WS_API_PROD_URL, SPOT_WS_API_TESTNET_URL, SPOT_WS_STREAMS_MARKET_URL, SPOT_WS_STREAMS_PROD_URL, SPOT_WS_STREAMS_TESTNET_URL, STAKING_REST_API_PROD_URL, SUB_ACCOUNT_REST_API_PROD_URL, ServerError, TimeUnit, TooManyRequestsError, UnauthorizedError, VIP_LOAN_REST_API_PROD_URL, WALLET_REST_API_PROD_URL, WebsocketAPIBase, WebsocketCommon, WebsocketEventEmitter, WebsocketStreamsBase, assertParamExists, buildQueryString, buildUserAgent, buildWebsocketAPIMessage, clearSignerCache, createStreamHandler, delay, getSignature, getTimestamp, httpRequestFunction, normalizeScientificNumbers, parseCustomHeaders, parseRateLimitHeaders, randomString, removeEmptyValue, replaceWebsocketStreamsPlaceholders, sanitizeHeaderValue, sendRequest, setSearchParams, shouldRetryRequest, sortObject, toPathString, validateTimeUnit };
1637
1625
  //# sourceMappingURL=index.mjs.map