@apollo/client 3.6.3 → 3.6.4

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 (58) hide show
  1. package/apollo-client.cjs +74 -14
  2. package/apollo-client.cjs.map +1 -1
  3. package/apollo-client.min.cjs +1 -1
  4. package/cache/cache.cjs.native.js +2289 -0
  5. package/core/core.cjs +1 -1
  6. package/core/core.cjs.map +1 -1
  7. package/core/core.cjs.native.js +2141 -0
  8. package/errors/errors.cjs.native.js +48 -0
  9. package/invariantErrorCodes.js +1 -1
  10. package/link/batch/batch.cjs.native.js +161 -0
  11. package/link/batch-http/batch-http.cjs.native.js +127 -0
  12. package/link/context/context.cjs.native.js +38 -0
  13. package/link/core/core.cjs.native.js +121 -0
  14. package/link/error/error.cjs.native.js +90 -0
  15. package/link/http/http.cjs.native.js +320 -0
  16. package/link/persisted-queries/persisted-queries.cjs.native.js +174 -0
  17. package/link/retry/retry.cjs.native.js +170 -0
  18. package/link/schema/schema.cjs.native.js +56 -0
  19. package/link/subscriptions/subscriptions.cjs.native.js +45 -0
  20. package/link/utils/utils.cjs.native.js +115 -0
  21. package/link/ws/ws.cjs.native.js +28 -0
  22. package/main.cjs.native.js +16 -0
  23. package/package.json +13 -14
  24. package/react/components/components.cjs.native.js +79 -0
  25. package/react/context/context.cjs.native.js +67 -0
  26. package/react/hoc/hoc.cjs.native.js +325 -0
  27. package/react/hooks/hooks.cjs +99 -31
  28. package/react/hooks/hooks.cjs.map +1 -1
  29. package/react/hooks/hooks.cjs.native.js +604 -0
  30. package/react/hooks/useQuery.js +1 -1
  31. package/react/hooks/useQuery.js.map +1 -1
  32. package/react/hooks/useSubscription.d.ts.map +1 -1
  33. package/react/hooks/useSubscription.js +17 -7
  34. package/react/hooks/useSubscription.js.map +1 -1
  35. package/react/hooks/useSyncExternalStore.d.ts +4 -0
  36. package/react/hooks/useSyncExternalStore.d.ts.map +1 -0
  37. package/react/hooks/useSyncExternalStore.js +48 -0
  38. package/react/hooks/useSyncExternalStore.js.map +1 -0
  39. package/react/parser/parser.cjs.native.js +103 -0
  40. package/react/react.cjs.native.js +22 -0
  41. package/react/ssr/ssr.cjs.native.js +150 -0
  42. package/testing/core/core.cjs.native.js +288 -0
  43. package/testing/testing.cjs.native.js +58 -0
  44. package/utilities/common/canUse.d.ts +2 -0
  45. package/utilities/common/canUse.d.ts.map +1 -1
  46. package/utilities/common/canUse.js +6 -2
  47. package/utilities/common/canUse.js.map +1 -1
  48. package/utilities/globals/globals.cjs.native.js +56 -0
  49. package/utilities/observables/Concast.d.ts.map +1 -1
  50. package/utilities/observables/Concast.js +5 -2
  51. package/utilities/observables/Concast.js.map +1 -1
  52. package/utilities/policies/pagination.d.ts.map +1 -1
  53. package/utilities/policies/pagination.js +9 -7
  54. package/utilities/policies/pagination.js.map +1 -1
  55. package/utilities/utilities.cjs +21 -11
  56. package/utilities/utilities.cjs.map +1 -1
  57. package/utilities/utilities.cjs.native.js +1284 -0
  58. package/version.js +1 -1
