@exhumer/signalr-client 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,11 +1,10 @@
1
- import { Dispatcher } from 'undici';
2
- export { Dispatcher } from 'undici';
3
- import { Readable } from 'node:stream';
4
- import { CookieJar } from 'tough-cookie';
5
- export { CookieJar } from 'tough-cookie';
6
- import { EventEmitter } from 'node:events';
7
- export { CookieAgent, cookie } from '@exhumer/undici-cookie-agent';
1
+ import { Dispatcher, Dispatcher as Dispatcher$1 } from "undici";
2
+ import { Readable } from "node:stream";
3
+ import { CookieJar, CookieJar as CookieJar$1 } from "tough-cookie";
4
+ import { EventEmitter } from "node:events";
5
+ import { CookieAgent, cookie } from "@exhumer/undici-cookie-agent";
8
6
 
7
+ //#region src/constants.d.ts
9
8
  /**
10
9
  * constants.ts
11
10
  *
@@ -14,46 +13,46 @@ export { CookieAgent, cookie } from '@exhumer/undici-cookie-agent';
14
13
  * types while being verified against a constraint at compile time.
15
14
  */
16
15
  declare const MessageType: Readonly<{
17
- readonly Invocation: 1;
18
- readonly StreamItem: 2;
19
- readonly Completion: 3;
20
- readonly StreamInvocation: 4;
21
- readonly CancelInvocation: 5;
22
- readonly Ping: 6;
23
- readonly Close: 7;
16
+ readonly Invocation: 1;
17
+ readonly StreamItem: 2;
18
+ readonly Completion: 3;
19
+ readonly StreamInvocation: 4;
20
+ readonly CancelInvocation: 5;
21
+ readonly Ping: 6;
22
+ readonly Close: 7;
24
23
  }>;
25
24
  /** Union of all valid message type numbers. */
26
25
  type MessageTypeValue = (typeof MessageType)[keyof typeof MessageType];
27
26
  declare const HubConnectionState: Readonly<{
28
- readonly Disconnected: "Disconnected";
29
- readonly Connecting: "Connecting";
30
- readonly Connected: "Connected";
31
- readonly Disconnecting: "Disconnecting";
32
- readonly Reconnecting: "Reconnecting";
27
+ readonly Disconnected: "Disconnected";
28
+ readonly Connecting: "Connecting";
29
+ readonly Connected: "Connected";
30
+ readonly Disconnecting: "Disconnecting";
31
+ readonly Reconnecting: "Reconnecting";
33
32
  }>;
34
33
  /** Union of all valid connection state strings. */
35
34
  type HubConnectionState = (typeof HubConnectionState)[keyof typeof HubConnectionState];
36
35
  declare const LogLevel: {
37
- readonly Trace: 0;
38
- readonly Debug: 1;
39
- readonly Information: 2;
40
- readonly Warning: 3;
41
- readonly Error: 4;
42
- readonly Critical: 5;
43
- readonly None: 6;
36
+ readonly Trace: 0;
37
+ readonly Debug: 1;
38
+ readonly Information: 2;
39
+ readonly Warning: 3;
40
+ readonly Error: 4;
41
+ readonly Critical: 5;
42
+ readonly None: 6;
44
43
  };
45
44
  type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];
46
45
  declare const HttpTransportType: {
47
- readonly None: 0;
48
- readonly WebSockets: 1;
49
- readonly ServerSentEvents: 2;
50
- readonly LongPolling: 4;
46
+ readonly None: 0;
47
+ readonly WebSockets: 1;
48
+ readonly ServerSentEvents: 2;
49
+ readonly LongPolling: 4;
51
50
  };
52
51
  /** Bitmask of enabled transports - values can be OR-ed together. */
53
52
  type HttpTransportType = (typeof HttpTransportType)[keyof typeof HttpTransportType];
54
53
  declare const TransferFormat: {
55
- readonly Text: 1;
56
- readonly Binary: 2;
54
+ readonly Text: 1;
55
+ readonly Binary: 2;
57
56
  };
58
57
  type TransferFormat = (typeof TransferFormat)[keyof typeof TransferFormat];
59
58
  /** ASCII 30 - the byte that terminates every SignalR JSON message. */
@@ -63,36 +62,8 @@ declare const NEGOTIATE_VERSION: 1;
63
62
  declare const DEFAULT_TIMEOUT_IN_MS: 30000;
64
63
  declare const DEFAULT_PING_INTERVAL_IN_MS: 15000;
65
64
  declare const DEFAULT_SERVER_TIMEOUT_IN_MS: 30000;
66
-
67
- /**
68
- * http-client.ts
69
- *
70
- * Five HTTP client implementations backed by undici, each wrapping a different
71
- * undici primitive. All five satisfy the `IHttpClient` contract so any one
72
- * can be used wherever an HTTP client is required (negotiate, SSE, polling…).
73
- *
74
- * ┌────────────────────┬───────────────────────────────────────────────────┐
75
- * │ Class │ undici primitive │
76
- * ├────────────────────┼───────────────────────────────────────────────────┤
77
- * │ RequestHttpClient │ undici.request() │
78
- * │ FetchHttpClient │ undici.fetch() (WHATWG-compatible) │
79
- * │ StreamHttpClient │ undici.stream() (factory-based streaming) │
80
- * │ PipelineHttpClient │ undici.pipeline() (Duplex pipe chain) │
81
- * │ DispatchHttpClient │ Dispatcher#dispatch (low-level handler interface) ← DEFAULT │
82
- * └────────────────────┴───────────────────────────────────────────────────┘
83
- *
84
- * Dispatcher (session-level):
85
- * Every client accepts an optional `dispatcher` option. Pass an undici
86
- * `Agent`, `Pool`, `Client`, `ProxyAgent`, etc. to customise connection
87
- * pooling, proxy routing, TLS, or any other transport-level behaviour for
88
- * the entire client session. When omitted, undici's process-global
89
- * default agent is used (`getGlobalDispatcher()`).
90
- *
91
- * HttpClient:
92
- * An alias for `DispatchHttpClient` so existing code that imported
93
- * `HttpClient` continues to work without changes.
94
- */
95
-
65
+ //#endregion
66
+ //#region src/http-client.d.ts
96
67
  type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
97
68
  /**
98
69
  * Per-request options accepted by every client method.
@@ -100,39 +71,41 @@ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTION
100
71
  * do not need to be changed when switching client implementations.
101
72
  */
102
73
  interface RequestOptions {
103
- /** Per-request headers merged on top of the instance-level defaults. */
104
- readonly headers?: Record<string, string>;
105
- /**
106
- * Request body.
107
- * Plain objects are serialised to JSON automatically.
108
- * Strings are sent as-is (set Content-Type explicitly if needed).
109
- */
110
- readonly body?: string | Record<string, unknown> | null;
111
- /** Override the session-level timeout for this single request (ms). */
112
- readonly timeout?: number;
74
+ /** Per-request headers merged on top of the instance-level defaults. */
75
+ readonly headers?: Record<string, string>;
76
+ /**
77
+ * Request body.
78
+ * Plain objects are serialised to JSON automatically.
79
+ * Strings are sent as-is (set Content-Type explicitly if needed).
80
+ */
81
+ readonly body?: string | Uint8Array | Record<string, unknown> | null;
82
+ /** Override the session-level timeout for this single request (ms). */
83
+ readonly timeout?: number;
113
84
  }
114
85
  /**
115
86
  * Session-level options shared by all client constructors.
116
87
  */
117
88
  interface HttpClientOptions {
118
- /** Headers sent with every request (merged before per-request headers). */
119
- readonly headers?: Record<string, string>;
120
- /** Default timeout in milliseconds applied to every request (default: 30 000). */
121
- readonly timeout?: number;
122
- /**
123
- * undici Dispatcher to use for the entire session.
124
- *
125
- * You can pass any `Dispatcher` subclass:
126
- * - `new undici.Agent(opts)` - connection-pool tuning
127
- * - `new undici.Pool(origin, opts)` - per-origin pool
128
- * - `new undici.Client(origin, opts)` - single connection
129
- * - `new undici.ProxyAgent(proxyUrl)` - HTTP proxy
130
- * - `new undici.MockAgent()` - in-process mocking
131
- *
132
- * When omitted the process-global dispatcher (`getGlobalDispatcher()`)
133
- * is used, which is undici's default `Agent`.
134
- */
135
- readonly dispatcher?: Dispatcher;
89
+ /** Headers sent with every request (merged before per-request headers). */
90
+ readonly headers?: Record<string, string>;
91
+ /** Default timeout in milliseconds applied to every request (default: 30 000). */
92
+ readonly timeout?: number;
93
+ /**
94
+ * undici Dispatcher to use for the entire session.
95
+ *
96
+ * You can pass any `Dispatcher` subclass:
97
+ * - `new undici.Agent(opts)` - connection-pool tuning
98
+ * - `new undici.Pool(origin, opts)` - per-origin pool
99
+ * - `new undici.Client(origin, opts)` - single connection
100
+ * - `new undici.ProxyAgent(proxyUrl)` - HTTP proxy
101
+ * - `new undici.MockAgent()` - in-process mocking
102
+ *
103
+ * When omitted the process-global dispatcher (`getGlobalDispatcher()`)
104
+ * is used, which is undici's default `Agent`.
105
+ */
106
+ readonly dispatcher?: Dispatcher$1;
107
+ /** Maximum buffered response body size in bytes (default: 32 MiB). */
108
+ readonly maximumResponseBodySize?: number;
136
109
  }
137
110
  /**
138
111
  * Holds the session-level options and exposes the convenience wrappers
@@ -141,21 +114,22 @@ interface HttpClientOptions {
141
114
  * Concrete subclasses only need to implement `request()` and `stream()`.
142
115
  */
