@aws-amplify/api-graphql 4.0.1-console-preview.3d7f188.0 → 4.0.1-mjs-test.20ead30.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 (156) hide show
  1. package/dist/cjs/GraphQLAPI.js +52 -0
  2. package/dist/cjs/GraphQLAPI.js.map +1 -0
  3. package/dist/cjs/Providers/AWSAppSyncRealTimeProvider/index.js +693 -0
  4. package/dist/cjs/Providers/AWSAppSyncRealTimeProvider/index.js.map +1 -0
  5. package/{lib → dist/cjs}/Providers/constants.js +8 -8
  6. package/dist/cjs/Providers/constants.js.map +1 -0
  7. package/dist/cjs/index.js +15 -0
  8. package/dist/cjs/index.js.map +1 -0
  9. package/dist/cjs/internals/InternalGraphQLAPI.js +274 -0
  10. package/dist/cjs/internals/InternalGraphQLAPI.js.map +1 -0
  11. package/dist/cjs/internals/index.js +14 -0
  12. package/dist/cjs/internals/index.js.map +1 -0
  13. package/{lib → dist/cjs}/internals/v6.js +7 -4
  14. package/dist/cjs/internals/v6.js.map +1 -0
  15. package/{lib → dist/cjs}/types/PubSub.js +6 -6
  16. package/dist/cjs/types/PubSub.js.map +1 -0
  17. package/{lib → dist/cjs}/types/index.js +7 -5
  18. package/dist/cjs/types/index.js.map +1 -0
  19. package/dist/cjs/utils/ConnectionStateMonitor.js +134 -0
  20. package/dist/cjs/utils/ConnectionStateMonitor.js.map +1 -0
  21. package/dist/cjs/utils/ReachabilityMonitor/index.js +10 -0
  22. package/dist/cjs/utils/ReachabilityMonitor/index.js.map +1 -0
  23. package/dist/cjs/utils/ReachabilityMonitor/index.native.js +12 -0
  24. package/dist/cjs/utils/ReachabilityMonitor/index.native.js.map +1 -0
  25. package/{lib → dist/cjs}/utils/ReconnectionMonitor.js +24 -25
  26. package/dist/cjs/utils/ReconnectionMonitor.js.map +1 -0
  27. package/dist/cjs/utils/errors/APIError.js +21 -0
  28. package/dist/cjs/utils/errors/APIError.js.map +1 -0
  29. package/dist/cjs/utils/errors/assertValidationError.js +19 -0
  30. package/dist/cjs/utils/errors/assertValidationError.js.map +1 -0
  31. package/dist/cjs/utils/errors/index.js +14 -0
  32. package/dist/cjs/utils/errors/index.js.map +1 -0
  33. package/{lib → dist/cjs}/utils/errors/validation.js +9 -7
  34. package/dist/cjs/utils/errors/validation.js.map +1 -0
  35. package/dist/cjs/utils/index.js +11 -0
  36. package/dist/cjs/utils/index.js.map +1 -0
  37. package/dist/cjs/utils/resolveConfig.js +26 -0
  38. package/dist/cjs/utils/resolveConfig.js.map +1 -0
  39. package/dist/cjs/utils/resolveLibraryOptions.js +16 -0
  40. package/dist/cjs/utils/resolveLibraryOptions.js.map +1 -0
  41. package/{lib-esm → dist/esm}/GraphQLAPI.d.ts +2 -2
  42. package/dist/esm/GraphQLAPI.mjs +50 -0
  43. package/dist/esm/GraphQLAPI.mjs.map +1 -0
  44. package/{lib → dist/esm}/Providers/AWSAppSyncRealTimeProvider/index.d.ts +1 -1
  45. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.mjs +691 -0
  46. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.mjs.map +1 -0
  47. package/{lib-esm/Providers/constants.js → dist/esm/Providers/constants.mjs} +18 -14
  48. package/dist/esm/Providers/constants.mjs.map +1 -0
  49. package/dist/esm/index.mjs +5 -0
  50. package/dist/esm/index.mjs.map +1 -0
  51. package/{lib → dist/esm}/internals/InternalGraphQLAPI.d.ts +2 -2
  52. package/dist/esm/internals/InternalGraphQLAPI.mjs +272 -0
  53. package/dist/esm/internals/InternalGraphQLAPI.mjs.map +1 -0
  54. package/dist/esm/internals/index.mjs +3 -0
  55. package/dist/esm/internals/index.mjs.map +1 -0
  56. package/{lib-esm/internals/v6.js → dist/esm/internals/v6.mjs} +10 -6
  57. package/dist/esm/internals/v6.mjs.map +1 -0
  58. package/{lib → dist/esm}/types/PubSub.d.ts +2 -2
  59. package/{lib-esm/types/PubSub.js → dist/esm/types/PubSub.mjs} +5 -2
  60. package/dist/esm/types/PubSub.mjs.map +1 -0
  61. package/{lib-esm → dist/esm}/types/index.d.ts +45 -25
  62. package/{lib-esm/types/index.js → dist/esm/types/index.mjs} +7 -3
  63. package/dist/esm/types/index.mjs.map +1 -0
  64. package/{lib-esm → dist/esm}/utils/ConnectionStateMonitor.d.ts +3 -3
  65. package/{lib-esm/utils/ConnectionStateMonitor.js → dist/esm/utils/ConnectionStateMonitor.mjs} +56 -66
  66. package/dist/esm/utils/ConnectionStateMonitor.mjs.map +1 -0
  67. package/dist/esm/utils/ReachabilityMonitor/index.d.ts +1 -0
  68. package/{lib-esm/utils/ReachabilityMonitor/index.js → dist/esm/utils/ReachabilityMonitor/index.mjs} +6 -2
  69. package/dist/esm/utils/ReachabilityMonitor/index.mjs.map +1 -0
  70. package/dist/esm/utils/ReachabilityMonitor/index.native.d.ts +1 -0
  71. package/dist/esm/utils/ReachabilityMonitor/index.native.mjs +9 -0
  72. package/dist/esm/utils/ReachabilityMonitor/index.native.mjs.map +1 -0
  73. package/{lib-esm/utils/ReconnectionMonitor.js → dist/esm/utils/ReconnectionMonitor.mjs} +25 -26
  74. package/dist/esm/utils/ReconnectionMonitor.mjs.map +1 -0
  75. package/dist/esm/utils/errors/APIError.mjs +19 -0
  76. package/dist/esm/utils/errors/APIError.mjs.map +1 -0
  77. package/dist/esm/utils/errors/assertValidationError.mjs +17 -0
  78. package/dist/esm/utils/errors/assertValidationError.mjs.map +1 -0
  79. package/dist/esm/utils/errors/index.mjs +4 -0
  80. package/dist/esm/utils/errors/index.mjs.map +1 -0
  81. package/{lib-esm/utils/errors/validation.js → dist/esm/utils/errors/validation.mjs} +9 -7
  82. package/dist/esm/utils/errors/validation.mjs.map +1 -0
  83. package/dist/esm/utils/index.mjs +3 -0
  84. package/dist/esm/utils/index.mjs.map +1 -0
  85. package/{lib → dist/esm}/utils/resolveConfig.d.ts +1 -1
  86. package/dist/esm/utils/resolveConfig.mjs +26 -0
  87. package/dist/esm/utils/resolveConfig.mjs.map +1 -0
  88. package/{lib-esm → dist/esm}/utils/resolveLibraryOptions.d.ts +2 -2
  89. package/dist/esm/utils/resolveLibraryOptions.mjs +13 -0
  90. package/dist/esm/utils/resolveLibraryOptions.mjs.map +1 -0
  91. package/internals/package.json +4 -4
  92. package/package.json +48 -26
  93. package/src/GraphQLAPI.ts +2 -2
  94. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +3 -3
  95. package/src/internals/InternalGraphQLAPI.ts +35 -10
  96. package/src/types/index.ts +51 -9
  97. package/lib/GraphQLAPI.d.ts +0 -38
  98. package/lib/GraphQLAPI.js +0 -57
  99. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js +0 -806
  100. package/lib/Providers/constants.d.ts +0 -95
  101. package/lib/index.d.ts +0 -3
  102. package/lib/index.js +0 -12
  103. package/lib/internals/InternalGraphQLAPI.js +0 -316
  104. package/lib/internals/index.d.ts +0 -2
  105. package/lib/internals/index.js +0 -11
  106. package/lib/internals/v6.d.ts +0 -101
  107. package/lib/tsconfig.tsbuildinfo +0 -6619
  108. package/lib/types/index.d.ts +0 -289
  109. package/lib/utils/ConnectionStateMonitor.d.ts +0 -41
  110. package/lib/utils/ConnectionStateMonitor.js +0 -144
  111. package/lib/utils/ReachabilityMonitor/index.d.ts +0 -1
  112. package/lib/utils/ReachabilityMonitor/index.js +0 -6
  113. package/lib/utils/ReachabilityMonitor/index.native.d.ts +0 -1
  114. package/lib/utils/ReachabilityMonitor/index.native.js +0 -10
  115. package/lib/utils/ReconnectionMonitor.d.ts +0 -29
  116. package/lib/utils/errors/APIError.d.ts +0 -7
  117. package/lib/utils/errors/APIError.js +0 -22
  118. package/lib/utils/errors/assertValidationError.d.ts +0 -5
  119. package/lib/utils/errors/assertValidationError.js +0 -16
  120. package/lib/utils/errors/index.d.ts +0 -3
  121. package/lib/utils/errors/index.js +0 -11
  122. package/lib/utils/errors/validation.d.ts +0 -7
  123. package/lib/utils/index.d.ts +0 -2
  124. package/lib/utils/index.js +0 -8
  125. package/lib/utils/resolveConfig.js +0 -23
  126. package/lib/utils/resolveLibraryOptions.d.ts +0 -11
  127. package/lib/utils/resolveLibraryOptions.js +0 -13
  128. package/lib-esm/GraphQLAPI.js +0 -55
  129. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +0 -64
  130. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js +0 -804
  131. package/lib-esm/index.js +0 -5
  132. package/lib-esm/internals/InternalGraphQLAPI.d.ts +0 -58
  133. package/lib-esm/internals/InternalGraphQLAPI.js +0 -314
  134. package/lib-esm/internals/index.js +0 -4
  135. package/lib-esm/tsconfig.tsbuildinfo +0 -6619
  136. package/lib-esm/types/PubSub.d.ts +0 -27
  137. package/lib-esm/utils/ReachabilityMonitor/index.d.ts +0 -1
  138. package/lib-esm/utils/ReachabilityMonitor/index.native.d.ts +0 -1
  139. package/lib-esm/utils/ReachabilityMonitor/index.native.js +0 -7
  140. package/lib-esm/utils/errors/APIError.js +0 -20
  141. package/lib-esm/utils/errors/assertValidationError.js +0 -13
  142. package/lib-esm/utils/errors/index.js +0 -5
  143. package/lib-esm/utils/index.js +0 -4
  144. package/lib-esm/utils/resolveConfig.d.ts +0 -12
  145. package/lib-esm/utils/resolveConfig.js +0 -21
  146. package/lib-esm/utils/resolveLibraryOptions.js +0 -11
  147. /package/{lib-esm → dist/esm}/Providers/constants.d.ts +0 -0
  148. /package/{lib-esm → dist/esm}/index.d.ts +0 -0
  149. /package/{lib-esm → dist/esm}/internals/index.d.ts +0 -0
  150. /package/{lib-esm → dist/esm}/internals/v6.d.ts +0 -0
  151. /package/{lib-esm → dist/esm}/utils/ReconnectionMonitor.d.ts +0 -0
  152. /package/{lib-esm → dist/esm}/utils/errors/APIError.d.ts +0 -0
  153. /package/{lib-esm → dist/esm}/utils/errors/assertValidationError.d.ts +0 -0
  154. /package/{lib-esm → dist/esm}/utils/errors/index.d.ts +0 -0
  155. /package/{lib-esm → dist/esm}/utils/errors/validation.d.ts +0 -0
  156. /package/{lib-esm → dist/esm}/utils/index.d.ts +0 -0