@@ -0,0 +1,320 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var globals = require('../../utilities/globals');
6
+ var utils = require('../utils');
7
+ var tslib = require('tslib');
8
+ var graphql = require('graphql');
9
+ var core = require('../core');
10
+ var utilities = require('../../utilities');
11
+
12
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
13
+ function parseAndCheckHttpResponse(operations) {
14
+ return function (response) { return response
15
+ .text()
16
+ .then(function (bodyText) {
17
+ try {
18
+ return JSON.parse(bodyText);
19
+ }
20
+ catch (err) {
21
+ var parseError = err;
22
+ parseError.name = 'ServerParseError';
23
+ parseError.response = response;
24
+ parseError.statusCode = response.status;
25
+ parseError.bodyText = bodyText;
26
+ throw parseError;
27
+ }
28
+ })
29
+ .then(function (result) {
30
+ if (response.status >= 300) {
31
+ utils.throwServerError(response, result, "Response not successful: Received status code ".concat(response.status));
32
+ }
33
+ if (!Array.isArray(result) &&
34
+ !hasOwnProperty.call(result, 'data') &&
35
+ !hasOwnProperty.call(result, 'errors')) {
36
+ utils.throwServerError(response, result, "Server response was missing for query '".concat(Array.isArray(operations)
37
+ ? operations.map(function (op) { return op.operationName; })
38
+ : operations.operationName, "'."));
39
+ }
40
+ return result;
41
+ }); };
42
+ }
43
+
44
+ var serializeFetchParameter = function (p, label) {
45
+ var serialized;
46
+ try {
47
+ serialized = JSON.stringify(p);
48
+ }
49
+ catch (e) {
50
+ var parseError = __DEV__ ? new globals.InvariantError("Network request failed. ".concat(label, " is not serializable: ").concat(e.message)) : new globals.InvariantError(21);
51
+ parseError.parseError = e;
52
+ throw parseError;
53
+ }
54
+ return serialized;
55
+ };
56
+
57
+ var defaultHttpOptions = {
58
+ includeQuery: true,
59
+ includeExtensions: false,
60
+ };
61
+ var defaultHeaders = {
62
+ accept: '*/*',
63
+ 'content-type': 'application/json',
64
+ };
65
+ var defaultOptions = {
66
+ method: 'POST',
67
+ };
68
+ var fallbackHttpConfig = {
69
+ http: defaultHttpOptions,
70
+ headers: defaultHeaders,
71
+ options: defaultOptions,
72
+ };
73
+ var defaultPrinter = function (ast, printer) { return printer(ast); };
74
+ function selectHttpOptionsAndBody(operation, fallbackConfig) {
75
+ var configs = [];
76
+ for (var _i = 2; _i < arguments.length; _i++) {
77
+ configs[_i - 2] = arguments[_i];
78
+ }
79
+ configs.unshift(fallbackConfig);
80
+ return selectHttpOptionsAndBodyInternal.apply(void 0, tslib.__spreadArray([operation,
81
+ defaultPrinter], configs, false));
82
+ }
83
+ function selectHttpOptionsAndBodyInternal(operation, printer) {
84
+ var configs = [];
85
+ for (var _i = 2; _i < arguments.length; _i++) {
86
+ configs[_i - 2] = arguments[_i];
87
+ }
88
+ var options = {};
89
+ var http = {};
90
+ configs.forEach(function (config) {
91
+ options = tslib.__assign(tslib.__assign(tslib.__assign({}, options), config.options), { headers: tslib.__assign(tslib.__assign({}, options.headers), headersToLowerCase(config.headers)) });
92
+ if (config.credentials) {
93
+ options.credentials = config.credentials;
94
+ }
95
+ http = tslib.__assign(tslib.__assign({}, http), config.http);
96
+ });
97
+ var operationName = operation.operationName, extensions = operation.extensions, variables = operation.variables, query = operation.query;
98
+ var body = { operationName: operationName, variables: variables };
99
+ if (http.includeExtensions)
100
+ body.extensions = extensions;
101
+ if (http.includeQuery)
102
+ body.query = printer(query, graphql.print);
103
+ return {
104
+ options: options,
105
+ body: body,
106
+ };
107
+ }
108
+ function headersToLowerCase(headers) {
109
+ if (headers) {
110
+ var normalized_1 = Object.create(null);
111
+ Object.keys(Object(headers)).forEach(function (name) {
112
+ normalized_1[name.toLowerCase()] = headers[name];
113
+ });
114
+ return normalized_1;
115
+ }
116
+ return headers;
117
+ }
118
+
119
+ var checkFetcher = function (fetcher) {
120
+ if (!fetcher && typeof fetch === 'undefined') {
121
+ throw __DEV__ ? new globals.InvariantError("\n\"fetch\" has not been found globally and no fetcher has been configured. To fix this, install a fetch package (like https://www.npmjs.com/package/cross-fetch), instantiate the fetcher, and pass it into your HttpLink constructor. For example:\n\nimport fetch from 'cross-fetch';\nimport { ApolloClient, HttpLink } from '@apollo/client';\nconst client = new ApolloClient({\n link: new HttpLink({ uri: '/graphql', fetch })\n});\n ") : new globals.InvariantError(20);
122
+ }
123
+ };
124
+
125
+ var createSignalIfSupported = function () {
126
+ if (typeof AbortController === 'undefined')
127
+ return { controller: false, signal: false };
128
+ var controller = new AbortController();
129
+ var signal = controller.signal;
130
+ return { controller: controller, signal: signal };
131
+ };
132
+
133
+ var selectURI = function (operation, fallbackURI) {
134
+ var context = operation.getContext();
135
+ var contextURI = context.uri;
136
+ if (contextURI) {
137
+ return contextURI;
138
+ }
139
+ else if (typeof fallbackURI === 'function') {
140
+ return fallbackURI(operation);
141
+ }
142
+ else {
143
+ return fallbackURI || '/graphql';
144
+ }
145
+ };
146
+
147
+ function rewriteURIForGET(chosenURI, body) {
148
+ var queryParams = [];
149
+ var addQueryParam = function (key, value) {
150
+ queryParams.push("".concat(key, "=").concat(encodeURIComponent(value)));
151
+ };
152
+ if ('query' in body) {
153
+ addQueryParam('query', body.query);
154
+ }
155
+ if (body.operationName) {
156
+ addQueryParam('operationName', body.operationName);
157
+ }
158
+ if (body.variables) {
159
+ var serializedVariables = void 0;
160
+ try {
161
+ serializedVariables = serializeFetchParameter(body.variables, 'Variables map');
162
+ }
163
+ catch (parseError) {
164
+ return { parseError: parseError };
165
+ }
166
+ addQueryParam('variables', serializedVariables);
167
+ }
168
+ if (body.extensions) {
169
+ var serializedExtensions = void 0;
170
+ try {
171
+ serializedExtensions = serializeFetchParameter(body.extensions, 'Extensions map');
172
+ }
173
+ catch (parseError) {
174
+ return { parseError: parseError };
175
+ }
176
+ addQueryParam('extensions', serializedExtensions);
177
+ }
178
+ var fragment = '', preFragment = chosenURI;
179
+ var fragmentStart = chosenURI.indexOf('#');
180
+ if (fragmentStart !== -1) {
181
+ fragment = chosenURI.substr(fragmentStart);
182
+ preFragment = chosenURI.substr(0, fragmentStart);
183
+ }
184
+ var queryParamsPrefix = preFragment.indexOf('?') === -1 ? '?' : '&';
185
+ var newURI = preFragment + queryParamsPrefix + queryParams.join('&') + fragment;
186
+ return { newURI: newURI };
187
+ }
188
+
189
+ var backupFetch = utilities.maybe(function () { return fetch; });
190
+ var createHttpLink = function (linkOptions) {
191
+ if (linkOptions === void 0) { linkOptions = {}; }
192
+ var _a = linkOptions.uri, uri = _a === void 0 ? '/graphql' : _a, preferredFetch = linkOptions.fetch, _b = linkOptions.print, print = _b === void 0 ? defaultPrinter : _b, includeExtensions = linkOptions.includeExtensions, useGETForQueries = linkOptions.useGETForQueries, _c = linkOptions.includeUnusedVariables, includeUnusedVariables = _c === void 0 ? false : _c, requestOptions = tslib.__rest(linkOptions, ["uri", "fetch", "print", "includeExtensions", "useGETForQueries", "includeUnusedVariables"]);
193
+ if (__DEV__) {
194
+ checkFetcher(preferredFetch || backupFetch);
195
+ }
196
+ var linkConfig = {
197
+ http: { includeExtensions: includeExtensions },
198
+ options: requestOptions.fetchOptions,
199
+ credentials: requestOptions.credentials,
200
+ headers: requestOptions.headers,
201
+ };
202
+ return new core.ApolloLink(function (operation) {
203
+ var chosenURI = selectURI(operation, uri);
204
+ var context = operation.getContext();
205
+ var clientAwarenessHeaders = {};
206
+ if (context.clientAwareness) {
207
+ var _a = context.clientAwareness, name_1 = _a.name, version = _a.version;
208
+ if (name_1) {
209
+ clientAwarenessHeaders['apollographql-client-name'] = name_1;
210
+ }
211
+ if (version) {
212
+ clientAwarenessHeaders['apollographql-client-version'] = version;
213
+ }
214
+ }
215
+ var contextHeaders = tslib.__assign(tslib.__assign({}, clientAwarenessHeaders), context.headers);
216
+ var contextConfig = {
217
+ http: context.http,
218
+ options: context.fetchOptions,
219
+ credentials: context.credentials,
220
+ headers: contextHeaders,
221
+ };
222
+ var _b = selectHttpOptionsAndBodyInternal(operation, print, fallbackHttpConfig, linkConfig, contextConfig), options = _b.options, body = _b.body;
223
+ if (body.variables && !includeUnusedVariables) {
224
+ var unusedNames_1 = new Set(Object.keys(body.variables));
225
+ graphql.visit(operation.query, {
226
+ Variable: function (node, _key, parent) {
227
+ if (parent && parent.kind !== 'VariableDefinition') {
228
+ unusedNames_1.delete(node.name.value);
229
+ }
230
+ },
231
+ });
232
+ if (unusedNames_1.size) {
233
+ body.variables = tslib.__assign({}, body.variables);
234
+ unusedNames_1.forEach(function (name) {
235
+ delete body.variables[name];
236
+ });
237
+ }
238
+ }
239
+ var controller;
240
+ if (!options.signal) {
241
+ var _c = createSignalIfSupported(), _controller = _c.controller, signal = _c.signal;
242
+ controller = _controller;
243
+ if (controller)
244
+ options.signal = signal;
245
+ }
246
+ var definitionIsMutation = function (d) {
247
+ return d.kind === 'OperationDefinition' && d.operation === 'mutation';
248
+ };
249
+ if (useGETForQueries &&
250
+ !operation.query.definitions.some(definitionIsMutation)) {
251
+ options.method = 'GET';
252
+ }
253
+ if (options.method === 'GET') {
254
+ var _d = rewriteURIForGET(chosenURI, body), newURI = _d.newURI, parseError = _d.parseError;
255
+ if (parseError) {
256
+ return utils.fromError(parseError);
257
+ }
258
+ chosenURI = newURI;
259
+ }
260
+ else {
261
+ try {
262
+ options.body = serializeFetchParameter(body, 'Payload');
263
+ }
264
+ catch (parseError) {
265
+ return utils.fromError(parseError);
266
+ }
267
+ }
268
+ return new utilities.Observable(function (observer) {
269
+ var currentFetch = preferredFetch || utilities.maybe(function () { return fetch; }) || backupFetch;
270
+ currentFetch(chosenURI, options)
271
+ .then(function (response) {
272
+ operation.setContext({ response: response });
273
+ return response;
274
+ })
275
+ .then(parseAndCheckHttpResponse(operation))
276
+ .then(function (result) {
277
+ observer.next(result);
278
+ observer.complete();
279
+ return result;
280
+ })
281
+ .catch(function (err) {
282
+ if (err.name === 'AbortError')
283
+ return;
284
+ if (err.result && err.result.errors && err.result.data) {
285
+ observer.next(err.result);
286
+ }
287
+ observer.error(err);
288
+ });
289
+ return function () {
290
+ if (controller)
291
+ controller.abort();
292
+ };
293
+ });
294
+ });
295
+ };
296
+
297
+ var HttpLink = (function (_super) {
298
+ tslib.__extends(HttpLink, _super);
299
+ function HttpLink(options) {
300
+ if (options === void 0) { options = {}; }
301
+ var _this = _super.call(this, createHttpLink(options).request) || this;
302
+ _this.options = options;
303
+ return _this;
304
+ }
305
+ return HttpLink;
306
+ }(core.ApolloLink));
307
+
308
+ exports.HttpLink = HttpLink;
309
+ exports.checkFetcher = checkFetcher;
310
+ exports.createHttpLink = createHttpLink;
311
+ exports.createSignalIfSupported = createSignalIfSupported;
312
+ exports.defaultPrinter = defaultPrinter;
313
+ exports.fallbackHttpConfig = fallbackHttpConfig;
314
+ exports.parseAndCheckHttpResponse = parseAndCheckHttpResponse;
315
+ exports.rewriteURIForGET = rewriteURIForGET;
316
+ exports.selectHttpOptionsAndBody = selectHttpOptionsAndBody;
317
+ exports.selectHttpOptionsAndBodyInternal = selectHttpOptionsAndBodyInternal;
318
+ exports.selectURI = selectURI;
319
+ exports.serializeFetchParameter = serializeFetchParameter;
320
+ //# sourceMappingURL=http.cjs.map
@@ -0,0 +1,174 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var tslib = require('tslib');
6
+ var globals = require('../../utilities/globals');
7
+ var graphql = require('graphql');
8
+ var core = require('../core');
9
+ var utilities = require('../../utilities');
10
+
11
+ var VERSION = 1;
12
+ exports.PersistedQueryLink = void 0;
13
+ (function (PersistedQueryLink) {
14
+ })(exports.PersistedQueryLink || (exports.PersistedQueryLink = {}));
15
+ function collectErrorsByMessage(graphQLErrors) {
16
+ var collected = Object.create(null);
17
+ if (utilities.isNonEmptyArray(graphQLErrors)) {
18
+ graphQLErrors.forEach(function (error) { return collected[error.message] = error; });
19
+ }
20
+ return collected;
21
+ }
22
+ var defaultOptions = {
23
+ disable: function (_a) {
24
+ var graphQLErrors = _a.graphQLErrors, operation = _a.operation;
25
+ var errorMessages = collectErrorsByMessage(graphQLErrors);
26
+ if (errorMessages.PersistedQueryNotSupported) {
27
+ return true;
28
+ }
29
+ if (errorMessages.PersistedQueryNotFound) {
30
+ return false;
31
+ }
32
+ var response = operation.getContext().response;
33
+ if (response &&
34
+ response.status &&
35
+ (response.status === 400 || response.status === 500)) {
36
+ return true;
37
+ }
38
+ return false;
39
+ },
40
+ useGETForHashedQueries: false,
41
+ };
42
+ function operationDefinesMutation(operation) {
43
+ return operation.query.definitions.some(function (d) { return d.kind === 'OperationDefinition' && d.operation === 'mutation'; });
44
+ }
45
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
46
+ var hashesByQuery = new WeakMap();
47
+ var nextHashesChildKey = 0;
48
+ var createPersistedQueryLink = function (options) {
49
+ __DEV__ ? globals.invariant(options && (typeof options.sha256 === 'function' ||
50
+ typeof options.generateHash === 'function'), 'Missing/invalid "sha256" or "generateHash" function. Please ' +
51
+ 'configure one using the "createPersistedQueryLink(options)" options ' +
52
+ 'parameter.') : globals.invariant(options && (typeof options.sha256 === 'function' ||
53
+ typeof options.generateHash === 'function'), 22);
54
+ var _a = utilities.compact(defaultOptions, options), sha256 = _a.sha256, _b = _a.generateHash, generateHash = _b === void 0 ? function (query) {
55
+ return Promise.resolve(sha256(graphql.print(query)));
56
+ } : _b, disable = _a.disable, useGETForHashedQueries = _a.useGETForHashedQueries;
57
+ var supportsPersistedQueries = true;
58
+ var hashesChildKey = 'forLink' + nextHashesChildKey++;
59
+ var getHashPromise = function (query) {
60
+ return new Promise(function (resolve) { return resolve(generateHash(query)); });
61
+ };
62
+ function getQueryHash(query) {
63
+ if (!query || typeof query !== 'object') {
64
+ return getHashPromise(query);
65
+ }
66
+ var hashes = hashesByQuery.get(query);
67
+ if (!hashes)
68
+ hashesByQuery.set(query, hashes = Object.create(null));
69
+ return hasOwnProperty.call(hashes, hashesChildKey)
70
+ ? hashes[hashesChildKey]
71
+ : hashes[hashesChildKey] = getHashPromise(query);
72
+ }
73
+ return new core.ApolloLink(function (operation, forward) {
74
+ __DEV__ ? globals.invariant(forward, 'PersistedQueryLink cannot be the last link in the chain.') : globals.invariant(forward, 23);
75
+ var query = operation.query;
76
+ return new utilities.Observable(function (observer) {
77
+ var subscription;
78
+ var retried = false;
79
+ var originalFetchOptions;
80
+ var setFetchOptions = false;
81
+ var retry = function (_a, cb) {
82
+ var response = _a.response, networkError = _a.networkError;
83
+ if (!retried && ((response && response.errors) || networkError)) {
84
+ retried = true;
85
+ var graphQLErrors = [];
86
+ var responseErrors = response && response.errors;
87
+ if (utilities.isNonEmptyArray(responseErrors)) {
88
+ graphQLErrors.push.apply(graphQLErrors, responseErrors);
89
+ }
90
+ var networkErrors = networkError &&
91
+ networkError.result &&
92
+ networkError.result.errors;
93
+ if (utilities.isNonEmptyArray(networkErrors)) {
94
+ graphQLErrors.push.apply(graphQLErrors, networkErrors);
95
+ }
96
+ var disablePayload = {
97
+ response: response,
98
+ networkError: networkError,
99
+ operation: operation,
100
+ graphQLErrors: utilities.isNonEmptyArray(graphQLErrors) ? graphQLErrors : void 0,
101
+ };
102
+ supportsPersistedQueries = !disable(disablePayload);
103
+ if (collectErrorsByMessage(graphQLErrors).PersistedQueryNotFound ||
104
+ !supportsPersistedQueries) {
105
+ if (subscription)
106
+ subscription.unsubscribe();
107
+ operation.setContext({
108
+ http: {
109
+ includeQuery: true,
110
+ includeExtensions: supportsPersistedQueries,
111
+ },
112
+ fetchOptions: {
113
+ method: 'POST',
114
+ },
115
+ });
116
+ if (setFetchOptions) {
117
+ operation.setContext({ fetchOptions: originalFetchOptions });
118
+ }
119
+ subscription = forward(operation).subscribe(handler);
120
+ return;
121
+ }
122
+ }
123
+ cb();
124
+ };
125
+ var handler = {
126
+ next: function (response) {
127
+ retry({ response: response }, function () { return observer.next(response); });
128
+ },
129
+ error: function (networkError) {
130
+ retry({ networkError: networkError }, function () { return observer.error(networkError); });
131
+ },
132
+ complete: observer.complete.bind(observer),
133
+ };
134
+ operation.setContext({
135
+ http: {
136
+ includeQuery: !supportsPersistedQueries,
137
+ includeExtensions: supportsPersistedQueries,
138
+ },
139
+ });
140
+ if (useGETForHashedQueries &&
141
+ supportsPersistedQueries &&
142
+ !operationDefinesMutation(operation)) {
143
+ operation.setContext(function (_a) {
144
+ var _b = _a.fetchOptions, fetchOptions = _b === void 0 ? {} : _b;
145
+ originalFetchOptions = fetchOptions;
146
+ return {
147
+ fetchOptions: tslib.__assign(tslib.__assign({}, fetchOptions), { method: 'GET' }),
148
+ };
149
+ });
150
+ setFetchOptions = true;
151
+ }
152
+ if (supportsPersistedQueries) {
153
+ getQueryHash(query).then(function (sha256Hash) {
154
+ operation.extensions.persistedQuery = {
155
+ version: VERSION,
156
+ sha256Hash: sha256Hash,
157
+ };
158
+ subscription = forward(operation).subscribe(handler);
159
+ }).catch(observer.error.bind(observer));
160
+ }
161
+ else {
162
+ subscription = forward(operation).subscribe(handler);
163
+ }
164
+ return function () {
165
+ if (subscription)
166
+ subscription.unsubscribe();
167
+ };
168
+ });
169
+ });
170
+ };
171
+
172
+ exports.VERSION = VERSION;
173
+ exports.createPersistedQueryLink = createPersistedQueryLink;
174
+ //# sourceMappingURL=persisted-queries.cjs.map
@@ -0,0 +1,170 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var tslib = require('tslib');
6
+ var core = require('../core');
7
+ var utilities = require('../../utilities');
8
+
9
+ function buildDelayFunction(delayOptions) {
10
+ var _a = delayOptions || {}, _b = _a.initial, initial = _b === void 0 ? 300 : _b, _c = _a.jitter, jitter = _c === void 0 ? true : _c, _d = _a.max, max = _d === void 0 ? Infinity : _d;
11
+ var baseDelay = jitter ? initial : initial / 2;
12
+ return function delayFunction(count) {
13
+ var delay = Math.min(max, baseDelay * Math.pow(2, count));
14
+ if (jitter) {
15
+ delay = Math.random() * delay;
16
+ }
17
+ return delay;
18
+ };
19
+ }
20
+
21
+ function buildRetryFunction(retryOptions) {
22
+ var _a = retryOptions || {}, retryIf = _a.retryIf, _b = _a.max, max = _b === void 0 ? 5 : _b;
23
+ return function retryFunction(count, operation, error) {
24
+ if (count >= max)
25
+ return false;
26
+ return retryIf ? retryIf(error, operation) : !!error;
27
+ };
28
+ }
29
+
30
+ var RetryableOperation = (function () {
31
+ function RetryableOperation(operation, nextLink, delayFor, retryIf) {
32
+ var _this = this;
33
+ this.operation = operation;
34
+ this.nextLink = nextLink;
35
+ this.delayFor = delayFor;
36
+ this.retryIf = retryIf;
37
+ this.retryCount = 0;
38
+ this.values = [];
39
+ this.complete = false;
40
+ this.canceled = false;
41
+ this.observers = [];
42
+ this.currentSubscription = null;
43
+ this.onNext = function (value) {
44
+ _this.values.push(value);
45
+ for (var _i = 0, _a = _this.observers; _i < _a.length; _i++) {
46
+ var observer = _a[_i];
47
+ if (!observer)
48
+ continue;
49
+ observer.next(value);
50
+ }
51
+ };
52
+ this.onComplete = function () {
53
+ _this.complete = true;
54
+ for (var _i = 0, _a = _this.observers; _i < _a.length; _i++) {
55
+ var observer = _a[_i];
56
+ if (!observer)
57
+ continue;
58
+ observer.complete();
59
+ }
60
+ };
61
+ this.onError = function (error) { return tslib.__awaiter(_this, void 0, void 0, function () {
62
+ var shouldRetry, _i, _a, observer;
63
+ return tslib.__generator(this, function (_b) {
64
+ switch (_b.label) {
65
+ case 0:
66
+ this.retryCount += 1;
67
+ return [4, this.retryIf(this.retryCount, this.operation, error)];
68
+ case 1:
69
+ shouldRetry = _b.sent();
70
+ if (shouldRetry) {
71
+ this.scheduleRetry(this.delayFor(this.retryCount, this.operation, error));
72
+ return [2];
73
+ }
74
+ this.error = error;
75
+ for (_i = 0, _a = this.observers; _i < _a.length; _i++) {
76
+ observer = _a[_i];
77
+ if (!observer)
78
+ continue;
79
+ observer.error(error);
80
+ }
81
+ return [2];
82
+ }
83
+ });
84
+ }); };
85
+ }
86
+ RetryableOperation.prototype.subscribe = function (observer) {
87
+ if (this.canceled) {
88
+ throw new Error("Subscribing to a retryable link that was canceled is not supported");
89
+ }
90
+ this.observers.push(observer);
91
+ for (var _i = 0, _a = this.values; _i < _a.length; _i++) {
92
+ var value = _a[_i];
93
+ observer.next(value);
94
+ }
95
+ if (this.complete) {
96
+ observer.complete();
97
+ }
98
+ else if (this.error) {
99
+ observer.error(this.error);
100
+ }
101
+ };
102
+ RetryableOperation.prototype.unsubscribe = function (observer) {
103
+ var index = this.observers.indexOf(observer);
104
+ if (index < 0) {
105
+ throw new Error("RetryLink BUG! Attempting to unsubscribe unknown observer!");
106
+ }
107
+ this.observers[index] = null;
108
+ if (this.observers.every(function (o) { return o === null; })) {
109
+ this.cancel();
110
+ }
111
+ };
112
+ RetryableOperation.prototype.start = function () {
113
+ if (this.currentSubscription)
114
+ return;
115
+ this.try();
116
+ };
117
+ RetryableOperation.prototype.cancel = function () {
118
+ if (this.currentSubscription) {
119
+ this.currentSubscription.unsubscribe();
120
+ }
121
+ clearTimeout(this.timerId);
122
+ this.timerId = undefined;
123
+ this.currentSubscription = null;
124
+ this.canceled = true;
125
+ };
126
+ RetryableOperation.prototype.try = function () {
127
+ this.currentSubscription = this.nextLink(this.operation).subscribe({
128
+ next: this.onNext,
129
+ error: this.onError,
130
+ complete: this.onComplete,
131
+ });
132
+ };
133
+ RetryableOperation.prototype.scheduleRetry = function (delay) {
134
+ var _this = this;
135
+ if (this.timerId) {
136
+ throw new Error("RetryLink BUG! Encountered overlapping retries");
137
+ }
138
+ this.timerId = setTimeout(function () {
139
+ _this.timerId = undefined;
140
+ _this.try();
141
+ }, delay);
142
+ };
143
+ return RetryableOperation;
144
+ }());
145
+ var RetryLink = (function (_super) {
146
+ tslib.__extends(RetryLink, _super);
147
+ function RetryLink(options) {
148
+ var _this = _super.call(this) || this;
149
+ var _a = options || {}, attempts = _a.attempts, delay = _a.delay;
150
+ _this.delayFor =
151
+ typeof delay === 'function' ? delay : buildDelayFunction(delay);
152
+ _this.retryIf =
153
+ typeof attempts === 'function' ? attempts : buildRetryFunction(attempts);
154
+ return _this;
155
+ }
156
+ RetryLink.prototype.request = function (operation, nextLink) {
157
+ var retryable = new RetryableOperation(operation, nextLink, this.delayFor, this.retryIf);
158
+ retryable.start();
159
+ return new utilities.Observable(function (observer) {
160
+ retryable.subscribe(observer);
161
+ return function () {
162
+ retryable.unsubscribe(observer);
163
+ };
164
+ });
165
+ };
166
+ return RetryLink;
167
+ }(core.ApolloLink));
168
+
169
+ exports.RetryLink = RetryLink;
170
+ //# sourceMappingURL=retry.cjs.map