143
116
  declare abstract class BaseUndiciClient implements IHttpClient {
144
- /** Default headers merged into every outgoing request. */
145
- protected readonly defaultHeaders: Record<string, string>;
146
- /** Session-level request timeout in milliseconds. */
147
- protected readonly defaultTimeout: number;
148
- /**
149
- * Shared undici Dispatcher. May be an Agent, Pool, Client, ProxyAgent, etc.
150
- * Defaults to undici's process-global agent when not specified.
151
- */
152
- protected readonly dispatcher: Dispatcher;
153
- constructor(options?: HttpClientOptions);
154
- get(url: string, options?: RequestOptions): Promise<HttpResponse>;
155
- post(url: string, options?: RequestOptions): Promise<HttpResponse>;
156
- delete(url: string, options?: RequestOptions): Promise<HttpResponse>;
157
- abstract request(method: HttpMethod, url: string, options?: RequestOptions): Promise<HttpResponse>;
158
- abstract stream(method: HttpMethod, url: string, options?: RequestOptions): Promise<StreamResult>;
117
+ /** Default headers merged into every outgoing request. */
118
+ protected readonly defaultHeaders: Record<string, string>;
119
+ /** Session-level request timeout in milliseconds. */
120
+ protected readonly defaultTimeout: number;
121
+ /**
122
+ * Shared undici Dispatcher. May be an Agent, Pool, Client, ProxyAgent, etc.
123
+ * Defaults to undici's process-global agent when not specified.
124
+ */
125
+ protected readonly dispatcher: Dispatcher$1;
126
+ protected readonly maximumResponseBodySize: number;
127
+ constructor(options?: HttpClientOptions);
128
+ get(url: string, options?: RequestOptions): Promise<HttpResponse>;
129
+ post(url: string, options?: RequestOptions): Promise<HttpResponse>;
130
+ delete(url: string, options?: RequestOptions): Promise<HttpResponse>;
131
+ abstract request(method: HttpMethod, url: string, options?: RequestOptions): Promise<HttpResponse>;
132
+ abstract stream(method: HttpMethod, url: string, options?: RequestOptions): Promise<StreamResult>;
159
133
  }
160
134
  /**
161
135
  * HTTP client backed by `undici.request()`.
@@ -171,20 +145,20 @@ declare abstract class BaseUndiciClient implements IHttpClient {
171
145
  *
172
146
  */
173
147
  declare class RequestHttpClient extends BaseUndiciClient {
174
- /**
175
- * Buffered request - collects the entire response body as a string.
176
- *
177
- * Timeout is implemented via undici's built-in `headersTimeout` /
178
- * `bodyTimeout` options rather than an external `setTimeout`.
179
- */
180
- request(method: HttpMethod, url: string, options?: RequestOptions): Promise<HttpResponse>;
181
- /**
182
- * Streaming request - returns the response body `Readable` without
183
- * buffering. Used by SSE and long-polling transports.
184
- *
185
- * The `abort()` method destroys the underlying socket and the body stream.
186
- */
187
- stream(method: HttpMethod, url: string, options?: RequestOptions): Promise<StreamResult>;
148
+ /**
149
+ * Buffered request - collects the entire response body as a string.
150
+ *
151
+ * Timeout is implemented via undici's built-in `headersTimeout` /
152
+ * `bodyTimeout` options rather than an external `setTimeout`.
153
+ */
154
+ request(method: HttpMethod, url: string, options?: RequestOptions): Promise<HttpResponse>;
155
+ /**
156
+ * Streaming request - returns the response body `Readable` without
157
+ * buffering. Used by SSE and long-polling transports.
158
+ *
159
+ * The `abort()` method destroys the underlying socket and the body stream.
160
+ */
161
+ stream(method: HttpMethod, url: string, options?: RequestOptions): Promise<StreamResult>;
188
162
  }
189
163
  /**
190
164
  * HTTP client backed by `undici.fetch()`.
@@ -201,8 +175,8 @@ declare class RequestHttpClient extends BaseUndiciClient {
201
175
  * Node.js `Readable` via `Readable.fromWeb()` (Node 17+).
202
176
  */
203
177
  declare class FetchHttpClient extends BaseUndiciClient {
204
- request(method: HttpMethod, url: string, options?: RequestOptions): Promise<HttpResponse>;
205
- stream(method: HttpMethod, url: string, options?: RequestOptions): Promise<StreamResult>;
178
+ request(method: HttpMethod, url: string, options?: RequestOptions): Promise<HttpResponse>;
179
+ stream(method: HttpMethod, url: string, options?: RequestOptions): Promise<StreamResult>;
206
180
  }
207
181
  /**
208
182
  * HTTP client backed by `undici.stream()`.
@@ -220,8 +194,8 @@ declare class FetchHttpClient extends BaseUndiciClient {
220
194
  * readable side as `StreamResult.body`.
221
195
  */
222
196
  declare class StreamHttpClient extends BaseUndiciClient {
223
- request(method: HttpMethod, url: string, options?: RequestOptions): Promise<HttpResponse>;
224
- stream(method: HttpMethod, url: string, options?: RequestOptions): Promise<StreamResult>;
197
+ request(method: HttpMethod, url: string, options?: RequestOptions): Promise<HttpResponse>;
198
+ stream(method: HttpMethod, url: string, options?: RequestOptions): Promise<StreamResult>;
225
199
  }
226
200
  /**
227
201
  * HTTP client backed by `undici.pipeline()`.
@@ -243,8 +217,8 @@ declare class StreamHttpClient extends BaseUndiciClient {
243
217
  * the duplex's readable side directly - zero extra buffering.
244
218
  */
245
219
  declare class PipelineHttpClient extends BaseUndiciClient {
246
- request(method: HttpMethod, url: string, options?: RequestOptions): Promise<HttpResponse>;
247
- stream(method: HttpMethod, url: string, options?: RequestOptions): Promise<StreamResult>;
220
+ request(method: HttpMethod, url: string, options?: RequestOptions): Promise<HttpResponse>;
221
+ stream(method: HttpMethod, url: string, options?: RequestOptions): Promise<StreamResult>;
248
222
  }
249
223
  /**
250
224
  * HTTP client backed by `Dispatcher#dispatch()`.
@@ -270,82 +244,71 @@ declare class PipelineHttpClient extends BaseUndiciClient {
270
244
  * already bound). We always pass `origin` for maximum compatibility.
271
245
  */
272
246
  declare class DispatchHttpClient extends BaseUndiciClient {
273
- request(method: HttpMethod, url: string, options?: RequestOptions): Promise<HttpResponse>;
274
- stream(method: HttpMethod, url: string, options?: RequestOptions): Promise<StreamResult>;
247
+ request(method: HttpMethod, url: string, options?: RequestOptions): Promise<HttpResponse>;
248
+ stream(method: HttpMethod, url: string, options?: RequestOptions): Promise<StreamResult>;
275
249
  }
276
-
277
- /**
278
- * messages.ts
279
- *
280
- * Full discriminated-union type definitions for every SignalR hub protocol
281
- * message. The `type` field on each interface carries a numeric literal type
282
- * derived from the `MessageType` constants so TypeScript narrows correctly
283
- * inside `switch` / `if` statements.
284
- *
285
- * Reference:
286
- * https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/HubProtocol.md
287
- */
288
-
250
+ //#endregion
251
+ //#region src/messages.d.ts
289
252
  declare const __invocationIdBrand: unique symbol;
290
253
  /**
291
254
  * Opaque wrapper around `string` for invocation IDs.
292
255
  * Prevents mixing arbitrary strings with IDs at the type level.
293
256
  */
294
257
  type InvocationId = string & {
295
- readonly [__invocationIdBrand]: void;
258
+ readonly [__invocationIdBrand]: void;
296
259
  };
297
260
  /** Cast a plain string to an InvocationId (only used inside the library). */
298
261
  declare function toInvocationId(s: string): InvocationId;
299
262
  /** Optional headers that may appear on any hub message. */
300
263
  type MessageHeaders = Readonly<Record<string, string>>;
301
264
  interface BaseMessage {
302
- readonly headers?: MessageHeaders;
265
+ readonly headers?: MessageHeaders;
303
266
  }
304
267
  type MT = typeof MessageType;
305
268
  /** Type 1 - Server→Client or Client→Server method call. */
306
269
  interface InvocationMessage extends BaseMessage {
307
- readonly type: MT['Invocation'];
308
- /** Absent on fire-and-forget invocations. */
309
- readonly invocationId?: InvocationId;
310
- readonly target: string;
311
- readonly arguments: readonly unknown[];
312
- readonly streamIds?: readonly string[];
270
+ readonly type: MT['Invocation'];
271
+ /** Absent on fire-and-forget invocations. */
272
+ readonly invocationId?: InvocationId;
273
+ readonly target: string;
274
+ readonly arguments: readonly unknown[];
275
+ readonly streamIds?: readonly string[];
313
276
  }
314
277
  /** Type 2 - One item from a server-streaming method. */
315
278
  interface StreamItemMessage extends BaseMessage {
316
- readonly type: MT['StreamItem'];
317
- readonly invocationId: InvocationId;
318
- readonly item: unknown;
279
+ readonly type: MT['StreamItem'];
280
+ readonly invocationId: InvocationId;
281
+ readonly item: unknown;
319
282
  }
320
283
  /** Type 3 - Terminal result or error for an invocation / stream. */
321
284
  interface CompletionMessage extends BaseMessage {
322
- readonly type: MT['Completion'];
323
- readonly invocationId: InvocationId;
324
- readonly error?: string;
325
- readonly result?: unknown;
285
+ readonly type: MT['Completion'];
286
+ readonly invocationId: InvocationId;
287
+ readonly error?: string;
288
+ readonly result?: unknown;
326
289
  }
327
290
  /** Type 4 - Client initiates a server-streaming call. */
328
291
  interface StreamInvocationMessage extends BaseMessage {
329
- readonly type: MT['StreamInvocation'];
330
- readonly invocationId: InvocationId;
331
- readonly target: string;
332
- readonly arguments: readonly unknown[];
333
- readonly streamIds?: readonly string[];
292
+ readonly type: MT['StreamInvocation'];
293
+ readonly invocationId: InvocationId;
294
+ readonly target: string;
295
+ readonly arguments: readonly unknown[];
296
+ readonly streamIds?: readonly string[];
334
297
  }
335
298
  /** Type 5 - Client cancels an outstanding server stream. */
336
299
  interface CancelInvocationMessage extends BaseMessage {
337
- readonly type: MT['CancelInvocation'];
338
- readonly invocationId: InvocationId;
300
+ readonly type: MT['CancelInvocation'];
301
+ readonly invocationId: InvocationId;
339
302
  }
340
303
  /** Type 6 - Keep-alive ping; expects no response from the other side. */
