@stomp/stompjs 7.1.1 → 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,535 +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 [Client#reconnectTimeMode]{@link Client#reconnectTimeMode} not LINEAR (e.g., EXPONENTIAL).
74
- * Set to 0 for no limit on wait time.
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}.
80
118
  *
119
+ * Example:
81
120
  * ```javascript
82
- * client.configure({
83
- * reconnectTimeMode: ReconnectionTimeMode.EXPONENTIAL,
84
- * reconnectDelay: 200, // It will wait 200, 400, 800 ms...
85
- * maxReconnectDelay: 10000, // Optional, when provided, it will not wait more that these ms
86
- * })
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
87
124
  * ```
88
125
  */
89
126
  reconnectTimeMode: ReconnectionTimeMode;
90
127
  /**
91
- * 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
+ * ```
92
136
  */
93
137
  heartbeatIncoming: number;
94
138
  /**
95
- * 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
+ * ```
96
151
  */
97
- heartbeatOutgoing: number;
152
+ heartbeatToleranceMultiplier: number;
98
153
  /**
99
- * Outgoing heartbeat strategy.
100
- * See https://github.com/stomp-js/stompjs/pull/579
154
+ * Interval (in milliseconds) for sending heartbeat signals to the server.
101
155
  *
102
- * Can be worker or interval strategy, but will always use `interval`
103
- * 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.
157
+ *
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.
104
166
  *
105
- * Using Web Workers may work better on long-running pages
106
- * and mobile apps, as the browser may suspend Timers in the main page.
107
- * Try the `Worker` mode if you discover disconnects when the browser tab is in the background.
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).
108
170
  *
109
- * 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.
110
174
  *
111
- * Defaults to `interval` strategy.
175
+ * Example:
176
+ * ```javascript
177
+ * client.heartbeatStrategy = TickerStrategy.Worker;
178
+ * ```
112
179
  */
113
180
  heartbeatStrategy: TickerStrategy;
114
181
  /**
115
- * This switches on a non-standard behavior while sending WebSocket packets.
116
- * It splits larger (text) packets into chunks of [maxWebSocketChunkSize]{@link Client#maxWebSocketChunkSize}.
117
- * Only Java Spring brokers seem to support this mode.
182
+ * Enables splitting of large text WebSocket frames into smaller chunks.
118
183
  *
119
- * WebSockets, by itself, split large (text) packets,
120
- * so it is not needed with a truly compliant STOMP/WebSocket broker.
121
- * 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`.
122
186
  *
123
- * `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.
124
190
  *
125
- * Binary frames are never split.
191
+ * Example:
192
+ * ```javascript
193
+ * client.splitLargeFrames = true;
194
+ * client.maxWebSocketChunkSize = 4096; // Allow chunks of 4 KB
195
+ * ```
126
196
  */
127
197
  splitLargeFrames: boolean;
128
198
  /**
129
- * See [splitLargeFrames]{@link Client#splitLargeFrames}.
130
- * 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`.
131
202
  */
132
203
  maxWebSocketChunkSize: number;
133
204
  /**
134
- * Usually the
135
- * [type of WebSocket frame]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send#Parameters}
136
- * is automatically decided by type of the payload.
137
- * Default is `false`, which should work with all compliant brokers.
205
+ * Forces all WebSocket frames to use binary transport, irrespective of payload type.
138
206
  *
139
- * Set this flag to force binary frames.
207
+ * Default behavior determines frame type based on payload (e.g., binary data for ArrayBuffers).
208
+ *
209
+ * Example:
210
+ * ```javascript
211
+ * client.forceBinaryWSFrames = true;
212
+ * ```
140
213
  */
141
214
  forceBinaryWSFrames: boolean;
