@aws-amplify/pubsub 4.2.5 → 4.2.6-custom-pk.86

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.
Files changed (63) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/dist/aws-amplify-pubsub.js +404 -339
  3. package/dist/aws-amplify-pubsub.js.map +1 -1
  4. package/dist/aws-amplify-pubsub.min.js +2 -2
  5. package/dist/aws-amplify-pubsub.min.js.map +1 -1
  6. package/lib/Providers/AWSAppSyncProvider.d.ts +3 -0
  7. package/lib/Providers/AWSAppSyncProvider.js +3 -0
  8. package/lib/Providers/AWSAppSyncProvider.js.map +1 -1
  9. package/lib/Providers/AWSAppSyncRealTimeProvider/constants.d.ts +82 -0
  10. package/lib/Providers/AWSAppSyncRealTimeProvider/constants.js +90 -0
  11. package/lib/Providers/AWSAppSyncRealTimeProvider/constants.js.map +1 -0
  12. package/lib/Providers/AWSAppSyncRealTimeProvider/index.d.ts +64 -0
  13. package/lib/Providers/{AWSAppSyncRealTimeProvider.js → AWSAppSyncRealTimeProvider/index.js} +214 -273
  14. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js.map +1 -0
  15. package/lib/Providers/AWSIotProvider.d.ts +6 -1
  16. package/lib/Providers/AWSIotProvider.js +3 -2
  17. package/lib/Providers/AWSIotProvider.js.map +1 -1
  18. package/lib/Providers/MqttOverWSProvider.d.ts +14 -11
  19. package/lib/Providers/MqttOverWSProvider.js +17 -10
  20. package/lib/Providers/MqttOverWSProvider.js.map +1 -1
  21. package/lib/Providers/PubSubProvider.d.ts +7 -7
  22. package/lib/Providers/PubSubProvider.js.map +1 -1
  23. package/lib/PubSub.d.ts +6 -6
  24. package/lib/PubSub.js +2 -2
  25. package/lib/PubSub.js.map +1 -1
  26. package/lib/types/Provider.d.ts +3 -3
  27. package/lib/types/PubSub.d.ts +5 -1
  28. package/lib-esm/Providers/AWSAppSyncProvider.d.ts +3 -0
  29. package/lib-esm/Providers/AWSAppSyncProvider.js +3 -0
  30. package/lib-esm/Providers/AWSAppSyncProvider.js.map +1 -1
  31. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/constants.d.ts +82 -0
  32. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/constants.js +88 -0
  33. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/constants.js.map +1 -0
  34. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +64 -0
  35. package/lib-esm/Providers/{AWSAppSyncRealTimeProvider.js → AWSAppSyncRealTimeProvider/index.js} +188 -247
  36. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js.map +1 -0
  37. package/lib-esm/Providers/AWSIotProvider.d.ts +6 -1
  38. package/lib-esm/Providers/AWSIotProvider.js +3 -2
  39. package/lib-esm/Providers/AWSIotProvider.js.map +1 -1
  40. package/lib-esm/Providers/MqttOverWSProvider.d.ts +14 -11
  41. package/lib-esm/Providers/MqttOverWSProvider.js +17 -10
  42. package/lib-esm/Providers/MqttOverWSProvider.js.map +1 -1
  43. package/lib-esm/Providers/PubSubProvider.d.ts +7 -7
  44. package/lib-esm/Providers/PubSubProvider.js.map +1 -1
  45. package/lib-esm/PubSub.d.ts +6 -6
  46. package/lib-esm/PubSub.js +2 -2
  47. package/lib-esm/PubSub.js.map +1 -1
  48. package/lib-esm/types/Provider.d.ts +3 -3
  49. package/lib-esm/types/PubSub.d.ts +5 -1
  50. package/package.json +13 -7
  51. package/src/Providers/AWSAppSyncProvider.ts +27 -26
  52. package/src/Providers/AWSAppSyncRealTimeProvider/constants.ts +95 -0
  53. package/src/Providers/{AWSAppSyncRealTimeProvider.ts → AWSAppSyncRealTimeProvider/index.ts} +276 -303
  54. package/src/Providers/AWSIotProvider.ts +10 -1
  55. package/src/Providers/MqttOverWSProvider.ts +52 -33
  56. package/src/Providers/PubSubProvider.ts +8 -8
  57. package/src/PubSub.ts +10 -10
  58. package/src/types/Provider.ts +3 -7
  59. package/src/types/PubSub.ts +6 -1
  60. package/lib/Providers/AWSAppSyncRealTimeProvider.d.ts +0 -38
  61. package/lib/Providers/AWSAppSyncRealTimeProvider.js.map +0 -1
  62. package/lib-esm/Providers/AWSAppSyncRealTimeProvider.d.ts +0 -38
  63. package/lib-esm/Providers/AWSAppSyncRealTimeProvider.js.map +0 -1
@@ -94,100 +94,13 @@ import { Buffer } from 'buffer';
94
94
  import { Logger, Credentials, Signer, Hub, Constants, USER_AGENT_HEADER, jitteredExponentialRetry, NonRetryableError, } from '@aws-amplify/core';
95
95
  import Cache from '@aws-amplify/cache';
96
96
  import Auth from '@aws-amplify/auth';