341
304
  interface PingMessage extends BaseMessage {
342
- readonly type: MT['Ping'];
305
+ readonly type: MT['Ping'];
343
306
  }
344
307
  /** Type 7 - Graceful close notification from the server. */
345
308
  interface CloseMessage extends BaseMessage {
346
- readonly type: MT['Close'];
347
- readonly error?: string;
348
- readonly allowReconnect?: boolean;
309
+ readonly type: MT['Close'];
310
+ readonly error?: string;
311
+ readonly allowReconnect?: boolean;
349
312
  }
350
313
  /** Exhaustive discriminated union of all SignalR hub protocol messages. */
351
314
  type HubMessage = InvocationMessage | StreamItemMessage | CompletionMessage | StreamInvocationMessage | CancelInvocationMessage | PingMessage | CloseMessage;
@@ -361,97 +324,97 @@ declare function isStreamInvocationMessage(msg: HubMessage): msg is StreamInvoca
361
324
  declare function isCancelInvocationMessage(msg: HubMessage): msg is CancelInvocationMessage;
362
325
  declare function isPingMessage(msg: HubMessage): msg is PingMessage;
363
326
  declare function isCloseMessage(msg: HubMessage): msg is CloseMessage;
364
-
327
+ //#endregion
328
+ //#region src/interfaces.d.ts
365
329
  /** Minimal logger contract. Implement this to plug in any logging framework. */
366
330
  interface ILogger {
367
- log(logLevel: LogLevel, message: string): void;
331
+ log(logLevel: LogLevel, message: string): void;
368
332
  }
369
333
  /** Low-level transport abstraction (WebSocket / SSE / LongPolling). */
370
334
  interface ITransport {
371
- /** Human-readable name used in log messages and error reporting. */
372
- readonly name: string;
373
- /**
374
- * Open the transport connection.
375
- * @param url Fully-qualified URL including any query parameters.
376
- * @param transferFormat Text or Binary.
377
- */
378
- connect(url: string, transferFormat: TransferFormat): Promise<void>;
379
- /** Send a message over the open transport. */
380
- send(data: string | Uint8Array): Promise<void>;
381
- /** Tear down the connection cleanly. */
382
- stop(): Promise<void>;
383
- /** Called by HubConnection whenever data arrives. */
384
- onreceive: ((data: string | Uint8Array) => void) | null;
385
- /** Called by HubConnection when the transport is closed (optionally with error). */
386
- onclose: ((error?: Error) => void) | null;
387
- }
388
- /** Wire-protocol codec (JSON today; MessagePack can be added as an alternate). */
335
+ /** Human-readable name used in log messages and error reporting. */
336
+ readonly name: string;
337
+ /**
338
+ * Open the transport connection.
339
+ * @param url Fully-qualified URL including any query parameters.
340
+ * @param transferFormat Text or Binary.
341
+ */
342
+ connect(url: string, transferFormat: TransferFormat): Promise<void>;
343
+ /** Send a message over the open transport. */
344
+ send(data: string | Uint8Array): Promise<void>;
345
+ /** Tear down the connection cleanly. */
346
+ stop(): Promise<void>;
347
+ /** Called by HubConnection whenever data arrives. */
348
+ onreceive: ((data: string | Uint8Array) => void) | null;
349
+ /** Called by HubConnection when the transport is closed (optionally with error). */
350
+ onclose: ((error?: Error) => void) | null;
351
+ }
352
+ /** Wire-protocol codec used by a HubConnection. */
389
353
  interface IHubProtocol {
390
- readonly name: string;
391
- readonly version: number;
392
- readonly transferFormat: TransferFormat;
393
- /**
394
- * Decode raw bytes/string into zero or more hub messages.
395
- * Implementations must handle partial/buffered inputs gracefully.
396
- */
397
- parseMessages(input: string | ArrayBuffer, logger: ILogger): HubMessage[];
398
- /** Encode a single hub message to its wire representation. */
399
- writeMessage(message: HubMessage): string | ArrayBuffer;
354
+ readonly name: string;
355
+ readonly version: number;
356
+ readonly transferFormat: TransferFormat;
357
+ /**
358
+ * Decode raw bytes/string into zero or more hub messages.
359
+ * Implementations must handle partial/buffered inputs gracefully.
360
+ */
361
+ parseMessages(input: string | ArrayBuffer, logger: ILogger): HubMessage[];
362
+ /** Encode a single hub message to its wire representation. */
363
+ writeMessage(message: HubMessage): string | ArrayBuffer;
400
364
  }
401
365
  /** Context passed to the retry policy on each reconnect attempt. */
402
366
  interface RetryContext {
403
- readonly previousRetryCount: number;
404
- readonly elapsedMilliseconds: number;
405
- readonly retryReason: Error | null;
367
+ readonly previousRetryCount: number;
368
+ readonly elapsedMilliseconds: number;
369
+ readonly retryReason: Error | null;
406
370
  }
407
371
  /**
408
372
  * Controls the automatic-reconnect delay strategy.
409
373
  * Return `null` to stop retrying.
410
374
  */
411
375
  interface IRetryPolicy {
412
- nextRetryDelayInMilliseconds(retryContext: RetryContext): number | null;
376
+ nextRetryDelayInMilliseconds(retryContext: RetryContext): number | null;
413
377
  }
414
378
  /** Observer passed to `IStreamResult.subscribe`. */
415
379
  interface IStreamSubscriber<T> {
416
- readonly next?: (value: T) => void;
417
- readonly error?: (err: Error) => void;
418
- readonly complete?: () => void;
380
+ readonly next?: (value: T) => void;
381
+ readonly error?: (err: Error) => void;
382
+ readonly complete?: () => void;
419
383
  }
420
384
  /**
421
385
  * A handle returned by `subscribe` that lets the caller cancel the stream.
422
386
  * Implements `Symbol.dispose` for use with the `using` keyword (TS 5.2+).
423
387
  */
424
388
  interface ISubscription {
425
- dispose(): void;
426
- /** Enables `using subscription = connection.stream(...).subscribe(...)` */
427
- [Symbol.dispose](): void;
389
+ dispose(): void;
390
+ /** Enables `using subscription = connection.stream(...).subscribe(...)` */
391
+ [Symbol.dispose](): void;
428
392
  }
429
393
  /**
430
- * Lazy stream result - the server-streaming call is not sent until
431
- * `subscribe` is called.
394
+ * A running server-streaming invocation. It supports one subscriber.
432
395
  */
433
396
  interface IStreamResult<T> {
434
- subscribe(subscriber: IStreamSubscriber<T>): ISubscription;
397
+ subscribe(subscriber: IStreamSubscriber<T>): ISubscription;
435
398
  }
436
399
  /** Shape of the /negotiate response from an ASP.NET Core SignalR server. */
437
400
  interface NegotiateResponse {
438
- readonly connectionId?: string;
439
- readonly connectionToken?: string;
440
- readonly negotiateVersion?: number;
441
- readonly url?: string;
442
- readonly accessToken?: string;
443
- readonly error?: string;
444
- readonly availableTransports?: readonly AvailableTransport[];
401
+ readonly connectionId?: string;
402
+ readonly connectionToken?: string;
403
+ readonly negotiateVersion?: number;
404
+ readonly url?: string;
405
+ readonly accessToken?: string;
406
+ readonly error?: string;
407
+ readonly availableTransports?: readonly AvailableTransport[];
445
408
  }
446
409
  interface AvailableTransport {
447
- readonly transport: string;
448
- readonly transferFormats: readonly string[];
410
+ readonly transport: string;
411
+ readonly transferFormats: readonly string[];
449
412
  }
450
413
  /** Buffered HTTP response shared by all client implementations. */
451
414
  interface HttpResponse {
452
- readonly status: number;
453
- readonly headers: Readonly<Record<string, string | string[] | undefined>>;
454
- readonly body: string;
415
+ readonly status: number;
416
+ readonly headers: Readonly<Record<string, string | string[] | undefined>>;
417
+ readonly body: string;
455
418
  }
456
419
  /**
457
420
  * Result of a non-buffered (streaming) HTTP request.
@@ -463,10 +426,10 @@ interface HttpResponse {
463
426
  * Replaces the former `req.destroy()` pattern.
464
427
  */
465
428
  interface StreamResult {
466
- readonly statusCode: number;
467
- readonly headers: Readonly<Record<string, string | string[] | undefined>>;
468
- readonly body: Readable;
469
- abort(): void;
429
+ readonly statusCode: number;
430
+ readonly headers: Readonly<Record<string, string | string[] | undefined>>;
431
+ readonly body: Readable;
432
+ abort(): void;
470
433
  }
471
434
  /**
472
435
  * Common contract satisfied by all five HTTP client variants
@@ -476,314 +439,280 @@ interface StreamResult {
476
439
  * injected via `HubConnectionOptions.httpClient`.
477
440
  */
