@binance/common 1.0.2 → 1.0.4

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.d.mts CHANGED
@@ -434,13 +434,20 @@ interface WebsocketApiRateLimit {
434
434
  count: number;
435
435
  }
436
436
  /**
437
- * Represents the response from a WebSocket API request.
438
- * @template T - The type of the data returned in the response.
439
- * @property {T} data - The data from the API response.
437
+ * Extracts the result or response from a WebSocket API response type.
438
+ * @template T - The type of the WebSocket API response.
439
+ * @returns {T['result'] | T['response'] | never} The extracted result or response, or never if neither exists.
440
+ * @description Checks if the type T has a 'result' or 'response' key and returns its value, otherwise returns never.
441
+ */
442
+ type ExtractWebsocketApiResponse<T> = 'result' extends keyof T ? T['result'] : 'response' extends keyof T ? T['response'] : unknown;
443
+ /**
444
+ * Represents the response from a WebSocket API.
445
+ * @template T - The type of the WebSocket API response.
446
+ * @property {NonNullable<ExtractWebsocketApiResponse<T>>} data - The extracted, non-null data from the WebSocket API response.
440
447
  * @property {WebsocketApiRateLimit[]} [rateLimits] - An optional array of rate limit information for the response.
441
448
  */
442
449
  type WebsocketApiResponse<T> = {
443
- data: T;
450
+ data: NonNullable<ExtractWebsocketApiResponse<T>>;
444
451
  rateLimits?: WebsocketApiRateLimit[];
445
452
  };
446
453
  /**
@@ -607,15 +614,6 @@ declare function sortObject(obj: ObjectType): ObjectType;
607
614
  * @returns {string} - The resulting string with placeholders replaced by their corresponding values.
608
615
  */
609
616
  declare function replaceWebsocketStreamsPlaceholders(str: string, variables: Record<string, unknown>): string;
610
- /**
611
- * Creates a WebsocketStream instance that subscribes to the specified stream and provides a callback for handling incoming messages.
612
- *
613
- * @param websocketBase - The WebsocketStreamsBase instance to use for subscribing and unsubscribing from the stream.
614
- * @param stream - The name of the stream to subscribe to.
615
- * @param id - An optional identifier for the stream.
616
- * @returns A WebsocketStream instance that can be used to handle incoming messages and unsubscribe from the stream.
617
- */
618
- declare function createStreamHandler<T>(websocketBase: WebsocketStreamsBase, stream: string, id?: string): WebsocketStream<T>;
619
617
 
