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