@aws-amplify/api-graphql 3.4.12-api-v6-models.b3abc9b.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +3 -0
  2. package/lib/GraphQLAPI.d.ts +17 -4
  3. package/lib/GraphQLAPI.js +33 -27
  4. package/lib/Providers/AWSAppSyncRealTimeProvider/index.d.ts +64 -0
  5. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js +690 -0
  6. package/lib/Providers/constants.d.ts +95 -0
  7. package/lib/Providers/constants.js +103 -0
  8. package/lib/index.d.ts +1 -3
  9. package/lib/index.js +6 -10
  10. package/lib/internals/InternalGraphQLAPI.d.ts +11 -34
  11. package/lib/internals/InternalGraphQLAPI.js +219 -345
  12. package/lib/internals/index.d.ts +1 -1
  13. package/lib/internals/index.js +2 -1
  14. package/lib/internals/v6.d.ts +14 -2
  15. package/lib/internals/v6.js +21 -3
  16. package/lib/tsconfig.tsbuildinfo +6813 -0
  17. package/lib/types/PubSub.d.ts +27 -0
  18. package/lib/types/PubSub.js +46 -0
  19. package/lib/types/index.d.ts +119 -12
  20. package/lib/types/index.js +4 -3
  21. package/lib/utils/ConnectionStateMonitor.d.ts +41 -0
  22. package/lib/utils/ConnectionStateMonitor.js +131 -0
  23. package/lib/utils/ReachabilityMonitor/index.d.ts +1 -0
  24. package/lib/utils/ReachabilityMonitor/index.js +6 -0
  25. package/lib/utils/ReachabilityMonitor/index.native.d.ts +1 -0
  26. package/lib/utils/ReachabilityMonitor/index.native.js +8 -0
  27. package/lib/utils/ReconnectionMonitor.d.ts +29 -0
  28. package/lib/utils/ReconnectionMonitor.js +68 -0
  29. package/lib/utils/errors/APIError.d.ts +7 -0
  30. package/lib/utils/errors/APIError.js +18 -0
  31. package/lib/utils/errors/assertValidationError.d.ts +5 -0
  32. package/lib/utils/errors/assertValidationError.js +16 -0
  33. package/lib/utils/errors/index.d.ts +3 -0
  34. package/lib/utils/errors/index.js +11 -0
  35. package/lib/utils/errors/validation.d.ts +7 -0
  36. package/lib/utils/errors/validation.js +25 -0
  37. package/lib/utils/index.d.ts +2 -0
  38. package/lib/utils/index.js +8 -0
  39. package/lib/utils/resolveConfig.d.ts +12 -0
  40. package/lib/utils/resolveConfig.js +22 -0
  41. package/lib/utils/resolveLibraryOptions.d.ts +11 -0
  42. package/lib/utils/resolveLibraryOptions.js +12 -0
  43. package/lib-esm/GraphQLAPI.d.ts +17 -4
  44. package/lib-esm/GraphQLAPI.js +33 -28
  45. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +64 -0
  46. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js +687 -0
  47. package/lib-esm/Providers/constants.d.ts +95 -0
  48. package/lib-esm/Providers/constants.js +100 -0
  49. package/lib-esm/index.d.ts +1 -3
  50. package/lib-esm/index.js +1 -4
  51. package/lib-esm/internals/InternalGraphQLAPI.d.ts +11 -34
  52. package/lib-esm/internals/InternalGraphQLAPI.js +218 -345
  53. package/lib-esm/internals/index.d.ts +1 -1
  54. package/lib-esm/internals/index.js +1 -2
  55. package/lib-esm/internals/v6.d.ts +14 -2
  56. package/lib-esm/internals/v6.js +18 -2
  57. package/lib-esm/tsconfig.tsbuildinfo +6813 -0
  58. package/lib-esm/types/PubSub.d.ts +27 -0
  59. package/lib-esm/types/PubSub.js +44 -0
  60. package/lib-esm/types/index.d.ts +119 -12
  61. package/lib-esm/types/index.js +2 -3
  62. package/lib-esm/utils/ConnectionStateMonitor.d.ts +41 -0
  63. package/lib-esm/utils/ConnectionStateMonitor.js +128 -0
  64. package/lib-esm/utils/ReachabilityMonitor/index.d.ts +1 -0
  65. package/lib-esm/utils/ReachabilityMonitor/index.js +4 -0
  66. package/lib-esm/utils/ReachabilityMonitor/index.native.d.ts +1 -0
  67. package/lib-esm/utils/ReachabilityMonitor/index.native.js +5 -0
  68. package/lib-esm/utils/ReconnectionMonitor.d.ts +29 -0
  69. package/lib-esm/utils/ReconnectionMonitor.js +65 -0
  70. package/lib-esm/utils/errors/APIError.d.ts +7 -0
  71. package/lib-esm/utils/errors/APIError.js +15 -0
  72. package/lib-esm/utils/errors/assertValidationError.d.ts +5 -0
  73. package/lib-esm/utils/errors/assertValidationError.js +13 -0
  74. package/lib-esm/utils/errors/index.d.ts +3 -0
  75. package/lib-esm/utils/errors/index.js +5 -0
  76. package/lib-esm/utils/errors/validation.d.ts +7 -0
  77. package/lib-esm/utils/errors/validation.js +23 -0
  78. package/lib-esm/utils/index.d.ts +2 -0
  79. package/lib-esm/utils/index.js +4 -0
  80. package/lib-esm/utils/resolveConfig.d.ts +12 -0
  81. package/lib-esm/utils/resolveConfig.js +20 -0
  82. package/lib-esm/utils/resolveLibraryOptions.d.ts +11 -0
  83. package/lib-esm/utils/resolveLibraryOptions.js +10 -0
  84. package/package.json +122 -118
  85. package/src/GraphQLAPI.ts +26 -4
  86. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +998 -0
  87. package/src/Providers/constants.ts +110 -0
  88. package/src/index.ts +2 -3
  89. package/src/internals/InternalGraphQLAPI.ts +181 -218
  90. package/src/internals/index.ts +1 -1
  91. package/src/internals/v6.ts +34 -2
  92. package/src/types/PubSub.ts +56 -0
  93. package/src/types/index.ts +175 -15
  94. package/src/utils/ConnectionStateMonitor.ts +199 -0
  95. package/src/utils/ReachabilityMonitor/index.native.ts +7 -0
  96. package/src/utils/ReachabilityMonitor/index.ts +4 -0
  97. package/src/utils/ReconnectionMonitor.ts +76 -0
  98. package/src/utils/errors/APIError.ts +21 -0
  99. package/src/utils/errors/assertValidationError.ts +19 -0
  100. package/src/utils/errors/index.ts +6 -0
  101. package/src/utils/errors/validation.ts +26 -0
  102. package/src/utils/index.ts +5 -0
  103. package/src/utils/resolveConfig.ts +35 -0
  104. package/src/utils/resolveLibraryOptions.ts +13 -0
  105. package/lib/.tsbuildinfo +0 -3
  106. package/lib/GraphQLAPI.js.map +0 -1
  107. package/lib/index.js.map +0 -1
  108. package/lib/internals/InternalGraphQLAPI.js.map +0 -1
  109. package/lib/internals/index.js.map +0 -1
  110. package/lib/internals/v6.js.map +0 -1
  111. package/lib/types/index.js.map +0 -1
  112. package/lib-esm/.tsbuildinfo +0 -3
  113. package/lib-esm/GraphQLAPI.js.map +0 -1
  114. package/lib-esm/index.js.map +0 -1
  115. package/lib-esm/internals/InternalGraphQLAPI.js.map +0 -1
  116. package/lib-esm/internals/index.js.map +0 -1
  117. package/lib-esm/internals/v6.js.map +0 -1
  118. package/lib-esm/types/index.js.map +0 -1
