@gmx-io/sdk 2.6.0-next.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +25 -0
  2. package/build/cjs/src/abis/ChainlinkPriceFeedProvider.js +27 -0
  3. package/build/cjs/src/abis/Pausable.js +11 -0
  4. package/build/cjs/src/abis/index.js +4 -0
  5. package/build/cjs/src/clients/v2/index.js +20 -1
  6. package/build/cjs/src/configs/express.js +1 -0
  7. package/build/cjs/src/configs/tokens.js +3 -0
  8. package/build/cjs/src/utils/__tests__/numbers.spec.js +15 -0
  9. package/build/cjs/src/utils/multichain/__tests__/api.spec.js +11 -1
  10. package/build/cjs/src/utils/multichain/api.js +3 -2
  11. package/build/cjs/src/utils/numbers/utils.js +8 -2
  12. package/build/cjs/src/utils/prices/api.js +15 -1
  13. package/build/cjs/src/utils/stream/WsStreamClient.js +363 -0
  14. package/build/cjs/src/utils/stream/__tests__/WsStreamClient.spec.js +383 -0
  15. package/build/cjs/src/utils/stream/__tests__/stream.integration.spec.js +133 -0
  16. package/build/cjs/src/utils/stream/index.js +11 -0
  17. package/build/cjs/src/utils/stream/subscription.js +61 -0
  18. package/build/cjs/src/utils/stream/types.js +2 -0
  19. package/build/esm/src/abis/ChainlinkPriceFeedProvider.js +25 -0
  20. package/build/esm/src/abis/Pausable.js +9 -0
  21. package/build/esm/src/abis/index.js +4 -0
  22. package/build/esm/src/clients/v2/index.js +21 -2
  23. package/build/esm/src/configs/express.js +1 -0
  24. package/build/esm/src/configs/tokens.js +3 -0
  25. package/build/esm/src/utils/__tests__/numbers.spec.js +15 -0
  26. package/build/esm/src/utils/multichain/__tests__/api.spec.js +11 -1
  27. package/build/esm/src/utils/multichain/api.js +2 -1
  28. package/build/esm/src/utils/numbers/utils.js +8 -2
  29. package/build/esm/src/utils/prices/api.js +12 -0
  30. package/build/esm/src/utils/stream/WsStreamClient.js +355 -0
  31. package/build/esm/src/utils/stream/__tests__/WsStreamClient.spec.js +381 -0
  32. package/build/esm/src/utils/stream/__tests__/stream.integration.spec.js +131 -0
  33. package/build/esm/src/utils/stream/index.js +5 -0
  34. package/build/esm/src/utils/stream/subscription.js +57 -0
  35. package/build/esm/src/utils/stream/types.js +1 -0
  36. package/build/tsconfig.tsbuildinfo +1 -1
  37. package/build/types/src/abis/ChainlinkPriceFeedProvider.d.ts +41 -0
  38. package/build/types/src/abis/Pausable.d.ts +12 -0
  39. package/build/types/src/abis/index.d.ts +51 -0
  40. package/build/types/src/clients/v2/index.d.ts +23 -5
  41. package/build/types/src/utils/multichain/api.d.ts +2 -1
  42. package/build/types/src/utils/orderTransactions/api.d.ts +2 -0
  43. package/build/types/src/utils/prices/api.d.ts +8 -0
  44. package/build/types/src/utils/stream/WsStreamClient.d.ts +63 -0
  45. package/build/types/src/utils/stream/__tests__/WsStreamClient.spec.d.ts +1 -0
  46. package/build/types/src/utils/stream/__tests__/stream.integration.spec.d.ts +1 -0
  47. package/build/types/src/utils/stream/index.d.ts +5 -0
  48. package/build/types/src/utils/stream/subscription.d.ts +3 -0
  49. package/build/types/src/utils/stream/types.d.ts +43 -0
  50. package/package.json +14 -2
