@stomp/stompjs 7.1.0 → 7.2.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/esm6/client.d.ts CHANGED
@@ -2,527 +2,892 @@ import { ITransaction } from './i-transaction.js';
2
2
  import { StompConfig } from './stomp-config.js';
3
3
  import { StompHeaders } from './stomp-headers.js';
4
4
  import { StompSubscription } from './stomp-subscription.js';
5
- import { ActivationState, closeEventCallbackType, debugFnType, frameCallbackType, IPublishParams, IStompSocket, messageCallbackType, ReconnectionTimeMode, TickerStrategy, wsErrorCallbackType } from './types.js';
5
+ import { ActivationState, closeEventCallbackType, debugFnType, emptyCallbackType, frameCallbackType, IPublishParams, IStompSocket, messageCallbackType, ReconnectionTimeMode, TickerStrategy, wsErrorCallbackType } from './types.js';
6
6
  import { Versions } from './versions.js';
7
7
  /**
8
8
  * STOMP Client Class.
9
9
  *
10
10
  * Part of `@stomp/stompjs`.
11
+ *
12
+ * This class provides a robust implementation for connecting to and interacting with a
13
+ * STOMP-compliant messaging broker over WebSocket. It supports STOMP versions 1.2, 1.1, and 1.0.
14
+ *
15
+ * Features:
16
+ * - Handles automatic reconnections.
17
+ * - Supports heartbeat mechanisms to detect and report communication failures.
18
+ * - Allows customization of connection and WebSocket behaviors through configurations.
19
+ * - Compatible with both browser environments and Node.js with polyfill support for WebSocket.
11
20
  */