@@ -1,186 +1,105 @@
1
- import { __assign, __awaiter, __generator, __read, __rest } from "tslib";
2
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
2
  // SPDX-License-Identifier: Apache-2.0
4
3
  import { print, parse, GraphQLError, } from 'graphql';
5
- import { Amplify, ConsoleLogger as Logger, Credentials, getAmplifyUserAgent, INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER, } from '@aws-amplify/core';
6
- import { InternalPubSub } from '@aws-amplify/pubsub/internals';
7
- import { Auth } from '@aws-amplify/auth';
8
- import { Cache } from '@aws-amplify/cache';
4
+ import { ConsoleLogger } from '@aws-amplify/core';
5
+ import { getAmplifyUserAgent, AmplifyUrl, } from '@aws-amplify/core/internals/utils';
9
6
  import { GraphQLAuthError, } from '../types';
10
- import { RestClient } from '@aws-amplify/api-rest';
11
- var USER_AGENT_HEADER = 'x-amz-user-agent';
12
- var logger = new Logger('GraphQLAPI');
13
- export var graphqlOperation = function (query, variables, authToken) {
14
- if (variables === void 0) { variables = {}; }
15
- return ({
16
- query: query,
17
- variables: variables,
18
- authToken: authToken,
19
- });
7
+ import { isCancelError as isCancelErrorREST } from '@aws-amplify/api-rest';
8
+ import { post, cancel as cancelREST, updateRequestToBeCancellable, } from '@aws-amplify/api-rest/internals';
9
+ import { AWSAppSyncRealTimeProvider } from '../Providers/AWSAppSyncRealTimeProvider';
10
+ import { resolveConfig, resolveLibraryOptions } from '../utils';
11
+ const USER_AGENT_HEADER = 'x-amz-user-agent';
12
+ const logger = new ConsoleLogger('GraphQLAPI');
13
+ export const graphqlOperation = (query, variables = {}, authToken) => ({
14
+ query,
15
+ variables,
16
+ authToken,
17
+ });
18
+ const isAmplifyInstance = (amplify) => {
19
+ return typeof amplify !== 'function';
20
20
  };
21
21
  /**
22
22
  * Export Cloud Logic APIs
23
23
  */
24
- var InternalGraphQLAPIClass = /** @class */ (function () {
24
+ export class InternalGraphQLAPIClass {
25
25
  /**
26
26
  * Initialize GraphQL API with AWS configuration
27
27
  * @param {Object} options - Configuration object for API
28
28
  */
29
- function InternalGraphQLAPIClass(options) {
30
- this._api = null;
31
- this.Auth = Auth;
32
- this.Cache = Cache;
33
- this.Credentials = Credentials;
29
+ constructor(options) {
30
+ this._api = {
31
+ post,
32
+ cancelREST,
33
+ isCancelErrorREST,
34
+ updateRequestToBeCancellable,
35
+ };
34
36
  this._options = options;
35
37
  logger.debug('API Options', this._options);
36
38
  }
37
- InternalGraphQLAPIClass.prototype.getModuleName = function () {
39
+ getModuleName() {
38
40
  return 'InternalGraphQLAPI';
39
- };
40
- /**
41
- * Configure API
42
- * @param {Object} config - Configuration of the API
43
- * @return {Object} - The current configuration
44
- */
45
- InternalGraphQLAPIClass.prototype.configure = function (options) {
46
- var _a = options || {}, _b = _a.API, API = _b === void 0 ? {} : _b, otherOptions = __rest(_a, ["API"]);
47
- var opt = __assign(__assign({}, otherOptions), API);
48
- logger.debug('configure GraphQL API', { opt: opt });
49
- if (opt['aws_project_region']) {
50
- opt = Object.assign({}, opt, {
51
- region: opt['aws_project_region'],
52
- header: {},
53
- });
54
- }
55
- if (typeof opt.graphql_headers !== 'undefined' &&
56
- typeof opt.graphql_headers !== 'function') {
57
- logger.warn('graphql_headers should be a function');
58
- opt.graphql_headers = undefined;
59
- }
60
- this._options = Object.assign({}, this._options, opt);
61
- this.createInstance();
62
- return this._options;
63
- };
64
- /**
65
- * Create an instance of API for the library
66
- * @return - A promise of true if Success
67
- */
68
- InternalGraphQLAPIClass.prototype.createInstance = function () {
69
- logger.debug('create Rest instance');
70
- if (this._options) {
71
- this._api = new RestClient(this._options);
72
- // Share instance Credentials with client for SSR
73
- this._api.Credentials = this.Credentials;
74
- return true;
75
- }
76
- else {
77
- return Promise.reject('API not configured');
78
- }
79
- };
80
- InternalGraphQLAPIClass.prototype._headerBasedAuth = function (defaultAuthenticationType, additionalHeaders) {
81
- if (additionalHeaders === void 0) { additionalHeaders = {}; }
82
- return __awaiter(this, void 0, void 0, function () {
83
- var _a, aws_appsync_authenticationType, apiKey, authenticationType, headers, _b, credentialsOK, token, federatedInfo, currentUser, e_1, session, e_2;
84
- return __generator(this, function (_c) {
85
- switch (_c.label) {
86
- case 0:
87
- _a = this._options, aws_appsync_authenticationType = _a.aws_appsync_authenticationType, apiKey = _a.aws_appsync_apiKey;
88
- authenticationType = defaultAuthenticationType || aws_appsync_authenticationType || 'AWS_IAM';
89
- headers = {};
90
- _b = authenticationType;
91
- switch (_b) {
92
- case 'API_KEY': return [3 /*break*/, 1];
93
- case 'AWS_IAM': return [3 /*break*/, 2];
94
- case 'OPENID_CONNECT': return [3 /*break*/, 4];
95
- case 'AMAZON_COGNITO_USER_POOLS': return [3 /*break*/, 11];
96
- case 'AWS_LAMBDA': return [3 /*break*/, 15];
97
- }
98
- return [3 /*break*/, 16];
99
- case 1:
100
- if (!apiKey) {
101
- throw new Error(GraphQLAuthError.NO_API_KEY);
102
- }
103
- headers = {
104
- Authorization: null,
105
- 'X-Api-Key': apiKey,
106
- };
107
- return [3 /*break*/, 17];
108
- case 2: return [4 /*yield*/, this._ensureCredentials()];
109
- case 3:
110
- credentialsOK = _c.sent();
111
- if (!credentialsOK) {
112
- throw new Error(GraphQLAuthError.NO_CREDENTIALS);
113
- }
114
- return [3 /*break*/, 17];
115
- case 4:
116
- _c.trys.push([4, 9, , 10]);
117
- token = void 0;
118
- return [4 /*yield*/, Cache.getItem('federatedInfo')];
119
- case 5:
120
- federatedInfo = _c.sent();
121
- if (!federatedInfo) return [3 /*break*/, 6];
122
- token = federatedInfo.token;
123
- return [3 /*break*/, 8];
124
- case 6: return [4 /*yield*/, Auth.currentAuthenticatedUser()];
125
- case 7:
126
- currentUser = _c.sent();
127
- if (currentUser) {
128
- token = currentUser.token;
129
- }
130
- _c.label = 8;
131
- case 8:
132
- if (!token) {
133
- throw new Error(GraphQLAuthError.NO_FEDERATED_JWT);
134
- }
135
- headers = {
136
- Authorization: token,
137
- };
138
- return [3 /*break*/, 10];
139
- case 9:
140
- e_1 = _c.sent();
141
- throw new Error(GraphQLAuthError.NO_CURRENT_USER);
142
- case 10: return [3 /*break*/, 17];
143
- case 11:
144
- _c.trys.push([11, 13, , 14]);
145
- return [4 /*yield*/, this.Auth.currentSession()];
146
- case 12:
147
- session = _c.sent();
148
- headers = {
149
- Authorization: session.getAccessToken().getJwtToken(),
150
- };
151
- return [3 /*break*/, 14];
152
- case 13:
153
- e_2 = _c.sent();
154
- throw new Error(GraphQLAuthError.NO_CURRENT_USER);
155
- case 14: return [3 /*break*/, 17];
156
- case 15:
157
- if (!additionalHeaders.Authorization) {
158
- throw new Error(GraphQLAuthError.NO_AUTH_TOKEN);
159
- }
160
- headers = {
161
- Authorization: additionalHeaders.Authorization,
162
- };
163
- return [3 /*break*/, 17];
164
- case 16:
165
- headers = {
166
- Authorization: null,
167
- };
168
- return [3 /*break*/, 17];
169
- case 17: return [2 /*return*/, headers];
41
+ }
42
+ async _headerBasedAuth(amplify, authMode, additionalHeaders = {}) {
43
+ const config = amplify.getConfig();
44
+ const { region: region, endpoint: appSyncGraphqlEndpoint, apiKey, defaultAuthMode, } = resolveConfig(amplify);
45
+ const authenticationType = authMode || defaultAuthMode || 'iam';
46
+ let headers = {};
47
+ switch (authenticationType) {
48
+ case 'apiKey':
49
+ if (!apiKey) {
50
+ throw new Error(GraphQLAuthError.NO_API_KEY);
170
51
  }
171
- });
172
- });
173
- };
52
+ headers = {
53
+ 'X-Api-Key': apiKey,
54
+ };
55
+ break;
56
+ case 'iam':
57
+ const session = await amplify.Auth.fetchAuthSession();
58
+ if (session.credentials === undefined) {
59
+ throw new Error(GraphQLAuthError.NO_CREDENTIALS);
60
+ }
61
+ break;
62
+ case 'oidc':
63
+ case 'userPool':
64
+ try {
65
+ let token;
66
+ token = (await amplify.Auth.fetchAuthSession()).tokens?.accessToken.toString();
67
+ if (!token) {
68
+ throw new Error(GraphQLAuthError.NO_FEDERATED_JWT);
69
+ }
70
+ headers = {
71
+ Authorization: token,
72
+ };
73
+ }
74
+ catch (e) {
75
+ throw new Error(GraphQLAuthError.NO_CURRENT_USER);
76
+ }
77
+ break;
78
+ case 'lambda':
79
+ if (!additionalHeaders.Authorization) {
80
+ throw new Error(GraphQLAuthError.NO_AUTH_TOKEN);
81
+ }
82
+ headers = {
83
+ Authorization: additionalHeaders.Authorization,
84
+ };
85
+ break;
86
+ case 'none':
87
+ break;
88
+ default:
89
+ break;
90
+ }
91
+ return headers;
92
+ }
174
93
  /**
175
94
  * to get the operation type
176
95
  * @param operation
177
96
  */
178
- InternalGraphQLAPIClass.prototype.getGraphqlOperationType = function (operation) {
179
- var doc = parse(operation);
180
- var definitions = doc.definitions;
181
- var _a = __read(definitions, 1), operationType = _a[0].operation;
97
+ getGraphqlOperationType(operation) {
98
+ const doc = parse(operation);
99
+ const definitions = doc.definitions;
100
+ const [{ operation: operationType }] = definitions;
182
101
  return operationType;
183
- };
102
+ }
184
103
  /**
185
104
  * Executes a GraphQL operation
186
105
  *
@@ -188,14 +107,13 @@ var InternalGraphQLAPIClass = /** @class */ (function () {
188
107
  * @param [additionalHeaders] - headers to merge in after any `graphql_headers` set in the config
189
108
  * @returns An Observable if the query is a subscription query, else a promise of the graphql result.
190
109
  */
191
- InternalGraphQLAPIClass.prototype.graphql = function (_a, additionalHeaders, customUserAgentDetails) {
192
- var paramQuery = _a.query, _b = _a.variables, variables = _b === void 0 ? {} : _b, authMode = _a.authMode, authToken = _a.authToken;
193
- var query = typeof paramQuery === 'string'
110
+ graphql(amplify, { query: paramQuery, variables = {}, authMode, authToken }, additionalHeaders, customUserAgentDetails) {
111
+ const query = typeof paramQuery === 'string'
194
112
  ? parse(paramQuery)
195
113
  : parse(print(paramQuery));
196
- var _c = __read(query.definitions.filter(function (def) { return def.kind === 'OperationDefinition'; }), 1), _d = _c[0], operationDef = _d === void 0 ? {} : _d;
197
- var operationType = operationDef.operation;
198
- var headers = additionalHeaders || {};
114
+ const [operationDef = {}] = query.definitions.filter(def => def.kind === 'OperationDefinition');
115
+ const { operation: operationType } = operationDef;
116
+ const headers = additionalHeaders || {};
199
117
  // if an authorization header is set, have the explicit authToken take precedence
200
118
  if (authToken) {
201
119
  headers.Authorization = authToken;
@@ -203,196 +121,151 @@ var InternalGraphQLAPIClass = /** @class */ (function () {
203
121
  switch (operationType) {
204
122
  case 'query':
205
123
  case 'mutation':
206
- this.createInstanceIfNotCreated();
207
- var cancellableToken = this._api.getCancellableToken();
208
- var initParams = {
209
- cancellableToken: cancellableToken,
210
- withCredentials: this._options.withCredentials,
211
- };
212
- var responsePromise = this._graphql({ query: query, variables: variables, authMode: authMode }, headers, initParams, customUserAgentDetails);
213
- this._api.updateRequestToBeCancellable(responsePromise, cancellableToken);
124
+ const abortController = new AbortController();
125
+ let responsePromise;
126
+ if (isAmplifyInstance(amplify)) {
127
+ responsePromise = this._graphql(amplify, { query, variables, authMode }, headers, abortController, customUserAgentDetails);
128
+ }
129
+ else {
130
+ const wrapper = amplifyInstance => this._graphql(amplifyInstance, { query, variables, authMode }, headers, abortController, customUserAgentDetails);
131
+ responsePromise = amplify(wrapper);
132
+ }
133
+ this._api.updateRequestToBeCancellable(responsePromise, abortController);
214
134
  return responsePromise;
215
135
  case 'subscription':
216
- return this._graphqlSubscribe({ query: query, variables: variables, authMode: authMode }, headers, customUserAgentDetails);
136
+ return this._graphqlSubscribe(amplify, { query, variables, authMode }, headers, customUserAgentDetails);
217
137
  default:
218
- throw new Error("invalid operation type: " + operationType);
138
+ throw new Error(`invalid operation type: ${operationType}`);
219
139
  }
220
- };
221
- InternalGraphQLAPIClass.prototype._graphql = function (_a, additionalHeaders, initParams, customUserAgentDetails) {
222
- var query = _a.query, variables = _a.variables, authMode = _a.authMode;
223
- if (additionalHeaders === void 0) { additionalHeaders = {}; }
224
- if (initParams === void 0) { initParams = {}; }
225
- return __awaiter(this, void 0, void 0, function () {
226
- var _b, region, appSyncGraphqlEndpoint, _c, graphql_headers, customGraphqlEndpoint, customEndpointRegion, headers, _d, _e, _f, _g, _h, _j, body, init, endpoint, error, response, err_1, errors;
227
- var _k;
228
- return __generator(this, function (_l) {
229
- switch (_l.label) {
230
- case 0:
231
- this.createInstanceIfNotCreated();
232
- _b = this._options, region = _b.aws_appsync_region, appSyncGraphqlEndpoint = _b.aws_appsync_graphqlEndpoint, _c = _b.graphql_headers, graphql_headers = _c === void 0 ? function () { return ({}); } : _c, customGraphqlEndpoint = _b.graphql_endpoint, customEndpointRegion = _b.graphql_endpoint_iam_region;
233
- _d = [{}];
234
- _e = !customGraphqlEndpoint;
235
- if (!_e) return [3 /*break*/, 2];
236
- return [4 /*yield*/, this._headerBasedAuth(authMode, additionalHeaders)];
237
- case 1:
238
- _e = (_l.sent());
239
- _l.label = 2;
240
- case 2:
241
- _f = [__assign.apply(void 0, _d.concat([(_e)]))];
242
- _g = customGraphqlEndpoint;
243
- if (!_g) return [3 /*break*/, 6];
244
- if (!customEndpointRegion) return [3 /*break*/, 4];
245
- return [4 /*yield*/, this._headerBasedAuth(authMode, additionalHeaders)];
246
- case 3:
247
- _h = _l.sent();
248
- return [3 /*break*/, 5];
249
- case 4:
250
- _h = { Authorization: null };
251
- _l.label = 5;
252
- case 5:
253
- _g = (_h);
254
- _l.label = 6;
255
- case 6:
256
- _j = [__assign.apply(void 0, _f.concat([(_g)]))];
257
- return [4 /*yield*/, graphql_headers({ query: query, variables: variables })];
258
- case 7:
259
- headers = __assign.apply(void 0, [__assign.apply(void 0, [__assign.apply(void 0, _j.concat([(_l.sent())])), additionalHeaders]), (!customGraphqlEndpoint && (_k = {},
260
- _k[USER_AGENT_HEADER] = getAmplifyUserAgent(customUserAgentDetails),
261
- _k))]);
262
- body = {
263
- query: print(query),
264
- variables: variables,
265
- };
266
- init = Object.assign({
267
- headers: headers,
268
- body: body,
269
- signerServiceInfo: {
270
- service: !customGraphqlEndpoint ? 'appsync' : 'execute-api',
271
- region: !customGraphqlEndpoint ? region : customEndpointRegion,
272
- },
273
- }, initParams);
274
- endpoint = customGraphqlEndpoint || appSyncGraphqlEndpoint;
275
- if (!endpoint) {
276
- error = new GraphQLError('No graphql endpoint provided.');
277
- throw {
278
- data: {},
279
- errors: [error],
280
- };
281
- }
282
- _l.label = 8;
283
- case 8:
284
- _l.trys.push([8, 10, , 11]);
285
- return [4 /*yield*/, this._api.post(endpoint, init)];
286
- case 9:
287
- response = _l.sent();
288
- return [3 /*break*/, 11];
289
- case 10:
290
- err_1 = _l.sent();
291
- // If the exception is because user intentionally
292
- // cancelled the request, do not modify the exception
293
- // so that clients can identify the exception correctly.
294
- if (this._api.isCancel(err_1)) {
295
- throw err_1;
296
- }
297
- response = {
298
- data: {},
299
- errors: [new GraphQLError(err_1.message, null, null, null, null, err_1)],
300
- };
301
- return [3 /*break*/, 11];
302
- case 11:
303
- errors = response.errors;
304
- if (errors && errors.length) {
305
- throw response;
306
- }
307
- return [2 /*return*/, response];
308
- }
309
- });
310
- });
311
- };
312
- InternalGraphQLAPIClass.prototype.createInstanceIfNotCreated = function () {
313
- return __awaiter(this, void 0, void 0, function () {
314
- return __generator(this, function (_a) {
315
- switch (_a.label) {
316
- case 0:
317
- if (!!this._api) return [3 /*break*/, 2];
318
- return [4 /*yield*/, this.createInstance()];
319
- case 1:
320
- _a.sent();
321
- _a.label = 2;
322
- case 2: return [2 /*return*/];
323
- }
140
+ }
141
+ async _graphql(amplify, { query, variables, authMode }, additionalHeaders = {}, abortController, customUserAgentDetails) {
142
+ const { region: region, endpoint: appSyncGraphqlEndpoint, customEndpoint, customEndpointRegion, } = resolveConfig(amplify);
143
+ // Retrieve library options from Amplify configuration
144
+ const { headers: customHeaders, withCredentials } = resolveLibraryOptions(amplify);
145
+ // TODO: Figure what we need to do to remove `!`'s.
146
+ const headers = {
147
+ ...(!customEndpoint &&
148
+ (await this._headerBasedAuth(amplify, authMode, additionalHeaders))),
149
+ /**
150
+ * Custom endpoint headers.
151
+ * If there is both a custom endpoint and custom region present, we get the headers.
152
+ * If there is a custom endpoint but no region, we return an empty object.
153
+ * If neither are present, we return an empty object.
154
+ */
155
+ ...((customEndpoint &&
156
+ (customEndpointRegion
157
+ ? await this._headerBasedAuth(amplify, authMode, additionalHeaders)
158
+ : {})) ||
159
+ {}),
160
+ // Custom headers included in Amplify configuration options:
161
+ ...(customHeaders &&
162
+ (await customHeaders({
163
+ query: print(query),
164
+ variables,
165
+ }))),
166
+ // Headers from individual calls to `graphql`:
167
+ ...additionalHeaders,
168
+ // User agent headers:
169
+ ...(!customEndpoint && {
170
+ [USER_AGENT_HEADER]: getAmplifyUserAgent(customUserAgentDetails),
171
+ }),
172
+ };
173
+ const body = {
174
+ query: print(query),
175
+ variables: variables || null,
176
+ };
177
+ let signingServiceInfo;
178
+ /**
179
+ * We do not send the signing service info to the REST API under the
180
+ * following conditions (i.e. it will not sign the request):
181
+ * - there is a custom endpoint but no region
182
+ * - the auth mode is `none`, or `apiKey`
183
+ * - the auth mode is a type other than the types listed below
184
+ */
185
+ if ((customEndpoint && !customEndpointRegion) ||
186
+ (authMode !== 'oidc' &&
187
+ authMode !== 'userPool' &&
188
+ authMode !== 'iam' &&
189
+ authMode !== 'lambda')) {
190
+ signingServiceInfo = null;
191
+ }
192
+ else {
193
+ signingServiceInfo = {
194
+ service: !customEndpointRegion ? 'appsync' : 'execute-api',
195
+ region: !customEndpointRegion ? region : customEndpointRegion,
196
+ };
197
+ }
198
+ const endpoint = customEndpoint || appSyncGraphqlEndpoint;
199
+ if (!endpoint) {
200
+ const error = new GraphQLError('No graphql endpoint provided.');
201
+ throw {
202
+ data: {},
203
+ errors: [error],
204
+ };
205
+ }
206
+ let response;
207
+ try {
208
+ const { body: responseBody } = await this._api.post({
209
+ url: new AmplifyUrl(endpoint),
210
+ options: {
211
+ headers,
212
+ body,
213
+ signingServiceInfo,
214
+ withCredentials,
215
+ },
216
+ abortController,
324
217
  });
325
- });
326
- };
218
+ const result = await responseBody.json();
219
+ response = result;
220
+ }
221
+ catch (err) {
222
+ // If the exception is because user intentionally
223
+ // cancelled the request, do not modify the exception
224
+ // so that clients can identify the exception correctly.
225
+ if (this.isCancelError(err)) {
226
+ throw err;
227
+ }
228
+ response = {
229
+ data: {},
230
+ errors: [new GraphQLError(err.message, null, null, null, null, err)],
231
+ };
232
+ }
233
+ const { errors } = response;
234
+ if (errors && errors.length) {
235
+ throw response;
236
+ }
237
+ return response;
238
+ }
327
239
  /**
328
240
  * Checks to see if an error thrown is from an api request cancellation
329
241
  * @param {any} error - Any error
330
242
  * @return {boolean} - A boolean indicating if the error was from an api request cancellation
331
243
  */
332
- InternalGraphQLAPIClass.prototype.isCancel = function (error) {
333
- return this._api.isCancel(error);
334
- };
244
+ isCancelError(error) {
245
+ return this._api.isCancelErrorREST(error);
246
+ }
335
247
  /**
336
248
  * Cancels an inflight request. Only applicable for graphql queries and mutations
337
249
  * @param {any} request - request to cancel
338
- * @return {boolean} - A boolean indicating if the request was cancelled
250
+ * @returns - A boolean indicating if the request was cancelled
339
251
  */
340
- InternalGraphQLAPIClass.prototype.cancel = function (request, message) {
341
- return this._api.cancel(request, message);
342
- };
343
- /**
344
- * Check if the request has a corresponding cancel token in the WeakMap.
345
- * @params request - The request promise
346
- * @return if the request has a corresponding cancel token.
347
- */
348
- InternalGraphQLAPIClass.prototype.hasCancelToken = function (request) {
349
- return this._api.hasCancelToken(request);
350
- };
351
- InternalGraphQLAPIClass.prototype._graphqlSubscribe = function (_a, additionalHeaders, customUserAgentDetails) {
352
- var query = _a.query, variables = _a.variables, defaultAuthenticationType = _a.authMode, authToken = _a.authToken;
353
- if (additionalHeaders === void 0) { additionalHeaders = {}; }
354
- var _b = this._options, region = _b.aws_appsync_region, appSyncGraphqlEndpoint = _b.aws_appsync_graphqlEndpoint, aws_appsync_authenticationType = _b.aws_appsync_authenticationType, apiKey = _b.aws_appsync_apiKey, _c = _b.graphql_headers, graphql_headers = _c === void 0 ? function () { return ({}); } : _c;
355
- var authenticationType = defaultAuthenticationType || aws_appsync_authenticationType || 'AWS_IAM';
356
- if (InternalPubSub && typeof InternalPubSub.subscribe === 'function') {
357
- return InternalPubSub.subscribe('', {
358
- provider: INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER,
359
- appSyncGraphqlEndpoint: appSyncGraphqlEndpoint,
360
- authenticationType: authenticationType,
361
- apiKey: apiKey,
362
- query: print(query),
363
- region: region,
364
- variables: variables,
365
- graphql_headers: graphql_headers,
366
- additionalHeaders: additionalHeaders,
367
- authToken: authToken,
368
- }, customUserAgentDetails);
369
- }
370
- else {
371
- logger.debug('No pubsub module applied for subscription');
372
- throw new Error('No pubsub module applied for subscription');
252
+ cancel(request, message) {
253
+ return this._api.cancelREST(request, message);
254
+ }
255
+ _graphqlSubscribe(amplify, { query, variables, authMode }, additionalHeaders = {}, customUserAgentDetails) {
256
+ const config = resolveConfig(amplify);
257
+ if (!this.appSyncRealTime) {
258
+ this.appSyncRealTime = new AWSAppSyncRealTimeProvider();
373
259
  }
374
- };
375
- /**
376
- * @private
377
- */
378
- InternalGraphQLAPIClass.prototype._ensureCredentials = function () {
379
- var _this = this;
380
- return this.Credentials.get()
381
- .then(function (credentials) {
382
- if (!credentials)
383
- return false;
384
- var cred = _this.Credentials.shear(credentials);
385
- logger.debug('set credentials for api', cred);
386
- return true;
387
- })
388
- .catch(function (err) {
389
- logger.warn('ensure credentials error', err);
390
- return false;
391
- });
392
- };
393
- return InternalGraphQLAPIClass;
394
- }());
395
- export { InternalGraphQLAPIClass };
396
- export var InternalGraphQLAPI = new InternalGraphQLAPIClass(null);
397
- Amplify.register(InternalGraphQLAPI);
398
- //# sourceMappingURL=InternalGraphQLAPI.js.map
260
+ return this.appSyncRealTime.subscribe({
261
+ query: print(query),
262
+ variables,
263
+ appSyncGraphqlEndpoint: config?.endpoint,
264
+ region: config?.region,
265
+ authenticationType: authMode ?? config?.defaultAuthMode,
266
+ apiKey: config?.apiKey,
267
+ additionalHeaders,
268
+ }, customUserAgentDetails);
269
+ }
270
+ }
271
+ export const InternalGraphQLAPI = new InternalGraphQLAPIClass(null);
@@ -1,2 +1,2 @@
1
1
  export { InternalGraphQLAPI, InternalGraphQLAPIClass, } from './InternalGraphQLAPI';
2
- export { graphql } from './v6';
2
+ export { graphql, cancel, isCancelError } from './v6';
@@ -1,5 +1,4 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  export { InternalGraphQLAPI, InternalGraphQLAPIClass, } from './InternalGraphQLAPI';
4
- export { graphql } from './v6';
5
- //# sourceMappingURL=index.js.map
4
+ export { graphql, cancel, isCancelError } from './v6';