@aws-amplify/api-graphql 3.4.11 → 4.0.1-console-preview.047a1dd.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +3 -0
  2. package/lib/GraphQLAPI.js +0 -5
  3. package/lib/Providers/AWSAppSyncRealTimeProvider/index.d.ts +67 -0
  4. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js +817 -0
  5. package/lib/Providers/constants.d.ts +95 -0
  6. package/lib/Providers/constants.js +103 -0
  7. package/lib/index.d.ts +0 -3
  8. package/lib/index.js +3 -9
  9. package/lib/internals/InternalGraphQLAPI.d.ts +4 -40
  10. package/lib/internals/InternalGraphQLAPI.js +89 -243
  11. package/lib/internals/index.d.ts +1 -0
  12. package/lib/internals/index.js +2 -1
  13. package/lib/internals/v6.d.ts +89 -0
  14. package/lib/internals/v6.js +99 -0
  15. package/lib/tsconfig.tsbuildinfo +5790 -0
  16. package/lib/types/PubSub.d.ts +27 -0
  17. package/lib/types/PubSub.js +46 -0
  18. package/lib/types/index.d.ts +184 -4
  19. package/lib/types/index.js +0 -3
  20. package/lib/utils/ConnectionStateMonitor.d.ts +41 -0
  21. package/lib/utils/ConnectionStateMonitor.js +143 -0
  22. package/lib/utils/ReachabilityMonitor/index.d.ts +3 -0
  23. package/lib/utils/ReachabilityMonitor/index.js +6 -0
  24. package/lib/utils/ReachabilityMonitor/index.native.d.ts +3 -0
  25. package/lib/utils/ReachabilityMonitor/index.native.js +10 -0
  26. package/lib/utils/ReconnectionMonitor.d.ts +29 -0
  27. package/lib/utils/ReconnectionMonitor.js +72 -0
  28. package/lib/utils/errors/APIError.d.ts +7 -0
  29. package/lib/utils/errors/APIError.js +22 -0
  30. package/lib/utils/errors/assertValidationError.d.ts +5 -0
  31. package/lib/utils/errors/assertValidationError.js +16 -0
  32. package/lib/utils/errors/index.d.ts +3 -0
  33. package/lib/utils/errors/index.js +11 -0
  34. package/lib/utils/errors/validation.d.ts +8 -0
  35. package/lib/utils/errors/validation.js +26 -0
  36. package/lib/utils/index.d.ts +2 -0
  37. package/lib/utils/index.js +8 -0
  38. package/lib/utils/resolveConfig.d.ts +8 -0
  39. package/lib/utils/resolveConfig.js +17 -0
  40. package/lib/utils/resolveCredentials.d.ts +12 -0
  41. package/lib/utils/resolveCredentials.js +22 -0
  42. package/lib-esm/GraphQLAPI.js +0 -5
  43. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +67 -0
  44. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js +815 -0
  45. package/lib-esm/Providers/constants.d.ts +95 -0
  46. package/lib-esm/Providers/constants.js +100 -0
  47. package/lib-esm/index.d.ts +0 -3
  48. package/lib-esm/index.js +0 -4
  49. package/lib-esm/internals/InternalGraphQLAPI.d.ts +4 -40
  50. package/lib-esm/internals/InternalGraphQLAPI.js +90 -244
  51. package/lib-esm/internals/index.d.ts +1 -0
  52. package/lib-esm/internals/index.js +1 -1
  53. package/lib-esm/internals/v6.d.ts +89 -0
  54. package/lib-esm/internals/v6.js +96 -0
  55. package/lib-esm/tsconfig.tsbuildinfo +5790 -0
  56. package/lib-esm/types/PubSub.d.ts +27 -0
  57. package/lib-esm/types/PubSub.js +44 -0
  58. package/lib-esm/types/index.d.ts +184 -4
  59. package/lib-esm/types/index.js +0 -3
  60. package/lib-esm/utils/ConnectionStateMonitor.d.ts +41 -0
  61. package/lib-esm/utils/ConnectionStateMonitor.js +141 -0
  62. package/lib-esm/utils/ReachabilityMonitor/index.d.ts +3 -0
  63. package/lib-esm/utils/ReachabilityMonitor/index.js +4 -0
  64. package/lib-esm/utils/ReachabilityMonitor/index.native.d.ts +3 -0
  65. package/lib-esm/utils/ReachabilityMonitor/index.native.js +7 -0
  66. package/lib-esm/utils/ReconnectionMonitor.d.ts +29 -0
  67. package/lib-esm/utils/ReconnectionMonitor.js +70 -0
  68. package/lib-esm/utils/errors/APIError.d.ts +7 -0
  69. package/lib-esm/utils/errors/APIError.js +20 -0
  70. package/lib-esm/utils/errors/assertValidationError.d.ts +5 -0
  71. package/lib-esm/utils/errors/assertValidationError.js +13 -0
  72. package/lib-esm/utils/errors/index.d.ts +3 -0
  73. package/lib-esm/utils/errors/index.js +5 -0
  74. package/lib-esm/utils/errors/validation.d.ts +8 -0
  75. package/lib-esm/utils/errors/validation.js +24 -0
  76. package/lib-esm/utils/index.d.ts +2 -0
  77. package/lib-esm/utils/index.js +4 -0
  78. package/lib-esm/utils/resolveConfig.d.ts +8 -0
  79. package/lib-esm/utils/resolveConfig.js +15 -0
  80. package/lib-esm/utils/resolveCredentials.d.ts +12 -0
  81. package/lib-esm/utils/resolveCredentials.js +20 -0
  82. package/package.json +114 -114
  83. package/src/GraphQLAPI.ts +0 -2
  84. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +1003 -0
  85. package/src/Providers/constants.ts +110 -0
  86. package/src/index.ts +0 -3
  87. package/src/internals/InternalGraphQLAPI.ts +62 -221
  88. package/src/internals/index.ts +2 -0
  89. package/src/internals/v6.ts +106 -0
  90. package/src/types/PubSub.ts +58 -0
  91. package/src/types/index.ts +234 -7
  92. package/src/utils/ConnectionStateMonitor.ts +195 -0
  93. package/src/utils/ReachabilityMonitor/index.native.ts +7 -0
  94. package/src/utils/ReachabilityMonitor/index.ts +4 -0
  95. package/src/utils/ReconnectionMonitor.ts +76 -0
  96. package/src/utils/errors/APIError.ts +18 -0
  97. package/src/utils/errors/assertValidationError.ts +19 -0
  98. package/src/utils/errors/index.ts +6 -0
  99. package/src/utils/errors/validation.ts +26 -0
  100. package/src/utils/index.ts +5 -0
  101. package/src/utils/resolveConfig.ts +20 -0
  102. package/src/utils/resolveCredentials.ts +14 -0
  103. package/lib/.tsbuildinfo +0 -3
  104. package/lib/GraphQLAPI.js.map +0 -1
  105. package/lib/index.js.map +0 -1
  106. package/lib/internals/InternalGraphQLAPI.js.map +0 -1
  107. package/lib/internals/index.js.map +0 -1
  108. package/lib/types/index.js.map +0 -1
  109. package/lib-esm/.tsbuildinfo +0 -3
  110. package/lib-esm/GraphQLAPI.js.map +0 -1
  111. package/lib-esm/index.js.map +0 -1
  112. package/lib-esm/internals/InternalGraphQLAPI.js.map +0 -1
  113. package/lib-esm/internals/index.js.map +0 -1
  114. package/lib-esm/types/index.js.map +0 -1
