@aws-amplify/api-graphql 4.0.1-server-generate-client.1e317a1.0 → 4.0.1-ssr-api.df60e41.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.
Files changed (91) hide show
  1. package/lib/GraphQLAPI.d.ts +1 -1
  2. package/lib/GraphQLAPI.js +25 -30
  3. package/lib/Providers/AWSAppSyncRealTimeProvider/index.d.ts +1 -1
  4. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js +468 -584
  5. package/lib/Providers/constants.js +4 -5
  6. package/lib/index.js +5 -6
  7. package/lib/internals/InternalGraphQLAPI.d.ts +1 -1
  8. package/lib/internals/InternalGraphQLAPI.js +203 -263
  9. package/lib/internals/index.d.ts +0 -1
  10. package/lib/internals/index.js +5 -8
  11. package/lib/internals/v6.js +3 -4
  12. package/lib/tsconfig.tsbuildinfo +6798 -1
  13. package/lib/types/PubSub.d.ts +2 -2
  14. package/lib/types/PubSub.js +2 -3
  15. package/lib/types/index.d.ts +39 -28
  16. package/lib/types/index.js +3 -4
  17. package/lib/utils/ConnectionStateMonitor.d.ts +3 -3
  18. package/lib/utils/ConnectionStateMonitor.js +51 -65
  19. package/lib/utils/ReachabilityMonitor/index.d.ts +1 -1
  20. package/lib/utils/ReachabilityMonitor/index.js +2 -4
  21. package/lib/utils/ReachabilityMonitor/index.native.d.ts +1 -1
  22. package/lib/utils/ReachabilityMonitor/index.native.js +4 -8
  23. package/lib/utils/ReconnectionMonitor.js +21 -26
  24. package/lib/utils/errors/APIError.js +7 -12
  25. package/lib/utils/errors/assertValidationError.js +4 -5
  26. package/lib/utils/errors/index.js +4 -5
  27. package/lib/utils/errors/validation.js +6 -8
  28. package/lib/utils/index.js +2 -3
  29. package/lib/utils/resolveConfig.d.ts +1 -1
  30. package/lib/utils/resolveConfig.js +10 -13
  31. package/lib/utils/resolveLibraryOptions.d.ts +1 -1
  32. package/lib/utils/resolveLibraryOptions.js +4 -7
  33. package/lib-esm/GraphQLAPI.d.ts +1 -1
  34. package/lib-esm/GraphQLAPI.js +25 -29
  35. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +1 -1
  36. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js +459 -575
  37. package/lib-esm/Providers/constants.js +10 -10
  38. package/lib-esm/internals/InternalGraphQLAPI.d.ts +1 -1
  39. package/lib-esm/internals/InternalGraphQLAPI.js +197 -256
  40. package/lib-esm/internals/index.d.ts +0 -1
  41. package/lib-esm/internals/index.js +0 -1
  42. package/lib-esm/internals/v6.js +1 -1
  43. package/lib-esm/tsconfig.tsbuildinfo +6798 -1
  44. package/lib-esm/types/PubSub.d.ts +2 -2
  45. package/lib-esm/types/index.d.ts +39 -28
  46. package/lib-esm/types/index.js +1 -1
  47. package/lib-esm/utils/ConnectionStateMonitor.d.ts +3 -3
  48. package/lib-esm/utils/ConnectionStateMonitor.js +49 -63
  49. package/lib-esm/utils/ReachabilityMonitor/index.d.ts +1 -1
  50. package/lib-esm/utils/ReachabilityMonitor/index.js +1 -1
  51. package/lib-esm/utils/ReachabilityMonitor/index.native.d.ts +1 -1
  52. package/lib-esm/utils/ReachabilityMonitor/index.native.js +1 -3
  53. package/lib-esm/utils/ReconnectionMonitor.js +19 -24
  54. package/lib-esm/utils/errors/APIError.js +6 -11
  55. package/lib-esm/utils/errors/assertValidationError.js +2 -2
  56. package/lib-esm/utils/errors/validation.js +5 -6
  57. package/lib-esm/utils/resolveConfig.d.ts +1 -1
  58. package/lib-esm/utils/resolveConfig.js +8 -9
  59. package/lib-esm/utils/resolveLibraryOptions.d.ts +1 -1
  60. package/lib-esm/utils/resolveLibraryOptions.js +4 -5
  61. package/package.json +6 -12
  62. package/src/GraphQLAPI.ts +6 -1
  63. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +6 -5
  64. package/src/internals/InternalGraphQLAPI.ts +7 -8
  65. package/src/internals/index.ts +0 -1
  66. package/src/types/index.ts +39 -15
  67. package/lib/internals/APIClient.d.ts +0 -101
  68. package/lib/internals/APIClient.js +0 -443
  69. package/lib/internals/generateClient.d.ts +0 -12
  70. package/lib/internals/generateClient.js +0 -30
  71. package/lib/internals/generateModelsProperty.d.ts +0 -4
  72. package/lib/internals/generateModelsProperty.js +0 -169
  73. package/lib/internals/types.d.ts +0 -10
  74. package/lib/internals/types.js +0 -2
  75. package/lib/utils/resolveOwnerFields.d.ts +0 -12
  76. package/lib/utils/resolveOwnerFields.js +0 -63
  77. package/lib-esm/internals/APIClient.d.ts +0 -101
  78. package/lib-esm/internals/APIClient.js +0 -432
  79. package/lib-esm/internals/generateClient.d.ts +0 -12
  80. package/lib-esm/internals/generateClient.js +0 -26
  81. package/lib-esm/internals/generateModelsProperty.d.ts +0 -4
  82. package/lib-esm/internals/generateModelsProperty.js +0 -165
  83. package/lib-esm/internals/types.d.ts +0 -10
  84. package/lib-esm/internals/types.js +0 -1
  85. package/lib-esm/utils/resolveOwnerFields.d.ts +0 -12
  86. package/lib-esm/utils/resolveOwnerFields.js +0 -59
  87. package/src/internals/APIClient.ts +0 -583
  88. package/src/internals/generateClient.ts +0 -30
  89. package/src/internals/generateModelsProperty.ts +0 -192
  90. package/src/internals/types.ts +0 -15
  91. package/src/utils/resolveOwnerFields.ts +0 -65
@@ -1,30 +1,24 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AWSAppSyncRealTimeProvider = void 0;
4
- var tslib_1 = require("tslib");
5
3
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
4
  // SPDX-License-Identifier: Apache-2.0