478
441
  interface IHttpClient {
479
- get(url: string, options?: RequestOptions): Promise<HttpResponse>;
480
- post(url: string, options?: RequestOptions): Promise<HttpResponse>;
481
- delete(url: string, options?: RequestOptions): Promise<HttpResponse>;
482
- request(method: HttpMethod, url: string, options?: RequestOptions): Promise<HttpResponse>;
483
- stream(method: HttpMethod, url: string, options?: RequestOptions): Promise<StreamResult>;
484
- }
485
-
486
- /**
487
- * hub-connection.ts
488
- *
489
- * Core HubConnection - the main object users interact with.
490
- *
491
- * Mirrors the Microsoft SignalR JavaScript client API with full TypeScript types:
492
- * start() / stop()
493
- * invoke<T>(method, ...args) → Promise<T>
494
- * send(method, ...args) → Promise<void>
495
- * stream<T>(method, ...args) → IStreamResult<T>
496
- * on(method, handler)
497
- * off(method, [handler])
498
- * onclose / onreconnecting / onreconnected
499
- */
500
-
442
+ get(url: string, options?: RequestOptions): Promise<HttpResponse>;
443
+ post(url: string, options?: RequestOptions): Promise<HttpResponse>;
444
+ delete(url: string, options?: RequestOptions): Promise<HttpResponse>;
445
+ request(method: HttpMethod, url: string, options?: RequestOptions): Promise<HttpResponse>;
446
+ stream(method: HttpMethod, url: string, options?: RequestOptions): Promise<StreamResult>;
447
+ }
448
+ //#endregion
449
+ //#region src/hub-connection.d.ts
501
450
  interface HubConnectionOptions {
502
- readonly logger?: ILogger;
503
- readonly accessTokenFactory?: () => Promise<string | null>;
504
- /** Bitmask of HttpTransportType flags (default: all transports). */
505
- readonly transport?: number;
506
- readonly headers?: Record<string, string>;
507
- readonly skipNegotiation?: boolean;
508
- readonly serverTimeoutInMilliseconds?: number;
509
- readonly keepAliveIntervalInMilliseconds?: number;
510
- /**
511
- * Override the SignalR handshake timeout (ms). Defaults to 15 000.
512
- * Intended for testing; production code should leave this at the default.
513
- */
514
- readonly handshakeTimeoutInMilliseconds?: number;
515
- readonly reconnectPolicy?: IRetryPolicy | null;
516
- /**
517
- * undici Dispatcher shared by all HTTP requests (negotiate, SSE, polling)
518
- * and the WebSocket upgrade for this connection.
519
- *
520
- * Pass an `Agent`, `Pool`, `Client`, `ProxyAgent`, etc. to customise
521
- * connection pooling, TLS, or proxy routing for the entire SignalR session.
522
- * When omitted, undici's process-global default agent is used.
523
- */
524
- readonly dispatcher?: Dispatcher;
525
- /**
526
- * Custom HTTP client to use for all requests made by this connection
527
- * (negotiate, SSE body reads, long-polling).
528
- *
529
- * When omitted, a `DispatchHttpClient` is created automatically using
530
- * the `dispatcher` option (if any). Provide this to use a different
531
- * undici primitive (e.g. `FetchHttpClient`) or to inject a mock in tests.
532
- */
533
- readonly httpClient?: IHttpClient;
451
+ readonly logger?: ILogger;
452
+ readonly accessTokenFactory?: () => Promise<string | null>;
453
+ /** Bitmask of HttpTransportType flags (default: all transports). */
454
+ readonly transport?: number;
455
+ readonly headers?: Record<string, string>;
456
+ readonly skipNegotiation?: boolean;
457
+ readonly serverTimeoutInMilliseconds?: number;
458
+ readonly keepAliveIntervalInMilliseconds?: number;
459
+ /**
460
+ * Override the SignalR handshake timeout (ms). Defaults to 15 000.
461
+ * Intended for testing; production code should leave this at the default.
462
+ */
463
+ readonly handshakeTimeoutInMilliseconds?: number;
464
+ readonly reconnectPolicy?: IRetryPolicy | null;
465
+ /**
466
+ * undici Dispatcher shared by all HTTP requests (negotiate, SSE, polling)
467
+ * and the WebSocket upgrade for this connection.
468
+ *
469
+ * Pass an `Agent`, `Pool`, `Client`, `ProxyAgent`, etc. to customise
470
+ * connection pooling, TLS, or proxy routing for the entire SignalR session.
471
+ * When omitted, undici's process-global default agent is used.
472
+ */
473
+ readonly dispatcher?: Dispatcher;
474
+ /**
475
+ * Custom HTTP client to use for all requests made by this connection
476
+ * (negotiate, SSE body reads, long-polling).
477
+ *
478
+ * When omitted, a `DispatchHttpClient` is created automatically using
479
+ * the `dispatcher` option (if any). Provide this to use a different
480
+ * undici primitive (e.g. `FetchHttpClient`) or to inject a mock in tests.
481
+ */
482
+ readonly httpClient?: IHttpClient;
483
+ /** Hub wire protocol. Defaults to JSON protocol version 1. */
484
+ readonly protocol?: IHubProtocol;
485
+ /** Maximum accepted transport payload size. Defaults to 32 MiB. */
486
+ readonly maximumReceiveMessageSize?: number;
487
+ /** Internal: close a builder-created dispatcher when the connection ends. */
488
+ readonly ownsDispatcher?: boolean;
534
489
  }
535
490
  declare class HubConnection {
536
- #private;
537
- constructor(url: string, options?: HubConnectionOptions);
538
- get state(): HubConnectionState;
539
- get connectionId(): string | null;
540
- start(): Promise<void>;
541
- stop(): Promise<void>;
542
- /**
543
- * Invoke a hub method and return the server's result.
544
- *
545
- * @typeParam T The expected return type. Asserted at runtime - the server
546
- * decides the actual value.
547
- */
548
- invoke<T = void>(methodName: string, ...args: unknown[]): Promise<T>;
549
- /**
550
- * Fire-and-forget hub method invocation.
551
- * The server does not send a completion message.
552
- */
553
- send(methodName: string, ...args: unknown[]): Promise<void>;
554
- /**
555
- * Start a server-streaming invocation.
556
- * The call is not sent until `subscribe` is called.
557
- * The returned `ISubscription` implements `Symbol.dispose` for `using`.
558
- *
559
- * @typeParam T Type of each streamed item.
560
- *
561
- * @example
562
- * ```ts
563
- * using sub = connection.stream<number>('Counter', 10).subscribe({
564
- * next: (n) => console.log(n),
565
- * complete: () => console.log('done'),
566
- * });
567
- * ```
568
- */
569
- stream<T = unknown>(methodName: string, ...args: unknown[]): IStreamResult<T>;
570
- /**
571
- * Register a handler for a server→client hub method.
572
- * Multiple handlers for the same method are supported.
573
- *
574
- * @typeParam TArgs Tuple of argument types for the hub method.
575
- */
576
- on<TArgs extends unknown[] = unknown[]>(methodName: string, handler: (...args: TArgs) => void): void;
577
- /**
578
- * Remove a previously registered handler, or all handlers for a method.
579
- */
580
- off(methodName: string, handler?: (...args: unknown[]) => void): void;
581
- onclose(callback: (error?: Error) => void): void;
582
- onreconnecting(callback: (error?: Error) => void): void;
583
- onreconnected(callback: (connectionId: string | null) => void): void;
584
- }
585
-
586
- /**
587
- * hub-connection-builder.ts
588
- *
589
- * Fluent builder for HubConnection - mirrors the official Microsoft client API.
590
- * Uses `const` type parameters (TS 5.0+) and `NoInfer<T>` (TS 5.4+) where
591
- * applicable to preserve literal types and prevent unintended widening.
592
- *
593
- * Usage
594
- * ─────
595
- * const connection = new HubConnectionBuilder()
596
- * .withUrl('https://example.com/hub', {
597
- * accessTokenFactory: () => fetchToken(),
598
- * transport: HttpTransportType.WebSockets,
599
- * })
600
- * .configureLogging(LogLevel.Information)
601
- * .withAutomaticReconnect()
602
- * .build();
603
- */
604
-
491
+ #private;
492
+ constructor(url: string, options?: HubConnectionOptions);
493
+ get state(): HubConnectionState;
494
+ get connectionId(): string | null;
495
+ start(): Promise<void>;
496
+ stop(): Promise<void>;
497
+ /**
498
+ * Invoke a hub method and return the server's result.
499
+ *
500
+ * @typeParam T The expected return type. Asserted at runtime - the server
501
+ * decides the actual value.
502
+ */
503
+ invoke<T = void>(methodName: string, ...args: unknown[]): Promise<T>;
504
+ /**
505
+ * Fire-and-forget hub method invocation.
506
+ * The server does not send a completion message.
507
+ */
508
+ send(methodName: string, ...args: unknown[]): Promise<void>;
509
+ /**
510
+ * Start a server-streaming invocation immediately.
511
+ * The returned `ISubscription` implements `Symbol.dispose` for `using`.
512
+ *
513
+ * @typeParam T Type of each streamed item.
514
+ *
515
+ * @example
516
+ * ```ts
517
+ * using sub = connection.stream<number>('Counter', 10).subscribe({
518
+ * next: (n) => console.log(n),
519
+ * complete: () => console.log('done'),
520
+ * });
521
+ * ```
522
+ */
523
+ stream<T = unknown>(methodName: string, ...args: unknown[]): IStreamResult<T>;
524
+ /**
525
+ * Register a handler for a server→client hub method.
526
+ * Multiple handlers for the same method are supported.
527
+ *
528
+ * @typeParam TArgs Tuple of argument types for the hub method.
529
+ */
530
+ on<TArgs extends unknown[] = unknown[]>(methodName: string, handler: (...args: TArgs) => unknown): void;
531
+ /**
532
+ * Remove a previously registered handler, or all handlers for a method.
533
+ */
534
+ off(methodName: string, handler?: (...args: unknown[]) => unknown): void;
535
+ onclose(callback: (error?: Error) => void): void;
536
+ onreconnecting(callback: (error?: Error) => void): void;
537
+ onreconnected(callback: (connectionId: string | null) => void): void;
538
+ }
539
+ //#endregion
540
+ //#region src/hub-connection-builder.d.ts
605
541
  interface UrlOptions {
606
- /** Async function returning a Bearer token (or null for unauthenticated). */
607
- readonly accessTokenFactory?: () => Promise<string | null>;
608
- /**
609
- * Bitmask of {@link HttpTransportType} values.
610
- * Defaults to all three transports if omitted.
611
- */
612
- readonly transport?: number;
613
- /** Extra HTTP headers appended to every request (negotiate, upgrade, poll…). */
614
- readonly headers?: Record<string, string>;
615
- /**
616
- * Skip the /negotiate step and connect directly via WebSocket.
617
- * Only valid when transport is exclusively `HttpTransportType.WebSockets`.
618
- */
619
- readonly skipNegotiation?: boolean;
620
- /** ms before the connection is considered unresponsive (default: 30 000). */
621
- readonly serverTimeoutInMilliseconds?: number;
622
- /** ms between keep-alive pings (default: 15 000). */
623
- readonly keepAliveIntervalInMilliseconds?: number;
624
- /** ms to wait for the SignalR handshake response (default: 15 000). */
625
- readonly handshakeTimeoutInMilliseconds?: number;
542
+ /** Async function returning a Bearer token (or null for unauthenticated). */
543
+ readonly accessTokenFactory?: () => Promise<string | null>;
544
+ /**
545
+ * Bitmask of {@link HttpTransportType} values.
546
+ * Defaults to all three transports if omitted.
547
+ */
548
+ readonly transport?: number;
549
+ /** Extra HTTP headers appended to every request (negotiate, upgrade, poll…). */
550
+ readonly headers?: Record<string, string>;
551
+ /**
552
+ * Skip the /negotiate step and connect directly via WebSocket.
553
+ * Only valid when transport is exclusively `HttpTransportType.WebSockets`.
554
+ */
555
+ readonly skipNegotiation?: boolean;
556
+ /** ms before the connection is considered unresponsive (default: 30 000). */
557
+ readonly serverTimeoutInMilliseconds?: number;
558
+ /** ms between keep-alive pings (default: 15 000). */
559
+ readonly keepAliveIntervalInMilliseconds?: number;
560
+ /** ms to wait for the SignalR handshake response (default: 15 000). */
561
+ readonly handshakeTimeoutInMilliseconds?: number;
562
+ /** Maximum accepted transport payload size (default: 32 MiB). */
563
+ readonly maximumReceiveMessageSize?: number;
626
564
  }