142
215
  /**
143
- * A bug in ReactNative chops a string on occurrence of a NULL.
144
- * See issue [https://github.com/stomp-js/stompjs/issues/89]{@link https://github.com/stomp-js/stompjs/issues/89}.
145
- * This makes incoming WebSocket messages invalid STOMP packets.
146
- * Setting this flag attempts to reverse the damage by appending a NULL.
147
- * If the broker splits a large message into multiple WebSocket messages,
148
- * 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.
217
+ *
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.
149
222
  *
150
- * This is not an ideal solution, but a stop gap until the underlying issue is fixed at ReactNative library.
223
+ * Example:
224
+ * ```javascript
225
+ * client.appendMissingNULLonIncoming = true;
226
+ * ```
151
227
  */
152
228
  appendMissingNULLonIncoming: boolean;
153
229
  /**
154
- * 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.
155
249
  */
156
250
  get webSocket(): IStompSocket | undefined;
157
251
  /**
158
- * Connection headers, important keys - `login`, `passcode`, `host`.
159
- * Though STOMP 1.2 standard marks these keys to be present, check your broker documentation for
160
- * 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
+ * ```
161
266
  */
162
267
  connectHeaders: StompHeaders;
163
268
  /**
164
- * 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
+ * ```
165
279
  */
166
280
  get disconnectHeaders(): StompHeaders;
167
281
  set disconnectHeaders(value: StompHeaders);
168
282
  private _disconnectHeaders;
169
283
  /**
170
- * This function will be called for any unhandled messages.
171
- * It is useful for receiving messages sent to RabbitMQ temporary queues.
284
+ * Callback invoked for any unhandled messages received from the broker.
172
285
  *
173
- * It can also get invoked with stray messages while the server is processing
174
- * a request to [Client#unsubscribe]{@link Client#unsubscribe}
175
- * from an endpoint.
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.
176
289
  *
177
- * The actual {@link IMessage} will be passed as parameter to the callback.
290
+ * Usage:
291
+ * ```javascript
292
+ * client.onUnhandledMessage = (message) => {
293
+ * console.log('Unhandled message:', message);
294
+ * };
295
+ * ```
296
+ *
297
+ * @param message The actual {@link IMessage} received.
178
298
  */
179
299
  onUnhandledMessage: messageCallbackType;
180
300
  /**
181
- * STOMP brokers can be requested to notify when an operation is actually completed.
182
- * Prefer using [Client#watchForReceipt]{@link Client#watchForReceipt}. See
183
- * [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.
304
+ *
305
+ * Usage Example:
306
+ * See [Client#watchForReceipt]{@link Client#watchForReceipt}.
184
307
  *
185
- * The actual {@link IFrame} will be passed as parameter to the callback.
308
+ * @param frame The actual {@link IFrame} received from the broker.
186
309
  */
187
310
  onUnhandledReceipt: frameCallbackType;
188
311
  /**
189
- * 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.
317
+ *
318
+ * Usage:
319
+ * ```javascript
320
+ * client.onUnhandledFrame = (frame) => {
321
+ * console.warn('Unhandled frame received:', frame);
322
+ * };
323
+ * ```
190
324
  *
191
- * The actual {@link IFrame} will be passed as parameter to the callback.
325
+ * @param frame The actual {@link IFrame} received from the broker.
192
326
  */
193
327
  onUnhandledFrame: frameCallbackType;
194
328
  /**
195
- * `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.
196
378
  */
197
379
  get connected(): boolean;
198
380
  /**
199
- * 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.
200
385
  *
201
- * You can change options on the client, which will impact the immediate connecting.
202
- * 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.
203
388
  *
204
- * As of version 5.1, this callback can be
205
- * [async](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
206
- * (i.e., it can return a
207
- * [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)).
208
- * In that case, connect will be called only after the Promise is resolved.
209
- * This can be used to reliably fetch credentials, access token etc. from some other service
210
- * 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
+ * ```
211
396
  */
212
397
  beforeConnect: (client: Client) => void | Promise<void>;
