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