@@ -1,20 +1,25 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { Source, DocumentNode, GraphQLError, OperationTypeNode } from 'graphql';
3
+ import { Source, DocumentNode, GraphQLError } from 'graphql';
4
4
  export { OperationTypeNode } from 'graphql';
5
- import { GRAPHQL_AUTH_MODE } from '@aws-amplify/auth';
6
- export { GRAPHQL_AUTH_MODE };
7
- import { CustomUserAgentDetails } from '@aws-amplify/core';
5
+ import { Observable } from 'zen-observable-ts';
8
6
 
7
+ import { DocumentType } from '@aws-amplify/api-rest';
8
+ export type GraphQLAuthMode = 'AWS_IAM' | 'COGNITO_USERPOOLS' | 'API_KEY';
9
+
10
+ /**
11
+ * Loose/Unknown options for raw GraphQLAPICategory `graphql()`.
12
+ */
9
13
  export interface GraphQLOptions {
10
14
  query: string | DocumentNode;
11
- variables?: object;
12
- authMode?: keyof typeof GRAPHQL_AUTH_MODE;
15
+ variables?: Record<string, DocumentType>;
16
+ // authMode?: GraphQLAuthMode;
17
+ authMode?: string;
13
18
  authToken?: string;
14
19
  /**
15
20
  * @deprecated This property should not be used
16
21
  */
17
- userAgentSuffix?: string; // TODO: remove in v6
22
+ userAgentSuffix?: string;
18
23
  }
19
24
 
