@aws-amplify/pubsub 6.0.1-api-v6-models.9351bcf.0 → 6.0.1-api-v6-models.891fe0d.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.
@@ -3,25 +3,25 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.MqttOverWS = exports.mqttTopicMatch = void 0;
6
- var tslib_1 = require("tslib");
6
+ const tslib_1 = require("tslib");
7
7
  // @ts-ignore
8
- var Paho = tslib_1.__importStar(require("../vendor/paho-mqtt"));
9
- var rxjs_1 = require("rxjs");
10
- var PubSub_1 = require("./PubSub");
11
- var PubSub_2 = require("../types/PubSub");
12
- var core_1 = require("@aws-amplify/core");
13
- var utils_1 = require("@aws-amplify/core/internals/utils");
14
- var ConnectionStateMonitor_1 = require("../utils/ConnectionStateMonitor");
15
- var ReconnectionMonitor_1 = require("../utils/ReconnectionMonitor");
16
- var constants_1 = require("./constants");
17
- var logger = new core_1.ConsoleLogger('MqttOverWS');
8
+ const Paho = tslib_1.__importStar(require("../vendor/paho-mqtt"));
9
+ const rxjs_1 = require("rxjs");
10
+ const PubSub_1 = require("./PubSub");
11
+ const PubSub_2 = require("../types/PubSub");
12
+ const core_1 = require("@aws-amplify/core");
13
+ const utils_1 = require("@aws-amplify/core/internals/utils");
14
+ const ConnectionStateMonitor_1 = require("../utils/ConnectionStateMonitor");
15
+ const ReconnectionMonitor_1 = require("../utils/ReconnectionMonitor");
16
+ const constants_1 = require("./constants");
17
+ const logger = new core_1.ConsoleLogger('MqttOverWS');
18
18
  function mqttTopicMatch(filter, topic) {
19
- var filterArray = filter.split('/');
20
- var length = filterArray.length;
21
- var topicArray = topic.split('/');
22
- for (var i = 0; i < length; ++i) {
23
- var left = filterArray[i];
24
- var right = topicArray[i];
19
+ const filterArray = filter.split('/');
20
+ const length = filterArray.length;
21
+ const topicArray = topic.split('/');
22
+ for (let i = 0; i < length; ++i) {
23
+ const left = filterArray[i];
24
+ const right = topicArray[i];
25
25
  if (left === '#')
26
26
  return topicArray.length >= length;
27
27
  if (left !== '+' && left !== right)
@@ -30,369 +30,245 @@ function mqttTopicMatch(filter, topic) {
30
30
  return length === topicArray.length;
31
31
  }
32
32
  exports.mqttTopicMatch = mqttTopicMatch;
33
- var ClientsQueue = /** @class */ (function () {
34
- function ClientsQueue() {
33
+ class ClientsQueue {
34
+ constructor() {
35
35
  this.promises = new Map();
36
36
  }
37
- ClientsQueue.prototype.get = function (clientId, clientFactory) {
38
- return tslib_1.__awaiter(this, void 0, void 0, function () {
39
- var cachedPromise, newPromise;
40
- var _this = this;
41
- return tslib_1.__generator(this, function (_a) {
42
- cachedPromise = this.promises.get(clientId);
43
- if (cachedPromise)
44
- return [2 /*return*/, cachedPromise];
45
- if (clientFactory) {
46
- newPromise = clientFactory(clientId);
47
- this.promises.set(clientId, newPromise);
48
- newPromise.catch(function () { return _this.promises.delete(clientId); });
49
- return [2 /*return*/, newPromise];
50
- }
51
- return [2 /*return*/, undefined];
52
- });
53
- });
54
- };
55
- Object.defineProperty(ClientsQueue.prototype, "allClients", {
56
- get: function () {
57
- return Array.from(this.promises.keys());
58
- },
59
- enumerable: false,
60
- configurable: true
61
- });
62
- ClientsQueue.prototype.remove = function (clientId) {
37
+ async get(clientId, clientFactory) {
38
+ const cachedPromise = this.promises.get(clientId);
39
+ if (cachedPromise)
40
+ return cachedPromise;
41
+ if (clientFactory) {
42
+ const newPromise = clientFactory(clientId);
43
+ this.promises.set(clientId, newPromise);
44
+ newPromise.catch(() => this.promises.delete(clientId));
45
+ return newPromise;
46
+ }
47
+ return undefined;
48
+ }
49
+ get allClients() {
50
+ return Array.from(this.promises.keys());
51
+ }
52
+ remove(clientId) {
63
53
  this.promises.delete(clientId);
64
- };
65
- return ClientsQueue;
66
- }());
67
- var dispatchPubSubEvent = function (payload) {
54
+ }
55
+ }
56
+ const dispatchPubSubEvent = (payload) => {
68
57
  core_1.Hub.dispatch('pubsub', payload, 'PubSub', constants_1.AMPLIFY_SYMBOL);
69
58
  };
70
- var topicSymbol = typeof Symbol !== 'undefined' ? Symbol('topic') : '@@topic';
71
- var MqttOverWS = /** @class */ (function (_super) {
72
- tslib_1.__extends(MqttOverWS, _super);
73
- function MqttOverWS(options) {
74
- if (options === void 0) { options = {}; }
75
- var _this = _super.call(this, tslib_1.__assign(tslib_1.__assign({}, options), { clientId: options.clientId || (0, utils_1.amplifyUuid)() })) || this;
76
- _this._clientsQueue = new ClientsQueue();
77
- _this.connectionStateMonitor = new ConnectionStateMonitor_1.ConnectionStateMonitor();
78
- _this.reconnectionMonitor = new ReconnectionMonitor_1.ReconnectionMonitor();
79
- _this._topicObservers = new Map();
80
- _this._clientIdObservers = new Map();
59
+ const topicSymbol = typeof Symbol !== 'undefined' ? Symbol('topic') : '@@topic';
60
+ class MqttOverWS extends PubSub_1.AbstractPubSub {
61
+ constructor(options = {}) {
62
+ super({ ...options, clientId: options.clientId || (0, utils_1.amplifyUuid)() });
63
+ this._clientsQueue = new ClientsQueue();
64
+ this.connectionStateMonitor = new ConnectionStateMonitor_1.ConnectionStateMonitor();
65
+ this.reconnectionMonitor = new ReconnectionMonitor_1.ReconnectionMonitor();
66
+ this._topicObservers = new Map();
67
+ this._clientIdObservers = new Map();
81
68
  // Monitor the connection health state and pass changes along to Hub
82
- _this.connectionStateMonitor.connectionStateObservable.subscribe(function (connectionStateChange) {
69
+ this.connectionStateMonitor.connectionStateObservable.subscribe(connectionStateChange => {
83
70
  dispatchPubSubEvent({
84
71
  event: constants_1.CONNECTION_STATE_CHANGE,
85
72
  data: {
86
- provider: _this,
73
+ provider: this,
87
74
  connectionState: connectionStateChange,
88
75
  },
89
- message: "Connection state is ".concat(connectionStateChange),
76
+ message: `Connection state is ${connectionStateChange}`,
90
77
  });
91
- _this.connectionState = connectionStateChange;
78
+ this.connectionState = connectionStateChange;
92
79
  // Trigger reconnection when the connection is disrupted
93
80
  if (connectionStateChange === PubSub_2.ConnectionState.ConnectionDisrupted) {
94
- _this.reconnectionMonitor.record(ReconnectionMonitor_1.ReconnectEvent.START_RECONNECT);
81
+ this.reconnectionMonitor.record(ReconnectionMonitor_1.ReconnectEvent.START_RECONNECT);
95
82
  }
96
83
  else if (connectionStateChange !== PubSub_2.ConnectionState.Connecting) {
97
84
  // Trigger connected to halt reconnection attempts
98
- _this.reconnectionMonitor.record(ReconnectionMonitor_1.ReconnectEvent.HALT_RECONNECT);
85
+ this.reconnectionMonitor.record(ReconnectionMonitor_1.ReconnectEvent.HALT_RECONNECT);
99
86
  }
100
87
  });
101
- return _this;
102
88
  }
103
- Object.defineProperty(MqttOverWS.prototype, "clientId", {
104
- get: function () {
105
- return this.options.clientId;
106
- },
107
- enumerable: false,
108
- configurable: true
109
- });
110
- Object.defineProperty(MqttOverWS.prototype, "endpoint", {
111
- get: function () {
112
- return Promise.resolve(this.options.endpoint);
113
- },
114
- enumerable: false,
115
- configurable: true
116
- });
117
- Object.defineProperty(MqttOverWS.prototype, "clientsQueue", {
118
- get: function () {
119
- return this._clientsQueue;
120
- },
121
- enumerable: false,
122
- configurable: true
123
- });
124
- Object.defineProperty(MqttOverWS.prototype, "isSSLEnabled", {
125
- get: function () {
126
- return !this.options['aws_appsync_dangerously_connect_to_http_endpoint_for_testing'];
127
- },
128
- enumerable: false,
129
- configurable: true
130
- });
131
- MqttOverWS.prototype.onDisconnect = function (_a) {
132
- var clientId = _a.clientId, errorCode = _a.errorCode, args = tslib_1.__rest(_a, ["clientId", "errorCode"]);
89
+ get clientId() {
90
+ return this.options.clientId;
91
+ }
92
+ get endpoint() {
93
+ return Promise.resolve(this.options.endpoint);
94
+ }
95
+ get clientsQueue() {
96
+ return this._clientsQueue;
97
+ }
98
+ get isSSLEnabled() {
99
+ return !this.options['aws_appsync_dangerously_connect_to_http_endpoint_for_testing'];
100
+ }
101
+ onDisconnect({ clientId, errorCode, ...args }) {
133
102
  if (errorCode !== 0) {
134
- logger.warn(clientId, JSON.stringify(tslib_1.__assign({ errorCode: errorCode }, args), null, 2));
103
+ logger.warn(clientId, JSON.stringify({ errorCode, ...args }, null, 2));
135
104
  if (!clientId) {
136
105
  return;
137
106
  }
138
- var clientIdObservers = this._clientIdObservers.get(clientId);
107
+ const clientIdObservers = this._clientIdObservers.get(clientId);
139
108
  if (!clientIdObservers) {
140
109
  return;
141
110
  }
142
111
  this.disconnect(clientId);
143
112
  }
144
- };
145
- MqttOverWS.prototype.newClient = function (_a) {
146
- var url = _a.url, clientId = _a.clientId;
147
- return tslib_1.__awaiter(this, void 0, void 0, function () {
148
- var client, connected;
149
- var _this = this;
150
- return tslib_1.__generator(this, function (_b) {
151
- switch (_b.label) {
152
- case 0:
153
- logger.debug('Creating new MQTT client', clientId);
154
- this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.OPENING_CONNECTION);
155
- client = new Paho.Client(url, clientId);
156
- client.onMessageArrived = function (_a) {
157
- var topic = _a.destinationName, msg = _a.payloadString;
158
- _this._onMessage(topic, msg);
159
- };
160
- client.onConnectionLost = function (_a) {
161
- var errorCode = _a.errorCode, args = tslib_1.__rest(_a, ["errorCode"]);
162
- _this.onDisconnect(tslib_1.__assign({ clientId: clientId, errorCode: errorCode }, args));
163
- _this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
164
- };
165
- return [4 /*yield*/, new Promise(function (resolve, reject) {
166
- client.connect({
167
- useSSL: _this.isSSLEnabled,
168
- mqttVersion: 3,
169
- onSuccess: function () { return resolve(true); },
170
- onFailure: function () {
171
- if (clientId)
172
- _this._clientsQueue.remove(clientId);
173
- _this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
174
- resolve(false);
175
- },
176
- });
177
- })];
178
- case 1:
179
- connected = _b.sent();
180
- if (connected) {
181
- this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CONNECTION_ESTABLISHED);
182
- }
183
- return [2 /*return*/, client];
184
- }
185
- });
186
- });
187
- };
188
- MqttOverWS.prototype.connect = function (clientId, options) {
189
- if (options === void 0) { options = {}; }
190
- return tslib_1.__awaiter(this, void 0, void 0, function () {
191
- var _this = this;
192
- return tslib_1.__generator(this, function (_a) {
193
- switch (_a.label) {
194
- case 0: return [4 /*yield*/, this.clientsQueue.get(clientId, function (clientId) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
195
- var client;
196
- return tslib_1.__generator(this, function (_a) {
197
- switch (_a.label) {
198
- case 0: return [4 /*yield*/, this.newClient(tslib_1.__assign(tslib_1.__assign({}, options), { clientId: clientId }))];
199
- case 1:
200
- client = _a.sent();
201
- if (client) {
202
- // Once connected, subscribe to all topics registered observers
203
- this._topicObservers.forEach(function (_value, key) {
204
- client.subscribe(key);
205
- });
206
- }
207
- return [2 /*return*/, client];
208
- }
209
- });
210
- }); })];
211
- case 1: return [2 /*return*/, _a.sent()];
212
- }
213
- });
214
- });
215
- };
216
- MqttOverWS.prototype.disconnect = function (clientId) {
217
- return tslib_1.__awaiter(this, void 0, void 0, function () {
218
- var client;
219
- return tslib_1.__generator(this, function (_a) {
220
- switch (_a.label) {
221
- case 0: return [4 /*yield*/, this.clientsQueue.get(clientId)];
222
- case 1:
223
- client = _a.sent();
224
- if (client && client.isConnected()) {
225
- client.disconnect();
226
- }
227
- this.clientsQueue.remove(clientId);
228
- this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
229
- return [2 /*return*/];
230
- }
113
+ }
114
+ async newClient({ url, clientId }) {
115
+ logger.debug('Creating new MQTT client', clientId);
116
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.OPENING_CONNECTION);
117
+ // @ts-ignore
118
+ const client = new Paho.Client(url, clientId);
119
+ client.onMessageArrived = ({ destinationName: topic, payloadString: msg, }) => {
120
+ this._onMessage(topic, msg);
121
+ };
122
+ client.onConnectionLost = ({ errorCode, ...args }) => {
123
+ this.onDisconnect({ clientId, errorCode, ...args });
124
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
125
+ };
126
+ const connected = await new Promise((resolve, reject) => {
127
+ client.connect({
128
+ useSSL: this.isSSLEnabled,
129
+ mqttVersion: 3,
130
+ onSuccess: () => resolve(true),
131
+ onFailure: () => {
132
+ if (clientId)
133
+ this._clientsQueue.remove(clientId);
134
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
135
+ resolve(false);
136
+ },
231
137
  });
232
138
  });
233
- };
234
- MqttOverWS.prototype.publish = function (topics, msg) {
235
- return tslib_1.__awaiter(this, void 0, void 0, function () {
236
- var targetTopics, message, client;
237
- return tslib_1.__generator(this, function (_a) {
238
- switch (_a.label) {
239
- case 0:
240
- targetTopics = [].concat(topics);
241
- message = JSON.stringify(msg);
242
- return [4 /*yield*/, this.clientsQueue.get(this.clientId)];
243
- case 1:
244
- client = _a.sent();
245
- if (client) {
246
- logger.debug('Publishing to topic(s)', targetTopics.join(','), message);
247
- targetTopics.forEach(function (topic) { return client.send(topic, message); });
248
- }
249
- else {
250
- logger.debug('Publishing to topic(s) failed', targetTopics.join(','), message);
251
- }
252
- return [2 /*return*/];
253
- }
254
- });
139
+ if (connected) {
140
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CONNECTION_ESTABLISHED);
141
+ }
142
+ return client;
143
+ }
144
+ async connect(clientId, options = {}) {
145
+ return await this.clientsQueue.get(clientId, async (clientId) => {
146
+ const client = await this.newClient({ ...options, clientId });
147
+ if (client) {
148
+ // Once connected, subscribe to all topics registered observers
149
+ this._topicObservers.forEach((_value, key) => {
150
+ client.subscribe(key);
151
+ });
152
+ }
153
+ return client;
255
154
  });
256
- };
257
- MqttOverWS.prototype._onMessage = function (topic, msg) {
155
+ }
156
+ async disconnect(clientId) {
157
+ const client = await this.clientsQueue.get(clientId);
158
+ if (client && client.isConnected()) {
159
+ client.disconnect();
160
+ }
161
+ this.clientsQueue.remove(clientId);
162
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
163
+ }
164
+ async publish({ topics, message }) {
165
+ const targetTopics = [].concat(topics);
166
+ const msg = JSON.stringify(message);
167
+ const client = await this.clientsQueue.get(this.clientId);
168
+ if (client) {
169
+ logger.debug('Publishing to topic(s)', targetTopics.join(','), message);
170
+ targetTopics.forEach(topic => client.send(topic, msg));
171
+ }
172
+ else {
173
+ logger.debug('Publishing to topic(s) failed', targetTopics.join(','), message);
174
+ }
175
+ }
176
+ _onMessage(topic, msg) {
258
177
  try {
259
- var matchedTopicObservers_1 = [];
260
- this._topicObservers.forEach(function (observerForTopic, observerTopic) {
178
+ const matchedTopicObservers = [];
179
+ this._topicObservers.forEach((observerForTopic, observerTopic) => {
261
180
  if (mqttTopicMatch(observerTopic, topic)) {
262
- matchedTopicObservers_1.push(observerForTopic);
181
+ matchedTopicObservers.push(observerForTopic);
263
182
  }
264
183
  });
265
- var parsedMessage_1 = JSON.parse(msg);
266
- if (typeof parsedMessage_1 === 'object') {
184
+ const parsedMessage = JSON.parse(msg);
185
+ if (typeof parsedMessage === 'object') {
267
186
  // @ts-ignore
268
- parsedMessage_1[topicSymbol] = topic;
187
+ parsedMessage[topicSymbol] = topic;
269
188
  }
270
- matchedTopicObservers_1.forEach(function (observersForTopic) {
271
- observersForTopic.forEach(function (observer) { return observer.next(parsedMessage_1); });
189
+ matchedTopicObservers.forEach(observersForTopic => {
190
+ observersForTopic.forEach(observer => observer.next(parsedMessage));
272
191
  });
273
192
  }
274
193
  catch (error) {
275
194
  logger.warn('Error handling message', error, msg);
276
195
  }
277
- };
278
- MqttOverWS.prototype.subscribe = function (topics, options) {
279
- var _this = this;
280
- if (options === void 0) { options = {}; }
281
- var targetTopics = [].concat(topics);
196
+ }
197
+ subscribe({ topics, options = {}, }) {
198
+ const targetTopics = [].concat(topics);
282
199
  logger.debug('Subscribing to topic(s)', targetTopics.join(','));
283
- var reconnectSubscription;
284
- return new rxjs_1.Observable(function (observer) {
285
- targetTopics.forEach(function (topic) {
200
+ let reconnectSubscription;
201
+ return new rxjs_1.Observable(observer => {
202
+ targetTopics.forEach(topic => {
286
203
  // this._topicObservers is used to notify the observers according to the topic received on the message
287
- var observersForTopic = _this._topicObservers.get(topic);
204
+ let observersForTopic = this._topicObservers.get(topic);
288
205
  if (!observersForTopic) {
289
206
  observersForTopic = new Set();
290
- _this._topicObservers.set(topic, observersForTopic);
207
+ this._topicObservers.set(topic, observersForTopic);
291
208
  }
292
209
  observersForTopic.add(observer);
293
210
  });
294
- var _a = options.clientId, clientId = _a === void 0 ? _this.clientId : _a;
211
+ const { clientId = this.clientId } = options;
295
212
  // this._clientIdObservers is used to close observers when client gets disconnected
296
- var observersForClientId = _this._clientIdObservers.get(clientId);
213
+ let observersForClientId = this._clientIdObservers.get(clientId);
297
214
  if (!observersForClientId) {
298
215
  observersForClientId = new Set();
299
216
  }
300
217
  if (observersForClientId) {
301
218
  observersForClientId.add(observer);
302
- _this._clientIdObservers.set(clientId, observersForClientId);
219
+ this._clientIdObservers.set(clientId, observersForClientId);
303
220
  }
304
- (function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
305
- var getClient;
306
- var _this = this;
307
- return tslib_1.__generator(this, function (_a) {
308
- switch (_a.label) {
309
- case 0:
310
- getClient = function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
311
- var _a, url, _b, client_1, e_1;
312
- return tslib_1.__generator(this, function (_c) {
313
- switch (_c.label) {
314
- case 0:
315
- _c.trys.push([0, 5, , 6]);
316
- _a = options.url;
317
- if (!(_a === void 0)) return [3 /*break*/, 2];
318
- return [4 /*yield*/, this.endpoint];
319
- case 1:
320
- _b = _c.sent();
321
- return [3 /*break*/, 3];
322
- case 2:
323
- _b = _a;
324
- _c.label = 3;
325
- case 3:
326
- url = _b;
327
- return [4 /*yield*/, this.connect(clientId, { url: url })];
328
- case 4:
329
- client_1 = _c.sent();
330
- if (client_1 !== undefined) {
331
- targetTopics.forEach(function (topic) {
332
- client_1.subscribe(topic);
333
- });
334
- }
335
- return [3 /*break*/, 6];
336
- case 5:
337
- e_1 = _c.sent();
338
- logger.debug('Error forming connection', e_1);
339
- return [3 /*break*/, 6];
340
- case 6: return [2 /*return*/];
341
- }
342
- });
343
- }); };
344
- // Establish the initial connection
345
- return [4 /*yield*/, getClient()];
346
- case 1:
347
- // Establish the initial connection
348
- _a.sent();
349
- // Add an observable to the reconnection list to manage reconnection for this subscription
350
- reconnectSubscription = new rxjs_1.Observable(function (observer) {
351
- _this.reconnectionMonitor.addObserver(observer);
352
- }).subscribe(function () {
353
- getClient();
221
+ (async () => {
222
+ const getClient = async () => {
223
+ try {
224
+ const { url = await this.endpoint } = options;
225
+ const client = await this.connect(clientId, { url });
226
+ if (client !== undefined) {
227
+ targetTopics.forEach(topic => {
228
+ client.subscribe(topic);
354
229
  });
355
- return [2 /*return*/];
230
+ }
356
231
  }
357
- });
358
- }); })();
359
- return function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
360
- var client;
361
- var _this = this;
362
- var _a, _b;
363
- return tslib_1.__generator(this, function (_c) {
364
- switch (_c.label) {
365
- case 0: return [4 /*yield*/, this.clientsQueue.get(clientId)];
366
- case 1:
367
- client = _c.sent();
368
- reconnectSubscription === null || reconnectSubscription === void 0 ? void 0 : reconnectSubscription.unsubscribe();
369
- if (client) {
370
- (_a = this._clientIdObservers.get(clientId)) === null || _a === void 0 ? void 0 : _a.delete(observer);
371
- // No more observers per client => client not needed anymore
372
- if (((_b = this._clientIdObservers.get(clientId)) === null || _b === void 0 ? void 0 : _b.size) === 0) {
373
- this.disconnect(clientId);
374
- this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSING_CONNECTION);
375
- this._clientIdObservers.delete(clientId);
376
- }
377
- targetTopics.forEach(function (topic) {
378
- var observersForTopic = _this._topicObservers.get(topic) ||
379
- new Set();
380
- observersForTopic.delete(observer);
381
- // if no observers exists for the topic, topic should be removed
382
- if (observersForTopic.size === 0) {
383
- _this._topicObservers.delete(topic);
384
- if (client.isConnected()) {
385
- client.unsubscribe(topic);
386
- }
387
- }
388
- });
389
- }
390
- return [2 /*return*/, null];
232
+ catch (e) {
233
+ logger.debug('Error forming connection', e);
391
234
  }
235
+ };
236
+ // Establish the initial connection
237
+ await getClient();
238
+ // Add an observable to the reconnection list to manage reconnection for this subscription
239
+ reconnectSubscription = new rxjs_1.Observable(observer => {
240
+ this.reconnectionMonitor.addObserver(observer);
241
+ }).subscribe(() => {
242
+ getClient();
392
243
  });
393
- }); };
244
+ })();
245
+ return async () => {
246
+ const client = await this.clientsQueue.get(clientId);
247
+ reconnectSubscription?.unsubscribe();
248
+ if (client) {
249
+ this._clientIdObservers.get(clientId)?.delete(observer);
250
+ // No more observers per client => client not needed anymore
251
+ if (this._clientIdObservers.get(clientId)?.size === 0) {
252
+ this.disconnect(clientId);
253
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSING_CONNECTION);
254
+ this._clientIdObservers.delete(clientId);
255
+ }
256
+ targetTopics.forEach(topic => {
257
+ const observersForTopic = this._topicObservers.get(topic) ||
258
+ new Set();
259
+ observersForTopic.delete(observer);
260
+ // if no observers exists for the topic, topic should be removed
261
+ if (observersForTopic.size === 0) {
262
+ this._topicObservers.delete(topic);
263
+ if (client.isConnected()) {
264
+ client.unsubscribe(topic);
265
+ }
266
+ }
267
+ });
268
+ }
269
+ return null;
270
+ };
394
271
  });
395
- };
396
- return MqttOverWS;
397
- }(PubSub_1.AbstractPubSub));
272
+ }
273
+ }
398
274
  exports.MqttOverWS = MqttOverWS;
@@ -1,12 +1,11 @@
1
1
  import { Observable } from 'rxjs';
2
- import { PubSubBase, PubSubOptions, PubSubContent } from '../types/PubSub';
3
- import { CustomUserAgentDetails } from '@aws-amplify/core/internals/utils';
2
+ import { PubSubBase, PubSubOptions, PubSubContent, PublishInput, SubscribeInput } from '../types/PubSub';
4
3
  export declare abstract class AbstractPubSub<T extends PubSubOptions> implements PubSubBase {
5
4
  private _config;
6
5
  constructor(options: T);
7
6
  configure(config: T): T;
8
7
  protected get options(): T;
9
8
  abstract newClient(clientOptions: T): Promise<any>;
10
- abstract publish(topics: string[] | string, msg: PubSubContent, options?: T): void;
11
- abstract subscribe(topics: string[] | string, options?: T, customUserAgentDetails?: CustomUserAgentDetails): Observable<PubSubContent>;
9
+ abstract publish(input: PublishInput): void;
10
+ abstract subscribe(input: SubscribeInput): Observable<PubSubContent>;
12
11
  }
@@ -1,25 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AbstractPubSub = void 0;
4
- var tslib_1 = require("tslib");
5
- var core_1 = require("@aws-amplify/core");
6
- var logger = new core_1.ConsoleLogger('AbstractPubSubProvider');
7
- var AbstractPubSub = /** @class */ (function () {
8
- function AbstractPubSub(options) {
4
+ const core_1 = require("@aws-amplify/core");
5
+ const logger = new core_1.ConsoleLogger('AbstractPubSubProvider');
6
+ class AbstractPubSub {
7
+ constructor(options) {
9
8
  this._config = options;
10
9
  }
11
- AbstractPubSub.prototype.configure = function (config) {
12
- this._config = tslib_1.__assign(tslib_1.__assign({}, config), this._config);
13
- logger.debug("configure", this._config);
10
+ configure(config) {
11
+ this._config = { ...config, ...this._config };
12
+ logger.debug(`configure`, this._config);
14
13
  return this.options;
15
- };
16
- Object.defineProperty(AbstractPubSub.prototype, "options", {
17
- get: function () {
18
- return tslib_1.__assign({}, this._config);
19
- },
20
- enumerable: false,
21
- configurable: true
22
- });
23
- return AbstractPubSub;
24
- }());
14
+ }
15
+ get options() {
16
+ return { ...this._config };
17
+ }
18
+ }
25
19
  exports.AbstractPubSub = AbstractPubSub;