213
398
  /**
214
- * Callback, invoked on every successful connection to the STOMP broker.
399
+ * Callback executed upon every successful connection to the STOMP broker.
400
+ *
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.
215
404
  *
216
- * The actual {@link IFrame} will be passed as parameter to the callback.
217
- * Sometimes clients will like to use headers from this frame.
405
+ * Example:
406
+ * ```javascript
407
+ * client.onConnect = (frame) => {
408
+ * console.log('Connected to broker, session ID:', frame.headers['session']);
409
+ * };
410
+ * ```
218
411
  */
219
412
  onConnect: frameCallbackType;
220
413
  /**
221
- * Callback, invoked on every successful disconnection from the STOMP broker. It will not be invoked if
222
- * the STOMP broker disconnected due to an error.
414
+ * Callback executed upon successful disconnection from the STOMP broker.
223
415
  *
224
- * 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}.
225
420
  *
226
- * The way STOMP protocol is designed, the connection may close/terminate without the client
227
- * receiving the Receipt {@link IFrame} acknowledging the DISCONNECT.
228
- * You might find [Client#onWebSocketClose]{@link Client#onWebSocketClose} more appropriate to watch
229
- * STOMP broker disconnects.
421
+ * Example:
422
+ * ```javascript
423
+ * client.onDisconnect = (frame) => {
424
+ * console.log('Disconnected successfully');
425
+ * };
426
+ * ```
230
427
  */
231
428
  onDisconnect: frameCallbackType;
232
429
  /**
233
- * Callback, invoked on an ERROR frame received from the STOMP Broker.
234
- * A compliant STOMP Broker will close the connection after this type of frame.
235
- * Please check broker specific documentation for exact behavior.
430
+ * Callback executed when an ERROR frame is received from the STOMP broker.
431
+ *
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.
236
435
  *
237
- * The actual {@link IFrame} will be passed as parameter to the callback.
436
+ * Example:
437
+ * ```javascript
438
+ * client.onStompError = (frame) => {
439
+ * console.error('Broker reported an error:', frame.body);
440
+ * };
441
+ * ```
238
442
  */
239
443
  onStompError: frameCallbackType;
240
444
  /**
241
- * Callback, invoked when underlying WebSocket is closed.
445
+ * Callback executed when the underlying WebSocket is closed.
242
446
  *
243
- * Actual [CloseEvent]{@link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent}
244
- * is passed as parameter to the callback.
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.
450
+ *
451
+ * Example:
452
+ * ```javascript
453
+ * client.onWebSocketClose = (event) => {
454
+ * console.log('WebSocket closed. Code:', event.code);
455
+ * };
456
+ * ```
245
457
  */
246
458
  onWebSocketClose: closeEventCallbackType;
247
459
  /**
248
- * Callback, invoked when underlying WebSocket raises an error.
460
+ * Callback executed when the underlying WebSocket raises an error.
249
461
  *
250
- * Actual [Event]{@link https://developer.mozilla.org/en-US/docs/Web/API/Event}
251
- * is passed as parameter to the callback.
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.
464
+ *
465
+ * Example:
466
+ * ```javascript
467
+ * client.onWebSocketError = (event) => {
468
+ * console.error('WebSocket error:', event);
469
+ * };
470
+ * ```
252
471
  */
253
472
  onWebSocketError: wsErrorCallbackType;
254
473
  /**
255
- * Set it to log the actual raw communication with the broker.
256
- * 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.
257
478
  *
258
- * Changes effect from the next broker reconnect.
479
+ * **Caution**: Raw communication frames must contain valid UTF-8 strings,
480
+ * as any non-compliant data can cause errors in the logging process.
259
481
  *
260
- * **Caution: this assumes that frames only have valid UTF8 strings.**
482
+ * Changes to this setting will take effect during the next broker reconnect.
483
+ *
484
+ * Example:
485
+ * ```javascript
486
+ * client.logRawCommunication = true; // Enable logging raw communication
487
+ * ```
261
488
  */
262
489
  logRawCommunication: boolean;