12
21
  export declare class Client {
13
22
  /**
14
23
  * The URL for the STOMP broker to connect to.
15
- * Typically like `"ws://broker.329broker.com:15674/ws"` or `"wss://broker.329broker.com:15674/ws"`.
24
+ * Example: `"ws://broker.domain.com:15674/ws"` or `"wss://broker.domain.com:15674/ws"`.
16
25
  *
17
- * Only one of this or [Client#webSocketFactory]{@link Client#webSocketFactory} need to be set.
18
- * If both are set, [Client#webSocketFactory]{@link Client#webSocketFactory} will be used.
19
- *
20
- * If your environment does not support WebSockets natively, please refer to
21
- * [Polyfills]{@link https://stomp-js.github.io/guide/stompjs/rx-stomp/ng2-stompjs/pollyfils-for-stompjs-v5.html}.
26
+ * Use this property to define the broker's WebSocket endpoint.
27
+ * Note:
28
+ * - Only one of `brokerURL` or [Client#webSocketFactory]{@link Client#webSocketFactory} needs to be set.
29
+ * - If both are provided, [Client#webSocketFactory]{@link Client#webSocketFactory} takes precedence.
30
+ * - When targeting environments without native WebSocket support, refer to
31
+ * [Polyfills]{@link https://stomp-js.github.io/guide/stompjs/rx-stomp/ng2-stompjs/pollyfils-for-stompjs-v5.html}.
22
32
  */
23
33
  brokerURL: string | undefined;
24
34
  /**
25
- * STOMP versions to attempt during STOMP handshake. By default, versions `1.2`, `1.1`, and `1.0` are attempted.
35
+ * STOMP protocol versions to use during the handshake. By default, the client will attempt
36
+ * versions `1.2`, `1.1`, and `1.0` in descending order of preference.
26
37
  *
27
38
  * Example:
28
39
  * ```javascript
29
- * // Try only versions 1.1 and 1.0
30
- * client.stompVersions = new Versions(['1.1', '1.0'])
40
+ * // Configure the client to only use versions 1.1 and 1.0
41
+ * client.stompVersions = new Versions(['1.1', '1.0']);
31
42
  * ```
32
43
  */
33
44
  stompVersions: Versions;
34
45
  /**
35
- * This function should return a WebSocket or a similar (e.g. SockJS) object.
36
- * If your environment does not support WebSockets natively, please refer to
37
- * [Polyfills]{@link https://stomp-js.github.io/guide/stompjs/rx-stomp/ng2-stompjs/pollyfils-for-stompjs-v5.html}.
38
- * If your STOMP Broker supports WebSockets, prefer setting [Client#brokerURL]{@link Client#brokerURL}.
46
+ * A function that returns a WebSocket or a similar object (e.g., SockJS) to establish connections.
39
47
  *
40
- * If both this and [Client#brokerURL]{@link Client#brokerURL} are set, this will be used.
48
+ * This is an alternative to [Client#brokerURL]{@link Client#brokerURL}.
49
+ * Using this allows finer control over WebSocket creation, especially for custom wrappers
50
+ * or when working in non-standard environments.
41
51
  *
42
52
  * Example:
43
53
  * ```javascript
44
- * // use a WebSocket
45
- * client.webSocketFactory= function () {
46
- * return new WebSocket("wss://broker.329broker.com:15674/ws");
47
- * };
48
- *
49
- * // Typical usage with SockJS
50
- * client.webSocketFactory= function () {
51
- * return new SockJS("http://broker.329broker.com/stomp");
52
- * };
54
+ * client.webSocketFactory = function () {
55
+ * return new WebSocket("ws://my-custom-websocket-endpoint");
56
+ * };
57
+ *
58
+ * // Typical usage with SockJS
59
+ * client.webSocketFactory= function () {
60
+ * return new SockJS("http://broker.329broker.com/stomp");
61
+ * };
53
62
  * ```
63
+ *
64
+ * Note:
65
+ * - If both [Client#brokerURL]{@link Client#brokerURL} and this property are set, the factory will be used.
66
+ * - Refer to [Polyfills Guide]{@link https://stomp-js.github.io/guide/stompjs/rx-stomp/ng2-stompjs/pollyfils-for-stompjs-v5.html}
67
+ * when running in environments without native WebSocket support.
54
68
  */
55
69
  webSocketFactory: (() => IStompSocket) | undefined;
56
70
  /**
57
- * Will retry if Stomp connection is not established in specified milliseconds.
58
- * Default 0, which switches off automatic reconnection.
71
+ * Timeout for establishing STOMP connection, in milliseconds.
72
+ *
73
+ * If the connection is not established within this period, the attempt will fail.
74
+ * The default is `0`, meaning no timeout is set for connection attempts.
75
+ *
76
+ * Example:
77
+ * ```javascript
78
+ * client.connectionTimeout = 5000; // Fail connection if not established in 5 seconds
79
+ * ```
59
80
  */
60
81
  connectionTimeout: number;
61
82
  private _connectionWatcher;
62
83
  /**
63
- * automatically reconnect with delay in milliseconds, set to 0 to disable.
84
+ * Delay (in milliseconds) between reconnection attempts if the connection drops.
85
+ *
86
+ * Set to `0` to disable automatic reconnections. The default value is `5000` ms (5 seconds).
87
+ *
88
+ * Example:
89
+ * ```javascript
90
+ * client.reconnectDelay = 3000; // Attempt reconnection every 3 seconds
91
+ * client.reconnectDelay = 0; // Disable automatic reconnection
92
+ * ```
64
93
  */
65
94
  reconnectDelay: number;
66
95
  /**
67
- * tracking the time to the next reconnection. Initialized to [Client#reconnectDelay]{@link Client#reconnectDelay}'s value and it may
68
- * change depending on the [Client#reconnectTimeMode]{@link Client#reconnectTimeMode} setting
96
+ * The next reconnection delay, used internally.
97
+ * Initialized to the value of [Client#reconnectDelay]{@link Client#reconnectDelay}, and it may
98
+ * dynamically change based on [Client#reconnectTimeMode]{@link Client#reconnectTimeMode}.
69
99
  */
70
100
  private _nextReconnectDelay;
71
101
  /**
72
- * Maximum time to wait between reconnects, in milliseconds. Defaults to 15 minutes.
73
- * Only relevant when reconnectTimeMode not LINEAR (e.g. EXPONENTIAL).
74
- * Set to 0 to wait indefinitely.
102
+ * Maximum delay (in milliseconds) between reconnection attempts when using exponential backoff.
103
+ *
104
+ * Default is 15 minutes (`15 * 60 * 1000` milliseconds). If `0`, there will be no upper limit.
105
+ *
106
+ * Example:
107
+ * ```javascript
108
+ * client.maxReconnectDelay = 10000; // Maximum wait time is 10 seconds
109
+ * ```
75
110
  */
76
111
  maxReconnectDelay: number;
77
112
  /**
78
- * Reconnection wait time mode, either linear (default) or exponential.
79
- * Note: See [Client#maxReconnectDelay]{@link Client#maxReconnectDelay} for setting the maximum delay when exponential
113
+ * Mode for determining the time interval between reconnection attempts.
114
+ *
115
+ * Available modes:
116
+ * - `ReconnectionTimeMode.LINEAR` (default): Fixed delays between reconnection attempts.
117
+ * - `ReconnectionTimeMode.EXPONENTIAL`: Delay doubles after each attempt, capped by [maxReconnectDelay]{@link Client#maxReconnectDelay}.
118
+ *
119
+ * Example:
120
+ * ```javascript
121
+ * client.reconnectTimeMode = ReconnectionTimeMode.EXPONENTIAL;
122
+ * client.reconnectDelay = 200; // Initial delay of 200 ms, doubles with each attempt
123
+ * client.maxReconnectDelay = 2 * 60 * 1000; // Cap delay at 10 minutes
124
+ * ```
80
125
  */
81
126
  reconnectTimeMode: ReconnectionTimeMode;
82
127
  /**
83
- * Incoming heartbeat interval in milliseconds. Set to 0 to disable.
128
+ * Interval (in milliseconds) for receiving heartbeat signals from the server.
129
+ *
130
+ * Specifies the expected frequency of heartbeats sent by the server. Set to `0` to disable.
131
+ *
132
+ * Example:
133
+ * ```javascript
134
+ * client.heartbeatIncoming = 10000; // Expect a heartbeat every 10 seconds
135
+ * ```
84
136
  */
85
137
  heartbeatIncoming: number;
86
138
  /**
87
- * Outgoing heartbeat interval in milliseconds. Set to 0 to disable.
139
+ * Multiplier for adjusting tolerance when processing heartbeat signals.
140
+ *
141
+ * Tolerance level is calculated using the multiplier:
142
+ * `tolerance = heartbeatIncoming * heartbeatToleranceMultiplier`.
143
+ * This helps account for delays in network communication or variations in timings.
144
+ *
145
+ * Default value is `2`.
146
+ *
147
+ * Example:
148
+ * ```javascript
149
+ * client.heartbeatToleranceMultiplier = 2.5; // Tolerates longer delays
150
+ * ```
88
151
  */
89
- heartbeatOutgoing: number;
152
+ heartbeatToleranceMultiplier: number;
90
153
  /**
91
- * Outgoing heartbeat strategy.
92
- * See https://github.com/stomp-js/stompjs/pull/579
154
+ * Interval (in milliseconds) for sending heartbeat signals to the server.
93
155
  *
94
- * Can be worker or interval strategy, but will always use `interval`
95
- * if web workers are unavailable, for example, in a non-browser environment.
156
+ * Specifies how frequently heartbeats should be sent to the server. Set to `0` to disable.
96
157
  *
97
- * Using Web Workers may work better on long-running pages
98
- * and mobile apps, as the browser may suspend Timers in the main page.
99
- * Try the `Worker` mode if you discover disconnects when the browser tab is in the background.
158
+ * Example:
159
+ * ```javascript
160
+ * client.heartbeatOutgoing = 5000; // Send a heartbeat every 5 seconds
161
+ * ```
162
+ */
163
+ heartbeatOutgoing: number;
164
+ /**
165
+ * Strategy for sending outgoing heartbeats.
166
+ *
167
+ * Options:
168
+ * - `TickerStrategy.Worker`: Uses Web Workers for sending heartbeats (recommended for long-running or background sessions).
169
+ * - `TickerStrategy.Interval`: Uses standard JavaScript `setInterval` (default).
100
170
  *
101
- * When used in a JS environment, use 'worker' or 'interval' as valid values.
171
+ * Note:
172
+ * - If Web Workers are unavailable (e.g., in Node.js), the `Interval` strategy is used automatically.
173
+ * - Web Workers are preferable in browsers for reducing disconnects when tabs are in the background.
102
174
  *
103
- * Defaults to `interval` strategy.
175
+ * Example:
176
+ * ```javascript
177
+ * client.heartbeatStrategy = TickerStrategy.Worker;
178
+ * ```
104
179
  */
105
180
  heartbeatStrategy: TickerStrategy;
106
181
  /**
107
- * This switches on a non-standard behavior while sending WebSocket packets.
108
- * It splits larger (text) packets into chunks of [maxWebSocketChunkSize]{@link Client#maxWebSocketChunkSize}.
109
- * Only Java Spring brokers seem to support this mode.
182
+ * Enables splitting of large text WebSocket frames into smaller chunks.
110
183
  *
111
- * WebSockets, by itself, split large (text) packets,
112
- * so it is not needed with a truly compliant STOMP/WebSocket broker.
113
- * Setting it for such a broker will cause large messages to fail.
184
+ * This setting is enabled for brokers that support only chunked messages (e.g., Java Spring-based brokers).
185
+ * Default is `false`.
114
186
  *
115
- * `false` by default.
187
+ * Warning:
188
+ * - Should not be used with WebSocket-compliant brokers, as chunking may cause large message failures.
189
+ * - Binary WebSocket frames are never split.
116
190
  *
117
- * Binary frames are never split.
191
+ * Example:
192
+ * ```javascript
193
+ * client.splitLargeFrames = true;
194
+ * client.maxWebSocketChunkSize = 4096; // Allow chunks of 4 KB
195
+ * ```
118
196
  */
119
197
  splitLargeFrames: boolean;
120
198
  /**
121
- * See [splitLargeFrames]{@link Client#splitLargeFrames}.
122
- * This has no effect if [splitLargeFrames]{@link Client#splitLargeFrames} is `false`.
199
+ * Maximum size (in bytes) for individual WebSocket chunks if [splitLargeFrames]{@link Client#splitLargeFrames} is enabled.
200
+ *
201
+ * Default is 8 KB (`8 * 1024` bytes). This value has no effect if [splitLargeFrames]{@link Client#splitLargeFrames} is `false`.
123
202
  */
124
203
  maxWebSocketChunkSize: number;
125
204
  /**
126
- * Usually the
127
- * [type of WebSocket frame]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send#Parameters}
128
- * is automatically decided by type of the payload.
129
- * Default is `false`, which should work with all compliant brokers.
205
+ * Forces all WebSocket frames to use binary transport, irrespective of payload type.
206
+ *
207
+ * Default behavior determines frame type based on payload (e.g., binary data for ArrayBuffers).
130
208
  *
131
- * Set this flag to force binary frames.
209
+ * Example:
210
+ * ```javascript
211
+ * client.forceBinaryWSFrames = true;
212
+ * ```
132
213
  */
133
214
  forceBinaryWSFrames: boolean;
134
215
  /**
135
- * A bug in ReactNative chops a string on occurrence of a NULL.
136
- * See issue [https://github.com/stomp-js/stompjs/issues/89]{@link https://github.com/stomp-js/stompjs/issues/89}.
137
- * This makes incoming WebSocket messages invalid STOMP packets.
138
- * Setting this flag attempts to reverse the damage by appending a NULL.
139
- * If the broker splits a large message into multiple WebSocket messages,
140
- * this flag will cause data loss and abnormal termination of connection.
216
+ * Workaround for a React Native WebSocket bug, where messages containing `NULL` are chopped.
141
217
  *
142
- * This is not an ideal solution, but a stop gap until the underlying issue is fixed at ReactNative library.
218
+ * Enabling this appends a `NULL` character to incoming frames to ensure they remain valid STOMP packets.
219
+ *
220
+ * Warning:
221
+ * - For brokers that split large messages, this may cause data loss or connection termination.
222
+ *
223
+ * Example:
224
+ * ```javascript
225
+ * client.appendMissingNULLonIncoming = true;
226
+ * ```
143
227
  */
144
228
  appendMissingNULLonIncoming: boolean;
145
229
  /**
146
- * Underlying WebSocket instance, READONLY.
230
+ * Provides access to the underlying WebSocket instance.
231
+ * This property is **read-only**.
232
+ *
233
+ * Example:
234
+ * ```javascript
235
+ * const webSocket = client.webSocket;
236
+ * if (webSocket) {
237
+ * console.log('WebSocket is connected:', webSocket.readyState === WebSocket.OPEN);
238
+ * }
239
+ * ```
240
+ *
241
+ * **Caution:**
242
+ * Directly interacting with the WebSocket instance (e.g., sending or receiving frames)
243
+ * can interfere with the proper functioning of this library. Such actions may cause
244
+ * unexpected behavior, disconnections, or invalid state in the library's internal mechanisms.
245
+ *
246
+ * Instead, use the library's provided methods to manage STOMP communication.
247
+ *
248
+ * @returns The WebSocket instance used by the STOMP handler, or `undefined` if not connected.
147
249
  */
148
250
  get webSocket(): IStompSocket | undefined;
149
251
  /**
150
- * Connection headers, important keys - `login`, `passcode`, `host`.
151
- * Though STOMP 1.2 standard marks these keys to be present, check your broker documentation for
152
- * details specific to your broker.
252
+ * Connection headers to be sent during the connection handshake.
253
+ *
254
+ * Keys like `login`, `passcode`, and `host` are commonly expected for most brokers.
255
+ * Although STOMP 1.2 specifies these keys as mandatory, consult your broker's documentation
256
+ * for additional requirements or alternative header usage.
257
+ *
258
+ * Example:
259
+ * ```javascript
260
+ * client.connectHeaders = {
261
+ * login: 'my-username',
262
+ * passcode: 'my-password',
263
+ * host: 'my-vhost'
264
+ * };
265
+ * ```
153
266
  */
154
267
  connectHeaders: StompHeaders;
155
268
  /**
156
- * Disconnection headers.
269
+ * Allows customization of the disconnection headers.
270
+ *
271
+ * Any changes made during an active session will also be applied immediately.
272
+ *
273
+ * Example:
274
+ * ```javascript
275
+ * client.disconnectHeaders = {
276
+ * receipt: 'custom-receipt-id'
277
+ * };
278
+ * ```
157
279
  */
158
280
  get disconnectHeaders(): StompHeaders;
159
281
  set disconnectHeaders(value: StompHeaders);
160
282
  private _disconnectHeaders;
161
283
  /**
162
- * This function will be called for any unhandled messages.
163
- * It is useful for receiving messages sent to RabbitMQ temporary queues.
284
+ * Callback invoked for any unhandled messages received from the broker.
285
+ *
286
+ * This is particularly useful for handling messages sent to RabbitMQ temporary queues
287
+ * or other queues where no explicit subscription exists. It can also be triggered
288
+ * by stray messages received while a subscription is being unsubscribed.
164
289
  *
165
- * It can also get invoked with stray messages while the server is processing
166
- * a request to [Client#unsubscribe]{@link Client#unsubscribe}
167
- * from an endpoint.
290
+ * Usage:
291
+ * ```javascript
292
+ * client.onUnhandledMessage = (message) => {
293
+ * console.log('Unhandled message:', message);
294
+ * };
295
+ * ```
168
296
  *
169
- * The actual {@link IMessage} will be passed as parameter to the callback.
297
+ * @param message The actual {@link IMessage} received.
170
298
  */
171
299
  onUnhandledMessage: messageCallbackType;
172
300
  /**
173
- * STOMP brokers can be requested to notify when an operation is actually completed.
174
- * Prefer using [Client#watchForReceipt]{@link Client#watchForReceipt}. See
175
- * [Client#watchForReceipt]{@link Client#watchForReceipt} for examples.
301
+ * Callback invoked when the broker sends a receipt indicating the completion
302
+ * of an operation. Receipts are typically requested using the
303
+ * [Client#watchForReceipt]{@link Client#watchForReceipt} function.
176
304
  *
177
- * The actual {@link IFrame} will be passed as parameter to the callback.
305
+ * Usage Example:
306
+ * See [Client#watchForReceipt]{@link Client#watchForReceipt}.
307
+ *
308
+ * @param frame The actual {@link IFrame} received from the broker.
178
309
  */
179
310
  onUnhandledReceipt: frameCallbackType;
180
311
  /**
181
- * Will be invoked if {@link IFrame} of an unknown type is received from the STOMP broker.
312
+ * Callback invoked when a frame of an unknown or unexpected type is received
313
+ * from the broker.
314
+ *
315
+ * This is intended as a fallback for handling unexpected or unsupported frames
316
+ * sent by the broker.
182
317
  *
183
- * The actual {@link IFrame} will be passed as parameter to the callback.
318
+ * Usage:
319
+ * ```javascript
320
+ * client.onUnhandledFrame = (frame) => {
321
+ * console.warn('Unhandled frame received:', frame);
322
+ * };
323
+ * ```
324
+ *
325
+ * @param frame The actual {@link IFrame} received from the broker.
184
326
  */
185
327
  onUnhandledFrame: frameCallbackType;
186
328
  /**
187
- * `true` if there is an active connection to STOMP Broker
329
+ * Callback invoked when a heartbeat message is received from the STOMP broker.
330
+ *
331
+ * Heartbeats ensure that the connection remains active and responsive. This callback
332
+ * is executed on every received heartbeat. It is useful for monitoring connection health
333
+ * or logging heartbeat activity.
334
+ *
335
+ * **Note**: The library handles heartbeats internally to maintain and verify connection status.
336
+ * Implementing this callback is optional and primarily for custom monitoring or debugging.
337
+ *
338
+ * Usage:
339
+ * ```javascript
340
+ * client.onHeartbeatReceived = () => {
341
+ * console.log('Heartbeat received');
342
+ * };
343
+ * ```
344
+ */
345
+ onHeartbeatReceived: emptyCallbackType;
346
+ /**
347
+ * Callback invoked when no heartbeat is received from the broker within
348
+ * the acceptable interval, indicating a potential communication issue or connection failure.
349
+ *
350
+ * This callback is triggered when the heartbeat interval defined by `heartbeatIncoming`
351
+ * elapses without a received heartbeat.
352
+ *
353
+ * **Note**: The library handles this condition internally and takes appropriate
354
+ * actions, such as marking the connection as failed. This callback is available
355
+ * for implementing custom recovery strategies or additional notifications.
356
+ *
357
+ * Usage:
358
+ * ```javascript
359
+ * client.onHeartbeatLost = () => {
360
+ * console.error('Lost connection to the broker');
361
+ * };
362
+ * ```
363
+ */
364
+ onHeartbeatLost: emptyCallbackType;
365
+ /**
366
+ * Indicates whether there is an active connection to the STOMP broker.
367
+ *
368
+ * Usage:
369
+ * ```javascript
370
+ * if (client.connected) {
371
+ * console.log('Client is connected to the broker.');
372
+ * } else {
373
+ * console.log('No connection to the broker.');
374
+ * }
375
+ * ```
376
+ *
377
+ * @returns `true` if the client is currently connected, `false` otherwise.
188
378
  */
189
379
  get connected(): boolean;
190
380
  /**
191
- * Callback, invoked on before a connection to the STOMP broker.
381
+ * Callback executed before initiating a connection to the STOMP broker.
382
+ *
383
+ * This callback allows users to modify connection options dynamically,
384
+ * such as updating credentials or connection parameters, before the connection is made.
192
385
  *
193
- * You can change options on the client, which will impact the immediate connecting.
194
- * It is valid to call [Client#decativate]{@link Client#deactivate} in this callback.
386
+ * As of version 5.1, this callback supports `async/await`, enabling seamless integration
387
+ * with asynchronous operations, such as fetching tokens or credentials.
195
388
  *
196
- * As of version 5.1, this callback can be
197
- * [async](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
198
- * (i.e., it can return a
199
- * [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)).
200
- * In that case, connect will be called only after the Promise is resolved.
201
- * This can be used to reliably fetch credentials, access token etc. from some other service
202
- * in an asynchronous way.
389
+ * Example:
390
+ * ```javascript
391
+ * client.beforeConnect = async () => {
392
+ * const token = await fetchToken();
393
+ * client.connectHeaders = { Authorization: `Bearer ${token}` };
394
+ * };
395
+ * ```
203
396
  */
204
397
  beforeConnect: (client: Client) => void | Promise<void>;
205
398
  /**
206
- * Callback, invoked on every successful connection to the STOMP broker.
399
+ * Callback executed upon every successful connection to the STOMP broker.
207
400
  *
208
- * The actual {@link IFrame} will be passed as parameter to the callback.
209
- * Sometimes clients will like to use headers from this frame.
401
+ * This callback is invoked after the connection is established and the CONNECTED frame
402
+ * is received from the broker. It provides access to the broker's response frame,
403
+ * allowing users to parse its headers or other data.
404
+ *
405
+ * Example:
406
+ * ```javascript
407
+ * client.onConnect = (frame) => {
408
+ * console.log('Connected to broker, session ID:', frame.headers['session']);
409
+ * };
410
+ * ```
210
411
  */
211
412
  onConnect: frameCallbackType;
212
413
  /**
213
- * Callback, invoked on every successful disconnection from the STOMP broker. It will not be invoked if
214
- * the STOMP broker disconnected due to an error.
414
+ * Callback executed upon successful disconnection from the STOMP broker.
215
415
  *
216
- * The actual Receipt {@link IFrame} acknowledging the DISCONNECT will be passed as parameter to the callback.
416
+ * The callback is invoked when the DISCONNECT receipt is received from the broker.
417
+ * Note that due to the design of the STOMP protocol or communication interrupts, the
418
+ * DISCONNECT receipt may not always be received. For handling such cases, use
419
+ * [Client#onWebSocketClose]{@link Client#onWebSocketClose}.
217
420
  *
218
- * The way STOMP protocol is designed, the connection may close/terminate without the client
219
- * receiving the Receipt {@link IFrame} acknowledging the DISCONNECT.
220
- * You might find [Client#onWebSocketClose]{@link Client#onWebSocketClose} more appropriate to watch
221
- * STOMP broker disconnects.
421
+ * Example:
422
+ * ```javascript
423
+ * client.onDisconnect = (frame) => {
424
+ * console.log('Disconnected successfully');
425
+ * };
426
+ * ```
222
427
  */
223
428
  onDisconnect: frameCallbackType;
224
429
  /**
225
- * Callback, invoked on an ERROR frame received from the STOMP Broker.
226
- * A compliant STOMP Broker will close the connection after this type of frame.
227
- * Please check broker specific documentation for exact behavior.
430
+ * Callback executed when an ERROR frame is received from the STOMP broker.
228
431
  *
229
- * The actual {@link IFrame} will be passed as parameter to the callback.
432
+ * Receiving an ERROR frame typically indicates a problem with the subscription,
433
+ * message format, or protocol violation. The broker will usually close the connection
434
+ * after sending an ERROR frame.
435
+ *
436
+ * Example:
437
+ * ```javascript
438
+ * client.onStompError = (frame) => {
439
+ * console.error('Broker reported an error:', frame.body);
440
+ * };
441
+ * ```
230
442
  */
231
443
  onStompError: frameCallbackType;
232
444
  /**
233
- * Callback, invoked when underlying WebSocket is closed.
445
+ * Callback executed when the underlying WebSocket is closed.
446
+ *
447
+ * This can occur due to various reasons, such as network interruptions or broker shutdown.
448
+ * The callback provides the WebSocket [CloseEvent]{@link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent},
449
+ * which contains details about the closure.
234
450
  *
235
- * Actual [CloseEvent]{@link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent}
236
- * is passed as parameter to the callback.
451
+ * Example:
452
+ * ```javascript
453
+ * client.onWebSocketClose = (event) => {
454
+ * console.log('WebSocket closed. Code:', event.code);
455
+ * };
456
+ * ```
237
457
  */
238
458
  onWebSocketClose: closeEventCallbackType;
239
459
  /**
240
- * Callback, invoked when underlying WebSocket raises an error.
460
+ * Callback executed when the underlying WebSocket raises an error.
461
+ *
462
+ * This callback provides an [Event]{@link https://developer.mozilla.org/en-US/docs/Web/API/Event}
463
+ * representing the error raised by the WebSocket.
241
464
  *
242
- * Actual [Event]{@link https://developer.mozilla.org/en-US/docs/Web/API/Event}
243
- * is passed as parameter to the callback.
465
+ * Example:
466
+ * ```javascript
467
+ * client.onWebSocketError = (event) => {
468
+ * console.error('WebSocket error:', event);
469
+ * };
470
+ * ```
244
471
  */
245
472
  onWebSocketError: wsErrorCallbackType;
246
473
  /**
247
- * Set it to log the actual raw communication with the broker.
248
- * When unset, it logs headers of the parsed frames.
474
+ * Enable or disable logging of the raw communication with the broker.
475
+ *
476
+ * When enabled, it logs the raw frames exchanged with the broker. If disabled,
477
+ * only the headers of the parsed frames will be logged.
478
+ *
479
+ * **Caution**: Raw communication frames must contain valid UTF-8 strings,
480
+ * as any non-compliant data can cause errors in the logging process.
249
481
  *
250
- * Changes effect from the next broker reconnect.
482
+ * Changes to this setting will take effect during the next broker reconnect.
251
483
  *
252
- * **Caution: this assumes that frames only have valid UTF8 strings.**
484
+ * Example:
485
+ * ```javascript
486
+ * client.logRawCommunication = true; // Enable logging raw communication
487
+ * ```
253
488
  */
254
489
  logRawCommunication: boolean;
255
490
  /**
256
- * By default, debug messages are discarded. To log to `console` following can be used:
491
+ * Set a custom debug function to capture debug messages.
257
492
  *
493
+ * By default, debug messages are discarded. To log messages to the console, you can use:
258
494
  * ```javascript
259
- * client.debug = function(str) {
260
- * console.log(str);
261
- * };
495
+ * client.debug = (str) => {
496
+ * console.log(str);
497
+ * };
262
498
  * ```
263
499
  *
264
- * Currently this method does not support levels of log. Be aware that the
265
- * output can be quite verbose
266
- * and may contain sensitive information (like passwords, tokens etc.).
500
+ * **Note**: This method does not support configurable log levels, and the output can be
501
+ * verbose. Be cautious as debug messages may contain sensitive information, such as
502
+ * credentials or tokens.
267
503
  */
268
504
  debug: debugFnType;
269
505
  /**
270
- * Browsers do not immediately close WebSockets when `.close` is issued.
271
- * This may cause reconnection to take a significantly long time in case
272
- * of some types of failures.
273
- * In case of incoming heartbeat failure, this experimental flag instructs
274
- * the library to discard the socket immediately
275
- * (even before it is actually closed).
506
+ * Instruct the library to immediately terminate the socket on communication failures, even
507
+ * before the WebSocket is completely closed.
508
+ *
509
+ * This is particularly useful in browser environments where WebSocket closure may get delayed,
510
+ * causing prolonged reconnection intervals under certain failure conditions.
511
+ *
512
+ *
513
+ * Example:
514
+ * ```javascript
515
+ * client.discardWebsocketOnCommFailure = true; // Enable aggressive closing of WebSocket
516
+ * ```
517
+ *
518
+ * Default value: `false`.
276
519
  */
277
520
  discardWebsocketOnCommFailure: boolean;
278
521
  /**
279
- * version of STOMP protocol negotiated with the server, READONLY
522
+ * The version of the STOMP protocol negotiated with the server during connection.
523
+ *
524
+ * This is a **read-only** property and reflects the negotiated protocol version after
525
+ * a successful connection.
526
+ *
527
+ * Example:
528
+ * ```javascript
529
+ * console.log('Connected STOMP version:', client.connectedVersion);
530
+ * ```
531
+ *
532
+ * @returns The negotiated STOMP protocol version or `undefined` if not connected.
280
533
  */
281
534
  get connectedVersion(): string | undefined;
282
535
  private _stompHandler;
283
536
  /**
284
- * if the client is active (connected or going to reconnect)
537
+ * Indicates whether the client is currently active.
538
+ *
539
+ * A client is considered active if it is connected or actively attempting to reconnect.
540
+ *
541
+ * Example:
542
+ * ```javascript
543
+ * if (client.active) {
544
+ * console.log('The client is active.');
545
+ * } else {
546
+ * console.log('The client is inactive.');
547
+ * }
548
+ * ```
549
+ *
550
+ * @returns `true` if the client is active, otherwise `false`.
285
551
  */
286
552
  get active(): boolean;
287
553
  /**
288
- * It will be called on state change.
554
+ * Callback invoked whenever the client's state changes.
555
+ *
556
+ * This callback can be used to monitor transitions between various states, such as `ACTIVE`,
557
+ * `INACTIVE`, or `DEACTIVATING`. Note that in some scenarios, the client may transition
558
+ * directly from `ACTIVE` to `INACTIVE` without entering the `DEACTIVATING` state.
289
559
  *
290
- * When deactivating, it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
560
+ * Example:
561
+ * ```javascript
562
+ * client.onChangeState = (state) => {
563
+ * console.log(`Client state changed to: ${state}`);
564
+ * };
565
+ * ```
291
566
  */
292
567
  onChangeState: (state: ActivationState) => void;
293
568
  private _changeState;
294
569
  /**
295
- * Activation state.
570
+ * Current activation state of the client.
296
571
  *
297
- * It will usually be ACTIVE or INACTIVE.
298
- * When deactivating, it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
572
+ * Possible states:
573
+ * - `ActivationState.ACTIVE`: Client is connected or actively attempting to connect.
574
+ * - `ActivationState.INACTIVE`: Client is disconnected and not attempting to reconnect.
575
+ * - `ActivationState.DEACTIVATING`: Client is in the process of disconnecting.
576
+ *
577
+ * Note: The client may transition directly from `ACTIVE` to `INACTIVE` without entering
578
+ * the `DEACTIVATING` state.
299
579
  */
300
580
  state: ActivationState;
301
581
  private _reconnector;
302
582
  /**
303
- * Create an instance.
583
+ * Constructs a new STOMP client instance.
584
+ *
585
+ * The constructor initializes default values and sets up no-op callbacks for all events.
586
+ * Configuration can be passed during construction, or updated later using `configure`.
587
+ *
588
+ * Example:
589
+ * ```javascript
590
+ * const client = new Client({
591
+ * brokerURL: 'wss://broker.example.com',
592
+ * reconnectDelay: 5000
593
+ * });
594
+ * ```
595
+ *
596
+ * @param conf Optional configuration object to initialize the client with.
304
597
  */
305
598
  constructor(conf?: StompConfig);
306
599
  /**
307
- * Update configuration.
600
+ * Updates the client's configuration.
601
+ *
602
+ * All properties in the provided configuration object will override the current settings.
603
+ *
604
+ * Additionally, a warning is logged if `maxReconnectDelay` is configured to a
605
+ * value lower than `reconnectDelay`, and `maxReconnectDelay` is adjusted to match `reconnectDelay`.
606
+ *
607
+ * Example:
608
+ * ```javascript
609
+ * client.configure({
610
+ * reconnectDelay: 3000,
611
+ * maxReconnectDelay: 10000
612
+ * });
613
+ * ```
614
+ *
615
+ * @param conf Configuration object containing the new settings.
308
616
  */
309
617
  configure(conf: StompConfig): void;
310
618
  /**
311
- * Initiate the connection with the broker.
312
- * If the connection breaks, as per [Client#reconnectDelay]{@link Client#reconnectDelay},
313
- * it will keep trying to reconnect. If the [Client#reconnectTimeMode]{@link Client#reconnectTimeMode}
314
- * is set to EXPONENTIAL it will increase the wait time exponentially
619
+ * Activates the client, initiating a connection to the STOMP broker.
620
+ *
621
+ * On activation, the client attempts to connect and sets its state to `ACTIVE`. If the connection
622
+ * is lost, it will automatically retry based on `reconnectDelay` or `maxReconnectDelay`. If
623
+ * `reconnectTimeMode` is set to `EXPONENTIAL`, the reconnect delay increases exponentially.
624
+ *
625
+ * To stop reconnection attempts and disconnect, call [Client#deactivate]{@link Client#deactivate}.
626
+ *
627
+ * Example:
628
+ * ```javascript
629
+ * client.activate(); // Connect to the broker
630
+ * ```
315
631
  *
316
- * Call [Client#deactivate]{@link Client#deactivate} to disconnect and stop reconnection attempts.
632
+ * If the client is currently `DEACTIVATING`, connection is delayed until the deactivation process completes.
317
633
  */
318
634
  activate(): void;
319
635
  private _connect;
320
636
  private _createWebSocket;
321
637
  private _schedule_reconnect;
322
638
  /**
323
- * Disconnect if connected and stop auto reconnect loop.
324
- * Appropriate callbacks will be invoked if there is an underlying STOMP connection.
639
+ * Disconnects the client and stops the automatic reconnection loop.
325
640
  *
326
- * This call is async. It will resolve immediately if there is no underlying active websocket,
327
- * otherwise, it will resolve after the underlying websocket is properly disposed of.
641
+ * If there is an active STOMP connection at the time of invocation, the appropriate callbacks
642
+ * will be triggered during the shutdown sequence. Once deactivated, the client will enter the
643
+ * `INACTIVE` state, and no further reconnection attempts will be made.
328
644
  *
329
- * It is not an error to invoke this method more than once.
330
- * Each of those would resolve on completion of deactivation.
645
+ * **Behavior**:
646
+ * - If there is no active WebSocket connection, this method resolves immediately.
647
+ * - If there is an active connection, the method waits for the underlying WebSocket
648
+ * to properly close before resolving.
649
+ * - Multiple calls to this method are safe. Each invocation resolves upon completion.
650
+ * - To reactivate, call [Client#activate]{@link Client#activate}.
331
651
  *
332
- * To reactivate, you can call [Client#activate]{@link Client#activate}.
652
+ * **Experimental Option:**
653
+ * - By specifying the `force: true` option, the WebSocket connection is discarded immediately,
654
+ * bypassing both the STOMP and WebSocket shutdown sequences.
655
+ * - **Caution:** Using `force: true` may leave the WebSocket in an inconsistent state,
656
+ * and brokers may not immediately detect the termination.
333
657
  *
334
- * Experimental: pass `force: true` to immediately discard the underlying connection.
335
- * This mode will skip both the STOMP and the Websocket shutdown sequences.
336
- * In some cases, browsers take a long time in the Websocket shutdown
337
- * if the underlying connection had gone stale.
338
- * Using this mode can speed up.
339
- * When this mode is used, the actual Websocket may linger for a while
340
- * and the broker may not realize that the connection is no longer in use.
658
+ * Example:
659
+ * ```javascript
660
+ * // Graceful disconnect
661
+ * await client.deactivate();
341
662
  *
342
- * It is possible to invoke this method initially without the `force` option
343
- * and subsequently, say after a wait, with the `force` option.
663
+ * // Forced disconnect to speed up shutdown when the connection is stale
664
+ * await client.deactivate({ force: true });
665
+ * ```
666
+ *
667
+ * @param options Configuration options for deactivation. Use `force: true` for immediate shutdown.
668
+ * @returns A Promise that resolves when the deactivation process completes.
344
669
  */
345
670
  deactivate(options?: {
346
671
  force?: boolean;
347
672
  }): Promise<void>;
348
673
  /**
349
- * Force disconnect if there is an active connection by directly closing the underlying WebSocket.
350
- * This is different from a normal disconnect where a DISCONNECT sequence is carried out with the broker.
351
- * After forcing disconnect, automatic reconnect will be attempted.
352
- * To stop further reconnects call [Client#deactivate]{@link Client#deactivate} as well.
674
+ * Forces a disconnect by directly closing the WebSocket.
675
+ *
676
+ * Unlike a normal disconnect, this does not send a DISCONNECT sequence to the broker but
677
+ * instead closes the WebSocket connection directly. After forcing a disconnect, the client
678
+ * will automatically attempt to reconnect based on its `reconnectDelay` configuration.
679
+ *
680
+ * **Note:** To prevent further reconnect attempts, call [Client#deactivate]{@link Client#deactivate}.
681
+ *
682
+ * Example:
683
+ * ```javascript
684
+ * client.forceDisconnect();
685
+ * ```
353
686
  */
354
687
  forceDisconnect(): void;
355
688
  private _disposeStompHandler;
356
689
  /**
357
- * Send a message to a named destination. Refer to your STOMP broker documentation for types
358
- * and naming of destinations.
359
- *
360
- * STOMP protocol specifies and suggests some headers and also allows broker-specific headers.
361
- *
362
- * `body` must be String.
363
- * You will need to covert the payload to string in case it is not string (e.g. JSON).
690
+ * Sends a message to the specified destination on the STOMP broker.
364
691
  *
365
- * To send a binary message body, use `binaryBody` parameter. It should be a
366
- * [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).
367
- * Sometimes brokers may not support binary frames out of the box.
368
- * Please check your broker documentation.
692
+ * The `body` must be a `string`. For non-string payloads (e.g., JSON), encode it as a string before sending.
693
+ * If sending binary data, use the `binaryBody` parameter as a [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).
369
694
  *
370
- * `content-length` header is automatically added to the STOMP Frame sent to the broker.
371
- * Set `skipContentLengthHeader` to indicate that `content-length` header should not be added.
372
- * For binary messages, `content-length` header is always added.
695
+ * **Content-Length Behavior**:
696
+ * - For non-binary messages, the `content-length` header is added by default.
697
+ * - The `content-length` header can be skipped for text frames by setting `skipContentLengthHeader: true` in the parameters.
698
+ * - For binary messages, the `content-length` header is always included.
373
699
  *
374
- * Caution: The broker will, most likely, report an error and disconnect
375
- * if the message body has NULL octet(s) and `content-length` header is missing.
700
+ * **Notes**:
701
+ * - Ensure that brokers support binary frames before using `binaryBody`.
702
+ * - Sending messages with NULL octets and missing `content-length` headers can cause brokers to disconnect and throw errors.
376
703
  *
704
+ * Example:
377
705
  * ```javascript
378
- * client.publish({destination: "/queue/test", headers: {priority: 9}, body: "Hello, STOMP"});
379
- *
380
- * // Only destination is mandatory parameter
381
- * client.publish({destination: "/queue/test", body: "Hello, STOMP"});
382
- *
383
- * // Skip content-length header in the frame to the broker
384
- * client.publish({"/queue/test", body: "Hello, STOMP", skipContentLengthHeader: true});
385
- *
386
- * var binaryData = generateBinaryData(); // This need to be of type Uint8Array
387
- * // setting content-type header is not mandatory, however a good practice
388
- * client.publish({destination: '/topic/special', binaryBody: binaryData,
389
- * headers: {'content-type': 'application/octet-stream'}});
706
+ * // Basic text message
707
+ * client.publish({ destination: "/queue/test", body: "Hello, STOMP" });
708
+ *
709
+ * // Text message with additional headers
710
+ * client.publish({ destination: "/queue/test", headers: { priority: 9 }, body: "Hello, STOMP" });
711
+ *
712
+ * // Skip content-length header
713
+ * client.publish({ destination: "/queue/test", body: "Hello, STOMP", skipContentLengthHeader: true });
714
+ *
715
+ * // Binary message
716
+ * const binaryData = new Uint8Array([1, 2, 3, 4]);
717
+ * client.publish({
718
+ * destination: '/topic/special',
719
+ * binaryBody: binaryData,
720
+ * headers: { 'content-type': 'application/octet-stream' }
721
+ * });
390
722
  * ```
391
723
  */
392
724
  publish(params: IPublishParams): void;
393
725
  private _checkConnection;
394
726
  /**
395
- * STOMP brokers may carry out operation asynchronously and allow requesting for acknowledgement.
396
- * To request an acknowledgement, a `receipt` header needs to be sent with the actual request.
397
- * The value (say receipt-id) for this header needs to be unique for each use.
398
- * Typically, a sequence, a UUID, a random number or a combination may be used.
399
- *
400
- * A complaint broker will send a RECEIPT frame when an operation has actually been completed.
401
- * The operation needs to be matched based on the value of the receipt-id.
727
+ * Monitors for a receipt acknowledgment from the broker for specific operations.
402
728
  *
403
- * This method allows watching for a receipt and invoking the callback
404
- * when the corresponding receipt has been received.
729
+ * Add a `receipt` header to the operation (like subscribe or publish), and use this method with
730
+ * the same receipt ID to detect when the broker has acknowledged the operation's completion.
405
731
  *
406
- * The actual {@link IFrame} will be passed as parameter to the callback.
732
+ * The callback is invoked with the corresponding {@link IFrame} when the receipt is received.
407
733
  *
408
734
  * Example:
409
735
  * ```javascript
410
- * // Subscribing with acknowledgement
411
- * let receiptId = randomText();
412
- *
413
- * client.watchForReceipt(receiptId, function() {
414
- * // Will be called after server acknowledges
415
- * });
736
+ * const receiptId = "unique-receipt-id";
416
737
  *
417
- * client.subscribe(TEST.destination, onMessage, {receipt: receiptId});
738
+ * client.watchForReceipt(receiptId, (frame) => {
739
+ * console.log("Operation acknowledged by the broker:", frame);
740
+ * });
418
741
  *
419
- *
420
- * // Publishing with acknowledgement
421
- * receiptId = randomText();
422
- *
423
- * client.watchForReceipt(receiptId, function() {
424
- * // Will be called after server acknowledges
425
- * });
426
- * client.publish({destination: TEST.destination, headers: {receipt: receiptId}, body: msg});
742
+ * // Attach the receipt header to an operation
743
+ * client.publish({ destination: "/queue/test", headers: { receipt: receiptId }, body: "Hello" });
427
744
  * ```
745
+ *
746
+ * @param receiptId Unique identifier for the receipt.
747
+ * @param callback Callback function invoked on receiving the RECEIPT frame.
428
748
  */
429
749
  watchForReceipt(receiptId: string, callback: frameCallbackType): void;
430
750
  /**
431
- * Subscribe to a STOMP Broker location. The callback will be invoked for each
432
- * received message with the {@link IMessage} as argument.
751
+ * Subscribes to a destination on the STOMP broker.
752
+ *
753
+ * The callback is triggered for each message received from the subscribed destination. The message
754
+ * is passed as an {@link IMessage} instance.
433
755
  *
434
- * Note: The library will generate a unique ID if there is none provided in the headers.
435
- * To use your own ID, pass it using the `headers` argument.
756
+ * **Subscription ID**:
757
+ * - If no `id` is provided in `headers`, the library generates a unique subscription ID automatically.
758
+ * - Provide an explicit `id` in `headers` if you wish to manage the subscription ID manually.
436
759
  *
760
+ * Example:
437
761
  * ```javascript
438
- * callback = function(message) {
439
- * // called when the client receives a STOMP message from the server
440
- * if (message.body) {
441
- * alert("got message with body " + message.body)
442
- * } else {
443
- * alert("got empty message");
444
- * }
445
- * });
762
+ * const callback = (message) => {
763
+ * console.log("Received message:", message.body);
764
+ * };
446
765
  *
447
- * var subscription = client.subscribe("/queue/test", callback);
766
+ * // Auto-generated subscription ID
767
+ * const subscription = client.subscribe("/queue/test", callback);
448
768
  *
449
- * // Explicit subscription id
450
- * var mySubId = 'my-subscription-id-001';
451
- * var subscription = client.subscribe(destination, callback, { id: mySubId });
769
+ * // Explicit subscription ID
770
+ * const mySubId = "my-subscription-id";
771
+ * const subscription = client.subscribe("/queue/test", callback, { id: mySubId });
452
772
  * ```
773
+ *
774
+ * @param destination Destination to subscribe to.
775
+ * @param callback Function invoked for each received message.
776
+ * @param headers Optional headers for subscription, such as `id`.
777
+ * @returns A {@link StompSubscription} which can be used to manage the subscription.
453
778
  */
454
779
  subscribe(destination: string, callback: messageCallbackType, headers?: StompHeaders): StompSubscription;
455
780
  /**
456
- * It is preferable to unsubscribe from a subscription by calling
457
- * `unsubscribe()` directly on {@link StompSubscription} returned by `client.subscribe()`:
781
+ * Unsubscribes from a subscription on the STOMP broker.
782
+ *
783
+ * Prefer using the `unsubscribe` method directly on the {@link StompSubscription} returned from `subscribe` for cleaner management:
784
+ * ```javascript
785
+ * const subscription = client.subscribe("/queue/test", callback);
786
+ * // Unsubscribe using the subscription object
787
+ * subscription.unsubscribe();
788
+ * ```
458
789
  *
790
+ * This method can also be used directly with the subscription ID.
791
+ *
792
+ * Example:
459
793
  * ```javascript
460
- * var subscription = client.subscribe(destination, onmessage);
461
- * // ...
462
- * subscription.unsubscribe();
794
+ * client.unsubscribe("my-subscription-id");
463
795
  * ```
464
796
  *
465
- * See: https://stomp.github.com/stomp-specification-1.2.html#UNSUBSCRIBE UNSUBSCRIBE Frame
797
+ * @param id Subscription ID to unsubscribe.
798
+ * @param headers Optional headers to pass for the UNSUBSCRIBE frame.
466
799
  */
467
800
  unsubscribe(id: string, headers?: StompHeaders): void;
468
801
  /**
469
- * Start a transaction, the returned {@link ITransaction} has methods - [commit]{@link ITransaction#commit}
470
- * and [abort]{@link ITransaction#abort}.
802
+ * Starts a new transaction. The returned {@link ITransaction} object provides
803
+ * methods for [commit]{@link ITransaction#commit} and [abort]{@link ITransaction#abort}.
471
804
  *
472
- * `transactionId` is optional, if not passed the library will generate it internally.
805
+ * If `transactionId` is not provided, the library generates a unique ID internally.
806
+ *
807
+ * Example:
808
+ * ```javascript
809
+ * const tx = client.begin(); // Auto-generated ID
810
+ *
811
+ * // Or explicitly specify a transaction ID
812
+ * const tx = client.begin("my-transaction-id");
813
+ * ```
814
+ *
815
+ * @param transactionId Optional transaction ID.
816
+ * @returns An instance of {@link ITransaction}.
473
817
  */
474
818
  begin(transactionId?: string): ITransaction;
475
819
  /**
476
- * Commit a transaction.
820
+ * Commits a transaction.
477
821
  *
478
- * It is preferable to commit a transaction by calling [commit]{@link ITransaction#commit} directly on
479
- * {@link ITransaction} returned by [client.begin]{@link Client#begin}.
822
+ * It is strongly recommended to call [commit]{@link ITransaction#commit} on
823
+ * the transaction object returned by [client#begin]{@link Client#begin}.
480
824
  *
825
+ * Example:
481
826
  * ```javascript
482
- * var tx = client.begin(txId);
483
- * //...
484
- * tx.commit();
827
+ * const tx = client.begin();
828
+ * // Perform operations under this transaction
829
+ * tx.commit();
485
830
  * ```
831
+ *
832
+ * @param transactionId The ID of the transaction to commit.
486
833
  */
487
834
  commit(transactionId: string): void;
488
835
  /**
489
- * Abort a transaction.
490
- * It is preferable to abort a transaction by calling [abort]{@link ITransaction#abort} directly on
491
- * {@link ITransaction} returned by [client.begin]{@link Client#begin}.
836
+ * Aborts a transaction.
837
+ *
838
+ * It is strongly recommended to call [abort]{@link ITransaction#abort} directly
839
+ * on the transaction object returned by [client#begin]{@link Client#begin}.
492
840
  *
841
+ * Example:
493
842
  * ```javascript
494
- * var tx = client.begin(txId);
495
- * //...
496
- * tx.abort();
843
+ * const tx = client.begin();
844
+ * // Perform operations under this transaction
845
+ * tx.abort(); // Abort the transaction
497
846
  * ```
847
+ *
848
+ * @param transactionId The ID of the transaction to abort.
498
849
  */
499
850
  abort(transactionId: string): void;
500
851
  /**
501
- * ACK a message. It is preferable to acknowledge a message by calling [ack]{@link IMessage#ack} directly
502
- * on the {@link IMessage} handled by a subscription callback:
852
+ * Acknowledges receipt of a message. Typically, this should be done by calling
853
+ * [ack]{@link IMessage#ack} directly on the {@link IMessage} instance passed
854
+ * to the subscription callback.
503
855
  *
856
+ * Example:
504
857
  * ```javascript
505
- * var callback = function (message) {
506
- * // process the message
507
- * // acknowledge it
508
- * message.ack();
509
- * };
510
- * client.subscribe(destination, callback, {'ack': 'client'});
858
+ * const callback = (message) => {
859
+ * // Process the message
860
+ * message.ack(); // Acknowledge the message
861
+ * };
862
+ *
863
+ * client.subscribe("/queue/example", callback, { ack: "client" });
511
864
  * ```
865
+ *
866
+ * @param messageId The ID of the message to acknowledge.
867
+ * @param subscriptionId The ID of the subscription.
868
+ * @param headers Optional headers for the acknowledgment frame.
512
869
  */
513
870
  ack(messageId: string, subscriptionId: string, headers?: StompHeaders): void;
514
871
  /**
515
- * NACK a message. It is preferable to acknowledge a message by calling [nack]{@link IMessage#nack} directly
516
- * on the {@link IMessage} handled by a subscription callback:
872
+ * Rejects a message (negative acknowledgment). Like acknowledgments, this should
873
+ * typically be done by calling [nack]{@link IMessage#nack} directly on the {@link IMessage}
874
+ * instance passed to the subscription callback.
517
875
  *
876
+ * Example:
518
877
  * ```javascript
519
- * var callback = function (message) {
520
- * // process the message
521
- * // an error occurs, nack it
522
- * message.nack();
523
- * };
524
- * client.subscribe(destination, callback, {'ack': 'client'});
878
+ * const callback = (message) => {
879
+ * // Process the message
880
+ * if (isError(message)) {
881
+ * message.nack(); // Reject the message
882
+ * }
883
+ * };
884
+ *
885
+ * client.subscribe("/queue/example", callback, { ack: "client" });
525
886
  * ```
887
+ *
888
+ * @param messageId The ID of the message to negatively acknowledge.
889
+ * @param subscriptionId The ID of the subscription.
890
+ * @param headers Optional headers for the NACK frame.
526
891
  */
527
892
  nack(messageId: string, subscriptionId: string, headers?: StompHeaders): void;
528
893
  }