@aws-amplify/api-graphql 0.0.0-unstable-1ca644b-20260128091132

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 (257) hide show
  1. package/README.md +3 -0
  2. package/dist/cjs/GraphQLAPI.js +66 -0
  3. package/dist/cjs/GraphQLAPI.js.map +1 -0
  4. package/dist/cjs/Providers/AWSAppSyncEventsProvider/index.js +117 -0
  5. package/dist/cjs/Providers/AWSAppSyncEventsProvider/index.js.map +1 -0
  6. package/dist/cjs/Providers/AWSAppSyncRealTimeProvider/index.js +96 -0
  7. package/dist/cjs/Providers/AWSAppSyncRealTimeProvider/index.js.map +1 -0
  8. package/dist/cjs/Providers/AWSWebSocketProvider/appsyncUrl.js +113 -0
  9. package/dist/cjs/Providers/AWSWebSocketProvider/appsyncUrl.js.map +1 -0
  10. package/dist/cjs/Providers/AWSWebSocketProvider/authHeaders.js +99 -0
  11. package/dist/cjs/Providers/AWSWebSocketProvider/authHeaders.js.map +1 -0
  12. package/dist/cjs/Providers/AWSWebSocketProvider/index.js +693 -0
  13. package/dist/cjs/Providers/AWSWebSocketProvider/index.js.map +1 -0
  14. package/dist/cjs/Providers/constants.js +149 -0
  15. package/dist/cjs/Providers/constants.js.map +1 -0
  16. package/dist/cjs/index.js +18 -0
  17. package/dist/cjs/index.js.map +1 -0
  18. package/dist/cjs/internals/InternalGraphQLAPI.js +269 -0
  19. package/dist/cjs/internals/InternalGraphQLAPI.js.map +1 -0
  20. package/dist/cjs/internals/events/appsyncRequest.js +96 -0
  21. package/dist/cjs/internals/events/appsyncRequest.js.map +1 -0
  22. package/dist/cjs/internals/events/index.js +142 -0
  23. package/dist/cjs/internals/events/index.js.map +1 -0
  24. package/dist/cjs/internals/events/types.js +6 -0
  25. package/dist/cjs/internals/events/types.js.map +1 -0
  26. package/dist/cjs/internals/events/utils.js +57 -0
  27. package/dist/cjs/internals/events/utils.js.map +1 -0
  28. package/dist/cjs/internals/generateClient.js +86 -0
  29. package/dist/cjs/internals/generateClient.js.map +1 -0
  30. package/dist/cjs/internals/graphqlAuth.js +63 -0
  31. package/dist/cjs/internals/graphqlAuth.js.map +1 -0
  32. package/dist/cjs/internals/graphqlRequest.js +19 -0
  33. package/dist/cjs/internals/graphqlRequest.js.map +1 -0
  34. package/dist/cjs/internals/index.js +16 -0
  35. package/dist/cjs/internals/index.js.map +1 -0
  36. package/dist/cjs/internals/server/generateClientWithAmplifyInstance.js +48 -0
  37. package/dist/cjs/internals/server/generateClientWithAmplifyInstance.js.map +1 -0
  38. package/dist/cjs/internals/server/index.js +9 -0
  39. package/dist/cjs/internals/server/index.js.map +1 -0
  40. package/dist/cjs/internals/types.js +4 -0
  41. package/dist/cjs/internals/types.js.map +1 -0
  42. package/dist/cjs/internals/utils/runtimeTypeGuards/isApiGraphQLProviderConfig.js +10 -0
  43. package/dist/cjs/internals/utils/runtimeTypeGuards/isApiGraphQLProviderConfig.js.map +1 -0
  44. package/dist/cjs/internals/utils/runtimeTypeGuards/isConfigureEventWithResourceConfig.js +10 -0
  45. package/dist/cjs/internals/utils/runtimeTypeGuards/isConfigureEventWithResourceConfig.js.map +1 -0
  46. package/dist/cjs/internals/utils/runtimeTypeGuards/isGraphQLResponseWithErrors.js +14 -0
  47. package/dist/cjs/internals/utils/runtimeTypeGuards/isGraphQLResponseWithErrors.js.map +1 -0
  48. package/dist/cjs/internals/v6.js +155 -0
  49. package/dist/cjs/internals/v6.js.map +1 -0
  50. package/dist/cjs/server/generateClient.js +42 -0
  51. package/dist/cjs/server/generateClient.js.map +1 -0
  52. package/dist/cjs/server/index.js +9 -0
  53. package/dist/cjs/server/index.js.map +1 -0
  54. package/dist/cjs/types/PubSub.js +49 -0
  55. package/dist/cjs/types/PubSub.js.map +1 -0
  56. package/dist/cjs/types/index.js +34 -0
  57. package/dist/cjs/types/index.js.map +1 -0
  58. package/dist/cjs/utils/ConnectionStateMonitor.js +134 -0
  59. package/dist/cjs/utils/ConnectionStateMonitor.js.map +1 -0
  60. package/dist/cjs/utils/ReachabilityMonitor/index.js +10 -0
  61. package/dist/cjs/utils/ReachabilityMonitor/index.js.map +1 -0
  62. package/dist/cjs/utils/ReachabilityMonitor/index.native.js +12 -0
  63. package/dist/cjs/utils/ReachabilityMonitor/index.native.js.map +1 -0
  64. package/dist/cjs/utils/ReconnectionMonitor.js +71 -0
  65. package/dist/cjs/utils/ReconnectionMonitor.js.map +1 -0
  66. package/dist/cjs/utils/errors/GraphQLApiError.js +21 -0
  67. package/dist/cjs/utils/errors/GraphQLApiError.js.map +1 -0
  68. package/dist/cjs/utils/errors/assertValidationError.js +18 -0
  69. package/dist/cjs/utils/errors/assertValidationError.js.map +1 -0
  70. package/dist/cjs/utils/errors/constants.js +47 -0
  71. package/dist/cjs/utils/errors/constants.js.map +1 -0
  72. package/dist/cjs/utils/errors/createGraphQLResultWithError.js +15 -0
  73. package/dist/cjs/utils/errors/createGraphQLResultWithError.js.map +1 -0
  74. package/dist/cjs/utils/errors/index.js +16 -0
  75. package/dist/cjs/utils/errors/index.js.map +1 -0
  76. package/dist/cjs/utils/errors/repackageAuthError.js +38 -0
  77. package/dist/cjs/utils/errors/repackageAuthError.js.map +1 -0
  78. package/dist/cjs/utils/errors/validation.js +28 -0
  79. package/dist/cjs/utils/errors/validation.js.map +1 -0
  80. package/dist/cjs/utils/index.js +11 -0
  81. package/dist/cjs/utils/index.js.map +1 -0
  82. package/dist/cjs/utils/resolveConfig.js +32 -0
  83. package/dist/cjs/utils/resolveConfig.js.map +1 -0
  84. package/dist/cjs/utils/resolveLibraryOptions.js +16 -0
  85. package/dist/cjs/utils/resolveLibraryOptions.js.map +1 -0
  86. package/dist/esm/GraphQLAPI.d.ts +37 -0
  87. package/dist/esm/GraphQLAPI.mjs +63 -0
  88. package/dist/esm/GraphQLAPI.mjs.map +1 -0
  89. package/dist/esm/Providers/AWSAppSyncEventsProvider/index.d.ts +49 -0
  90. package/dist/esm/Providers/AWSAppSyncEventsProvider/index.mjs +115 -0
  91. package/dist/esm/Providers/AWSAppSyncEventsProvider/index.mjs.map +1 -0
  92. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +47 -0
  93. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.mjs +94 -0
  94. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.mjs.map +1 -0
  95. package/dist/esm/Providers/AWSWebSocketProvider/appsyncUrl.d.ts +21 -0
  96. package/dist/esm/Providers/AWSWebSocketProvider/appsyncUrl.mjs +107 -0
  97. package/dist/esm/Providers/AWSWebSocketProvider/appsyncUrl.mjs.map +1 -0
  98. package/dist/esm/Providers/AWSWebSocketProvider/authHeaders.d.ts +8 -0
  99. package/dist/esm/Providers/AWSWebSocketProvider/authHeaders.mjs +97 -0
  100. package/dist/esm/Providers/AWSWebSocketProvider/authHeaders.mjs.map +1 -0
  101. package/dist/esm/Providers/AWSWebSocketProvider/index.d.ts +99 -0
  102. package/dist/esm/Providers/AWSWebSocketProvider/index.mjs +691 -0
  103. package/dist/esm/Providers/AWSWebSocketProvider/index.mjs.map +1 -0
  104. package/dist/esm/Providers/constants.d.ts +135 -0
  105. package/dist/esm/Providers/constants.mjs +147 -0
  106. package/dist/esm/Providers/constants.mjs.map +1 -0
  107. package/dist/esm/index.d.ts +6 -0
  108. package/dist/esm/index.mjs +7 -0
  109. package/dist/esm/index.mjs.map +1 -0
  110. package/dist/esm/internals/InternalGraphQLAPI.d.ts +45 -0
  111. package/dist/esm/internals/InternalGraphQLAPI.mjs +270 -0
  112. package/dist/esm/internals/InternalGraphQLAPI.mjs.map +1 -0
  113. package/dist/esm/internals/events/appsyncRequest.d.ts +14 -0
  114. package/dist/esm/internals/events/appsyncRequest.mjs +96 -0
  115. package/dist/esm/internals/events/appsyncRequest.mjs.map +1 -0
  116. package/dist/esm/internals/events/index.d.ts +58 -0
  117. package/dist/esm/internals/events/index.mjs +139 -0
  118. package/dist/esm/internals/events/index.mjs.map +1 -0
  119. package/dist/esm/internals/events/types.d.ts +93 -0
  120. package/dist/esm/internals/events/types.mjs +2 -0
  121. package/dist/esm/internals/events/types.mjs.map +1 -0
  122. package/dist/esm/internals/events/utils.d.ts +16 -0
  123. package/dist/esm/internals/events/utils.mjs +53 -0
  124. package/dist/esm/internals/events/utils.mjs.map +1 -0
  125. package/dist/esm/internals/generateClient.d.ts +12 -0
  126. package/dist/esm/internals/generateClient.mjs +85 -0
  127. package/dist/esm/internals/generateClient.mjs.map +1 -0
  128. package/dist/esm/internals/graphqlAuth.d.ts +3 -0
  129. package/dist/esm/internals/graphqlAuth.mjs +64 -0
  130. package/dist/esm/internals/graphqlAuth.mjs.map +1 -0
  131. package/dist/esm/internals/graphqlRequest.d.ts +3 -0
  132. package/dist/esm/internals/graphqlRequest.mjs +18 -0
  133. package/dist/esm/internals/graphqlRequest.mjs.map +1 -0
  134. package/dist/esm/internals/index.d.ts +4 -0
  135. package/dist/esm/internals/index.mjs +4 -0
  136. package/dist/esm/internals/index.mjs.map +1 -0
  137. package/dist/esm/internals/server/generateClientWithAmplifyInstance.d.ts +13 -0
  138. package/dist/esm/internals/server/generateClientWithAmplifyInstance.mjs +61 -0
  139. package/dist/esm/internals/server/generateClientWithAmplifyInstance.mjs.map +1 -0
  140. package/dist/esm/internals/server/index.d.ts +1 -0
  141. package/dist/esm/internals/server/index.mjs +2 -0
  142. package/dist/esm/internals/server/index.mjs.map +1 -0
  143. package/dist/esm/internals/types.d.ts +34 -0
  144. package/dist/esm/internals/types.mjs +2 -0
  145. package/dist/esm/internals/types.mjs.map +1 -0
  146. package/dist/esm/internals/utils/runtimeTypeGuards/isApiGraphQLProviderConfig.d.ts +2 -0
  147. package/dist/esm/internals/utils/runtimeTypeGuards/isApiGraphQLProviderConfig.mjs +8 -0
  148. package/dist/esm/internals/utils/runtimeTypeGuards/isApiGraphQLProviderConfig.mjs.map +1 -0
  149. package/dist/esm/internals/utils/runtimeTypeGuards/isConfigureEventWithResourceConfig.d.ts +8 -0
  150. package/dist/esm/internals/utils/runtimeTypeGuards/isConfigureEventWithResourceConfig.mjs +8 -0
  151. package/dist/esm/internals/utils/runtimeTypeGuards/isConfigureEventWithResourceConfig.mjs.map +1 -0
  152. package/dist/esm/internals/utils/runtimeTypeGuards/isGraphQLResponseWithErrors.d.ts +2 -0
  153. package/dist/esm/internals/utils/runtimeTypeGuards/isGraphQLResponseWithErrors.mjs +12 -0
  154. package/dist/esm/internals/utils/runtimeTypeGuards/isGraphQLResponseWithErrors.mjs.map +1 -0
  155. package/dist/esm/internals/v6.d.ts +100 -0
  156. package/dist/esm/internals/v6.mjs +152 -0
  157. package/dist/esm/internals/v6.mjs.map +1 -0
  158. package/dist/esm/server/generateClient.d.ts +21 -0
  159. package/dist/esm/server/generateClient.mjs +41 -0
  160. package/dist/esm/server/generateClient.mjs.map +1 -0
  161. package/dist/esm/server/index.d.ts +1 -0
  162. package/dist/esm/server/index.mjs +2 -0
  163. package/dist/esm/server/index.mjs.map +1 -0
  164. package/dist/esm/types/PubSub.d.ts +27 -0
  165. package/dist/esm/types/PubSub.mjs +47 -0
  166. package/dist/esm/types/PubSub.mjs.map +1 -0
  167. package/dist/esm/types/index.d.ts +369 -0
  168. package/dist/esm/types/index.mjs +30 -0
  169. package/dist/esm/types/index.mjs.map +1 -0
  170. package/dist/esm/utils/ConnectionStateMonitor.d.ts +69 -0
  171. package/dist/esm/utils/ConnectionStateMonitor.mjs +132 -0
  172. package/dist/esm/utils/ConnectionStateMonitor.mjs.map +1 -0
  173. package/dist/esm/utils/ReachabilityMonitor/index.d.ts +1 -0
  174. package/dist/esm/utils/ReachabilityMonitor/index.mjs +8 -0
  175. package/dist/esm/utils/ReachabilityMonitor/index.mjs.map +1 -0
  176. package/dist/esm/utils/ReachabilityMonitor/index.native.d.ts +1 -0
  177. package/dist/esm/utils/ReachabilityMonitor/index.native.mjs +9 -0
  178. package/dist/esm/utils/ReachabilityMonitor/index.native.mjs.map +1 -0
  179. package/dist/esm/utils/ReconnectionMonitor.d.ts +29 -0
  180. package/dist/esm/utils/ReconnectionMonitor.mjs +69 -0
  181. package/dist/esm/utils/ReconnectionMonitor.mjs.map +1 -0
  182. package/dist/esm/utils/errors/GraphQLApiError.d.ts +7 -0
  183. package/dist/esm/utils/errors/GraphQLApiError.mjs +19 -0
  184. package/dist/esm/utils/errors/GraphQLApiError.mjs.map +1 -0
  185. package/dist/esm/utils/errors/assertValidationError.d.ts +5 -0
  186. package/dist/esm/utils/errors/assertValidationError.mjs +17 -0
  187. package/dist/esm/utils/errors/assertValidationError.mjs.map +1 -0
  188. package/dist/esm/utils/errors/constants.d.ts +7 -0
  189. package/dist/esm/utils/errors/constants.mjs +46 -0
  190. package/dist/esm/utils/errors/constants.mjs.map +1 -0
  191. package/dist/esm/utils/errors/createGraphQLResultWithError.d.ts +2 -0
  192. package/dist/esm/utils/errors/createGraphQLResultWithError.mjs +13 -0
  193. package/dist/esm/utils/errors/createGraphQLResultWithError.mjs.map +1 -0
  194. package/dist/esm/utils/errors/index.d.ts +4 -0
  195. package/dist/esm/utils/errors/index.mjs +5 -0
  196. package/dist/esm/utils/errors/index.mjs.map +1 -0
  197. package/dist/esm/utils/errors/repackageAuthError.d.ts +7 -0
  198. package/dist/esm/utils/errors/repackageAuthError.mjs +36 -0
  199. package/dist/esm/utils/errors/repackageAuthError.mjs.map +1 -0
  200. package/dist/esm/utils/errors/validation.d.ts +7 -0
  201. package/dist/esm/utils/errors/validation.mjs +26 -0
  202. package/dist/esm/utils/errors/validation.mjs.map +1 -0
  203. package/dist/esm/utils/index.d.ts +2 -0
  204. package/dist/esm/utils/index.mjs +3 -0
  205. package/dist/esm/utils/index.mjs.map +1 -0
  206. package/dist/esm/utils/resolveConfig.d.ts +12 -0
  207. package/dist/esm/utils/resolveConfig.mjs +33 -0
  208. package/dist/esm/utils/resolveConfig.mjs.map +1 -0
  209. package/dist/esm/utils/resolveLibraryOptions.d.ts +11 -0
  210. package/dist/esm/utils/resolveLibraryOptions.mjs +13 -0
  211. package/dist/esm/utils/resolveLibraryOptions.mjs.map +1 -0
  212. package/internals/package.json +8 -0
  213. package/internals/server/package.json +8 -0
  214. package/package.json +99 -0
  215. package/server/package.json +7 -0
  216. package/src/GraphQLAPI.ts +97 -0
  217. package/src/Providers/AWSAppSyncEventsProvider/index.ts +218 -0
  218. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +185 -0
  219. package/src/Providers/AWSWebSocketProvider/appsyncUrl.ts +152 -0
  220. package/src/Providers/AWSWebSocketProvider/authHeaders.ts +146 -0
  221. package/src/Providers/AWSWebSocketProvider/index.ts +1028 -0
  222. package/src/Providers/constants.ts +154 -0
  223. package/src/index.ts +12 -0
  224. package/src/internals/InternalGraphQLAPI.ts +424 -0
  225. package/src/internals/events/appsyncRequest.ts +169 -0
  226. package/src/internals/events/index.ts +199 -0
  227. package/src/internals/events/types.ts +109 -0
  228. package/src/internals/events/utils.ts +77 -0
  229. package/src/internals/generateClient.ts +120 -0
  230. package/src/internals/graphqlAuth.ts +87 -0
  231. package/src/internals/graphqlRequest.ts +30 -0
  232. package/src/internals/index.ts +10 -0
  233. package/src/internals/server/generateClientWithAmplifyInstance.ts +73 -0
  234. package/src/internals/server/index.ts +4 -0
  235. package/src/internals/types.ts +42 -0
  236. package/src/internals/utils/runtimeTypeGuards/isApiGraphQLProviderConfig.ts +10 -0
  237. package/src/internals/utils/runtimeTypeGuards/isConfigureEventWithResourceConfig.ts +13 -0
  238. package/src/internals/utils/runtimeTypeGuards/isGraphQLResponseWithErrors.ts +15 -0
  239. package/src/internals/v6.ts +189 -0
  240. package/src/server/generateClient.ts +68 -0
  241. package/src/server/index.ts +4 -0
  242. package/src/types/PubSub.ts +57 -0
  243. package/src/types/index.ts +524 -0
  244. package/src/utils/ConnectionStateMonitor.ts +195 -0
  245. package/src/utils/ReachabilityMonitor/index.native.ts +7 -0
  246. package/src/utils/ReachabilityMonitor/index.ts +5 -0
  247. package/src/utils/ReconnectionMonitor.ts +77 -0
  248. package/src/utils/errors/GraphQLApiError.ts +21 -0
  249. package/src/utils/errors/assertValidationError.ts +19 -0
  250. package/src/utils/errors/constants.ts +56 -0
  251. package/src/utils/errors/createGraphQLResultWithError.ts +15 -0
  252. package/src/utils/errors/index.ts +7 -0
  253. package/src/utils/errors/repackageAuthError.ts +43 -0
  254. package/src/utils/errors/validation.ts +26 -0
  255. package/src/utils/index.ts +5 -0
  256. package/src/utils/resolveConfig.ts +46 -0
  257. package/src/utils/resolveLibraryOptions.ts +14 -0