@@ -1,806 +0,0 @@
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 rxjs_1 = require("rxjs");
7
- var graphql_1 = require("graphql");
8
- var buffer_1 = require("buffer");
9
- var core_1 = require("@aws-amplify/core");
10
- var aws_client_utils_1 = require("@aws-amplify/core/internals/aws-client-utils");
11
- var utils_1 = require("@aws-amplify/core/internals/utils");
12
- var PubSub_1 = require("../../types/PubSub");
13
- var constants_1 = require("../constants");
14
- var ConnectionStateMonitor_1 = require("../../utils/ConnectionStateMonitor");
15
- var ReconnectionMonitor_1 = require("../../utils/ReconnectionMonitor");
16
- var logger = new core_1.ConsoleLogger('AWSAppSyncRealTimeProvider');
17
- var dispatchApiEvent = function (payload) {
18
- core_1.Hub.dispatch('api', payload, 'PubSub', constants_1.AMPLIFY_SYMBOL);
19
- };
20
- var standardDomainPattern = /^https:\/\/\w{26}\.appsync\-api\.\w{2}(?:(?:\-\w{2,})+)\-\d\.amazonaws.com(?:\.cn)?\/graphql$/i;
21
- var customDomainPath = '/realtime';
22
- var AWSAppSyncRealTimeProvider = /** @class */ (function () {
23
- function AWSAppSyncRealTimeProvider(options) {
24
- var _this = this;
25
- if (options === void 0) { options = {}; }
26
- this.socketStatus = constants_1.SOCKET_STATUS.CLOSED;
27
- this.keepAliveTimeout = constants_1.DEFAULT_KEEP_ALIVE_TIMEOUT;
28
- this.subscriptionObserverMap = new Map();
29
- this.promiseArray = [];
30
- this.connectionStateMonitor = new ConnectionStateMonitor_1.ConnectionStateMonitor();
31
- this.reconnectionMonitor = new ReconnectionMonitor_1.ReconnectionMonitor();
32
- // Monitor the connection state and pass changes along to Hub
33
- this.connectionStateMonitorSubscription =
34
- this.connectionStateMonitor.connectionStateObservable.subscribe(function (connectionState) {
35
- dispatchApiEvent({
36
- event: constants_1.CONNECTION_STATE_CHANGE,
37
- data: {
38
- provider: _this,
39
- connectionState: connectionState,
40
- },
41
- message: "Connection state is " + connectionState,
42
- });
43
- _this.connectionState = connectionState;
44
- // Trigger START_RECONNECT when the connection is disrupted
45
- if (connectionState === PubSub_1.ConnectionState.ConnectionDisrupted) {
46
- _this.reconnectionMonitor.record(ReconnectionMonitor_1.ReconnectEvent.START_RECONNECT);
47
- }
48
- // Trigger HALT_RECONNECT to halt reconnection attempts when the state is anything other than
49
- // ConnectionDisrupted or Connecting
50
- if ([
51
- PubSub_1.ConnectionState.Connected,
52
- PubSub_1.ConnectionState.ConnectedPendingDisconnect,
53
- PubSub_1.ConnectionState.ConnectedPendingKeepAlive,
54
- PubSub_1.ConnectionState.ConnectedPendingNetwork,
55
- PubSub_1.ConnectionState.ConnectionDisruptedPendingNetwork,
56
- PubSub_1.ConnectionState.Disconnected,
57
- ].includes(connectionState)) {
58
- _this.reconnectionMonitor.record(ReconnectionMonitor_1.ReconnectEvent.HALT_RECONNECT);
59
- }
60
- });
61
- }
62
- /**
63
- * Mark the socket closed and release all active listeners
64
- */
65
- AWSAppSyncRealTimeProvider.prototype.close = function () {
66
- // Mark the socket closed both in status and the connection monitor
67
- this.socketStatus = constants_1.SOCKET_STATUS.CLOSED;
68
- this.connectionStateMonitor.record(ConnectionStateMonitor_1.CONNECTION_CHANGE.CONNECTION_FAILED);
69
- // Turn off the subscription monitor Hub publishing
70
- this.connectionStateMonitorSubscription.unsubscribe();
71
- // Complete all reconnect observers
72
- this.reconnectionMonitor.close();
73
- };
74
- AWSAppSyncRealTimeProvider.prototype.getNewWebSocket = function (url, protocol) {
75
- return new WebSocket(url, protocol);
76
- };
77
- AWSAppSyncRealTimeProvider.prototype.getProviderName = function () {
78
- return 'AWSAppSyncRealTimeProvider';
79
- };
80
- // Check if url matches standard domain pattern
81
- AWSAppSyncRealTimeProvider.prototype.isCustomDomain = function (url) {
82
- return url.match(standardDomainPattern) === null;
83
- };
84
- AWSAppSyncRealTimeProvider.prototype.subscribe = function (options, customUserAgentDetails) {
85
- var _this = this;
86
- var _a = options || {}, appSyncGraphqlEndpoint = _a.appSyncGraphqlEndpoint, region = _a.region, query = _a.query, variables = _a.variables, authenticationType = _a.authenticationType, additionalHeaders = _a.additionalHeaders, apiKey = _a.apiKey;
87
- return new rxjs_1.Observable(function (observer) {
88
- if (!options || !appSyncGraphqlEndpoint) {
89
- observer.error({
90
- errors: [
91
- tslib_1.__assign({}, new graphql_1.GraphQLError("Subscribe only available for AWS AppSync endpoint")),
92
- ],
93
- });
94
- observer.complete();
95
- }
96
- else {
97
- var subscriptionStartActive_1 = false;
98
- var subscriptionId_1 = utils_1.amplifyUuid();
99
- var startSubscription_1 = function () {
100
- if (!subscriptionStartActive_1) {
101
- subscriptionStartActive_1 = true;
102
- var startSubscriptionPromise = _this._startSubscriptionWithAWSAppSyncRealTime({
103
- options: {
104
- query: query,
105
- variables: variables,
106
- region: region,
107
- authenticationType: authenticationType,
108
- appSyncGraphqlEndpoint: appSyncGraphqlEndpoint,
109
- additionalHeaders: additionalHeaders,
110
- apiKey: apiKey,
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 rxjs_1.Observable(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
- event: PubSub_1.CONTROL_MSG.SUBSCRIPTION_ACK,
402
- data: { query: query, variables: variables },
403
- message: '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 apiKey = _a.apiKey, 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, resolvedApiKey, 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
- oidc: this._awsAuthTokenHeader.bind(this),
692
- userPool: this._awsAuthTokenHeader.bind(this),
693
- lambda: this._customAuthHeader,
694
- none: this._customAuthHeader,
695
- };
696
- if (!(!authenticationType || !headerHandler[authenticationType])) return [3 /*break*/, 1];
697
- logger.debug("Authentication type " + authenticationType + " not supported");
698
- return [2 /*return*/, undefined];
699
- case 1:
700
- handler = headerHandler[authenticationType];
701
- host = appSyncGraphqlEndpoint
702
- ? new utils_1.AmplifyUrl(appSyncGraphqlEndpoint).host
703
- : undefined;
704
- logger.debug("Authenticating with " + 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 host = _a.host;
727
- var _b, _c;
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*/, 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',
768
- };
769
- return [4 /*yield*/, core_1.fetchAuthSession()];
770
- case 1:
771
- creds = (_b.sent()).credentials;
772
- request = {
773
- url: "" + appSyncGraphqlEndpoint + canonicalUri,
774
- data: payload,
775
- method: 'POST',
776
- headers: tslib_1.__assign({}, constants_1.AWS_APPSYNC_REALTIME_HEADERS),
777
- };
778
- signed_params = 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
- }
791
- });
792
- });
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'])) {
797
- throw new Error('No auth token specified');
798
- }
799
- return {
800
- Authorization: additionalHeaders.Authorization,
801
- host: host,
802
- };
803
- };
804
- return AWSAppSyncRealTimeProvider;
805
- }());
806
- exports.AWSAppSyncRealTimeProvider = AWSAppSyncRealTimeProvider;