263
490
  /**
264
- * By default, debug messages are discarded. To log to `console` following can be used:
491
+ * Set a custom debug function to capture debug messages.
265
492
  *
493
+ * By default, debug messages are discarded. To log messages to the console, you can use:
266
494
  * ```javascript
267
- * client.debug = function(str) {
268
- * console.log(str);
269
- * };
495
+ * client.debug = (str) => {
496
+ * console.log(str);
497
+ * };
270
498
  * ```
271
499
  *
272
- * Currently this method does not support levels of log. Be aware that the
273
- * output can be quite verbose
274
- * 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.
275
503
  */
276
504
  debug: debugFnType;
277
505
  /**
278
- * Browsers do not immediately close WebSockets when `.close` is issued.
279
- * This may cause reconnection to take a significantly long time in case
280
- * of some types of failures.
281
- * In case of incoming heartbeat failure, this experimental flag instructs
282
- * the library to discard the socket immediately
283
- * (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`.
284
519
  */
285
520
  discardWebsocketOnCommFailure: boolean;
286
521
  /**
287
- * 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.
288
533
  */
289
534
  get connectedVersion(): string | undefined;
290
535
  private _stompHandler;
291
536
  /**
292
- * 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`.
293
551
  */
294
552
  get active(): boolean;
295
553
  /**
296
- * It will be called on state change.
554
+ * Callback invoked whenever the client's state changes.
297
555
  *
298
- * When deactivating, it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
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.
559
+ *
560
+ * Example:
561
+ * ```javascript
562
+ * client.onChangeState = (state) => {
563
+ * console.log(`Client state changed to: ${state}`);
564
+ * };
565
+ * ```
299
566
  */
300
567
  onChangeState: (state: ActivationState) => void;
301
568
  private _changeState;
302
569
  /**
303
- * Activation state.
570
+ * Current activation state of the client.
571
+ *
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.
304
576
  *
305
- * It will usually be ACTIVE or INACTIVE.
306
- * When deactivating, it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
577
+ * Note: The client may transition directly from `ACTIVE` to `INACTIVE` without entering
578
+ * the `DEACTIVATING` state.
307
579
  */
308
580
  state: ActivationState;
309
581
  private _reconnector;
310
582
  /**
311
- * 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.
312
597
  */
313
598
  constructor(conf?: StompConfig);
314
599
  /**
315
- * 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.
316
616
  */
317
617
  configure(conf: StompConfig): void;
318
618
  /**
319
- * Initiate the connection with the broker.
320
- * If the connection breaks, as per [Client#reconnectDelay]{@link Client#reconnectDelay},
321
- * it will keep trying to reconnect. If the [Client#reconnectTimeMode]{@link Client#reconnectTimeMode}
322
- * 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
+ * ```
323
631
  *
324
- * 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.
325
633
  */
326
634
  activate(): void;
327
635
  private _connect;
328
636
  private _createWebSocket;
329
637
  private _schedule_reconnect;
330
638
  /**
331
- * Disconnect if connected and stop auto reconnect loop.
332
- * Appropriate callbacks will be invoked if there is an underlying STOMP connection.
639
+ * Disconnects the client and stops the automatic reconnection loop.
333
640
  *
334
- * This call is async. It will resolve immediately if there is no underlying active websocket,
335
- * 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.
336
644
  *
337
- * It is not an error to invoke this method more than once.
338
- * 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}.
339
651
  *
340
- * 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.
341
657
  *
342
- * Experimental: pass `force: true` to immediately discard the underlying connection.
343
- * This mode will skip both the STOMP and the Websocket shutdown sequences.
344
- * In some cases, browsers take a long time in the Websocket shutdown
345
- * if the underlying connection had gone stale.
346
- * Using this mode can speed up.
347
- * When this mode is used, the actual Websocket may linger for a while
348
- * 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();
349
662
  *
350
- * It is possible to invoke this method initially without the `force` option
351
- * 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.
352
669
  */
353
670
  deactivate(options?: {
354
671
  force?: boolean;
355
672
  }): Promise<void>;