20
25
  export interface GraphQLResult<T = object> {
@@ -25,6 +30,75 @@ export interface GraphQLResult<T = object> {
25
30
  };
26
31
  }
27
32
 
33
+ // Opaque type used for determining the graphql query type
34
+ declare const queryType: unique symbol;
35
+
36
+ export type GraphQLQuery<T> = T & { readonly [queryType]: 'query' };
37
+ export type GraphQLSubscription<T> = T & {
38
+ readonly [queryType]: 'subscription';
39
+ };
40
+
41
+ /**
42
+ * The return value from a `graphql({query})` call when `query` is a subscription.
43
+ *
44
+ * ```ts
45
+ * // |-- You are here
46
+ * // v
47
+ * const subResult: GraphqlSubscriptionResult<T> = client.graphql({
48
+ * query: onCreateWidget
49
+ * });
50
+ *
51
+ * const sub = subResult.subscribe({
52
+ * //
53
+ * // |-- You are here
54
+ * // v
55
+ * next(message: GraphqlSubscriptionMessage<OnCreateWidgetSubscription>) {
56
+ * handle(message.value); // <-- type OnCreateWidgetSubscription
57
+ * }
58
+ * })
59
+ * ```
60
+ */
61
+ export type GraphqlSubscriptionResult<T> = Observable<
62
+ GraphqlSubscriptionMessage<T>
63
+ >;
64
+
65
+ /**
66
+ * The shape of messages passed to `next()` from a graphql subscription. E.g.,
67
+ *
68
+ * ```ts
69
+ * const sub = client.graphql({
70
+ * query: onCreateWidget,
71
+ * }).subscribe({
72
+ * //
73
+ * // |-- You are here
74
+ * // v
75
+ * next(message: GraphqlSubscriptionMessage<OnCreateWidgetSubscription>) {
76
+ * handle(message.value); // <-- type OnCreateWidgetSubscription
77
+ * }
78
+ * })
79
+ * ```
80
+ */
81
+ export type GraphqlSubscriptionMessage<T> = {
82
+ data?: T;
83
+ };
84
+
85
+ export interface AWSAppSyncRealTimeProviderOptions {
86
+ appSyncGraphqlEndpoint?: string;
87
+ authenticationType?: GraphQLAuthMode;
88
+ query?: string;
89
+ variables?: Record<string, unknown>;
90
+ apiKey?: string;
91
+ region?: string;
92
+ graphql_headers?: () => {} | (() => Promise<{}>);
93
+ additionalHeaders?: { [key: string]: string };
94
+ }
95
+
96
+ export type AWSAppSyncRealTimeProvider = {
97
+ subscribe(
98
+ options?: AWSAppSyncRealTimeProviderOptions
99
+ ): Observable<Record<string, unknown>>;
100
+ };
101
+
28
102
  export enum GraphQLAuthError {
29
103
  NO_API_KEY = 'No api-key configured',
30
104
  NO_CURRENT_USER = 'No current user',
@@ -38,3 +112,156 @@ export enum GraphQLAuthError {
38
112
  * @see: https://graphql.org/graphql-js/language/#parse
39
113
  */
40
114
  export type GraphQLOperation = Source | string;
115
+
116
+ /**
117
+ * API V6 `graphql({options})` type that can leverage branded graphql `query`
118
+ * objects and fallback types.
119
+ */
120
+ export interface GraphQLOptionsV6<
121
+ FALLBACK_TYPES = unknown,
122
+ TYPED_GQL_STRING extends string = string
123
+ > {
124
+ query: TYPED_GQL_STRING | DocumentNode;
125
+ variables?: GraphQLVariablesV6<FALLBACK_TYPES, TYPED_GQL_STRING>;
126
+ authMode?: GraphQLAuthMode;
127
+ authToken?: string;
128
+ /**
129
+ * @deprecated This property should not be used
130
+ */
131
+ userAgentSuffix?: string;
132
+ }
133
+
134
+ /**
135
+ * Result type for `graphql()` operations that don't include any specific
136
+ * type information. The result could be either a `Promise` or `Subscription`.
137
+ *
138
+ * Invoking code should either cast the result or use `?` and `!` operators to
139
+ * navigate the result objects.
140
+ */
141
+ export type UnknownGraphQLResponse =
142
+ | Promise<GraphQLResult<any>>
143
+ | GraphqlSubscriptionResult<any>;
144
+
145
+ /**
146
+ * The expected type for `variables` in a V6 `graphql()` operation with
147
+ * respect to the given `FALLBACK_TYPES` and `TYPED_GQL_STRING`.
148
+ */
149
+ export type GraphQLVariablesV6<
150
+ FALLBACK_TYPES = unknown,
151
+ TYPED_GQL_STRING extends string = string
152
+ > = TYPED_GQL_STRING extends GeneratedQuery<infer IN, any>
153
+ ? IN
154
+ : TYPED_GQL_STRING extends GeneratedMutation<infer IN, any>
155
+ ? IN
156
+ : TYPED_GQL_STRING extends GeneratedSubscription<infer IN, any>
157
+ ? IN
158
+ : FALLBACK_TYPES extends GraphQLOperationType<infer IN, any>
159
+ ? IN
160
+ : any;
161
+
162
+ /**
163
+ * The expected return type with respect to the given `FALLBACK_TYPE`
164
+ * and `TYPED_GQL_STRING`.
165
+ */
166
+ export type GraphQLResponseV6<
167
+ FALLBACK_TYPE = unknown,
168
+ TYPED_GQL_STRING extends string = string
169
+ > = TYPED_GQL_STRING extends GeneratedQuery<infer IN, infer QUERY_OUT>
170
+ ? Promise<GraphQLResult<QUERY_OUT>>
171
+ : TYPED_GQL_STRING extends GeneratedMutation<infer IN, infer MUTATION_OUT>
172
+ ? Promise<GraphQLResult<MUTATION_OUT>>
173
+ : TYPED_GQL_STRING extends GeneratedSubscription<infer IN, infer SUB_OUT>
174
+ ? GraphqlSubscriptionResult<SUB_OUT>
175
+ : FALLBACK_TYPE extends GraphQLQuery<infer T>
176
+ ? Promise<GraphQLResult<FALLBACK_TYPE>>
177
+ : FALLBACK_TYPE extends GraphQLSubscription<infer T>
178
+ ? GraphqlSubscriptionResult<FALLBACK_TYPE>
179
+ : FALLBACK_TYPE extends GraphQLOperationType<infer IN, infer CUSTOM_OUT>
180
+ ? CUSTOM_OUT
181
+ : UnknownGraphQLResponse;
182
+
183
+ /**
184
+ * The shape customers can use to provide `T` to `graphql<T>()` to specify both
185
+ * `IN` and `OUT` types (the type of `variables` and the return type, respectively).
186
+ *
187
+ * I.E.,
188
+ *
189
+ * ```ts
190
+ * type MyVariablesType = { ... };
191
+ * type MyResultType = { ... };
192
+ * type MyOperationType = { variables: MyVariablesType, result: MyResultType };
193
+ *
194
+ * const result: MyResultType = graphql<MyOperationType>("graphql string", {
195
+ * variables: {
196
+ * // MyVariablesType
197
+ * }
198
+ * })
199
+ * ```
200
+ */
201
+ export type GraphQLOperationType<IN extends {}, OUT extends {}> = {
202
+ variables: IN;
203
+ result: OUT;
204
+ };
205
+
206
+ /**
207
+ * Nominal type for branding generated graphql query operation strings with
208
+ * input and output types.
209
+ *
210
+ * E.g.,
211
+ *
212
+ * ```ts
213
+ * export const getWidget = `...` as GeneratedQuery<
214
+ * GetWidgetQueryVariables,
215
+ * GetWidgetQuery
216
+ * >;
217
+ * ```
218
+ *
219
+ * This allows `graphql()` to extract `InputType` and `OutputType` to correctly
220
+ * assign types to the `variables` and result objects.
221
+ */
222
+ export type GeneratedQuery<InputType, OutputType> = string & {
223
+ __generatedQueryInput: InputType;
224
+ __generatedQueryOutput: OutputType;
225
+ };
226
+
227
+ /**
228
+ * Nominal type for branding generated graphql mutation operation strings with
229
+ * input and output types.
230
+ *
231
+ * E.g.,
232
+ *
233
+ * ```ts
234
+ * export const createWidget = `...` as GeneratedQuery<
235
+ * CreateWidgetMutationVariables,
236
+ * CreateWidgetMutation
237
+ * >;
238
+ * ```
239
+ *
240
+ * This allows `graphql()` to extract `InputType` and `OutputType` to correctly
241
+ * assign types to the `variables` and result objects.
242
+ */
243
+ export type GeneratedMutation<InputType, OutputType> = string & {
244
+ __generatedMutationInput: InputType;
245
+ __generatedMutationOutput: OutputType;
246
+ };
247
+
248
+ /**
249
+ * Nominal type for branding generated graphql mutation operation strings with
250
+ * input and output types.
251
+ *
252
+ * E.g.,
253
+ *
254
+ * ```ts
255
+ * export const createWidget = `...` as GeneratedMutation<
256
+ * CreateWidgetMutationVariables,
257
+ * CreateWidgetMutation
258
+ * >;
259
+ * ```
260
+ *
261
+ * This allows `graphql()` to extract `InputType` and `OutputType` to correctly
262
+ * assign types to the `variables` and result objects.
263
+ */
264
+ export type GeneratedSubscription<InputType, OutputType> = string & {
265
+ __generatedSubscriptionInput: InputType;
266
+ __generatedSubscriptionOutput: OutputType;
267
+ };
@@ -0,0 +1,195 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import Observable, { ZenObservable } from 'zen-observable-ts';
5
+ import { ConnectionState } from '../types/PubSub';
6
+ import { ReachabilityMonitor } from './ReachabilityMonitor';
7
+
8
+ // Internal types for tracking different connection states
9
+ type LinkedConnectionState = 'connected' | 'disconnected';
10
+ type LinkedHealthState = 'healthy' | 'unhealthy';
11
+ type LinkedConnectionStates = {
12
+ networkState: LinkedConnectionState;
13
+ connectionState: LinkedConnectionState | 'connecting';
14
+ intendedConnectionState: LinkedConnectionState;
15
+ keepAliveState: LinkedHealthState;
16
+ };
17
+
18
+ export const CONNECTION_CHANGE: {
19
+ [key in
20
+ | 'KEEP_ALIVE_MISSED'
21
+ | 'KEEP_ALIVE'
22
+ | 'CONNECTION_ESTABLISHED'
23
+ | 'CONNECTION_FAILED'
24
+ | 'CLOSING_CONNECTION'
25
+ | 'OPENING_CONNECTION'
26
+ | 'CLOSED'
27
+ | 'ONLINE'
28
+ | 'OFFLINE']: Partial<LinkedConnectionStates>;
29
+ } = {
30
+ KEEP_ALIVE_MISSED: { keepAliveState: 'unhealthy' },
31
+ KEEP_ALIVE: { keepAliveState: 'healthy' },
32
+ CONNECTION_ESTABLISHED: { connectionState: 'connected' },
33
+ CONNECTION_FAILED: {
34
+ intendedConnectionState: 'disconnected',
35
+ connectionState: 'disconnected',
36
+ },
37
+ CLOSING_CONNECTION: { intendedConnectionState: 'disconnected' },
38
+ OPENING_CONNECTION: {
39
+ intendedConnectionState: 'connected',
40
+ connectionState: 'connecting',
41
+ },
42
+ CLOSED: { connectionState: 'disconnected' },
43
+ ONLINE: { networkState: 'connected' },
44
+ OFFLINE: { networkState: 'disconnected' },
45
+ };
46
+
47
+ export class ConnectionStateMonitor {
48
+ /**
49
+ * @private
50
+ */
51
+ private _linkedConnectionState: LinkedConnectionStates;
52
+ private _linkedConnectionStateObservable: Observable<LinkedConnectionStates>;
53
+ private _linkedConnectionStateObserver: ZenObservable.SubscriptionObserver<LinkedConnectionStates>;
54
+ private _networkMonitoringSubscription?: ZenObservable.Subscription;
55
+ private _initialNetworkStateSubscription?: ZenObservable.Subscription;
56
+
57
+ constructor() {
58
+ this._networkMonitoringSubscription = undefined;
59
+ this._linkedConnectionState = {
60
+ networkState: 'connected',
61
+ connectionState: 'disconnected',
62
+ intendedConnectionState: 'disconnected',
63
+ keepAliveState: 'healthy',
64
+ };
65
+
66
+ // Attempt to update the state with the current actual network state
67
+ this._initialNetworkStateSubscription = ReachabilityMonitor().subscribe(
68
+ ({ online }) => {
69
+ this.record(
70
+ online ? CONNECTION_CHANGE.ONLINE : CONNECTION_CHANGE.OFFLINE
71
+ );
72
+ this._initialNetworkStateSubscription?.unsubscribe();
73
+ }
74
+ );
75
+
76
+ this._linkedConnectionStateObservable =
77
+ new Observable<LinkedConnectionStates>(connectionStateObserver => {
78
+ connectionStateObserver.next(this._linkedConnectionState);
79
+ this._linkedConnectionStateObserver = connectionStateObserver;
80
+ });
81
+ }
82
+
83
+ /**
84
+ * Turn network state monitoring on if it isn't on already
85
+ */
86
+ private enableNetworkMonitoring() {
87
+ // If no initial network state was discovered, stop trying
88
+ this._initialNetworkStateSubscription?.unsubscribe();
89
+
90
+ // Maintain the network state based on the reachability monitor
91
+ if (this._networkMonitoringSubscription === undefined) {
92
+ this._networkMonitoringSubscription = ReachabilityMonitor().subscribe(
93
+ ({ online }) => {
94
+ this.record(
95
+ online ? CONNECTION_CHANGE.ONLINE : CONNECTION_CHANGE.OFFLINE
96
+ );
97
+ }
98
+ );
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Turn network state monitoring off if it isn't off already
104
+ */
105
+ private disableNetworkMonitoring() {
106
+ this._networkMonitoringSubscription?.unsubscribe();
107
+ this._networkMonitoringSubscription = undefined;
108
+ }
109
+
110
+ /**
111
+ * Get the observable that allows us to monitor the connection state
112
+ *
113
+ * @returns {Observable<ConnectionState>} - The observable that emits ConnectionState updates
114
+ */
115
+ public get connectionStateObservable(): Observable<ConnectionState> {
116
+ let previous: ConnectionState;
117
+
118
+ // The linked state aggregates state changes to any of the network, connection,
119
+ // intendedConnection and keepAliveHealth. Some states will change these independent
120
+ // states without changing the overall connection state.
121
+
122
+ // After translating from linked states to ConnectionState, then remove any duplicates
123
+ return this._linkedConnectionStateObservable
124
+ .map(value => {
125
+ return this.connectionStatesTranslator(value);
126
+ })
127
+ .filter(current => {
128
+ const toInclude = current !== previous;
129
+ previous = current;
130
+ return toInclude;
131
+ });
132
+ }
133
+
134
+ /*
135
+ * Updates local connection state and emits the full state to the observer.
136
+ */
137
+ record(statusUpdates: Partial<LinkedConnectionStates>) {
138
+ // Maintain the network monitor
139
+ if (statusUpdates.intendedConnectionState === 'connected') {
140
+ this.enableNetworkMonitoring();
141
+ } else if (statusUpdates.intendedConnectionState === 'disconnected') {
142
+ this.disableNetworkMonitoring();
143
+ }
144
+
145
+ // Maintain the socket state
146
+ const newSocketStatus = {
147
+ ...this._linkedConnectionState,
148
+ ...statusUpdates,
149
+ };
150
+
151
+ this._linkedConnectionState = { ...newSocketStatus };
152
+
153
+ this._linkedConnectionStateObserver.next(this._linkedConnectionState);
154
+ }
155
+
156
+ /*
157
+ * Translate the ConnectionState structure into a specific ConnectionState string literal union
158
+ */
159
+ private connectionStatesTranslator({
160
+ connectionState,
161
+ networkState,
162
+ intendedConnectionState,
163
+ keepAliveState,
164
+ }: LinkedConnectionStates): ConnectionState {
165
+ if (connectionState === 'connected' && networkState === 'disconnected')
166
+ return ConnectionState.ConnectedPendingNetwork;
167
+
168
+ if (
169
+ connectionState === 'connected' &&
170
+ intendedConnectionState === 'disconnected'
171
+ )
172
+ return ConnectionState.ConnectedPendingDisconnect;
173
+
174
+ if (
175
+ connectionState === 'disconnected' &&
176
+ intendedConnectionState === 'connected' &&
177
+ networkState === 'disconnected'
178
+ )
179
+ return ConnectionState.ConnectionDisruptedPendingNetwork;
180
+
181
+ if (
182
+ connectionState === 'disconnected' &&
183
+ intendedConnectionState === 'connected'
184
+ )
185
+ return ConnectionState.ConnectionDisrupted;
186
+
187
+ if (connectionState === 'connected' && keepAliveState === 'unhealthy')
188
+ return ConnectionState.ConnectedPendingKeepAlive;
189
+
190
+ // All remaining states directly correspond to the connection state
191
+ if (connectionState === 'connecting') return ConnectionState.Connecting;
192
+ if (connectionState === 'disconnected') return ConnectionState.Disconnected;
193
+ return ConnectionState.Connected;
194
+ }
195
+ }
@@ -0,0 +1,7 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { Reachability } from '@aws-amplify/core/internals/utils';
4
+ import { default as NetInfo } from '@react-native-community/netinfo';
5
+
6
+ export const ReachabilityMonitor = () =>
7
+ new Reachability().networkMonitor(NetInfo);
@@ -0,0 +1,4 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { Reachability } from '@aws-amplify/core/internals/utils';
4
+ export const ReachabilityMonitor = () => new Reachability().networkMonitor();
@@ -0,0 +1,76 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { Observer } from 'zen-observable-ts';
4
+ import { RECONNECT_DELAY, RECONNECT_INTERVAL } from '../Providers/constants';
5
+
6
+ export enum ReconnectEvent {
7
+ START_RECONNECT = 'START_RECONNECT',
8
+ HALT_RECONNECT = 'HALT_RECONNECT',
9
+ }
10
+
11
+ /**
12
+ * Captures the reconnect event logic used to determine when to reconnect to PubSub providers.
13
+ * Reconnnect attempts are delayed by 5 seconds to let the interface settle.
14
+ * Attempting to reconnect only once creates unrecoverable states when the network state isn't
15
+ * supported by the browser, so this keeps retrying every minute until halted.
16
+ */
17
+ export class ReconnectionMonitor {
18
+ private reconnectObservers: Observer<void>[] = [];
19
+ private reconnectIntervalId?: ReturnType<typeof setInterval>;
20
+ private reconnectSetTimeoutId?: ReturnType<typeof setTimeout>;
21
+
22
+ /**
23
+ * Add reconnect observer to the list of observers to alert on reconnect
24
+ */
25
+ addObserver(reconnectObserver: Observer<void>) {
26
+ this.reconnectObservers.push(reconnectObserver);
27
+ }
28
+
29
+ /**
30
+ * Given a reconnect event, start the appropriate behavior
31
+ */
32
+ record(event: ReconnectEvent) {
33
+ if (event === ReconnectEvent.START_RECONNECT) {
34
+ // If the reconnection hasn't been started
35
+ if (
36
+ this.reconnectSetTimeoutId === undefined &&
37
+ this.reconnectIntervalId === undefined
38
+ ) {
39
+ this.reconnectSetTimeoutId = setTimeout(() => {
40
+ // Reconnect now
41
+ this._triggerReconnect();
42
+ // Retry reconnect every periodically until it works
43
+ this.reconnectIntervalId = setInterval(() => {
44
+ this._triggerReconnect();
45
+ }, RECONNECT_INTERVAL);
46
+ }, RECONNECT_DELAY);
47
+ }
48
+ }
49
+
50
+ if (event === ReconnectEvent.HALT_RECONNECT) {
51
+ if (this.reconnectIntervalId) {
52
+ clearInterval(this.reconnectIntervalId);
53
+ this.reconnectIntervalId = undefined;
54
+ }
55
+ if (this.reconnectSetTimeoutId) {
56
+ clearTimeout(this.reconnectSetTimeoutId);
57
+ this.reconnectSetTimeoutId = undefined;
58
+ }
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Complete all reconnect observers
64
+ */
65
+ close() {
66
+ this.reconnectObservers.forEach(reconnectObserver => {
67
+ reconnectObserver.complete?.();
68
+ });
69
+ }
70
+
71
+ private _triggerReconnect() {
72
+ this.reconnectObservers.forEach(reconnectObserver => {
73
+ reconnectObserver.next?.();
74
+ });
75
+ }
76
+ }
@@ -0,0 +1,18 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { AmplifyError, ErrorParams } from '@aws-amplify/core/internals/utils';
5
+
6
+ /**
7
+ * @internal
8
+ */
9
+ export class APIError extends AmplifyError {
10
+ constructor(params: ErrorParams) {
11
+ super(params);
12
+
13
+ // Hack for making the custom error class work when transpiled to es5
14
+ // TODO: Delete the following 2 lines after we change the build target to >= es2015
15
+ this.constructor = APIError;
16
+ Object.setPrototypeOf(this, APIError.prototype);
17
+ }
18
+ }
@@ -0,0 +1,19 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { APIError } from './APIError';
5
+ import { APIValidationErrorCode, validationErrorMap } from './validation';
6
+
7
+ /**
8
+ * @internal
9
+ */
10
+ export function assertValidationError(
11
+ assertion: boolean,
12
+ name: APIValidationErrorCode
13
+ ): asserts assertion {
14
+ const { message, recoverySuggestion } = validationErrorMap[name];
15
+
16
+ if (!assertion) {
17
+ throw new APIError({ name, message, recoverySuggestion });
18
+ }
19
+ }
@@ -0,0 +1,6 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ export { APIError } from './APIError';
5
+ export { assertValidationError } from './assertValidationError';
6
+ export { APIValidationErrorCode, validationErrorMap } from './validation';
@@ -0,0 +1,26 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { AmplifyErrorMap } from '@aws-amplify/core/internals/utils';
5
+
6
+ export enum APIValidationErrorCode {
7
+ NoAppId = 'NoAppId',
8
+ NoCredentials = 'NoCredentials',
9
+ NoRegion = 'NoRegion',
10
+ NoDefaultAuthMode = 'NoDefaultAuthMode',
11
+ }
12
+
13
+ export const validationErrorMap: AmplifyErrorMap<APIValidationErrorCode> = {
14
+ [APIValidationErrorCode.NoAppId]: {
15
+ message: 'Missing application id.',
16
+ },
17
+ [APIValidationErrorCode.NoCredentials]: {
18
+ message: 'Credentials should not be empty.',
19
+ },
20
+ [APIValidationErrorCode.NoRegion]: {
21
+ message: 'Missing region.',
22
+ },
23
+ [APIValidationErrorCode.NoDefaultAuthMode]: {
24
+ message: 'Missing default auth mode',
25
+ },
26
+ };
@@ -0,0 +1,5 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ export { resolveConfig } from './resolveConfig';
5
+ export { resolveCredentials } from './resolveCredentials';
@@ -0,0 +1,20 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { Amplify } from '@aws-amplify/core';
5
+ import { APIValidationErrorCode, assertValidationError } from './errors';
6
+
7
+ /**
8
+ * @internal
9
+ */
10
+ export const resolveConfig = () => {
11
+ const { region, defaultAuthMode, endpoint } =
12
+ Amplify.getConfig().API?.AppSync ?? {};
13
+ assertValidationError(!!endpoint, APIValidationErrorCode.NoAppId);
14
+ assertValidationError(!!region, APIValidationErrorCode.NoRegion);
15
+ assertValidationError(
16
+ !!defaultAuthMode,
17
+ APIValidationErrorCode.NoDefaultAuthMode
18
+ );
19
+ return { endpoint, region, defaultAuthMode };
20
+ };
@@ -0,0 +1,14 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { fetchAuthSession } from '@aws-amplify/core';
5
+ import { APIValidationErrorCode, assertValidationError } from './errors';
6
+
7
+ /**
8
+ * @internal
9
+ */
10
+ export const resolveCredentials = async () => {
11
+ const { credentials, identityId } = await fetchAuthSession();
12
+ assertValidationError(!!credentials, APIValidationErrorCode.NoCredentials);
13
+ return { credentials, identityId };
14
+ };
package/lib/.tsbuildinfo DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "version": "3.8.3"
3
- }
@@ -1 +0,0 @@
1
- {"version":3,"file":"GraphQLAPI.js","sourceRoot":"","sources":["../src/GraphQLAPI.ts"],"names":[],"mappings":";;;AAAA,qEAAqE;AACrE,sCAAsC;AACtC,0CAA4C;AAE5C,yCAAsD;AAGzC,QAAA,gBAAgB,GAAG,UAC/B,KAAK,EACL,SAAc,EACd,SAAkB;IADlB,0BAAA,EAAA,cAAc;IAEV,OAAA,CAAC;QACL,KAAK,OAAA;QACL,SAAS,WAAA;QACT,SAAS,WAAA;KACT,CAAC;AAJG,CAIH,CAAC;AAEH;;GAEG;AACH;IAAqC,2CAAuB;IAA5D;;IAkBA,CAAC;IAjBO,uCAAa,GAApB;QACC,OAAO,YAAY,CAAC;IACrB,CAAC;IAED;;;;;;OAMG;IACH,iCAAO,GAAP,UACC,OAAuB,EACvB,iBAA6C;QAE7C,OAAO,iBAAM,OAAO,YAAC,OAAO,EAAE,iBAAiB,CAAC,CAAC;IAClD,CAAC;IACF,sBAAC;AAAD,CAAC,AAlBD,CAAqC,mCAAuB,GAkB3D;AAlBY,0CAAe;AAoBf,QAAA,UAAU,GAAG,IAAI,eAAe,CAAC,IAAI,CAAC,CAAC;AACpD,cAAO,CAAC,QAAQ,CAAC,kBAAU,CAAC,CAAC"}
package/lib/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,qEAAqE;AACrE,sCAAsC;;;AAEtC,2CAA0C;AAC1C,iCAA6E;AAArD,mCAAA,gBAAgB,CAAA;AAAE,oCAAA,iBAAiB,CAAA;AAC3D,2CAA6E;AAApE,kCAAA,UAAU,CAAA;AAAE,uCAAA,eAAe,CAAA;AAAE,wCAAA,gBAAgB,CAAA;AACtD,kDAAwB;AACxB,kBAAe,uBAAU,CAAC"}