627
565
  declare class HubConnectionBuilder {
628
- #private;
629
- withUrl(url: string, options?: UrlOptions): this;
630
- /**
631
- * Enable automatic cookie handling for the entire connection session using
632
- * a `tough-cookie` `CookieJar` and an `@exhumer/undici-cookie-agent` `CookieAgent`.
633
- *
634
- * When enabled, the `CookieAgent` wraps every outgoing request - including
635
- * the `/negotiate` POST, WebSocket upgrade, SSE long-lived GET, and all
636
- * long-polling requests - so that:
637
- *
638
- * 1. `Set-Cookie` headers in the **negotiate response** (and any subsequent
639
- * response) are stored in the jar automatically.
640
- * 2. All subsequent requests from the same session include the matching
641
- * `Cookie` header, exactly as a browser would.
642
- *
643
- * @param jar
644
- * An existing `CookieJar` to use. Pass your own jar when you need to
645
- * pre-seed cookies (e.g. an auth session cookie obtained before calling
646
- * `start()`) or inspect the jar after the session ends.
647
- * When omitted a new, empty jar is created automatically.
648
- *
649
- * @throws if {@link withDispatcher} has already been called. To combine a
650
- * custom dispatcher (e.g. `ProxyAgent`) with cookie support, compose the
651
- * `cookie` interceptor onto your dispatcher and pass it to `withDispatcher()`:
652
- *
653
- * ```ts
654
- * import { ProxyAgent } from 'undici';
655
- * import { cookie, CookieJar } from '@exhumer/signalr-client';
656
- *
657
- * const jar = new CookieJar();
658
- * const agent = new ProxyAgent('http://proxy:8080').compose(cookie({ jar }));
659
- *
660
- * const conn = new HubConnectionBuilder()
661
- * .withUrl('https://example.com/hub')
662
- * .withDispatcher(agent)
663
- * .build();
664
- * ```
665
- *
666
- * @example
667
- * ```ts
668
- * // Automatic jar - no pre-configuration needed
669
- * const conn = new HubConnectionBuilder()
670
- * .withUrl('https://example.com/hub')
671
- * .withCookies()
672
- * .build();
673
- *
674
- * // Pre-seeded jar - inject a session cookie before connecting
675
- * import { CookieJar } from '@exhumer/signalr-client';
676
- * const jar = new CookieJar();
677
- * await jar.setCookie('session=abc123', 'https://example.com');
678
- *
679
- * const conn = new HubConnectionBuilder()
680
- * .withUrl('https://example.com/hub')
681
- * .withCookies(jar)
682
- * .build();
683
- * ```
684
- */
685
- withCookies(jar?: CookieJar): this;
686
- /**
687
- * Set the undici `Dispatcher` for the entire connection session.
688
- *
689
- * The same dispatcher is used for:
690
- * • the `/negotiate` HTTP POST
691
- * • the WebSocket upgrade request
692
- * • SSE long-lived GET and send POSTs
693
- * • long-polling GETs, POSTs, and DELETE
694
- *
695
- * Accepts any `Dispatcher` subclass: `Agent`, `Pool`, `Client`,
696
- * `ProxyAgent`, `MockAgent`, etc.
697
- *
698
- * To combine a custom dispatcher with automatic cookie handling, use
699
- * `createCookieAgentClass()` to build a cookie-aware variant of your
700
- * dispatcher and pass that here. Do **not** chain both
701
- * `withDispatcher()` and `withCookies()` - they are mutually exclusive
702
- * because `withCookies()` creates its own dispatcher internally.
703
- *
704
- * @example
705
- * ```ts
706
- * import { ProxyAgent } from 'undici';
707
- *
708
- * const conn = new HubConnectionBuilder()
709
- * .withUrl('https://example.com/hub')
710
- * .withDispatcher(new ProxyAgent('http://proxy:8080'))
711
- * .build();
712
- * ```
713
- */
714
- withDispatcher(dispatcher: Dispatcher): this;
715
- /**
716
- * Provide a custom HTTP client implementation.
717
- *
718
- * By default `HubConnection` uses `DispatchHttpClient` (undici `dispatch`).
719
- * Use this to substitute any of the other undici-backed clients, or
720
- * to inject a mock for testing.
721
- *
722
- * @example
723
- * ```ts
724
- * import { FetchHttpClient } from '@signalr/client';
725
- *
726
- * const conn = new HubConnectionBuilder()
727
- * .withUrl('https://example.com/hub')
728
- * .withHttpClient(new FetchHttpClient())
729
- * .build();
730
- * ```
731
- */
732
- withHttpClient(httpClient: IHttpClient): this;
733
- /**
734
- * Set the minimum log level or provide a custom logger.
735
- *
736
- * @param logLevelOrLogger
737
- * - `LogLevel` number → uses the built-in ConsoleLogger
738
- * - `ILogger` object → used as-is
739
- */
740
- configureLogging(logLevelOrLogger: LogLevel | ILogger): this;
741
- /**
742
- * Enable automatic reconnection on unexpected disconnections.
743
- *
744
- * @overload withAutomaticReconnect()
745
- * Uses the built-in delay sequence: 0 ms, 2 s, 10 s, 30 s.
746
- *
747
- * @overload withAutomaticReconnect(retryDelays: readonly number[])
748
- * Each element is the wait (ms) before the corresponding retry.
749
- * Reconnection stops after all delays are exhausted.
750
- * Uses `NoInfer<number>` so literals are not widened unexpectedly.
751
- *
752
- * @overload withAutomaticReconnect(policy: IRetryPolicy)
753
- * Custom policy. Return `null` from
754
- * `nextRetryDelayInMilliseconds` to stop retrying.
755
- */
756
- withAutomaticReconnect(): this;
757
- withAutomaticReconnect(retryDelays: readonly NoInfer<number>[]): this;
758
- withAutomaticReconnect(policy: IRetryPolicy): this;
759
- build(): HubConnection;
566
+ #private;
567
+ withUrl(url: string, options?: UrlOptions): this;
568
+ /**
569
+ * Enable automatic cookie handling for the entire connection session using
570
+ * a `tough-cookie` `CookieJar` and an `@exhumer/undici-cookie-agent` `CookieAgent`.
571
+ *
572
+ * When enabled, the `CookieAgent` wraps every outgoing request - including
573
+ * the `/negotiate` POST, WebSocket upgrade, SSE long-lived GET, and all
574
+ * long-polling requests - so that:
575
+ *
576
+ * 1. `Set-Cookie` headers in the **negotiate response** (and any subsequent
577
+ * response) are stored in the jar automatically.
578
+ * 2. All subsequent requests from the same session include the matching
579
+ * `Cookie` header, exactly as a browser would.
580
+ *
581
+ * @param jar
582
+ * An existing `CookieJar` to use. Pass your own jar when you need to
583
+ * pre-seed cookies (e.g. an auth session cookie obtained before calling
584
+ * `start()`) or inspect the jar after the session ends.
585
+ * When omitted a new, empty jar is created automatically.
586
+ *
587
+ * @throws if {@link withDispatcher} has already been called. To combine a
588
+ * custom dispatcher (e.g. `ProxyAgent`) with cookie support, compose the
589
+ * `cookie` interceptor onto your dispatcher and pass it to `withDispatcher()`:
590
+ *
591
+ * ```ts
592
+ * import { ProxyAgent } from 'undici';
593
+ * import { cookie, CookieJar } from '@exhumer/signalr-client';
594
+ *
595
+ * const jar = new CookieJar();
596
+ * const agent = new ProxyAgent('http://proxy:8080').compose(cookie({ jar }));
597
+ *
598
+ * const conn = new HubConnectionBuilder()
599
+ * .withUrl('https://example.com/hub')
600
+ * .withDispatcher(agent)
601
+ * .build();
602
+ * ```
603
+ *
604
+ * @example
605
+ * ```ts
606
+ * // Automatic jar - no pre-configuration needed
607
+ * const conn = new HubConnectionBuilder()
608
+ * .withUrl('https://example.com/hub')
609
+ * .withCookies()
610
+ * .build();
611
+ *
612
+ * // Pre-seeded jar - inject a session cookie before connecting
613
+ * import { CookieJar } from '@exhumer/signalr-client';
614
+ * const jar = new CookieJar();
615
+ * await jar.setCookie('session=abc123', 'https://example.com');
616
+ *
617
+ * const conn = new HubConnectionBuilder()
618
+ * .withUrl('https://example.com/hub')
619
+ * .withCookies(jar)
620
+ * .build();
621
+ * ```
622
+ */
623
+ withCookies(jar?: CookieJar$1): this;
624
+ /**
625
+ * Set the undici `Dispatcher` for the entire connection session.
626
+ *
627
+ * The same dispatcher is used for:
628
+ * • the `/negotiate` HTTP POST
629
+ * • the WebSocket upgrade request
630
+ * • SSE long-lived GET and send POSTs
631
+ * • long-polling GETs, POSTs, and DELETE
632
+ *
633
+ * Accepts any `Dispatcher` subclass: `Agent`, `Pool`, `Client`,
634
+ * `ProxyAgent`, `MockAgent`, etc.
635
+ *
636
+ * To combine a custom dispatcher with automatic cookie handling, use
637
+ * `createCookieAgentClass()` to build a cookie-aware variant of your
638
+ * dispatcher and pass that here. Do **not** chain both
639
+ * `withDispatcher()` and `withCookies()` - they are mutually exclusive
640
+ * because `withCookies()` creates its own dispatcher internally.
641
+ *
642
+ * @example
643
+ * ```ts
644
+ * import { ProxyAgent } from 'undici';
645
+ *
646
+ * const conn = new HubConnectionBuilder()
647
+ * .withUrl('https://example.com/hub')
648
+ * .withDispatcher(new ProxyAgent('http://proxy:8080'))
649
+ * .build();
650
+ * ```
651
+ */
652
+ withDispatcher(dispatcher: Dispatcher): this;
653
+ /**
654
+ * Provide a custom HTTP client implementation.
655
+ *
656
+ * By default `HubConnection` uses `DispatchHttpClient` (undici `dispatch`).
657
+ * Use this to substitute any of the other undici-backed clients, or
658
+ * to inject a mock for testing.
659
+ *
660
+ * @example
661
+ * ```ts
662
+ * import { FetchHttpClient } from '@signalr/client';
663
+ *
664
+ * const conn = new HubConnectionBuilder()
665
+ * .withUrl('https://example.com/hub')
666
+ * .withHttpClient(new FetchHttpClient())
667
+ * .build();
668
+ * ```
669
+ */
670
+ withHttpClient(httpClient: IHttpClient): this;
671
+ /** Select the hub wire protocol (for example, MessagePack). */
672
+ withHubProtocol(protocol: IHubProtocol): this;
673
+ /**
674
+ * Set the minimum log level or provide a custom logger.
675
+ *
676
+ * @param logLevelOrLogger
677
+ * - `LogLevel` number → uses the built-in ConsoleLogger
678
+ * - `ILogger` object → used as-is
679
+ */
680
+ configureLogging(logLevelOrLogger: LogLevel | ILogger): this;
681
+ /**
682
+ * Enable automatic reconnection on unexpected disconnections.
683
+ *
684
+ * @overload withAutomaticReconnect()
685
+ * Uses the built-in delay sequence: 0 ms, 2 s, 10 s, 30 s.
686
+ *
687
+ * @overload withAutomaticReconnect(retryDelays: readonly number[])
688
+ * Each element is the wait (ms) before the corresponding retry.
689
+ * Reconnection stops after all delays are exhausted.
690
+ * Uses `NoInfer<number>` so literals are not widened unexpectedly.
691
+ *
692
+ * @overload withAutomaticReconnect(policy: IRetryPolicy)
693
+ * Custom policy. Return `null` from
694
+ * `nextRetryDelayInMilliseconds` to stop retrying.
695
+ */
696
+ withAutomaticReconnect(): this;
697
+ withAutomaticReconnect(retryDelays: readonly NoInfer<number>[]): this;
698
+ withAutomaticReconnect(policy: IRetryPolicy): this;
699
+ build(): HubConnection;
760
700
  }