620
618
  declare class WebsocketEventEmitter {
621
619
  private eventEmitter;
@@ -812,6 +810,7 @@ interface WebsocketSendMsgOptions {
812
810
  }
813
811
  declare class WebsocketAPIBase extends WebsocketCommon {
814
812
  private isConnecting;
813
+ streamCallbackMap: Map<string, Set<(data: unknown) => void>>;
815
814
  configuration: ConfigurationWebsocketAPI;
816
815
  logger: Logger;
817
816
  constructor(configuration: ConfigurationWebsocketAPI, connectionPool?: WebsocketConnection[]);
@@ -825,7 +824,7 @@ declare class WebsocketAPIBase extends WebsocketCommon {
825
824
  * Processes incoming WebSocket messages
826
825
  * @param data The raw message data received
827
826
  */
828
- protected onMessage(data: string, connection: WebsocketConnection): void;
827
+ protected onMessage<T>(data: string, connection: WebsocketConnection): void;
829
828
  /**
830
829
  * Establishes a WebSocket connection to Binance
831
830
  * @returns Promise that resolves when connection is established
@@ -846,18 +845,6 @@ declare class WebsocketAPIBase extends WebsocketCommon {
846
845
  isSigned?: boolean;
847
846
  }): Promise<WebsocketApiResponse<T>>;
848
847
  }
849
- interface WebsocketStream<T> {
850
- /**
851
- * Attach a listener for the stream.
852
- * @param event - Event name (currently supports "message").
853
- * @param callback - Callback function to handle incoming data.
854
- */
855
- on(event: 'message', callback: (data: T) => void): void;
856
- /**
857
- * Unsubscribe from the stream and clean up resources.
858
- */
859
- unsubscribe(): void;
860
- }
861
848
  declare class WebsocketStreamsBase extends WebsocketCommon {
862
849
  private streamConnectionMap;
863
850
  protected configuration: ConfigurationWebsocketStreams;
@@ -951,5 +938,27 @@ declare class WebsocketStreamsBase extends WebsocketCommon {
951
938
  */
952
939
  isSubscribed(stream: string): boolean;
953
940
  }
941
+ interface WebsocketStream<T> {
942
+ /**
943
+ * Attach a listener for the stream.
944
+ * @param event - Event name (currently supports "message").
945
+ * @param callback - Callback function to handle incoming data.
946
+ */
947
+ on(event: 'message', callback: (data: T) => void): void;
948
+ /**
949
+ * Unsubscribe from the stream and clean up resources.
950
+ */
951
+ unsubscribe(): void;
952
+ }
953
+ /**
954
+ * Creates a WebSocket stream handler for managing stream subscriptions and callbacks.
955
+ *
956
+ * @template T The type of data expected in the stream messages
957
+ * @param {WebsocketAPIBase | WebsocketStreamsBase} websocketBase The WebSocket base instance
958
+ * @param {string} streamOrId The stream identifier
959
+ * @param {string} [id] Optional additional identifier
960
+ * @returns {WebsocketStream<T>} A stream handler with methods to register callbacks and unsubscribe
961
+ */
962
+ declare function createStreamHandler<T>(websocketBase: WebsocketAPIBase | WebsocketStreamsBase, streamOrId: string, id?: string): WebsocketStream<T>;
954
963
 
955
964
  export { ALGO_REST_API_PROD_URL, AUTO_INVEST_REST_API_PROD_URL, type AxiosRequestArgs, BadRequestError, C2C_REST_API_PROD_URL, CONVERT_REST_API_PROD_URL, COPY_TRADING_REST_API_PROD_URL, CRYPTO_LOAN_REST_API_PROD_URL, ConfigurationRestAPI, ConfigurationWebsocketAPI, ConfigurationWebsocketStreams, ConnectorClientError, DERIVATIVES_TRADING_COIN_FUTURES_REST_API_PROD_URL, DERIVATIVES_TRADING_COIN_FUTURES_REST_API_TESTNET_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_API_PROD_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_API_TESTNET_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_PROD_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_TESTNET_URL, DERIVATIVES_TRADING_OPTIONS_REST_API_PROD_URL, DERIVATIVES_TRADING_OPTIONS_WS_STREAMS_PROD_URL, DERIVATIVES_TRADING_PORTFOLIO_MARGIN_PRO_REST_API_PROD_URL, DERIVATIVES_TRADING_PORTFOLIO_MARGIN_PRO_REST_API_TESTNET_URL, DERIVATIVES_TRADING_PORTFOLIO_MARGIN_REST_API_PROD_URL, DERIVATIVES_TRADING_PORTFOLIO_MARGIN_REST_API_TESTNET_URL, DERIVATIVES_TRADING_USDS_FUTURES_REST_API_PROD_URL, DERIVATIVES_TRADING_USDS_FUTURES_REST_API_TESTNET_URL, DERIVATIVES_TRADING_USDS_FUTURES_WS_API_PROD_URL, DERIVATIVES_TRADING_USDS_FUTURES_WS_API_TESTNET_URL, DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_PROD_URL, DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_TESTNET_URL, DUAL_INVESTMENT_REST_API_PROD_URL, FIAT_REST_API_PROD_URL, ForbiddenError, GIFT_CARD_REST_API_PROD_URL, LogLevel, Logger, MARGIN_TRADING_REST_API_PROD_URL, MINING_REST_API_PROD_URL, NFT_REST_API_PROD_URL, NetworkError, NotFoundError, type ObjectType, PAY_REST_API_PROD_URL, REBATE_REST_API_PROD_URL, RateLimitBanError, type RequestArgs, RequiredError, type RestApiRateLimit, type RestApiResponse, SIMPLE_EARN_REST_API_PROD_URL, SPOT_REST_API_MARKET_URL, SPOT_REST_API_PROD_URL, SPOT_REST_API_TESTNET_URL, SPOT_WS_API_PROD_URL, SPOT_WS_API_TESTNET_URL, SPOT_WS_STREAMS_MARKET_URL, SPOT_WS_STREAMS_PROD_URL, SPOT_WS_STREAMS_TESTNET_URL, STAKING_REST_API_PROD_URL, SUB_ACCOUNT_REST_API_PROD_URL, type SendMessageOptions, ServerError, TimeUnit, TooManyRequestsError, UnauthorizedError, VIP_LOAN_REST_API_PROD_URL, WALLET_REST_API_PROD_URL, WebsocketAPIBase, type WebsocketApiRateLimit, type WebsocketApiResponse, WebsocketCommon, type WebsocketConnection, WebsocketEventEmitter, type WebsocketSendMsgOptions, type WebsocketStream, WebsocketStreamsBase, assertParamExists, buildQueryString, createStreamHandler, delay, getSignature, getTimestamp, httpRequestFunction, parseRateLimitHeaders, randomString, removeEmptyValue, replaceWebsocketStreamsPlaceholders, sendRequest, setSearchParams, shouldRetryRequest, sortObject, toPathString, validateTimeUnit };
package/dist/index.d.ts CHANGED
@@ -434,13 +434,20 @@ interface WebsocketApiRateLimit {
434
434
  count: number;
435
435
  }
436
436
  /**
437
- * Represents the response from a WebSocket API request.
438
- * @template T - The type of the data returned in the response.
439
- * @property {T} data - The data from the API response.
437
+ * Extracts the result or response from a WebSocket API response type.
438
+ * @template T - The type of the WebSocket API response.
439
+ * @returns {T['result'] | T['response'] | never} The extracted result or response, or never if neither exists.
440
+ * @description Checks if the type T has a 'result' or 'response' key and returns its value, otherwise returns never.
441
+ */
442
+ type ExtractWebsocketApiResponse<T> = 'result' extends keyof T ? T['result'] : 'response' extends keyof T ? T['response'] : unknown;
443
+ /**
444
+ * Represents the response from a WebSocket API.
445
+ * @template T - The type of the WebSocket API response.
446
+ * @property {NonNullable<ExtractWebsocketApiResponse<T>>} data - The extracted, non-null data from the WebSocket API response.
440
447
  * @property {WebsocketApiRateLimit[]} [rateLimits] - An optional array of rate limit information for the response.
441
448
  */
442
449
  type WebsocketApiResponse<T> = {
443
- data: T;
450
+ data: NonNullable<ExtractWebsocketApiResponse<T>>;
444
451
  rateLimits?: WebsocketApiRateLimit[];
445
452
  };
446
453
  /**
@@ -607,15 +614,6 @@ declare function sortObject(obj: ObjectType): ObjectType;
607
614
  * @returns {string} - The resulting string with placeholders replaced by their corresponding values.
608
615
  */
609
616
  declare function replaceWebsocketStreamsPlaceholders(str: string, variables: Record<string, unknown>): string;
610
- /**
611
- * Creates a WebsocketStream instance that subscribes to the specified stream and provides a callback for handling incoming messages.
612
- *
613
- * @param websocketBase - The WebsocketStreamsBase instance to use for subscribing and unsubscribing from the stream.
614
- * @param stream - The name of the stream to subscribe to.
615
- * @param id - An optional identifier for the stream.
616
- * @returns A WebsocketStream instance that can be used to handle incoming messages and unsubscribe from the stream.
617
- */
618
- declare function createStreamHandler<T>(websocketBase: WebsocketStreamsBase, stream: string, id?: string): WebsocketStream<T>;
619
617
 
620
618
  declare class WebsocketEventEmitter {
621
619
  private eventEmitter;
@@ -812,6 +810,7 @@ interface WebsocketSendMsgOptions {
812
810
  }
813
811
  declare class WebsocketAPIBase extends WebsocketCommon {
814
812
  private isConnecting;
813
+ streamCallbackMap: Map<string, Set<(data: unknown) => void>>;
815
814
  configuration: ConfigurationWebsocketAPI;
816
815
  logger: Logger;
817
816
  constructor(configuration: ConfigurationWebsocketAPI, connectionPool?: WebsocketConnection[]);
@@ -825,7 +824,7 @@ declare class WebsocketAPIBase extends WebsocketCommon {
825
824
  * Processes incoming WebSocket messages
826
825
  * @param data The raw message data received
827
826
  */
828
- protected onMessage(data: string, connection: WebsocketConnection): void;
827
+ protected onMessage<T>(data: string, connection: WebsocketConnection): void;
829
828
  /**
830
829
  * Establishes a WebSocket connection to Binance
831
830
  * @returns Promise that resolves when connection is established
@@ -846,18 +845,6 @@ declare class WebsocketAPIBase extends WebsocketCommon {
846
845
  isSigned?: boolean;
847
846
  }): Promise<WebsocketApiResponse<T>>;
848
847
  }
849
- interface WebsocketStream<T> {
850
- /**
851
- * Attach a listener for the stream.
852
- * @param event - Event name (currently supports "message").
853
- * @param callback - Callback function to handle incoming data.
854
- */
855
- on(event: 'message', callback: (data: T) => void): void;
856
- /**
857
- * Unsubscribe from the stream and clean up resources.
858
- */
859
- unsubscribe(): void;
860
- }
861
848
  declare class WebsocketStreamsBase extends WebsocketCommon {
862
849
  private streamConnectionMap;
863
850
  protected configuration: ConfigurationWebsocketStreams;
@@ -951,5 +938,27 @@ declare class WebsocketStreamsBase extends WebsocketCommon {
951
938
  */
952
939
  isSubscribed(stream: string): boolean;
953
940
  }
941
+ interface WebsocketStream<T> {
942
+ /**
943
+ * Attach a listener for the stream.
944
+ * @param event - Event name (currently supports "message").
945
+ * @param callback - Callback function to handle incoming data.
946
+ */
947
+ on(event: 'message', callback: (data: T) => void): void;
948
+ /**
949
+ * Unsubscribe from the stream and clean up resources.
950
+ */
951
+ unsubscribe(): void;
952
+ }
953
+ /**
954
+ * Creates a WebSocket stream handler for managing stream subscriptions and callbacks.
955
+ *
956
+ * @template T The type of data expected in the stream messages
957
+ * @param {WebsocketAPIBase | WebsocketStreamsBase} websocketBase The WebSocket base instance
958
+ * @param {string} streamOrId The stream identifier
959
+ * @param {string} [id] Optional additional identifier
960
+ * @returns {WebsocketStream<T>} A stream handler with methods to register callbacks and unsubscribe
961
+ */
962
+ declare function createStreamHandler<T>(websocketBase: WebsocketAPIBase | WebsocketStreamsBase, streamOrId: string, id?: string): WebsocketStream<T>;
954
963
 
955
964
  export { ALGO_REST_API_PROD_URL, AUTO_INVEST_REST_API_PROD_URL, type AxiosRequestArgs, BadRequestError, C2C_REST_API_PROD_URL, CONVERT_REST_API_PROD_URL, COPY_TRADING_REST_API_PROD_URL, CRYPTO_LOAN_REST_API_PROD_URL, ConfigurationRestAPI, ConfigurationWebsocketAPI, ConfigurationWebsocketStreams, ConnectorClientError, DERIVATIVES_TRADING_COIN_FUTURES_REST_API_PROD_URL, DERIVATIVES_TRADING_COIN_FUTURES_REST_API_TESTNET_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_API_PROD_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_API_TESTNET_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_PROD_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_TESTNET_URL, DERIVATIVES_TRADING_OPTIONS_REST_API_PROD_URL, DERIVATIVES_TRADING_OPTIONS_WS_STREAMS_PROD_URL, DERIVATIVES_TRADING_PORTFOLIO_MARGIN_PRO_REST_API_PROD_URL, DERIVATIVES_TRADING_PORTFOLIO_MARGIN_PRO_REST_API_TESTNET_URL, DERIVATIVES_TRADING_PORTFOLIO_MARGIN_REST_API_PROD_URL, DERIVATIVES_TRADING_PORTFOLIO_MARGIN_REST_API_TESTNET_URL, DERIVATIVES_TRADING_USDS_FUTURES_REST_API_PROD_URL, DERIVATIVES_TRADING_USDS_FUTURES_REST_API_TESTNET_URL, DERIVATIVES_TRADING_USDS_FUTURES_WS_API_PROD_URL, DERIVATIVES_TRADING_USDS_FUTURES_WS_API_TESTNET_URL, DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_PROD_URL, DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_TESTNET_URL, DUAL_INVESTMENT_REST_API_PROD_URL, FIAT_REST_API_PROD_URL, ForbiddenError, GIFT_CARD_REST_API_PROD_URL, LogLevel, Logger, MARGIN_TRADING_REST_API_PROD_URL, MINING_REST_API_PROD_URL, NFT_REST_API_PROD_URL, NetworkError, NotFoundError, type ObjectType, PAY_REST_API_PROD_URL, REBATE_REST_API_PROD_URL, RateLimitBanError, type RequestArgs, RequiredError, type RestApiRateLimit, type RestApiResponse, SIMPLE_EARN_REST_API_PROD_URL, SPOT_REST_API_MARKET_URL, SPOT_REST_API_PROD_URL, SPOT_REST_API_TESTNET_URL, SPOT_WS_API_PROD_URL, SPOT_WS_API_TESTNET_URL, SPOT_WS_STREAMS_MARKET_URL, SPOT_WS_STREAMS_PROD_URL, SPOT_WS_STREAMS_TESTNET_URL, STAKING_REST_API_PROD_URL, SUB_ACCOUNT_REST_API_PROD_URL, type SendMessageOptions, ServerError, TimeUnit, TooManyRequestsError, UnauthorizedError, VIP_LOAN_REST_API_PROD_URL, WALLET_REST_API_PROD_URL, WebsocketAPIBase, type WebsocketApiRateLimit, type WebsocketApiResponse, WebsocketCommon, type WebsocketConnection, WebsocketEventEmitter, type WebsocketSendMsgOptions, type WebsocketStream, WebsocketStreamsBase, assertParamExists, buildQueryString, createStreamHandler, delay, getSignature, getTimestamp, httpRequestFunction, parseRateLimitHeaders, randomString, removeEmptyValue, replaceWebsocketStreamsPlaceholders, sendRequest, setSearchParams, shouldRetryRequest, sortObject, toPathString, validateTimeUnit };
package/dist/index.js CHANGED
@@ -94,7 +94,7 @@ __export(index_exports, {
94
94
  WebsocketAPIBase: () => WebsocketAPIBase,
95
95
  WebsocketCommon: () => WebsocketCommon,
96
96
  WebsocketEventEmitter: () => WebsocketEventEmitter,
97
- WebsocketStreamsBase: () => WebsocketStreamsBase2,
97
+ WebsocketStreamsBase: () => WebsocketStreamsBase,
98
98
  assertParamExists: () => assertParamExists,
99
99
  buildQueryString: () => buildQueryString,
100
100
  createStreamHandler: () => createStreamHandler,
@@ -686,25 +686,6 @@ function replaceWebsocketStreamsPlaceholders(str, variables) {
686
686
  return "";
687
687
  });
688
688
  }
689
- function createStreamHandler(websocketBase, stream, id) {
690
- websocketBase.subscribe(stream, id);
691
- let registeredCallback;
692
- return {
693
- on: (event, callback) => {
694
- if (event === "message") {
695
- registeredCallback = (data) => callback(data);
696
- const callbackSet = websocketBase.streamCallbackMap.get(stream) ?? /* @__PURE__ */ new Set();
697
- callbackSet.add(registeredCallback);
698
- websocketBase.streamCallbackMap.set(stream, callbackSet);
699
- }
700
- },
701
- unsubscribe: () => {
702
- if (registeredCallback)
703
- websocketBase.streamCallbackMap.get(stream)?.delete(registeredCallback);
704
- websocketBase.unsubscribe(stream, id);
705
- }
706
- };
707
- }
708
689
 
709
690
  // src/websocket.ts
710
691
  var import_events = require("events");
@@ -1164,6 +1145,7 @@ var WebsocketAPIBase = class extends WebsocketCommon {
1164
1145
  constructor(configuration, connectionPool = []) {
1165
1146
  super(configuration, connectionPool);
1166
1147
  this.isConnecting = false;
1148
+ this.streamCallbackMap = /* @__PURE__ */ new Map();
1167
1149
  this.logger = Logger.getInstance();
1168
1150
  this.configuration = configuration;
1169
1151
  }
@@ -1198,10 +1180,16 @@ var WebsocketAPIBase = class extends WebsocketCommon {
1198
1180
  if (status && status >= 400) {
1199
1181
  request?.reject(message.error);
1200
1182
  } else {
1201
- const response = { data: message.result };
1202
- if (message?.rateLimits) response.rateLimits = message.rateLimits;
1183
+ const response = {
1184
+ data: message.result ?? message.response,
1185
+ ...message.rateLimits && { rateLimits: message.rateLimits }
1186
+ };
1203
1187
  request?.resolve(response);
1204
1188
  }
1189
+ } else if ("event" in message && "e" in message["event"] && this.streamCallbackMap.size > 0) {
1190
+ this.streamCallbackMap.forEach(
1191
+ (callbacks) => callbacks.forEach((callback) => callback(message["event"]))
1192
+ );
1205
1193
  } else {
1206
1194
  this.logger.warn("Received response for unknown or timed-out request:", message);
1207
1195
  }
@@ -1271,7 +1259,7 @@ var WebsocketAPIBase = class extends WebsocketCommon {
1271
1259
  return this.send(JSON.stringify(data), id, true, this.configuration?.timeout);
1272
1260
  }
1273
1261
  };
1274
- var WebsocketStreamsBase2 = class extends WebsocketCommon {
1262
+ var WebsocketStreamsBase = class extends WebsocketCommon {
1275
1263
  constructor(configuration, connectionPool = []) {
1276
1264
  super(configuration, connectionPool);
1277
1265
  this.streamConnectionMap = /* @__PURE__ */ new Map();
@@ -1477,6 +1465,26 @@ var WebsocketStreamsBase2 = class extends WebsocketCommon {
1477
1465
  return this.streamConnectionMap.has(stream);
1478
1466
  }
1479
1467
  };
1468
+ function createStreamHandler(websocketBase, streamOrId, id) {
1469
+ if (websocketBase instanceof WebsocketStreamsBase) websocketBase.subscribe(streamOrId, id);
1470
+ let registeredCallback;
1471
+ return {
1472
+ on: (event, callback) => {
1473
+ if (event === "message") {
1474
+ registeredCallback = (data) => callback(data);
1475
+ const callbackSet = websocketBase.streamCallbackMap.get(streamOrId) ?? /* @__PURE__ */ new Set();
1476
+ callbackSet.add(registeredCallback);
1477
+ websocketBase.streamCallbackMap.set(streamOrId, callbackSet);
1478
+ }
1479
+ },
1480
+ unsubscribe: () => {
1481
+ if (registeredCallback)
1482
+ websocketBase.streamCallbackMap.get(streamOrId)?.delete(registeredCallback);
1483
+ if (websocketBase instanceof WebsocketStreamsBase)
1484
+ websocketBase.unsubscribe(streamOrId, id);
1485
+ }
1486
+ };
1487
+ }
1480
1488
  // Annotate the CommonJS export names for ESM import in node:
1481
1489
  0 && (module.exports = {
1482
1490
  ALGO_REST_API_PROD_URL,