97
- import { AbstractPubSubProvider } from './PubSubProvider';
98
- import { CONTROL_MSG } from '../index';
97
+ import { AbstractPubSubProvider } from '../PubSubProvider';
98
+ import { CONTROL_MSG } from '../../index';
99
+ import { AMPLIFY_SYMBOL, AWS_APPSYNC_REALTIME_HEADERS, CONNECTION_INIT_TIMEOUT, DEFAULT_KEEP_ALIVE_TIMEOUT, MAX_DELAY_MS, MESSAGE_TYPES, NON_RETRYABLE_CODES, SOCKET_STATUS, START_ACK_TIMEOUT, SUBSCRIPTION_STATUS, } from './constants';
99
100
  var logger = new Logger('AWSAppSyncRealTimeProvider');
100
- var AMPLIFY_SYMBOL = (typeof Symbol !== 'undefined' &&
101
- typeof Symbol.for === 'function'
102
- ? Symbol.for('amplify_default')
103
- : '@@amplify_default');
104
101
  var dispatchApiEvent = function (event, data, message) {
105
102
  Hub.dispatch('api', { event: event, data: data, message: message }, 'PubSub', AMPLIFY_SYMBOL);
106
103
  };
107
- var MAX_DELAY_MS = 5000;
108
- var NON_RETRYABLE_CODES = [400, 401, 403];
109
- var MESSAGE_TYPES;
110
- (function (MESSAGE_TYPES) {
111
- /**
112
- * Client -> Server message.
113
- * This message type is the first message after handshake and this will initialize AWS AppSync RealTime communication
114
- */
115
- MESSAGE_TYPES["GQL_CONNECTION_INIT"] = "connection_init";
116
- /**
117
- * Server -> Client message
118
- * This message type is in case there is an issue with AWS AppSync RealTime when establishing connection
119
- */
120
- MESSAGE_TYPES["GQL_CONNECTION_ERROR"] = "connection_error";
121
- /**
122
- * Server -> Client message.
123
- * This message type is for the ack response from AWS AppSync RealTime for GQL_CONNECTION_INIT message
124
- */
125
- MESSAGE_TYPES["GQL_CONNECTION_ACK"] = "connection_ack";
126
- /**
127
- * Client -> Server message.
128
- * This message type is for register subscriptions with AWS AppSync RealTime
129
- */
130
- MESSAGE_TYPES["GQL_START"] = "start";
131
- /**
132
- * Server -> Client message.
133
- * This message type is for the ack response from AWS AppSync RealTime for GQL_START message
134
- */
135
- MESSAGE_TYPES["GQL_START_ACK"] = "start_ack";
136
- /**
137
- * Server -> Client message.
138
- * This message type is for subscription message from AWS AppSync RealTime
139
- */
140
- MESSAGE_TYPES["GQL_DATA"] = "data";
141
- /**
142
- * Server -> Client message.
143
- * This message type helps the client to know is still receiving messages from AWS AppSync RealTime
144
- */
145
- MESSAGE_TYPES["GQL_CONNECTION_KEEP_ALIVE"] = "ka";
146
- /**
147
- * Client -> Server message.
148
- * This message type is for unregister subscriptions with AWS AppSync RealTime
149
- */
150
- MESSAGE_TYPES["GQL_STOP"] = "stop";
151
- /**
152
- * Server -> Client message.
153
- * This message type is for the ack response from AWS AppSync RealTime for GQL_STOP message
154
- */
155
- MESSAGE_TYPES["GQL_COMPLETE"] = "complete";
156
- /**
157
- * Server -> Client message.
158
- * This message type is for sending error messages from AWS AppSync RealTime to the client
159
- */
160
- MESSAGE_TYPES["GQL_ERROR"] = "error";
161
- })(MESSAGE_TYPES || (MESSAGE_TYPES = {}));
162
- var SUBSCRIPTION_STATUS;
163
- (function (SUBSCRIPTION_STATUS) {
164
- SUBSCRIPTION_STATUS[SUBSCRIPTION_STATUS["PENDING"] = 0] = "PENDING";
165
- SUBSCRIPTION_STATUS[SUBSCRIPTION_STATUS["CONNECTED"] = 1] = "CONNECTED";
166
- SUBSCRIPTION_STATUS[SUBSCRIPTION_STATUS["FAILED"] = 2] = "FAILED";
167
- })(SUBSCRIPTION_STATUS || (SUBSCRIPTION_STATUS = {}));
168
- var SOCKET_STATUS;
169
- (function (SOCKET_STATUS) {
170
- SOCKET_STATUS[SOCKET_STATUS["CLOSED"] = 0] = "CLOSED";
171
- SOCKET_STATUS[SOCKET_STATUS["READY"] = 1] = "READY";
172
- SOCKET_STATUS[SOCKET_STATUS["CONNECTING"] = 2] = "CONNECTING";
173
- })(SOCKET_STATUS || (SOCKET_STATUS = {}));
174
- var AWS_APPSYNC_REALTIME_HEADERS = {
175
- accept: 'application/json, text/javascript',
176
- 'content-encoding': 'amz-1.0',
177
- 'content-type': 'application/json; charset=UTF-8',
178
- };
179
- /**
180
- * Time in milleseconds to wait for GQL_CONNECTION_INIT message
181
- */
182
- var CONNECTION_INIT_TIMEOUT = 15000;
183
- /**
184
- * Time in milleseconds to wait for GQL_START_ACK message
185
- */
186
- var START_ACK_TIMEOUT = 15000;
187
- /**
188
- * Default Time in milleseconds to wait for GQL_CONNECTION_KEEP_ALIVE message
189
- */
190
- var DEFAULT_KEEP_ALIVE_TIMEOUT = 5 * 60 * 1000;
191
104
  var standardDomainPattern = /^https:\/\/\w{26}\.appsync\-api\.\w{2}(?:(?:\-\w{2,})+)\-\d\.amazonaws.com\/graphql$/i;