761
701
  declare class DefaultReconnectPolicy implements IRetryPolicy {
762
- #private;
763
- constructor(retryDelays?: readonly number[]);
764
- nextRetryDelayInMilliseconds(context: RetryContext): number | null;
702
+ #private;
703
+ constructor(retryDelays?: readonly number[]);
704
+ nextRetryDelayInMilliseconds(context: RetryContext): number | null;
765
705
  }
766
-
767
- /**
768
- * json-hub-protocol.ts
769
- *
770
- * Implements the SignalR Hub Protocol over JSON (version 1).
771
- *
772
- * Wire format: every message is JSON followed by ASCII 0x1e (RECORD_SEPARATOR).
773
- * A single transport payload may contain multiple messages.
774
- *
775
- * Reference:
776
- * https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/HubProtocol.md
777
- */
778
-
779
- declare const HANDSHAKE_REQUEST$1: string;
706
+ //#endregion
707
+ //#region src/protocols/json-hub-protocol.d.ts
708
+ declare const HANDSHAKE_REQUEST: string;
780
709
  interface HandshakeResponse {
781
- readonly error?: string;
782
- readonly minorVersion?: number;
710
+ readonly error?: string;
711
+ readonly minorVersion?: number;
783
712
  }
784
713
  interface HandshakeParseResult {
785
- /** Remainder of the input string after the handshake record (may be non-empty). */
786
- readonly remainder: string;
714
+ /** Remainder of the input string after the handshake record (may be non-empty). */
715
+ readonly remainder: string;
787
716
  }
788
717
  /**
789
718
  * Parse the first record from `data` as the server handshake response.
@@ -791,95 +720,61 @@ interface HandshakeParseResult {
791
720
  */
792
721
  declare function parseHandshakeResponse(data: string): HandshakeParseResult;
793
722
  declare class JsonHubProtocol implements IHubProtocol {
794
- #private;
795
- readonly name: "json";
796
- readonly version: 1;
797
- readonly transferFormat: 1;
798
- parseMessages(input: string | ArrayBuffer, logger: ILogger): HubMessage[];
799
- writeMessage(message: HubMessage): string;
800
- static invocation(invocationId: InvocationId, target: string, args: readonly unknown[], streamIds?: readonly string[]): InvocationMessage;
801
- /**
802
- * Fire-and-forget (no `invocationId` → server won't send a Completion).
803
- */
804
- static send(target: string, args: readonly unknown[], streamIds?: readonly string[]): InvocationMessage;
805
- static streamInvocation(invocationId: InvocationId, target: string, args: readonly unknown[], streamIds?: readonly string[]): StreamInvocationMessage;
806
- static cancelInvocation(invocationId: InvocationId): CancelInvocationMessage;
807
- static streamItem(invocationId: InvocationId, item: unknown): StreamItemMessage;
808
- static completion(invocationId: InvocationId, result: unknown, error: string | null): CompletionMessage;
809
- static ping(): PingMessage;
810
- }
811
-
812
- /**
813
- * msgpack-hub-protocol.ts
814
- *
815
- * Implements the SignalR Hub Protocol over MessagePack (version 1).
816
- *
817
- * Wire format
818
- * ───────────
819
- * • Handshake: JSON text terminated by ASCII 0x1e - identical to the JSON
820
- * protocol, only the "protocol" field changes to "messagepack".
821
- * • All subsequent messages: binary MessagePack, each frame prefixed by a
822
- * base-128 VarInt carrying the byte-length of the following MessagePack
823
- * payload. A single transport payload may contain multiple such frames.
824
- *
825
- * MessagePack array layout (per message type)
826
- * ────────────────────────────────────────────
827
- * Invocation [1, headers, invocationId|null, target, args, streamIds]
828
- * StreamItem [2, headers, invocationId, item]
829
- * Completion [3, headers, invocationId, resultKind, value?]
830
- * resultKind: 1 = error string, 2 = void, 3 = non-void result value
831
- * StreamInvocation [4, headers, invocationId, target, args, streamIds]
832
- * CancelInvocation [5, headers, invocationId]
833
- * Ping [6]
834
- * Close [7, error|null, allowReconnect]
835
- *
836
- * Reference:
837
- * https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/HubProtocol.md
838
- */
839
-
723
+ #private;
724
+ readonly name: "json";
725
+ readonly version: 1;
726
+ readonly transferFormat: 1;
727
+ parseMessages(input: string | ArrayBuffer, logger: ILogger): HubMessage[];
728
+ writeMessage(message: HubMessage): string;
729
+ static invocation(invocationId: InvocationId, target: string, args: readonly unknown[], streamIds?: readonly string[]): InvocationMessage;
730
+ /**
731
+ * Fire-and-forget (no `invocationId` → server won't send a Completion).
732
+ */
733
+ static send(target: string, args: readonly unknown[], streamIds?: readonly string[]): InvocationMessage;
734
+ static streamInvocation(invocationId: InvocationId, target: string, args: readonly unknown[], streamIds?: readonly string[]): StreamInvocationMessage;
735
+ static cancelInvocation(invocationId: InvocationId): CancelInvocationMessage;
736
+ static streamItem(invocationId: InvocationId, item: unknown): StreamItemMessage;
737
+ static completion(invocationId: InvocationId, result: unknown, error: string | null): CompletionMessage;
738
+ static ping(): PingMessage;
739
+ }
740
+ //#endregion
741
+ //#region src/protocols/msgpack-hub-protocol.d.ts
840
742
  /**
841
743
  * The JSON-formatted handshake request the client sends once the transport
842
744
  * is open. The server always responds with JSON ({} on success), regardless
843
745
  * of the chosen hub protocol.
844
746
  */
845
- declare const HANDSHAKE_REQUEST: string;
846
-
747
+ declare const HANDSHAKE_REQUEST$1: string;
847
748
  declare class MsgpackHubProtocol implements IHubProtocol {
848
- #private;
849
- readonly name: "messagepack";
850
- readonly version: 1;
851
- readonly transferFormat: 2;
852
- parseMessages(input: string | ArrayBuffer, logger: ILogger): HubMessage[];
853
- writeMessage(message: HubMessage): ArrayBuffer;
854
- static invocation(invocationId: InvocationId, target: string, args: readonly unknown[], streamIds?: readonly string[]): InvocationMessage;
855
- /** Fire-and-forget (no `invocationId`). */
856
- static send(target: string, args: readonly unknown[], streamIds?: readonly string[]): InvocationMessage;
857
- static streamInvocation(invocationId: InvocationId, target: string, args: readonly unknown[], streamIds?: readonly string[]): StreamInvocationMessage;
858
- static cancelInvocation(invocationId: InvocationId): CancelInvocationMessage;
859
- static streamItem(invocationId: InvocationId, item: unknown): StreamItemMessage;
860
- static completion(invocationId: InvocationId, result: unknown, error: string | null): CompletionMessage;
861
- static ping(): PingMessage;
862
- }
863
-
864
- /**
865
- * logger.ts
866
- *
867
- * Built-in ILogger implementations.
868
- * ConsoleLogger - writes to console with timestamps and severity labels.
869
- * NullLogger - discards everything (default when no logger is configured).
870
- */
871
-
749
+ #private;
750
+ readonly name: "messagepack";
751
+ readonly version: 1;
752
+ readonly transferFormat: 2;
753
+ parseMessages(input: string | ArrayBuffer, logger: ILogger): HubMessage[];
754
+ writeMessage(message: HubMessage): ArrayBuffer;
755
+ static invocation(invocationId: InvocationId, target: string, args: readonly unknown[], streamIds?: readonly string[]): InvocationMessage;
756
+ /** Fire-and-forget (no `invocationId`). */
757
+ static send(target: string, args: readonly unknown[], streamIds?: readonly string[]): InvocationMessage;
758
+ static streamInvocation(invocationId: InvocationId, target: string, args: readonly unknown[], streamIds?: readonly string[]): StreamInvocationMessage;
759
+ static cancelInvocation(invocationId: InvocationId): CancelInvocationMessage;
760
+ static streamItem(invocationId: InvocationId, item: unknown): StreamItemMessage;
761
+ static completion(invocationId: InvocationId, result: unknown, error: string | null): CompletionMessage;
762
+ static ping(): PingMessage;
763
+ }
764
+ //#endregion
765
+ //#region src/logger.d.ts
872
766
  declare class ConsoleLogger implements ILogger {
873
- #private;
874
- constructor(minimumLevel?: LogLevel);
875
- log(level: LogLevel, message: string): void;
767
+ #private;
768
+ constructor(minimumLevel?: LogLevel);
769
+ log(level: LogLevel, message: string): void;
876
770
  }