@@ -0,0 +1,691 @@
1
+ import { Observable } from 'rxjs';
2
+ import { GraphQLError } from 'graphql';
3
+ import { ConsoleLogger, Hub } from '@aws-amplify/core';
4
+ import { NonRetryableError, amplifyUuid, isNonRetryableError, base64Encoder, jitteredExponentialRetry, AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';
5
+ import { ConnectionState, CONTROL_MSG } from '../../types/PubSub.mjs';
6
+ import { SOCKET_STATUS, NON_RETRYABLE_CODES, NON_RETRYABLE_ERROR_TYPES, SUBSCRIPTION_STATUS, START_ACK_TIMEOUT, DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT, MESSAGE_TYPES, MAX_DELAY_MS, CONNECTION_INIT_TIMEOUT, DEFAULT_KEEP_ALIVE_HEARTBEAT_TIMEOUT, CONNECTION_STATE_CHANGE } from '../constants.mjs';
7
+ import { ConnectionStateMonitor, CONNECTION_CHANGE } from '../../utils/ConnectionStateMonitor.mjs';
8
+ import { ReconnectionMonitor, ReconnectEvent } from '../../utils/ReconnectionMonitor.mjs';
9
+ import { additionalHeadersFromOptions, queryParamsFromCustomHeaders, realtimeUrlWithQueryString } from './appsyncUrl.mjs';
10
+ import { awsRealTimeHeaderBasedAuth } from './authHeaders.mjs';
11
+
12
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
13
+ // SPDX-License-Identifier: Apache-2.0
14
+ const dispatchApiEvent = (payload) => {
15
+ Hub.dispatch('api', payload, 'PubSub', AMPLIFY_SYMBOL);
16
+ };
17
+ class AWSWebSocketProvider {
18
+ constructor(args) {
19
+ this.subscriptionObserverMap = new Map();
20
+ this.allowNoSubscriptions = false;
21
+ this.socketStatus = SOCKET_STATUS.CLOSED;
22
+ this.keepAliveTimestamp = Date.now();
23
+ this.promiseArray = [];
24
+ this.connectionStateMonitor = new ConnectionStateMonitor();
25
+ this.reconnectionMonitor = new ReconnectionMonitor();
26
+ /**
27
+ * Open WebSocket connection & perform handshake
28
+ * Ref: https://docs.aws.amazon.com/appsync/latest/devguide/real-time-websocket-client.html#appsynclong-real-time-websocket-client-implementation-guide-for-graphql-subscriptions
29
+ *
30
+ * @param subprotocol -
31
+ */
32
+ this._establishConnection = async (awsRealTimeUrl, subprotocol) => {
33
+ this.logger.debug(`Establishing WebSocket connection to ${awsRealTimeUrl}`);
34
+ try {
35
+ await this._openConnection(awsRealTimeUrl, subprotocol);
36
+ await this._initiateHandshake();
37
+ }
38
+ catch (err) {
39
+ const { errorType, errorCode } = err;
40
+ if (NON_RETRYABLE_CODES.includes(errorCode) ||
41
+ // Event API does not currently return `errorCode`. This may change in the future.
42
+ // For now fall back to also checking known non-retryable error types
43
+ NON_RETRYABLE_ERROR_TYPES.includes(errorType)) {
44
+ throw new NonRetryableError(errorType);
45
+ }
46
+ else if (errorType) {
47
+ throw new Error(errorType);
48
+ }
49
+ else {
50
+ throw err;
51
+ }
52
+ }
53
+ };
54
+ this.logger = new ConsoleLogger(args.providerName);
55
+ this.wsProtocolName = args.wsProtocolName;
56
+ this.wsConnectUri = args.connectUri;
57
+ this.connectionStateMonitorSubscription =
58
+ this._startConnectionStateMonitoring();
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 = SOCKET_STATUS.CLOSED;
66
+ this.connectionStateMonitor.record(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
+ return new Promise((resolve, reject) => {
72
+ if (this.awsRealTimeSocket) {
73
+ this.awsRealTimeSocket.onclose = (_) => {
74
+ this._closeSocket();
75
+ this.subscriptionObserverMap = new Map();
76
+ this.awsRealTimeSocket = undefined;
77
+ resolve();
78
+ };
79
+ this.awsRealTimeSocket.onerror = (err) => {
80
+ reject(err);
81
+ };
82
+ this.awsRealTimeSocket.close();
83
+ }
84
+ else {
85
+ resolve();
86
+ }
87
+ });
88
+ }
89
+ subscribe(options, customUserAgentDetails) {
90
+ return new Observable(observer => {
91
+ if (!options?.appSyncGraphqlEndpoint) {
92
+ observer.error({
93
+ errors: [
94
+ {
95
+ ...new GraphQLError(`Subscribe only available for AWS AppSync endpoint`),
96
+ },
97
+ ],
98
+ });
99
+ observer.complete();
100
+ return;
101
+ }
102
+ let subscriptionStartInProgress = false;
103
+ const subscriptionId = amplifyUuid();
104
+ const startSubscription = () => {
105
+ if (!subscriptionStartInProgress) {
106
+ subscriptionStartInProgress = true;
107
+ this._startSubscriptionWithAWSAppSyncRealTime({
108
+ options,
109
+ observer,
110
+ subscriptionId,
111
+ customUserAgentDetails,
112
+ })
113
+ .catch(err => {
114
+ this.logger.debug(`${CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR}: ${err}`);
115
+ this._closeSocket();
116
+ })
117
+ .finally(() => {
118
+ subscriptionStartInProgress = false;
119
+ });
120
+ }
121
+ };
122
+ // Add an observable to the reconnection list to manage reconnection for this subscription
123
+ const reconnectSubscription = new Observable(reconnectSubscriptionObserver => {
124
+ this.reconnectionMonitor.addObserver(reconnectSubscriptionObserver);
125
+ }).subscribe(() => {
126
+ startSubscription();
127
+ });
128
+ startSubscription();
129
+ return async () => {
130
+ await this._cleanupSubscription(subscriptionId, reconnectSubscription);
131
+ };
132
+ });
133
+ }
134
+ async connect(options) {
135
+ if (this.socketStatus === SOCKET_STATUS.READY) {
136
+ return;
137
+ }
138
+ await this._connectWebSocket(options);
139
+ }
140
+ async publish(options, customUserAgentDetails) {
141
+ if (this.socketStatus !== SOCKET_STATUS.READY) {
142
+ throw new Error('Subscription has not been initialized');
143
+ }
144
+ return this._publishMessage(options, customUserAgentDetails);
145
+ }
146
+ async _connectWebSocket(options) {
147
+ const { apiKey, appSyncGraphqlEndpoint, authenticationType, region } = options;
148
+ const { additionalCustomHeaders } = await additionalHeadersFromOptions(options);
149
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.OPENING_CONNECTION);
150
+ await this._initializeWebSocketConnection({
151
+ apiKey,
152
+ appSyncGraphqlEndpoint,
153
+ authenticationType,
154
+ region,
155
+ additionalCustomHeaders,
156
+ });
157
+ }
158
+ async _publishMessage(options, customUserAgentDetails) {
159
+ const subscriptionId = amplifyUuid();
160
+ const { additionalCustomHeaders, libraryConfigHeaders } = await additionalHeadersFromOptions(options);
161
+ const serializedSubscriptionMessage = await this._prepareSubscriptionPayload({
162
+ options,
163
+ subscriptionId,
164
+ customUserAgentDetails,
165
+ additionalCustomHeaders,
166
+ libraryConfigHeaders,
167
+ publish: true,
168
+ });
169
+ return new Promise((resolve, reject) => {
170
+ if (this.awsRealTimeSocket) {
171
+ const publishListener = (event) => {
172
+ const data = JSON.parse(event.data);
173
+ if (data.id === subscriptionId && data.type === 'publish_success') {
174
+ this.awsRealTimeSocket &&
175
+ this.awsRealTimeSocket.removeEventListener('message', publishListener);
176
+ cleanup();
177
+ resolve();
178
+ }
179
+ if (data.errors && data.errors.length > 0) {
180
+ const errorTypes = data.errors.map((error) => error.errorType);
181
+ cleanup();
182
+ reject(new Error(`Publish errors: ${errorTypes.join(', ')}`));
183
+ }
184
+ };
185
+ const errorListener = (error) => {
186
+ cleanup();
187
+ reject(new Error(`WebSocket error: ${error}`));
188
+ };
189
+ const closeListener = () => {
190
+ cleanup();
191
+ reject(new Error('WebSocket is closed'));
192
+ };
193
+ const cleanup = () => {
194
+ this.awsRealTimeSocket?.removeEventListener('message', publishListener);
195
+ this.awsRealTimeSocket?.removeEventListener('error', errorListener);
196
+ this.awsRealTimeSocket?.removeEventListener('close', closeListener);
197
+ };
198
+ this.awsRealTimeSocket.addEventListener('message', publishListener);
199
+ this.awsRealTimeSocket.addEventListener('error', errorListener);
200
+ this.awsRealTimeSocket.addEventListener('close', closeListener);
201
+ this.awsRealTimeSocket.send(serializedSubscriptionMessage);
202
+ }
203
+ else {
204
+ reject(new Error('WebSocket is not connected'));
205
+ }
206
+ });
207
+ }
208
+ async _cleanupSubscription(subscriptionId, reconnectSubscription) {
209
+ // Cleanup reconnection subscription
210
+ reconnectSubscription?.unsubscribe();
211
+ // Cleanup after unsubscribing or observer.complete was called after _startSubscriptionWithAWSAppSyncRealTime
212
+ try {
213
+ // Waiting that subscription has been connected before trying to unsubscribe
214
+ await this._waitForSubscriptionToBeConnected(subscriptionId);
215
+ const { subscriptionState } = this.subscriptionObserverMap.get(subscriptionId) || {};
216
+ if (!subscriptionState) {
217
+ // subscription already unsubscribed
218
+ return;
219
+ }
220
+ if (subscriptionState === SUBSCRIPTION_STATUS.CONNECTED) {
221
+ this._sendUnsubscriptionMessage(subscriptionId);
222
+ }
223
+ else {
224
+ throw new Error('Subscription never connected');
225
+ }
226
+ }
227
+ catch (err) {
228
+ this.logger.debug(`Error while unsubscribing ${err}`);
229
+ }
230
+ finally {
231
+ this._removeSubscriptionObserver(subscriptionId);
232
+ }
233
+ }
234
+ // Monitor the connection state and pass changes along to Hub
235
+ _startConnectionStateMonitoring() {
236
+ return this.connectionStateMonitor.connectionStateObservable.subscribe(connectionState => {
237
+ dispatchApiEvent({
238
+ event: CONNECTION_STATE_CHANGE,
239
+ data: {
240
+ provider: this,
241
+ connectionState,
242
+ },
243
+ message: `Connection state is ${connectionState}`,
244
+ });
245
+ this.connectionState = connectionState;
246
+ // Trigger START_RECONNECT when the connection is disrupted
247
+ if (connectionState === ConnectionState.ConnectionDisrupted) {
248
+ this.reconnectionMonitor.record(ReconnectEvent.START_RECONNECT);
249
+ }
250
+ // Trigger HALT_RECONNECT to halt reconnection attempts when the state is anything other than
251
+ // ConnectionDisrupted or Connecting
252
+ if ([
253
+ ConnectionState.Connected,
254
+ ConnectionState.ConnectedPendingDisconnect,
255
+ ConnectionState.ConnectedPendingKeepAlive,
256
+ ConnectionState.ConnectedPendingNetwork,
257
+ ConnectionState.ConnectionDisruptedPendingNetwork,
258
+ ConnectionState.Disconnected,
259
+ ].includes(connectionState)) {
260
+ this.reconnectionMonitor.record(ReconnectEvent.HALT_RECONNECT);
261
+ }
262
+ });
263
+ }
264
+ async _startSubscriptionWithAWSAppSyncRealTime({ options, observer, subscriptionId, customUserAgentDetails, }) {
265
+ const { query, variables } = options;
266
+ this.subscriptionObserverMap.set(subscriptionId, {
267
+ observer,
268
+ query: query ?? '',
269
+ variables: variables ?? {},
270
+ subscriptionState: SUBSCRIPTION_STATUS.PENDING,
271
+ startAckTimeoutId: undefined,
272
+ });
273
+ const { additionalCustomHeaders, libraryConfigHeaders } = await additionalHeadersFromOptions(options);
274
+ const serializedSubscriptionMessage = await this._prepareSubscriptionPayload({
275
+ options,
276
+ subscriptionId,
277
+ customUserAgentDetails,
278
+ additionalCustomHeaders,
279
+ libraryConfigHeaders,
280
+ });
281
+ try {
282
+ await this._connectWebSocket(options);
283
+ }
284
+ catch (err) {
285
+ this._logStartSubscriptionError(subscriptionId, observer, err);
286
+ return;
287
+ }
288
+ // Potential race condition can occur when unsubscribe is called during _initializeWebSocketConnection.
289
+ // E.g.unsubscribe gets invoked prior to finishing WebSocket handshake or START_ACK.
290
+ // Both subscriptionFailedCallback and subscriptionReadyCallback are used to synchronized this.
291
+ const { subscriptionFailedCallback, subscriptionReadyCallback } = this.subscriptionObserverMap.get(subscriptionId) ?? {};
292
+ // This must be done before sending the message in order to be listening immediately
293
+ this.subscriptionObserverMap.set(subscriptionId, {
294
+ observer,
295
+ subscriptionState: SUBSCRIPTION_STATUS.PENDING,
296
+ query: query ?? '',
297
+ variables: variables ?? {},
298
+ subscriptionReadyCallback,
299
+ subscriptionFailedCallback,
300
+ startAckTimeoutId: setTimeout(() => {
301
+ this._timeoutStartSubscriptionAck(subscriptionId);
302
+ }, START_ACK_TIMEOUT),
303
+ });
304
+ if (this.awsRealTimeSocket) {
305
+ this.awsRealTimeSocket.send(serializedSubscriptionMessage);
306
+ }
307
+ }
308
+ // Log logic for start subscription failures
309
+ _logStartSubscriptionError(subscriptionId, observer, err) {
310
+ this.logger.debug({ err });
311
+ const message = String(err.message ?? '');
312
+ // Resolving to give the state observer time to propogate the update
313
+ this._closeSocket();
314
+ // Capture the error only when the network didn't cause disruption
315
+ if (this.connectionState !== ConnectionState.ConnectionDisruptedPendingNetwork) {
316
+ // When the error is non-retriable, error out the observable
317
+ if (isNonRetryableError(err)) {
318
+ observer.error({
319
+ errors: [
320
+ {
321
+ ...new GraphQLError(`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`),
322
+ },
323
+ ],
324
+ });
325
+ }
326
+ else {
327
+ this.logger.debug(`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`);
328
+ }
329
+ const { subscriptionFailedCallback } = this.subscriptionObserverMap.get(subscriptionId) || {};
330
+ // Notify concurrent unsubscription
331
+ if (typeof subscriptionFailedCallback === 'function') {
332
+ subscriptionFailedCallback();
333
+ }
334
+ }
335
+ }
336
+ // Waiting that subscription has been connected before trying to unsubscribe
337
+ async _waitForSubscriptionToBeConnected(subscriptionId) {
338
+ const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
339
+ if (subscriptionObserver) {
340
+ const { subscriptionState } = subscriptionObserver;
341
+ // This in case unsubscribe is invoked before sending start subscription message
342
+ if (subscriptionState === SUBSCRIPTION_STATUS.PENDING) {
343
+ return new Promise((resolve, reject) => {
344
+ const { observer, subscriptionState: observedSubscriptionState, variables, query, } = subscriptionObserver;
345
+ this.subscriptionObserverMap.set(subscriptionId, {
346
+ observer,
347
+ subscriptionState: observedSubscriptionState,
348
+ variables,
349
+ query,
350
+ subscriptionReadyCallback: resolve,
351
+ subscriptionFailedCallback: reject,
352
+ });
353
+ });
354
+ }
355
+ }
356
+ }
357
+ _sendUnsubscriptionMessage(subscriptionId) {
358
+ try {
359
+ if (this.awsRealTimeSocket &&
360
+ this.awsRealTimeSocket.readyState === WebSocket.OPEN &&
361
+ this.socketStatus === SOCKET_STATUS.READY) {
362
+ // Preparing unsubscribe message to stop receiving messages for that subscription
363
+ const unsubscribeMessage = this._unsubscribeMessage(subscriptionId);
364
+ const stringToAWSRealTime = JSON.stringify(unsubscribeMessage);
365
+ this.awsRealTimeSocket.send(stringToAWSRealTime);
366
+ }
367
+ }
368
+ catch (err) {
369
+ // If GQL_STOP is not sent because of disconnection issue, then there is nothing the client can do
370
+ this.logger.debug({ err });
371
+ }
372
+ }
373
+ _removeSubscriptionObserver(subscriptionId) {
374
+ this.subscriptionObserverMap.delete(subscriptionId);
375
+ // Verifying 1000ms after removing subscription in case there are new subscription unmount/mount
376
+ if (!this.allowNoSubscriptions) {
377
+ setTimeout(this._closeSocketIfRequired.bind(this), 1000);
378
+ }
379
+ }
380
+ _closeSocketIfRequired() {
381
+ if (this.subscriptionObserverMap.size > 0) {
382
+ // Active subscriptions on the WebSocket
383
+ return;
384
+ }
385
+ if (!this.awsRealTimeSocket) {
386
+ this.socketStatus = SOCKET_STATUS.CLOSED;
387
+ return;
388
+ }
389
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSING_CONNECTION);
390
+ if (this.awsRealTimeSocket.bufferedAmount > 0) {
391
+ // Still data on the WebSocket
392
+ setTimeout(this._closeSocketIfRequired.bind(this), 1000);
393
+ }
394
+ else {
395
+ this.logger.debug('closing WebSocket...');
396
+ const tempSocket = this.awsRealTimeSocket;
397
+ // Cleaning callbacks to avoid race condition, socket still exists
398
+ tempSocket.onclose = null;
399
+ tempSocket.onerror = null;
400
+ tempSocket.close(1000);
401
+ this.awsRealTimeSocket = undefined;
402
+ this.socketStatus = SOCKET_STATUS.CLOSED;
403
+ this._closeSocket();
404
+ }
405
+ }
406
+ maintainKeepAlive() {
407
+ this.keepAliveTimestamp = Date.now();
408
+ }
409
+ keepAliveHeartbeat(connectionTimeoutMs) {
410
+ const currentTime = Date.now();
411
+ // Check for missed KA message
412
+ if (currentTime - this.keepAliveTimestamp >
413
+ DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT) {
414
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE_MISSED);
415
+ }
416
+ else {
417
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE);
418
+ }
419
+ // Recognize we are disconnected if we haven't seen messages in the keep alive timeout period
420
+ if (currentTime - this.keepAliveTimestamp > connectionTimeoutMs) {
421
+ this._errorDisconnect(CONTROL_MSG.TIMEOUT_DISCONNECT);
422
+ }
423
+ }
424
+ _handleIncomingSubscriptionMessage(message) {
425
+ if (typeof message.data !== 'string') {
426
+ return;
427
+ }
428
+ const [isData, data] = this._handleSubscriptionData(message);
429
+ if (isData) {
430
+ this.maintainKeepAlive();
431
+ return;
432
+ }
433
+ const { type, id, payload } = data;
434
+ const { observer = null, query = '', variables = {}, startAckTimeoutId, subscriptionReadyCallback, subscriptionFailedCallback, } = this.subscriptionObserverMap.get(id) || {};
435
+ if (type === MESSAGE_TYPES.GQL_START_ACK ||
436
+ type === MESSAGE_TYPES.EVENT_SUBSCRIBE_ACK) {
437
+ this.logger.debug(`subscription ready for ${JSON.stringify({ query, variables })}`);
438
+ if (typeof subscriptionReadyCallback === 'function') {
439
+ subscriptionReadyCallback();
440
+ }
441
+ if (startAckTimeoutId)
442
+ clearTimeout(startAckTimeoutId);
443
+ dispatchApiEvent({
444
+ event: CONTROL_MSG.SUBSCRIPTION_ACK,
445
+ data: { query, variables },
446
+ message: 'Connection established for subscription',
447
+ });
448
+ const subscriptionState = SUBSCRIPTION_STATUS.CONNECTED;
449
+ if (observer) {
450
+ this.subscriptionObserverMap.set(id, {
451
+ observer,
452
+ query,
453
+ variables,
454
+ startAckTimeoutId: undefined,
455
+ subscriptionState,
456
+ subscriptionReadyCallback,
457
+ subscriptionFailedCallback,
458
+ });
459
+ }
460
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_ESTABLISHED);
461
+ return;
462
+ }
463
+ if (type === MESSAGE_TYPES.GQL_CONNECTION_KEEP_ALIVE) {
464
+ this.maintainKeepAlive();
465
+ return;
466
+ }
467
+ if (type === MESSAGE_TYPES.GQL_ERROR ||
468
+ type === MESSAGE_TYPES.EVENT_SUBSCRIBE_ERROR) {
469
+ const subscriptionState = SUBSCRIPTION_STATUS.FAILED;
470
+ if (observer) {
471
+ this.subscriptionObserverMap.set(id, {
472
+ observer,
473
+ query,
474
+ variables,
475
+ startAckTimeoutId,
476
+ subscriptionReadyCallback,
477
+ subscriptionFailedCallback,
478
+ subscriptionState,
479
+ });
480
+ let errorMessage = JSON.stringify(payload ?? data);
481
+ if (type === MESSAGE_TYPES.EVENT_SUBSCRIBE_ERROR) {
482
+ const { errors } = JSON.parse(String(message.data));
483
+ if (Array.isArray(errors) && errors.length > 0) {
484
+ const error = errors[0];
485
+ errorMessage = `${error.errorType}: ${error.message}`;
486
+ }
487
+ }
488
+ this.logger.debug(`${CONTROL_MSG.CONNECTION_FAILED}: ${errorMessage}`);
489
+ observer.error({
490
+ errors: [
491
+ {
492
+ ...new GraphQLError(`${CONTROL_MSG.CONNECTION_FAILED}: ${errorMessage}`),
493
+ },
494
+ ],
495
+ });
496
+ if (startAckTimeoutId)
497
+ clearTimeout(startAckTimeoutId);
498
+ if (typeof subscriptionFailedCallback === 'function') {
499
+ subscriptionFailedCallback();
500
+ }
501
+ }
502
+ }
503
+ }
504
+ _errorDisconnect(msg) {
505
+ this.logger.debug(`Disconnect error: ${msg}`);
506
+ if (this.awsRealTimeSocket) {
507
+ this._closeSocket();
508
+ this.awsRealTimeSocket.close();
509
+ }
510
+ this.socketStatus = SOCKET_STATUS.CLOSED;
511
+ }
512
+ _closeSocket() {
513
+ if (this.keepAliveHeartbeatIntervalId) {
514
+ clearInterval(this.keepAliveHeartbeatIntervalId);
515
+ this.keepAliveHeartbeatIntervalId = undefined;
516
+ }
517
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
518
+ }
519
+ _timeoutStartSubscriptionAck(subscriptionId) {
520
+ const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
521
+ if (subscriptionObserver) {
522
+ const { observer, query, variables } = subscriptionObserver;
523
+ if (!observer) {
524
+ return;
525
+ }
526
+ this.subscriptionObserverMap.set(subscriptionId, {
527
+ observer,
528
+ query,
529
+ variables,
530
+ subscriptionState: SUBSCRIPTION_STATUS.FAILED,
531
+ });
532
+ this._closeSocket();
533
+ this.logger.debug('timeoutStartSubscription', JSON.stringify({ query, variables }));
534
+ }
535
+ }
536
+ _initializeWebSocketConnection({ appSyncGraphqlEndpoint, authenticationType, apiKey, region, additionalCustomHeaders, }) {
537
+ if (this.socketStatus === SOCKET_STATUS.READY) {
538
+ return;
539
+ }
540
+ // TODO(Eslint): refactor to now use async function as the promise executor
541
+ // eslint-disable-next-line no-async-promise-executor
542
+ return new Promise(async (resolve, reject) => {
543
+ this.promiseArray.push({ res: resolve, rej: reject });
544
+ if (this.socketStatus === SOCKET_STATUS.CLOSED) {
545
+ try {
546
+ this.socketStatus = SOCKET_STATUS.CONNECTING;
547
+ // Empty payload on connect
548
+ const payloadString = '{}';
549
+ const authHeader = await awsRealTimeHeaderBasedAuth({
550
+ authenticationType,
551
+ payload: payloadString,
552
+ canonicalUri: this.wsConnectUri,
553
+ apiKey,
554
+ appSyncGraphqlEndpoint,
555
+ region,
556
+ additionalCustomHeaders,
557
+ });
558
+ const headerString = authHeader ? JSON.stringify(authHeader) : '';
559
+ // base64url-encoded string
560
+ const encodedHeader = base64Encoder.convert(headerString, {
561
+ urlSafe: true,
562
+ skipPadding: true,
563
+ });
564
+ const authTokenSubprotocol = `header-${encodedHeader}`;
565
+ const queryParams = queryParamsFromCustomHeaders(additionalCustomHeaders);
566
+ const awsRealTimeUrl = realtimeUrlWithQueryString(appSyncGraphqlEndpoint, queryParams);
567
+ await this._establishRetryableConnection(awsRealTimeUrl, authTokenSubprotocol);
568
+ this.promiseArray.forEach(({ res }) => {
569
+ this.logger.debug('Notifying connection successful');
570
+ res();
571
+ });
572
+ this.socketStatus = SOCKET_STATUS.READY;
573
+ this.promiseArray = [];
574
+ }
575
+ catch (err) {
576
+ this.logger.debug('Connection exited with', err);
577
+ this.promiseArray.forEach(({ rej }) => {
578
+ rej(err);
579
+ });
580
+ this.promiseArray = [];
581
+ if (this.awsRealTimeSocket &&
582
+ this.awsRealTimeSocket.readyState === WebSocket.OPEN) {
583
+ this.awsRealTimeSocket.close(3001);
584
+ }
585
+ this.awsRealTimeSocket = undefined;
586
+ this.socketStatus = SOCKET_STATUS.CLOSED;
587
+ }
588
+ }
589
+ });
590
+ }
591
+ async _establishRetryableConnection(awsRealTimeUrl, subprotocol) {
592
+ this.logger.debug(`Establishing retryable connection`);
593
+ await jitteredExponentialRetry(this._establishConnection.bind(this), [awsRealTimeUrl, subprotocol], MAX_DELAY_MS);
594
+ }
595
+ async _openConnection(awsRealTimeUrl, subprotocol) {
596
+ return new Promise((resolve, reject) => {
597
+ const newSocket = this._getNewWebSocket(awsRealTimeUrl, [
598
+ this.wsProtocolName,
599
+ subprotocol,
600
+ ]);
601
+ newSocket.onerror = () => {
602
+ this.logger.debug(`WebSocket connection error`);
603
+ };
604
+ newSocket.onclose = () => {
605
+ this._closeSocket();
606
+ reject(new Error('Connection handshake error'));
607
+ };
608
+ newSocket.onopen = () => {
609
+ this.awsRealTimeSocket = newSocket;
610
+ resolve();
611
+ };
612
+ });
613
+ }
614
+ _getNewWebSocket(url, protocol) {
615
+ return new WebSocket(url, protocol);
616
+ }
617
+ async _initiateHandshake() {
618
+ return new Promise((resolve, reject) => {
619
+ if (!this.awsRealTimeSocket) {
620
+ reject(new Error('awsRealTimeSocket undefined'));
621
+ return;
622
+ }
623
+ let ackOk = false;
624
+ this.awsRealTimeSocket.onerror = error => {
625
+ this.logger.debug(`WebSocket error ${JSON.stringify(error)}`);
626
+ };
627
+ this.awsRealTimeSocket.onclose = event => {
628
+ this.logger.debug(`WebSocket closed ${event.reason}`);
629
+ this._closeSocket();
630
+ reject(new Error(JSON.stringify(event)));
631
+ };
632
+ this.awsRealTimeSocket.onmessage = (message) => {
633
+ if (typeof message.data !== 'string') {
634
+ return;
635
+ }
636
+ this.logger.debug(`subscription message from AWS AppSyncRealTime: ${message.data} `);
637
+ const data = JSON.parse(message.data);
638
+ const { type } = data;
639
+ const connectionTimeoutMs = this._extractConnectionTimeout(data);
640
+ if (type === MESSAGE_TYPES.GQL_CONNECTION_ACK) {
641
+ ackOk = true;
642
+ this._registerWebsocketHandlers(connectionTimeoutMs);
643
+ resolve('Connected to AWS AppSyncRealTime');
644
+ return;
645
+ }
646
+ if (type === MESSAGE_TYPES.GQL_CONNECTION_ERROR) {
647
+ const { errorType, errorCode } = this._extractErrorCodeAndType(data);
648
+ // TODO(Eslint): refactor to reject an Error object instead of a plain object
649
+ // eslint-disable-next-line prefer-promise-reject-errors
650
+ reject({ errorType, errorCode });
651
+ }
652
+ };
653
+ const gqlInit = {
654
+ type: MESSAGE_TYPES.GQL_CONNECTION_INIT,
655
+ };
656
+ this.awsRealTimeSocket.send(JSON.stringify(gqlInit));
657
+ const checkAckOk = (targetAckOk) => {
658
+ if (!targetAckOk) {
659
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_FAILED);
660
+ reject(new Error(`Connection timeout: ack from AWSAppSyncRealTime was not received after ${CONNECTION_INIT_TIMEOUT} ms`));
661
+ }
662
+ };
663
+ setTimeout(() => {
664
+ checkAckOk(ackOk);
665
+ }, CONNECTION_INIT_TIMEOUT);
666
+ });
667
+ }
668
+ _registerWebsocketHandlers(connectionTimeoutMs) {
669
+ if (!this.awsRealTimeSocket) {
670
+ return;
671
+ }
672
+ // Set up a keep alive heartbeat for this connection
673
+ this.keepAliveHeartbeatIntervalId = setInterval(() => {
674
+ this.keepAliveHeartbeat(connectionTimeoutMs);
675
+ }, DEFAULT_KEEP_ALIVE_HEARTBEAT_TIMEOUT);
676
+ this.awsRealTimeSocket.onmessage =
677
+ this._handleIncomingSubscriptionMessage.bind(this);
678
+ this.awsRealTimeSocket.onerror = err => {
679
+ this.logger.debug(err);
680
+ this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
681
+ };
682
+ this.awsRealTimeSocket.onclose = event => {
683
+ this.logger.debug(`WebSocket closed ${event.reason}`);
684
+ this._closeSocket();
685
+ this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
686
+ };
687
+ }
688
+ }
689
+
690
+ export { AWSWebSocketProvider };
691
+ //# sourceMappingURL=index.mjs.map