@maxtroost/use-websocket 1.0.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +224 -237
- package/dist/index.d.ts +319 -46
- package/dist/index.js +236 -221
- package/dist/index.js.map +1 -1
- package/package.json +9 -8
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,24 @@
|
|
|
1
|
+
import { FunctionComponent } from 'react';
|
|
2
|
+
import { PropsWithChildren } from 'react';
|
|
1
3
|
import { Store } from '@tanstack/react-store';
|
|
2
4
|
import { Store as Store_2 } from '@tanstack/store';
|
|
3
5
|
|
|
4
|
-
/**
|
|
6
|
+
/**
|
|
7
|
+
* Creates the initial state for a {@link WebsocketSubscriptionStore}.
|
|
8
|
+
*
|
|
9
|
+
* @template TData - The type of data in the store's `message` field
|
|
10
|
+
* @returns A new store with default values (message: undefined, subscribed: false, etc.)
|
|
11
|
+
*/
|
|
5
12
|
export declare function createInitialWebsocketSubscriptionStore<TData = unknown>(): WebsocketSubscriptionStore<TData>;
|
|
6
13
|
|
|
14
|
+
/** Heartbeat (ping/pong) configuration */
|
|
15
|
+
export declare interface HeartbeatConfig {
|
|
16
|
+
/** Whether to send ping messages and expect pong responses. Default: true */
|
|
17
|
+
enabled: boolean;
|
|
18
|
+
/** Time in ms to wait for a pong before considering the connection dead. Default: 10000 */
|
|
19
|
+
pongTimeoutMs: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
7
22
|
/**
|
|
8
23
|
* Structure of incoming WebSocket messages.
|
|
9
24
|
*
|
|
@@ -21,6 +36,11 @@ export declare interface IncomingWebsocketMessage<TBody = unknown> {
|
|
|
21
36
|
method?: string;
|
|
22
37
|
}
|
|
23
38
|
|
|
39
|
+
/**
|
|
40
|
+
* Type definitions for the WebSocket connection system.
|
|
41
|
+
*
|
|
42
|
+
* @module types
|
|
43
|
+
*/
|
|
24
44
|
/**
|
|
25
45
|
* WebSocket connection ready states.
|
|
26
46
|
*
|
|
@@ -43,6 +63,62 @@ declare enum ReadyState_2 {
|
|
|
43
63
|
}
|
|
44
64
|
export { ReadyState_2 as ReadyState }
|
|
45
65
|
|
|
66
|
+
/**
|
|
67
|
+
* Configuration for WebSocket reconnection behavior with exponential backoff.
|
|
68
|
+
*
|
|
69
|
+
* The reconnection strategy uses three phases:
|
|
70
|
+
* - First phase (attempts 0-4): 4 second delay
|
|
71
|
+
* - Second phase (attempts 5-9): 30 second delay
|
|
72
|
+
* - Third phase (attempts 10+): 90 second delay
|
|
73
|
+
*
|
|
74
|
+
* User notifications are only shown after the notification threshold is exceeded
|
|
75
|
+
* to avoid spamming users during brief network interruptions.
|
|
76
|
+
*
|
|
77
|
+
* After MAX_RETRY_ATTEMPTS, reconnection stops to avoid infinite retries on dead
|
|
78
|
+
* endpoints (e.g. ~10 attempts ≈ 12 minutes); the user can manually retry via the
|
|
79
|
+
* notification action.
|
|
80
|
+
*/
|
|
81
|
+
declare const RECONNECTION_CONFIG: {
|
|
82
|
+
/**
|
|
83
|
+
* Maximum number of reconnection attempts before stopping and showing a permanent
|
|
84
|
+
* error. Prevents infinite retries on dead endpoints (CPU wake-ups, battery drain).
|
|
85
|
+
* ~10 attempts ≈ 12 minutes at phase 3 (90s interval). User can retry manually.
|
|
86
|
+
*/
|
|
87
|
+
readonly MAX_RETRY_ATTEMPTS: 20;
|
|
88
|
+
/**
|
|
89
|
+
* Number of failed reconnection attempts before showing user notifications.
|
|
90
|
+
* Prevents notification spam during brief network interruptions.
|
|
91
|
+
*/
|
|
92
|
+
readonly NOTIFICATION_THRESHOLD: 10;
|
|
93
|
+
/**
|
|
94
|
+
* Initial delay (in ms) when server closes with 1013 Try Again Later.
|
|
95
|
+
* The server explicitly asks to wait before reconnecting.
|
|
96
|
+
*/
|
|
97
|
+
readonly TRY_AGAIN_LATER_DELAY_MS: 30000;
|
|
98
|
+
/**
|
|
99
|
+
* Delay durations (in milliseconds) for each reconnection phase.
|
|
100
|
+
*/
|
|
101
|
+
readonly DELAYS: {
|
|
102
|
+
/** First phase delay: 4 seconds for the first 5 attempts */
|
|
103
|
+
readonly FIRST_PHASE: 4000;
|
|
104
|
+
/** Second phase delay: 30 seconds for attempts 6-10 */
|
|
105
|
+
readonly SECOND_PHASE: 30000;
|
|
106
|
+
/** Third phase delay: 90 seconds for attempts 11+ */
|
|
107
|
+
readonly THIRD_PHASE: 90000;
|
|
108
|
+
};
|
|
109
|
+
/**
|
|
110
|
+
* Threshold values that determine when to transition between reconnection phases.
|
|
111
|
+
*/
|
|
112
|
+
readonly PHASE_THRESHOLDS: {
|
|
113
|
+
/** Maximum attempts in the first phase (0-4) */
|
|
114
|
+
readonly FIRST: 5;
|
|
115
|
+
/** Maximum attempts in the second phase (5-9) */
|
|
116
|
+
readonly SECOND: 10;
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
export declare type ReconnectionConfig = typeof RECONNECTION_CONFIG;
|
|
121
|
+
|
|
46
122
|
/**
|
|
47
123
|
* Structure for outgoing WebSocket messages.
|
|
48
124
|
*
|
|
@@ -60,8 +136,6 @@ export declare interface SendMessage<TMethod = string, TUri = string, TBody = un
|
|
|
60
136
|
uri?: TUri;
|
|
61
137
|
/** Optional message body/payload */
|
|
62
138
|
body?: TBody;
|
|
63
|
-
/** Correlation ID for tracking messages (automatically generated) */
|
|
64
|
-
correlation?: string;
|
|
65
139
|
}
|
|
66
140
|
|
|
67
141
|
/**
|
|
@@ -81,6 +155,22 @@ export declare interface SendMessageOptions {
|
|
|
81
155
|
*/
|
|
82
156
|
export declare type SendToConnectionFn = (message: SendMessage<string, string, unknown>) => void;
|
|
83
157
|
|
|
158
|
+
/**
|
|
159
|
+
* Returns the {@link WebsocketClient} from the nearest {@link WebsocketClientProvider}.
|
|
160
|
+
*
|
|
161
|
+
* Must be used within a `WebsocketClientProvider`; throws otherwise.
|
|
162
|
+
*
|
|
163
|
+
* @returns The WebsocketClient instance
|
|
164
|
+
* @throws Error if used outside WebsocketClientProvider
|
|
165
|
+
*
|
|
166
|
+
* @example
|
|
167
|
+
* ```typescript
|
|
168
|
+
* const client = useWebsocketClient();
|
|
169
|
+
* const api = useWebsocketSubscription({ key: 'my-sub', url: '...', uri: '...' });
|
|
170
|
+
* ```
|
|
171
|
+
*/
|
|
172
|
+
export declare const useWebsocketClient: () => WebsocketClient;
|
|
173
|
+
|
|
84
174
|
/**
|
|
85
175
|
* React hook that manages a WebSocket Message API for request/response style messaging.
|
|
86
176
|
*
|
|
@@ -102,7 +192,7 @@ export declare type SendToConnectionFn = (message: SendMessage<string, string, u
|
|
|
102
192
|
* - `url`: The WebSocket URL
|
|
103
193
|
* - `key`: Unique identifier (components with same key share the API)
|
|
104
194
|
* - `enabled`: Whether this API is enabled (default: true)
|
|
105
|
-
* - `responseTimeoutMs`: Default timeout for `sendMessage` (default:
|
|
195
|
+
* - `responseTimeoutMs`: Default timeout for `sendMessage` (default: 10000)
|
|
106
196
|
* - `onError`, `onMessageError`, `onClose`: Optional callbacks
|
|
107
197
|
* @returns {@link WebsocketMessageApiPublic} with `sendMessage`, `sendMessageNoWait`, `reset`, `url`, `key`, `isEnabled`
|
|
108
198
|
*
|
|
@@ -111,7 +201,7 @@ export declare type SendToConnectionFn = (message: SendMessage<string, string, u
|
|
|
111
201
|
* const api = useWebsocketMessage<ModifyVoyageUim, ModifyVoyageUim>({
|
|
112
202
|
* key: 'voyages/modify',
|
|
113
203
|
* url: '/api',
|
|
114
|
-
* responseTimeoutMs:
|
|
204
|
+
* responseTimeoutMs: 10000
|
|
115
205
|
* });
|
|
116
206
|
*
|
|
117
207
|
* // Await response (full form: uri, method, body?, options?)
|
|
@@ -146,7 +236,7 @@ export declare const useWebsocketMessage: (options: WebsocketMessageOptions) =>
|
|
|
146
236
|
* - Manages the underlying WebSocket connection lifecycle
|
|
147
237
|
* - Handles reconnection, heartbeat, and connection state
|
|
148
238
|
* - Routes incoming messages to the appropriate Subscription handlers
|
|
149
|
-
* - Retrieved via `
|
|
239
|
+
* - Retrieved via `WebsocketClient.addConnection()` which ensures only one
|
|
150
240
|
* connection exists per WebSocket URL
|
|
151
241
|
*
|
|
152
242
|
* 2. **WebsocketSubscriptionApi** (one per subscription per connection)
|
|
@@ -166,7 +256,7 @@ export declare const useWebsocketMessage: (options: WebsocketMessageOptions) =>
|
|
|
166
256
|
* │ ├─→ Provides reactive store for data updates
|
|
167
257
|
* │ └─→ Handles subscribe/unsubscribe lifecycle
|
|
168
258
|
* │
|
|
169
|
-
* └─→
|
|
259
|
+
* └─→ client.addConnection(url, url)
|
|
170
260
|
* └─→ Returns/creates WebsocketConnection singleton (per URL)
|
|
171
261
|
* ├─→ Manages WebSocket connection (connect, reconnect, heartbeat)
|
|
172
262
|
* ├─→ Routes messages to registered listeners
|
|
@@ -263,6 +353,169 @@ export declare function useWebsocketSubscription<TData = unknown, TBody = unknow
|
|
|
263
353
|
*/
|
|
264
354
|
export declare const useWebsocketSubscriptionByKey: <TData = unknown>(key: string) => Store_2<WebsocketSubscriptionStore<TData>>;
|
|
265
355
|
|
|
356
|
+
/**
|
|
357
|
+
* Global WebSocket configuration used by all WebsocketConnection instances.
|
|
358
|
+
*
|
|
359
|
+
* Instantiate with {@link WebsocketClientOverrides} to customize behavior.
|
|
360
|
+
* All overrides are merged with defaults; partial overrides are supported.
|
|
361
|
+
*
|
|
362
|
+
* @example
|
|
363
|
+
* ```typescript
|
|
364
|
+
* const client = new WebsocketClient({
|
|
365
|
+
* maxRetryAttempts: 10,
|
|
366
|
+
* heartbeat: { enabled: false },
|
|
367
|
+
* messageResponseTimeoutMs: 5000
|
|
368
|
+
* });
|
|
369
|
+
* ```
|
|
370
|
+
*/
|
|
371
|
+
export declare class WebsocketClient {
|
|
372
|
+
/**
|
|
373
|
+
* Global map of active WebSocket connections, keyed by URL.
|
|
374
|
+
*
|
|
375
|
+
* One connection per key. Managed by {@link addConnection} and {@link removeConnection}.
|
|
376
|
+
*/
|
|
377
|
+
private _connections;
|
|
378
|
+
/**
|
|
379
|
+
* Global map of active WebSocket listeners (subscription and message APIs), keyed by API key.
|
|
380
|
+
*
|
|
381
|
+
* One listener per key. Subscription APIs have `uri`; message APIs have `hasWaitingUri`.
|
|
382
|
+
* Managed by {@link createWebsocketSubscriptionApi}, {@link createWebsocketMessageApi},
|
|
383
|
+
* and {@link removeWebsocketListenerFromConnection}.
|
|
384
|
+
*/
|
|
385
|
+
private _listeners;
|
|
386
|
+
/** Maximum reconnection attempts before stopping. */
|
|
387
|
+
maxRetryAttempts: number;
|
|
388
|
+
/** Attempts before showing user notifications. */
|
|
389
|
+
notificationThreshold: number;
|
|
390
|
+
/** Delay (ms) when server closes with 1013 Try Again Later. */
|
|
391
|
+
tryAgainLaterDelayMs: number;
|
|
392
|
+
/** Delay durations (ms) for each reconnection phase. */
|
|
393
|
+
delays: {
|
|
394
|
+
firstPhase: number;
|
|
395
|
+
secondPhase: number;
|
|
396
|
+
thirdPhase: number;
|
|
397
|
+
};
|
|
398
|
+
phaseThresholds: {
|
|
399
|
+
first: number;
|
|
400
|
+
second: number;
|
|
401
|
+
};
|
|
402
|
+
/** Delay (ms) before closing connection when no listeners remain. */
|
|
403
|
+
connectionCleanupDelayMs: number;
|
|
404
|
+
/** Default timeout (ms) for message API responses. */
|
|
405
|
+
messageResponseTimeoutMs: number;
|
|
406
|
+
/** Heartbeat (ping/pong) configuration. */
|
|
407
|
+
heartbeat: HeartbeatConfig;
|
|
408
|
+
/** Optional transform for outgoing message payloads. */
|
|
409
|
+
transformMessagePayload: ((payload: SendMessage<string, string, unknown>) => SendMessage<string, string, unknown>) | undefined;
|
|
410
|
+
/** Optional callback for connection event logging. */
|
|
411
|
+
connectionEvent: ((event: WebsocketLoggerConnectionEvent) => void) | undefined;
|
|
412
|
+
/**
|
|
413
|
+
* Creates a new WebsocketClient with optional overrides.
|
|
414
|
+
*
|
|
415
|
+
* All overrides are merged with defaults from {@link RECONNECTION_CONFIG},
|
|
416
|
+
* {@link CONNECTION_CLEANUP_DELAY_MS}, and {@link DEFAULT_HEARTBEAT_CONFIG}.
|
|
417
|
+
*
|
|
418
|
+
* @param overrides - Partial configuration overrides. Omitted values use defaults.
|
|
419
|
+
*/
|
|
420
|
+
constructor({ maxRetryAttempts, notificationThreshold, tryAgainLaterDelayMs, delays, phaseThresholds, connectionCleanupDelayMs, messageResponseTimeoutMs, heartbeat, transformMessagePayload, connectionEvent }: WebsocketClientOverrides);
|
|
421
|
+
/** Reconnects all active WebSocket connections. Use after auth/region change. */
|
|
422
|
+
reconnectAllConnections: () => void;
|
|
423
|
+
/** Registers a listener (subscription or message API) in the client. */
|
|
424
|
+
addListener: (listener: WebsocketListener) => void;
|
|
425
|
+
/** Unregisters a listener from the client. */
|
|
426
|
+
removeListener: (listener: WebsocketListener) => void;
|
|
427
|
+
/**
|
|
428
|
+
* Returns a listener by key and type.
|
|
429
|
+
*
|
|
430
|
+
* @param key - The listener's unique key
|
|
431
|
+
* @param type - `'subscription'` or `'message'`
|
|
432
|
+
* @returns The listener if found, otherwise undefined
|
|
433
|
+
*/
|
|
434
|
+
getListener<TData = unknown, TBody = unknown>(key: string, type: 'subscription'): WebsocketSubscriptionApi<TData, TBody> | undefined;
|
|
435
|
+
getListener(key: string, type: 'message'): WebsocketMessageApi | undefined;
|
|
436
|
+
/** Returns the WebSocket connection for the given URL key, or undefined. */
|
|
437
|
+
getConnection: (key: string) => WebsocketConnection | undefined;
|
|
438
|
+
/**
|
|
439
|
+
* Adds or returns an existing WebSocket connection for the given URL.
|
|
440
|
+
*
|
|
441
|
+
* @param key - The key used to identify the connection (typically the URL)
|
|
442
|
+
* @param url - The WebSocket URL to connect to
|
|
443
|
+
* @returns The existing or newly created connection
|
|
444
|
+
*/
|
|
445
|
+
addConnection: (key: string, url: string) => WebsocketConnection;
|
|
446
|
+
/**
|
|
447
|
+
* Removes a connection from the client.
|
|
448
|
+
*
|
|
449
|
+
* @param url - The WebSocket URL used as the key when calling {@link addConnection}.
|
|
450
|
+
*/
|
|
451
|
+
removeConnection: (url: string) => void;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** Overrides for the global WebSocket configuration. All fields are optional. */
|
|
455
|
+
export declare interface WebsocketClientOverrides {
|
|
456
|
+
/** Maximum number of reconnection attempts before stopping and showing a permanent error. Prevents infinite retries on dead endpoints (CPU wake-ups, battery drain). ~10 attempts ≈ 12 minutes at phase 3 (90s interval). User can retry manually. */
|
|
457
|
+
maxRetryAttempts?: number;
|
|
458
|
+
/** Number of failed reconnection attempts before showing user notifications. Prevents notification spam during brief network interruptions. */
|
|
459
|
+
notificationThreshold?: number;
|
|
460
|
+
/** Initial delay (in ms) when server closes with 1013 Try Again Later. The server explicitly asks to wait before reconnecting. */
|
|
461
|
+
tryAgainLaterDelayMs?: number;
|
|
462
|
+
/** Delay durations (in milliseconds) for each reconnection phase. */
|
|
463
|
+
delays?: {
|
|
464
|
+
firstPhase?: number;
|
|
465
|
+
secondPhase?: number;
|
|
466
|
+
thirdPhase?: number;
|
|
467
|
+
};
|
|
468
|
+
/** Threshold values that determine when to transition between reconnection phases. */
|
|
469
|
+
phaseThresholds?: {
|
|
470
|
+
first?: number;
|
|
471
|
+
second?: number;
|
|
472
|
+
};
|
|
473
|
+
/** Override connection cleanup delay when no listeners remain */
|
|
474
|
+
connectionCleanupDelayMs?: number;
|
|
475
|
+
/** Default timeout in ms when waiting for a message response. Used by WebsocketMessageApi */
|
|
476
|
+
messageResponseTimeoutMs?: number;
|
|
477
|
+
/** Override ping/pong heartbeat behavior */
|
|
478
|
+
heartbeat?: Partial<HeartbeatConfig>;
|
|
479
|
+
transformMessagePayload?: (payload: SendMessage<string, string, unknown>) => SendMessage<string, string, unknown>;
|
|
480
|
+
/**
|
|
481
|
+
* Callback for connection event logging. Receives events such as:
|
|
482
|
+
* - `{ type: 'open' | 'connect', url, retries, uriApis }`
|
|
483
|
+
* - `{ type: 'close', url, code, reason, wasClean, subscriptions }`
|
|
484
|
+
* - `{ type: 'reconnecting' | 'max-retries-exceeded', url, retries }`
|
|
485
|
+
* - `{ type: 'message-error', url, uri, uriApis, message }`
|
|
486
|
+
* - `{ type: 'invalid-message', url, uriApis, message }`
|
|
487
|
+
* - `{ type: 'parse-error', url, uriApis, message, error }`
|
|
488
|
+
* - `{ type: 'send-message', url, uri?, body, method? }`
|
|
489
|
+
* - `{ type: 'cleanup', url }`
|
|
490
|
+
* - `{ type: 'pong-timeout', url }`
|
|
491
|
+
*
|
|
492
|
+
* @param event - The connection event
|
|
493
|
+
*/
|
|
494
|
+
connectionEvent?: (event: WebsocketLoggerConnectionEvent) => void;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* Provides a {@link WebsocketClient} to the component tree.
|
|
499
|
+
*
|
|
500
|
+
* Wrap your app (or the part that uses WebSocket hooks) with this provider.
|
|
501
|
+
* Create the client once (e.g. at app startup) and pass it here.
|
|
502
|
+
*
|
|
503
|
+
* @example
|
|
504
|
+
* ```typescript
|
|
505
|
+
* const client = new WebsocketClient({ maxRetryAttempts: 10 });
|
|
506
|
+
* <WebsocketClientProvider client={client}>
|
|
507
|
+
* <App />
|
|
508
|
+
* </WebsocketClientProvider>
|
|
509
|
+
* ```
|
|
510
|
+
*/
|
|
511
|
+
export declare const WebsocketClientProvider: FunctionComponent<PropsWithChildren<WebsocketClientProviderProps>>;
|
|
512
|
+
|
|
513
|
+
/** Props for {@link WebsocketClientProvider}. */
|
|
514
|
+
declare interface WebsocketClientProviderProps {
|
|
515
|
+
/** The WebsocketClient instance to provide to descendants. */
|
|
516
|
+
client: WebsocketClient;
|
|
517
|
+
}
|
|
518
|
+
|
|
266
519
|
/**
|
|
267
520
|
* Manages a WebSocket connection with automatic reconnection, heartbeat monitoring, and URI-based message routing.
|
|
268
521
|
*
|
|
@@ -271,7 +524,7 @@ export declare const useWebsocketSubscriptionByKey: <TData = unknown>(key: strin
|
|
|
271
524
|
* - Heartbeat/ping mechanism to keep connections alive
|
|
272
525
|
* - Multiple URI API registration for routing messages to different handlers
|
|
273
526
|
* - Online/offline detection and handling
|
|
274
|
-
* - Custom logger support for monitoring (configure via {@link
|
|
527
|
+
* - Custom logger support for monitoring (configure via {@link WebsocketClient} connectionEvent)
|
|
275
528
|
* - User notifications for connection status
|
|
276
529
|
*
|
|
277
530
|
* @example
|
|
@@ -288,26 +541,15 @@ export declare const useWebsocketSubscriptionByKey: <TData = unknown>(key: strin
|
|
|
288
541
|
* connection.addListener(uriApi);
|
|
289
542
|
* ```
|
|
290
543
|
*
|
|
291
|
-
* @see {@link
|
|
292
|
-
* @see {@link setCustomLogger} - Configure logging and connection-failed callback
|
|
544
|
+
* @see {@link WebsocketClient.reconnectAllConnections} - Reconnect all connections (e.g. on auth change)
|
|
293
545
|
*/
|
|
294
546
|
export declare class WebsocketConnection {
|
|
295
|
-
/** Custom logger instance. Use {@link setCustomLogger} to configure. */
|
|
296
|
-
private static _logger;
|
|
297
|
-
/**
|
|
298
|
-
* Sets a custom logger for WebSocket connection events.
|
|
299
|
-
*
|
|
300
|
-
* @param logger - Logger implementation, or `undefined` to clear
|
|
301
|
-
*/
|
|
302
|
-
static setCustomLogger(logger: WebsocketLogger | undefined): void;
|
|
303
547
|
/** The underlying WebSocket instance */
|
|
304
548
|
private _socket?;
|
|
305
549
|
/** Map of all listeners (subscription and message APIs) keyed by their unique key */
|
|
306
550
|
private _listeners;
|
|
307
551
|
/** The WebSocket URL */
|
|
308
552
|
private _url;
|
|
309
|
-
/** Display name extracted from URL pathname for user notifications */
|
|
310
|
-
private _name;
|
|
311
553
|
/** Timeout for the next ping message */
|
|
312
554
|
private pingTimeOut;
|
|
313
555
|
/** Timeout for detecting missing pong after ping (dead-connection detection) */
|
|
@@ -325,13 +567,17 @@ export declare class WebsocketConnection {
|
|
|
325
567
|
* Flushed when the connection opens. Subscribe messages are NOT cached — they trigger connect only.
|
|
326
568
|
*/
|
|
327
569
|
private cachedMessages;
|
|
570
|
+
/** The WebsocketClient instance */
|
|
571
|
+
private _client;
|
|
328
572
|
/**
|
|
329
573
|
* Creates a new WebSocket connection instance.
|
|
330
|
-
*
|
|
574
|
+
*
|
|
575
|
+
* The connection is not established until a listener is added via {@link addListener}.
|
|
331
576
|
*
|
|
332
577
|
* @param url - The WebSocket URL to connect to
|
|
578
|
+
* @param client - The {@link WebsocketClient} for configuration (reconnection, heartbeat, etc.)
|
|
333
579
|
*/
|
|
334
|
-
constructor(url: string);
|
|
580
|
+
constructor(url: string, client: WebsocketClient);
|
|
335
581
|
/**
|
|
336
582
|
* Gets the current ready state of the WebSocket connection.
|
|
337
583
|
*
|
|
@@ -351,18 +597,6 @@ export declare class WebsocketConnection {
|
|
|
351
597
|
* @returns The WebSocket instance if connected, or undefined if the connection hasn't been established yet or has been closed.
|
|
352
598
|
*/
|
|
353
599
|
getSocket: () => WebSocket | undefined;
|
|
354
|
-
/**
|
|
355
|
-
* Retrieves a registered subscription API by its unique key.
|
|
356
|
-
* Message APIs are not returned; use {@link getWebsocketMessageApiByKey} for those.
|
|
357
|
-
*
|
|
358
|
-
* @template TData - The type of data stored in the subscription store
|
|
359
|
-
* @param key - The unique key identifying the subscription (must match the key used in {@link addListener})
|
|
360
|
-
* @returns The {@link WebsocketSubscriptionApi} instance if found, or `undefined`
|
|
361
|
-
*
|
|
362
|
-
* @see {@link addListener} - Method to register a listener
|
|
363
|
-
* @see {@link getWebsocketUriApiByKey} - Global function to search across all connections
|
|
364
|
-
*/
|
|
365
|
-
getUriApiByKey: <TData = unknown>(key: string) => WebsocketSubscriptionApi<TData, any> | undefined;
|
|
366
600
|
/**
|
|
367
601
|
* Registers a listener (subscription or message API) with this connection.
|
|
368
602
|
*
|
|
@@ -379,13 +613,13 @@ export declare class WebsocketConnection {
|
|
|
379
613
|
* Unregisters a listener and schedules connection cleanup if no listeners remain.
|
|
380
614
|
*
|
|
381
615
|
* Disconnects the listener's send callback and removes it from the routing map.
|
|
382
|
-
* The WebSocket connection will be closed after {@link
|
|
616
|
+
* The WebSocket connection will be closed after {@link CONNECTION_CLEANUP_DELAY_MS} if no other
|
|
383
617
|
* listeners are registered.
|
|
384
618
|
*
|
|
385
619
|
* @param listener - The listener instance to unregister
|
|
386
620
|
*/
|
|
387
621
|
removeListener: (listener: WebsocketListener) => void;
|
|
388
|
-
/** Schedules connection close after
|
|
622
|
+
/** Schedules connection close after configured delay when no listeners remain. */
|
|
389
623
|
private scheduleConnectionCleanup;
|
|
390
624
|
/**
|
|
391
625
|
* Replaces the WebSocket URL and re-establishes the connection.
|
|
@@ -456,7 +690,7 @@ export declare class WebsocketConnection {
|
|
|
456
690
|
* Shows user notifications after the threshold number of attempts.
|
|
457
691
|
* Only attempts reconnection when the browser is online.
|
|
458
692
|
* When closeCode is 1013 (Try Again Later), waits an extra delay before reconnecting.
|
|
459
|
-
* Stops after
|
|
693
|
+
* Stops after configured MAX_RETRY_ATTEMPTS and shows a permanent error with a manual retry button.
|
|
460
694
|
*
|
|
461
695
|
* @param closeCode - Optional WebSocket close code; used to apply TRY_AGAIN_LATER delay when 1013
|
|
462
696
|
*/
|
|
@@ -547,7 +781,7 @@ export declare class WebsocketConnection {
|
|
|
547
781
|
private clearPongTimeout;
|
|
548
782
|
/**
|
|
549
783
|
* Schedules a timeout to detect missing pong. If no pong arrives within
|
|
550
|
-
*
|
|
784
|
+
* configured pong timeout, force-closes the socket to trigger reconnection.
|
|
551
785
|
*/
|
|
552
786
|
private schedulePongTimeout;
|
|
553
787
|
/**
|
|
@@ -576,8 +810,6 @@ export declare class WebsocketConnection {
|
|
|
576
810
|
private forEachMatchingListener;
|
|
577
811
|
}
|
|
578
812
|
|
|
579
|
-
export declare const websocketConnectionsReconnect: () => void;
|
|
580
|
-
|
|
581
813
|
/**
|
|
582
814
|
* Common interface for WebSocket listeners registered with {@link WebsocketConnection}.
|
|
583
815
|
*
|
|
@@ -606,19 +838,44 @@ export declare interface WebsocketListener {
|
|
|
606
838
|
hasWaitingUri?(uri: string): boolean;
|
|
607
839
|
/** Message listeners: delivers a response for a pending request */
|
|
608
840
|
deliverMessage?(uri: string, data: unknown): void;
|
|
841
|
+
readonly type: 'subscription' | 'message';
|
|
609
842
|
}
|
|
610
843
|
|
|
611
844
|
/**
|
|
612
845
|
* Optional custom logger for WebSocket connection events.
|
|
613
|
-
* Set via {@link
|
|
846
|
+
* Set via {@link WebsocketConfig.setCustomLogger}.
|
|
614
847
|
*/
|
|
615
848
|
export declare interface WebsocketLogger {
|
|
616
849
|
/** Logs connection events (e.g. ws-connect, ws-close, ws-error, ws-reconnect) */
|
|
617
|
-
log?(level: 'debug' | 'info' | 'warn' | 'error', message: string, context?: Record<string, unknown>): void;
|
|
618
850
|
/** Called when max retry attempts exceeded; use to trigger token refresh or other recovery */
|
|
619
|
-
|
|
851
|
+
connectionEvents?: (event: WebsocketLoggerConnectionEvent) => void;
|
|
620
852
|
}
|
|
621
853
|
|
|
854
|
+
/* Excluded from this release type: WebsocketLoggerCleanupEvent */
|
|
855
|
+
|
|
856
|
+
/* Excluded from this release type: WebsocketLoggerCloseEvent */
|
|
857
|
+
|
|
858
|
+
/** Union of all connection event types passed to {@link WebsocketClientOverrides.connectionEvent}. */
|
|
859
|
+
export declare type WebsocketLoggerConnectionEvent = WebsocketLoggerCloseEvent | WebsocketLoggerOpenEvent | WebsocketLoggerMessageEvent | WebsocketLoggerErrorEvent | WebsocketLoggerReconnectingEvent | WebsocketLoggerPongTimeoutEvent | WebsocketLoggerInvalidMessageEvent | WebsocketLoggerMessageErrorEvent | WebsocketLoggerParseErrorEvent | WebsocketLoggerSendMessageEvent | WebsocketLoggerCleanupEvent;
|
|
860
|
+
|
|
861
|
+
/* Excluded from this release type: WebsocketLoggerErrorEvent */
|
|
862
|
+
|
|
863
|
+
/* Excluded from this release type: WebsocketLoggerInvalidMessageEvent */
|
|
864
|
+
|
|
865
|
+
/* Excluded from this release type: WebsocketLoggerMessageErrorEvent */
|
|
866
|
+
|
|
867
|
+
/* Excluded from this release type: WebsocketLoggerMessageEvent */
|
|
868
|
+
|
|
869
|
+
/* Excluded from this release type: WebsocketLoggerOpenEvent */
|
|
870
|
+
|
|
871
|
+
/* Excluded from this release type: WebsocketLoggerParseErrorEvent */
|
|
872
|
+
|
|
873
|
+
/* Excluded from this release type: WebsocketLoggerPongTimeoutEvent */
|
|
874
|
+
|
|
875
|
+
/* Excluded from this release type: WebsocketLoggerReconnectingEvent */
|
|
876
|
+
|
|
877
|
+
/* Excluded from this release type: WebsocketLoggerSendMessageEvent */
|
|
878
|
+
|
|
622
879
|
/**
|
|
623
880
|
* Manages WebSocket request/response messaging without subscription.
|
|
624
881
|
*
|
|
@@ -669,9 +926,18 @@ export declare class WebsocketMessageApi implements WebsocketListener {
|
|
|
669
926
|
private _pendingMessages;
|
|
670
927
|
private _registeredHooks;
|
|
671
928
|
private _hookRemovalTimeout;
|
|
672
|
-
|
|
929
|
+
private _client;
|
|
930
|
+
readonly type = "message";
|
|
931
|
+
/**
|
|
932
|
+
* Creates a new WebsocketMessageApi.
|
|
933
|
+
*
|
|
934
|
+
* @param options - Configuration options (url, key, callbacks, etc.)
|
|
935
|
+
* @param client - The {@link WebsocketClient} for timeout defaults and connection management
|
|
936
|
+
*/
|
|
937
|
+
constructor(options: WebsocketMessageOptions, client: WebsocketClient);
|
|
673
938
|
/** Unique key identifier for this Message API. */
|
|
674
939
|
get key(): string;
|
|
940
|
+
/** WebSocket URL for Datadog tracking. */
|
|
675
941
|
get url(): string;
|
|
676
942
|
/** Whether this Message API is enabled. */
|
|
677
943
|
get isEnabled(): boolean;
|
|
@@ -889,11 +1155,18 @@ export declare class WebsocketSubscriptionApi<TData = unknown, TBody = unknown>
|
|
|
889
1155
|
private _hookRemovalTimeout;
|
|
890
1156
|
private _sendToConnection;
|
|
891
1157
|
private _pendingMessages;
|
|
1158
|
+
readonly type = "subscription";
|
|
1159
|
+
/**
|
|
1160
|
+
* Creates a new WebsocketSubscriptionApi.
|
|
1161
|
+
*
|
|
1162
|
+
* @param options - Configuration options (url, uri, key, callbacks, etc.)
|
|
1163
|
+
*/
|
|
892
1164
|
constructor(options: WebsocketSubscriptionOptions<TData, TBody>);
|
|
893
1165
|
/** Unique key identifier for this WebSocket URI API. */
|
|
894
1166
|
get key(): string;
|
|
895
1167
|
/** URI path for this WebSocket subscription. */
|
|
896
1168
|
get uri(): string;
|
|
1169
|
+
/** WebSocket URL for Datadog tracking. */
|
|
897
1170
|
get url(): string;
|
|
898
1171
|
/** Configuration options for this WebSocket URI. */
|
|
899
1172
|
get options(): WebsocketSubscriptionOptions<TData, TBody>;
|
|
@@ -1078,9 +1351,9 @@ export declare interface WebsocketSubscriptionOptions<TData = unknown, TBody = u
|
|
|
1078
1351
|
*/
|
|
1079
1352
|
onError?: (error: WebsocketTransportError) => void;
|
|
1080
1353
|
/**
|
|
1081
|
-
*
|
|
1354
|
+
* Callback invoked when a server error message is received for this subscription.
|
|
1082
1355
|
*
|
|
1083
|
-
* @param
|
|
1356
|
+
* @param error - Server error with parsed message body (`error.type === 'server'`, `error.message` contains the incoming message)
|
|
1084
1357
|
*/
|
|
1085
1358
|
onMessageError?: (error: WebsocketServerError<TBody>) => void;
|
|
1086
1359
|
/**
|