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