877
771
  declare class NullLogger implements ILogger {
878
- /** Singleton - no state, so one instance is enough. */
879
- static readonly instance: NullLogger;
880
- log(_logLevel: LogLevel, _message: string): void;
772
+ /** Singleton - no state, so one instance is enough. */
773
+ static readonly instance: NullLogger;
774
+ log(_logLevel: LogLevel, _message: string): void;
881
775
  }
882
-
776
+ //#endregion
777
+ //#region src/errors.d.ts
883
778
  /**
884
779
  * errors.ts
885
780
  *
@@ -889,198 +784,130 @@ declare class NullLogger implements ILogger {
889
784
  */
890
785
  /** Thrown when a hub method invocation fails with a server-side error. */
891
786
  declare class HubError extends Error {
892
- readonly name: "HubError";
893
- constructor(message: string);
787
+ readonly name: "HubError";
788
+ constructor(message: string);
894
789
  }
895
790
  /** Thrown when an in-flight operation is cancelled (e.g. connection closed). */
896
791
  declare class AbortError extends Error {
897
- readonly name: "AbortError";
898
- constructor(message?: string);
792
+ readonly name: "AbortError";
793
+ constructor(message?: string);
899
794
  }
900
795
  /** Thrown on network-level transport failures. */
901
796
  declare class TransportError extends Error {
902
- readonly name: "TransportError";
903
- readonly statusCode: number | undefined;
904
- constructor(message: string, statusCode?: number);
797
+ readonly name: "TransportError";
798
+ readonly statusCode: number | undefined;
799
+ constructor(message: string, statusCode?: number);
905
800
  }
906
801
  /** Thrown when the SignalR protocol handshake is rejected by the server. */
907
802
  declare class HandshakeError extends Error {
908
- readonly name: "HandshakeError";
909
- constructor(message: string);
803
+ readonly name: "HandshakeError";
804
+ constructor(message: string);
910
805
  }
911
806
  /** Thrown when no acceptable transport could be negotiated. */
912
807
  declare class UnsupportedTransportError extends Error {
913
- readonly name: "UnsupportedTransportError";
914
- readonly transport: number | null;
915
- constructor(message: string, transport: number | null);
808
+ readonly name: "UnsupportedTransportError";
809
+ readonly transport: number | null;
810
+ constructor(message: string, transport: number | null);
916
811
  }
917
812
  declare function isHubError(e: unknown): e is HubError;
918
813
  declare function isAbortError(e: unknown): e is AbortError;
919
814
  declare function isTransportError(e: unknown): e is TransportError;
920
-
921
- /**
922
- * websocket-transport.ts
923
- *
924
- * SignalR WebSocket transport - rewritten to use undici's built-in
925
- * WHATWG-compatible `WebSocket` implementation.
926
- *
927
- * Why undici WebSocket instead of the hand-rolled RFC 6455 client?
928
- * ─────────────────────────────────────────────────────────────────
929
- * • undici is the HTTP engine Node.js core ships with (≥ v18).
930
- * • Its WebSocket implementation passes the Autobahn test suite.
931
- * • It accepts the same `Dispatcher` used by the HTTP clients, so the
932
- * entire SignalR session (negotiate, handshake, upgrade) shares a single
933
- * connection pool / proxy config.
934
- * • It supports custom headers on the upgrade request (needed for auth
935
- * and extra headers), which the browser WebSocket API does not.
936
- *
937
- * undici WebSocket quirks in Node.js
938
- * ────────────────────────────────────
939
- * • The constructor signature is:
940
- * new WebSocket(url, { headers?, dispatcher?, protocols? })
941
- * The `headers` and `dispatcher` fields are undici extensions not in the
942
- * WHATWG spec.
943
- * • `MessageEvent.data` type depends on `ws.binaryType`:
944
- * 'arraybuffer' (what we set) → ArrayBuffer
945
- * 'blob' → Blob
946
- * We set `binaryType = 'arraybuffer'` and convert ArrayBuffer → Buffer on
947
- * receipt. ('nodebuffer' is a valid undici runtime value but is absent from
948
- * the WHATWG BinaryType union in undici's TypeScript declarations.)
949
- * • `CloseEvent.code` / `.reason` behave identically to the browser.
950
- */
951
-
815
+ //#endregion
816
+ //#region src/transports/websocket-transport.d.ts
952
817
  declare class WebSocketTransport implements ITransport {
953
- #private;
954
- readonly name: "WebSockets";
955
- onreceive: ((data: string | Uint8Array) => void) | null;
956
- onclose: ((error?: Error) => void) | null;
957
- /**
958
- * @param accessTokenFactory Async factory for Bearer tokens, or null.
959
- * @param logger Logger instance.
960
- * @param extraHeaders Headers forwarded on every upgrade request.
961
- * @param dispatcher Optional undici Dispatcher (Agent/Pool/Client/
962
- * ProxyAgent). When omitted, undici's default
963
- * global agent is used. Pass the same dispatcher
964
- * used by your HTTP clients to share the pool.
965
- */
966
- constructor(accessTokenFactory: (() => Promise<string | null>) | null, logger: ILogger, extraHeaders?: Record<string, string>, dispatcher?: Dispatcher);
967
- connect(url: string, _transferFormat: TransferFormat): Promise<void>;
968
- send(data: string | Uint8Array): Promise<void>;
969
- stop(): Promise<void>;
970
- }
971
-
972
- /**
973
- * sse-transport.ts
974
- *
975
- * SignalR transport using Server-Sent Events (SSE) for receiving and
976
- * HTTP POST for sending.
977
- *
978
- * SSE spec: https://html.spec.whatwg.org/multipage/server-sent-events.html
979
- *
980
- * Updated to use the new StreamResult shape from http-client.ts:
981
- * result.body - Node Readable carrying the SSE byte stream
982
- * result.abort - cancels the in-flight request (replaces req.destroy())
983
- */
984
-
818
+ #private;
819
+ readonly name: "WebSockets";
820
+ onclose: ((error?: Error) => void) | null;
821
+ get onreceive(): ((data: string | Uint8Array) => void) | null;
822
+ set onreceive(handler: ((data: string | Uint8Array) => void) | null);
823
+ /**
824
+ * @param accessTokenFactory Async factory for Bearer tokens, or null.
825
+ * @param logger Logger instance.
826
+ * @param extraHeaders Headers forwarded on every upgrade request.
827
+ * @param dispatcher Optional undici Dispatcher (Agent/Pool/Client/
828
+ * ProxyAgent). When omitted, undici's default
829
+ * global agent is used. Pass the same dispatcher
830
+ * used by your HTTP clients to share the pool.
831
+ */
832
+ constructor(accessTokenFactory: (() => Promise<string | null>) | null, logger: ILogger, extraHeaders?: Record<string, string>, dispatcher?: Dispatcher$1);
833
+ connect(url: string, _transferFormat: TransferFormat): Promise<void>;
834
+ send(data: string | Uint8Array): Promise<void>;
835
+ stop(): Promise<void>;
836
+ }
837
+ //#endregion
838
+ //#region src/transports/sse-transport.d.ts
985
839
  declare class ServerSentEventsTransport implements ITransport {
986
- #private;
987
- readonly name: "ServerSentEvents";
988
- onreceive: ((data: string | Uint8Array) => void) | null;
989
- onclose: ((error?: Error) => void) | null;
990
- constructor(httpClient: IHttpClient, accessTokenFactory: (() => Promise<string | null>) | null, logger: ILogger, extraHeaders?: Record<string, string>);
991
- connect(url: string, transferFormat: TransferFormat): Promise<void>;
992
- send(data: string | Uint8Array): Promise<void>;
993
- stop(): Promise<void>;
994
- }
995
-
996
- /**
997
- * long-polling-transport.ts
998
- *
999
- * SignalR Long-Polling transport.
1000
- * HTTP GET (hangs until data arrives) → receive
1001
- * HTTP POST → send
1002
- * HTTP DELETE → disconnect
1003
- *
1004
- * Updated to depend on IHttpClient rather than the concrete HttpClient class
1005
- * so any of the five undici-backed client implementations can be injected.
1006
- */
1007
-
840
+ #private;
841
+ readonly name: "ServerSentEvents";
842
+ onreceive: ((data: string | Uint8Array) => void) | null;
843
+ onclose: ((error?: Error) => void) | null;
844
+ constructor(httpClient: IHttpClient, accessTokenFactory: (() => Promise<string | null>) | null, logger: ILogger, extraHeaders?: Record<string, string>);
845
+ connect(url: string, transferFormat: TransferFormat): Promise<void>;
846
+ send(data: string | Uint8Array): Promise<void>;
847
+ stop(): Promise<void>;
848
+ }
849
+ //#endregion
850
+ //#region src/transports/long-polling-transport.d.ts
1008
851
  declare class LongPollingTransport implements ITransport {
1009
- #private;
1010
- readonly name: "LongPolling";
1011
- onreceive: ((data: string | Uint8Array) => void) | null;
1012
- onclose: ((error?: Error) => void) | null;
1013
- constructor(httpClient: IHttpClient, accessTokenFactory: (() => Promise<string | null>) | null, logger: ILogger, extraHeaders?: Record<string, string>);
1014
- connect(url: string, _transferFormat: TransferFormat): Promise<void>;
1015
- send(data: string | Uint8Array): Promise<void>;
1016
- stop(): Promise<void>;
1017
- }
1018
-
1019
- /**
1020
- * ws-client.ts
1021
- *
1022
- * From-scratch WebSocket client (RFC 6455) built on Node's built-in `net`
1023
- * and `tls` modules. Zero external runtime dependencies.
1024
- *
1025
- * Typed EventEmitter via interface declaration merging.
1026
- *
1027
- * Emitted events
1028
- * 'open' - handshake complete, ready to send/receive
1029
- * 'message' (string) - UTF-8 text frame received
1030
- * 'binary' (Buffer) - binary frame received
1031
- * 'ping' (Buffer) - ping frame received (pong sent automatically)
1032
- * 'pong' (Buffer) - pong frame received
1033
- * 'close' - socket fully closed
1034
- * 'error' (Error) - socket-level error
1035
- */
1036
-
852
+ #private;
853
+ readonly name: "LongPolling";
854
+ onreceive: ((data: string | Uint8Array) => void) | null;
855
+ onclose: ((error?: Error) => void) | null;
856
+ constructor(httpClient: IHttpClient, accessTokenFactory: (() => Promise<string | null>) | null, logger: ILogger, extraHeaders?: Record<string, string>);
857
+ connect(url: string, transferFormat: TransferFormat): Promise<void>;
858
+ send(data: string | Uint8Array): Promise<void>;
859
+ stop(): Promise<void>;
860
+ }
861
+ //#endregion
862
+ //#region src/ws-client.d.ts
1037
863
  declare const enum WebSocketReadyState {
1038
- Connecting = 0,
1039
- Open = 1,
1040
- Closing = 2,
1041
- Closed = 3
864
+ Connecting = 0,
865
+ Open = 1,
866
+ Closing = 2,
867
+ Closed = 3
1042
868
  }
