client.d.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. import { ITransaction } from './i-transaction.js';
  2. import { StompConfig } from './stomp-config.js';
  3. import { StompHeaders } from './stomp-headers.js';
  4. import { StompSubscription } from './stomp-subscription.js';
  5. import { ActivationState, closeEventCallbackType, debugFnType, frameCallbackType, IPublishParams, IStompSocket, messageCallbackType, wsErrorCallbackType } from './types.js';
  6. import { Versions } from './versions.js';
  7. /**
  8. * STOMP Client Class.
  9. *
  10. * Part of `@stomp/stompjs`.
  11. */
  12. export 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 | undefined;
  24. /**
  25. * STOMP versions to attempt during STOMP handshake. By default, versions `1.2`, `1.1`, and `1.0` are attempted.
  26. *
  27. * Example:
  28. * ```javascript
  29. * // Try only versions 1.1 and 1.0
  30. * client.stompVersions = new Versions(['1.1', '1.0'])
  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) | undefined;
  56. /**
  57. * Will retry if Stomp connection is not established in specified milliseconds.
  58. * Default 0, which switches off automatic reconnection.
  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 seem to support 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. * Setting it for such a 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. get webSocket(): IStompSocket | undefined;
  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. get disconnectHeaders(): StompHeaders;
  127. set disconnectHeaders(value: StompHeaders);
  128. private _disconnectHeaders;
  129. /**
  130. * This function will be called for any unhandled messages.
  131. * It is useful for receiving messages sent to RabbitMQ temporary queues.
  132. *
  133. * It can also get invoked with stray messages while the server is processing
  134. * a request to [Client#unsubscribe]{@link Client#unsubscribe}
  135. * from an endpoint.
  136. *
  137. * The actual {@link IMessage} will be passed as parameter to the callback.
  138. */
  139. onUnhandledMessage: messageCallbackType;
  140. /**
  141. * STOMP brokers can be requested to notify when an operation is actually completed.
  142. * Prefer using [Client#watchForReceipt]{@link Client#watchForReceipt}. See
  143. * [Client#watchForReceipt]{@link Client#watchForReceipt} for examples.
  144. *
  145. * The actual {@link IFrame} will be passed as parameter to the callback.
  146. */
  147. onUnhandledReceipt: frameCallbackType;
  148. /**
  149. * Will be invoked if {@link IFrame} of an unknown type is received from the STOMP broker.
  150. *
  151. * The actual {@link IFrame} will be passed as parameter to the callback.
  152. */
  153. onUnhandledFrame: frameCallbackType;
  154. /**
  155. * `true` if there is an active connection to STOMP Broker
  156. */
  157. get connected(): boolean;
  158. /**
  159. * Callback, invoked on before a connection to the STOMP broker.
  160. *
  161. * You can change options on the client, which will impact the immediate connecting.
  162. * It is valid to call [Client#decativate]{@link Client#deactivate} in this callback.
  163. *
  164. * As of version 5.1, this callback can be
  165. * [async](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
  166. * (i.e., it can return a
  167. * [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)).
  168. * In that case, connect will be called only after the Promise is resolved.
  169. * This can be used to reliably fetch credentials, access token etc. from some other service
  170. * in an asynchronous way.
  171. */
  172. beforeConnect: () => void | Promise<void>;
  173. /**
  174. * Callback, invoked on every successful connection to the STOMP broker.
  175. *
  176. * The actual {@link IFrame} will be passed as parameter to the callback.
  177. * Sometimes clients will like to use headers from this frame.
  178. */
  179. onConnect: frameCallbackType;
  180. /**
  181. * Callback, invoked on every successful disconnection from the STOMP broker. It will not be invoked if
  182. * the STOMP broker disconnected due to an error.
  183. *
  184. * The actual Receipt {@link IFrame} acknowledging the DISCONNECT will be passed as parameter to the callback.
  185. *
  186. * The way STOMP protocol is designed, the connection may close/terminate without the client
  187. * receiving the Receipt {@link IFrame} acknowledging the DISCONNECT.
  188. * You might find [Client#onWebSocketClose]{@link Client#onWebSocketClose} more appropriate to watch
  189. * STOMP broker disconnects.
  190. */
  191. onDisconnect: frameCallbackType;
  192. /**
  193. * Callback, invoked on an ERROR frame received from the STOMP Broker.
  194. * A compliant STOMP Broker will close the connection after this type of frame.
  195. * Please check broker specific documentation for exact behavior.
  196. *
  197. * The actual {@link IFrame} will be passed as parameter to the callback.
  198. */
  199. onStompError: frameCallbackType;
  200. /**
  201. * Callback, invoked when underlying WebSocket is closed.
  202. *
  203. * Actual [CloseEvent]{@link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent}
  204. * is passed as parameter to the callback.
  205. */
  206. onWebSocketClose: closeEventCallbackType;
  207. /**
  208. * Callback, invoked when underlying WebSocket raises an error.
  209. *
  210. * Actual [Event]{@link https://developer.mozilla.org/en-US/docs/Web/API/Event}
  211. * is passed as parameter to the callback.
  212. */
  213. onWebSocketError: wsErrorCallbackType;
  214. /**
  215. * Set it to log the actual raw communication with the broker.
  216. * When unset, it logs headers of the parsed frames.
  217. *
  218. * Changes effect from the next broker reconnect.
  219. *
  220. * **Caution: this assumes that frames only have valid UTF8 strings.**
  221. */
  222. logRawCommunication: boolean;
  223. /**
  224. * By default, debug messages are discarded. To log to `console` following can be used:
  225. *
  226. * ```javascript
  227. * client.debug = function(str) {
  228. * console.log(str);
  229. * };
  230. * ```
  231. *
  232. * Currently this method does not support levels of log. Be aware that the
  233. * output can be quite verbose
  234. * and may contain sensitive information (like passwords, tokens etc.).
  235. */
  236. debug: debugFnType;
  237. /**
  238. * Browsers do not immediately close WebSockets when `.close` is issued.
  239. * This may cause reconnection to take a significantly long time in case
  240. * of some types of failures.
  241. * In case of incoming heartbeat failure, this experimental flag instructs
  242. * the library to discard the socket immediately
  243. * (even before it is actually closed).
  244. */
  245. discardWebsocketOnCommFailure: boolean;
  246. /**
  247. * version of STOMP protocol negotiated with the server, READONLY
  248. */
  249. get connectedVersion(): string | undefined;
  250. private _stompHandler;
  251. /**
  252. * if the client is active (connected or going to reconnect)
  253. */
  254. get active(): boolean;
  255. /**
  256. * It will be called on state change.
  257. *
  258. * When deactivating, it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
  259. */
  260. onChangeState: (state: ActivationState) => void;
  261. private _changeState;
  262. /**
  263. * Activation state.
  264. *
  265. * It will usually be ACTIVE or INACTIVE.
  266. * When deactivating, it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
  267. */
  268. state: ActivationState;
  269. private _reconnector;
  270. /**
  271. * Create an instance.
  272. */
  273. constructor(conf?: StompConfig);
  274. /**
  275. * Update configuration.
  276. */
  277. configure(conf: StompConfig): void;
  278. /**
  279. * Initiate the connection with the broker.
  280. * If the connection breaks, as per [Client#reconnectDelay]{@link Client#reconnectDelay},
  281. * it will keep trying to reconnect.
  282. *
  283. * Call [Client#deactivate]{@link Client#deactivate} to disconnect and stop reconnection attempts.
  284. */
  285. activate(): void;
  286. private _connect;
  287. private _createWebSocket;
  288. private _schedule_reconnect;
  289. /**
  290. * Disconnect if connected and stop auto reconnect loop.
  291. * Appropriate callbacks will be invoked if there is an underlying STOMP connection.
  292. *
  293. * This call is async. It will resolve immediately if there is no underlying active websocket,
  294. * otherwise, it will resolve after the underlying websocket is properly disposed of.
  295. *
  296. * It is not an error to invoke this method more than once.
  297. * Each of those would resolve on completion of deactivation.
  298. *
  299. * To reactivate, you can call [Client#activate]{@link Client#activate}.
  300. *
  301. * Experimental: pass `force: true` to immediately discard the underlying connection.
  302. * This mode will skip both the STOMP and the Websocket shutdown sequences.
  303. * In some cases, browsers take a long time in the Websocket shutdown
  304. * if the underlying connection had gone stale.
  305. * Using this mode can speed up.
  306. * When this mode is used, the actual Websocket may linger for a while
  307. * and the broker may not realize that the connection is no longer in use.
  308. *
  309. * It is possible to invoke this method initially without the `force` option
  310. * and subsequently, say after a wait, with the `force` option.
  311. */
  312. deactivate(options?: {
  313. force?: boolean;
  314. }): Promise<void>;
  315. /**
  316. * Force disconnect if there is an active connection by directly closing the underlying WebSocket.
  317. * This is different from a normal disconnect where a DISCONNECT sequence is carried out with the broker.
  318. * After forcing disconnect, automatic reconnect will be attempted.
  319. * To stop further reconnects call [Client#deactivate]{@link Client#deactivate} as well.
  320. */
  321. forceDisconnect(): void;
  322. private _disposeStompHandler;
  323. /**
  324. * Send a message to a named destination. Refer to your STOMP broker documentation for types
  325. * and naming of destinations.
  326. *
  327. * STOMP protocol specifies and suggests some headers and also allows broker-specific headers.
  328. *
  329. * `body` must be String.
  330. * You will need to covert the payload to string in case it is not string (e.g. JSON).
  331. *
  332. * To send a binary message body, use `binaryBody` parameter. It should be a
  333. * [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).
  334. * Sometimes brokers may not support binary frames out of the box.
  335. * Please check your broker documentation.
  336. *
  337. * `content-length` header is automatically added to the STOMP Frame sent to the broker.
  338. * Set `skipContentLengthHeader` to indicate that `content-length` header should not be added.
  339. * For binary messages, `content-length` header is always added.
  340. *
  341. * Caution: The broker will, most likely, report an error and disconnect
  342. * if the message body has NULL octet(s) and `content-length` header is missing.
  343. *
  344. * ```javascript
  345. * client.publish({destination: "/queue/test", headers: {priority: 9}, body: "Hello, STOMP"});
  346. *
  347. * // Only destination is mandatory parameter
  348. * client.publish({destination: "/queue/test", body: "Hello, STOMP"});
  349. *
  350. * // Skip content-length header in the frame to the broker
  351. * client.publish({"/queue/test", body: "Hello, STOMP", skipContentLengthHeader: true});
  352. *
  353. * var binaryData = generateBinaryData(); // This need to be of type Uint8Array
  354. * // setting content-type header is not mandatory, however a good practice
  355. * client.publish({destination: '/topic/special', binaryBody: binaryData,
  356. * headers: {'content-type': 'application/octet-stream'}});
  357. * ```
  358. */
  359. publish(params: IPublishParams): void;
  360. private _checkConnection;
  361. /**
  362. * STOMP brokers may carry out operation asynchronously and allow requesting for acknowledgement.
  363. * To request an acknowledgement, a `receipt` header needs to be sent with the actual request.
  364. * The value (say receipt-id) for this header needs to be unique for each use.
  365. * Typically, a sequence, a UUID, a random number or a combination may be used.
  366. *
  367. * A complaint broker will send a RECEIPT frame when an operation has actually been completed.
  368. * The operation needs to be matched based on the value of the receipt-id.
  369. *
  370. * This method allows watching for a receipt and invoking the callback
  371. * when the corresponding receipt has been received.
  372. *
  373. * The actual {@link IFrame} will be passed as parameter to the callback.
  374. *
  375. * Example:
  376. * ```javascript
  377. * // Subscribing with acknowledgement
  378. * let receiptId = randomText();
  379. *
  380. * client.watchForReceipt(receiptId, function() {
  381. * // Will be called after server acknowledges
  382. * });
  383. *
  384. * client.subscribe(TEST.destination, onMessage, {receipt: receiptId});
  385. *
  386. *
  387. * // Publishing with acknowledgement
  388. * receiptId = randomText();
  389. *
  390. * client.watchForReceipt(receiptId, function() {
  391. * // Will be called after server acknowledges
  392. * });
  393. * client.publish({destination: TEST.destination, headers: {receipt: receiptId}, body: msg});
  394. * ```
  395. */
  396. watchForReceipt(receiptId: string, callback: frameCallbackType): void;
  397. /**
  398. * Subscribe to a STOMP Broker location. The callback will be invoked for each
  399. * received message with the {@link IMessage} as argument.
  400. *
  401. * Note: The library will generate a unique ID if there is none provided in the headers.
  402. * To use your own ID, pass it using the `headers` argument.
  403. *
  404. * ```javascript
  405. * callback = function(message) {
  406. * // called when the client receives a STOMP message from the server
  407. * if (message.body) {
  408. * alert("got message with body " + message.body)
  409. * } else {
  410. * alert("got empty message");
  411. * }
  412. * });
  413. *
  414. * var subscription = client.subscribe("/queue/test", callback);
  415. *
  416. * // Explicit subscription id
  417. * var mySubId = 'my-subscription-id-001';
  418. * var subscription = client.subscribe(destination, callback, { id: mySubId });
  419. * ```
  420. */
  421. subscribe(destination: string, callback: messageCallbackType, headers?: StompHeaders): StompSubscription;
  422. /**
  423. * It is preferable to unsubscribe from a subscription by calling
  424. * `unsubscribe()` directly on {@link StompSubscription} returned by `client.subscribe()`:
  425. *
  426. * ```javascript
  427. * var subscription = client.subscribe(destination, onmessage);
  428. * // ...
  429. * subscription.unsubscribe();
  430. * ```
  431. *
  432. * See: https://stomp.github.com/stomp-specification-1.2.html#UNSUBSCRIBE UNSUBSCRIBE Frame
  433. */
  434. unsubscribe(id: string, headers?: StompHeaders): void;
  435. /**
  436. * Start a transaction, the returned {@link ITransaction} has methods - [commit]{@link ITransaction#commit}
  437. * and [abort]{@link ITransaction#abort}.
  438. *
  439. * `transactionId` is optional, if not passed the library will generate it internally.
  440. */
  441. begin(transactionId?: string): ITransaction;
  442. /**
  443. * Commit a transaction.
  444. *
  445. * It is preferable to commit a transaction by calling [commit]{@link ITransaction#commit} directly on
  446. * {@link ITransaction} returned by [client.begin]{@link Client#begin}.
  447. *
  448. * ```javascript
  449. * var tx = client.begin(txId);
  450. * //...
  451. * tx.commit();
  452. * ```
  453. */
  454. commit(transactionId: string): void;
  455. /**
  456. * Abort a transaction.
  457. * It is preferable to abort a transaction by calling [abort]{@link ITransaction#abort} directly on
  458. * {@link ITransaction} returned by [client.begin]{@link Client#begin}.
  459. *
  460. * ```javascript
  461. * var tx = client.begin(txId);
  462. * //...
  463. * tx.abort();
  464. * ```
  465. */
  466. abort(transactionId: string): void;
  467. /**
  468. * ACK a message. It is preferable to acknowledge a message by calling [ack]{@link IMessage#ack} directly
  469. * on the {@link IMessage} handled by a subscription callback:
  470. *
  471. * ```javascript
  472. * var callback = function (message) {
  473. * // process the message
  474. * // acknowledge it
  475. * message.ack();
  476. * };
  477. * client.subscribe(destination, callback, {'ack': 'client'});
  478. * ```
  479. */
  480. ack(messageId: string, subscriptionId: string, headers?: StompHeaders): void;
  481. /**
  482. * NACK a message. It is preferable to acknowledge a message by calling [nack]{@link IMessage#nack} directly
  483. * on the {@link IMessage} handled by a subscription callback:
  484. *
  485. * ```javascript
  486. * var callback = function (message) {
  487. * // process the message
  488. * // an error occurs, nack it
  489. * message.nack();
  490. * };
  491. * client.subscribe(destination, callback, {'ack': 'client'});
  492. * ```
  493. */
  494. nack(messageId: string, subscriptionId: string, headers?: StompHeaders): void;
  495. }