UNPKG

20.1 kBTypeScriptView Raw
1import { ITransaction } from './i-transaction';
2import { StompConfig } from './stomp-config';
3import { StompHeaders } from './stomp-headers';
4import { StompSubscription } from './stomp-subscription';
5import { ActivationState, closeEventCallbackType, debugFnType, frameCallbackType, IPublishParams, IStompSocket, messageCallbackType, wsErrorCallbackType } from './types';
6import { Versions } from './versions';
7/**
8 * STOMP Client Class.
9 *
10 * Part of `@stomp/stompjs`.
11 */
12export declare class Client {
13 /**
14 * 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"`.
16 *
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}.
22 */
23 brokerURL: string;
24 /**
25 * STOMP versions to attempt during STOMP handshake. By default versions `1.0`, `1.1`, and `1.2` are attempted.
26 *
27 * Example:
28 * ```javascript
29 * // Try only versions 1.0 and 1.1
30 * client.stompVersions = new Versions(['1.0', '1.1'])
31 * ```
32 */
33 stompVersions: Versions;
34 /**
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}.
39 *
40 * If both this and [Client#brokerURL]{@link Client#brokerURL} are set, this will be used.
41 *
42 * Example:
43 * ```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 * };
53 * ```
54 */
55 webSocketFactory: () => IStompSocket;
56 /**
57 * Will retry if Stomp connection is not established in specified milliseconds.
58 * Default 0, which implies wait for ever.
59 */
60 connectionTimeout: number;
61 private _connectionWatcher;
62 /**
63 * automatically reconnect with delay in milliseconds, set to 0 to disable.
64 */
65 reconnectDelay: number;
66 /**
67 * Incoming heartbeat interval in milliseconds. Set to 0 to disable.
68 */
69 heartbeatIncoming: number;
70 /**
71 * Outgoing heartbeat interval in milliseconds. Set to 0 to disable.
72 */
73 heartbeatOutgoing: number;
74 /**
75 * This switches on a non standard behavior while sending WebSocket packets.
76 * It splits larger (text) packets into chunks of [maxWebSocketChunkSize]{@link Client#maxWebSocketChunkSize}.
77 * Only Java Spring brokers seems to use this mode.
78 *
79 * WebSockets, by itself, split large (text) packets,
80 * so it is not needed with a truly compliant STOMP/WebSocket broker.
81 * Actually setting it for such broker will cause large messages to fail.
82 *
83 * `false` by default.
84 *
85 * Binary frames are never split.
86 */
87 splitLargeFrames: boolean;
88 /**
89 * See [splitLargeFrames]{@link Client#splitLargeFrames}.
90 * This has no effect if [splitLargeFrames]{@link Client#splitLargeFrames} is `false`.
91 */
92 maxWebSocketChunkSize: number;
93 /**
94 * Usually the
95 * [type of WebSocket frame]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send#Parameters}
96 * is automatically decided by type of the payload.
97 * Default is `false`, which should work with all compliant brokers.
98 *
99 * Set this flag to force binary frames.
100 */
101 forceBinaryWSFrames: boolean;
102 /**
103 * A bug in ReactNative chops a string on occurrence of a NULL.
104 * See issue [https://github.com/stomp-js/stompjs/issues/89]{@link https://github.com/stomp-js/stompjs/issues/89}.
105 * This makes incoming WebSocket messages invalid STOMP packets.
106 * Setting this flag attempts to reverse the damage by appending a NULL.
107 * If the broker splits a large message into multiple WebSocket messages,
108 * this flag will cause data loss and abnormal termination of connection.
109 *
110 * This is not an ideal solution, but a stop gap until the underlying issue is fixed at ReactNative library.
111 */
112 appendMissingNULLonIncoming: boolean;
113 /**
114 * Underlying WebSocket instance, READONLY.
115 */
116 readonly webSocket: IStompSocket;
117 /**
118 * Connection headers, important keys - `login`, `passcode`, `host`.
119 * Though STOMP 1.2 standard marks these keys to be present, check your broker documentation for
120 * details specific to your broker.
121 */
122 connectHeaders: StompHeaders;
123 /**
124 * Disconnection headers.
125 */
126 disconnectHeaders: StompHeaders;
127 private _disconnectHeaders;
128 /**
129 * This function will be called for any unhandled messages.
130 * It is useful for receiving messages sent to RabbitMQ temporary queues.
131 *
132 * It can also get invoked with stray messages while the server is processing
133 * a request to [Client#unsubscribe]{@link Client#unsubscribe}
134 * from an endpoint.
135 *
136 * The actual {@link IMessage} will be passed as parameter to the callback.
137 */
138 onUnhandledMessage: messageCallbackType;
139 /**
140 * STOMP brokers can be requested to notify when an operation is actually completed.
141 * Prefer using [Client#watchForReceipt]{@link Client#watchForReceipt}. See
142 * [Client#watchForReceipt]{@link Client#watchForReceipt} for examples.
143 *
144 * The actual {@link FrameImpl} will be passed as parameter to the callback.
145 */
146 onUnhandledReceipt: frameCallbackType;
147 /**
148 * Will be invoked if {@link FrameImpl} of unknown type is received from the STOMP broker.
149 *
150 * The actual {@link IFrame} will be passed as parameter to the callback.
151 */
152 onUnhandledFrame: frameCallbackType;
153 /**
154 * `true` if there is a active connection with STOMP Broker
155 */
156 readonly connected: boolean;
157 /**
158 * Callback, invoked on before a connection connection to the STOMP broker.
159 *
160 * You can change options on the client, which will impact the immediate connect.
161 * It is valid to call [Client#decativate]{@link Client#deactivate} in this callback.
162 *
163 * As of version 5.1, this callback can be
164 * [async](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
165 * (i.e., it can return a
166 * [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)).
167 * In that case connect will be called only after the Promise is resolved.
168 * This can be used to reliably fetch credentials, access token etc. from some other service
169 * in an asynchronous way.
170 */
171 beforeConnect: () => void | Promise<void>;
172 /**
173 * Callback, invoked on every successful connection to the STOMP broker.
174 *
175 * The actual {@link FrameImpl} will be passed as parameter to the callback.
176 * Sometimes clients will like to use headers from this frame.
177 */
178 onConnect: frameCallbackType;
179 /**
180 * Callback, invoked on every successful disconnection from the STOMP broker. It will not be invoked if
181 * the STOMP broker disconnected due to an error.
182 *
183 * The actual Receipt {@link FrameImpl} acknowledging the DISCONNECT will be passed as parameter to the callback.
184 *
185 * The way STOMP protocol is designed, the connection may close/terminate without the client
186 * receiving the Receipt {@link FrameImpl} acknowledging the DISCONNECT.
187 * You might find [Client#onWebSocketClose]{@link Client#onWebSocketClose} more appropriate to watch
188 * STOMP broker disconnects.
189 */
190 onDisconnect: frameCallbackType;
191 /**
192 * Callback, invoked on an ERROR frame received from the STOMP Broker.
193 * A compliant STOMP Broker will close the connection after this type of frame.
194 * Please check broker specific documentation for exact behavior.
195 *
196 * The actual {@link IFrame} will be passed as parameter to the callback.
197 */
198 onStompError: frameCallbackType;
199 /**
200 * Callback, invoked when underlying WebSocket is closed.
201 *
202 * Actual [CloseEvent]{@link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent}
203 * is passed as parameter to the callback.
204 */
205 onWebSocketClose: closeEventCallbackType;
206 /**
207 * Callback, invoked when underlying WebSocket raises an error.
208 *
209 * Actual [Event]{@link https://developer.mozilla.org/en-US/docs/Web/API/Event}
210 * is passed as parameter to the callback.
211 */
212 onWebSocketError: wsErrorCallbackType;
213 /**
214 * Set it to log the actual raw communication with the broker.
215 * When unset, it logs headers of the parsed frames.
216 *
217 * Change in this effects from next broker reconnect.
218 *
219 * **Caution: this assumes that frames only have valid UTF8 strings.**
220 */
221 logRawCommunication: boolean;
222 /**
223 * By default, debug messages are discarded. To log to `console` following can be used:
224 *
225 * ```javascript
226 * client.debug = function(str) {
227 * console.log(str);
228 * };
229 * ```
230 *
231 * Currently this method does not support levels of log. Be aware that the output can be quite verbose
232 * and may contain sensitive information (like passwords, tokens etc.).
233 */
234 debug: debugFnType;
235 /**
236 * Browsers do not immediately close WebSockets when `.close` is issued.
237 * This may cause reconnection to take a longer on certain type of failures.
238 * In case of incoming heartbeat failure, this experimental flag instructs the library
239 * to discard the socket immediately (even before it is actually closed).
240 */
241 discardWebsocketOnCommFailure: boolean;
242 /**
243 * version of STOMP protocol negotiated with the server, READONLY
244 */
245 readonly connectedVersion: string;
246 private _stompHandler;
247 /**
248 * if the client is active (connected or going to reconnect)
249 */
250 readonly active: boolean;
251 /**
252 * It will be called on state change.
253 *
254 * When deactivating it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
255 */
256 onChangeState: (state: ActivationState) => void;
257 private _changeState;
258 private _resolveSocketClose;
259 /**
260 * Activation state.
261 *
262 * It will usually be ACTIVE or INACTIVE.
263 * When deactivating it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
264 */
265 state: ActivationState;
266 private _reconnector;
267 /**
268 * Create an instance.
269 */
270 constructor(conf?: StompConfig);
271 /**
272 * Update configuration.
273 */
274 configure(conf: StompConfig): void;
275 /**
276 * Initiate the connection with the broker.
277 * If the connection breaks, as per [Client#reconnectDelay]{@link Client#reconnectDelay},
278 * it will keep trying to reconnect.
279 *
280 * Call [Client#deactivate]{@link Client#deactivate} to disconnect and stop reconnection attempts.
281 */
282 activate(): void;
283 private _connect;
284 private _createWebSocket;
285 private _schedule_reconnect;
286 /**
287 * Disconnect if connected and stop auto reconnect loop.
288 * Appropriate callbacks will be invoked if underlying STOMP connection was connected.
289 *
290 * This call is async, it will resolve immediately if there is no underlying active websocket,
291 * otherwise, it will resolve after underlying websocket is properly disposed.
292 *
293 * To reactivate you can call [Client#activate]{@link Client#activate}.
294 */
295 deactivate(): Promise<void>;
296 /**
297 * Force disconnect if there is an active connection by directly closing the underlying WebSocket.
298 * This is different than a normal disconnect where a DISCONNECT sequence is carried out with the broker.
299 * After forcing disconnect, automatic reconnect will be attempted.
300 * To stop further reconnects call [Client#deactivate]{@link Client#deactivate} as well.
301 */
302 forceDisconnect(): void;
303 private _disposeStompHandler;
304 /**
305 * Send a message to a named destination. Refer to your STOMP broker documentation for types
306 * and naming of destinations.
307 *
308 * STOMP protocol specifies and suggests some headers and also allows broker specific headers.
309 *
310 * `body` must be String.
311 * You will need to covert the payload to string in case it is not string (e.g. JSON).
312 *
313 * To send a binary message body use binaryBody parameter. It should be a
314 * [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).
315 * Sometimes brokers may not support binary frames out of the box.
316 * Please check your broker documentation.
317 *
318 * `content-length` header is automatically added to the STOMP Frame sent to the broker.
319 * Set `skipContentLengthHeader` to indicate that `content-length` header should not be added.
320 * For binary messages `content-length` header is always added.
321 *
322 * Caution: The broker will, most likely, report an error and disconnect if message body has NULL octet(s)
323 * and `content-length` header is missing.
324 *
325 * ```javascript
326 * client.publish({destination: "/queue/test", headers: {priority: 9}, body: "Hello, STOMP"});
327 *
328 * // Only destination is mandatory parameter
329 * client.publish({destination: "/queue/test", body: "Hello, STOMP"});
330 *
331 * // Skip content-length header in the frame to the broker
332 * client.publish({"/queue/test", body: "Hello, STOMP", skipContentLengthHeader: true});
333 *
334 * var binaryData = generateBinaryData(); // This need to be of type Uint8Array
335 * // setting content-type header is not mandatory, however a good practice
336 * client.publish({destination: '/topic/special', binaryBody: binaryData,
337 * headers: {'content-type': 'application/octet-stream'}});
338 * ```
339 */
340 publish(params: IPublishParams): void;
341 /**
342 * STOMP brokers may carry out operation asynchronously and allow requesting for acknowledgement.
343 * To request an acknowledgement, a `receipt` header needs to be sent with the actual request.
344 * The value (say receipt-id) for this header needs to be unique for each use. Typically a sequence, a UUID, a
345 * random number or a combination may be used.
346 *
347 * A complaint broker will send a RECEIPT frame when an operation has actually been completed.
348 * The operation needs to be matched based in the value of the receipt-id.
349 *
350 * This method allow watching for a receipt and invoke the callback
351 * when corresponding receipt has been received.
352 *
353 * The actual {@link FrameImpl} will be passed as parameter to the callback.
354 *
355 * Example:
356 * ```javascript
357 * // Subscribing with acknowledgement
358 * let receiptId = randomText();
359 *
360 * client.watchForReceipt(receiptId, function() {
361 * // Will be called after server acknowledges
362 * });
363 *
364 * client.subscribe(TEST.destination, onMessage, {receipt: receiptId});
365 *
366 *
367 * // Publishing with acknowledgement
368 * receiptId = randomText();
369 *
370 * client.watchForReceipt(receiptId, function() {
371 * // Will be called after server acknowledges
372 * });
373 * client.publish({destination: TEST.destination, headers: {receipt: receiptId}, body: msg});
374 * ```
375 */
376 watchForReceipt(receiptId: string, callback: frameCallbackType): void;
377 /**
378 * Subscribe to a STOMP Broker location. The callback will be invoked for each received message with
379 * the {@link IMessage} as argument.
380 *
381 * Note: The library will generate an unique ID if there is none provided in the headers.
382 * To use your own ID, pass it using the headers argument.
383 *
384 * ```javascript
385 * callback = function(message) {
386 * // called when the client receives a STOMP message from the server
387 * if (message.body) {
388 * alert("got message with body " + message.body)
389 * } else {
390 * alert("got empty message");
391 * }
392 * });
393 *
394 * var subscription = client.subscribe("/queue/test", callback);
395 *
396 * // Explicit subscription id
397 * var mySubId = 'my-subscription-id-001';
398 * var subscription = client.subscribe(destination, callback, { id: mySubId });
399 * ```
400 */
401 subscribe(destination: string, callback: messageCallbackType, headers?: StompHeaders): StompSubscription;
402 /**
403 * It is preferable to unsubscribe from a subscription by calling
404 * `unsubscribe()` directly on {@link StompSubscription} returned by `client.subscribe()`:
405 *
406 * ```javascript
407 * var subscription = client.subscribe(destination, onmessage);
408 * // ...
409 * subscription.unsubscribe();
410 * ```
411 *
412 * See: http://stomp.github.com/stomp-specification-1.2.html#UNSUBSCRIBE UNSUBSCRIBE Frame
413 */
414 unsubscribe(id: string, headers?: StompHeaders): void;
415 /**
416 * Start a transaction, the returned {@link ITransaction} has methods - [commit]{@link ITransaction#commit}
417 * and [abort]{@link ITransaction#abort}.
418 *
419 * `transactionId` is optional, if not passed the library will generate it internally.
420 */
421 begin(transactionId?: string): ITransaction;
422 /**
423 * Commit a transaction.
424 *
425 * It is preferable to commit a transaction by calling [commit]{@link ITransaction#commit} directly on
426 * {@link ITransaction} returned by [client.begin]{@link Client#begin}.
427 *
428 * ```javascript
429 * var tx = client.begin(txId);
430 * //...
431 * tx.commit();
432 * ```
433 */
434 commit(transactionId: string): void;
435 /**
436 * Abort a transaction.
437 * It is preferable to abort a transaction by calling [abort]{@link ITransaction#abort} directly on
438 * {@link ITransaction} returned by [client.begin]{@link Client#begin}.
439 *
440 * ```javascript
441 * var tx = client.begin(txId);
442 * //...
443 * tx.abort();
444 * ```
445 */
446 abort(transactionId: string): void;
447 /**
448 * ACK a message. It is preferable to acknowledge a message by calling [ack]{@link IMessage#ack} directly
449 * on the {@link IMessage} handled by a subscription callback:
450 *
451 * ```javascript
452 * var callback = function (message) {
453 * // process the message
454 * // acknowledge it
455 * message.ack();
456 * };
457 * client.subscribe(destination, callback, {'ack': 'client'});
458 * ```
459 */
460 ack(messageId: string, subscriptionId: string, headers?: StompHeaders): void;
461 /**
462 * NACK a message. It is preferable to acknowledge a message by calling [nack]{@link IMessage#nack} directly
463 * on the {@link IMessage} handled by a subscription callback:
464 *
465 * ```javascript
466 * var callback = function (message) {
467 * // process the message
468 * // an error occurs, nack it
469 * message.nack();
470 * };
471 * client.subscribe(destination, callback, {'ack': 'client'});
472 * ```
473 */
474 nack(messageId: string, subscriptionId: string, headers?: StompHeaders): void;
475}