7
- var rxjs_1 = require("rxjs");
8
- var graphql_1 = require("graphql");
9
- var url = tslib_1.__importStar(require("url"));
10
- var buffer_1 = require("buffer");
11
- var core_1 = require("@aws-amplify/core");
12
- var aws_client_utils_1 = require("@aws-amplify/core/internals/aws-client-utils");
13
- var utils_1 = require("@aws-amplify/core/internals/utils");
14
- var PubSub_1 = require("../../types/PubSub");
15
- var constants_1 = require("../constants");
16
- var ConnectionStateMonitor_1 = require("../../utils/ConnectionStateMonitor");
17
- var ReconnectionMonitor_1 = require("../../utils/ReconnectionMonitor");
18
- var logger = new core_1.ConsoleLogger('AWSAppSyncRealTimeProvider');
19
- var dispatchApiEvent = function (payload) {
5
+ const rxjs_1 = require("rxjs");
6
+ const graphql_1 = require("graphql");
7
+ const core_1 = require("@aws-amplify/core");
8
+ const aws_client_utils_1 = require("@aws-amplify/core/internals/aws-client-utils");
9
+ const utils_1 = require("@aws-amplify/core/internals/utils");
10
+ const PubSub_1 = require("../../types/PubSub");
11
+ const constants_1 = require("../constants");
12
+ const ConnectionStateMonitor_1 = require("../../utils/ConnectionStateMonitor");
13
+ const ReconnectionMonitor_1 = require("../../utils/ReconnectionMonitor");
14
+ const logger = new core_1.ConsoleLogger('AWSAppSyncRealTimeProvider');
15
+ const dispatchApiEvent = payload => {
20
16
  core_1.Hub.dispatch('api', payload, 'PubSub', constants_1.AMPLIFY_SYMBOL);
21
17
  };
22
- var standardDomainPattern = /^https:\/\/\w{26}\.appsync\-api\.\w{2}(?:(?:\-\w{2,})+)\-\d\.amazonaws.com(?:\.cn)?\/graphql$/i;
23
- var customDomainPath = '/realtime';
24
- var AWSAppSyncRealTimeProvider = /** @class */ (function () {
25
- function AWSAppSyncRealTimeProvider(options) {
26
- if (options === void 0) { options = {}; }
27
- var _this = this;
18
+ const standardDomainPattern = /^https:\/\/\w{26}\.appsync\-api\.\w{2}(?:(?:\-\w{2,})+)\-\d\.amazonaws.com(?:\.cn)?\/graphql$/i;
19
+ const customDomainPath = '/realtime';
20
+ class AWSAppSyncRealTimeProvider {
21
+ constructor(options = {}) {
28
22
  this.socketStatus = constants_1.SOCKET_STATUS.CLOSED;
29
23
  this.keepAliveTimeout = constants_1.DEFAULT_KEEP_ALIVE_TIMEOUT;
30
24
  this.subscriptionObserverMap = new Map();
@@ -33,19 +27,19 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function () {
33
27
  this.reconnectionMonitor = new ReconnectionMonitor_1.ReconnectionMonitor();
34
28
  // Monitor the connection state and pass changes along to Hub
35
29
  this.connectionStateMonitorSubscription =
36
- this.connectionStateMonitor.connectionStateObservable.subscribe(function (connectionState) {
30
+ this.connectionStateMonitor.connectionStateObservable.subscribe(connectionState => {
37
31
  dispatchApiEvent({
38
32
  event: constants_1.CONNECTION_STATE_CHANGE,
39
33
  data: {
40
- provider: _this,
41
- connectionState: connectionState,
34
+ provider: this,
35
+ connectionState,
42
36
  },
43
- message: "Connection state is ".concat(connectionState),
37
+ message: `Connection state is ${connectionState}`,
44
38
  });
45
- _this.connectionState = connectionState;
39
+ this.connectionState = connectionState;
46
40
  // Trigger START_RECONNECT when the connection is disrupted
47
41
  if (connectionState === PubSub_1.ConnectionState.ConnectionDisrupted) {
48
- _this.reconnectionMonitor.record(ReconnectionMonitor_1.ReconnectEvent.START_RECONNECT);
42
+ this.reconnectionMonitor.record(ReconnectionMonitor_1.ReconnectEvent.START_RECONNECT);
49
43
  }
50
44
  // Trigger HALT_RECONNECT to halt reconnection attempts when the state is anything other than
51
45
  // ConnectionDisrupted or Connecting
@@ -57,14 +51,14 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function () {
57
51
  PubSub_1.ConnectionState.ConnectionDisruptedPendingNetwork,
58
52
  PubSub_1.ConnectionState.Disconnected,
59
53
  ].includes(connectionState)) {
60
- _this.reconnectionMonitor.record(ReconnectionMonitor_1.ReconnectEvent.HALT_RECONNECT);
54
+ this.reconnectionMonitor.record(ReconnectionMonitor_1.ReconnectEvent.HALT_RECONNECT);
61
55
  }
62
56
  });
63
57
  }
64
58
  /**
65
59
  * Mark the socket closed and release all active listeners
66
60
  */
67
- AWSAppSyncRealTimeProvider.prototype.close = function () {
61
+ close() {
68
62
  // Mark the socket closed both in status and the connection monitor
69
63
  this.socketStatus = constants_1.SOCKET_STATUS.CLOSED;
70
64
  this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CONNECTION_FAILED);
@@ -72,277 +66,247 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function () {
72
66
  this.connectionStateMonitorSubscription.unsubscribe();
73
67
  // Complete all reconnect observers
74
68
  this.reconnectionMonitor.close();
75
- };
76
- AWSAppSyncRealTimeProvider.prototype.getNewWebSocket = function (url, protocol) {
69
+ }
70
+ getNewWebSocket(url, protocol) {
77
71
  return new WebSocket(url, protocol);
78
- };
79
- AWSAppSyncRealTimeProvider.prototype.getProviderName = function () {
72
+ }
73
+ getProviderName() {
80
74
  return 'AWSAppSyncRealTimeProvider';
81
- };
75
+ }
82
76
  // Check if url matches standard domain pattern
83
- AWSAppSyncRealTimeProvider.prototype.isCustomDomain = function (url) {
77
+ isCustomDomain(url) {
84
78
  return url.match(standardDomainPattern) === null;
85
- };
86
- AWSAppSyncRealTimeProvider.prototype.subscribe = function (options, customUserAgentDetails) {
87
- var _this = this;
88
- var _a = options || {}, appSyncGraphqlEndpoint = _a.appSyncGraphqlEndpoint, region = _a.region, query = _a.query, variables = _a.variables, authenticationType = _a.authenticationType, additionalHeaders = _a.additionalHeaders, apiKey = _a.apiKey;
89
- return new rxjs_1.Observable(function (observer) {
79
+ }
80
+ subscribe(options, customUserAgentDetails) {
81
+ const { appSyncGraphqlEndpoint, region, query, variables, authenticationType, additionalHeaders, apiKey, } = options || {};
82
+ return new rxjs_1.Observable(observer => {
90
83
  if (!options || !appSyncGraphqlEndpoint) {
91
84
  observer.error({
92
85
  errors: [
93
- tslib_1.__assign({}, new graphql_1.GraphQLError("Subscribe only available for AWS AppSync endpoint")),
86
+ {
87
+ ...new graphql_1.GraphQLError(`Subscribe only available for AWS AppSync endpoint`),
88
+ },
94
89
  ],
95
90
  });
96
91
  observer.complete();
97
92
  }
98
93
  else {
99
- var subscriptionStartActive_1 = false;
100
- var subscriptionId_1 = (0, utils_1.amplifyUuid)();
101
- var startSubscription_1 = function () {
102
- if (!subscriptionStartActive_1) {
103
- subscriptionStartActive_1 = true;
104
- var startSubscriptionPromise = _this._startSubscriptionWithAWSAppSyncRealTime({
94
+ let subscriptionStartActive = false;
95
+ const subscriptionId = utils_1.amplifyUuid();
96
+ const startSubscription = () => {
97
+ if (!subscriptionStartActive) {
98
+ subscriptionStartActive = true;
99
+ const startSubscriptionPromise = this._startSubscriptionWithAWSAppSyncRealTime({
105
100
  options: {
106
- query: query,
107
- variables: variables,
108
- region: region,
109
- authenticationType: authenticationType,
110
- appSyncGraphqlEndpoint: appSyncGraphqlEndpoint,
111
- additionalHeaders: additionalHeaders,
112
- apiKey: apiKey,
101
+ query,
102
+ variables,
103
+ region,
104
+ authenticationType,
105
+ appSyncGraphqlEndpoint,
106
+ additionalHeaders,
107
+ apiKey,
113
108
  },
114
- observer: observer,
115
- subscriptionId: subscriptionId_1,
116
- customUserAgentDetails: customUserAgentDetails,
117
- }).catch(function (err) {
118
- logger.debug("".concat(PubSub_1.CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR, ": ").concat(err));
119
- _this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
109
+ observer,
110
+ subscriptionId,
111
+ customUserAgentDetails,
112
+ }).catch(err => {
113
+ logger.debug(`${PubSub_1.CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR}: ${err}`);
114
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
120
115
  });
121
- startSubscriptionPromise.finally(function () {
122
- subscriptionStartActive_1 = false;
116
+ startSubscriptionPromise.finally(() => {
117
+ subscriptionStartActive = false;
123
118
  });
124
119
  }
125
120
  };
126
- var reconnectSubscription_1;
121
+ let reconnectSubscription;
127
122
  // Add an observable to the reconnection list to manage reconnection for this subscription
128
- reconnectSubscription_1 = new rxjs_1.Observable(function (observer) {
129
- _this.reconnectionMonitor.addObserver(observer);
130
- }).subscribe(function () {
131
- startSubscription_1();
123
+ reconnectSubscription = new rxjs_1.Observable(observer => {
124
+ this.reconnectionMonitor.addObserver(observer);
125
+ }).subscribe(() => {
126
+ startSubscription();
132
127
  });
133
- startSubscription_1();
134
- return function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
135
- var subscriptionState, err_1;
136
- return tslib_1.__generator(this, function (_a) {
137
- switch (_a.label) {
138
- case 0:
139
- // Cleanup reconnection subscription
140
- reconnectSubscription_1 === null || reconnectSubscription_1 === void 0 ? void 0 : reconnectSubscription_1.unsubscribe();
141
- _a.label = 1;
142
- case 1:
143
- _a.trys.push([1, 3, 4, 5]);
144
- // Waiting that subscription has been connected before trying to unsubscribe
145
- return [4 /*yield*/, this._waitForSubscriptionToBeConnected(subscriptionId_1)];
146
- case 2:
147
- // Waiting that subscription has been connected before trying to unsubscribe
148
- _a.sent();
149
- subscriptionState = (this.subscriptionObserverMap.get(subscriptionId_1) || {}).subscriptionState;
150
- if (!subscriptionState) {
151
- // subscription already unsubscribed
152
- return [2 /*return*/];
153
- }
154
- if (subscriptionState === constants_1.SUBSCRIPTION_STATUS.CONNECTED) {
155
- this._sendUnsubscriptionMessage(subscriptionId_1);
156
- }
157
- else {
158
- throw new Error('Subscription never connected');
159
- }
160
- return [3 /*break*/, 5];
161
- case 3:
162
- err_1 = _a.sent();
163
- logger.debug("Error while unsubscribing ".concat(err_1));
164
- return [3 /*break*/, 5];
165
- case 4:
166
- this._removeSubscriptionObserver(subscriptionId_1);
167
- return [7 /*endfinally*/];
168
- case 5: return [2 /*return*/];
128
+ startSubscription();
129
+ return async () => {
130
+ // Cleanup reconnection subscription
131
+ reconnectSubscription?.unsubscribe();
132
+ // Cleanup after unsubscribing or observer.complete was called after _startSubscriptionWithAWSAppSyncRealTime
133
+ try {
134
+ // Waiting that subscription has been connected before trying to unsubscribe
135
+ await this._waitForSubscriptionToBeConnected(subscriptionId);
136
+ const { subscriptionState } = this.subscriptionObserverMap.get(subscriptionId) || {};
137
+ if (!subscriptionState) {
138
+ // subscription already unsubscribed
139
+ return;
169
140
  }
170
- });
171
- }); };
141
+ if (subscriptionState === constants_1.SUBSCRIPTION_STATUS.CONNECTED) {
142
+ this._sendUnsubscriptionMessage(subscriptionId);
143
+ }
144
+ else {
145
+ throw new Error('Subscription never connected');
146
+ }
147
+ }
148
+ catch (err) {
149
+ logger.debug(`Error while unsubscribing ${err}`);
150
+ }
151
+ finally {
152
+ this._removeSubscriptionObserver(subscriptionId);
153
+ }
154
+ };
172
155
  }
173
156
  });
174
- };
175
- AWSAppSyncRealTimeProvider.prototype._startSubscriptionWithAWSAppSyncRealTime = function (_a) {
176
- var _b;
177
- var options = _a.options, observer = _a.observer, subscriptionId = _a.subscriptionId, customUserAgentDetails = _a.customUserAgentDetails;
178
- return tslib_1.__awaiter(this, void 0, void 0, function () {
179
- var appSyncGraphqlEndpoint, authenticationType, query, variables, apiKey, region, _c, graphql_headers, _d, additionalHeaders, subscriptionState, data, dataString, headerObj, _e, _f, subscriptionMessage, stringToAWSRealTime, err_2, _g, subscriptionFailedCallback, subscriptionReadyCallback;
180
- var _h;
181
- var _this = this;
182
- return tslib_1.__generator(this, function (_j) {
183
- switch (_j.label) {
184
- case 0:
185
- appSyncGraphqlEndpoint = options.appSyncGraphqlEndpoint, authenticationType = options.authenticationType, query = options.query, variables = options.variables, apiKey = options.apiKey, region = options.region, _c = options.graphql_headers, graphql_headers = _c === void 0 ? function () { return ({}); } : _c, _d = options.additionalHeaders, additionalHeaders = _d === void 0 ? {} : _d;
186
- subscriptionState = constants_1.SUBSCRIPTION_STATUS.PENDING;
187
- data = {
188
- query: query,
189
- variables: variables,
190
- };
191
- // Having a subscription id map will make it simple to forward messages received
192
- this.subscriptionObserverMap.set(subscriptionId, {
193
- observer: observer,
194
- query: query !== null && query !== void 0 ? query : '',
195
- variables: variables !== null && variables !== void 0 ? variables : {},
196
- subscriptionState: subscriptionState,
197
- startAckTimeoutId: undefined,
198
- });
199
- dataString = JSON.stringify(data);
200
- _e = [{}];
201
- return [4 /*yield*/, this._awsRealTimeHeaderBasedAuth({
202
- apiKey: apiKey,
203
- appSyncGraphqlEndpoint: appSyncGraphqlEndpoint,
204
- authenticationType: authenticationType,
205
- payload: dataString,
206
- canonicalUri: '',
207
- region: region,
208
- additionalHeaders: additionalHeaders,
209
- })];
210
- case 1:
211
- _f = [tslib_1.__assign.apply(void 0, _e.concat([(_j.sent())]))];
212
- return [4 /*yield*/, graphql_headers()];
213
- case 2:
214
- headerObj = tslib_1.__assign.apply(void 0, [tslib_1.__assign.apply(void 0, [tslib_1.__assign.apply(void 0, _f.concat([(_j.sent())])), additionalHeaders]), (_h = {}, _h[utils_1.USER_AGENT_HEADER] = (0, utils_1.getAmplifyUserAgent)(customUserAgentDetails), _h)]);
215
- subscriptionMessage = {
216
- id: subscriptionId,
217
- payload: {
218
- data: dataString,
219
- extensions: {
220
- authorization: tslib_1.__assign({}, headerObj),
221
- },
222
- },
223
- type: constants_1.MESSAGE_TYPES.GQL_START,
224
- };
225
- stringToAWSRealTime = JSON.stringify(subscriptionMessage);
226
- _j.label = 3;
227
- case 3:
228
- _j.trys.push([3, 5, , 6]);
229
- this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.OPENING_CONNECTION);
230
- return [4 /*yield*/, this._initializeWebSocketConnection({
231
- apiKey: apiKey,
232
- appSyncGraphqlEndpoint: appSyncGraphqlEndpoint,
233
- authenticationType: authenticationType,
234
- region: region,
235
- additionalHeaders: additionalHeaders,
236
- })];
237
- case 4:
238
- _j.sent();
239
- return [3 /*break*/, 6];
240
- case 5:
241
- err_2 = _j.sent();
242
- this._logStartSubscriptionError(subscriptionId, observer, err_2);
243
- return [2 /*return*/];
244
- case 6:
245
- _g = (_b = this.subscriptionObserverMap.get(subscriptionId)) !== null && _b !== void 0 ? _b : {}, subscriptionFailedCallback = _g.subscriptionFailedCallback, subscriptionReadyCallback = _g.subscriptionReadyCallback;
246
- // This must be done before sending the message in order to be listening immediately
247
- this.subscriptionObserverMap.set(subscriptionId, {
248
- observer: observer,
249
- subscriptionState: subscriptionState,
250
- query: query !== null && query !== void 0 ? query : '',
251
- variables: variables !== null && variables !== void 0 ? variables : {},
252
- subscriptionReadyCallback: subscriptionReadyCallback,
253
- subscriptionFailedCallback: subscriptionFailedCallback,
254
- startAckTimeoutId: setTimeout(function () {
255
- _this._timeoutStartSubscriptionAck.call(_this, subscriptionId);
256
- }, constants_1.START_ACK_TIMEOUT),
257
- });
258
- if (this.awsRealTimeSocket) {
259
- this.awsRealTimeSocket.send(stringToAWSRealTime);
260
- }
261
- return [2 /*return*/];
262
- }
157
+ }
158
+ async _startSubscriptionWithAWSAppSyncRealTime({ options, observer, subscriptionId, customUserAgentDetails, }) {
159
+ const { appSyncGraphqlEndpoint, authenticationType, query, variables, apiKey, region, graphql_headers = () => ({}), additionalHeaders = {}, } = options;
160
+ const subscriptionState = constants_1.SUBSCRIPTION_STATUS.PENDING;
161
+ const data = {
162
+ query,
163
+ variables,
164
+ };
165
+ // Having a subscription id map will make it simple to forward messages received
166
+ this.subscriptionObserverMap.set(subscriptionId, {
167
+ observer,
168
+ query: query ?? '',
169
+ variables: variables ?? {},
170
+ subscriptionState,
171
+ startAckTimeoutId: undefined,
172
+ });
173
+ // Preparing payload for subscription message
174
+ const dataString = JSON.stringify(data);
175
+ const headerObj = {
176
+ ...(await this._awsRealTimeHeaderBasedAuth({
177
+ apiKey,
178
+ appSyncGraphqlEndpoint,
179
+ authenticationType,
180
+ payload: dataString,
181
+ canonicalUri: '',
182
+ region,
183
+ additionalHeaders,
184
+ })),
185
+ ...(await graphql_headers()),
186
+ ...additionalHeaders,
187
+ [utils_1.USER_AGENT_HEADER]: utils_1.getAmplifyUserAgent(customUserAgentDetails),
188
+ };
189
+ const subscriptionMessage = {
190
+ id: subscriptionId,
191
+ payload: {
192
+ data: dataString,
193
+ extensions: {
194
+ authorization: {
195
+ ...headerObj,
196
+ },
197
+ },
198
+ },
199
+ type: constants_1.MESSAGE_TYPES.GQL_START,
200
+ };
201
+ const stringToAWSRealTime = JSON.stringify(subscriptionMessage);
202
+ try {
203
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.OPENING_CONNECTION);
204
+ await this._initializeWebSocketConnection({
205
+ apiKey,
206
+ appSyncGraphqlEndpoint,
207
+ authenticationType,
208
+ region,
209
+ additionalHeaders,
263
210
  });
211
+ }
212
+ catch (err) {
213
+ this._logStartSubscriptionError(subscriptionId, observer, err);
214
+ return;
215
+ }
216
+ // Potential race condition can occur when unsubscribe is called during _initializeWebSocketConnection.
217
+ // E.g.unsubscribe gets invoked prior to finishing WebSocket handshake or START_ACK.
218
+ // Both subscriptionFailedCallback and subscriptionReadyCallback are used to synchronized this.
219
+ const { subscriptionFailedCallback, subscriptionReadyCallback } = this.subscriptionObserverMap.get(subscriptionId) ?? {};
220
+ // This must be done before sending the message in order to be listening immediately
221
+ this.subscriptionObserverMap.set(subscriptionId, {
222
+ observer,
223
+ subscriptionState,
224
+ query: query ?? '',
225
+ variables: variables ?? {},
226
+ subscriptionReadyCallback,
227
+ subscriptionFailedCallback,
228
+ startAckTimeoutId: setTimeout(() => {
229
+ this._timeoutStartSubscriptionAck.call(this, subscriptionId);
230
+ }, constants_1.START_ACK_TIMEOUT),
264
231
  });
265
- };
232
+ if (this.awsRealTimeSocket) {
233
+ this.awsRealTimeSocket.send(stringToAWSRealTime);
234
+ }
235
+ }
266
236
  // Log logic for start subscription failures
267
- AWSAppSyncRealTimeProvider.prototype._logStartSubscriptionError = function (subscriptionId, observer, err) {
268
- var _a;
269
- logger.debug({ err: err });
270
- var message = String((_a = err.message) !== null && _a !== void 0 ? _a : '');
237
+ _logStartSubscriptionError(subscriptionId, observer, err) {
238
+ logger.debug({ err });
239
+ const message = String(err.message ?? '');
271
240
  // Resolving to give the state observer time to propogate the update
272
241
  Promise.resolve(this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED));
273
242
  // Capture the error only when the network didn't cause disruption
274
243
  if (this.connectionState !== PubSub_1.ConnectionState.ConnectionDisruptedPendingNetwork) {
275
244
  // When the error is non-retriable, error out the observable
276
- if ((0, utils_1.isNonRetryableError)(err)) {
245
+ if (utils_1.isNonRetryableError(err)) {
277
246
  observer.error({
278
247
  errors: [
279
- tslib_1.__assign({}, new graphql_1.GraphQLError("".concat(PubSub_1.CONTROL_MSG.CONNECTION_FAILED, ": ").concat(message))),
248
+ {
249
+ ...new graphql_1.GraphQLError(`${PubSub_1.CONTROL_MSG.CONNECTION_FAILED}: ${message}`),
250
+ },
280
251
  ],
281
252
  });
282
253
  }
283
254
  else {
284
- logger.debug("".concat(PubSub_1.CONTROL_MSG.CONNECTION_FAILED, ": ").concat(message));
255
+ logger.debug(`${PubSub_1.CONTROL_MSG.CONNECTION_FAILED}: ${message}`);
285
256
  }
286
- var subscriptionFailedCallback = (this.subscriptionObserverMap.get(subscriptionId) || {}).subscriptionFailedCallback;
257
+ const { subscriptionFailedCallback } = this.subscriptionObserverMap.get(subscriptionId) || {};
287
258
  // Notify concurrent unsubscription
288
259
  if (typeof subscriptionFailedCallback === 'function') {
289
260
  subscriptionFailedCallback();
290
261
  }
291
262
  }
292
- };
263
+ }
293
264
  // Waiting that subscription has been connected before trying to unsubscribe
294
- AWSAppSyncRealTimeProvider.prototype._waitForSubscriptionToBeConnected = function (subscriptionId) {
295
- return tslib_1.__awaiter(this, void 0, void 0, function () {
296
- var subscriptionObserver, subscriptionState;
297
- var _this = this;
298
- return tslib_1.__generator(this, function (_a) {
299
- subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
300
- if (subscriptionObserver) {
301
- subscriptionState = subscriptionObserver.subscriptionState;
302
- // This in case unsubscribe is invoked before sending start subscription message
303
- if (subscriptionState === constants_1.SUBSCRIPTION_STATUS.PENDING) {
304
- return [2 /*return*/, new Promise(function (res, rej) {
305
- var observer = subscriptionObserver.observer, subscriptionState = subscriptionObserver.subscriptionState, variables = subscriptionObserver.variables, query = subscriptionObserver.query;
306
- _this.subscriptionObserverMap.set(subscriptionId, {
307
- observer: observer,
308
- subscriptionState: subscriptionState,
309
- variables: variables,
310
- query: query,
311
- subscriptionReadyCallback: res,
312
- subscriptionFailedCallback: rej,
313
- });
314
- })];
315
- }
316
- }
317
- return [2 /*return*/];
318
- });
319
- });
320
- };
321
- AWSAppSyncRealTimeProvider.prototype._sendUnsubscriptionMessage = function (subscriptionId) {
265
+ async _waitForSubscriptionToBeConnected(subscriptionId) {
266
+ const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
267
+ if (subscriptionObserver) {
268
+ const { subscriptionState } = subscriptionObserver;
269
+ // This in case unsubscribe is invoked before sending start subscription message
270
+ if (subscriptionState === constants_1.SUBSCRIPTION_STATUS.PENDING) {
271
+ return new Promise((res, rej) => {
272
+ const { observer, subscriptionState, variables, query } = subscriptionObserver;
273
+ this.subscriptionObserverMap.set(subscriptionId, {
274
+ observer,
275
+ subscriptionState,
276
+ variables,
277
+ query,
278
+ subscriptionReadyCallback: res,
279
+ subscriptionFailedCallback: rej,
280
+ });
281
+ });
282
+ }
283
+ }
284
+ }
285
+ _sendUnsubscriptionMessage(subscriptionId) {
322
286
  try {
323
287
  if (this.awsRealTimeSocket &&
324
288
  this.awsRealTimeSocket.readyState === WebSocket.OPEN &&
325
289
  this.socketStatus === constants_1.SOCKET_STATUS.READY) {
326
290
  // Preparing unsubscribe message to stop receiving messages for that subscription
327
- var unsubscribeMessage = {
291
+ const unsubscribeMessage = {
328
292
  id: subscriptionId,
329
293
  type: constants_1.MESSAGE_TYPES.GQL_STOP,
330
294
  };
331
- var stringToAWSRealTime = JSON.stringify(unsubscribeMessage);
295
+ const stringToAWSRealTime = JSON.stringify(unsubscribeMessage);
332
296
  this.awsRealTimeSocket.send(stringToAWSRealTime);
333
297
  }
334
298
  }
335
299
  catch (err) {
336
300
  // If GQL_STOP is not sent because of disconnection issue, then there is nothing the client can do
337
- logger.debug({ err: err });
301
+ logger.debug({ err });
338
302
  }
339
- };
340
- AWSAppSyncRealTimeProvider.prototype._removeSubscriptionObserver = function (subscriptionId) {
303
+ }
304
+ _removeSubscriptionObserver(subscriptionId) {
341
305
  this.subscriptionObserverMap.delete(subscriptionId);
342
306
  // Verifying 1000ms after removing subscription in case there are new subscription unmount/mount
343
307
  setTimeout(this._closeSocketIfRequired.bind(this), 1000);
344
- };
345
- AWSAppSyncRealTimeProvider.prototype._closeSocketIfRequired = function () {
308
+ }
309
+ _closeSocketIfRequired() {
346
310
  if (this.subscriptionObserverMap.size > 0) {
347
311
  // Active subscriptions on the WebSocket
348
312
  return;
@@ -364,7 +328,7 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function () {
364
328
  if (this.keepAliveAlertTimeoutId) {
365
329
  clearTimeout(this.keepAliveAlertTimeoutId);
366
330
  }
367
- var tempSocket = this.awsRealTimeSocket;
331
+ const tempSocket = this.awsRealTimeSocket;
368
332
  // Cleaning callbacks to avoid race condition, socket still exists
369
333
  tempSocket.onclose = null;
370
334
  tempSocket.onerror = null;
@@ -373,27 +337,26 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function () {
373
337
  this.socketStatus = constants_1.SOCKET_STATUS.CLOSED;
374
338
  this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
375
339
  }
376
- };
377
- AWSAppSyncRealTimeProvider.prototype._handleIncomingSubscriptionMessage = function (message) {
378
- var _this = this;
340
+ }
341
+ _handleIncomingSubscriptionMessage(message) {
379
342
  if (typeof message.data !== 'string') {
380
343
  return;
381
344
  }
382
- logger.debug("subscription message from AWS AppSync RealTime: ".concat(message.data));
383
- var _a = JSON.parse(String(message.data)), _b = _a.id, id = _b === void 0 ? '' : _b, payload = _a.payload, type = _a.type;
384
- var _c = this.subscriptionObserverMap.get(id) || {}, _d = _c.observer, observer = _d === void 0 ? null : _d, _e = _c.query, query = _e === void 0 ? '' : _e, _f = _c.variables, variables = _f === void 0 ? {} : _f, startAckTimeoutId = _c.startAckTimeoutId, subscriptionReadyCallback = _c.subscriptionReadyCallback, subscriptionFailedCallback = _c.subscriptionFailedCallback;
385
- logger.debug({ id: id, observer: observer, query: query, variables: variables });
345
+ logger.debug(`subscription message from AWS AppSync RealTime: ${message.data}`);
346
+ const { id = '', payload, type, } = JSON.parse(String(message.data));
347
+ const { observer = null, query = '', variables = {}, startAckTimeoutId, subscriptionReadyCallback, subscriptionFailedCallback, } = this.subscriptionObserverMap.get(id) || {};
348
+ logger.debug({ id, observer, query, variables });
386
349
  if (type === constants_1.MESSAGE_TYPES.GQL_DATA && payload && payload.data) {
387
350
  if (observer) {
388
351
  observer.next(payload);
389
352
  }
390
353
  else {
391
- logger.debug("observer not found for id: ".concat(id));
354
+ logger.debug(`observer not found for id: ${id}`);
392
355
  }
393
356
  return;
394
357
  }
395
358
  if (type === constants_1.MESSAGE_TYPES.GQL_START_ACK) {
396
- logger.debug("subscription ready for ".concat(JSON.stringify({ query: query, variables: variables })));
359
+ logger.debug(`subscription ready for ${JSON.stringify({ query, variables })}`);
397
360
  if (typeof subscriptionReadyCallback === 'function') {
398
361
  subscriptionReadyCallback();
399
362
  }
@@ -401,19 +364,19 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function () {
401
364
  clearTimeout(startAckTimeoutId);
402
365
  dispatchApiEvent({
403
366
  event: PubSub_1.CONTROL_MSG.SUBSCRIPTION_ACK,
404
- data: { query: query, variables: variables },
367
+ data: { query, variables },
405
368
  message: 'Connection established for subscription',
406
369
  });
407
- var subscriptionState = constants_1.SUBSCRIPTION_STATUS.CONNECTED;
370
+ const subscriptionState = constants_1.SUBSCRIPTION_STATUS.CONNECTED;
408
371
  if (observer) {
409
372
  this.subscriptionObserverMap.set(id, {
410
- observer: observer,
411
- query: query,
412
- variables: variables,
373
+ observer,
374
+ query,
375
+ variables,
413
376
  startAckTimeoutId: undefined,
414
- subscriptionState: subscriptionState,
415
- subscriptionReadyCallback: subscriptionReadyCallback,
416
- subscriptionFailedCallback: subscriptionFailedCallback,
377
+ subscriptionState,
378
+ subscriptionReadyCallback,
379
+ subscriptionFailedCallback,
417
380
  });
418
381
  }
419
382
  this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CONNECTION_ESTABLISHED);
@@ -424,29 +387,31 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function () {
424
387
  clearTimeout(this.keepAliveTimeoutId);
425
388
  if (this.keepAliveAlertTimeoutId)
426
389
  clearTimeout(this.keepAliveAlertTimeoutId);
427
- this.keepAliveTimeoutId = setTimeout(function () { return _this._errorDisconnect(PubSub_1.CONTROL_MSG.TIMEOUT_DISCONNECT); }, this.keepAliveTimeout);
428
- this.keepAliveAlertTimeoutId = setTimeout(function () {
429
- _this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.KEEP_ALIVE_MISSED);
390
+ this.keepAliveTimeoutId = setTimeout(() => this._errorDisconnect(PubSub_1.CONTROL_MSG.TIMEOUT_DISCONNECT), this.keepAliveTimeout);
391
+ this.keepAliveAlertTimeoutId = setTimeout(() => {
392
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.KEEP_ALIVE_MISSED);
430
393
  }, constants_1.DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT);
431
394
  this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.KEEP_ALIVE);
432
395
  return;
433
396
  }
434
397
  if (type === constants_1.MESSAGE_TYPES.GQL_ERROR) {
435
- var subscriptionState = constants_1.SUBSCRIPTION_STATUS.FAILED;
398
+ const subscriptionState = constants_1.SUBSCRIPTION_STATUS.FAILED;
436
399
  if (observer) {
437
400
  this.subscriptionObserverMap.set(id, {
438
- observer: observer,
439
- query: query,
440
- variables: variables,
441
- startAckTimeoutId: startAckTimeoutId,
442
- subscriptionReadyCallback: subscriptionReadyCallback,
443
- subscriptionFailedCallback: subscriptionFailedCallback,
444
- subscriptionState: subscriptionState,
401
+ observer,
402
+ query,
403
+ variables,
404
+ startAckTimeoutId,
405
+ subscriptionReadyCallback,
406
+ subscriptionFailedCallback,
407
+ subscriptionState,
445
408
  });
446
- logger.debug("".concat(PubSub_1.CONTROL_MSG.CONNECTION_FAILED, ": ").concat(JSON.stringify(payload)));
409
+ logger.debug(`${PubSub_1.CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`);
447
410
  observer.error({
448
411
  errors: [
449
- tslib_1.__assign({}, new graphql_1.GraphQLError("".concat(PubSub_1.CONTROL_MSG.CONNECTION_FAILED, ": ").concat(JSON.stringify(payload)))),
412
+ {
413
+ ...new graphql_1.GraphQLError(`${PubSub_1.CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`),
414
+ },
450
415
  ],
451
416
  });
452
417
  if (startAckTimeoutId)
@@ -456,351 +421,270 @@ var AWSAppSyncRealTimeProvider = /** @class */ (function () {
456
421
  }
457
422
  }
458
423
  }
459
- };
460
- AWSAppSyncRealTimeProvider.prototype._errorDisconnect = function (msg) {
461
- logger.debug("Disconnect error: ".concat(msg));
424
+ }
425
+ _errorDisconnect(msg) {
426
+ logger.debug(`Disconnect error: ${msg}`);
462
427
  if (this.awsRealTimeSocket) {
463
428
  this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
464
429
  this.awsRealTimeSocket.close();
465
430
  }
466
431
  this.socketStatus = constants_1.SOCKET_STATUS.CLOSED;
467
- };
468
- AWSAppSyncRealTimeProvider.prototype._timeoutStartSubscriptionAck = function (subscriptionId) {
469
- var subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
432
+ }
433
+ _timeoutStartSubscriptionAck(subscriptionId) {
434
+ const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
470
435
  if (subscriptionObserver) {
471
- var observer = subscriptionObserver.observer, query = subscriptionObserver.query, variables = subscriptionObserver.variables;
436
+ const { observer, query, variables } = subscriptionObserver;
472
437
  if (!observer) {
473
438
  return;
474
439
  }
475
440
  this.subscriptionObserverMap.set(subscriptionId, {
476
- observer: observer,
477
- query: query,
478
- variables: variables,
441
+ observer,
442
+ query,
443
+ variables,
479
444
  subscriptionState: constants_1.SUBSCRIPTION_STATUS.FAILED,
480
445
  });
481
446
  this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CLOSED);
482
- logger.debug('timeoutStartSubscription', JSON.stringify({ query: query, variables: variables }));
447
+ logger.debug('timeoutStartSubscription', JSON.stringify({ query, variables }));
483
448
  }
484
- };
485
- AWSAppSyncRealTimeProvider.prototype._initializeWebSocketConnection = function (_a) {
486
- var _this = this;
487
- var appSyncGraphqlEndpoint = _a.appSyncGraphqlEndpoint, authenticationType = _a.authenticationType, apiKey = _a.apiKey, region = _a.region, additionalHeaders = _a.additionalHeaders;
449
+ }
450
+ _initializeWebSocketConnection({ appSyncGraphqlEndpoint, authenticationType, apiKey, region, additionalHeaders, }) {
488
451
  if (this.socketStatus === constants_1.SOCKET_STATUS.READY) {
489
452
  return;
490
453
  }
491
- return new Promise(function (res, rej) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
492
- var payloadString, authHeader, headerString, headerQs, payloadQs, discoverableEndpoint, protocol, awsRealTimeUrl, err_3;
493
- return tslib_1.__generator(this, function (_a) {
494
- switch (_a.label) {
495
- case 0:
496
- this.promiseArray.push({ res: res, rej: rej });
497
- if (!(this.socketStatus === constants_1.SOCKET_STATUS.CLOSED)) return [3 /*break*/, 5];
498
- _a.label = 1;
499
- case 1:
500
- _a.trys.push([1, 4, , 5]);
501
- this.socketStatus = constants_1.SOCKET_STATUS.CONNECTING;
502
- payloadString = '{}';
503
- return [4 /*yield*/, this._awsRealTimeHeaderBasedAuth({
504
- authenticationType: authenticationType,
505
- payload: payloadString,
506
- canonicalUri: '/connect',
507
- apiKey: apiKey,
508
- appSyncGraphqlEndpoint: appSyncGraphqlEndpoint,
509
- region: region,
510
- additionalHeaders: additionalHeaders,
511
- })];
512
- case 2:
513
- authHeader = _a.sent();
514
- headerString = authHeader ? JSON.stringify(authHeader) : '';
515
- headerQs = buffer_1.Buffer.from(headerString).toString('base64');
516
- payloadQs = buffer_1.Buffer.from(payloadString).toString('base64');
517
- discoverableEndpoint = appSyncGraphqlEndpoint !== null && appSyncGraphqlEndpoint !== void 0 ? appSyncGraphqlEndpoint : '';
518
- if (this.isCustomDomain(discoverableEndpoint)) {
519
- discoverableEndpoint =
520
- discoverableEndpoint.concat(customDomainPath);
521
- }
522
- else {
523
- discoverableEndpoint = discoverableEndpoint
524
- .replace('appsync-api', 'appsync-realtime-api')
525
- .replace('gogi-beta', 'grt-beta');
526
- }
527
- protocol = 'wss://';
454
+ return new Promise(async (res, rej) => {
455
+ this.promiseArray.push({ res, rej });
456
+ if (this.socketStatus === constants_1.SOCKET_STATUS.CLOSED) {
457
+ try {
458
+ this.socketStatus = constants_1.SOCKET_STATUS.CONNECTING;
459
+ const payloadString = '{}';
460
+ const authHeader = await this._awsRealTimeHeaderBasedAuth({
461
+ authenticationType,
462
+ payload: payloadString,
463
+ canonicalUri: '/connect',
464
+ apiKey,
465
+ appSyncGraphqlEndpoint,
466
+ region,
467
+ additionalHeaders,
468
+ });
469
+ const headerString = authHeader ? JSON.stringify(authHeader) : '';
470
+ const headerQs = utils_1.base64Encoder.convert(headerString);
471
+ const payloadQs = utils_1.base64Encoder.convert(payloadString);
472
+ let discoverableEndpoint = appSyncGraphqlEndpoint ?? '';
473
+ if (this.isCustomDomain(discoverableEndpoint)) {
474
+ discoverableEndpoint =
475
+ discoverableEndpoint.concat(customDomainPath);
476
+ }
477
+ else {
528
478
  discoverableEndpoint = discoverableEndpoint
529
- .replace('https://', protocol)
530
- .replace('http://', protocol);
531
- awsRealTimeUrl = "".concat(discoverableEndpoint, "?header=").concat(headerQs, "&payload=").concat(payloadQs);
532
- return [4 /*yield*/, this._initializeRetryableHandshake(awsRealTimeUrl)];
533
- case 3:
534
- _a.sent();
535
- this.promiseArray.forEach(function (_a) {
536
- var res = _a.res;
537
- logger.debug('Notifying connection successful');
538
- res();
539
- });
540
- this.socketStatus = constants_1.SOCKET_STATUS.READY;
541
- this.promiseArray = [];
542
- return [3 /*break*/, 5];
543
- case 4:
544
- err_3 = _a.sent();
545
- logger.debug('Connection exited with', err_3);
546
- this.promiseArray.forEach(function (_a) {
547
- var rej = _a.rej;
548
- return rej(err_3);
549
- });
550
- this.promiseArray = [];
551
- if (this.awsRealTimeSocket &&
552
- this.awsRealTimeSocket.readyState === WebSocket.OPEN) {
553
- this.awsRealTimeSocket.close(3001);
554
- }
555
- this.awsRealTimeSocket = undefined;
556
- this.socketStatus = constants_1.SOCKET_STATUS.CLOSED;
557
- return [3 /*break*/, 5];
558
- case 5: return [2 /*return*/];
479
+ .replace('appsync-api', 'appsync-realtime-api')
480
+ .replace('gogi-beta', 'grt-beta');
481
+ }
482
+ // Creating websocket url with required query strings
483
+ const protocol = 'wss://';
484
+ discoverableEndpoint = discoverableEndpoint
485
+ .replace('https://', protocol)
486
+ .replace('http://', protocol);
487
+ const awsRealTimeUrl = `${discoverableEndpoint}?header=${headerQs}&payload=${payloadQs}`;
488
+ await this._initializeRetryableHandshake(awsRealTimeUrl);
489
+ this.promiseArray.forEach(({ res }) => {
490
+ logger.debug('Notifying connection successful');
491
+ res();
492
+ });
493
+ this.socketStatus = constants_1.SOCKET_STATUS.READY;
494
+ this.promiseArray = [];
559
495
  }
560
- });
561
- }); });
562
- };
563
- AWSAppSyncRealTimeProvider.prototype._initializeRetryableHandshake = function (awsRealTimeUrl) {
564
- return tslib_1.__awaiter(this, void 0, void 0, function () {
565
- return tslib_1.__generator(this, function (_a) {
566
- switch (_a.label) {
567
- case 0:
568
- logger.debug("Initializaling retryable Handshake");
569
- return [4 /*yield*/, (0, utils_1.jitteredExponentialRetry)(this._initializeHandshake.bind(this), [awsRealTimeUrl], constants_1.MAX_DELAY_MS)];
570
- case 1:
571
- _a.sent();
572
- return [2 /*return*/];
496
+ catch (err) {
497
+ logger.debug('Connection exited with', err);
498
+ this.promiseArray.forEach(({ rej }) => rej(err));
499
+ this.promiseArray = [];
500
+ if (this.awsRealTimeSocket &&
501
+ this.awsRealTimeSocket.readyState === WebSocket.OPEN) {
502
+ this.awsRealTimeSocket.close(3001);
503
+ }
504
+ this.awsRealTimeSocket = undefined;
505
+ this.socketStatus = constants_1.SOCKET_STATUS.CLOSED;
573
506
  }
574
- });
507
+ }
575
508
  });
576
- };
577
- AWSAppSyncRealTimeProvider.prototype._initializeHandshake = function (awsRealTimeUrl) {
578
- return tslib_1.__awaiter(this, void 0, void 0, function () {
579
- var err_4, _a, errorType, errorCode;
580
- var _this = this;
581
- return tslib_1.__generator(this, function (_b) {
582
- switch (_b.label) {
583
- case 0:
584
- logger.debug("Initializing handshake ".concat(awsRealTimeUrl));
585
- _b.label = 1;
586
- case 1:
587
- _b.trys.push([1, 4, , 5]);
588
- return [4 /*yield*/, (function () {
589
- return new Promise(function (res, rej) {
590
- var newSocket = _this.getNewWebSocket(awsRealTimeUrl, 'graphql-ws');
591
- newSocket.onerror = function () {
592
- logger.debug("WebSocket connection error");
593
- };
594
- newSocket.onclose = function () {
595
- rej(new Error('Connection handshake error'));
509
+ }
510
+ async _initializeRetryableHandshake(awsRealTimeUrl) {
511
+ logger.debug(`Initializaling retryable Handshake`);
512
+ await utils_1.jitteredExponentialRetry(this._initializeHandshake.bind(this), [awsRealTimeUrl], constants_1.MAX_DELAY_MS);
513
+ }
514
+ async _initializeHandshake(awsRealTimeUrl) {
515
+ logger.debug(`Initializing handshake ${awsRealTimeUrl}`);
516
+ // Because connecting the socket is async, is waiting until connection is open
517
+ // Step 1: connect websocket
518
+ try {
519
+ await (() => {
520
+ return new Promise((res, rej) => {
521
+ const newSocket = this.getNewWebSocket(awsRealTimeUrl, 'graphql-ws');
522
+ newSocket.onerror = () => {
523
+ logger.debug(`WebSocket connection error`);
524
+ };
525
+ newSocket.onclose = () => {
526
+ rej(new Error('Connection handshake error'));
527
+ };
528
+ newSocket.onopen = () => {
529
+ this.awsRealTimeSocket = newSocket;
530
+ return res();
531
+ };
532
+ });
533
+ })();
534
+ // Step 2: wait for ack from AWS AppSyncReaTime after sending init
535
+ await (() => {
536
+ return new Promise((res, rej) => {
537
+ if (this.awsRealTimeSocket) {
538
+ let ackOk = false;
539
+ this.awsRealTimeSocket.onerror = error => {
540
+ logger.debug(`WebSocket error ${JSON.stringify(error)}`);
541
+ };
542
+ this.awsRealTimeSocket.onclose = event => {
543
+ logger.debug(`WebSocket closed ${event.reason}`);
544
+ rej(new Error(JSON.stringify(event)));
545
+ };
546
+ this.awsRealTimeSocket.onmessage = (message) => {
547
+ if (typeof message.data !== 'string') {
548
+ return;
549
+ }
550
+ logger.debug(`subscription message from AWS AppSyncRealTime: ${message.data} `);
551
+ const data = JSON.parse(message.data);
552
+ const { type, payload: { connectionTimeoutMs = constants_1.DEFAULT_KEEP_ALIVE_TIMEOUT, } = {}, } = data;
553
+ if (type === constants_1.MESSAGE_TYPES.GQL_CONNECTION_ACK) {
554
+ ackOk = true;
555
+ if (this.awsRealTimeSocket) {
556
+ this.keepAliveTimeout = connectionTimeoutMs;
557
+ this.awsRealTimeSocket.onmessage =
558
+ this._handleIncomingSubscriptionMessage.bind(this);
559
+ this.awsRealTimeSocket.onerror = err => {
560
+ logger.debug(err);
561
+ this._errorDisconnect(PubSub_1.CONTROL_MSG.CONNECTION_CLOSED);
596
562
  };
597
- newSocket.onopen = function () {
598
- _this.awsRealTimeSocket = newSocket;
599
- return res();
563
+ this.awsRealTimeSocket.onclose = event => {
564
+ logger.debug(`WebSocket closed ${event.reason}`);
565
+ this._errorDisconnect(PubSub_1.CONTROL_MSG.CONNECTION_CLOSED);
600
566
  };
601
- });
602
- })()];
603
- case 2:
604
- _b.sent();
605
- // Step 2: wait for ack from AWS AppSyncReaTime after sending init
606
- return [4 /*yield*/, (function () {
607
- return new Promise(function (res, rej) {
608
- if (_this.awsRealTimeSocket) {
609
- var ackOk_1 = false;
610
- _this.awsRealTimeSocket.onerror = function (error) {
611
- logger.debug("WebSocket error ".concat(JSON.stringify(error)));
612
- };
613
- _this.awsRealTimeSocket.onclose = function (event) {
614
- logger.debug("WebSocket closed ".concat(event.reason));
615
- rej(new Error(JSON.stringify(event)));
616
- };
617
- _this.awsRealTimeSocket.onmessage = function (message) {
618
- if (typeof message.data !== 'string') {
619
- return;
620
- }
621
- logger.debug("subscription message from AWS AppSyncRealTime: ".concat(message.data, " "));
622
- var data = JSON.parse(message.data);
623
- var type = data.type, _a = data.payload, _b = _a === void 0 ? {} : _a, _c = _b.connectionTimeoutMs, connectionTimeoutMs = _c === void 0 ? constants_1.DEFAULT_KEEP_ALIVE_TIMEOUT : _c;
624
- if (type === constants_1.MESSAGE_TYPES.GQL_CONNECTION_ACK) {
625
- ackOk_1 = true;
626
- if (_this.awsRealTimeSocket) {
627
- _this.keepAliveTimeout = connectionTimeoutMs;
628
- _this.awsRealTimeSocket.onmessage =
629
- _this._handleIncomingSubscriptionMessage.bind(_this);
630
- _this.awsRealTimeSocket.onerror = function (err) {
631
- logger.debug(err);
632
- _this._errorDisconnect(PubSub_1.CONTROL_MSG.CONNECTION_CLOSED);
633
- };
634
- _this.awsRealTimeSocket.onclose = function (event) {
635
- logger.debug("WebSocket closed ".concat(event.reason));
636
- _this._errorDisconnect(PubSub_1.CONTROL_MSG.CONNECTION_CLOSED);
637
- };
638
- }
639
- res('Cool, connected to AWS AppSyncRealTime');
640
- return;
641
- }
642
- if (type === constants_1.MESSAGE_TYPES.GQL_CONNECTION_ERROR) {
643
- var _d = data.payload, _e = _d === void 0 ? {} : _d, _f = _e.errors, _g = _f === void 0 ? [] : _f, _h = tslib_1.__read(_g, 1), _j = _h[0], _k = _j === void 0 ? {} : _j, _l = _k.errorType, errorType = _l === void 0 ? '' : _l, _m = _k.errorCode, errorCode = _m === void 0 ? 0 : _m;
644
- rej({ errorType: errorType, errorCode: errorCode });
645
- }
646
- };
647
- var gqlInit = {
648
- type: constants_1.MESSAGE_TYPES.GQL_CONNECTION_INIT,
649
- };
650
- _this.awsRealTimeSocket.send(JSON.stringify(gqlInit));
651
- var checkAckOk_1 = function (ackOk) {
652
- if (!ackOk) {
653
- _this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CONNECTION_FAILED);
654
- rej(new Error("Connection timeout: ack from AWSAppSyncRealTime was not received after ".concat(constants_1.CONNECTION_INIT_TIMEOUT, " ms")));
655
- }
656
- };
657
- setTimeout(function () { return checkAckOk_1(ackOk_1); }, constants_1.CONNECTION_INIT_TIMEOUT);
658
- }
659
- });
660
- })()];
661
- case 3:
662
- // Step 2: wait for ack from AWS AppSyncReaTime after sending init
663
- _b.sent();
664
- return [3 /*break*/, 5];
665
- case 4:
666
- err_4 = _b.sent();
667
- _a = err_4, errorType = _a.errorType, errorCode = _a.errorCode;
668
- if (constants_1.NON_RETRYABLE_CODES.includes(errorCode)) {
669
- throw new utils_1.NonRetryableError(errorType);
670
- }
671
- else if (errorType) {
672
- throw new Error(errorType);
673
- }
674
- else {
675
- throw err_4;
676
- }
677
- return [3 /*break*/, 5];
678
- case 5: return [2 /*return*/];
679
- }
680
- });
681
- });
682
- };
683
- AWSAppSyncRealTimeProvider.prototype._awsRealTimeHeaderBasedAuth = function (_a) {
684
- var apiKey = _a.apiKey, authenticationType = _a.authenticationType, payload = _a.payload, canonicalUri = _a.canonicalUri, appSyncGraphqlEndpoint = _a.appSyncGraphqlEndpoint, region = _a.region, additionalHeaders = _a.additionalHeaders;
685
- return tslib_1.__awaiter(this, void 0, void 0, function () {
686
- var headerHandler, handler, host, resolvedApiKey, result;
687
- return tslib_1.__generator(this, function (_b) {
688
- switch (_b.label) {
689
- case 0:
690
- headerHandler = {
691
- apiKey: this._awsRealTimeApiKeyHeader.bind(this),
692
- iam: this._awsRealTimeIAMHeader.bind(this),
693
- oidc: this._awsAuthTokenHeader.bind(this),
694
- userPool: this._awsAuthTokenHeader.bind(this),
695
- lambda: this._customAuthHeader,
696
- none: this._customAuthHeader,
567
+ }
568
+ res('Cool, connected to AWS AppSyncRealTime');
569
+ return;
570
+ }
571
+ if (type === constants_1.MESSAGE_TYPES.GQL_CONNECTION_ERROR) {
572
+ const { payload: { errors: [{ errorType = '', errorCode = 0 } = {}] = [], } = {}, } = data;
573
+ rej({ errorType, errorCode });
574
+ }
697
575
  };
698
- if (!(!authenticationType || !headerHandler[authenticationType])) return [3 /*break*/, 1];
699
- logger.debug("Authentication type ".concat(authenticationType, " not supported"));
700
- return [2 /*return*/, undefined];
701
- case 1:
702
- handler = headerHandler[authenticationType];
703
- host = url.parse(appSyncGraphqlEndpoint !== null && appSyncGraphqlEndpoint !== void 0 ? appSyncGraphqlEndpoint : '').host;
704
- logger.debug("Authenticating with ".concat(JSON.stringify(authenticationType)));
705
- resolvedApiKey = void 0;
706
- if (authenticationType === 'apiKey') {
707
- resolvedApiKey = apiKey;
708
- }
709
- return [4 /*yield*/, handler({
710
- payload: payload,
711
- canonicalUri: canonicalUri,
712
- appSyncGraphqlEndpoint: appSyncGraphqlEndpoint,
713
- apiKey: resolvedApiKey,
714
- region: region,
715
- host: host,
716
- additionalHeaders: additionalHeaders,
717
- })];
718
- case 2:
719
- result = _b.sent();
720
- return [2 /*return*/, result];
721
- }
722
- });
723
- });
724
- };
725
- AWSAppSyncRealTimeProvider.prototype._awsAuthTokenHeader = function (_a) {
726
- var _b, _c;
727
- var host = _a.host;
728
- return tslib_1.__awaiter(this, void 0, void 0, function () {
729
- var session;
730
- return tslib_1.__generator(this, function (_d) {
731
- switch (_d.label) {
732
- case 0: return [4 /*yield*/, (0, core_1.fetchAuthSession)()];
733
- case 1:
734
- session = _d.sent();
735
- return [2 /*return*/, {
736
- Authorization: (_c = (_b = session === null || session === void 0 ? void 0 : session.tokens) === null || _b === void 0 ? void 0 : _b.accessToken) === null || _c === void 0 ? void 0 : _c.toString(),
737
- host: host,
738
- }];
739
- }
740
- });
741
- });
742
- };
743
- AWSAppSyncRealTimeProvider.prototype._awsRealTimeApiKeyHeader = function (_a) {
744
- var apiKey = _a.apiKey, host = _a.host;
745
- return tslib_1.__awaiter(this, void 0, void 0, function () {
746
- var dt, dtStr;
747
- return tslib_1.__generator(this, function (_b) {
748
- dt = new Date();
749
- dtStr = dt.toISOString().replace(/[:\-]|\.\d{3}/g, '');
750
- return [2 /*return*/, {
751
- host: host,
752
- 'x-amz-date': dtStr,
753
- 'x-api-key': apiKey,
754
- }];
755
- });
756
- });
757
- };
758
- AWSAppSyncRealTimeProvider.prototype._awsRealTimeIAMHeader = function (_a) {
759
- var payload = _a.payload, canonicalUri = _a.canonicalUri, appSyncGraphqlEndpoint = _a.appSyncGraphqlEndpoint, region = _a.region;
760
- return tslib_1.__awaiter(this, void 0, void 0, function () {
761
- var endpointInfo, creds, request, signed_params;
762
- return tslib_1.__generator(this, function (_b) {
763
- switch (_b.label) {
764
- case 0:
765
- endpointInfo = {
766
- region: region,
767
- service: 'appsync',
576
+ const gqlInit = {
577
+ type: constants_1.MESSAGE_TYPES.GQL_CONNECTION_INIT,
768
578
  };
769
- return [4 /*yield*/, (0, core_1.fetchAuthSession)()];
770
- case 1:
771
- creds = (_b.sent()).credentials;
772
- request = {
773
- url: "".concat(appSyncGraphqlEndpoint).concat(canonicalUri),
774
- data: payload,
775
- method: 'POST',
776
- headers: tslib_1.__assign({}, constants_1.AWS_APPSYNC_REALTIME_HEADERS),
579
+ this.awsRealTimeSocket.send(JSON.stringify(gqlInit));
580
+ const checkAckOk = (ackOk) => {
581
+ if (!ackOk) {
582
+ this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CONNECTION_FAILED);
583
+ rej(new Error(`Connection timeout: ack from AWSAppSyncRealTime was not received after ${constants_1.CONNECTION_INIT_TIMEOUT} ms`));
584
+ }
777
585
  };
778
- signed_params = (0, aws_client_utils_1.signRequest)({
779
- headers: request.headers,
780
- method: request.method,
781
- url: new utils_1.AmplifyUrl(request.url),
782
- body: request.data,
783
- }, {
784
- // TODO: What do we need to do to remove these !'s?
785
- credentials: creds,
786
- signingRegion: endpointInfo.region,
787
- signingService: endpointInfo.service,
788
- });
789
- return [2 /*return*/, signed_params.headers];
790
- }
586
+ setTimeout(() => checkAckOk(ackOk), constants_1.CONNECTION_INIT_TIMEOUT);
587
+ }
588
+ });
589
+ })();
590
+ }
591
+ catch (err) {
592
+ const { errorType, errorCode } = err;
593
+ if (constants_1.NON_RETRYABLE_CODES.includes(errorCode)) {
594
+ throw new utils_1.NonRetryableError(errorType);
595
+ }
596
+ else if (errorType) {
597
+ throw new Error(errorType);
598
+ }
599
+ else {
600
+ throw err;
601
+ }
602
+ }
603
+ }
604
+ async _awsRealTimeHeaderBasedAuth({ apiKey, authenticationType, payload, canonicalUri, appSyncGraphqlEndpoint, region, additionalHeaders, }) {
605
+ const headerHandler = {
606
+ apiKey: this._awsRealTimeApiKeyHeader.bind(this),
607
+ iam: this._awsRealTimeIAMHeader.bind(this),
608
+ oidc: this._awsAuthTokenHeader.bind(this),
609
+ userPool: this._awsAuthTokenHeader.bind(this),
610
+ lambda: this._customAuthHeader,
611
+ none: this._customAuthHeader,
612
+ };
613
+ if (!authenticationType || !headerHandler[authenticationType]) {
614
+ logger.debug(`Authentication type ${authenticationType} not supported`);
615
+ return undefined;
616
+ }
617
+ else {
618
+ const handler = headerHandler[authenticationType];
619
+ const host = appSyncGraphqlEndpoint
620
+ ? new utils_1.AmplifyUrl(appSyncGraphqlEndpoint).host
621
+ : undefined;
622
+ logger.debug(`Authenticating with ${JSON.stringify(authenticationType)}`);
623
+ let resolvedApiKey;
624
+ if (authenticationType === 'apiKey') {
625
+ resolvedApiKey = apiKey;
626
+ }
627
+ const result = await handler({
628
+ payload,
629
+ canonicalUri,
630
+ appSyncGraphqlEndpoint,
631
+ apiKey: resolvedApiKey,
632
+ region,
633
+ host,
634
+ additionalHeaders,
791
635
  });
636
+ return result;
637
+ }
638
+ }
639
+ async _awsAuthTokenHeader({ host }) {
640
+ const session = await core_1.fetchAuthSession();
641
+ return {
642
+ Authorization: session?.tokens?.accessToken?.toString(),
643
+ host,
644
+ };
645
+ }
646
+ async _awsRealTimeApiKeyHeader({ apiKey, host, }) {
647
+ const dt = new Date();
648
+ const dtStr = dt.toISOString().replace(/[:\-]|\.\d{3}/g, '');
649
+ return {
650
+ host,
651
+ 'x-amz-date': dtStr,
652
+ 'x-api-key': apiKey,
653
+ };
654
+ }
655
+ async _awsRealTimeIAMHeader({ payload, canonicalUri, appSyncGraphqlEndpoint, region, }) {
656
+ const endpointInfo = {
657
+ region,
658
+ service: 'appsync',
659
+ };
660
+ const creds = (await core_1.fetchAuthSession()).credentials;
661
+ const request = {
662
+ url: `${appSyncGraphqlEndpoint}${canonicalUri}`,
663
+ data: payload,
664
+ method: 'POST',
665
+ headers: { ...constants_1.AWS_APPSYNC_REALTIME_HEADERS },
666
+ };
667
+ const signed_params = aws_client_utils_1.signRequest({
668
+ headers: request.headers,
669
+ method: request.method,
670
+ url: new utils_1.AmplifyUrl(request.url),
671
+ body: request.data,
672
+ }, {
673
+ // TODO: What do we need to do to remove these !'s?
674
+ credentials: creds,
675
+ signingRegion: endpointInfo.region,
676
+ signingService: endpointInfo.service,
792
677
  });
793
- };
794
- AWSAppSyncRealTimeProvider.prototype._customAuthHeader = function (_a) {
795
- var host = _a.host, additionalHeaders = _a.additionalHeaders;
796
- if (!(additionalHeaders === null || additionalHeaders === void 0 ? void 0 : additionalHeaders['Authorization'])) {
678
+ return signed_params.headers;
679
+ }
680
+ _customAuthHeader({ host, additionalHeaders, }) {
681
+ if (!additionalHeaders?.['Authorization']) {
797
682
  throw new Error('No auth token specified');
798
683
  }
799
684
  return {
800
685
  Authorization: additionalHeaders.Authorization,
801
- host: host,
686
+ host,
802
687
  };
803
- };
804
- return AWSAppSyncRealTimeProvider;
805
- }());
688
+ }
689
+ }
806
690
  exports.AWSAppSyncRealTimeProvider = AWSAppSyncRealTimeProvider;