1043
869
  interface WebSocketClient {
1044
- on(event: 'open', listener: () => void): this;
1045
- on(event: 'message', listener: (data: string) => void): this;
1046
- on(event: 'binary', listener: (data: Buffer) => void): this;
1047
- on(event: 'ping', listener: (data: Buffer) => void): this;
1048
- on(event: 'pong', listener: (data: Buffer) => void): this;
1049
- on(event: 'close', listener: () => void): this;
1050
- on(event: 'error', listener: (err: Error) => void): this;
1051
- once(event: 'open', listener: () => void): this;
1052
- once(event: 'message', listener: (data: string) => void): this;
1053
- once(event: 'close', listener: () => void): this;
1054
- once(event: 'error', listener: (err: Error) => void): this;
1055
- emit(event: 'open'): boolean;
1056
- emit(event: 'message', data: string): boolean;
1057
- emit(event: 'binary', data: Buffer): boolean;
1058
- emit(event: 'ping', data: Buffer): boolean;
1059
- emit(event: 'pong', data: Buffer): boolean;
1060
- emit(event: 'close'): boolean;
1061
- emit(event: 'error', err: Error): boolean;
1062
- removeAllListeners(event?: string): this;
870
+ on(event: 'open', listener: () => void): this;
871
+ on(event: 'message', listener: (data: string) => void): this;
872
+ on(event: 'binary', listener: (data: Buffer) => void): this;
873
+ on(event: 'ping', listener: (data: Buffer) => void): this;
874
+ on(event: 'pong', listener: (data: Buffer) => void): this;
875
+ on(event: 'close', listener: () => void): this;
876
+ on(event: 'error', listener: (err: Error) => void): this;
877
+ once(event: 'open', listener: () => void): this;
878
+ once(event: 'message', listener: (data: string) => void): this;
879
+ once(event: 'close', listener: () => void): this;
880
+ once(event: 'error', listener: (err: Error) => void): this;
881
+ emit(event: 'open'): boolean;
882
+ emit(event: 'message', data: string): boolean;
883
+ emit(event: 'binary', data: Buffer): boolean;
884
+ emit(event: 'ping', data: Buffer): boolean;
885
+ emit(event: 'pong', data: Buffer): boolean;
886
+ emit(event: 'close'): boolean;
887
+ emit(event: 'error', err: Error): boolean;
888
+ removeAllListeners(event?: string): this;
1063
889
  }
1064
890
  declare class WebSocketClient extends EventEmitter {
1065
- #private;
1066
- get readyState(): WebSocketReadyState;
1067
- /**
1068
- * Open a WebSocket connection.
1069
- * @param url ws:// or wss:// URL
1070
- * @param headers Extra HTTP headers for the upgrade request
1071
- */
1072
- connect(url: string, headers?: Record<string, string>): Promise<void>;
1073
- /**
1074
- * Send a text or binary message.
1075
- * @throws if the socket is not open.
1076
- */
1077
- send(data: string | Buffer | Uint8Array): void;
1078
- /**
1079
- * Initiate a clean close handshake.
1080
- * @param code WebSocket close code (default 1000 = Normal Closure)
1081
- * @param reason UTF-8 reason string (max 123 bytes)
1082
- */
1083
- close(code?: number, reason?: string): void;
1084
- }
1085
-
1086
- export { AbortError, type AvailableTransport, type CancelInvocationMessage, type CloseMessage, type CompletionMessage, ConsoleLogger, DEFAULT_PING_INTERVAL_IN_MS, DEFAULT_SERVER_TIMEOUT_IN_MS, DEFAULT_TIMEOUT_IN_MS, DefaultReconnectPolicy, DispatchHttpClient, FetchHttpClient, HANDSHAKE_REQUEST$1 as HANDSHAKE_REQUEST, HandshakeError, type HandshakeParseResult, type HandshakeResponse, DispatchHttpClient as HttpClient, type HttpClientOptions, type HttpMethod, type HttpResponse, HttpTransportType, HubConnection, HubConnectionBuilder, type HubConnectionOptions, HubConnectionState, HubError, type HubMessage, type IHttpClient, type IHubProtocol, type ILogger, type IRetryPolicy, type IStreamResult, type IStreamSubscriber, type ISubscription, type ITransport, type InvocationId, type InvocationMessage, JsonHubProtocol, LogLevel, LongPollingTransport, HANDSHAKE_REQUEST as MSGPACK_HANDSHAKE_REQUEST, type MessageHeaders, MessageType, type MessageTypeValue, MsgpackHubProtocol, NEGOTIATE_VERSION, type NegotiateResponse, NullLogger, type PingMessage, PipelineHttpClient, RECORD_SEPARATOR, RequestHttpClient, type RequestOptions, type RetryContext, ServerSentEventsTransport, StreamHttpClient, type StreamInvocationMessage, type StreamItemMessage, type StreamResult, TransferFormat, TransportError, UnsupportedTransportError, type UrlOptions, WebSocketClient, WebSocketReadyState, WebSocketTransport, assertNever, isAbortError, isCancelInvocationMessage, isCloseMessage, isCompletionMessage, isHubError, isInvocationMessage, isPingMessage, isStreamInvocationMessage, isStreamItemMessage, isTransportError, parseHandshakeResponse, toInvocationId };
891
+ #private;
892
+ get readyState(): WebSocketReadyState;
893
+ /**
894
+ * Open a WebSocket connection.
895
+ * @param url ws:// or wss:// URL
896
+ * @param headers Extra HTTP headers for the upgrade request
897
+ */
898
+ connect(url: string, headers?: Record<string, string>): Promise<void>;
899
+ /**
900
+ * Send a text or binary message.
901
+ * @throws if the socket is not open.
902
+ */
903
+ send(data: string | Buffer | Uint8Array): void;
904
+ /**
905
+ * Initiate a clean close handshake.
906
+ * @param code WebSocket close code (default 1000 = Normal Closure)
907
+ * @param reason UTF-8 reason string (max 123 bytes)
908
+ */
909
+ close(code?: number, reason?: string): void;
910
+ }
911
+ //#endregion
912
+ export { AbortError, type AvailableTransport, type CancelInvocationMessage, type CloseMessage, type CompletionMessage, ConsoleLogger, CookieAgent, CookieJar, DEFAULT_PING_INTERVAL_IN_MS, DEFAULT_SERVER_TIMEOUT_IN_MS, DEFAULT_TIMEOUT_IN_MS, DefaultReconnectPolicy, DispatchHttpClient, DispatchHttpClient as HttpClient, type Dispatcher, FetchHttpClient, HANDSHAKE_REQUEST, HandshakeError, type HandshakeParseResult, type HandshakeResponse, type HttpClientOptions, type HttpMethod, type HttpResponse, HttpTransportType, HubConnection, HubConnectionBuilder, type HubConnectionOptions, HubConnectionState, HubError, type HubMessage, type IHttpClient, type IHubProtocol, type ILogger, type IRetryPolicy, type IStreamResult, type IStreamSubscriber, type ISubscription, type ITransport, type InvocationId, type InvocationMessage, JsonHubProtocol, LogLevel, LongPollingTransport, HANDSHAKE_REQUEST$1 as MSGPACK_HANDSHAKE_REQUEST, type MessageHeaders, MessageType, type MessageTypeValue, MsgpackHubProtocol, NEGOTIATE_VERSION, type NegotiateResponse, NullLogger, type PingMessage, PipelineHttpClient, RECORD_SEPARATOR, RequestHttpClient, type RequestOptions, type RetryContext, ServerSentEventsTransport, StreamHttpClient, type StreamInvocationMessage, type StreamItemMessage, type StreamResult, TransferFormat, TransportError, UnsupportedTransportError, type UrlOptions, WebSocketClient, WebSocketReadyState, WebSocketTransport, assertNever, cookie, isAbortError, isCancelInvocationMessage, isCloseMessage, isCompletionMessage, isHubError, isInvocationMessage, isPingMessage, isStreamInvocationMessage, isStreamItemMessage, isTransportError, parseHandshakeResponse, toInvocationId };
913
+ //# sourceMappingURL=index.d.cts.map