@binance/common 2.0.0 → 2.1.0

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