192
105
  var customDomainPath = '/realtime';
193
106
  var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
@@ -200,6 +113,9 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
200
113
  _this.promiseArray = [];
201
114
  return _this;
202
115
  }
116
+ AWSAppSyncRealTimeProvider.prototype.getNewWebSocket = function (url, protocol) {
117
+ return new WebSocket(url, protocol);
118
+ };
203
119
  AWSAppSyncRealTimeProvider.prototype.getProviderName = function () {
204
120
  return 'AWSAppSyncRealTimeProvider';
205
121
  };
@@ -219,9 +135,9 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
219
135
  };
220
136
  AWSAppSyncRealTimeProvider.prototype.subscribe = function (_topics, options) {
221
137
  var _this = this;
222
- var appSyncGraphqlEndpoint = options.appSyncGraphqlEndpoint;
138
+ var appSyncGraphqlEndpoint = options === null || options === void 0 ? void 0 : options.appSyncGraphqlEndpoint;
223
139
  return new Observable(function (observer) {
224
- if (!appSyncGraphqlEndpoint) {
140
+ if (!options || !appSyncGraphqlEndpoint) {
225
141
  observer.error({
226
142
  errors: [
227
143
  __assign({}, new GraphQLError("Subscribe only available for AWS AppSync endpoint")),
@@ -290,14 +206,15 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
290
206
  });
291
207
  AWSAppSyncRealTimeProvider.prototype._startSubscriptionWithAWSAppSyncRealTime = function (_a) {
292
208
  var options = _a.options, observer = _a.observer, subscriptionId = _a.subscriptionId;
209
+ var _b, _c;
293
210
  return __awaiter(this, void 0, void 0, function () {
294
- var appSyncGraphqlEndpoint, authenticationType, query, variables, apiKey, region, _b, graphql_headers, _c, additionalHeaders, subscriptionState, data, dataString, headerObj, _d, _e, subscriptionMessage, stringToAWSRealTime, err_2, _f, message, subscriptionFailedCallback_1, _g, subscriptionFailedCallback, subscriptionReadyCallback;
295
- var _h;
211
+ var appSyncGraphqlEndpoint, authenticationType, query, variables, apiKey, region, _d, graphql_headers, _e, additionalHeaders, subscriptionState, data, dataString, headerObj, _f, _g, subscriptionMessage, stringToAWSRealTime, err_2, message, subscriptionFailedCallback_1, _h, subscriptionFailedCallback, subscriptionReadyCallback;
212
+ var _j;
296
213
  var _this = this;
297
- return __generator(this, function (_j) {
298
- switch (_j.label) {
214
+ return __generator(this, function (_k) {
215
+ switch (_k.label) {
299
216
  case 0:
300
- appSyncGraphqlEndpoint = options.appSyncGraphqlEndpoint, authenticationType = options.authenticationType, query = options.query, variables = options.variables, apiKey = options.apiKey, region = options.region, _b = options.graphql_headers, graphql_headers = _b === void 0 ? function () { return ({}); } : _b, _c = options.additionalHeaders, additionalHeaders = _c === void 0 ? {} : _c;
217
+ appSyncGraphqlEndpoint = options.appSyncGraphqlEndpoint, authenticationType = options.authenticationType, query = options.query, variables = options.variables, apiKey = options.apiKey, region = options.region, _d = options.graphql_headers, graphql_headers = _d === void 0 ? function () { return ({}); } : _d, _e = options.additionalHeaders, additionalHeaders = _e === void 0 ? {} : _e;
301
218
  subscriptionState = SUBSCRIPTION_STATUS.PENDING;
302
219
  data = {
303
220
  query: query,
@@ -306,13 +223,13 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
306
223
  // Having a subscription id map will make it simple to forward messages received
307
224
  this.subscriptionObserverMap.set(subscriptionId, {
308
225
  observer: observer,
309
- query: query,
310
- variables: variables,
226
+ query: query !== null && query !== void 0 ? query : '',
227
+ variables: variables !== null && variables !== void 0 ? variables : {},
311
228
  subscriptionState: subscriptionState,
312
- startAckTimeoutId: null,
229
+ startAckTimeoutId: undefined,
313
230
  });
314
231
  dataString = JSON.stringify(data);
315
- _d = [{}];
232
+ _f = [{}];
316
233
  return [4 /*yield*/, this._awsRealTimeHeaderBasedAuth({
317
234
  apiKey: apiKey,
318
235
  appSyncGraphqlEndpoint: appSyncGraphqlEndpoint,
@@ -323,10 +240,10 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
323
240
  additionalHeaders: additionalHeaders,
324
241
  })];
325
242
  case 1:
326
- _e = [__assign.apply(void 0, _d.concat([(_j.sent())]))];
243
+ _g = [__assign.apply(void 0, _f.concat([(_k.sent())]))];
327
244
  return [4 /*yield*/, graphql_headers()];
328
245
  case 2:
329
- headerObj = __assign.apply(void 0, [__assign.apply(void 0, [__assign.apply(void 0, _e.concat([(_j.sent())])), additionalHeaders]), (_h = {}, _h[USER_AGENT_HEADER] = Constants.userAgent, _h)]);
246
+ headerObj = __assign.apply(void 0, [__assign.apply(void 0, [__assign.apply(void 0, _g.concat([(_k.sent())])), additionalHeaders]), (_j = {}, _j[USER_AGENT_HEADER] = Constants.userAgent, _j)]);
330
247
  subscriptionMessage = {
331
248
  id: subscriptionId,
332
249
  payload: {
@@ -338,9 +255,9 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
338
255
  type: MESSAGE_TYPES.GQL_START,
339
256
  };
340
257
  stringToAWSRealTime = JSON.stringify(subscriptionMessage);
341
- _j.label = 3;
258
+ _k.label = 3;
342
259
  case 3:
343
- _j.trys.push([3, 5, , 6]);
260
+ _k.trys.push([3, 5, , 6]);
344
261
  return [4 /*yield*/, this._initializeWebSocketConnection({
345
262
  apiKey: apiKey,
346
263
  appSyncGraphqlEndpoint: appSyncGraphqlEndpoint,
@@ -349,12 +266,12 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
349
266
  additionalHeaders: additionalHeaders,
350
267
  })];
351
268
  case 4:
352
- _j.sent();
269
+ _k.sent();
353
270
  return [3 /*break*/, 6];
354
271
  case 5:
355
- err_2 = _j.sent();
272
+ err_2 = _k.sent();
356
273
  logger.debug({ err: err_2 });
357
- _f = err_2.message, message = _f === void 0 ? '' : _f;
274
+ message = (_b = err_2['message']) !== null && _b !== void 0 ? _b : '';
358
275
  observer.error({
359
276
  errors: [
360
277
  __assign({}, new GraphQLError(CONTROL_MSG.CONNECTION_FAILED + ": " + message)),
@@ -368,13 +285,13 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
368
285
  }
369
286
  return [2 /*return*/];
370
287
  case 6:
371
- _g = this.subscriptionObserverMap.get(subscriptionId), subscriptionFailedCallback = _g.subscriptionFailedCallback, subscriptionReadyCallback = _g.subscriptionReadyCallback;
288
+ _h = (_c = this.subscriptionObserverMap.get(subscriptionId)) !== null && _c !== void 0 ? _c : {}, subscriptionFailedCallback = _h.subscriptionFailedCallback, subscriptionReadyCallback = _h.subscriptionReadyCallback;
372
289
  // This must be done before sending the message in order to be listening immediately
373
290
  this.subscriptionObserverMap.set(subscriptionId, {
374
291
  observer: observer,
375
292
  subscriptionState: subscriptionState,
376
- variables: variables,
377
- query: query,
293
+ query: query !== null && query !== void 0 ? query : '',
294
+ variables: variables !== null && variables !== void 0 ? variables : {},
378
295
  subscriptionReadyCallback: subscriptionReadyCallback,
379
296
  subscriptionFailedCallback: subscriptionFailedCallback,
380
297
  startAckTimeoutId: setTimeout(function () {
@@ -392,23 +309,26 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
392
309
  // Waiting that subscription has been connected before trying to unsubscribe
393
310
  AWSAppSyncRealTimeProvider.prototype._waitForSubscriptionToBeConnected = function (subscriptionId) {
394
311
  return __awaiter(this, void 0, void 0, function () {
395
- var subscriptionState;
312
+ var subscriptionObserver, subscriptionState;
396
313
  var _this = this;
397
314
  return __generator(this, function (_a) {
398
- subscriptionState = this.subscriptionObserverMap.get(subscriptionId).subscriptionState;
399
- // This in case unsubscribe is invoked before sending start subscription message
400
- if (subscriptionState === SUBSCRIPTION_STATUS.PENDING) {
401
- return [2 /*return*/, new Promise(function (res, rej) {
402
- var _a = _this.subscriptionObserverMap.get(subscriptionId), observer = _a.observer, subscriptionState = _a.subscriptionState, variables = _a.variables, query = _a.query;
403
- _this.subscriptionObserverMap.set(subscriptionId, {
404
- observer: observer,
405
- subscriptionState: subscriptionState,
406
- variables: variables,
407
- query: query,
408
- subscriptionReadyCallback: res,
409
- subscriptionFailedCallback: rej,
410
- });
411
- })];
315
+ subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
316
+ if (subscriptionObserver) {
317
+ subscriptionState = subscriptionObserver.subscriptionState;
318
+ // This in case unsubscribe is invoked before sending start subscription message
319
+ if (subscriptionState === SUBSCRIPTION_STATUS.PENDING) {
320
+ return [2 /*return*/, new Promise(function (res, rej) {
321
+ var observer = subscriptionObserver.observer, subscriptionState = subscriptionObserver.subscriptionState, variables = subscriptionObserver.variables, query = subscriptionObserver.query;
322
+ _this.subscriptionObserverMap.set(subscriptionId, {
323
+ observer: observer,
324
+ subscriptionState: subscriptionState,
325
+ variables: variables,
326
+ query: query,
327
+ subscriptionReadyCallback: res,
328
+ subscriptionFailedCallback: rej,
329
+ });
330
+ })];
331
+ }
412
332
  }
413
333
  return [2 /*return*/];
414
334
  });
@@ -453,13 +373,14 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
453
373
  }
454
374
  else {
455
375
  logger.debug('closing WebSocket...');
456
- clearTimeout(this.keepAliveTimeoutId);
376
+ if (this.keepAliveTimeoutId)
377
+ clearTimeout(this.keepAliveTimeoutId);
457
378
  var tempSocket = this.awsRealTimeSocket;
458
379
  // Cleaning callbacks to avoid race condition, socket still exists
459
- tempSocket.onclose = undefined;
460
- tempSocket.onerror = undefined;
380
+ tempSocket.onclose = null;
381
+ tempSocket.onerror = null;
461
382
  tempSocket.close(1000);
462
- this.awsRealTimeSocket = null;
383
+ this.awsRealTimeSocket = undefined;
463
384
  this.socketStatus = SOCKET_STATUS.CLOSED;
464
385
  }
465
386
  };
@@ -482,46 +403,53 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
482
403
  if (typeof subscriptionReadyCallback === 'function') {
483
404
  subscriptionReadyCallback();
484
405
  }
485
- clearTimeout(startAckTimeoutId);
406
+ if (startAckTimeoutId)
407
+ clearTimeout(startAckTimeoutId);
486
408
  dispatchApiEvent(CONTROL_MSG.SUBSCRIPTION_ACK, { query: query, variables: variables }, 'Connection established for subscription');
487
409
  var subscriptionState = SUBSCRIPTION_STATUS.CONNECTED;
488
- this.subscriptionObserverMap.set(id, {
489
- observer: observer,
490
- query: query,
491
- variables: variables,
492
- startAckTimeoutId: null,
493
- subscriptionState: subscriptionState,
494
- subscriptionReadyCallback: subscriptionReadyCallback,
495
- subscriptionFailedCallback: subscriptionFailedCallback,
496
- });
410
+ if (observer) {
411
+ this.subscriptionObserverMap.set(id, {
412
+ observer: observer,
413
+ query: query,
414
+ variables: variables,
415
+ startAckTimeoutId: undefined,
416
+ subscriptionState: subscriptionState,
417
+ subscriptionReadyCallback: subscriptionReadyCallback,
418
+ subscriptionFailedCallback: subscriptionFailedCallback,
419
+ });
420
+ }
497
421
  // TODO: emit event on hub but it requires to store the id first
498
422
  return;
499
423
  }
500
424
  if (type === MESSAGE_TYPES.GQL_CONNECTION_KEEP_ALIVE) {
501
- clearTimeout(this.keepAliveTimeoutId);
425
+ if (this.keepAliveTimeoutId)
426
+ clearTimeout(this.keepAliveTimeoutId);
502
427
  this.keepAliveTimeoutId = setTimeout(this._errorDisconnect.bind(this, CONTROL_MSG.TIMEOUT_DISCONNECT), this.keepAliveTimeout);
503
428
  return;
504
429
  }
505
430
  if (type === MESSAGE_TYPES.GQL_ERROR) {
506
431
  var subscriptionState = SUBSCRIPTION_STATUS.FAILED;
507
- this.subscriptionObserverMap.set(id, {
508
- observer: observer,
509
- query: query,
510
- variables: variables,
511
- startAckTimeoutId: startAckTimeoutId,
512
- subscriptionReadyCallback: subscriptionReadyCallback,
513
- subscriptionFailedCallback: subscriptionFailedCallback,
514
- subscriptionState: subscriptionState,
515
- });
516
- observer.error({
517
- errors: [
518
- __assign({}, new GraphQLError(CONTROL_MSG.CONNECTION_FAILED + ": " + JSON.stringify(payload))),
519
- ],
520
- });
521
- clearTimeout(startAckTimeoutId);
522
- observer.complete();
523
- if (typeof subscriptionFailedCallback === 'function') {
524
- subscriptionFailedCallback();
432
+ if (observer) {
433
+ this.subscriptionObserverMap.set(id, {
434
+ observer: observer,
435
+ query: query,
436
+ variables: variables,
437
+ startAckTimeoutId: startAckTimeoutId,
438
+ subscriptionReadyCallback: subscriptionReadyCallback,
439
+ subscriptionFailedCallback: subscriptionFailedCallback,
440
+ subscriptionState: subscriptionState,
441
+ });
442
+ observer.error({
443
+ errors: [
444
+ __assign({}, new GraphQLError(CONTROL_MSG.CONNECTION_FAILED + ": " + JSON.stringify(payload))),
445
+ ],
446
+ });
447
+ if (startAckTimeoutId)
448
+ clearTimeout(startAckTimeoutId);
449
+ observer.complete();
450
+ if (typeof subscriptionFailedCallback === 'function') {
451
+ subscriptionFailedCallback();
452
+ }
525
453
  }
526
454
  }
527
455
  };
@@ -542,29 +470,32 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
542
470
  this.socketStatus = SOCKET_STATUS.CLOSED;
543
471
  };
544
472
  AWSAppSyncRealTimeProvider.prototype._timeoutStartSubscriptionAck = function (subscriptionId) {
545
- var _a = this.subscriptionObserverMap.get(subscriptionId) || {}, observer = _a.observer, query = _a.query, variables = _a.variables;
546
- if (!observer) {
547
- return;
548
- }
549
- this.subscriptionObserverMap.set(subscriptionId, {
550
- observer: observer,
551
- query: query,
552
- variables: variables,
553
- subscriptionState: SUBSCRIPTION_STATUS.FAILED,
554
- });
555
- if (observer && !observer.closed) {
556
- observer.error({
557
- errors: [
558
- __assign({}, new GraphQLError("Subscription timeout " + JSON.stringify({
559
- query: query,
560
- variables: variables,
561
- }))),
562
- ],
473
+ var subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
474
+ if (subscriptionObserver) {
475
+ var observer = subscriptionObserver.observer, query = subscriptionObserver.query, variables = subscriptionObserver.variables;
476
+ if (!observer) {
477
+ return;
478
+ }
479
+ this.subscriptionObserverMap.set(subscriptionId, {
480
+ observer: observer,
481
+ query: query,
482
+ variables: variables,
483
+ subscriptionState: SUBSCRIPTION_STATUS.FAILED,
563
484
  });
564
- // Cleanup will be automatically executed
565
- observer.complete();
485
+ if (observer && !observer.closed) {
486
+ observer.error({
487
+ errors: [
488
+ __assign({}, new GraphQLError("Subscription timeout " + JSON.stringify({
489
+ query: query,
490
+ variables: variables,
491
+ }))),
492
+ ],
493
+ });
494
+ // Cleanup will be automatically executed
495
+ observer.complete();
496
+ }
497
+ logger.debug('timeoutStartSubscription', JSON.stringify({ query: query, variables: variables }));
566
498
  }
567
- logger.debug('timeoutStartSubscription', JSON.stringify({ query: query, variables: variables }));
568
499
  };
569
500
  AWSAppSyncRealTimeProvider.prototype._initializeWebSocketConnection = function (_a) {
570
501
  var _this = this;
@@ -598,19 +529,22 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
598
529
  headerString = _b.apply(_a, [_c.sent()]);
599
530
  headerQs = Buffer.from(headerString).toString('base64');
600
531
  payloadQs = Buffer.from(payloadString).toString('base64');
601
- discoverableEndpoint = appSyncGraphqlEndpoint;
532
+ discoverableEndpoint = appSyncGraphqlEndpoint !== null && appSyncGraphqlEndpoint !== void 0 ? appSyncGraphqlEndpoint : '';
602
533
  if (this.isCustomDomain(discoverableEndpoint)) {
603
- discoverableEndpoint = discoverableEndpoint.concat(customDomainPath);
534
+ discoverableEndpoint =
535
+ discoverableEndpoint.concat(customDomainPath);
604
536
  }
605
537
  else {
606
- discoverableEndpoint = discoverableEndpoint.replace('appsync-api', 'appsync-realtime-api').replace('gogi-beta', 'grt-beta');
538
+ discoverableEndpoint = discoverableEndpoint
539
+ .replace('appsync-api', 'appsync-realtime-api')
540
+ .replace('gogi-beta', 'grt-beta');
607
541
  }
608
542
  protocol = this.isSSLEnabled ? 'wss://' : 'ws://';
609
543
  discoverableEndpoint = discoverableEndpoint
610
544
  .replace('https://', protocol)
611
545
  .replace('http://', protocol);
612
546
  awsRealTimeUrl = discoverableEndpoint + "?header=" + headerQs + "&payload=" + payloadQs;
613
- return [4 /*yield*/, this._initializeRetryableHandshake({ awsRealTimeUrl: awsRealTimeUrl })];
547
+ return [4 /*yield*/, this._initializeRetryableHandshake(awsRealTimeUrl)];
614
548
  case 3:
615
549
  _c.sent();
616
550
  this.promiseArray.forEach(function (_a) {
@@ -632,7 +566,7 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
632
566
  this.awsRealTimeSocket.readyState === WebSocket.OPEN) {
633
567
  this.awsRealTimeSocket.close(3001);
634
568
  }
635
- this.awsRealTimeSocket = null;
569
+ this.awsRealTimeSocket = undefined;
636
570
  this.socketStatus = SOCKET_STATUS.CLOSED;
637
571
  return [3 /*break*/, 5];
638
572
  case 5: return [2 /*return*/];
@@ -640,25 +574,23 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
640
574
  });
641
575
  }); });
642
576
  };
643
- AWSAppSyncRealTimeProvider.prototype._initializeRetryableHandshake = function (_a) {
644
- var awsRealTimeUrl = _a.awsRealTimeUrl;
577
+ AWSAppSyncRealTimeProvider.prototype._initializeRetryableHandshake = function (awsRealTimeUrl) {
645
578
  return __awaiter(this, void 0, void 0, function () {
646
- return __generator(this, function (_b) {
647
- switch (_b.label) {
579
+ return __generator(this, function (_a) {
580
+ switch (_a.label) {
648
581
  case 0:
649
582
  logger.debug("Initializaling retryable Handshake");
650
- return [4 /*yield*/, jitteredExponentialRetry(this._initializeHandshake.bind(this), [{ awsRealTimeUrl: awsRealTimeUrl }], MAX_DELAY_MS)];
583
+ return [4 /*yield*/, jitteredExponentialRetry(this._initializeHandshake.bind(this), [awsRealTimeUrl], MAX_DELAY_MS)];
651
584
  case 1:
652
- _b.sent();
585
+ _a.sent();
653
586
  return [2 /*return*/];
654
587
  }
655
588
  });
656
589
  });
657
590
  };
658
- AWSAppSyncRealTimeProvider.prototype._initializeHandshake = function (_a) {
659
- var awsRealTimeUrl = _a.awsRealTimeUrl;
591
+ AWSAppSyncRealTimeProvider.prototype._initializeHandshake = function (awsRealTimeUrl) {
660
592
  return __awaiter(this, void 0, void 0, function () {
661
- var err_4, errorType, errorCode;
593
+ var err_4, _a, errorType, errorCode;
662
594
  var _this = this;
663
595
  return __generator(this, function (_b) {
664
596
  switch (_b.label) {
@@ -669,7 +601,7 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
669
601
  _b.trys.push([1, 4, , 5]);
670
602
  return [4 /*yield*/, (function () {
671
603
  return new Promise(function (res, rej) {
672
- var newSocket = new WebSocket(awsRealTimeUrl, 'graphql-ws');
604
+ var newSocket = _this.getNewWebSocket(awsRealTimeUrl, 'graphql-ws');
673
605
  newSocket.onerror = function () {
674
606
  logger.debug("WebSocket connection error");
675
607
  };
@@ -687,48 +619,53 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
687
619
  // Step 2: wait for ack from AWS AppSyncReaTime after sending init
688
620
  return [4 /*yield*/, (function () {
689
621
  return new Promise(function (res, rej) {
690
- var ackOk = false;
691
- _this.awsRealTimeSocket.onerror = function (error) {
692
- logger.debug("WebSocket error " + JSON.stringify(error));
693
- };
694
- _this.awsRealTimeSocket.onclose = function (event) {
695
- logger.debug("WebSocket closed " + event.reason);
696
- rej(new Error(JSON.stringify(event)));
697
- };
698
- _this.awsRealTimeSocket.onmessage = function (message) {
699
- logger.debug("subscription message from AWS AppSyncRealTime: " + message.data + " ");
700
- var data = JSON.parse(message.data);
701
- var type = data.type, _a = data.payload, _b = (_a === void 0 ? {} : _a).connectionTimeoutMs, connectionTimeoutMs = _b === void 0 ? DEFAULT_KEEP_ALIVE_TIMEOUT : _b;
702
- if (type === MESSAGE_TYPES.GQL_CONNECTION_ACK) {
703
- ackOk = true;
704
- _this.keepAliveTimeout = connectionTimeoutMs;
705
- _this.awsRealTimeSocket.onmessage = _this._handleIncomingSubscriptionMessage.bind(_this);
706
- _this.awsRealTimeSocket.onerror = function (err) {
707
- logger.debug(err);
708
- _this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
709
- };
710
- _this.awsRealTimeSocket.onclose = function (event) {
711
- logger.debug("WebSocket closed " + event.reason);
712
- _this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
713
- };
714
- res('Cool, connected to AWS AppSyncRealTime');
715
- return;
716
- }
717
- if (type === MESSAGE_TYPES.GQL_CONNECTION_ERROR) {
718
- var _c = data.payload, _d = (_c === void 0 ? {} : _c).errors, _e = __read(_d === void 0 ? [] : _d, 1), _f = _e[0], _g = _f === void 0 ? {} : _f, _h = _g.errorType, errorType = _h === void 0 ? '' : _h, _j = _g.errorCode, errorCode = _j === void 0 ? 0 : _j;
719
- rej({ errorType: errorType, errorCode: errorCode });
720
- }
721
- };
722
- var gqlInit = {
723
- type: MESSAGE_TYPES.GQL_CONNECTION_INIT,
724
- };
725
- _this.awsRealTimeSocket.send(JSON.stringify(gqlInit));
726
- function checkAckOk() {
622
+ if (_this.awsRealTimeSocket) {
623
+ var ackOk_1 = false;
624
+ _this.awsRealTimeSocket.onerror = function (error) {
625
+ logger.debug("WebSocket error " + JSON.stringify(error));
626
+ };
627
+ _this.awsRealTimeSocket.onclose = function (event) {
628
+ logger.debug("WebSocket closed " + event.reason);
629
+ rej(new Error(JSON.stringify(event)));
630
+ };
631
+ _this.awsRealTimeSocket.onmessage = function (message) {
632
+ logger.debug("subscription message from AWS AppSyncRealTime: " + message.data + " ");
633
+ var data = JSON.parse(message.data);
634
+ var type = data.type, _a = data.payload, _b = (_a === void 0 ? {} : _a).connectionTimeoutMs, connectionTimeoutMs = _b === void 0 ? DEFAULT_KEEP_ALIVE_TIMEOUT : _b;
635
+ if (type === MESSAGE_TYPES.GQL_CONNECTION_ACK) {
636
+ ackOk_1 = true;
637
+ if (_this.awsRealTimeSocket) {
638
+ _this.keepAliveTimeout = connectionTimeoutMs;
639
+ _this.awsRealTimeSocket.onmessage =
640
+ _this._handleIncomingSubscriptionMessage.bind(_this);
641
+ _this.awsRealTimeSocket.onerror = function (err) {
642
+ logger.debug(err);
643
+ _this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
644
+ };
645
+ _this.awsRealTimeSocket.onclose = function (event) {
646
+ logger.debug("WebSocket closed " + event.reason);
647
+ _this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
648
+ };
649
+ }
650
+ res('Cool, connected to AWS AppSyncRealTime');
651
+ return;
652
+ }
653
+ if (type === MESSAGE_TYPES.GQL_CONNECTION_ERROR) {
654
+ var _c = data.payload, _d = (_c === void 0 ? {} : _c).errors, _e = __read(_d === void 0 ? [] : _d, 1), _f = _e[0], _g = _f === void 0 ? {} : _f, _h = _g.errorType, errorType = _h === void 0 ? '' : _h, _j = _g.errorCode, errorCode = _j === void 0 ? 0 : _j;
655
+ rej({ errorType: errorType, errorCode: errorCode });
656
+ }
657
+ };
658
+ var gqlInit = {
659
+ type: MESSAGE_TYPES.GQL_CONNECTION_INIT,
660
+ };
661
+ _this.awsRealTimeSocket.send(JSON.stringify(gqlInit));
662
+ setTimeout(checkAckOk.bind(_this, ackOk_1), CONNECTION_INIT_TIMEOUT);
663
+ }
664
+ function checkAckOk(ackOk) {
727
665
  if (!ackOk) {
728
666
  rej(new Error("Connection timeout: ack from AWSRealTime was not received on " + CONNECTION_INIT_TIMEOUT + " ms"));
729
667
  }
730
668
  }
731
- setTimeout(checkAckOk.bind(_this), CONNECTION_INIT_TIMEOUT);
732
669
  });
733
670
  })()];
734
671
  case 3:
@@ -737,7 +674,7 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
737
674
  return [3 /*break*/, 5];
738
675
  case 4:
739
676
  err_4 = _b.sent();
740
- errorType = err_4.errorType, errorCode = err_4.errorCode;
677
+ _a = err_4, errorType = _a.errorType, errorCode = _a.errorCode;
741
678
  if (NON_RETRYABLE_CODES.includes(errorCode)) {
742
679
  throw new NonRetryableError(errorType);
743
680
  }
@@ -767,12 +704,13 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
767
704
  AMAZON_COGNITO_USER_POOLS: this._awsRealTimeCUPHeader.bind(this),
768
705
  AWS_LAMBDA: this._customAuthHeader,
769
706
  };
707
+ if (!(!authenticationType || !headerHandler[authenticationType])) return [3 /*break*/, 1];
708
+ logger.debug("Authentication type " + authenticationType + " not supported");
709
+ return [2 /*return*/, ''];
710
+ case 1:
770
711
  handler = headerHandler[authenticationType];
771
- if (typeof handler !== 'function') {
772
- logger.debug("Authentication type " + authenticationType + " not supported");
773
- return [2 /*return*/, ''];
774
- }
775
- host = url.parse(appSyncGraphqlEndpoint).host;
712
+ host = url.parse(appSyncGraphqlEndpoint !== null && appSyncGraphqlEndpoint !== void 0 ? appSyncGraphqlEndpoint : '').host;
713
+ logger.debug("Authenticating with " + authenticationType);
776
714
  return [4 /*yield*/, handler({
777
715
  payload: payload,
778
716
  canonicalUri: canonicalUri,
@@ -782,7 +720,7 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
782
720
  host: host,
783
721
  additionalHeaders: additionalHeaders,
784
722
  })];
785
- case 1:
723
+ case 2:
786
724
  result = _b.sent();
787
725
  return [2 /*return*/, result];
788
726
  }
@@ -869,11 +807,14 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
869
807
  if (!credentialsOK) {
870
808
  throw new Error('No credentials');
871
809
  }
872
- return [4 /*yield*/, Credentials.get().then(function (credentials) { return ({
873
- secret_key: credentials.secretAccessKey,
874
- access_key: credentials.accessKeyId,
875
- session_token: credentials.sessionToken,
876
- }); })];
810
+ return [4 /*yield*/, Credentials.get().then(function (credentials) {
811
+ var _a = credentials, secretAccessKey = _a.secretAccessKey, accessKeyId = _a.accessKeyId, sessionToken = _a.sessionToken;
812
+ return {
813
+ secret_key: secretAccessKey,
814
+ access_key: accessKeyId,
815
+ session_token: sessionToken,
816
+ };
817
+ })];
877
818
  case 2:
878
819
  creds = _b.sent();
879
820
  request = {
@@ -890,7 +831,7 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
890
831
  };
891
832
  AWSAppSyncRealTimeProvider.prototype._customAuthHeader = function (_a) {
892
833
  var host = _a.host, additionalHeaders = _a.additionalHeaders;
893
- if (!additionalHeaders.Authorization) {
834
+ if (!additionalHeaders || !additionalHeaders['Authorization']) {
894
835
  throw new Error('No auth token specified');
895
836
  }
896
837
  return {
@@ -918,4 +859,4 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function (_super) {
918
859
  return AWSAppSyncRealTimeProvider;
919
860
  }(AbstractPubSubProvider));
920
861
  export { AWSAppSyncRealTimeProvider };
921
- //# sourceMappingURL=AWSAppSyncRealTimeProvider.js.map
862
+ //# sourceMappingURL=index.js.map