package/README.md CHANGED
@@ -231,6 +231,31 @@ sdk.orders.swap({
231
231
 
232
232
  Note the distinction between `payTokenAddress` and `collateralTokenAddress`. These represent the ERC20 token addresses for payment and collateral respectively. Some markets use synthetic tokens, so you'll need to provide the correct underlying token address. For example, the BTC/USD [WETH-USDC] market has a synthetic BTC token as its `indexTokenAddress`, so you should pass the WBTC address instead of BTC.
233
233
 
234
+ ### Execution-fee deposits with a zero-tip bundler
235
+
236
+ The v2 API client's `prepareOrder` and `prepareCollateral` methods accept
237
+ `skipExecutionFeePriorityFeeAllowance?: boolean`, which defaults to `false`:
238
+
239
+ ```typescript
240
+ const prepared = await api.prepareOrder({
241
+ ...request,
242
+ mode: "classic",
243
+ skipExecutionFeePriorityFeeAllowance: true,
244
+ });
245
+ ```
246
+
247
+ Set this to `true` only when the outer transaction your bundler submits to Arbitrum uses zero priority
248
+ fee, including retries and wallet fallbacks. A zero tip on a UserOperation alone is not sufficient.
249
+ This removes only the 0.03 gwei-per-gas wallet-tip allowance and preserves `executionFeeBufferBps`,
250
+ including the default 30% buffer, and the remaining execution-fee calculation. It applies to attached
251
+ TP/SL orders, every TWAP part and collateral operations. Express and other chains retain their current
252
+ calculation.
253
+
254
+ The keeper executes separately later, so this does not guarantee future gas costs or a refund.
255
+ A later tipped submission or order edit can fail with `InsufficientExecutionFee`; use
256
+ `executionFeeTopUp` when an edit needs more funding. The API deployment must support the option before
257
+ clients send it; older deployments reject the unknown field. Malformed values return HTTP 400.
258
+
234
259
  ### JIT-aware trading capacity
235
260
 
236
261
  Use the v2 API client to get the current increase-order capacity for one market side:
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = [
4
+ {
5
+ inputs: [
6
+ { internalType: "address", name: "token", type: "address" },
7
+ { internalType: "bytes", name: "", type: "bytes" },
8
+ ],
9
+ name: "getOraclePrice",
10
+ outputs: [
11
+ {
12
+ components: [
13
+ { internalType: "address", name: "token", type: "address" },
14
+ { internalType: "uint256", name: "min", type: "uint256" },
15
+ { internalType: "uint256", name: "max", type: "uint256" },
16
+ { internalType: "uint256", name: "timestamp", type: "uint256" },
17
+ { internalType: "address", name: "provider", type: "address" },
18
+ ],
19
+ internalType: "struct OracleUtils.ValidatedPrice",
20
+ name: "",
21
+ type: "tuple",
22
+ },
23
+ ],
24
+ stateMutability: "view",
25
+ type: "function",
26
+ },
27
+ ];
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = [
4
+ {
5
+ inputs: [],
6
+ name: "paused",
7
+ outputs: [{ internalType: "bool", name: "", type: "bool" }],
8
+ stateMutability: "view",
9
+ type: "function",
10
+ },
11
+ ];
@@ -8,6 +8,7 @@ const viem_1 = require("viem");
8
8
  const AbstractSubaccountApprovalNonceable_1 = __importDefault(require("./AbstractSubaccountApprovalNonceable"));
9
9
  const ArbitrumNodeInterface_1 = __importDefault(require("./ArbitrumNodeInterface"));
10
10
  const ArbSys_1 = __importDefault(require("./ArbSys"));
11
+ const ChainlinkPriceFeedProvider_1 = __importDefault(require("./ChainlinkPriceFeedProvider"));
11
12
  const ClaimHandler_1 = __importDefault(require("./ClaimHandler"));
12
13
  const CustomErrors_1 = __importDefault(require("./CustomErrors"));
13
14
  const CustomErrorsV2_2_1_1 = __importDefault(require("./CustomErrorsV2_2_1"));
@@ -33,6 +34,7 @@ const MultichainOrderRouter_1 = __importDefault(require("./MultichainOrderRouter
33
34
  const MultichainSubaccountRouter_1 = __importDefault(require("./MultichainSubaccountRouter"));
34
35
  const MultichainTransferRouter_1 = __importDefault(require("./MultichainTransferRouter"));
35
36
  const MultichainVault_1 = __importDefault(require("./MultichainVault"));
37
+ const Pausable_1 = __importDefault(require("./Pausable"));
36
38
  const Reader_1 = __importDefault(require("./Reader"));
37
39
  const ReaderV2_1 = __importDefault(require("./ReaderV2"));
38
40
  const ReferralStorage_1 = __importDefault(require("./ReferralStorage"));
@@ -67,6 +69,7 @@ exports.abis = {
67
69
  AbstractSubaccountApprovalNonceable: AbstractSubaccountApprovalNonceable_1.default,
68
70
  ArbitrumNodeInterface: ArbitrumNodeInterface_1.default,
69
71
  ArbSys: ArbSys_1.default,
72
+ ChainlinkPriceFeedProvider: ChainlinkPriceFeedProvider_1.default,
70
73
  ClaimHandler: ClaimHandler_1.default,
71
74
  CustomErrors: [...CustomErrors_1.default, ...CustomErrorsV2_2_1_1.default],
72
75
  DataStore: DataStore_1.default,
@@ -91,6 +94,7 @@ exports.abis = {
91
94
  MultichainSubaccountRouter: MultichainSubaccountRouter_1.default,
92
95
  MultichainTransferRouter: MultichainTransferRouter_1.default,
93
96
  MultichainVault: MultichainVault_1.default,
97
+ Pausable: Pausable_1.default,
94
98
  ReferralStorage: ReferralStorage_1.default,
95
99
  RelayParams: RelayParams_1.default,
96
100
  RewardReader: RewardReader_1.default,
@@ -23,6 +23,7 @@ const api_12 = require("../../utils/positions/api");
23
23
  const api_13 = require("../../utils/prices/api");
24
24
  const api_14 = require("../../utils/rates/api");
25
25
  const api_15 = require("../../utils/staking/api");
26
+ const stream_1 = require("../../utils/stream");
26
27
  const api_16 = require("../../utils/subaccount/api");
27
28
  const sdkClient_1 = require("../../utils/subaccount/sdkClient");
28
29
  const api_17 = require("../../utils/tokens/api");
@@ -43,8 +44,10 @@ Object.defineProperty(exports, "HttpClientWithFallback", { enumerable: true, get
43
44
  var express_1 = require("../../configs/express");
44
45
  Object.defineProperty(exports, "getGasPaymentTokens", { enumerable: true, get: function () { return express_1.getGasPaymentTokens; } });
45
46
  class GmxApiSdk {
46
- constructor({ chainId, apiUrl, api }) {
47
+ constructor({ chainId, apiUrl, api, streamUrl, webSocketImpl, }) {
47
48
  this.preparedSubaccountApprovals = new Map();
49
+ this.streamUrlOverride = streamUrl;
50
+ this.webSocketImpl = webSocketImpl;
48
51
  if (api) {
49
52
  this.ctx = { chainId, api };
50
53
  return;
@@ -107,6 +110,22 @@ class GmxApiSdk {
107
110
  fetchTokens() {
108
111
  return (0, api_17.fetchApiTokens)(this.ctx);
109
112
  }
113
+ getStreamClient() {
114
+ if (!this._streamClient) {
115
+ const url = this.streamUrlOverride ?? (0, stream_1.toStreamUrl)(this.ctx.api.url);
116
+ this._streamClient = new stream_1.WsStreamClient({ url, webSocketImpl: this.webSocketImpl });
117
+ }
118
+ return this._streamClient;
119
+ }
120
+ fetchTokenPrices() {
121
+ return (0, api_13.fetchApiTokenPrices)(this.ctx);
122
+ }
123
+ watchTokenPrices() {
124
+ return (0, stream_1.createChannelSubscription)(this.getStreamClient(), "prices", api_13.parseApiTokenPrices);
125
+ }
126
+ watchCandles(params) {
127
+ return (0, stream_1.createChannelSubscription)(this.getStreamClient(), `candles:${params.symbol}:${params.timeframe}`, (raw) => raw);
128
+ }
110
129
  fetchPositionsInfo(params) {
111
130
  return (0, api_12.fetchApiPositionsInfo)(this.ctx, params);
112
131
  }
@@ -16,6 +16,7 @@ const GAS_PAYMENT_TOKENS = {
16
16
  (0, tokens_1.getTokenBySymbol)(chains_1.ARBITRUM, "USDC").address,
17
17
  (0, tokens_1.getTokenBySymbol)(chains_1.ARBITRUM, "WETH").address,
18
18
  (0, tokens_1.getTokenBySymbol)(chains_1.ARBITRUM, "USDT").address,
19
+ (0, tokens_1.getTokenBySymbol)(chains_1.ARBITRUM, "USDG").address,
19
20
  ],
20
21
  [chains_1.AVALANCHE]: [
21
22
  (0, tokens_1.getTokenBySymbol)(chains_1.AVALANCHE, "USDC").address,
@@ -134,6 +134,9 @@ exports.TOKENS = {
134
134
  isStable: true,
135
135
  imageUrl: "https://coin-images.coingecko.com/coins/images/51281/small/GDN_USDG_Token_200x200.png?1730484111",
136
136
  explorerUrl: "https://arbiscan.io/token/0x004B506865409877C9fA29bfb1ebA929984B9bbC",
137
+ isPermitSupported: true,
138
+ // the contract has no version() to read it from
139
+ contractVersion: "1",
137
140
  },
138
141
  {
139
142
  name: "Tether",
@@ -259,6 +259,21 @@ const ONE_USD = 1000000000000000000000000000000n;
259
259
  (0, vitest_1.expect)((0, numbers_1.formatUsdPrice)(ONE_USD / 10000000000n)).toBe("<\u00a0$\u200a0.000000001");
260
260
  });
261
261
  });
262
+ (0, vitest_1.describe)("formatBigUsd", () => {
263
+ (0, vitest_1.it)("shows cents for sub-dollar amounts and whole dollars otherwise PRO-4565", () => {
264
+ const cases = [
265
+ [0n, "$ 0"],
266
+ [ONE_USD / 200n, "< $ 0.01"],
267
+ [(ONE_USD * 229n) / 10000n, "$ 0.02"],
268
+ [(ONE_USD * 99n) / 100n, "$ 0.99"],
269
+ [ONE_USD, "$ 1"],
270
+ [(ONE_USD * 7058342n) / 10n, "$ 705,834"],
271
+ ];
272
+ for (const [amount, expected] of cases) {
273
+ (0, vitest_1.expect)((0, numbers_1.formatBigUsd)(amount)).toBe(expected);
274
+ }
275
+ });
276
+ });
262
277
  (0, vitest_1.describe)("formatNumberHuman", () => {
263
278
  vitest_1.it.each([
264
279
  [999.94, 1, "999.9"],
@@ -120,13 +120,23 @@ function decodeMulticall(data) {
120
120
  const [decodedDstEid] = (0, viem_1.decodeAbiParameters)([{ type: "uint32" }], params.data);
121
121
  (0, vitest_1.expect)(decodedDstEid).toBe(multichain_1.CHAIN_ID_TO_ENDPOINT_ID[chains_1.SOURCE_BASE_MAINNET]);
122
122
  });
123
- (0, vitest_1.it)("defaults minAmountOut to amount when slippage is unspecified", () => {
123
+ (0, vitest_1.it)("leaves 50 bps for the bridge fee when slippage is unspecified", () => {
124
124
  const params = (0, api_1.buildCrossChainWithdrawBridgeOutParams)({
125
125
  tokenAddress: USDC_ARBITRUM,
126
126
  amount: 1000000n,
127
127
  dstChainId: chains_1.SOURCE_BASE_MAINNET,
128
128
  stargateAddress: STARGATE_USDC_ARBITRUM,
129
129
  });
130
+ (0, vitest_1.expect)(params.minAmountOut).toBe(995000n);
131
+ });
132
+ (0, vitest_1.it)("keeps minAmountOut equal to amount with zero slippage", () => {
133
+ const params = (0, api_1.buildCrossChainWithdrawBridgeOutParams)({
134
+ tokenAddress: USDC_ARBITRUM,
135
+ amount: 1000000n,
136
+ dstChainId: chains_1.SOURCE_BASE_MAINNET,
137
+ stargateAddress: STARGATE_USDC_ARBITRUM,
138
+ slippageBps: 0,
139
+ });
130
140
  (0, vitest_1.expect)(params.minAmountOut).toBe(1000000n);
131
141
  });
132
142
  });
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.executeSameChainWithdraw = exports.executeSameChainDeposit = exports.buildCrossChainWithdrawBridgeOutParams = exports.buildSameChainWithdrawTxn = exports.buildSameChainWithdrawBridgeOutParams = exports.getEmptyBridgeFeeParams = exports.buildSameChainDepositTxn = void 0;
3
+ exports.executeSameChainWithdraw = exports.executeSameChainDeposit = exports.buildCrossChainWithdrawBridgeOutParams = exports.DEFAULT_CROSS_CHAIN_WITHDRAW_SLIPPAGE_BPS = exports.buildSameChainWithdrawTxn = exports.buildSameChainWithdrawBridgeOutParams = exports.getEmptyBridgeFeeParams = exports.buildSameChainDepositTxn = void 0;
4
4
  const viem_1 = require("viem");
5
5
  const getAbi_1 = require("../../abis/getAbi");
6
6
  const contracts_1 = require("../../configs/contracts");
@@ -86,6 +86,7 @@ function buildSameChainWithdrawTxn(request) {
86
86
  return { to: router, data, value: 0n };
87
87
  }
88
88
  exports.buildSameChainWithdrawTxn = buildSameChainWithdrawTxn;
89
+ exports.DEFAULT_CROSS_CHAIN_WITHDRAW_SLIPPAGE_BPS = 50;
89
90
  /**
90
91
  * `BridgeOutParams.data` for cross-chain delivery is a single `uint32 dstEid`
91
92
  * pointing at the destination LayerZero endpoint; the on-chain provider takes
@@ -94,7 +95,7 @@ exports.buildSameChainWithdrawTxn = buildSameChainWithdrawTxn;
94
95
  * `utils/express/utils/bridgeOutUtils`.
95
96
  */
96
97
  function buildCrossChainWithdrawBridgeOutParams(params) {
97
- const { tokenAddress, amount, dstChainId, stargateAddress, slippageBps = 0 } = params;
98
+ const { tokenAddress, amount, dstChainId, stargateAddress, slippageBps = exports.DEFAULT_CROSS_CHAIN_WITHDRAW_SLIPPAGE_BPS, } = params;
98
99
  if (!Number.isInteger(slippageBps) || slippageBps < 0 || slippageBps >= 10000) {
99
100
  throw new Error(`slippageBps must be an integer in range [0, 10000), got ${slippageBps}`);
100
101
  }
@@ -34,6 +34,7 @@ exports.isUint256 = isUint256;
34
34
  exports.PERCENT_PRECISION_DECIMALS = exports.PRECISION_DECIMALS - 2;
35
35
  const MAX_EXCEEDING_THRESHOLD = "1000000000";
36
36
  const MIN_EXCEEDING_THRESHOLD = "0.01";
37
+ const MIN_EXCEEDING_THRESHOLD_DECIMALS = 2;
37
38
  exports.TRIGGER_PREFIX_ABOVE = ">";
38
39
  exports.TRIGGER_PREFIX_BELOW = "<";
39
40
  function isNonZero(value) {
@@ -201,7 +202,10 @@ function formatUsdParts(usd, opts = {}) {
201
202
  const maybePlus = opts.displayPlus ? "+" : "";
202
203
  const sign = usd < 0n ? "-" : maybePlus;
203
204
  const symbol = exceedingInfo.symbol ? `${exceedingInfo.symbol}\u00a0` : "";
204
- const displayUsd = (0, exports.formatAmount)(exceedingInfo.value, exports.USD_DECIMALS, displayDecimals, true);
205
+ const valueDecimals = exceedingInfo.symbol === exports.TRIGGER_PREFIX_BELOW
206
+ ? Math.max(displayDecimals, MIN_EXCEEDING_THRESHOLD_DECIMALS)
207
+ : displayDecimals;
208
+ const displayUsd = (0, exports.formatAmount)(exceedingInfo.value, exports.USD_DECIMALS, valueDecimals, true);
205
209
  return (0, parts_1.numberParts)(symbol, sign, parts_1.USD_PART, displayUsd);
206
210
  }
207
211
  exports.formatUsdParts = formatUsdParts;
@@ -211,9 +215,11 @@ function formatUsd(usd, opts = {}) {
211
215
  }
212
216
  exports.formatUsd = formatUsd;
213
217
  function formatBigUsdParts(amount, opts = {}) {
218
+ // whole dollars would show a few cents as $0
219
+ const defaultDisplayDecimals = amount !== 0n && roundsToZero(amount, exports.USD_DECIMALS, 0) ? 2 : 0;
214
220
  return formatUsdParts(amount, {
215
221
  maxThreshold: "9999999999999999999999999",
216
- displayDecimals: opts.displayDecimals ?? 0,
222
+ displayDecimals: opts.displayDecimals ?? defaultDisplayDecimals,
217
223
  });
218
224
  }
219
225
  exports.formatBigUsdParts = formatBigUsdParts;
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.fetchApiOhlcv = void 0;
3
+ exports.fetchApiTokenPrices = exports.parseApiTokenPrices = exports.fetchApiOhlcv = void 0;
4
+ const numbers_1 = require("../numbers");
5
+ const objects_1 = require("../objects");
4
6
  async function fetchApiOhlcv(ctx, params) {
5
7
  return ctx.api.fetchJson("/v1/prices/ohlcv", {
6
8
  query: {
@@ -12,3 +14,15 @@ async function fetchApiOhlcv(ctx, params) {
12
14
  });
13
15
  }
14
16
  exports.fetchApiOhlcv = fetchApiOhlcv;
17
+ function parseApiTokenPrices(raw) {
18
+ return (0, numbers_1.deserializeBigIntsInObject)(raw, { handleInts: true });
19
+ }
20
+ exports.parseApiTokenPrices = parseApiTokenPrices;
21
+ async function fetchApiTokenPrices(ctx) {
22
+ const raw = await ctx.api.fetchJson("/v1/prices/tickers");
23
+ if (!(0, objects_1.isRecord)(raw) || !(0, objects_1.isRecord)(raw.prices) || typeof raw.originTs !== "number") {
24
+ throw new Error("Invalid /v1/prices/tickers response");
25
+ }
26
+ return { prices: parseApiTokenPrices(raw.prices), originTs: raw.originTs };
27
+ }
28
+ exports.fetchApiTokenPrices = fetchApiTokenPrices;
@@ -0,0 +1,363 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.WsStreamClient = exports.callListener = void 0;
7
+ const isomorphic_ws_1 = __importDefault(require("isomorphic-ws"));
8
+ const DEFAULT_RECONNECT_BASE_MS = 500;
9
+ const DEFAULT_RECONNECT_MAX_MS = 10000;
10
+ const DEFAULT_PROBE_INTERVAL_MS = 15000;
11
+ const DEFAULT_PROBE_TIMEOUT_MS = 10000;
12
+ const CONNECT_TIMEOUT_MS = 10000;
13
+ const IDLE_CLOSE_MS = 10000;
14
+ // a socket that stayed up this long proves the path works; one dropped sooner keeps backing off
15
+ const STABLE_CONNECTION_MS = 30000;
16
+ const REFUSED_MESSAGE = "subscription refused";
17
+ function resolveWebSocketCtor(injected) {
18
+ return injected ?? isomorphic_ws_1.default;
19
+ }
20
+ function callListener(listener, value) {
21
+ try {
22
+ listener(value);
23
+ }
24
+ catch (error) {
25
+ queueMicrotask(() => {
26
+ throw error;
27
+ });
28
+ }
29
+ }
30
+ exports.callListener = callListener;
31
+ class WsStreamClient {
32
+ constructor(params) {
33
+ this.connectionStatus = "closed";
34
+ this.listeners = new Map();
35
+ this.connectionStatusListeners = new Set();
36
+ this.lastFrameByChannel = new Map();
37
+ this.originTsByChannel = new Map();
38
+ this.refusalByChannel = new Map();
39
+ this.pendingOps = [];
40
+ this.reconnectAttempt = 0;
41
+ this.messageCount = 0;
42
+ this.closedByUser = false;
43
+ this.url = params.url;
44
+ this.WebSocketImpl = resolveWebSocketCtor(params.webSocketImpl);
45
+ this.reconnectBaseMs = params.reconnectBaseMs ?? DEFAULT_RECONNECT_BASE_MS;
46
+ this.reconnectMaxMs = params.reconnectMaxMs ?? DEFAULT_RECONNECT_MAX_MS;
47
+ this.probeIntervalMs = params.probeIntervalMs ?? DEFAULT_PROBE_INTERVAL_MS;
48
+ this.probeTimeoutMs = params.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
49
+ this.random = params.random ?? Math.random;
50
+ }
51
+ subscribe(channel, listener, onError) {
52
+ const subscriber = { onFrame: listener, onError };
53
+ clearTimeout(this.idleCloseTimer);
54
+ const existing = this.listeners.get(channel);
55
+ if (existing) {
56
+ existing.add(subscriber);
57
+ const frame = this.lastFrameByChannel.get(channel);
58
+ const refusal = this.refusalByChannel.get(channel);
59
+ queueMicrotask(() => this.replay(channel, subscriber, frame, refusal));
60
+ }
61
+ else {
62
+ this.listeners.set(channel, new Set([subscriber]));
63
+ }
64
+ this.ensureConnected();
65
+ if (!existing && this.connectionStatus === "live") {
66
+ this.sendOp("subscribe", [channel]);
67
+ }
68
+ return () => {
69
+ const current = this.listeners.get(channel);
70
+ if (!current?.delete(subscriber)) {
71
+ return;
72
+ }
73
+ if (current.size === 0) {
74
+ this.listeners.delete(channel);
75
+ this.lastFrameByChannel.delete(channel);
76
+ this.originTsByChannel.delete(channel);
77
+ this.refusalByChannel.delete(channel);
78
+ if (this.connectionStatus === "live") {
79
+ this.sendOp("unsubscribe", [channel]);
80
+ }
81
+ }
82
+ if (this.listeners.size === 0) {
83
+ this.idleCloseTimer = setTimeout(() => this.close(), IDLE_CLOSE_MS);
84
+ }
85
+ };
86
+ }
87
+ subscribeConnectionStatus(listener) {
88
+ this.connectionStatusListeners.add(listener);
89
+ return () => {
90
+ this.connectionStatusListeners.delete(listener);
91
+ };
92
+ }
93
+ ensureConnected() {
94
+ if (this.ws || this.reconnectTimer) {
95
+ return;
96
+ }
97
+ this.closedByUser = false;
98
+ this.connect();
99
+ }
100
+ canConnect() {
101
+ return !this.ws && !this.closedByUser && this.listeners.size > 0;
102
+ }
103
+ connect() {
104
+ if (!this.canConnect()) {
105
+ return;
106
+ }
107
+ this.setConnectionStatus(this.connectionStatus === "closed" ? "connecting" : "reconnecting");
108
+ if (!this.canConnect()) {
109
+ return;
110
+ }
111
+ this.pendingOps = [];
112
+ this.refusalByChannel.clear();
113
+ this.openedAt = undefined;
114
+ let ws;
115
+ try {
116
+ ws = new this.WebSocketImpl(this.url);
117
+ }
118
+ catch {
119
+ this.scheduleReconnect();
120
+ return;
121
+ }
122
+ this.ws = ws;
123
+ this.connectTimeoutTimer = setTimeout(() => {
124
+ if (this.ws === ws && this.connectionStatus !== "live") {
125
+ this.dropSocket();
126
+ this.scheduleReconnect();
127
+ }
128
+ }, CONNECT_TIMEOUT_MS);
129
+ ws.onopen = () => {
130
+ if (this.ws !== ws) {
131
+ return;
132
+ }
133
+ clearTimeout(this.connectTimeoutTimer);
134
+ this.openedAt = Date.now();
135
+ const channels = [...this.listeners.keys()];
136
+ if (channels.length) {
137
+ this.sendOp("subscribe", channels);
138
+ }
139
+ this.setConnectionStatus("live");
140
+ };
141
+ ws.onmessage = (ev) => {
142
+ if (this.ws === ws) {
143
+ this.onMessage(ev.data);
144
+ }
145
+ };
146
+ ws.onclose = () => {
147
+ if (this.ws === ws) {
148
+ this.onClose();
149
+ }
150
+ };
151
+ ws.onerror = () => {
152
+ // a close event always follows; reconnection is handled there
153
+ };
154
+ }
155
+ onMessage(raw) {
156
+ this.messageCount += 1;
157
+ const text = typeof raw === "string" ? raw : String(raw);
158
+ let parsed;
159
+ try {
160
+ parsed = JSON.parse(text);
161
+ }
162
+ catch {
163
+ return;
164
+ }
165
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
166
+ return;
167
+ }
168
+ const frame = parsed;
169
+ if ("op" in frame) {
170
+ this.onOp(frame);
171
+ return;
172
+ }
173
+ if (frame.type !== "snapshot") {
174
+ return;
175
+ }
176
+ if (frame.data === undefined) {
177
+ return;
178
+ }
179
+ const set = this.listeners.get(frame.ch);
180
+ if (!set) {
181
+ return;
182
+ }
183
+ if (typeof frame.originTs === "number") {
184
+ const newest = this.originTsByChannel.get(frame.ch);
185
+ if (newest !== undefined && frame.originTs < newest) {
186
+ return;
187
+ }
188
+ this.originTsByChannel.set(frame.ch, frame.originTs);
189
+ }
190
+ const payload = {
191
+ data: frame.data,
192
+ serverTs: frame.serverTs,
193
+ originTs: frame.originTs,
194
+ receivedAt: Date.now(),
195
+ };
196
+ this.lastFrameByChannel.set(frame.ch, payload);
197
+ this.refusalByChannel.delete(frame.ch);
198
+ for (const subscriber of set) {
199
+ callListener(subscriber.onFrame, payload);
200
+ }
201
+ }
202
+ onOp(frame) {
203
+ if (frame.op === "error") {
204
+ if (!Array.isArray(frame.channels)) {
205
+ return;
206
+ }
207
+ const pending = this.pendingOps[0];
208
+ for (const channel of frame.channels) {
209
+ if (pending?.op === "subscribe") {
210
+ pending.channels = pending.channels.filter((requested) => requested !== channel);
211
+ }
212
+ this.refuse(channel, frame.message);
213
+ }
214
+ return;
215
+ }
216
+ if (frame.op !== "ack") {
217
+ return;
218
+ }
219
+ const pending = this.pendingOps.shift();
220
+ if (pending?.op !== "subscribe" || !Array.isArray(frame.channels)) {
221
+ return;
222
+ }
223
+ for (const channel of pending.channels) {
224
+ if (!frame.channels.includes(channel)) {
225
+ this.refuse(channel, REFUSED_MESSAGE);
226
+ }
227
+ }
228
+ }
229
+ refuse(channel, message) {
230
+ const set = this.listeners.get(channel);
231
+ if (!set) {
232
+ return;
233
+ }
234
+ const error = { message };
235
+ this.refusalByChannel.set(channel, error);
236
+ for (const subscriber of set) {
237
+ if (subscriber.onError) {
238
+ callListener(subscriber.onError, error);
239
+ }
240
+ }
241
+ }
242
+ replay(channel, subscriber, frame, refusal) {
243
+ if (!this.listeners.get(channel)?.has(subscriber)) {
244
+ return;
245
+ }
246
+ // only while still current: anything newer already reached this subscriber directly
247
+ if (frame && frame === this.lastFrameByChannel.get(channel)) {
248
+ callListener(subscriber.onFrame, frame);
249
+ }
250
+ if (refusal && refusal === this.refusalByChannel.get(channel) && subscriber.onError) {
251
+ callListener(subscriber.onError, refusal);
252
+ }
253
+ }
254
+ onClose() {
255
+ this.ws = undefined;
256
+ clearTimeout(this.connectTimeoutTimer);
257
+ this.noteSocketEnded();
258
+ if (this.closedByUser || this.listeners.size === 0) {
259
+ this.setConnectionStatus("closed");
260
+ return;
261
+ }
262
+ this.scheduleReconnect();
263
+ }
264
+ noteSocketEnded() {
265
+ if (this.openedAt !== undefined && Date.now() - this.openedAt >= STABLE_CONNECTION_MS) {
266
+ this.reconnectAttempt = 0;
267
+ }
268
+ this.openedAt = undefined;
269
+ }
270
+ scheduleReconnect() {
271
+ const ceiling = Math.min(this.reconnectMaxMs, this.reconnectBaseMs * 2 ** this.reconnectAttempt);
272
+ this.reconnectAttempt += 1;
273
+ this.reconnectTimer = setTimeout(() => {
274
+ this.reconnectTimer = undefined;
275
+ this.connect();
276
+ }, ceiling / 2 + (this.random() * ceiling) / 2);
277
+ this.setConnectionStatus("reconnecting");
278
+ }
279
+ startProbe() {
280
+ this.probeTimer = setTimeout(() => {
281
+ const messagesAtProbe = this.messageCount;
282
+ this.sendOp("subscribe", []);
283
+ if (!this.probeTimeoutTimer) {
284
+ this.probeTimeoutTimer = setTimeout(() => {
285
+ this.probeTimeoutTimer = undefined;
286
+ if (this.messageCount === messagesAtProbe) {
287
+ this.dropSocket();
288
+ this.noteSocketEnded();
289
+ this.scheduleReconnect();
290
+ }
291
+ }, this.probeTimeoutMs);
292
+ }
293
+ this.startProbe();
294
+ }, this.probeIntervalMs);
295
+ }
296
+ stopProbe() {
297
+ clearTimeout(this.probeTimer);
298
+ clearTimeout(this.probeTimeoutTimer);
299
+ this.probeTimer = undefined;
300
+ this.probeTimeoutTimer = undefined;
301
+ }
302
+ sendOp(op, channels) {
303
+ try {
304
+ this.ws?.send(JSON.stringify({ op, channels }));
305
+ this.pendingOps.push({ op, channels });
306
+ }
307
+ catch {
308
+ // socket raced into a non-open state; resubscribe runs on reconnect
309
+ }
310
+ }
311
+ setConnectionStatus(status) {
312
+ if (this.connectionStatus === status) {
313
+ return;
314
+ }
315
+ this.connectionStatus = status;
316
+ if (status === "live") {
317
+ this.startProbe();
318
+ }
319
+ else {
320
+ this.stopProbe();
321
+ }
322
+ for (const listener of this.connectionStatusListeners) {
323
+ if (this.connectionStatus !== status) {
324
+ return;
325
+ }
326
+ callListener(listener, status);
327
+ }
328
+ }
329
+ dropSocket() {
330
+ const ws = this.ws;
331
+ this.ws = undefined;
332
+ clearTimeout(this.connectTimeoutTimer);
333
+ if (!ws) {
334
+ return;
335
+ }
336
+ // onerror stays attached: ws in Node throws on an unhandled "error" when a CONNECTING socket is closed
337
+ ws.onopen = null;
338
+ ws.onmessage = null;
339
+ ws.onclose = null;
340
+ try {
341
+ ws.close();
342
+ }
343
+ catch {
344
+ // already closing
345
+ }
346
+ }
347
+ close() {
348
+ this.closedByUser = true;
349
+ clearTimeout(this.idleCloseTimer);
350
+ if (this.reconnectTimer) {
351
+ clearTimeout(this.reconnectTimer);
352
+ this.reconnectTimer = undefined;
353
+ }
354
+ this.listeners.clear();
355
+ this.lastFrameByChannel.clear();
356
+ this.originTsByChannel.clear();
357
+ this.refusalByChannel.clear();
358
+ this.reconnectAttempt = 0;
359
+ this.dropSocket();
360
+ this.setConnectionStatus("closed");
361
+ }
362
+ }
363
+ exports.WsStreamClient = WsStreamClient;