356
673
  /**
357
- * Force disconnect if there is an active connection by directly closing the underlying WebSocket.
358
- * This is different from a normal disconnect where a DISCONNECT sequence is carried out with the broker.
359
- * After forcing disconnect, automatic reconnect will be attempted.
360
- * 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
+ * ```
361
686
  */
362
687
  forceDisconnect(): void;
363
688
  private _disposeStompHandler;
364
689
  /**
365
- * Send a message to a named destination. Refer to your STOMP broker documentation for types
366
- * and naming of destinations.
367
- *
368
- * STOMP protocol specifies and suggests some headers and also allows broker-specific headers.
369
- *
370
- * `body` must be String.
371
- * 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.
372
691
  *
373
- * To send a binary message body, use `binaryBody` parameter. It should be a
374
- * [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).
375
- * Sometimes brokers may not support binary frames out of the box.
376
- * 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).
377
694
  *
378
- * `content-length` header is automatically added to the STOMP Frame sent to the broker.
379
- * Set `skipContentLengthHeader` to indicate that `content-length` header should not be added.
380
- * 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.
381
699
  *
382
- * Caution: The broker will, most likely, report an error and disconnect
383
- * 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.
384
703
  *
704
+ * Example:
385
705
  * ```javascript
386
- * client.publish({destination: "/queue/test", headers: {priority: 9}, body: "Hello, STOMP"});
387
- *
388
- * // Only destination is mandatory parameter
389
- * client.publish({destination: "/queue/test", body: "Hello, STOMP"});
390
- *
391
- * // Skip content-length header in the frame to the broker
392
- * client.publish({"/queue/test", body: "Hello, STOMP", skipContentLengthHeader: true});
393
- *
394
- * var binaryData = generateBinaryData(); // This need to be of type Uint8Array
395
- * // setting content-type header is not mandatory, however a good practice
396
- * client.publish({destination: '/topic/special', binaryBody: binaryData,
397
- * 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
+ * });
398
722
  * ```
399
723
  */
400
724
  publish(params: IPublishParams): void;
401
725
  private _checkConnection;
402
726
  /**
403
- * STOMP brokers may carry out operation asynchronously and allow requesting for acknowledgement.
404
- * To request an acknowledgement, a `receipt` header needs to be sent with the actual request.
405
- * The value (say receipt-id) for this header needs to be unique for each use.
406
- * Typically, a sequence, a UUID, a random number or a combination may be used.
407
- *
408
- * A complaint broker will send a RECEIPT frame when an operation has actually been completed.
409
- * 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.
410
728
  *
411
- * This method allows watching for a receipt and invoking the callback
412
- * 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.
413
731
  *
414
- * 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.
415
733
  *
416
734
  * Example:
417
735
  * ```javascript
418
- * // Subscribing with acknowledgement
419
- * let receiptId = randomText();
420
- *
421
- * client.watchForReceipt(receiptId, function() {
422
- * // Will be called after server acknowledges
423
- * });
736
+ * const receiptId = "unique-receipt-id";
424
737
  *
425
- * client.subscribe(TEST.destination, onMessage, {receipt: receiptId});
738
+ * client.watchForReceipt(receiptId, (frame) => {
739
+ * console.log("Operation acknowledged by the broker:", frame);
740
+ * });
426
741
  *
427
- *
428
- * // Publishing with acknowledgement
429
- * receiptId = randomText();
430
- *
431
- * client.watchForReceipt(receiptId, function() {
432
- * // Will be called after server acknowledges
433
- * });
434
- * 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" });
435
744
  * ```
745
+ *
746
+ * @param receiptId Unique identifier for the receipt.
747
+ * @param callback Callback function invoked on receiving the RECEIPT frame.
436
748
  */
437
749
  watchForReceipt(receiptId: string, callback: frameCallbackType): void;
