Skip to content

📈 Get real-time stocks from TradingView

Harden RC.1 network recovery and add HTTP/WebSocket proxy support (#343)

Mathieu Colmon98fcee3aaed3
diff --git a/docs/low-level-api.md b/docs/low-level-api.md
index 021ee2f..d9c1c29 100644
--- a/docs/low-level-api.md
+++ b/docs/low-level-api.md
@@ -174,7 +174,24 @@ All accept `{ fetch?, signal?, headers? }`; functions that can use an account al
## Transport
-The default transport uses the [`ws`](https://github.com/websockets/ws) package, which works in Node and Bun. To use a proxy or another websocket implementation, pass `transport`:
+The default transport uses the [`ws`](https://github.com/websockets/ws) package, which works in Node and Bun.
+
+### Proxy
+
+`createProxy` returns a `fetch` and a `transport` that both go through the same proxy, for the websocket, the account lookup and HTTP functions:
+
+```ts
+import { createProxy, getCandles, searchMarkets, TradingViewClient } from '@mathieuc/tradingview';
+
+const proxy = createProxy(process.env.HTTPS_PROXY!); // e.g. http://user:[email protected]:3128
+const client = new TradingViewClient({ ...proxy, credentials });
+await getCandles({ symbol: 'BINANCE:BTCUSDT', clientOptions: proxy });
+await searchMarkets('BTC', { fetch: proxy.fetch });
+```
+
+A `http:` or `https:` proxy URL uses a built-in CONNECT tunnel (basic auth from the URL; `{ tls: { ca } }` trusts an inspecting proxy). On Node, a SOCKS or other proxy `Agent` (for example from `socks-proxy-agent`) can be passed instead of the URL. On Bun, the URL is handed to Bun's native proxy support, which requires Bun 1.3.6 or later.
+
+To use another websocket implementation, pass `transport`:
```ts
import type { TransportFactory } from '@mathieuc/tradingview';
diff --git a/docs/v4-backlog-triage.md b/docs/v4-backlog-triage.md
index 29cb635..c3481d2 100644
--- a/docs/v4-backlog-triage.md
+++ b/docs/v4-backlog-triage.md
@@ -69,7 +69,7 @@ Rows describe capability disposition, not automatic authorization to close repor
| [#192](https://github.com/Mathieu2301/TradingView-API/issues/192) 15 minutes delay for MOEX market | Upstream entitlement / missing | Exchange real-time rights and server delays must be checked with that venue/account. getScreener is available since beta.3, but does not grant exchange real-time rights. |
| [#191](https://github.com/Mathieu2301/TradingView-API/issues/191) How to install? | Covered | README installation/quick start, docs/data-api.md and examples cover the requested entry point; package consumer smoke passes. |
| [#188](https://github.com/Mathieu2301/TradingView-API/issues/188) Pine 'referencing length of a series' error after about 12 hours | Needs long-run reproduction | 12-hour Pine max_bars_back failure is not a normal indicator input. Need script and long-running capture; short endurance runs cannot resolve it. |
-| [#184](https://github.com/Mathieu2301/TradingView-API/issues/184) Proxy support | Partial | Custom WebSocket transport and HTTP fetch hooks permit adapters, but no documented/tested unified proxy configuration. PR #208 cannot be merged unchanged. |
+| [#184](https://github.com/Mathieu2301/TradingView-API/issues/184) Proxy support | Implemented | `createProxy(url \| agent)` returns a matching `fetch` and websocket `transport`; loopback CONNECT proxy tests cover HTTP, WS, HTTPS/WSS and auth failures on Node and Bun 1.3.6+. PR #208 cannot be merged unchanged. |
| [#182](https://github.com/Mathieu2301/TradingView-API/issues/182) Can't load indicator - (Study error: Study not allowed in this connection) | Upstream auth requirement | Authenticated Pine path is live-tested; anonymous study refusal is not eliminated. Recheck original script with credentials. |
| [#179](https://github.com/Mathieu2301/TradingView-API/issues/179) "Calculation timed out" error and account bans | Upstream limits | Server study/session/calculation limits are not removed by V4. Bound concurrency, release sessions and reproduce account-specific thresholds; no bulk retry flood. |
| [#174](https://github.com/Mathieu2301/TradingView-API/issues/174) How to use Supertrend? | Partial documentation | Indicator values/events and Pine discovery are documented. Supertrend transition semantics and plot selection deserve a focused example. |
@@ -130,7 +130,7 @@ Rows describe capability disposition, not automatic authorization to close repor
| [#318](https://github.com/Mathieu2301/TradingView-API/pull/318) | V4 uses standalone HTTP functions and patched Vitest 4.1.11. The original Vitest 3 baseline no longer applies. | Audit confirmed GHSA-82fw-gwwq-j7x9 in Vitest/mocker. Updated to patched Vitest 4.1.11+ in this change; not the older vulnerable 4.1.9 from the PR. |
| [#289](https://github.com/Mathieu2301/TradingView-API/pull/289) | General chart event registration exists via Emitter.on/onAny and event tests. | Superseded for V4; no need to port V3 callback storage. |
| [#219](https://github.com/Mathieu2301/TradingView-API/pull/219) | Native TS build emits declarations and package smoke compiles a strict consumer. | Superseded for V4; avoid stale generated V3 declarations. |
-| [#208](https://github.com/Mathieu2301/TradingView-API/pull/208) | Axios/ws proxy patch targets removed V3 architecture. V4 offers transport/fetch injection, not a turnkey proxy. | Preserve intent; implement/test an adapter recipe across both HTTP and WS before resolving #184. |
+| [#208](https://github.com/Mathieu2301/TradingView-API/pull/208) | Axios/ws proxy patch targets removed V3 architecture. V4 offers transport/fetch injection, not a turnkey proxy. | Intent preserved by `createProxy` (no global `SetAgent`, no new dependency; SOCKS via a caller-supplied agent on Node). |
| [#204](https://github.com/Mathieu2301/TradingView-API/pull/204) | Distinct history-data/HistorySession protocol absent in V4. Author’s historical Premium run is not current verification. | Port only after current capture/entitlement proof; share report decoding and add failure/cleanup tests. |
## Verification for this change
diff --git a/examples/builtin-indicator.js b/examples/builtin-indicator.js
index 551bc3b..ee893fe 100644
--- a/examples/builtin-indicator.js
+++ b/examples/builtin-indicator.js
@@ -15,8 +15,11 @@ study.on('update', async () => {
.filter((h) => h.lastBarTime === 0) // Profile that ends on the latest bar
.sort((a, b) => b.priceHigh - a.priceHigh);
if (!rows.length) return;
+ // rate holds the [up, down] volume of each row: scale bars to 50 characters.
+ const max = Math.max(...rows.map((h) => h.rate[0] + h.rate[1]));
for (const h of rows) {
- console.log(`~ ${Math.round((h.priceHigh + h.priceLow) / 2)} € : ${'_'.repeat(h.rate[0] / 3)}${'_'.repeat(h.rate[1] / 3)}`);
+ const bar = (volume) => '_'.repeat(Math.round((volume / max) * 50));
+ console.log(`~ ${Math.round((h.priceHigh + h.priceLow) / 2)} € : ${bar(h.rate[0])}${bar(h.rate[1])}`);
}
await client.close();
});
diff --git a/examples/replay.js b/examples/replay.js
index d48b46c..df50510 100644
--- a/examples/replay.js
+++ b/examples/replay.js
@@ -22,14 +22,28 @@ if (credentials) {
let ended = false;
chart.on('replayEnd', () => { ended = true; });
-await new Promise((resolve) => { chart.once('replayLoaded', resolve); });
-while (!ended) {
- await chart.replayStep(1);
+// replayStep() resolves when the server acknowledges the step; bars and study
+// values arrive afterwards in chart updates, so print them from the 'update'
+// event once every study has computed the latest bar.
+let lastTime;
+chart.on('update', () => {
const bar = chart.lastCandle;
- const values = Object.fromEntries(Object.entries(studies).map(([name, study]) => [name, study.values.at(-1)]));
- console.log(bar && new Date(bar.time * 1000).toISOString(), bar?.close, values);
-}
+ if (!bar || bar.time === lastTime) return;
+ const values = {};
+ for (const [name, study] of Object.entries(studies)) {
+ const row = study.values.find((v) => v.$time === bar.time);
+ if (!row) return;
+ values[name] = Object.entries(row).find(([key]) => key !== '$time')?.[1]; // First plot
+ }
+ lastTime = bar.time;
+ console.log(new Date(bar.time * 1000).toISOString(), bar.close, values);
+});
+
+// Wait for the first bars before stepping.
+await new Promise((resolve) => { chart.once('update', resolve); });
+while (!ended) await chart.replayStep(1);
+await new Promise((resolve) => { setTimeout(resolve, 1000); }); // Let the last bars arrive
// chart.replayStart(1000) plays automatically; chart.replayStop() pauses.
await client.close();
diff --git a/scripts/smoke.mjs b/scripts/smoke.mjs
index c598f3e..d4a322d 100644
--- a/scripts/smoke.mjs
+++ b/scripts/smoke.mjs
@@ -100,9 +100,10 @@ writeFileSync(process.env.TV_CAPTURE, JSON.stringify({ args: process.argv.slice(
const tsc = join(root, 'node_modules', 'typescript', 'bin', 'tsc');
writeFileSync(join(dir, 'consumer.ts'), `
import { getCandles, TradingViewProvider, type Candle, type MarketDataProvider } from '@mathieuc/tradingview/data';
- import { getScreener, getHotlist, getWatchlists, type ScreenerResult, type Watchlist, TradingViewClient, type StudyValue } from '@mathieuc/tradingview';
- const candles: Promise<Candle[]> = getCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: '60', count: 10 });
- const client = new TradingViewClient();
+ import { getScreener, getHotlist, getWatchlists, type ScreenerResult, type Watchlist, TradingViewClient, type StudyValue, createProxy } from '@mathieuc/tradingview';
+ const proxy = createProxy('http://127.0.0.1:3128', { tls: { rejectUnauthorized: true } });
+ const candles: Promise<Candle[]> = getCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: '60', count: 10, clientOptions: proxy });
+ const client = new TradingViewClient({ ...proxy });
const chart = client.createChart();
chart.on('update', (changes: string[]) => console.log(changes, chart.candles.at(-1)?.close));
const row: StudyValue = { $time: 1 };
diff --git a/src/client/client.ts b/src/client/client.ts
index 70a890b..7bc372c 100644
--- a/src/client/client.ts
+++ b/src/client/client.ts
@@ -33,6 +33,14 @@ export interface ClientOptions {
fetch?: typeof fetch;
/** Time allowed to open and authenticate the connection. Default: 20 000 ms. */
connectTimeoutMs?: number;
+ /**
+ * Maximum silence from the server once connected. The server sends a
+ * heartbeat about every 10 seconds, so a longer silence means the network
+ * was lost without a close (sleep, NAT or proxy timeout): the client then
+ * fails with `CONNECTION_ERROR` and closes. `0` or `Infinity` disables it.
+ * Default: 60 000 ms.
+ */
+ inactivityTimeoutMs?: number;
}
export interface ClientEvents {
@@ -101,6 +109,12 @@ export class TradingViewClient extends Emitter<ClientEvents> {
#closeWaiters: Array<() => void> = [];
+ readonly #inactivityTimeout: number;
+
+ #inactivityTimer?: ReturnType<typeof setTimeout>;
+
+ #lastActivity = 0;
+
constructor(options: ClientOptions = {}) {
super();
if (options.debug === true) this.#log = (...args) => console.log('[tradingview]', ...args);
@@ -112,6 +126,7 @@ export class TradingViewClient extends Emitter<ClientEvents> {
});
this.ready.catch(() => { /* Surfaced through the error event too. */ });
+ this.#inactivityTimeout = options.inactivityTimeoutMs ?? 60_000;
const timeout = options.connectTimeoutMs ?? 20_000;
this.#readyTimer = setTimeout(() => {
this.#fail(new TradingViewError('TIMEOUT', `Connection not ready after ${timeout} ms`));
@@ -226,7 +241,7 @@ export class TradingViewClient extends Emitter<ClientEvents> {
this.#closing = true;
this.#authController.abort();
// Do not hang if the server never acknowledges the close.
- setTimeout(() => this.#onClose(1000, 'Close timeout'), 3_000).unref?.();
+ setTimeout(() => this.#forceClose(1000, 'Close timeout'), 3_000).unref?.();
this.#transport.close();
});
}
@@ -234,9 +249,25 @@ export class TradingViewClient extends Emitter<ClientEvents> {
#onOpen(): void {
this.#log?.('open');
this.emit('open');
+ this.#lastActivity = Date.now();
+ this.#watchInactivity(this.#inactivityTimeout);
this.#authenticate();
}
+ #watchInactivity(delay: number): void {
+ if (!(this.#inactivityTimeout > 0 && Number.isFinite(this.#inactivityTimeout)) || this.#closed) return;
+ // Longer timer delays overflow and fire at once.
+ this.#inactivityTimer = setTimeout(() => {
+ const idle = Date.now() - this.#lastActivity;
+ if (idle < this.#inactivityTimeout) {
+ this.#watchInactivity(this.#inactivityTimeout - idle);
+ return;
+ }
+ this.#fail(new TradingViewError('CONNECTION_ERROR', `No data from the server for ${idle} ms`), true);
+ }, Math.min(delay, 2 ** 31 - 1));
+ this.#inactivityTimer.unref?.();
+ }
+
#authenticate(): void {
if (this.#authenticated || !this.#authToken || !this.#transport.isOpen || this.#closing) return;
this.#transport.send(encodePacket('set_auth_token', [this.#authToken]));
@@ -257,6 +288,7 @@ export class TradingViewClient extends Emitter<ClientEvents> {
#onMessage(data: string): void {
if (this.#closed) return;
+ this.#lastActivity = Date.now();
for (const frame of decodeFrames(data)) {
if (frame.type === 'heartbeat') {
if (this.#transport.isOpen) this.#transport.send(encodeHeartbeat(frame.id));
@@ -294,7 +326,8 @@ export class TradingViewClient extends Emitter<ClientEvents> {
}
}
- #fail(error: TradingViewError): void {
+ /** `unresponsive`: the peer would never complete a closing handshake. */
+ #fail(error: TradingViewError, unresponsive = false): void {
if (this.#closed) return;
clearTimeout(this.#readyTimer);
const wasReady = this.#authenticated;
@@ -305,18 +338,28 @@ export class TradingViewClient extends Emitter<ClientEvents> {
if (!wasReady || error.code === 'AUTH_ERROR' || error.code === 'CONNECTION_ERROR') {
this.#closing = true;
this.#authController.abort();
- this.#transport.close();
+ if (unresponsive && this.#transport.terminate) this.#transport.terminate();
+ else this.#transport.close();
// Some transports never emit close after a failed handshake.
- setTimeout(() => this.#onClose(undefined, error.message), 3_000).unref?.();
+ setTimeout(() => this.#forceClose(undefined, error.message), 3_000).unref?.();
}
}
+ /** Ends a connection whose transport did not report its close in time. */
+ #forceClose(code?: number, reason?: string): void {
+ if (this.#closed) return;
+ // Releases the socket now instead of after the transport's own close timeout.
+ this.#transport.terminate?.();
+ this.#onClose(code, reason);
+ }
+
#onClose(code?: number, reason?: string): void {
if (this.#closed) return;
this.#closed = true;
this.#authController.abort();
this.#authenticated = false;
clearTimeout(this.#readyTimer);
+ clearTimeout(this.#inactivityTimer);
this.#log?.('close', code, reason);
const cause = this.#failure;
diff --git a/src/client/index.ts b/src/client/index.ts
index 8c239ab..de7fdee 100644
--- a/src/client/index.ts
+++ b/src/client/index.ts
@@ -2,7 +2,9 @@ export { TradingViewClient } from './client.js';
export type {
ClientEvents, ClientOptions, DebugOption, ServerName, SessionHandler,
} from './client.js';
-export { wsTransport } from './transport.js';
+export { createWsTransport, wsTransport } from './transport.js';
export type {
- Transport, TransportFactory, TransportHandlers, TransportRequest,
+ HttpAgentLike, Transport, TransportFactory, TransportHandlers, TransportRequest, WsTransportOptions,
} from './transport.js';
+export { createProxy } from './proxy.js';
+export type { ProxyAdapter, ProxyOptions, ProxyTlsOptions } from './proxy.js';
diff --git a/src/client/proxy.ts b/src/client/proxy.ts
new file mode 100644
index 0000000..cdd3a88
--- /dev/null
+++ b/src/client/proxy.ts
@@ -0,0 +1,392 @@
+import { Buffer } from 'node:buffer';
+import {
+ Agent as HttpAgent, request as httpRequest, type ClientRequestArgs, type IncomingMessage, type RequestOptions,
+} from 'node:http';
+import { Agent as HttpsAgent, request as httpsRequest } from 'node:https';
+import type { Socket } from 'node:net';
+import type { Duplex } from 'node:stream';
+import { connect as tlsConnect, type ConnectionOptions } from 'node:tls';
+import { brotliDecompressSync, gunzipSync, inflateSync } from 'node:zlib';
+
+import { TradingViewError } from '../errors.js';
+import {
+ createWsTransport, wsTransportWith, type HttpAgentLike, type TransportFactory,
+} from './transport.js';
+
+/** Subset of Node `tls.ConnectionOptions`; other Node TLS options are passed through. */
+export interface ProxyTlsOptions {
+ /** Extra trusted certificate authorities (PEM). */
+ ca?: string | Uint8Array | Array<string | Uint8Array>;
+ rejectUnauthorized?: boolean;
+ [option: string]: unknown;
+}
+
+export interface ProxyOptions {
+ /**
+ * TLS options for TradingView connections made through the tunnel, and for
+ * the proxy itself when it uses `https:`. Use `ca` to trust an inspecting
+ * corporate proxy.
+ */
+ tls?: ProxyTlsOptions;
+ /** Time allowed for the proxy to open a tunnel. Default: 20 000 ms. */
+ connectTimeoutMs?: number;
+}
+
+/** `fetch` and websocket transport that both go through the same proxy. */
+export interface ProxyAdapter {
+ /** Pass as the `fetch` option of HTTP functions, the client or the data API. */
+ fetch: typeof fetch;
+ /** Pass as the `transport` option of the client or the data API `clientOptions`. */
+ transport: TransportFactory;
+}
+
+type ConnectionCallback = (error: Error | null, socket?: Socket) => void;
+
+function proxyUrl(proxy: string | URL): URL {
+ let url: URL;
+ try {
+ url = new URL(proxy);
+ } catch {
+ throw new TradingViewError('INVALID_ARGUMENT', 'Invalid proxy URL');
+ }
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
+ throw new TradingViewError(
+ 'INVALID_ARGUMENT',
+ `Unsupported proxy protocol "${url.protocol}": use an http(s) proxy URL or pass an Agent (e.g. for SOCKS)`,
+ );
+ }
+ return url;
+}
+
+function proxyAuthorization(proxy: URL): string | undefined {
+ if (!proxy.username && !proxy.password) return undefined;
+ const user = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
+ return `Basic ${Buffer.from(user).toString('base64')}`;
+}
+
+/** Opens an HTTP CONNECT tunnel. Errors never include the proxy credentials. */
+function openTunnel(proxy: URL, target: string, options: ProxyOptions, callback: ConnectionCallback): void {
+ const secure = proxy.protocol === 'https:';
+ const authorization = proxyAuthorization(proxy);
+ const connectOptions: RequestOptions & ConnectionOptions = {
+ ...(secure ? options.tls as ConnectionOptions : {}),
+ host: proxy.hostname.replace(/^\[|\]$/g, ''),
+ port: Number(proxy.port) || (secure ? 443 : 80),
+ method: 'CONNECT',
+ path: target,
+ agent: false,
+ headers: { host: target, ...(authorization ? { 'proxy-authorization': authorization } : {}) },
+ };
+ const timeout = options.connectTimeoutMs ?? 20_000;
+ let done = false;
+ const finish = (error: Error | null, socket?: Socket) => {
+ if (done) {
+ socket?.destroy();
+ return;
+ }
+ done = true;
+ callback(error, socket);
+ };
+
+ const connect = (secure ? httpsRequest : httpRequest)(connectOptions);
+ connect.setTimeout(timeout, () => {
+ connect.destroy(new TradingViewError('TIMEOUT', `Proxy ${proxy.host} did not open a tunnel to ${target} in ${timeout} ms`));
+ });
+ connect.once('connect', (response: IncomingMessage, socket: Socket) => {
+ connect.setTimeout(0);
+ if (response.statusCode !== 200) {
+ socket.destroy();
+ finish(new TradingViewError(
+ 'CONNECTION_ERROR',
+ `Proxy ${proxy.host} refused a tunnel to ${target} (HTTP ${response.statusCode})`,
+ { details: { status: response.statusCode } },
+ ));
+ return;
+ }
+ finish(null, socket);
+ });
+ connect.once('error', (error) => {
+ finish(error instanceof TradingViewError ? error : new TradingViewError(
+ 'CONNECTION_ERROR',
+ `Proxy ${proxy.host} is unreachable: ${error.message}`,
+ { cause: error },
+ ));
+ });
+ connect.end();
+}
+
+function tunnelTarget(options: ClientRequestArgs, defaultPort: number): { host: string; target: string } {
+ const host = String(options.hostname ?? options.host ?? 'localhost');
+ const port = Number(options.port) || defaultPort;
+ return { host, target: `${host.includes(':') ? `[${host}]` : host}:${port}` };
+}
+
+type AgentCallback = (error: Error | null, stream: Duplex) => void;
+
+function connectionCallback(callback?: AgentCallback): ConnectionCallback {
+ return (error, socket) => callback?.(error, socket as Duplex);
+}
+
+/** Agent for `http:`/`ws:` targets: a CONNECT tunnel, then the raw socket. */
+class HttpTunnelAgent extends HttpAgent {
+ readonly #proxy: URL;
+
+ readonly #settings: ProxyOptions;
+
+ constructor(proxy: URL, settings: ProxyOptions) {
+ super({ keepAlive: false });
+ this.#proxy = proxy;
+ this.#settings = settings;
+ }
+
+ override createConnection(options: ClientRequestArgs, callback?: AgentCallback): undefined {
+ openTunnel(this.#proxy, tunnelTarget(options, 80).target, this.#settings, connectionCallback(callback));
+ return undefined;
+ }
+}
+
+/** Agent for `https:`/`wss:` targets: a CONNECT tunnel, then TLS to the target. */
+class HttpsTunnelAgent extends HttpsAgent {
+ readonly #proxy: URL;
+
+ readonly #settings: ProxyOptions;
+
+ constructor(proxy: URL, settings: ProxyOptions) {
+ super({ keepAlive: false });
+ this.#proxy = proxy;
+ this.#settings = settings;
+ }
+
+ override createConnection(options: ClientRequestArgs & { servername?: string }, callback?: AgentCallback): undefined {
+ const done = connectionCallback(callback);
+ const { host, target } = tunnelTarget(options, 443);
+ openTunnel(this.#proxy, target, this.#settings, (error, socket) => {
+ if (error || !socket) {
+ done(error ?? new Error('No tunnel socket'));
+ return;
+ }
+ const servername = options.servername || (host.includes(':') ? undefined : host);
+ done(null, tlsConnect({ ...this.#settings.tls as ConnectionOptions, socket, servername }));
+ });
+ return undefined;
+ }
+}
+
+const REDIRECTS = new Set([301, 302, 303, 307, 308]);
+const NULL_BODY = new Set([101, 103, 204, 205, 304]);
+
+function decodeBody(body: Buffer, encoding: string | null): Buffer {
+ switch (encoding?.trim().toLowerCase()) {
+ case 'gzip':
+ case 'x-gzip':
+ return gunzipSync(body);
+ case 'deflate':
+ return inflateSync(body);
+ case 'br':
+ return brotliDecompressSync(body);
+ default:
+ return body;
+ }
+}
+
+function abortError(signal: AbortSignal): unknown {
+ return signal.reason ?? new DOMException('This operation was aborted', 'AbortError');
+}
+
+interface RawResponse {
+ status: number;
+ statusText: string;
+ headers: Headers;
+ body: Buffer;
+}
+
+function send(url: URL, method: string, headers: Headers, body: Buffer | undefined, agent: HttpAgent,
+ signal: AbortSignal | null): Promise<RawResponse> {
+ return new Promise((resolve, reject) => {
+ if (signal?.aborted) {
+ reject(abortError(signal));
+ return;
+ }
+ const outgoing: Record<string, string> = {};
+ headers.forEach((value, key) => { outgoing[key] = value; });
+ outgoing['accept-encoding'] ??= 'gzip, deflate, br';
+ if (body) outgoing['content-length'] = String(body.length);
+
+ const request = (url.protocol === 'https:' ? httpsRequest : httpRequest)(url, { method, headers: outgoing, agent });
+ const onAbort = () => request.destroy(abortError(signal as AbortSignal) as Error);
+ signal?.addEventListener('abort', onAbort, { once: true });
+ const cleanup = () => signal?.removeEventListener('abort', onAbort);
+
+ request.once('error', (error) => {
+ cleanup();
+ reject(error);
+ });
+ request.once('response', (response) => {
+ const chunks: Buffer[] = [];
+ response.on('data', (chunk: Buffer) => chunks.push(chunk));
+ response.once('error', (error) => {
+ cleanup();
+ reject(error);
+ });
+ response.once('end', () => {
+ cleanup();
+ const responseHeaders = new Headers();
+ for (let i = 0; i < response.rawHeaders.length; i += 2) {
+ responseHeaders.append(response.rawHeaders[i], response.rawHeaders[i + 1]);
+ }
+ try {
+ let decoded: Buffer = Buffer.concat(chunks);
+ if (method !== 'HEAD' && responseHeaders.has('content-encoding')) {
+ decoded = decodeBody(decoded, responseHeaders.get('content-encoding'));
+ responseHeaders.delete('content-encoding');
+ responseHeaders.delete('content-length');
+ }
+ resolve({
+ status: response.statusCode ?? 0,
+ statusText: response.statusMessage ?? '',
+ headers: responseHeaders,
+ body: decoded,
+ });
+ } catch (error) {
+ reject(error);
+ }
+ });
+ });
+ request.end(body);
+ });
+}
+
+interface ProxyRequestState {
+ url: URL;
+ method: string;
+ headers: Headers;
+ body: Buffer | undefined;
+}
+
+function followRedirect(state: ProxyRequestState, raw: RawResponse,
+ policy: Request['redirect'], redirects: number): boolean {
+ const location = raw.headers.get('location');
+ if (policy === 'manual' || !REDIRECTS.has(raw.status) || !location) return false;
+ if (policy === 'error') throw new TypeError(`Unexpected redirect from ${state.url.origin}`);
+ if (redirects >= 20) throw new TypeError('Too many redirects');
+
+ const next = new URL(location, state.url);
+ if (raw.status === 303 || ((raw.status === 301 || raw.status === 302) && state.method === 'POST')) {
+ if (state.method !== 'HEAD') state.method = 'GET';
+ state.body = undefined;
+ for (const name of ['content-type', 'content-length', 'content-encoding', 'content-language', 'content-location']) {
+ state.headers.delete(name);
+ }
+ }
+ if (next.origin !== state.url.origin) {
+ for (const name of ['authorization', 'cookie', 'proxy-authorization', 'host']) state.headers.delete(name);
+ }
+ state.url = next;
+ return true;
+}
+
+function fetchResponse(raw: RawResponse, state: ProxyRequestState, redirected: boolean): Response {
+ const response = new Response(NULL_BODY.has(raw.status) || state.method === 'HEAD' ? null : new Uint8Array(raw.body), {
+ status: raw.status, statusText: raw.statusText, headers: raw.headers,
+ });
+ Object.defineProperty(response, 'url', { value: state.url.toString() });
+ Object.defineProperty(response, 'redirected', { value: redirected });
+ return response;
+}
+
+/** `fetch` built on `node:http(s)` so requests can use an `Agent` (proxy tunnels). */
+function agentFetch(agentFor: (url: URL) => HttpAgent): typeof fetch {
+ return async (input, init) => {
+ const initial = new Request(input, init);
+ const state: ProxyRequestState = {
+ url: new URL(initial.url),
+ method: initial.method,
+ headers: new Headers(initial.headers),
+ body: initial.body ? Buffer.from(await initial.arrayBuffer()) : undefined,
+ };
+ for (let redirects = 0; ; redirects += 1) {
+ const raw = await send(state.url, state.method, state.headers, state.body, agentFor(state.url), initial.signal);
+ if (followRedirect(state, raw, initial.redirect, redirects)) continue;
+ return fetchResponse(raw, state, redirects > 0);
+ }
+ };
+}
+
+function isAgent(value: unknown): value is HttpAgentLike {
+ return typeof value === 'object' && value !== null && !(value instanceof URL);
+}
+
+/** Oldest Bun whose `WebSocket` honours the `proxy` option (older ones silently connect directly). */
+const BUN_MIN_PROXY_VERSION = [1, 3, 6];
+
+function bunVersion(): number[] | undefined {
+ const version = (globalThis as { Bun?: { version?: string } }).Bun?.version;
+ return version ? version.split(/[.-]/).slice(0, 3).map(Number) : undefined;
+}
+
+/** Bun ignores Node agents: use its native `proxy` option for `fetch` and `WebSocket`. */
+function bunProxy(proxy: string | URL | HttpAgentLike, options: ProxyOptions, version: number[]): ProxyAdapter {
+ if (isAgent(proxy)) {
+ throw new TradingViewError('INVALID_ARGUMENT', 'Bun ignores Node agents: pass the proxy URL instead');
+ }
+ const parsed = proxyUrl(proxy);
+ const url = parsed.toString();
+ const supported = BUN_MIN_PROXY_VERSION.findIndex((part, i) => version[i] !== part);
+ if (supported !== -1 && version[supported] < BUN_MIN_PROXY_VERSION[supported]) {
+ throw new TradingViewError(
+ 'INVALID_STATE',
+ `Bun ${version.join('.')} cannot proxy websockets: Bun ${BUN_MIN_PROXY_VERSION.join('.')} or later is required`,
+ );
+ }
+ const tls = options.tls ? { tls: options.tls } : {};
+ const nativeFetch = globalThis.fetch;
+ return {
+ fetch: (async (input, init) => {
+ const response = await nativeFetch(input, { ...init, proxy: url, ...tls } as unknown as RequestInit);
+ // Plain-HTTP targets are forwarded, not tunnelled: surface a refusal like a failed tunnel.
+ if (response.status === 407) {
+ await response.body?.cancel();
+ throw new TradingViewError('CONNECTION_ERROR', `Proxy ${parsed.host} refused the request (HTTP 407)`, {
+ details: { status: 407 },
+ });
+ }
+ return response;
+ }) as typeof fetch,
+ transport: wsTransportWith(() => ({ proxy: url, ...tls })),
+ };
+}
+
+/**
+ * Routes HTTP requests and websockets through a proxy. Pass the result where a
+ * `fetch` or `transport` is accepted:
+ *
+ * ```ts
+ * const proxy = createProxy('http://user:[email protected]:3128');
+ * const client = new TradingViewClient({ ...proxy, credentials });
+ * await getCandles({ symbol: 'BINANCE:BTCUSDT', clientOptions: proxy });
+ * await searchMarkets('BTC', { fetch: proxy.fetch });
+ * ```
+ *
+ * A URL creates a built-in HTTP CONNECT tunnel (`http:` or `https:` proxy,
+ * optional basic auth from the URL). On Node, any other `Agent` (for example
+ * from `socks-proxy-agent`) is used as-is for both paths. On Bun (1.3.6+),
+ * the URL is passed to Bun's native `proxy` support.
+ */
+export function createProxy(proxy: string | URL | HttpAgentLike, options: ProxyOptions = {}): ProxyAdapter {
+ const bun = bunVersion();
+ if (bun) return bunProxy(proxy, options, bun);
+
+ let agentFor: (url: URL) => HttpAgent;
+ if (isAgent(proxy)) {
+ agentFor = () => proxy as HttpAgent;
+ } else {
+ const url = proxyUrl(proxy);
+ const http = new HttpTunnelAgent(url, options);
+ const https = new HttpsTunnelAgent(url, options);
+ agentFor = (target) => (target.protocol === 'https:' || target.protocol === 'wss:' ? https : http);
+ }
+ return {
+ fetch: agentFetch(agentFor),
+ transport: createWsTransport({ agent: (url) => agentFor(new URL(url)) }),
+ };
+}
diff --git a/src/client/transport.ts b/src/client/transport.ts
index a9872d4..cfaa9f3 100644
--- a/src/client/transport.ts
+++ b/src/client/transport.ts
@@ -15,6 +15,8 @@ export interface Transport {
send(data: string): void;
/** Starts a graceful close. `onClose` must be called once closed. */
close(): void;
+ /** Destroys the connection without a closing handshake (unresponsive peer). */
+ terminate?(): void;
}
export interface TransportRequest {
@@ -25,7 +27,8 @@ export interface TransportRequest {
/**
* Creates a transport. The default uses the `ws` package (Node and Bun).
- * Provide your own to use a proxy, another websocket library or a test double.
+ * Provide your own to use another websocket library or a test double; see
+ * `createProxy` for proxies.
*/
export type TransportFactory = (request: TransportRequest, handlers: TransportHandlers) => Transport;
@@ -36,29 +39,57 @@ function toText(data: WebSocket.RawData): string {
return data.toString('utf8');
}
-/** Default transport based on the `ws` package. */
-export const wsTransport: TransportFactory = (request, handlers) => {
- // Bun's `ws` implementation ignores the `origin` option: also send it as a header.
- const socket = new WebSocket(request.url, {
- origin: request.origin,
- headers: { Origin: request.origin, ...request.headers },
+/** A Node `http.Agent` (typed structurally so declarations do not need `@types/node`). */
+export interface HttpAgentLike {
+ destroy(): void;
+}
+
+export interface WsTransportOptions {
+ /** Node `Agent` used for the handshake, e.g. a proxy agent. May depend on the websocket URL. */
+ agent?: HttpAgentLike | ((url: string) => HttpAgentLike);
+}
+
+/** Creates a transport based on the `ws` package. */
+export function createWsTransport(options: WsTransportOptions = {}): TransportFactory {
+ return wsTransportWith((url) => {
+ const agent = typeof options.agent === 'function' ? options.agent(url) : options.agent;
+ return agent ? { agent } : {};
});
- socket.on('open', () => handlers.onOpen());
- socket.on('message', (data) => handlers.onMessage(toText(data)));
- socket.on('close', (code, reason) => handlers.onClose(code, reason.toString()));
- socket.on('error', (error) => handlers.onError(error));
+}
+
+/** @internal */
+export function wsTransportWith(extra: (url: string) => Record<string, unknown>): TransportFactory {
+ // Extra `ws` client options; Bun's built-in `ws` also reads `proxy` and `tls`.
+ return (request, handlers) => {
+ // Bun's `ws` implementation ignores the `origin` option: also send it as a header.
+ const socket = new WebSocket(request.url, {
+ ...extra(request.url),
+ origin: request.origin,
+ headers: { Origin: request.origin, ...request.headers },
+ } as WebSocket.ClientOptions);
+ socket.on('open', () => handlers.onOpen());
+ socket.on('message', (data) => handlers.onMessage(toText(data)));
+ socket.on('close', (code, reason) => handlers.onClose(code, reason.toString()));
+ socket.on('error', (error) => handlers.onError(error));
- return {
- get isOpen() {
- return socket.readyState === WebSocket.OPEN;
- },
- send(data) {
- socket.send(data);
- },
- close() {
- if (socket.readyState === WebSocket.CLOSED) return;
- if (socket.readyState === WebSocket.CONNECTING) socket.terminate();
- else socket.close();
- },
+ return {
+ get isOpen() {
+ return socket.readyState === WebSocket.OPEN;
+ },
+ send(data) {
+ socket.send(data);
+ },
+ close() {
+ if (socket.readyState === WebSocket.CLOSED) return;
+ if (socket.readyState === WebSocket.CONNECTING) socket.terminate();
+ else socket.close();
+ },
+ terminate() {
+ if (socket.readyState !== WebSocket.CLOSED) socket.terminate();
+ },
+ };
};
-};
+}
+
+/** Default transport based on the `ws` package. */
+export const wsTransport: TransportFactory = wsTransportWith(() => ({}));
diff --git a/src/events.ts b/src/events.ts
index 8bf7cb9..2279ac3 100644
--- a/src/events.ts
+++ b/src/events.ts
@@ -37,7 +37,7 @@ export class Emitter<Events extends EventMap> {
once<K extends keyof Events & string>(event: K, listener: Listener<Events[K]>): Unsubscribe {
const wrapper: Listener<Events[K]> = (...args) => {
this.off(event, wrapper);
- listener(...args);
+ return listener(...args);
};
return this.on(event, wrapper);
}
@@ -76,12 +76,17 @@ export class Emitter<Events extends EventMap> {
return;
}
for (const listener of [...(set ?? [])]) Emitter.#call(() => listener(...args));
- for (const listener of [...this.#anyListeners]) Emitter.#call(() => (listener as (...a: unknown[]) => void)(event, ...args));
+ for (const listener of [...this.#anyListeners]) Emitter.#call(() => (listener as (...a: unknown[]) => unknown)(event, ...args));
}
- static #call(fn: () => void): void {
+ static #call(fn: () => unknown): void {
try {
- fn();
+ const result = fn();
+ if (result && typeof result === 'object' && 'then' in result) {
+ Promise.resolve(result).catch((error) => {
+ console.error('[tradingview] Listener threw:', error);
+ });
+ }
} catch (error) {
console.error('[tradingview] Listener threw:', error);
}
diff --git a/tests/helpers/fake-server.ts b/tests/helpers/fake-server.ts
index ffc61fd..0d531fb 100644
--- a/tests/helpers/fake-server.ts
+++ b/tests/helpers/fake-server.ts
@@ -16,12 +16,17 @@ export class FakeConnection implements Transport {
closed = false;
+ /** True after `terminate()`. */
+ terminated = false;
+
readonly sent: SentPacket[] = [];
readonly raw: string[] = [];
readonly heartbeats: number[] = [];
+ #ended = false;
+
constructor(
readonly server: FakeServer,
readonly request: TransportRequest,
@@ -49,7 +54,21 @@ export class FakeConnection implements Transport {
if (this.closed) return;
this.closed = true;
this.isOpen = false;
- setTimeout(() => this.handlers.onClose(1000, ''), 0);
+ setTimeout(() => this.#end(1000, ''), 0);
+ }
+
+ /** Like `ws`: drops the socket and reports an abnormal close. */
+ terminate(): void {
+ this.terminated = true;
+ this.closed = true;
+ this.isOpen = false;
+ setTimeout(() => this.#end(1006, ''), 0);
+ }
+
+ #end(code: number, reason: string): void {
+ if (this.#ended) return;
+ this.#ended = true;
+ this.handlers.onClose(code, reason);
}
/** Server → client: one websocket message containing these frames. */
@@ -68,7 +87,7 @@ export class FakeConnection implements Transport {
if (this.closed) return;
this.closed = true;
this.isOpen = false;
- this.handlers.onClose(code, reason);
+ this.#end(code, reason);
}
/** Packets sent with a method. */
diff --git a/tests/helpers/native-server.mjs b/tests/helpers/native-server.mjs
index 48fe567..97f02fe 100644
--- a/tests/helpers/native-server.mjs
+++ b/tests/helpers/native-server.mjs
@@ -14,4 +14,14 @@ if (process.argv[2] === 'echo') {
});
});
}
+if (process.argv[2] === 'drop') {
+ // Abrupt loss: the TCP socket is destroyed without a closing handshake.
+ new WebSocketServer({ server }).on('connection', (socket) => {
+ socket.on('message', () => socket.terminate());
+ });
+}
+if (process.argv[2] === 'silent') {
+ // Black hole: the socket stays open but nothing is read or answered, not even a close.
+ new WebSocketServer({ server }).on('connection', (socket) => socket.pause());
+}
server.listen(0, '127.0.0.1', () => console.log(server.address().port));
diff --git a/tests/helpers/proxy-server.mjs b/tests/helpers/proxy-server.mjs
new file mode 100644
index 0000000..a8717dc
--- /dev/null
+++ b/tests/helpers/proxy-server.mjs
@@ -0,0 +1,150 @@
+// Node loopback fixture: an HTTP CONNECT proxy plus the servers it tunnels to.
+// The proxy maps every requested host to 127.0.0.1, so names such as
+// `api.tradingview.test` or `data.tradingview.com` only work through it.
+// Port 443 reaches the TLS server (when a certificate is given), any other
+// port reaches the plain server. Each proxied request is logged as a JSON line.
+import { Buffer } from 'node:buffer';
+import { readFileSync } from 'node:fs';
+import { createServer, request as httpRequest } from 'node:http';
+import { createServer as createSecureServer } from 'node:https';
+import { connect } from 'node:net';
+import { gzipSync } from 'node:zlib';
+import { WebSocketServer } from 'ws';
+
+const expectedAuth = process.env.PROXY_AUTH
+ ? `Basic ${Buffer.from(process.env.PROXY_AUTH).toString('base64')}` : undefined;
+const certDir = process.argv[2];
+
+function frame(data) {
+ const text = typeof data === 'string' ? data : JSON.stringify(data);
+ return `~m~${text.length}~m~${text}`;
+}
+
+function handle(request, response) {
+ const chunks = [];
+ request.on('data', (chunk) => chunks.push(chunk));
+ request.on('end', () => {
+ const url = new URL(request.url, `http://${request.headers.host}`);
+ if (url.pathname === '/redirect') {
+ response.writeHead(302, { location: '/echo?redirected=1', 'set-cookie': ['a=1; Path=/', 'b=2; Path=/'] });
+ response.end();
+ return;
+ }
+ if (url.pathname === '/chart/') {
+ if (!/sessionid=proxy-session/.test(request.headers.cookie ?? '')) {
+ response.writeHead(302, { location: '/accounts/signin/' });
+ response.end();
+ return;
+ }
+ response.writeHead(200, { 'content-type': 'text/html' });
+ response.end('<script>window.user = {"id":42,"username":"proxied","auth_token":"proxy-token"};</script>');
+ return;
+ }
+ const body = JSON.stringify({
+ method: request.method,
+ host: request.headers.host,
+ path: url.pathname + url.search,
+ cookie: request.headers.cookie,
+ contentType: request.headers['content-type'],
+ body: Buffer.concat(chunks).toString(),
+ });
+ if (url.pathname === '/gzip') {
+ response.writeHead(200, { 'content-type': 'application/json', 'content-encoding': 'gzip' });
+ response.end(gzipSync(body));
+ return;
+ }
+ response.writeHead(200, { 'content-type': 'application/json' });
+ response.end(body);
+ });
+}
+
+function attachWebSocket(server) {
+ new WebSocketServer({ server }).on('connection', (socket, request) => {
+ if (request.url?.startsWith('/socket.io/websocket')) {
+ // Minimal TradingView greeting; acknowledges the auth token as a packet.
+ socket.send(frame({ session_id: 'proxy-hello', timestamp: 1 }));
+ socket.on('message', (data) => {
+ const token = /"set_auth_token","p":\["([^"]*)"\]/.exec(data.toString())?.[1];
+ if (token) socket.send(frame({ m: 'proxy_ack', p: [token, request.headers.origin] }));
+ });
+ return;
+ }
+ socket.on('message', (data) => {
+ socket.send(JSON.stringify({ host: request.headers.host, origin: request.headers.origin, echo: data.toString() }));
+ socket.close(1000, 'finished');
+ });
+ });
+}
+
+function listen(server) {
+ return new Promise((resolve) => { server.listen(0, '127.0.0.1', () => resolve(server.address().port)); });
+}
+
+const plain = createServer(handle);
+attachWebSocket(plain);
+const plainPort = await listen(plain);
+
+let securePort;
+const tlsOptions = certDir && { key: readFileSync(`${certDir}/key.pem`), cert: readFileSync(`${certDir}/cert.pem`) };
+if (tlsOptions) {
+ const secure = createSecureServer(tlsOptions, handle);
+ attachWebSocket(secure);
+ securePort = await listen(secure);
+}
+
+// Absolute-form forwarding for plain-HTTP targets (Bun's fetch proxies them this way).
+function forward(request, response) {
+ const target = URL.canParse(request.url) ? new URL(request.url) : undefined;
+ const authorized = !expectedAuth || request.headers['proxy-authorization'] === expectedAuth;
+ if (!target) {
+ response.writeHead(405);
+ response.end();
+ return;
+ }
+ console.log(JSON.stringify({ target: target.host, authorized }));
+ if (!authorized) {
+ response.writeHead(407, { 'proxy-authenticate': 'Basic' });
+ response.end();
+ return;
+ }
+ const headers = { ...request.headers };
+ delete headers['proxy-authorization'];
+ delete headers['proxy-connection'];
+ const upstream = httpRequest({
+ host: '127.0.0.1', port: plainPort, method: request.method, path: target.pathname + target.search, headers,
+ }, (answer) => {
+ response.writeHead(answer.statusCode, answer.rawHeaders);
+ answer.pipe(response);
+ });
+ upstream.on('error', () => response.destroy());
+ request.pipe(upstream);
+}
+
+function tunnel(request, client, head) {
+ const authorized = !expectedAuth || request.headers['proxy-authorization'] === expectedAuth;
+ console.log(JSON.stringify({ target: request.url, authorized }));
+ if (!authorized) {
+ client.end('HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic\r\n\r\n');
+ return;
+ }
+ const port = Number(request.url.split(':').pop()) === 443 ? securePort : plainPort;
+ if (!port) {
+ client.end('HTTP/1.1 502 Bad Gateway\r\n\r\n');
+ return;
+ }
+ const upstream = connect(port, '127.0.0.1', () => {
+ client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
+ if (head.length) upstream.write(head);
+ upstream.pipe(client);
+ client.pipe(upstream);
+ });
+ upstream.on('error', () => client.destroy());
+ client.on('error', () => upstream.destroy());
+}
+
+const proxy = createServer(forward).on('connect', tunnel);
+// With a certificate, the same proxy is also offered over TLS (`https:` proxy URL).
+const secureProxy = tlsOptions && createSecureServer(tlsOptions, forward).on('connect', tunnel);
+console.log(JSON.stringify({
+ proxy: await listen(proxy), secureProxy: secureProxy && await listen(secureProxy), plain: plainPort,
+}));
diff --git a/tests/live/recovery.test.ts b/tests/live/recovery.test.ts
index 9112ec5..044772f 100644
--- a/tests/live/recovery.test.ts
+++ b/tests/live/recovery.test.ts
@@ -1,12 +1,19 @@
import { describe, expect, it } from 'vitest';
-import { TradingViewClient } from '../../src/index.js';
+import { TradingViewClient, wsTransport, type Transport } from '../../src/index.js';
import { getCandles, watchCandles, watchQuotes, type CandleWatcher, type QuoteWatcher } from '../../src/data/index.js';
import { LIVE } from './env.js';
describe.skipIf(!LIVE)('live: connection recovery', () => {
- it('closes active watchers and starts fresh on a new connection', async () => {
+ it('stops active watchers on an abrupt socket loss and starts fresh on a new connection', async () => {
const symbol = 'BINANCE:BTCUSDT';
- const client = new TradingViewClient();
+ let socket: Transport | undefined;
+ const client = new TradingViewClient({
+ transport: (request, handlers) => {
+ socket = wsTransport(request, handlers);
+ return socket;
+ },
+ });
+ const closeCode = new Promise<number | undefined>((resolve) => { client.on('close', (code) => resolve(code)); });
const errors: string[] = [];
let candles: CandleWatcher | undefined;
let quotes: QuoteWatcher | undefined;
@@ -19,9 +26,11 @@ describe.skipIf(!LIVE)('live: connection recovery', () => {
});
expect(candles.latest).toHaveLength(5);
expect(quotes.latest[symbol]?.lp).toBeTypeOf('number');
- // End the transport while subscriptions are still live, as a lost socket would.
- await client.close();
+ // Destroy the TCP socket without a closing handshake, as a lost network would.
+ socket?.terminate?.();
await Promise.all([candles.closed, quotes.closed]);
+ expect(await closeCode).toBe(1006);
+ expect(client.isClosed).toBe(true);
expect(candles.isActive).toBe(false);
expect(quotes.isActive).toBe(false);
expect(errors.sort()).toEqual(['DISCONNECTED', 'DISCONNECTED']);
diff --git a/tests/unit/client.test.ts b/tests/unit/client.test.ts
index af047a8..0acbd30 100644
--- a/tests/unit/client.test.ts
+++ b/tests/unit/client.test.ts
@@ -193,3 +193,81 @@ describe('account lookup lifecycle', () => {
});
}
});
+
+describe('unexpected connection loss', () => {
+ it('fails and terminates a connection that goes silent, but not one that keeps beating', async () => {
+ const { server, client } = setup({ inactivityTimeoutMs: 80 });
+ const errors: string[] = [];
+ client.on('error', (error) => errors.push(error.code));
+ const onClose = vi.fn();
+ client.registerSession('cs_silent', { onPacket: () => {}, onClose });
+ const closed = new Promise((resolve) => { client.on('close', (code) => resolve(code)); });
+ await client.ready;
+ for (let beat = 1; beat <= 4; beat += 1) {
+ await new Promise((resolve) => { setTimeout(resolve, 40); });
+ server.last.push(`~h~${beat}`);
+ }
+ expect(client.isOpen).toBe(true);
+ expect(errors).toEqual([]);
+ await expect(closed).resolves.toBe(1006);
+ expect(server.last.terminated).toBe(true);
+ expect(errors).toEqual(['CONNECTION_ERROR']);
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(onClose.mock.calls[0][0]).toMatchObject({
+ code: 'DISCONNECTED',
+ message: expect.stringContaining('No data from the server'),
+ cause: expect.objectContaining({ code: 'CONNECTION_ERROR' }),
+ });
+ expect(onClose.mock.calls[0][1]).toBe(false);
+ });
+
+ for (const inactivityTimeoutMs of [0, Infinity, 2 ** 40]) {
+ it(`keeps a silent connection open with inactivityTimeoutMs ${inactivityTimeoutMs}`, async () => {
+ const { server, client } = setup({ inactivityTimeoutMs });
+ await client.ready;
+ await new Promise((resolve) => { setTimeout(resolve, 50); });
+ expect(client.isOpen).toBe(true);
+ expect(server.last.terminated).toBe(false);
+ await client.close();
+ });
+ }
+
+ it('reports a socket error followed by a close once, as CONNECTION_ERROR', async () => {
+ const { server, client } = setup();
+ const errors: string[] = [];
+ client.on('error', (error) => errors.push(error.code));
+ const onClose = vi.fn();
+ client.registerSession('cs_reset', { onPacket: () => {}, onClose });
+ await client.ready;
+ server.last.handlers.onError(new Error('read ECONNRESET'));
+ server.last.drop(1006, '');
+ await until(() => client.isClosed);
+ expect(errors).toEqual(['CONNECTION_ERROR']);
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(onClose.mock.calls[0][0]).toMatchObject({
+ code: 'DISCONNECTED', cause: expect.objectContaining({ message: expect.stringContaining('ECONNRESET') }),
+ });
+ expect(onClose.mock.calls[0][1]).toBe(false);
+ await client.close();
+ });
+
+ it('starts a fresh connection after an abrupt loss without leaking state', async () => {
+ const server = new FakeServer();
+ const first = new TradingViewClient({ transport: server.transport });
+ await first.ready;
+ first.registerSession('cs_old', { onPacket: () => {} });
+ server.last.drop();
+ await until(() => first.isClosed);
+ expect(() => first.send('late')).toThrow(/closed/);
+ await first.close();
+
+ const second = new TradingViewClient({ transport: server.transport });
+ await second.ready;
+ const received: string[] = [];
+ second.registerSession('cs_new', { onPacket: (packet) => received.push(packet.m) });
+ server.last.push({ m: 'series_loading', p: ['cs_new'] }, { m: 'series_loading', p: ['cs_old'] });
+ expect(received).toEqual(['series_loading']);
+ expect(server.connections).toHaveLength(2);
+ await second.close();
+ });
+});
diff --git a/tests/unit/data.test.ts b/tests/unit/data.test.ts
index 42ee1bc..ac182c5 100644
--- a/tests/unit/data.test.ts
+++ b/tests/unit/data.test.ts
@@ -401,3 +401,41 @@ describe('indicator data', () => {
expect(server.last.closed).toBe(true);
});
});
+
+describe('watchers after an unexpected connection loss', () => {
+ it('stops every watcher on a shared client once, then works on a new connection', async () => {
+ const server = new FakeServer();
+ const client = new TradingViewClient({ transport: server.transport });
+ const errors: string[] = [];
+ const onError = (error: { code: string }) => errors.push(error.code);
+ const candles = await watchCandles({ symbol: 'A', timeframe: '1', count: 5, client }, { onData: () => {}, onError });
+ const quotes = await watchQuotes({ symbols: ['A'], fields: 'price', client }, { onData: () => {}, onError });
+ expect(candles.latest).toHaveLength(5);
+
+ server.last.drop(1006, '');
+ await Promise.all([candles.closed, quotes.closed]);
+ expect(errors).toEqual(['DISCONNECTED', 'DISCONNECTED']);
+ expect([candles.isActive, quotes.isActive, client.isClosed]).toEqual([false, false, true]);
+ // Late packets on the dead socket and repeated stops are harmless.
+ server.last.handlers.onMessage('~m~20~m~{"m":"du","p":["x"]}');
+ await Promise.all([candles.stop(), quotes.stop(), client.close()]);
+ expect(errors).toHaveLength(2);
+ await expect(watchCandles({ symbol: 'A', client }, { onData: () => {} })).rejects.toMatchObject({ code: 'INVALID_STATE' });
+
+ const replacement = new TradingViewClient({ transport: server.transport });
+ expect(await getCandles({ symbol: 'A', timeframe: '1', count: 5, client: replacement })).toHaveLength(5);
+ expect(replacement.isClosed).toBe(false);
+ await replacement.close();
+ });
+
+ it('stops an owned watcher with CONNECTION_ERROR when the server goes silent', async () => {
+ const { server, clientOptions } = fake();
+ const errors: string[] = [];
+ const watcher = await watchCandles({ symbol: 'A', clientOptions: { ...clientOptions, inactivityTimeoutMs: 50 } }, {
+ onData: () => {}, onError: (error) => errors.push(error.code),
+ });
+ await watcher.closed;
+ expect(errors).toEqual(['CONNECTION_ERROR']);
+ expect(server.last.terminated).toBe(true);
+ });
+});
diff --git a/tests/unit/events.test.ts b/tests/unit/events.test.ts
index 918f0d6..eed1f5d 100644
--- a/tests/unit/events.test.ts
+++ b/tests/unit/events.test.ts
@@ -35,6 +35,23 @@ describe('Emitter', () => {
expect(spy).toHaveBeenCalledWith('[tradingview]', new Error('boom'));
});
+ it('handles async listener rejections, including once and catch-all listeners', async () => {
+ const emitter = new TestEmitter();
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const after = vi.fn();
+ emitter.on('tick', async () => { throw new Error('async on'); });
+ emitter.once('tick', async () => { throw new Error('async once'); });
+ emitter.onAny(async () => { throw new Error('async any'); });
+ emitter.on('tick', after);
+ emitter.fire('tick', 1);
+ await new Promise((resolve) => { setTimeout(resolve, 0); });
+ expect(logged).toHaveBeenCalledTimes(3);
+ expect(after).toHaveBeenCalledWith(1);
+ expect(logged).toHaveBeenCalledWith('[tradingview] Listener threw:', expect.objectContaining({ message: 'async on' }));
+ expect(logged).toHaveBeenCalledWith('[tradingview] Listener threw:', expect.objectContaining({ message: 'async once' }));
+ expect(logged).toHaveBeenCalledWith('[tradingview] Listener threw:', expect.objectContaining({ message: 'async any' }));
+ });
+
it('isolates throwing listeners from the emitter', () => {
const emitter = new TestEmitter();
const after = vi.fn();
diff --git a/tests/unit/exports.test.ts b/tests/unit/exports.test.ts
index 037f130..71c17be 100644
--- a/tests/unit/exports.test.ts
+++ b/tests/unit/exports.test.ts
@@ -7,7 +7,7 @@ describe('public API', () => {
expect(Object.keys(root).sort()).toEqual([
'ALL_QUOTE_FIELDS', 'BuiltInIndicator', 'CHART_TYPE_STUDIES', 'ChartSession', 'DEFAULT_TIMEOUT_MS', 'Emitter',
'PineIndicator', 'PinePermissionManager', 'QuoteSession', 'QuoteSubscription', 'Study', 'TradingViewClient',
- 'TradingViewError', 'TradingViewProvider', 'applyGraphicsCommands', 'clearIndicatorCache', 'getCandles', 'getChartToken', 'getDrawings', 'getHotlist',
+ 'TradingViewError', 'TradingViewProvider', 'applyGraphicsCommands', 'clearIndicatorCache', 'createProxy', 'createWsTransport', 'getCandles', 'getChartToken', 'getDrawings', 'getHotlist',
'getIndicator', 'getIndicatorData', 'getPrivateIndicators', 'getQuote', 'getQuotes', 'getScreener', 'getSymbolInfo',
'getTechnicalAnalysis', 'getUser', 'getWatchlists', 'loginUser', 'mergeStrategyReport', 'parseGraphics', 'parseIndicatorDefinition',
'parseTrades', 'protocol', 'quoteSymbolKey', 'resolveQuoteFields', 'searchIndicators', 'searchMarkets', 'summarizeStrategyReport',
diff --git a/tests/unit/proxy.test.ts b/tests/unit/proxy.test.ts
new file mode 100644
index 0000000..e20f70e
--- /dev/null
+++ b/tests/unit/proxy.test.ts
@@ -0,0 +1,296 @@
+import { execFileSync, spawn } from 'node:child_process';
+import { randomBytes } from 'node:crypto';
+import { once } from 'node:events';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { Agent, type ClientRequestArgs } from 'node:http';
+import {
+ connect, createServer, type AddressInfo, type Socket,
+} from 'node:net';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createInterface } from 'node:readline';
+import { fileURLToPath } from 'node:url';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { createProxy } from '../../src/client/proxy.js';
+import { TradingViewClient } from '../../src/client/client.js';
+import type { TransportFactory } from '../../src/client/transport.js';
+import { TradingViewError } from '../../src/errors.js';
+import { request } from '../../src/http/request.js';
+
+interface Fixture {
+ proxyUrl: (auth?: string, protocol?: 'http' | 'https') => string;
+ plainPort: number;
+ connects: Array<{ target: string; authorized: boolean }>;
+ stop(): Promise<void>;
+}
+
+// Node uses the built-in tunnel agents, Bun 1.3.6+ its native `proxy` option.
+const bun = (globalThis as { Bun?: { version: string } }).Bun?.version;
+const bunTooOld = bun !== undefined && !/^(1\.3\.([6-9]|\d{2,})|1\.([4-9]|\d{2,})\.|[2-9]\.)/.test(bun);
+
+// Random per run, passed to the fixture through the environment and never logged.
+const AUTH = `user:${randomBytes(12).toString('hex')}`;
+
+async function startFixture(certDir?: string): Promise<Fixture> {
+ const script = fileURLToPath(new URL('../helpers/proxy-server.mjs', import.meta.url));
+ const child = spawn('node', certDir ? [script, certDir] : [script], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, PROXY_AUTH: AUTH },
+ });
+ const exit = once(child, 'exit');
+ const connects: Fixture['connects'] = [];
+ const lines = createInterface({ input: child.stdout });
+ const ports = await Promise.race([
+ new Promise<{ proxy: number; secureProxy?: number; plain: number }>((resolve) => {
+ lines.on('line', (line) => {
+ const message = JSON.parse(line);
+ if (message.proxy) resolve(message);
+ else connects.push(message);
+ });
+ }),
+ exit.then(() => { throw new Error('Proxy fixture exited before listening'); }),
+ ]);
+ return {
+ proxyUrl: (auth = AUTH, protocol = 'http') => `${protocol}://${auth.split(':').map(encodeURIComponent).join(':')}`
+ + `@127.0.0.1:${protocol === 'https' ? ports.secureProxy : ports.proxy}`,
+ plainPort: ports.plain,
+ connects,
+ async stop() { child.kill(); await exit; },
+ };
+}
+
+function openTransport(factory: TransportFactory, url: string) {
+ let opened!: () => void;
+ let failed!: (error: Error) => void;
+ const open = new Promise<void>((resolve, reject) => { opened = resolve; failed = reject; });
+ const messages: string[] = [];
+ let received!: () => void;
+ const message = new Promise<void>((resolve) => { received = resolve; });
+ const transport = factory({ url, origin: 'https://www.tradingview.com', headers: {} }, {
+ onOpen: opened,
+ onMessage: (data) => { messages.push(data); received(); },
+ onClose: () => failed(new Error('closed')),
+ onError: failed,
+ });
+ return { transport, open, message, messages };
+}
+
+describe.skipIf(bunTooOld)('createProxy over a loopback proxy', () => {
+ let fixture: Fixture;
+ beforeAll(async () => { fixture = await startFixture(); });
+ afterAll(async () => { await fixture?.stop(); });
+
+ it('tunnels library HTTP requests with proxy basic auth', async () => {
+ const proxy = createProxy(fixture.proxyUrl());
+ const response = await request('http://api.tradingview.test:8080/echo', {
+ form: { symbol: 'BINANCE:BTCUSDT' }, credentials: { session: 'abc', signature: 'def' },
+ }, { fetch: proxy.fetch });
+
+ expect(response.status).toBe(200);
+ expect(response.data).toEqual({
+ method: 'POST',
+ host: 'api.tradingview.test:8080',
+ path: '/echo',
+ cookie: 'sessionid=abc;sessionid_sign=def',
+ contentType: 'application/x-www-form-urlencoded',
+ body: 'symbol=BINANCE%3ABTCUSDT',
+ });
+ expect(fixture.connects).toContainEqual({ target: 'api.tradingview.test:8080', authorized: true });
+ });
+
+ it('follows or exposes redirects, keeps every set-cookie and decodes gzip', async () => {
+ const proxy = createProxy(fixture.proxyUrl());
+ const manual = await proxy.fetch('http://api.tradingview.test:8080/redirect', { redirect: 'manual' });
+ expect(manual.status).toBe(302);
+ expect(manual.headers.get('location')).toBe('/echo?redirected=1');
+ expect(manual.headers.getSetCookie()).toEqual(['a=1; Path=/', 'b=2; Path=/']);
+
+ const followed = await proxy.fetch('http://api.tradingview.test:8080/redirect', { method: 'POST', body: 'x' });
+ expect(followed.redirected).toBe(true);
+ expect(followed.url).toBe('http://api.tradingview.test:8080/echo?redirected=1');
+ expect(await followed.json()).toMatchObject({ method: 'GET', path: '/echo?redirected=1', body: '' });
+
+ const gzip = await proxy.fetch('http://api.tradingview.test:8080/gzip');
+ expect(await gzip.json()).toMatchObject({ path: '/gzip' });
+ });
+
+ it('tunnels the websocket transport with its Origin header', async () => {
+ const proxy = createProxy(new URL(fixture.proxyUrl()));
+ const { transport, open, message, messages } = openTransport(proxy.transport, 'ws://data.tradingview.test:8080/');
+ try {
+ await open;
+ transport.send('through the proxy');
+ await message;
+ expect(JSON.parse(messages[0])).toEqual({
+ host: 'data.tradingview.test:8080', origin: 'https://www.tradingview.com', echo: 'through the proxy',
+ });
+ expect(fixture.connects).toContainEqual({ target: 'data.tradingview.test:8080', authorized: true });
+ } finally {
+ transport.close();
+ }
+ });
+
+ it('reports a refused tunnel on both paths without leaking proxy credentials', async () => {
+ const wrong = 'user:wrong-secret-value';
+ const proxy = createProxy(fixture.proxyUrl(wrong));
+
+ const httpError = await request('http://api.tradingview.test:8080/echo', {}, { fetch: proxy.fetch })
+ .catch((error: unknown) => error);
+ expect(httpError).toBeInstanceOf(TradingViewError);
+ expect((httpError as TradingViewError).message).toContain('HTTP 407');
+ expect((httpError as TradingViewError).message).not.toContain('wrong-secret-value');
+
+ const client = new TradingViewClient({
+ authToken: 'token',
+ transport: (req, handlers) => proxy.transport({ ...req, url: 'ws://data.tradingview.test:8080/' }, handlers),
+ });
+ const wsError = await client.ready.catch((error: unknown) => error);
+ expect(wsError).toMatchObject({ code: 'CONNECTION_ERROR' });
+ // Bun's native WebSocket only reports "Proxy connection failed".
+ expect((wsError as Error).message).toMatch(/HTTP 407|Proxy connection failed/);
+ expect((wsError as Error).message).not.toContain('wrong-secret-value');
+ await client.close();
+ // The proxy fixture reports CONNECT attempts through a separate process;
+ // the client can reject before its stdout event reaches this process.
+ const refusedWs = { target: 'data.tradingview.test:8080', authorized: false };
+ const deadline = Date.now() + 1_000;
+ while (!fixture.connects.some((entry) => entry.target === refusedWs.target && entry.authorized === false)
+ && Date.now() < deadline) {
+ await new Promise((resolve) => { setTimeout(resolve, 10); });
+ }
+ expect(fixture.connects).toContainEqual(refusedWs);
+ });
+
+ it('honours an abort signal', async () => {
+ const proxy = createProxy(fixture.proxyUrl());
+ const controller = new AbortController();
+ controller.abort();
+ await expect(proxy.fetch('http://api.tradingview.test:8080/echo', { signal: controller.signal }))
+ .rejects.toMatchObject({ name: 'AbortError' });
+ });
+
+ it.skipIf(bun)('uses a caller-supplied Agent (e.g. a SOCKS agent) for both paths', async () => {
+ const hosts: string[] = [];
+ // Stand-in for a third-party proxy agent: resolves every host to the fixture.
+ class RoutingAgent extends Agent {
+ override createConnection(options: ClientRequestArgs) {
+ hosts.push(`${options.host}:${options.port}`);
+ return connect(fixture.plainPort, '127.0.0.1');
+ }
+ }
+ const proxy = createProxy(new RoutingAgent());
+ const response = await proxy.fetch('http://api.tradingview.test:8080/echo');
+ expect(await response.json()).toMatchObject({ host: 'api.tradingview.test:8080' });
+
+ const { transport, open } = openTransport(proxy.transport, 'ws://data.tradingview.test:8080/');
+ await open;
+ transport.close();
+ expect(hosts).toEqual(['api.tradingview.test:8080', 'data.tradingview.test:8080']);
+ });
+
+ it.skipIf(bun)('reports an unreachable or stalled proxy', async () => {
+ const closed = createServer();
+ await new Promise<void>((resolve) => { closed.listen(0, '127.0.0.1', resolve); });
+ const closedPort = (closed.address() as AddressInfo).port;
+ await new Promise((resolve) => { closed.close(resolve); });
+ await expect(createProxy(`http://u:[email protected]:${closedPort}`).fetch('http://api.tradingview.test/'))
+ .rejects.toThrow(/is unreachable/);
+
+ const sockets: Socket[] = [];
+ const stalled = createServer((socket) => { sockets.push(socket); });
+ await new Promise<void>((resolve) => { stalled.listen(0, '127.0.0.1', resolve); });
+ try {
+ const proxy = createProxy(`http://127.0.0.1:${(stalled.address() as AddressInfo).port}`, { connectTimeoutMs: 50 });
+ await expect(proxy.fetch('http://api.tradingview.test/')).rejects.toMatchObject({ code: 'TIMEOUT' });
+ } finally {
+ for (const socket of sockets) socket.destroy();
+ await new Promise((resolve) => { stalled.close(resolve); });
+ }
+ });
+
+ it.skipIf(!bun)('rejects Node agents on Bun', () => {
+ expect(() => createProxy(new Agent())).toThrow(/Bun ignores Node agents/);
+ });
+
+ it('rejects unsupported proxy URLs', () => {
+ expect(() => createProxy('socks5://127.0.0.1:1080')).toThrow(/pass an Agent/);
+ expect(() => createProxy('not a url')).toThrow(/Invalid proxy URL/);
+ });
+});
+
+function hasOpenssl(): boolean {
+ try {
+ execFileSync('openssl', ['version'], { stdio: 'ignore' });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// Full client flow with the real TradingView URLs: account lookup over HTTPS and
+// the wss handshake both resolve only through the proxy, to local TLS servers.
+describe.skipIf(bunTooOld || !hasOpenssl())('createProxy end to end over TLS', () => {
+ let fixture: Fixture;
+ let certDir: string;
+ beforeAll(async () => {
+ certDir = mkdtempSync(join(tmpdir(), 'tv-proxy-'));
+ execFileSync('openssl', [
+ 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1', '-subj', '/CN=tradingview.com',
+ '-addext', 'subjectAltName=DNS:tradingview.com,DNS:*.tradingview.com,IP:127.0.0.1',
+ '-keyout', join(certDir, 'key.pem'), '-out', join(certDir, 'cert.pem'),
+ ], { stdio: 'ignore' });
+ fixture = await startFixture(certDir);
+ });
+ afterAll(async () => {
+ await fixture?.stop();
+ if (certDir) rmSync(certDir, { recursive: true, force: true });
+ });
+
+ it('authenticates a TradingViewClient through the proxy on both HTTPS and WSS', async () => {
+ const proxy = createProxy(fixture.proxyUrl(), { tls: { ca: readFileSync(join(certDir, 'cert.pem')) } });
+ const client = new TradingViewClient({ credentials: { session: 'proxy-session', signature: 'sig' }, ...proxy });
+ const ack = new Promise<unknown[]>((resolve) => {
+ client.on('packet', (packet) => { if (packet.m === 'proxy_ack') resolve(packet.p); });
+ });
+ try {
+ await client.ready;
+ expect(await ack).toEqual(['proxy-token', 'https://www.tradingview.com']);
+ expect(client.serverInfo?.session_id).toBe('proxy-hello');
+ expect([...fixture.connects].sort((a, b) => a.target.localeCompare(b.target))).toEqual([
+ { target: 'data.tradingview.com:443', authorized: true },
+ { target: 'www.tradingview.com:443', authorized: true },
+ ]);
+ } finally {
+ await client.close();
+ }
+ });
+
+ it('reaches TradingView through an https: proxy on both paths', async () => {
+ const ca = readFileSync(join(certDir, 'cert.pem'));
+ const proxy = createProxy(fixture.proxyUrl(AUTH, 'https'), { tls: { ca } });
+ const response = await request('https://www.tradingview.com/echo', {}, { fetch: proxy.fetch });
+ expect(response.data).toMatchObject({ host: 'www.tradingview.com', path: '/echo' });
+
+ const { transport, open, message, messages } = openTransport(proxy.transport, 'wss://data.tradingview.com/');
+ try {
+ await open;
+ transport.send('tls in tls');
+ await message;
+ expect(JSON.parse(messages[0])).toMatchObject({ host: 'data.tradingview.com', echo: 'tls in tls' });
+ } finally {
+ transport.close();
+ }
+ });
+
+ it('rejects an untrusted certificate behind the tunnel', async () => {
+ const proxy = createProxy(fixture.proxyUrl());
+ await expect(request('https://www.tradingview.com/chart/', {}, { fetch: proxy.fetch }))
+ .rejects.toMatchObject({ code: 'HTTP_ERROR' });
+ });
+});
+
+describe.skipIf(!bunTooOld)('createProxy on Bun before 1.3.6', () => {
+ it('refuses to create a proxy whose websocket would silently connect directly', () => {
+ expect(() => createProxy('http://127.0.0.1:3128')).toThrow(/Bun 1\.3\.6 or later is required/);
+ });
+});
diff --git a/tests/unit/transport.test.ts b/tests/unit/transport.test.ts
index 5faadb9..de70344 100644
--- a/tests/unit/transport.test.ts
+++ b/tests/unit/transport.test.ts
@@ -74,3 +74,75 @@ describe('native websocket transport', () => {
}
});
});
+
+describe('native websocket loss', () => {
+ function connect(url: string, options: ConstructorParameters<typeof TradingViewClient>[0] = {}) {
+ const socketCloses: Array<number | undefined> = [];
+ const client = new TradingViewClient({
+ ...options,
+ transport: (request, handlers) => wsTransport({ ...request, url }, {
+ ...handlers,
+ onClose: (code, reason) => { socketCloses.push(code); handlers.onClose(code, reason); },
+ }),
+ });
+ const errors: string[] = [];
+ client.on('error', (error) => errors.push(error.code));
+ const sessions: Array<[string, boolean]> = [];
+ client.registerSession('cs_native', { onPacket() {}, onClose: (error, expected) => sessions.push([error.code, expected]) });
+ const closed = new Promise<number | undefined>((resolve) => { client.on('close', (code) => resolve(code)); });
+ return { client, errors, sessions, closed, socketCloses };
+ }
+
+ it('reports an abrupt socket loss to sessions as an unexpected disconnection', async () => {
+ const server = await localServer('drop');
+ const { client, errors, sessions, closed } = connect(server.url);
+ try {
+ await client.ready;
+ client.send('ping_server');
+ expect(await closed).toBe(1006);
+ expect(client.isClosed).toBe(true);
+ expect(sessions).toEqual([['DISCONNECTED', false]]);
+ expect(errors).toEqual([]);
+ expect(() => client.send('late')).toThrow(/closed/);
+ } finally {
+ await client.close();
+ await server.stop();
+ }
+ });
+
+ it('detects a silent peer and releases the socket at once', async () => {
+ const server = await localServer('silent');
+ const { client, errors, sessions, closed, socketCloses } = connect(server.url, { inactivityTimeoutMs: 100 });
+ try {
+ await client.ready;
+ const start = Date.now();
+ expect(await closed).toBe(1006);
+ expect(Date.now() - start).toBeLessThan(1_000);
+ expect(errors).toEqual(['CONNECTION_ERROR']);
+ expect(sessions).toEqual([['DISCONNECTED', false]]);
+ expect(socketCloses).toEqual([1006]);
+ } finally {
+ await client.close();
+ await server.stop();
+ }
+ });
+
+ it('close() releases the socket of a peer that never answers the close', async () => {
+ const server = await localServer('silent');
+ const { client, sessions, socketCloses } = connect(server.url, { inactivityTimeoutMs: 0 });
+ try {
+ await client.ready;
+ await client.close();
+ expect(client.isClosed).toBe(true);
+ expect(sessions).toEqual([['DISCONNECTED', true]]);
+ // Without terminate(), Node's ws keeps the socket for its own 30 s close timeout.
+ const start = Date.now();
+ while (socketCloses.length === 0 && Date.now() - start < 1_000) {
+ await new Promise((resolve) => { setTimeout(resolve, 10); });
+ }
+ expect(socketCloses).toHaveLength(1);
+ } finally {
+ await server.stop();
+ }
+ }, 10_000);
+});