@binance/common 1.2.6 → 2.0.1

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