438
750
  /**
439
- * Subscribe to a STOMP Broker location. The callback will be invoked for each
440
- * 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.
441
755
  *
442
- * Note: The library will generate a unique ID if there is none provided in the headers.
443
- * 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.
444
759
  *
760
+ * Example:
445
761
  * ```javascript
446
- * callback = function(message) {
447
- * // called when the client receives a STOMP message from the server
448
- * if (message.body) {
449
- * alert("got message with body " + message.body)
450
- * } else {
451
- * alert("got empty message");
452
- * }
453
- * });
762
+ * const callback = (message) => {
763
+ * console.log("Received message:", message.body);
764
+ * };
454
765
  *
455
- * var subscription = client.subscribe("/queue/test", callback);
766
+ * // Auto-generated subscription ID
767
+ * const subscription = client.subscribe("/queue/test", callback);
456
768
  *
457
- * // Explicit subscription id
458
- * var mySubId = 'my-subscription-id-001';
459
- * 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 });
460
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.
461
778
  */
462
779
  subscribe(destination: string, callback: messageCallbackType, headers?: StompHeaders): StompSubscription;
463
780
  /**
464
- * It is preferable to unsubscribe from a subscription by calling
465
- * `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
+ * ```
466
789
  *
790
+ * This method can also be used directly with the subscription ID.
791
+ *
792
+ * Example:
467
793
  * ```javascript
468
- * var subscription = client.subscribe(destination, onmessage);
469
- * // ...
470
- * subscription.unsubscribe();
794
+ * client.unsubscribe("my-subscription-id");
471
795
  * ```
472
796
  *
473
- * 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.
474
799
  */
475
800
  unsubscribe(id: string, headers?: StompHeaders): void;
476
801
  /**
477
- * Start a transaction, the returned {@link ITransaction} has methods - [commit]{@link ITransaction#commit}
478
- * 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}.
479
804
  *
480
- * `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}.
481
817
  */
482
818
  begin(transactionId?: string): ITransaction;
483
819
  /**
484
- * Commit a transaction.
820
+ * Commits a transaction.
485
821
  *
486
- * It is preferable to commit a transaction by calling [commit]{@link ITransaction#commit} directly on
487
- * {@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}.
488
824
  *
825
+ * Example:
489
826
  * ```javascript
490
- * var tx = client.begin(txId);
491
- * //...
492
- * tx.commit();
827
+ * const tx = client.begin();
828
+ * // Perform operations under this transaction
829
+ * tx.commit();
493
830
  * ```
831
+ *
832
+ * @param transactionId The ID of the transaction to commit.
494
833
  */
495
834
  commit(transactionId: string): void;
496
835
  /**
497
- * Abort a transaction.
498
- * It is preferable to abort a transaction by calling [abort]{@link ITransaction#abort} directly on
499
- * {@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}.
500
840
  *
841
+ * Example:
501
842
  * ```javascript
502
- * var tx = client.begin(txId);
503
- * //...
504
- * tx.abort();
843
+ * const tx = client.begin();
844
+ * // Perform operations under this transaction
845
+ * tx.abort(); // Abort the transaction
505
846
  * ```
847
+ *
848
+ * @param transactionId The ID of the transaction to abort.
506
849
  */
507
850
  abort(transactionId: string): void;
508
851
  /**
509
- * ACK a message. It is preferable to acknowledge a message by calling [ack]{@link IMessage#ack} directly
510
- * 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.
511
855
  *
856
+ * Example:
512
857
  * ```javascript
513
- * var callback = function (message) {
514
- * // process the message
515
- * // acknowledge it
516
- * message.ack();
517
- * };
518
- * 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" });
519
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.
520
869
  */
521
870
  ack(messageId: string, subscriptionId: string, headers?: StompHeaders): void;
522
871
  /**
523
- * NACK a message. It is preferable to acknowledge a message by calling [nack]{@link IMessage#nack} directly
524
- * 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.
525
875
  *
876
+ * Example:
526
877
  * ```javascript
527
- * var callback = function (message) {
528
- * // process the message
529
- * // an error occurs, nack it
530
- * message.nack();
531
- * };
532
- * 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" });
533
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.
534
891
  */
535
892
  nack(messageId: string, subscriptionId: string, headers?: StompHeaders): void;
536
893
  }