UNPKG

94.5 kBJavaScriptView Raw
1(function (global, factory) {
2 if (typeof define === "function" && define.amd) {
3 define(["exports", "tslib", "apollo-utilities", "apollo-link", "symbol-observable", "ts-invariant", "graphql/language/visitor"], factory);
4 } else if (typeof exports !== "undefined") {
5 factory(exports, require("tslib"), require("apollo-utilities"), require("apollo-link"), require("symbol-observable"), require("ts-invariant"), require("graphql/language/visitor"));
6 } else {
7 var mod = {
8 exports: {}
9 };
10 factory(mod.exports, global.tslib, global.apolloUtilities, global.apolloLink, global.symbolObservable, global.tsInvariant, global.visitor);
11 global.unknown = mod.exports;
12 }
13})(this, function (_exports, _tslib, _apolloUtilities, _apolloLink, _symbolObservable, _tsInvariant, _visitor) {
14
15 _exports.__esModule = true;
16 _exports.isApolloError = isApolloError;
17 _exports.ObservableQuery = _exports.NetworkStatus = _exports.FetchType = _exports.ApolloError = _exports.ApolloClient = _exports.default = void 0;
18 _symbolObservable = _interopRequireDefault(_symbolObservable);
19
20 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
21
22 var NetworkStatus;
23 _exports.NetworkStatus = NetworkStatus;
24
25 (function (NetworkStatus) {
26 NetworkStatus[NetworkStatus["loading"] = 1] = "loading";
27 NetworkStatus[NetworkStatus["setVariables"] = 2] = "setVariables";
28 NetworkStatus[NetworkStatus["fetchMore"] = 3] = "fetchMore";
29 NetworkStatus[NetworkStatus["refetch"] = 4] = "refetch";
30 NetworkStatus[NetworkStatus["poll"] = 6] = "poll";
31 NetworkStatus[NetworkStatus["ready"] = 7] = "ready";
32 NetworkStatus[NetworkStatus["error"] = 8] = "error";
33 })(NetworkStatus || (_exports.NetworkStatus = NetworkStatus = {}));
34
35 function isNetworkRequestInFlight(networkStatus) {
36 return networkStatus < 7;
37 }
38
39 var Observable = function (_super) {
40 (0, _tslib.__extends)(Observable, _super);
41
42 function Observable() {
43 return _super !== null && _super.apply(this, arguments) || this;
44 }
45
46 Observable.prototype[_symbolObservable.default] = function () {
47 return this;
48 };
49
50 Observable.prototype['@@observable'] = function () {
51 return this;
52 };
53
54 return Observable;
55 }(_apolloLink.Observable);
56
57 function isNonEmptyArray(value) {
58 return Array.isArray(value) && value.length > 0;
59 }
60
61 function isApolloError(err) {
62 return err.hasOwnProperty('graphQLErrors');
63 }
64
65 var generateErrorMessage = function (err) {
66 var message = '';
67
68 if (isNonEmptyArray(err.graphQLErrors)) {
69 err.graphQLErrors.forEach(function (graphQLError) {
70 var errorMessage = graphQLError ? graphQLError.message : 'Error message not found.';
71 message += "GraphQL error: " + errorMessage + "\n";
72 });
73 }
74
75 if (err.networkError) {
76 message += 'Network error: ' + err.networkError.message + '\n';
77 }
78
79 message = message.replace(/\n$/, '');
80 return message;
81 };
82
83 var ApolloError = function (_super) {
84 (0, _tslib.__extends)(ApolloError, _super);
85
86 function ApolloError(_a) {
87 var graphQLErrors = _a.graphQLErrors,
88 networkError = _a.networkError,
89 errorMessage = _a.errorMessage,
90 extraInfo = _a.extraInfo;
91
92 var _this = _super.call(this, errorMessage) || this;
93
94 _this.graphQLErrors = graphQLErrors || [];
95 _this.networkError = networkError || null;
96
97 if (!errorMessage) {
98 _this.message = generateErrorMessage(_this);
99 } else {
100 _this.message = errorMessage;
101 }
102
103 _this.extraInfo = extraInfo;
104 _this.__proto__ = ApolloError.prototype;
105 return _this;
106 }
107
108 return ApolloError;
109 }(Error);
110
111 _exports.ApolloError = ApolloError;
112 var FetchType;
113 _exports.FetchType = FetchType;
114
115 (function (FetchType) {
116 FetchType[FetchType["normal"] = 1] = "normal";
117 FetchType[FetchType["refetch"] = 2] = "refetch";
118 FetchType[FetchType["poll"] = 3] = "poll";
119 })(FetchType || (_exports.FetchType = FetchType = {}));
120
121 var hasError = function (storeValue, policy) {
122 if (policy === void 0) {
123 policy = 'none';
124 }
125
126 return storeValue && (storeValue.networkError || policy === 'none' && isNonEmptyArray(storeValue.graphQLErrors));
127 };
128
129 var ObservableQuery = function (_super) {
130 (0, _tslib.__extends)(ObservableQuery, _super);
131
132 function ObservableQuery(_a) {
133 var queryManager = _a.queryManager,
134 options = _a.options,
135 _b = _a.shouldSubscribe,
136 shouldSubscribe = _b === void 0 ? true : _b;
137
138 var _this = _super.call(this, function (observer) {
139 return _this.onSubscribe(observer);
140 }) || this;
141
142 _this.observers = new Set();
143 _this.subscriptions = new Set();
144 _this.isTornDown = false;
145 _this.options = options;
146 _this.variables = options.variables || {};
147 _this.queryId = queryManager.generateQueryId();
148 _this.shouldSubscribe = shouldSubscribe;
149 var opDef = (0, _apolloUtilities.getOperationDefinition)(options.query);
150 _this.queryName = opDef && opDef.name && opDef.name.value;
151 _this.queryManager = queryManager;
152 return _this;
153 }
154
155 ObservableQuery.prototype.result = function () {
156 var _this = this;
157
158 return new Promise(function (resolve, reject) {
159 var observer = {
160 next: function (result) {
161 resolve(result);
162
163 _this.observers.delete(observer);
164
165 if (!_this.observers.size) {
166 _this.queryManager.removeQuery(_this.queryId);
167 }
168
169 setTimeout(function () {
170 subscription.unsubscribe();
171 }, 0);
172 },
173 error: reject
174 };
175
176 var subscription = _this.subscribe(observer);
177 });
178 };
179
180 ObservableQuery.prototype.currentResult = function () {
181 var result = this.getCurrentResult();
182
183 if (result.data === undefined) {
184 result.data = {};
185 }
186
187 return result;
188 };
189
190 ObservableQuery.prototype.getCurrentResult = function () {
191 if (this.isTornDown) {
192 var lastResult = this.lastResult;
193 return {
194 data: !this.lastError && lastResult && lastResult.data || void 0,
195 error: this.lastError,
196 loading: false,
197 networkStatus: NetworkStatus.error
198 };
199 }
200
201 var _a = this.queryManager.getCurrentQueryResult(this),
202 data = _a.data,
203 partial = _a.partial;
204
205 var queryStoreValue = this.queryManager.queryStore.get(this.queryId);
206 var result;
207 var fetchPolicy = this.options.fetchPolicy;
208 var isNetworkFetchPolicy = fetchPolicy === 'network-only' || fetchPolicy === 'no-cache';
209
210 if (queryStoreValue) {
211 var networkStatus = queryStoreValue.networkStatus;
212
213 if (hasError(queryStoreValue, this.options.errorPolicy)) {
214 return {
215 data: void 0,
216 loading: false,
217 networkStatus: networkStatus,
218 error: new ApolloError({
219 graphQLErrors: queryStoreValue.graphQLErrors,
220 networkError: queryStoreValue.networkError
221 })
222 };
223 }
224
225 if (queryStoreValue.variables) {
226 this.options.variables = (0, _tslib.__assign)({}, this.options.variables, queryStoreValue.variables);
227 this.variables = this.options.variables;
228 }
229
230 result = {
231 data: data,
232 loading: isNetworkRequestInFlight(networkStatus),
233 networkStatus: networkStatus
234 };
235
236 if (queryStoreValue.graphQLErrors && this.options.errorPolicy === 'all') {
237 result.errors = queryStoreValue.graphQLErrors;
238 }
239 } else {
240 var loading = isNetworkFetchPolicy || partial && fetchPolicy !== 'cache-only';
241 result = {
242 data: data,
243 loading: loading,
244 networkStatus: loading ? NetworkStatus.loading : NetworkStatus.ready
245 };
246 }
247
248 if (!partial) {
249 this.updateLastResult((0, _tslib.__assign)({}, result, {
250 stale: false
251 }));
252 }
253
254 return (0, _tslib.__assign)({}, result, {
255 partial: partial
256 });
257 };
258
259 ObservableQuery.prototype.isDifferentFromLastResult = function (newResult) {
260 var snapshot = this.lastResultSnapshot;
261 return !(snapshot && newResult && snapshot.networkStatus === newResult.networkStatus && snapshot.stale === newResult.stale && (0, _apolloUtilities.isEqual)(snapshot.data, newResult.data));
262 };
263
264 ObservableQuery.prototype.getLastResult = function () {
265 return this.lastResult;
266 };
267
268 ObservableQuery.prototype.getLastError = function () {
269 return this.lastError;
270 };
271
272 ObservableQuery.prototype.resetLastResults = function () {
273 delete this.lastResult;
274 delete this.lastResultSnapshot;
275 delete this.lastError;
276 this.isTornDown = false;
277 };
278
279 ObservableQuery.prototype.resetQueryStoreErrors = function () {
280 var queryStore = this.queryManager.queryStore.get(this.queryId);
281
282 if (queryStore) {
283 queryStore.networkError = null;
284 queryStore.graphQLErrors = [];
285 }
286 };
287
288 ObservableQuery.prototype.refetch = function (variables) {
289 var fetchPolicy = this.options.fetchPolicy;
290
291 if (fetchPolicy === 'cache-only') {
292 return Promise.reject(process.env.NODE_ENV === "production" ? new _tsInvariant.InvariantError(3) : new _tsInvariant.InvariantError('cache-only fetchPolicy option should not be used together with query refetch.'));
293 }
294
295 if (fetchPolicy !== 'no-cache' && fetchPolicy !== 'cache-and-network') {
296 fetchPolicy = 'network-only';
297 }
298
299 if (!(0, _apolloUtilities.isEqual)(this.variables, variables)) {
300 this.variables = (0, _tslib.__assign)({}, this.variables, variables);
301 }
302
303 if (!(0, _apolloUtilities.isEqual)(this.options.variables, this.variables)) {
304 this.options.variables = (0, _tslib.__assign)({}, this.options.variables, this.variables);
305 }
306
307 return this.queryManager.fetchQuery(this.queryId, (0, _tslib.__assign)({}, this.options, {
308 fetchPolicy: fetchPolicy
309 }), FetchType.refetch);
310 };
311
312 ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {
313 var _this = this;
314
315 process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(fetchMoreOptions.updateQuery, 4) : (0, _tsInvariant.invariant)(fetchMoreOptions.updateQuery, 'updateQuery option is required. This function defines how to update the query data with the new results.');
316 var combinedOptions = (0, _tslib.__assign)({}, fetchMoreOptions.query ? fetchMoreOptions : (0, _tslib.__assign)({}, this.options, fetchMoreOptions, {
317 variables: (0, _tslib.__assign)({}, this.variables, fetchMoreOptions.variables)
318 }), {
319 fetchPolicy: 'network-only'
320 });
321 var qid = this.queryManager.generateQueryId();
322 return this.queryManager.fetchQuery(qid, combinedOptions, FetchType.normal, this.queryId).then(function (fetchMoreResult) {
323 _this.updateQuery(function (previousResult) {
324 return fetchMoreOptions.updateQuery(previousResult, {
325 fetchMoreResult: fetchMoreResult.data,
326 variables: combinedOptions.variables
327 });
328 });
329
330 _this.queryManager.stopQuery(qid);
331
332 return fetchMoreResult;
333 }, function (error) {
334 _this.queryManager.stopQuery(qid);
335
336 throw error;
337 });
338 };
339
340 ObservableQuery.prototype.subscribeToMore = function (options) {
341 var _this = this;
342
343 var subscription = this.queryManager.startGraphQLSubscription({
344 query: options.document,
345 variables: options.variables
346 }).subscribe({
347 next: function (subscriptionData) {
348 var updateQuery = options.updateQuery;
349
350 if (updateQuery) {
351 _this.updateQuery(function (previous, _a) {
352 var variables = _a.variables;
353 return updateQuery(previous, {
354 subscriptionData: subscriptionData,
355 variables: variables
356 });
357 });
358 }
359 },
360 error: function (err) {
361 if (options.onError) {
362 options.onError(err);
363 return;
364 }
365
366 process.env.NODE_ENV === "production" || _tsInvariant.invariant.error('Unhandled GraphQL subscription error', err);
367 }
368 });
369 this.subscriptions.add(subscription);
370 return function () {
371 if (_this.subscriptions.delete(subscription)) {
372 subscription.unsubscribe();
373 }
374 };
375 };
376
377 ObservableQuery.prototype.setOptions = function (opts) {
378 var oldFetchPolicy = this.options.fetchPolicy;
379 this.options = (0, _tslib.__assign)({}, this.options, opts);
380
381 if (opts.pollInterval) {
382 this.startPolling(opts.pollInterval);
383 } else if (opts.pollInterval === 0) {
384 this.stopPolling();
385 }
386
387 var fetchPolicy = opts.fetchPolicy;
388 return this.setVariables(this.options.variables, oldFetchPolicy !== fetchPolicy && (oldFetchPolicy === 'cache-only' || oldFetchPolicy === 'standby' || fetchPolicy === 'network-only'), opts.fetchResults);
389 };
390
391 ObservableQuery.prototype.setVariables = function (variables, tryFetch, fetchResults) {
392 if (tryFetch === void 0) {
393 tryFetch = false;
394 }
395
396 if (fetchResults === void 0) {
397 fetchResults = true;
398 }
399
400 this.isTornDown = false;
401 variables = variables || this.variables;
402
403 if (!tryFetch && (0, _apolloUtilities.isEqual)(variables, this.variables)) {
404 return this.observers.size && fetchResults ? this.result() : Promise.resolve();
405 }
406
407 this.variables = this.options.variables = variables;
408
409 if (!this.observers.size) {
410 return Promise.resolve();
411 }
412
413 return this.queryManager.fetchQuery(this.queryId, this.options);
414 };
415
416 ObservableQuery.prototype.updateQuery = function (mapFn) {
417 var queryManager = this.queryManager;
418
419 var _a = queryManager.getQueryWithPreviousResult(this.queryId),
420 previousResult = _a.previousResult,
421 variables = _a.variables,
422 document = _a.document;
423
424 var newResult = (0, _apolloUtilities.tryFunctionOrLogError)(function () {
425 return mapFn(previousResult, {
426 variables: variables
427 });
428 });
429
430 if (newResult) {
431 queryManager.dataStore.markUpdateQueryResult(document, variables, newResult);
432 queryManager.broadcastQueries();
433 }
434 };
435
436 ObservableQuery.prototype.stopPolling = function () {
437 this.queryManager.stopPollingQuery(this.queryId);
438 this.options.pollInterval = undefined;
439 };
440
441 ObservableQuery.prototype.startPolling = function (pollInterval) {
442 assertNotCacheFirstOrOnly(this);
443 this.options.pollInterval = pollInterval;
444 this.queryManager.startPollingQuery(this.options, this.queryId);
445 };
446
447 ObservableQuery.prototype.updateLastResult = function (newResult) {
448 var previousResult = this.lastResult;
449 this.lastResult = newResult;
450 this.lastResultSnapshot = this.queryManager.assumeImmutableResults ? newResult : (0, _apolloUtilities.cloneDeep)(newResult);
451 return previousResult;
452 };
453
454 ObservableQuery.prototype.onSubscribe = function (observer) {
455 var _this = this;
456
457 try {
458 var subObserver = observer._subscription._observer;
459
460 if (subObserver && !subObserver.error) {
461 subObserver.error = defaultSubscriptionObserverErrorCallback;
462 }
463 } catch (_a) {}
464
465 var first = !this.observers.size;
466 this.observers.add(observer);
467 if (observer.next && this.lastResult) observer.next(this.lastResult);
468 if (observer.error && this.lastError) observer.error(this.lastError);
469
470 if (first) {
471 this.setUpQuery();
472 }
473
474 return function () {
475 if (_this.observers.delete(observer) && !_this.observers.size) {
476 _this.tearDownQuery();
477 }
478 };
479 };
480
481 ObservableQuery.prototype.setUpQuery = function () {
482 var _this = this;
483
484 var _a = this,
485 queryManager = _a.queryManager,
486 queryId = _a.queryId;
487
488 if (this.shouldSubscribe) {
489 queryManager.addObservableQuery(queryId, this);
490 }
491
492 if (this.options.pollInterval) {
493 assertNotCacheFirstOrOnly(this);
494 queryManager.startPollingQuery(this.options, queryId);
495 }
496
497 var onError = function (error) {
498 iterateObserversSafely(_this.observers, 'error', _this.lastError = error);
499 };
500
501 queryManager.observeQuery(queryId, this.options, {
502 next: function (result) {
503 if (_this.lastError || _this.isDifferentFromLastResult(result)) {
504 var previousResult_1 = _this.updateLastResult(result);
505
506 var _a = _this.options,
507 query_1 = _a.query,
508 variables = _a.variables,
509 fetchPolicy_1 = _a.fetchPolicy;
510
511 if (queryManager.transform(query_1).hasClientExports) {
512 queryManager.getLocalState().addExportedVariables(query_1, variables).then(function (variables) {
513 var previousVariables = _this.variables;
514 _this.variables = _this.options.variables = variables;
515
516 if (!result.loading && previousResult_1 && fetchPolicy_1 !== 'cache-only' && queryManager.transform(query_1).serverQuery && !(0, _apolloUtilities.isEqual)(previousVariables, variables)) {
517 _this.refetch();
518 } else {
519 iterateObserversSafely(_this.observers, 'next', result);
520 }
521 });
522 } else {
523 iterateObserversSafely(_this.observers, 'next', result);
524 }
525 }
526 },
527 error: onError
528 }).catch(onError);
529 };
530
531 ObservableQuery.prototype.tearDownQuery = function () {
532 var queryManager = this.queryManager;
533 this.isTornDown = true;
534 queryManager.stopPollingQuery(this.queryId);
535 this.subscriptions.forEach(function (sub) {
536 return sub.unsubscribe();
537 });
538 this.subscriptions.clear();
539 queryManager.removeObservableQuery(this.queryId);
540 queryManager.stopQuery(this.queryId);
541 this.observers.clear();
542 };
543
544 return ObservableQuery;
545 }(Observable);
546
547 _exports.ObservableQuery = ObservableQuery;
548
549 function defaultSubscriptionObserverErrorCallback(error) {
550 process.env.NODE_ENV === "production" || _tsInvariant.invariant.error('Unhandled error', error.message, error.stack);
551 }
552
553 function iterateObserversSafely(observers, method, argument) {
554 var observersWithMethod = [];
555 observers.forEach(function (obs) {
556 return obs[method] && observersWithMethod.push(obs);
557 });
558 observersWithMethod.forEach(function (obs) {
559 return obs[method](argument);
560 });
561 }
562
563 function assertNotCacheFirstOrOnly(obsQuery) {
564 var fetchPolicy = obsQuery.options.fetchPolicy;
565 process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(fetchPolicy !== 'cache-first' && fetchPolicy !== 'cache-only', 5) : (0, _tsInvariant.invariant)(fetchPolicy !== 'cache-first' && fetchPolicy !== 'cache-only', 'Queries that specify the cache-first and cache-only fetchPolicies cannot also be polling queries.');
566 }
567
568 var MutationStore = function () {
569 function MutationStore() {
570 this.store = {};
571 }
572
573 MutationStore.prototype.getStore = function () {
574 return this.store;
575 };
576
577 MutationStore.prototype.get = function (mutationId) {
578 return this.store[mutationId];
579 };
580
581 MutationStore.prototype.initMutation = function (mutationId, mutation, variables) {
582 this.store[mutationId] = {
583 mutation: mutation,
584 variables: variables || {},
585 loading: true,
586 error: null
587 };
588 };
589
590 MutationStore.prototype.markMutationError = function (mutationId, error) {
591 var mutation = this.store[mutationId];
592
593 if (mutation) {
594 mutation.loading = false;
595 mutation.error = error;
596 }
597 };
598
599 MutationStore.prototype.markMutationResult = function (mutationId) {
600 var mutation = this.store[mutationId];
601
602 if (mutation) {
603 mutation.loading = false;
604 mutation.error = null;
605 }
606 };
607
608 MutationStore.prototype.reset = function () {
609 this.store = {};
610 };
611
612 return MutationStore;
613 }();
614
615 var QueryStore = function () {
616 function QueryStore() {
617 this.store = {};
618 }
619
620 QueryStore.prototype.getStore = function () {
621 return this.store;
622 };
623
624 QueryStore.prototype.get = function (queryId) {
625 return this.store[queryId];
626 };
627
628 QueryStore.prototype.initQuery = function (query) {
629 var previousQuery = this.store[query.queryId];
630 process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(!previousQuery || previousQuery.document === query.document || (0, _apolloUtilities.isEqual)(previousQuery.document, query.document), 19) : (0, _tsInvariant.invariant)(!previousQuery || previousQuery.document === query.document || (0, _apolloUtilities.isEqual)(previousQuery.document, query.document), 'Internal Error: may not update existing query string in store');
631 var isSetVariables = false;
632 var previousVariables = null;
633
634 if (query.storePreviousVariables && previousQuery && previousQuery.networkStatus !== NetworkStatus.loading) {
635 if (!(0, _apolloUtilities.isEqual)(previousQuery.variables, query.variables)) {
636 isSetVariables = true;
637 previousVariables = previousQuery.variables;
638 }
639 }
640
641 var networkStatus;
642
643 if (isSetVariables) {
644 networkStatus = NetworkStatus.setVariables;
645 } else if (query.isPoll) {
646 networkStatus = NetworkStatus.poll;
647 } else if (query.isRefetch) {
648 networkStatus = NetworkStatus.refetch;
649 } else {
650 networkStatus = NetworkStatus.loading;
651 }
652
653 var graphQLErrors = [];
654
655 if (previousQuery && previousQuery.graphQLErrors) {
656 graphQLErrors = previousQuery.graphQLErrors;
657 }
658
659 this.store[query.queryId] = {
660 document: query.document,
661 variables: query.variables,
662 previousVariables: previousVariables,
663 networkError: null,
664 graphQLErrors: graphQLErrors,
665 networkStatus: networkStatus,
666 metadata: query.metadata
667 };
668
669 if (typeof query.fetchMoreForQueryId === 'string' && this.store[query.fetchMoreForQueryId]) {
670 this.store[query.fetchMoreForQueryId].networkStatus = NetworkStatus.fetchMore;
671 }
672 };
673
674 QueryStore.prototype.markQueryResult = function (queryId, result, fetchMoreForQueryId) {
675 if (!this.store || !this.store[queryId]) return;
676 this.store[queryId].networkError = null;
677 this.store[queryId].graphQLErrors = isNonEmptyArray(result.errors) ? result.errors : [];
678 this.store[queryId].previousVariables = null;
679 this.store[queryId].networkStatus = NetworkStatus.ready;
680
681 if (typeof fetchMoreForQueryId === 'string' && this.store[fetchMoreForQueryId]) {
682 this.store[fetchMoreForQueryId].networkStatus = NetworkStatus.ready;
683 }
684 };
685
686 QueryStore.prototype.markQueryError = function (queryId, error, fetchMoreForQueryId) {
687 if (!this.store || !this.store[queryId]) return;
688 this.store[queryId].networkError = error;
689 this.store[queryId].networkStatus = NetworkStatus.error;
690
691 if (typeof fetchMoreForQueryId === 'string') {
692 this.markQueryResultClient(fetchMoreForQueryId, true);
693 }
694 };
695
696 QueryStore.prototype.markQueryResultClient = function (queryId, complete) {
697 var storeValue = this.store && this.store[queryId];
698
699 if (storeValue) {
700 storeValue.networkError = null;
701 storeValue.previousVariables = null;
702
703 if (complete) {
704 storeValue.networkStatus = NetworkStatus.ready;
705 }
706 }
707 };
708
709 QueryStore.prototype.stopQuery = function (queryId) {
710 delete this.store[queryId];
711 };
712
713 QueryStore.prototype.reset = function (observableQueryIds) {
714 var _this = this;
715
716 Object.keys(this.store).forEach(function (queryId) {
717 if (observableQueryIds.indexOf(queryId) < 0) {
718 _this.stopQuery(queryId);
719 } else {
720 _this.store[queryId].networkStatus = NetworkStatus.loading;
721 }
722 });
723 };
724
725 return QueryStore;
726 }();
727
728 function capitalizeFirstLetter(str) {
729 return str.charAt(0).toUpperCase() + str.slice(1);
730 }
731
732 var LocalState = function () {
733 function LocalState(_a) {
734 var cache = _a.cache,
735 client = _a.client,
736 resolvers = _a.resolvers,
737 fragmentMatcher = _a.fragmentMatcher;
738 this.cache = cache;
739
740 if (client) {
741 this.client = client;
742 }
743
744 if (resolvers) {
745 this.addResolvers(resolvers);
746 }
747
748 if (fragmentMatcher) {
749 this.setFragmentMatcher(fragmentMatcher);
750 }
751 }
752
753 LocalState.prototype.addResolvers = function (resolvers) {
754 var _this = this;
755
756 this.resolvers = this.resolvers || {};
757
758 if (Array.isArray(resolvers)) {
759 resolvers.forEach(function (resolverGroup) {
760 _this.resolvers = (0, _apolloUtilities.mergeDeep)(_this.resolvers, resolverGroup);
761 });
762 } else {
763 this.resolvers = (0, _apolloUtilities.mergeDeep)(this.resolvers, resolvers);
764 }
765 };
766
767 LocalState.prototype.setResolvers = function (resolvers) {
768 this.resolvers = {};
769 this.addResolvers(resolvers);
770 };
771
772 LocalState.prototype.getResolvers = function () {
773 return this.resolvers || {};
774 };
775
776 LocalState.prototype.runResolvers = function (_a) {
777 var document = _a.document,
778 remoteResult = _a.remoteResult,
779 context = _a.context,
780 variables = _a.variables,
781 _b = _a.onlyRunForcedResolvers,
782 onlyRunForcedResolvers = _b === void 0 ? false : _b;
783 return (0, _tslib.__awaiter)(this, void 0, void 0, function () {
784 return (0, _tslib.__generator)(this, function (_c) {
785 if (document) {
786 return [2, this.resolveDocument(document, remoteResult.data, context, variables, this.fragmentMatcher, onlyRunForcedResolvers).then(function (localResult) {
787 return (0, _tslib.__assign)({}, remoteResult, {
788 data: localResult.result
789 });
790 })];
791 }
792
793 return [2, remoteResult];
794 });
795 });
796 };
797
798 LocalState.prototype.setFragmentMatcher = function (fragmentMatcher) {
799 this.fragmentMatcher = fragmentMatcher;
800 };
801
802 LocalState.prototype.getFragmentMatcher = function () {
803 return this.fragmentMatcher;
804 };
805
806 LocalState.prototype.clientQuery = function (document) {
807 if ((0, _apolloUtilities.hasDirectives)(['client'], document)) {
808 if (this.resolvers) {
809 return document;
810 }
811
812 process.env.NODE_ENV === "production" || _tsInvariant.invariant.warn('Found @client directives in a query but no ApolloClient resolvers ' + 'were specified. This means ApolloClient local resolver handling ' + 'has been disabled, and @client directives will be passed through ' + 'to your link chain.');
813 }
814
815 return null;
816 };
817
818 LocalState.prototype.serverQuery = function (document) {
819 return this.resolvers ? (0, _apolloUtilities.removeClientSetsFromDocument)(document) : document;
820 };
821
822 LocalState.prototype.prepareContext = function (context) {
823 if (context === void 0) {
824 context = {};
825 }
826
827 var cache = this.cache;
828 var newContext = (0, _tslib.__assign)({}, context, {
829 cache: cache,
830 getCacheKey: function (obj) {
831 if (cache.config) {
832 return cache.config.dataIdFromObject(obj);
833 } else {
834 process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(false, 17) : (0, _tsInvariant.invariant)(false, 'To use context.getCacheKey, you need to use a cache that has ' + 'a configurable dataIdFromObject, like apollo-cache-inmemory.');
835 }
836 }
837 });
838 return newContext;
839 };
840
841 LocalState.prototype.addExportedVariables = function (document, variables, context) {
842 if (variables === void 0) {
843 variables = {};
844 }
845
846 if (context === void 0) {
847 context = {};
848 }
849
850 return (0, _tslib.__awaiter)(this, void 0, void 0, function () {
851 return (0, _tslib.__generator)(this, function (_a) {
852 if (document) {
853 return [2, this.resolveDocument(document, this.buildRootValueFromCache(document, variables) || {}, this.prepareContext(context), variables).then(function (data) {
854 return (0, _tslib.__assign)({}, variables, data.exportedVariables);
855 })];
856 }
857
858 return [2, (0, _tslib.__assign)({}, variables)];
859 });
860 });
861 };
862
863 LocalState.prototype.shouldForceResolvers = function (document) {
864 var forceResolvers = false;
865 (0, _visitor.visit)(document, {
866 Directive: {
867 enter: function (node) {
868 if (node.name.value === 'client' && node.arguments) {
869 forceResolvers = node.arguments.some(function (arg) {
870 return arg.name.value === 'always' && arg.value.kind === 'BooleanValue' && arg.value.value === true;
871 });
872
873 if (forceResolvers) {
874 return _visitor.BREAK;
875 }
876 }
877 }
878 }
879 });
880 return forceResolvers;
881 };
882
883 LocalState.prototype.buildRootValueFromCache = function (document, variables) {
884 return this.cache.diff({
885 query: (0, _apolloUtilities.buildQueryFromSelectionSet)(document),
886 variables: variables,
887 returnPartialData: true,
888 optimistic: false
889 }).result;
890 };
891
892 LocalState.prototype.resolveDocument = function (document, rootValue, context, variables, fragmentMatcher, onlyRunForcedResolvers) {
893 if (context === void 0) {
894 context = {};
895 }
896
897 if (variables === void 0) {
898 variables = {};
899 }
900
901 if (fragmentMatcher === void 0) {
902 fragmentMatcher = function () {
903 return true;
904 };
905 }
906
907 if (onlyRunForcedResolvers === void 0) {
908 onlyRunForcedResolvers = false;
909 }
910
911 return (0, _tslib.__awaiter)(this, void 0, void 0, function () {
912 var mainDefinition, fragments, fragmentMap, definitionOperation, defaultOperationType, _a, cache, client, execContext;
913
914 return (0, _tslib.__generator)(this, function (_b) {
915 mainDefinition = (0, _apolloUtilities.getMainDefinition)(document);
916 fragments = (0, _apolloUtilities.getFragmentDefinitions)(document);
917 fragmentMap = (0, _apolloUtilities.createFragmentMap)(fragments);
918 definitionOperation = mainDefinition.operation;
919 defaultOperationType = definitionOperation ? capitalizeFirstLetter(definitionOperation) : 'Query';
920 _a = this, cache = _a.cache, client = _a.client;
921 execContext = {
922 fragmentMap: fragmentMap,
923 context: (0, _tslib.__assign)({}, context, {
924 cache: cache,
925 client: client
926 }),
927 variables: variables,
928 fragmentMatcher: fragmentMatcher,
929 defaultOperationType: defaultOperationType,
930 exportedVariables: {},
931 onlyRunForcedResolvers: onlyRunForcedResolvers
932 };
933 return [2, this.resolveSelectionSet(mainDefinition.selectionSet, rootValue, execContext).then(function (result) {
934 return {
935 result: result,
936 exportedVariables: execContext.exportedVariables
937 };
938 })];
939 });
940 });
941 };
942
943 LocalState.prototype.resolveSelectionSet = function (selectionSet, rootValue, execContext) {
944 return (0, _tslib.__awaiter)(this, void 0, void 0, function () {
945 var fragmentMap, context, variables, resultsToMerge, execute;
946
947 var _this = this;
948
949 return (0, _tslib.__generator)(this, function (_a) {
950 fragmentMap = execContext.fragmentMap, context = execContext.context, variables = execContext.variables;
951 resultsToMerge = [rootValue];
952
953 execute = function (selection) {
954 return (0, _tslib.__awaiter)(_this, void 0, void 0, function () {
955 var fragment, typeCondition;
956 return (0, _tslib.__generator)(this, function (_a) {
957 if (!(0, _apolloUtilities.shouldInclude)(selection, variables)) {
958 return [2];
959 }
960
961 if ((0, _apolloUtilities.isField)(selection)) {
962 return [2, this.resolveField(selection, rootValue, execContext).then(function (fieldResult) {
963 var _a;
964
965 if (typeof fieldResult !== 'undefined') {
966 resultsToMerge.push((_a = {}, _a[(0, _apolloUtilities.resultKeyNameFromField)(selection)] = fieldResult, _a));
967 }
968 })];
969 }
970
971 if ((0, _apolloUtilities.isInlineFragment)(selection)) {
972 fragment = selection;
973 } else {
974 fragment = fragmentMap[selection.name.value];
975 process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(fragment, 18) : (0, _tsInvariant.invariant)(fragment, "No fragment named " + selection.name.value);
976 }
977
978 if (fragment && fragment.typeCondition) {
979 typeCondition = fragment.typeCondition.name.value;
980
981 if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {
982 return [2, this.resolveSelectionSet(fragment.selectionSet, rootValue, execContext).then(function (fragmentResult) {
983 resultsToMerge.push(fragmentResult);
984 })];
985 }
986 }
987
988 return [2];
989 });
990 });
991 };
992
993 return [2, Promise.all(selectionSet.selections.map(execute)).then(function () {
994 return (0, _apolloUtilities.mergeDeepArray)(resultsToMerge);
995 })];
996 });
997 });
998 };
999
1000 LocalState.prototype.resolveField = function (field, rootValue, execContext) {
1001 return (0, _tslib.__awaiter)(this, void 0, void 0, function () {
1002 var variables, fieldName, aliasedFieldName, aliasUsed, defaultResult, resultPromise, resolverType, resolverMap, resolve;
1003
1004 var _this = this;
1005
1006 return (0, _tslib.__generator)(this, function (_a) {
1007 variables = execContext.variables;
1008 fieldName = field.name.value;
1009 aliasedFieldName = (0, _apolloUtilities.resultKeyNameFromField)(field);
1010 aliasUsed = fieldName !== aliasedFieldName;
1011 defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];
1012 resultPromise = Promise.resolve(defaultResult);
1013
1014 if (!execContext.onlyRunForcedResolvers || this.shouldForceResolvers(field)) {
1015 resolverType = rootValue.__typename || execContext.defaultOperationType;
1016 resolverMap = this.resolvers && this.resolvers[resolverType];
1017
1018 if (resolverMap) {
1019 resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];
1020
1021 if (resolve) {
1022 resultPromise = Promise.resolve(resolve(rootValue, (0, _apolloUtilities.argumentsObjectFromField)(field, variables), execContext.context, {
1023 field: field
1024 }));
1025 }
1026 }
1027 }
1028
1029 return [2, resultPromise.then(function (result) {
1030 if (result === void 0) {
1031 result = defaultResult;
1032 }
1033
1034 if (field.directives) {
1035 field.directives.forEach(function (directive) {
1036 if (directive.name.value === 'export' && directive.arguments) {
1037 directive.arguments.forEach(function (arg) {
1038 if (arg.name.value === 'as' && arg.value.kind === 'StringValue') {
1039 execContext.exportedVariables[arg.value.value] = result;
1040 }
1041 });
1042 }
1043 });
1044 }
1045
1046 if (!field.selectionSet) {
1047 return result;
1048 }
1049
1050 if (result == null) {
1051 return result;
1052 }
1053
1054 if (Array.isArray(result)) {
1055 return _this.resolveSubSelectedArray(field, result, execContext);
1056 }
1057
1058 if (field.selectionSet) {
1059 return _this.resolveSelectionSet(field.selectionSet, result, execContext);
1060 }
1061 })];
1062 });
1063 });
1064 };
1065
1066 LocalState.prototype.resolveSubSelectedArray = function (field, result, execContext) {
1067 var _this = this;
1068
1069 return Promise.all(result.map(function (item) {
1070 if (item === null) {
1071 return null;
1072 }
1073
1074 if (Array.isArray(item)) {
1075 return _this.resolveSubSelectedArray(field, item, execContext);
1076 }
1077
1078 if (field.selectionSet) {
1079 return _this.resolveSelectionSet(field.selectionSet, item, execContext);
1080 }
1081 }));
1082 };
1083
1084 return LocalState;
1085 }();
1086
1087 function multiplex(inner) {
1088 var observers = new Set();
1089 var sub = null;
1090 return new Observable(function (observer) {
1091 observers.add(observer);
1092 sub = sub || inner.subscribe({
1093 next: function (value) {
1094 observers.forEach(function (obs) {
1095 return obs.next && obs.next(value);
1096 });
1097 },
1098 error: function (error) {
1099 observers.forEach(function (obs) {
1100 return obs.error && obs.error(error);
1101 });
1102 },
1103 complete: function () {
1104 observers.forEach(function (obs) {
1105 return obs.complete && obs.complete();
1106 });
1107 }
1108 });
1109 return function () {
1110 if (observers.delete(observer) && !observers.size && sub) {
1111 sub.unsubscribe();
1112 sub = null;
1113 }
1114 };
1115 });
1116 }
1117
1118 function asyncMap(observable, mapFn) {
1119 return new Observable(function (observer) {
1120 var next = observer.next,
1121 error = observer.error,
1122 complete = observer.complete;
1123 var activeNextCount = 0;
1124 var completed = false;
1125 var handler = {
1126 next: function (value) {
1127 ++activeNextCount;
1128 new Promise(function (resolve) {
1129 resolve(mapFn(value));
1130 }).then(function (result) {
1131 --activeNextCount;
1132 next && next.call(observer, result);
1133 completed && handler.complete();
1134 }, function (e) {
1135 --activeNextCount;
1136 error && error.call(observer, e);
1137 });
1138 },
1139 error: function (e) {
1140 error && error.call(observer, e);
1141 },
1142 complete: function () {
1143 completed = true;
1144
1145 if (!activeNextCount) {
1146 complete && complete.call(observer);
1147 }
1148 }
1149 };
1150 var sub = observable.subscribe(handler);
1151 return function () {
1152 return sub.unsubscribe();
1153 };
1154 });
1155 }
1156
1157 var hasOwnProperty = Object.prototype.hasOwnProperty;
1158
1159 var QueryManager = function () {
1160 function QueryManager(_a) {
1161 var link = _a.link,
1162 _b = _a.queryDeduplication,
1163 queryDeduplication = _b === void 0 ? false : _b,
1164 store = _a.store,
1165 _c = _a.onBroadcast,
1166 onBroadcast = _c === void 0 ? function () {
1167 return undefined;
1168 } : _c,
1169 _d = _a.ssrMode,
1170 ssrMode = _d === void 0 ? false : _d,
1171 _e = _a.clientAwareness,
1172 clientAwareness = _e === void 0 ? {} : _e,
1173 localState = _a.localState,
1174 assumeImmutableResults = _a.assumeImmutableResults;
1175 this.mutationStore = new MutationStore();
1176 this.queryStore = new QueryStore();
1177 this.clientAwareness = {};
1178 this.idCounter = 1;
1179 this.queries = new Map();
1180 this.fetchQueryRejectFns = new Map();
1181 this.transformCache = new (_apolloUtilities.canUseWeakMap ? WeakMap : Map)();
1182 this.inFlightLinkObservables = new Map();
1183 this.pollingInfoByQueryId = new Map();
1184 this.link = link;
1185 this.queryDeduplication = queryDeduplication;
1186 this.dataStore = store;
1187 this.onBroadcast = onBroadcast;
1188 this.clientAwareness = clientAwareness;
1189 this.localState = localState || new LocalState({
1190 cache: store.getCache()
1191 });
1192 this.ssrMode = ssrMode;
1193 this.assumeImmutableResults = !!assumeImmutableResults;
1194 }
1195
1196 QueryManager.prototype.stop = function () {
1197 var _this = this;
1198
1199 this.queries.forEach(function (_info, queryId) {
1200 _this.stopQueryNoBroadcast(queryId);
1201 });
1202 this.fetchQueryRejectFns.forEach(function (reject) {
1203 reject(process.env.NODE_ENV === "production" ? new _tsInvariant.InvariantError(6) : new _tsInvariant.InvariantError('QueryManager stopped while query was in flight'));
1204 });
1205 };
1206
1207 QueryManager.prototype.mutate = function (_a) {
1208 var mutation = _a.mutation,
1209 variables = _a.variables,
1210 optimisticResponse = _a.optimisticResponse,
1211 updateQueriesByName = _a.updateQueries,
1212 _b = _a.refetchQueries,
1213 refetchQueries = _b === void 0 ? [] : _b,
1214 _c = _a.awaitRefetchQueries,
1215 awaitRefetchQueries = _c === void 0 ? false : _c,
1216 updateWithProxyFn = _a.update,
1217 _d = _a.errorPolicy,
1218 errorPolicy = _d === void 0 ? 'none' : _d,
1219 fetchPolicy = _a.fetchPolicy,
1220 _e = _a.context,
1221 context = _e === void 0 ? {} : _e;
1222 return (0, _tslib.__awaiter)(this, void 0, void 0, function () {
1223 var mutationId, generateUpdateQueriesInfo, self;
1224
1225 var _this = this;
1226
1227 return (0, _tslib.__generator)(this, function (_f) {
1228 switch (_f.label) {
1229 case 0:
1230 process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(mutation, 7) : (0, _tsInvariant.invariant)(mutation, 'mutation option is required. You must specify your GraphQL document in the mutation option.');
1231 process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(!fetchPolicy || fetchPolicy === 'no-cache', 8) : (0, _tsInvariant.invariant)(!fetchPolicy || fetchPolicy === 'no-cache', "fetchPolicy for mutations currently only supports the 'no-cache' policy");
1232 mutationId = this.generateQueryId();
1233 mutation = this.transform(mutation).document;
1234 this.setQuery(mutationId, function () {
1235 return {
1236 document: mutation
1237 };
1238 });
1239 variables = this.getVariables(mutation, variables);
1240 if (!this.transform(mutation).hasClientExports) return [3, 2];
1241 return [4, this.localState.addExportedVariables(mutation, variables, context)];
1242
1243 case 1:
1244 variables = _f.sent();
1245 _f.label = 2;
1246
1247 case 2:
1248 generateUpdateQueriesInfo = function () {
1249 var ret = {};
1250
1251 if (updateQueriesByName) {
1252 _this.queries.forEach(function (_a, queryId) {
1253 var observableQuery = _a.observableQuery;
1254
1255 if (observableQuery) {
1256 var queryName = observableQuery.queryName;
1257
1258 if (queryName && hasOwnProperty.call(updateQueriesByName, queryName)) {
1259 ret[queryId] = {
1260 updater: updateQueriesByName[queryName],
1261 query: _this.queryStore.get(queryId)
1262 };
1263 }
1264 }
1265 });
1266 }
1267
1268 return ret;
1269 };
1270
1271 this.mutationStore.initMutation(mutationId, mutation, variables);
1272 this.dataStore.markMutationInit({
1273 mutationId: mutationId,
1274 document: mutation,
1275 variables: variables,
1276 updateQueries: generateUpdateQueriesInfo(),
1277 update: updateWithProxyFn,
1278 optimisticResponse: optimisticResponse
1279 });
1280 this.broadcastQueries();
1281 self = this;
1282 return [2, new Promise(function (resolve, reject) {
1283 var storeResult;
1284 var error;
1285 self.getObservableFromLink(mutation, (0, _tslib.__assign)({}, context, {
1286 optimisticResponse: optimisticResponse
1287 }), variables, false).subscribe({
1288 next: function (result) {
1289 if ((0, _apolloUtilities.graphQLResultHasError)(result) && errorPolicy === 'none') {
1290 error = new ApolloError({
1291 graphQLErrors: result.errors
1292 });
1293 return;
1294 }
1295
1296 self.mutationStore.markMutationResult(mutationId);
1297
1298 if (fetchPolicy !== 'no-cache') {
1299 self.dataStore.markMutationResult({
1300 mutationId: mutationId,
1301 result: result,
1302 document: mutation,
1303 variables: variables,
1304 updateQueries: generateUpdateQueriesInfo(),
1305 update: updateWithProxyFn
1306 });
1307 }
1308
1309 storeResult = result;
1310 },
1311 error: function (err) {
1312 self.mutationStore.markMutationError(mutationId, err);
1313 self.dataStore.markMutationComplete({
1314 mutationId: mutationId,
1315 optimisticResponse: optimisticResponse
1316 });
1317 self.broadcastQueries();
1318 self.setQuery(mutationId, function () {
1319 return {
1320 document: null
1321 };
1322 });
1323 reject(new ApolloError({
1324 networkError: err
1325 }));
1326 },
1327 complete: function () {
1328 if (error) {
1329 self.mutationStore.markMutationError(mutationId, error);
1330 }
1331
1332 self.dataStore.markMutationComplete({
1333 mutationId: mutationId,
1334 optimisticResponse: optimisticResponse
1335 });
1336 self.broadcastQueries();
1337
1338 if (error) {
1339 reject(error);
1340 return;
1341 }
1342
1343 if (typeof refetchQueries === 'function') {
1344 refetchQueries = refetchQueries(storeResult);
1345 }
1346
1347 var refetchQueryPromises = [];
1348
1349 if (isNonEmptyArray(refetchQueries)) {
1350 refetchQueries.forEach(function (refetchQuery) {
1351 if (typeof refetchQuery === 'string') {
1352 self.queries.forEach(function (_a) {
1353 var observableQuery = _a.observableQuery;
1354
1355 if (observableQuery && observableQuery.queryName === refetchQuery) {
1356 refetchQueryPromises.push(observableQuery.refetch());
1357 }
1358 });
1359 } else {
1360 var queryOptions = {
1361 query: refetchQuery.query,
1362 variables: refetchQuery.variables,
1363 fetchPolicy: 'network-only'
1364 };
1365
1366 if (refetchQuery.context) {
1367 queryOptions.context = refetchQuery.context;
1368 }
1369
1370 refetchQueryPromises.push(self.query(queryOptions));
1371 }
1372 });
1373 }
1374
1375 Promise.all(awaitRefetchQueries ? refetchQueryPromises : []).then(function () {
1376 self.setQuery(mutationId, function () {
1377 return {
1378 document: null
1379 };
1380 });
1381
1382 if (errorPolicy === 'ignore' && storeResult && (0, _apolloUtilities.graphQLResultHasError)(storeResult)) {
1383 delete storeResult.errors;
1384 }
1385
1386 resolve(storeResult);
1387 });
1388 }
1389 });
1390 })];
1391 }
1392 });
1393 });
1394 };
1395
1396 QueryManager.prototype.fetchQuery = function (queryId, options, fetchType, fetchMoreForQueryId) {
1397 return (0, _tslib.__awaiter)(this, void 0, void 0, function () {
1398 var _a, metadata, _b, fetchPolicy, _c, context, query, variables, storeResult, isNetworkOnly, needToFetch, _d, complete, result, shouldFetch, requestId, cancel, networkResult;
1399
1400 var _this = this;
1401
1402 return (0, _tslib.__generator)(this, function (_e) {
1403 switch (_e.label) {
1404 case 0:
1405 _a = options.metadata, metadata = _a === void 0 ? null : _a, _b = options.fetchPolicy, fetchPolicy = _b === void 0 ? 'cache-first' : _b, _c = options.context, context = _c === void 0 ? {} : _c;
1406 query = this.transform(options.query).document;
1407 variables = this.getVariables(query, options.variables);
1408 if (!this.transform(query).hasClientExports) return [3, 2];
1409 return [4, this.localState.addExportedVariables(query, variables, context)];
1410
1411 case 1:
1412 variables = _e.sent();
1413 _e.label = 2;
1414
1415 case 2:
1416 options = (0, _tslib.__assign)({}, options, {
1417 variables: variables
1418 });
1419 isNetworkOnly = fetchPolicy === 'network-only' || fetchPolicy === 'no-cache';
1420 needToFetch = isNetworkOnly;
1421
1422 if (!isNetworkOnly) {
1423 _d = this.dataStore.getCache().diff({
1424 query: query,
1425 variables: variables,
1426 returnPartialData: true,
1427 optimistic: false
1428 }), complete = _d.complete, result = _d.result;
1429 needToFetch = !complete || fetchPolicy === 'cache-and-network';
1430 storeResult = result;
1431 }
1432
1433 shouldFetch = needToFetch && fetchPolicy !== 'cache-only' && fetchPolicy !== 'standby';
1434 if ((0, _apolloUtilities.hasDirectives)(['live'], query)) shouldFetch = true;
1435 requestId = this.idCounter++;
1436 cancel = fetchPolicy !== 'no-cache' ? this.updateQueryWatch(queryId, query, options) : undefined;
1437 this.setQuery(queryId, function () {
1438 return {
1439 document: query,
1440 lastRequestId: requestId,
1441 invalidated: true,
1442 cancel: cancel
1443 };
1444 });
1445 this.invalidate(fetchMoreForQueryId);
1446 this.queryStore.initQuery({
1447 queryId: queryId,
1448 document: query,
1449 storePreviousVariables: shouldFetch,
1450 variables: variables,
1451 isPoll: fetchType === FetchType.poll,
1452 isRefetch: fetchType === FetchType.refetch,
1453 metadata: metadata,
1454 fetchMoreForQueryId: fetchMoreForQueryId
1455 });
1456 this.broadcastQueries();
1457
1458 if (shouldFetch) {
1459 networkResult = this.fetchRequest({
1460 requestId: requestId,
1461 queryId: queryId,
1462 document: query,
1463 options: options,
1464 fetchMoreForQueryId: fetchMoreForQueryId
1465 }).catch(function (error) {
1466 if (isApolloError(error)) {
1467 throw error;
1468 } else {
1469 if (requestId >= _this.getQuery(queryId).lastRequestId) {
1470 _this.queryStore.markQueryError(queryId, error, fetchMoreForQueryId);
1471
1472 _this.invalidate(queryId);
1473
1474 _this.invalidate(fetchMoreForQueryId);
1475
1476 _this.broadcastQueries();
1477 }
1478
1479 throw new ApolloError({
1480 networkError: error
1481 });
1482 }
1483 });
1484
1485 if (fetchPolicy !== 'cache-and-network') {
1486 return [2, networkResult];
1487 }
1488
1489 networkResult.catch(function () {});
1490 }
1491
1492 this.queryStore.markQueryResultClient(queryId, !shouldFetch);
1493 this.invalidate(queryId);
1494 this.invalidate(fetchMoreForQueryId);
1495
1496 if (this.transform(query).hasForcedResolvers) {
1497 return [2, this.localState.runResolvers({
1498 document: query,
1499 remoteResult: {
1500 data: storeResult
1501 },
1502 context: context,
1503 variables: variables,
1504 onlyRunForcedResolvers: true
1505 }).then(function (result) {
1506 _this.markQueryResult(queryId, result, options, fetchMoreForQueryId);
1507
1508 _this.broadcastQueries();
1509
1510 return result;
1511 })];
1512 }
1513
1514 this.broadcastQueries();
1515 return [2, {
1516 data: storeResult
1517 }];
1518 }
1519 });
1520 });
1521 };
1522
1523 QueryManager.prototype.markQueryResult = function (queryId, result, _a, fetchMoreForQueryId) {
1524 var fetchPolicy = _a.fetchPolicy,
1525 variables = _a.variables,
1526 errorPolicy = _a.errorPolicy;
1527
1528 if (fetchPolicy === 'no-cache') {
1529 this.setQuery(queryId, function () {
1530 return {
1531 newData: {
1532 result: result.data,
1533 complete: true
1534 }
1535 };
1536 });
1537 } else {
1538 this.dataStore.markQueryResult(result, this.getQuery(queryId).document, variables, fetchMoreForQueryId, errorPolicy === 'ignore' || errorPolicy === 'all');
1539 }
1540 };
1541
1542 QueryManager.prototype.queryListenerForObserver = function (queryId, options, observer) {
1543 var _this = this;
1544
1545 function invoke(method, argument) {
1546 if (observer[method]) {
1547 try {
1548 observer[method](argument);
1549 } catch (e) {
1550 process.env.NODE_ENV === "production" || _tsInvariant.invariant.error(e);
1551 }
1552 } else if (method === 'error') {
1553 process.env.NODE_ENV === "production" || _tsInvariant.invariant.error(argument);
1554 }
1555 }
1556
1557 return function (queryStoreValue, newData) {
1558 _this.invalidate(queryId, false);
1559
1560 if (!queryStoreValue) return;
1561
1562 var _a = _this.getQuery(queryId),
1563 observableQuery = _a.observableQuery,
1564 document = _a.document;
1565
1566 var fetchPolicy = observableQuery ? observableQuery.options.fetchPolicy : options.fetchPolicy;
1567 if (fetchPolicy === 'standby') return;
1568 var loading = isNetworkRequestInFlight(queryStoreValue.networkStatus);
1569 var lastResult = observableQuery && observableQuery.getLastResult();
1570 var networkStatusChanged = !!(lastResult && lastResult.networkStatus !== queryStoreValue.networkStatus);
1571 var shouldNotifyIfLoading = options.returnPartialData || !newData && queryStoreValue.previousVariables || networkStatusChanged && options.notifyOnNetworkStatusChange || fetchPolicy === 'cache-only' || fetchPolicy === 'cache-and-network';
1572
1573 if (loading && !shouldNotifyIfLoading) {
1574 return;
1575 }
1576
1577 var hasGraphQLErrors = isNonEmptyArray(queryStoreValue.graphQLErrors);
1578 var errorPolicy = observableQuery && observableQuery.options.errorPolicy || options.errorPolicy || 'none';
1579
1580 if (errorPolicy === 'none' && hasGraphQLErrors || queryStoreValue.networkError) {
1581 return invoke('error', new ApolloError({
1582 graphQLErrors: queryStoreValue.graphQLErrors,
1583 networkError: queryStoreValue.networkError
1584 }));
1585 }
1586
1587 try {
1588 var data = void 0;
1589 var isMissing = void 0;
1590
1591 if (newData) {
1592 if (fetchPolicy !== 'no-cache' && fetchPolicy !== 'network-only') {
1593 _this.setQuery(queryId, function () {
1594 return {
1595 newData: null
1596 };
1597 });
1598 }
1599
1600 data = newData.result;
1601 isMissing = !newData.complete;
1602 } else {
1603 var lastError = observableQuery && observableQuery.getLastError();
1604 var errorStatusChanged = errorPolicy !== 'none' && (lastError && lastError.graphQLErrors) !== queryStoreValue.graphQLErrors;
1605
1606 if (lastResult && lastResult.data && !errorStatusChanged) {
1607 data = lastResult.data;
1608 isMissing = false;
1609 } else {
1610 var diffResult = _this.dataStore.getCache().diff({
1611 query: document,
1612 variables: queryStoreValue.previousVariables || queryStoreValue.variables,
1613 returnPartialData: true,
1614 optimistic: true
1615 });
1616
1617 data = diffResult.result;
1618 isMissing = !diffResult.complete;
1619 }
1620 }
1621
1622 var stale = isMissing && !(options.returnPartialData || fetchPolicy === 'cache-only');
1623 var resultFromStore = {
1624 data: stale ? lastResult && lastResult.data : data,
1625 loading: loading,
1626 networkStatus: queryStoreValue.networkStatus,
1627 stale: stale
1628 };
1629
1630 if (errorPolicy === 'all' && hasGraphQLErrors) {
1631 resultFromStore.errors = queryStoreValue.graphQLErrors;
1632 }
1633
1634 invoke('next', resultFromStore);
1635 } catch (networkError) {
1636 invoke('error', new ApolloError({
1637 networkError: networkError
1638 }));
1639 }
1640 };
1641 };
1642
1643 QueryManager.prototype.transform = function (document) {
1644 var transformCache = this.transformCache;
1645
1646 if (!transformCache.has(document)) {
1647 var cache = this.dataStore.getCache();
1648 var transformed = cache.transformDocument(document);
1649 var forLink = (0, _apolloUtilities.removeConnectionDirectiveFromDocument)(cache.transformForLink(transformed));
1650 var clientQuery = this.localState.clientQuery(transformed);
1651 var serverQuery = this.localState.serverQuery(forLink);
1652 var cacheEntry_1 = {
1653 document: transformed,
1654 hasClientExports: (0, _apolloUtilities.hasClientExports)(transformed),
1655 hasForcedResolvers: this.localState.shouldForceResolvers(transformed),
1656 clientQuery: clientQuery,
1657 serverQuery: serverQuery,
1658 defaultVars: (0, _apolloUtilities.getDefaultValues)((0, _apolloUtilities.getOperationDefinition)(transformed))
1659 };
1660
1661 var add = function (doc) {
1662 if (doc && !transformCache.has(doc)) {
1663 transformCache.set(doc, cacheEntry_1);
1664 }
1665 };
1666
1667 add(document);
1668 add(transformed);
1669 add(clientQuery);
1670 add(serverQuery);
1671 }
1672
1673 return transformCache.get(document);
1674 };
1675
1676 QueryManager.prototype.getVariables = function (document, variables) {
1677 return (0, _tslib.__assign)({}, this.transform(document).defaultVars, variables);
1678 };
1679
1680 QueryManager.prototype.watchQuery = function (options, shouldSubscribe) {
1681 if (shouldSubscribe === void 0) {
1682 shouldSubscribe = true;
1683 }
1684
1685 process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(options.fetchPolicy !== 'standby', 9) : (0, _tsInvariant.invariant)(options.fetchPolicy !== 'standby', 'client.watchQuery cannot be called with fetchPolicy set to "standby"');
1686 options.variables = this.getVariables(options.query, options.variables);
1687
1688 if (typeof options.notifyOnNetworkStatusChange === 'undefined') {
1689 options.notifyOnNetworkStatusChange = false;
1690 }
1691
1692 var transformedOptions = (0, _tslib.__assign)({}, options);
1693 return new ObservableQuery({
1694 queryManager: this,
1695 options: transformedOptions,
1696 shouldSubscribe: shouldSubscribe
1697 });
1698 };
1699
1700 QueryManager.prototype.query = function (options) {
1701 var _this = this;
1702
1703 process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(options.query, 10) : (0, _tsInvariant.invariant)(options.query, 'query option is required. You must specify your GraphQL document ' + 'in the query option.');
1704 process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(options.query.kind === 'Document', 11) : (0, _tsInvariant.invariant)(options.query.kind === 'Document', 'You must wrap the query string in a "gql" tag.');
1705 process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(!options.returnPartialData, 12) : (0, _tsInvariant.invariant)(!options.returnPartialData, 'returnPartialData option only supported on watchQuery.');
1706 process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(!options.pollInterval, 13) : (0, _tsInvariant.invariant)(!options.pollInterval, 'pollInterval option only supported on watchQuery.');
1707 return new Promise(function (resolve, reject) {
1708 var watchedQuery = _this.watchQuery(options, false);
1709
1710 _this.fetchQueryRejectFns.set("query:" + watchedQuery.queryId, reject);
1711
1712 watchedQuery.result().then(resolve, reject).then(function () {
1713 return _this.fetchQueryRejectFns.delete("query:" + watchedQuery.queryId);
1714 });
1715 });
1716 };
1717
1718 QueryManager.prototype.generateQueryId = function () {
1719 return String(this.idCounter++);
1720 };
1721
1722 QueryManager.prototype.stopQueryInStore = function (queryId) {
1723 this.stopQueryInStoreNoBroadcast(queryId);
1724 this.broadcastQueries();
1725 };
1726
1727 QueryManager.prototype.stopQueryInStoreNoBroadcast = function (queryId) {
1728 this.stopPollingQuery(queryId);
1729 this.queryStore.stopQuery(queryId);
1730 this.invalidate(queryId);
1731 };
1732
1733 QueryManager.prototype.addQueryListener = function (queryId, listener) {
1734 this.setQuery(queryId, function (_a) {
1735 var listeners = _a.listeners;
1736 listeners.add(listener);
1737 return {
1738 invalidated: false
1739 };
1740 });
1741 };
1742
1743 QueryManager.prototype.updateQueryWatch = function (queryId, document, options) {
1744 var _this = this;
1745
1746 var cancel = this.getQuery(queryId).cancel;
1747 if (cancel) cancel();
1748
1749 var previousResult = function () {
1750 var previousResult = null;
1751
1752 var observableQuery = _this.getQuery(queryId).observableQuery;
1753
1754 if (observableQuery) {
1755 var lastResult = observableQuery.getLastResult();
1756
1757 if (lastResult) {
1758 previousResult = lastResult.data;
1759 }
1760 }
1761
1762 return previousResult;
1763 };
1764
1765 return this.dataStore.getCache().watch({
1766 query: document,
1767 variables: options.variables,
1768 optimistic: true,
1769 previousResult: previousResult,
1770 callback: function (newData) {
1771 _this.setQuery(queryId, function () {
1772 return {
1773 invalidated: true,
1774 newData: newData
1775 };
1776 });
1777 }
1778 });
1779 };
1780
1781 QueryManager.prototype.addObservableQuery = function (queryId, observableQuery) {
1782 this.setQuery(queryId, function () {
1783 return {
1784 observableQuery: observableQuery
1785 };
1786 });
1787 };
1788
1789 QueryManager.prototype.removeObservableQuery = function (queryId) {
1790 var cancel = this.getQuery(queryId).cancel;
1791 this.setQuery(queryId, function () {
1792 return {
1793 observableQuery: null
1794 };
1795 });
1796 if (cancel) cancel();
1797 };
1798
1799 QueryManager.prototype.clearStore = function () {
1800 this.fetchQueryRejectFns.forEach(function (reject) {
1801 reject(process.env.NODE_ENV === "production" ? new _tsInvariant.InvariantError(14) : new _tsInvariant.InvariantError('Store reset while query was in flight (not completed in link chain)'));
1802 });
1803 var resetIds = [];
1804 this.queries.forEach(function (_a, queryId) {
1805 var observableQuery = _a.observableQuery;
1806 if (observableQuery) resetIds.push(queryId);
1807 });
1808 this.queryStore.reset(resetIds);
1809 this.mutationStore.reset();
1810 return this.dataStore.reset();
1811 };
1812
1813 QueryManager.prototype.resetStore = function () {
1814 var _this = this;
1815
1816 return this.clearStore().then(function () {
1817 return _this.reFetchObservableQueries();
1818 });
1819 };
1820
1821 QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {
1822 var _this = this;
1823
1824 if (includeStandby === void 0) {
1825 includeStandby = false;
1826 }
1827
1828 var observableQueryPromises = [];
1829 this.queries.forEach(function (_a, queryId) {
1830 var observableQuery = _a.observableQuery;
1831
1832 if (observableQuery) {
1833 var fetchPolicy = observableQuery.options.fetchPolicy;
1834 observableQuery.resetLastResults();
1835
1836 if (fetchPolicy !== 'cache-only' && (includeStandby || fetchPolicy !== 'standby')) {
1837 observableQueryPromises.push(observableQuery.refetch());
1838 }
1839
1840 _this.setQuery(queryId, function () {
1841 return {
1842 newData: null
1843 };
1844 });
1845
1846 _this.invalidate(queryId);
1847 }
1848 });
1849 this.broadcastQueries();
1850 return Promise.all(observableQueryPromises);
1851 };
1852
1853 QueryManager.prototype.observeQuery = function (queryId, options, observer) {
1854 this.addQueryListener(queryId, this.queryListenerForObserver(queryId, options, observer));
1855 return this.fetchQuery(queryId, options);
1856 };
1857
1858 QueryManager.prototype.startQuery = function (queryId, options, listener) {
1859 process.env.NODE_ENV === "production" || _tsInvariant.invariant.warn("The QueryManager.startQuery method has been deprecated");
1860 this.addQueryListener(queryId, listener);
1861 this.fetchQuery(queryId, options).catch(function () {
1862 return undefined;
1863 });
1864 return queryId;
1865 };
1866
1867 QueryManager.prototype.startGraphQLSubscription = function (_a) {
1868 var _this = this;
1869
1870 var query = _a.query,
1871 fetchPolicy = _a.fetchPolicy,
1872 variables = _a.variables;
1873 query = this.transform(query).document;
1874 variables = this.getVariables(query, variables);
1875
1876 var makeObservable = function (variables) {
1877 return _this.getObservableFromLink(query, {}, variables, false).map(function (result) {
1878 if (!fetchPolicy || fetchPolicy !== 'no-cache') {
1879 _this.dataStore.markSubscriptionResult(result, query, variables);
1880
1881 _this.broadcastQueries();
1882 }
1883
1884 if ((0, _apolloUtilities.graphQLResultHasError)(result)) {
1885 throw new ApolloError({
1886 graphQLErrors: result.errors
1887 });
1888 }
1889
1890 return result;
1891 });
1892 };
1893
1894 if (this.transform(query).hasClientExports) {
1895 var observablePromise_1 = this.localState.addExportedVariables(query, variables).then(makeObservable);
1896 return new Observable(function (observer) {
1897 var sub = null;
1898 observablePromise_1.then(function (observable) {
1899 return sub = observable.subscribe(observer);
1900 }, observer.error);
1901 return function () {
1902 return sub && sub.unsubscribe();
1903 };
1904 });
1905 }
1906
1907 return makeObservable(variables);
1908 };
1909
1910 QueryManager.prototype.stopQuery = function (queryId) {
1911 this.stopQueryNoBroadcast(queryId);
1912 this.broadcastQueries();
1913 };
1914
1915 QueryManager.prototype.stopQueryNoBroadcast = function (queryId) {
1916 this.stopQueryInStoreNoBroadcast(queryId);
1917 this.removeQuery(queryId);
1918 };
1919
1920 QueryManager.prototype.removeQuery = function (queryId) {
1921 this.fetchQueryRejectFns.delete("query:" + queryId);
1922 this.fetchQueryRejectFns.delete("fetchRequest:" + queryId);
1923 this.getQuery(queryId).subscriptions.forEach(function (x) {
1924 return x.unsubscribe();
1925 });
1926 this.queries.delete(queryId);
1927 };
1928
1929 QueryManager.prototype.getCurrentQueryResult = function (observableQuery, optimistic) {
1930 if (optimistic === void 0) {
1931 optimistic = true;
1932 }
1933
1934 var _a = observableQuery.options,
1935 variables = _a.variables,
1936 query = _a.query,
1937 fetchPolicy = _a.fetchPolicy,
1938 returnPartialData = _a.returnPartialData;
1939 var lastResult = observableQuery.getLastResult();
1940 var newData = this.getQuery(observableQuery.queryId).newData;
1941
1942 if (newData && newData.complete) {
1943 return {
1944 data: newData.result,
1945 partial: false
1946 };
1947 }
1948
1949 if (fetchPolicy === 'no-cache' || fetchPolicy === 'network-only') {
1950 return {
1951 data: undefined,
1952 partial: false
1953 };
1954 }
1955
1956 var _b = this.dataStore.getCache().diff({
1957 query: query,
1958 variables: variables,
1959 previousResult: lastResult ? lastResult.data : undefined,
1960 returnPartialData: true,
1961 optimistic: optimistic
1962 }),
1963 result = _b.result,
1964 complete = _b.complete;
1965
1966 return {
1967 data: complete || returnPartialData ? result : void 0,
1968 partial: !complete
1969 };
1970 };
1971
1972 QueryManager.prototype.getQueryWithPreviousResult = function (queryIdOrObservable) {
1973 var observableQuery;
1974
1975 if (typeof queryIdOrObservable === 'string') {
1976 var foundObserveableQuery = this.getQuery(queryIdOrObservable).observableQuery;
1977 process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(foundObserveableQuery, 15) : (0, _tsInvariant.invariant)(foundObserveableQuery, "ObservableQuery with this id doesn't exist: " + queryIdOrObservable);
1978 observableQuery = foundObserveableQuery;
1979 } else {
1980 observableQuery = queryIdOrObservable;
1981 }
1982
1983 var _a = observableQuery.options,
1984 variables = _a.variables,
1985 query = _a.query;
1986 return {
1987 previousResult: this.getCurrentQueryResult(observableQuery, false).data,
1988 variables: variables,
1989 document: query
1990 };
1991 };
1992
1993 QueryManager.prototype.broadcastQueries = function () {
1994 var _this = this;
1995
1996 this.onBroadcast();
1997 this.queries.forEach(function (info, id) {
1998 if (info.invalidated) {
1999 info.listeners.forEach(function (listener) {
2000 if (listener) {
2001 listener(_this.queryStore.get(id), info.newData);
2002 }
2003 });
2004 }
2005 });
2006 };
2007
2008 QueryManager.prototype.getLocalState = function () {
2009 return this.localState;
2010 };
2011
2012 QueryManager.prototype.getObservableFromLink = function (query, context, variables, deduplication) {
2013 var _this = this;
2014
2015 if (deduplication === void 0) {
2016 deduplication = this.queryDeduplication;
2017 }
2018
2019 var observable;
2020 var serverQuery = this.transform(query).serverQuery;
2021
2022 if (serverQuery) {
2023 var _a = this,
2024 inFlightLinkObservables_1 = _a.inFlightLinkObservables,
2025 link = _a.link;
2026
2027 var operation = {
2028 query: serverQuery,
2029 variables: variables,
2030 operationName: (0, _apolloUtilities.getOperationName)(serverQuery) || void 0,
2031 context: this.prepareContext((0, _tslib.__assign)({}, context, {
2032 forceFetch: !deduplication
2033 }))
2034 };
2035 context = operation.context;
2036
2037 if (deduplication) {
2038 var byVariables_1 = inFlightLinkObservables_1.get(serverQuery) || new Map();
2039 inFlightLinkObservables_1.set(serverQuery, byVariables_1);
2040 var varJson_1 = JSON.stringify(variables);
2041 observable = byVariables_1.get(varJson_1);
2042
2043 if (!observable) {
2044 byVariables_1.set(varJson_1, observable = multiplex((0, _apolloLink.execute)(link, operation)));
2045
2046 var cleanup = function () {
2047 byVariables_1.delete(varJson_1);
2048 if (!byVariables_1.size) inFlightLinkObservables_1.delete(serverQuery);
2049 cleanupSub_1.unsubscribe();
2050 };
2051
2052 var cleanupSub_1 = observable.subscribe({
2053 next: cleanup,
2054 error: cleanup,
2055 complete: cleanup
2056 });
2057 }
2058 } else {
2059 observable = multiplex((0, _apolloLink.execute)(link, operation));
2060 }
2061 } else {
2062 observable = Observable.of({
2063 data: {}
2064 });
2065 context = this.prepareContext(context);
2066 }
2067
2068 var clientQuery = this.transform(query).clientQuery;
2069
2070 if (clientQuery) {
2071 observable = asyncMap(observable, function (result) {
2072 return _this.localState.runResolvers({
2073 document: clientQuery,
2074 remoteResult: result,
2075 context: context,
2076 variables: variables
2077 });
2078 });
2079 }
2080
2081 return observable;
2082 };
2083
2084 QueryManager.prototype.fetchRequest = function (_a) {
2085 var _this = this;
2086
2087 var requestId = _a.requestId,
2088 queryId = _a.queryId,
2089 document = _a.document,
2090 options = _a.options,
2091 fetchMoreForQueryId = _a.fetchMoreForQueryId;
2092 var variables = options.variables,
2093 _b = options.errorPolicy,
2094 errorPolicy = _b === void 0 ? 'none' : _b,
2095 fetchPolicy = options.fetchPolicy;
2096 var resultFromStore;
2097 var errorsFromStore;
2098 return new Promise(function (resolve, reject) {
2099 var observable = _this.getObservableFromLink(document, options.context, variables);
2100
2101 var fqrfId = "fetchRequest:" + queryId;
2102
2103 _this.fetchQueryRejectFns.set(fqrfId, reject);
2104
2105 var cleanup = function () {
2106 _this.fetchQueryRejectFns.delete(fqrfId);
2107
2108 _this.setQuery(queryId, function (_a) {
2109 var subscriptions = _a.subscriptions;
2110 subscriptions.delete(subscription);
2111 });
2112 };
2113
2114 var subscription = observable.map(function (result) {
2115 if (requestId >= _this.getQuery(queryId).lastRequestId) {
2116 _this.markQueryResult(queryId, result, options, fetchMoreForQueryId);
2117
2118 _this.queryStore.markQueryResult(queryId, result, fetchMoreForQueryId);
2119
2120 _this.invalidate(queryId);
2121
2122 _this.invalidate(fetchMoreForQueryId);
2123
2124 _this.broadcastQueries();
2125 }
2126
2127 if (errorPolicy === 'none' && isNonEmptyArray(result.errors)) {
2128 return reject(new ApolloError({
2129 graphQLErrors: result.errors
2130 }));
2131 }
2132
2133 if (errorPolicy === 'all') {
2134 errorsFromStore = result.errors;
2135 }
2136
2137 if (fetchMoreForQueryId || fetchPolicy === 'no-cache') {
2138 resultFromStore = result.data;
2139 } else {
2140 var _a = _this.dataStore.getCache().diff({
2141 variables: variables,
2142 query: document,
2143 optimistic: false,
2144 returnPartialData: true
2145 }),
2146 result_1 = _a.result,
2147 complete = _a.complete;
2148
2149 if (complete || options.returnPartialData) {
2150 resultFromStore = result_1;
2151 }
2152 }
2153 }).subscribe({
2154 error: function (error) {
2155 cleanup();
2156 reject(error);
2157 },
2158 complete: function () {
2159 cleanup();
2160 resolve({
2161 data: resultFromStore,
2162 errors: errorsFromStore,
2163 loading: false,
2164 networkStatus: NetworkStatus.ready,
2165 stale: false
2166 });
2167 }
2168 });
2169
2170 _this.setQuery(queryId, function (_a) {
2171 var subscriptions = _a.subscriptions;
2172 subscriptions.add(subscription);
2173 });
2174 });
2175 };
2176
2177 QueryManager.prototype.getQuery = function (queryId) {
2178 return this.queries.get(queryId) || {
2179 listeners: new Set(),
2180 invalidated: false,
2181 document: null,
2182 newData: null,
2183 lastRequestId: 1,
2184 observableQuery: null,
2185 subscriptions: new Set()
2186 };
2187 };
2188
2189 QueryManager.prototype.setQuery = function (queryId, updater) {
2190 var prev = this.getQuery(queryId);
2191 var newInfo = (0, _tslib.__assign)({}, prev, updater(prev));
2192 this.queries.set(queryId, newInfo);
2193 };
2194
2195 QueryManager.prototype.invalidate = function (queryId, invalidated) {
2196 if (invalidated === void 0) {
2197 invalidated = true;
2198 }
2199
2200 if (queryId) {
2201 this.setQuery(queryId, function () {
2202 return {
2203 invalidated: invalidated
2204 };
2205 });
2206 }
2207 };
2208
2209 QueryManager.prototype.prepareContext = function (context) {
2210 if (context === void 0) {
2211 context = {};
2212 }
2213
2214 var newContext = this.localState.prepareContext(context);
2215 return (0, _tslib.__assign)({}, newContext, {
2216 clientAwareness: this.clientAwareness
2217 });
2218 };
2219
2220 QueryManager.prototype.checkInFlight = function (queryId) {
2221 var query = this.queryStore.get(queryId);
2222 return query && query.networkStatus !== NetworkStatus.ready && query.networkStatus !== NetworkStatus.error;
2223 };
2224
2225 QueryManager.prototype.startPollingQuery = function (options, queryId, listener) {
2226 var _this = this;
2227
2228 var pollInterval = options.pollInterval;
2229 process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(pollInterval, 16) : (0, _tsInvariant.invariant)(pollInterval, 'Attempted to start a polling query without a polling interval.');
2230
2231 if (!this.ssrMode) {
2232 var info = this.pollingInfoByQueryId.get(queryId);
2233
2234 if (!info) {
2235 this.pollingInfoByQueryId.set(queryId, info = {});
2236 }
2237
2238 info.interval = pollInterval;
2239 info.options = (0, _tslib.__assign)({}, options, {
2240 fetchPolicy: 'network-only'
2241 });
2242
2243 var maybeFetch_1 = function () {
2244 var info = _this.pollingInfoByQueryId.get(queryId);
2245
2246 if (info) {
2247 if (_this.checkInFlight(queryId)) {
2248 poll_1();
2249 } else {
2250 _this.fetchQuery(queryId, info.options, FetchType.poll).then(poll_1, poll_1);
2251 }
2252 }
2253 };
2254
2255 var poll_1 = function () {
2256 var info = _this.pollingInfoByQueryId.get(queryId);
2257
2258 if (info) {
2259 clearTimeout(info.timeout);
2260 info.timeout = setTimeout(maybeFetch_1, info.interval);
2261 }
2262 };
2263
2264 if (listener) {
2265 this.addQueryListener(queryId, listener);
2266 }
2267
2268 poll_1();
2269 }
2270
2271 return queryId;
2272 };
2273
2274 QueryManager.prototype.stopPollingQuery = function (queryId) {
2275 this.pollingInfoByQueryId.delete(queryId);
2276 };
2277
2278 return QueryManager;
2279 }();
2280
2281 var DataStore = function () {
2282 function DataStore(initialCache) {
2283 this.cache = initialCache;
2284 }
2285
2286 DataStore.prototype.getCache = function () {
2287 return this.cache;
2288 };
2289
2290 DataStore.prototype.markQueryResult = function (result, document, variables, fetchMoreForQueryId, ignoreErrors) {
2291 if (ignoreErrors === void 0) {
2292 ignoreErrors = false;
2293 }
2294
2295 var writeWithErrors = !(0, _apolloUtilities.graphQLResultHasError)(result);
2296
2297 if (ignoreErrors && (0, _apolloUtilities.graphQLResultHasError)(result) && result.data) {
2298 writeWithErrors = true;
2299 }
2300
2301 if (!fetchMoreForQueryId && writeWithErrors) {
2302 this.cache.write({
2303 result: result.data,
2304 dataId: 'ROOT_QUERY',
2305 query: document,
2306 variables: variables
2307 });
2308 }
2309 };
2310
2311 DataStore.prototype.markSubscriptionResult = function (result, document, variables) {
2312 if (!(0, _apolloUtilities.graphQLResultHasError)(result)) {
2313 this.cache.write({
2314 result: result.data,
2315 dataId: 'ROOT_SUBSCRIPTION',
2316 query: document,
2317 variables: variables
2318 });
2319 }
2320 };
2321
2322 DataStore.prototype.markMutationInit = function (mutation) {
2323 var _this = this;
2324
2325 if (mutation.optimisticResponse) {
2326 var optimistic_1;
2327
2328 if (typeof mutation.optimisticResponse === 'function') {
2329 optimistic_1 = mutation.optimisticResponse(mutation.variables);
2330 } else {
2331 optimistic_1 = mutation.optimisticResponse;
2332 }
2333
2334 this.cache.recordOptimisticTransaction(function (c) {
2335 var orig = _this.cache;
2336 _this.cache = c;
2337
2338 try {
2339 _this.markMutationResult({
2340 mutationId: mutation.mutationId,
2341 result: {
2342 data: optimistic_1
2343 },
2344 document: mutation.document,
2345 variables: mutation.variables,
2346 updateQueries: mutation.updateQueries,
2347 update: mutation.update
2348 });
2349 } finally {
2350 _this.cache = orig;
2351 }
2352 }, mutation.mutationId);
2353 }
2354 };
2355
2356 DataStore.prototype.markMutationResult = function (mutation) {
2357 var _this = this;
2358
2359 if (!(0, _apolloUtilities.graphQLResultHasError)(mutation.result)) {
2360 var cacheWrites_1 = [{
2361 result: mutation.result.data,
2362 dataId: 'ROOT_MUTATION',
2363 query: mutation.document,
2364 variables: mutation.variables
2365 }];
2366 var updateQueries_1 = mutation.updateQueries;
2367
2368 if (updateQueries_1) {
2369 Object.keys(updateQueries_1).forEach(function (id) {
2370 var _a = updateQueries_1[id],
2371 query = _a.query,
2372 updater = _a.updater;
2373
2374 var _b = _this.cache.diff({
2375 query: query.document,
2376 variables: query.variables,
2377 returnPartialData: true,
2378 optimistic: false
2379 }),
2380 currentQueryResult = _b.result,
2381 complete = _b.complete;
2382
2383 if (complete) {
2384 var nextQueryResult = (0, _apolloUtilities.tryFunctionOrLogError)(function () {
2385 return updater(currentQueryResult, {
2386 mutationResult: mutation.result,
2387 queryName: (0, _apolloUtilities.getOperationName)(query.document) || undefined,
2388 queryVariables: query.variables
2389 });
2390 });
2391
2392 if (nextQueryResult) {
2393 cacheWrites_1.push({
2394 result: nextQueryResult,
2395 dataId: 'ROOT_QUERY',
2396 query: query.document,
2397 variables: query.variables
2398 });
2399 }
2400 }
2401 });
2402 }
2403
2404 this.cache.performTransaction(function (c) {
2405 cacheWrites_1.forEach(function (write) {
2406 return c.write(write);
2407 });
2408 var update = mutation.update;
2409
2410 if (update) {
2411 (0, _apolloUtilities.tryFunctionOrLogError)(function () {
2412 return update(c, mutation.result);
2413 });
2414 }
2415 });
2416 }
2417 };
2418
2419 DataStore.prototype.markMutationComplete = function (_a) {
2420 var mutationId = _a.mutationId,
2421 optimisticResponse = _a.optimisticResponse;
2422
2423 if (optimisticResponse) {
2424 this.cache.removeOptimistic(mutationId);
2425 }
2426 };
2427
2428 DataStore.prototype.markUpdateQueryResult = function (document, variables, newResult) {
2429 this.cache.write({
2430 result: newResult,
2431 dataId: 'ROOT_QUERY',
2432 variables: variables,
2433 query: document
2434 });
2435 };
2436
2437 DataStore.prototype.reset = function () {
2438 return this.cache.reset();
2439 };
2440
2441 return DataStore;
2442 }();
2443
2444 var version = "2.6.3";
2445 var hasSuggestedDevtools = false;
2446
2447 var ApolloClient = function () {
2448 function ApolloClient(options) {
2449 var _this = this;
2450
2451 this.defaultOptions = {};
2452 this.resetStoreCallbacks = [];
2453 this.clearStoreCallbacks = [];
2454 var cache = options.cache,
2455 _a = options.ssrMode,
2456 ssrMode = _a === void 0 ? false : _a,
2457 _b = options.ssrForceFetchDelay,
2458 ssrForceFetchDelay = _b === void 0 ? 0 : _b,
2459 connectToDevTools = options.connectToDevTools,
2460 _c = options.queryDeduplication,
2461 queryDeduplication = _c === void 0 ? true : _c,
2462 defaultOptions = options.defaultOptions,
2463 _d = options.assumeImmutableResults,
2464 assumeImmutableResults = _d === void 0 ? false : _d,
2465 resolvers = options.resolvers,
2466 typeDefs = options.typeDefs,
2467 fragmentMatcher = options.fragmentMatcher,
2468 clientAwarenessName = options.name,
2469 clientAwarenessVersion = options.version;
2470 var link = options.link;
2471
2472 if (!link && resolvers) {
2473 link = _apolloLink.ApolloLink.empty();
2474 }
2475
2476 if (!link || !cache) {
2477 throw process.env.NODE_ENV === "production" ? new _tsInvariant.InvariantError(1) : new _tsInvariant.InvariantError("In order to initialize Apollo Client, you must specify 'link' and 'cache' properties in the options object.\n" + "These options are part of the upgrade requirements when migrating from Apollo Client 1.x to Apollo Client 2.x.\n" + "For more information, please visit: https://www.apollographql.com/docs/tutorial/client.html#apollo-client-setup");
2478 }
2479
2480 this.link = link;
2481 this.cache = cache;
2482 this.store = new DataStore(cache);
2483 this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
2484 this.queryDeduplication = queryDeduplication;
2485 this.defaultOptions = defaultOptions || {};
2486 this.typeDefs = typeDefs;
2487
2488 if (ssrForceFetchDelay) {
2489 setTimeout(function () {
2490 return _this.disableNetworkFetches = false;
2491 }, ssrForceFetchDelay);
2492 }
2493
2494 this.watchQuery = this.watchQuery.bind(this);
2495 this.query = this.query.bind(this);
2496 this.mutate = this.mutate.bind(this);
2497 this.resetStore = this.resetStore.bind(this);
2498 this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);
2499 var defaultConnectToDevTools = process.env.NODE_ENV !== 'production' && typeof window !== 'undefined' && !window.__APOLLO_CLIENT__;
2500
2501 if (typeof connectToDevTools === 'undefined' ? defaultConnectToDevTools : connectToDevTools && typeof window !== 'undefined') {
2502 window.__APOLLO_CLIENT__ = this;
2503 }
2504
2505 if (!hasSuggestedDevtools && process.env.NODE_ENV !== 'production') {
2506 hasSuggestedDevtools = true;
2507
2508 if (typeof window !== 'undefined' && window.document && window.top === window.self) {
2509 if (typeof window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
2510 if (window.navigator && window.navigator.userAgent && window.navigator.userAgent.indexOf('Chrome') > -1) {
2511 console.debug('Download the Apollo DevTools ' + 'for a better development experience: ' + 'https://chrome.google.com/webstore/detail/apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm');
2512 }
2513 }
2514 }
2515 }
2516
2517 this.version = version;
2518 this.localState = new LocalState({
2519 cache: cache,
2520 client: this,
2521 resolvers: resolvers,
2522 fragmentMatcher: fragmentMatcher
2523 });
2524 this.queryManager = new QueryManager({
2525 link: this.link,
2526 store: this.store,
2527 queryDeduplication: queryDeduplication,
2528 ssrMode: ssrMode,
2529 clientAwareness: {
2530 name: clientAwarenessName,
2531 version: clientAwarenessVersion
2532 },
2533 localState: this.localState,
2534 assumeImmutableResults: assumeImmutableResults,
2535 onBroadcast: function () {
2536 if (_this.devToolsHookCb) {
2537 _this.devToolsHookCb({
2538 action: {},
2539 state: {
2540 queries: _this.queryManager.queryStore.getStore(),
2541 mutations: _this.queryManager.mutationStore.getStore()
2542 },
2543 dataWithOptimisticResults: _this.cache.extract(true)
2544 });
2545 }
2546 }
2547 });
2548 }
2549
2550 ApolloClient.prototype.stop = function () {
2551 this.queryManager.stop();
2552 };
2553
2554 ApolloClient.prototype.watchQuery = function (options) {
2555 if (this.defaultOptions.watchQuery) {
2556 options = (0, _tslib.__assign)({}, this.defaultOptions.watchQuery, options);
2557 }
2558
2559 if (this.disableNetworkFetches && (options.fetchPolicy === 'network-only' || options.fetchPolicy === 'cache-and-network')) {
2560 options = (0, _tslib.__assign)({}, options, {
2561 fetchPolicy: 'cache-first'
2562 });
2563 }
2564
2565 return this.queryManager.watchQuery(options);
2566 };
2567
2568 ApolloClient.prototype.query = function (options) {
2569 if (this.defaultOptions.query) {
2570 options = (0, _tslib.__assign)({}, this.defaultOptions.query, options);
2571 }
2572
2573 process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(options.fetchPolicy !== 'cache-and-network', 2) : (0, _tsInvariant.invariant)(options.fetchPolicy !== 'cache-and-network', 'The cache-and-network fetchPolicy does not work with client.query, because ' + 'client.query can only return a single result. Please use client.watchQuery ' + 'to receive multiple results from the cache and the network, or consider ' + 'using a different fetchPolicy, such as cache-first or network-only.');
2574
2575 if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') {
2576 options = (0, _tslib.__assign)({}, options, {
2577 fetchPolicy: 'cache-first'
2578 });
2579 }
2580
2581 return this.queryManager.query(options);
2582 };
2583
2584 ApolloClient.prototype.mutate = function (options) {
2585 if (this.defaultOptions.mutate) {
2586 options = (0, _tslib.__assign)({}, this.defaultOptions.mutate, options);
2587 }
2588
2589 return this.queryManager.mutate(options);
2590 };
2591
2592 ApolloClient.prototype.subscribe = function (options) {
2593 return this.queryManager.startGraphQLSubscription(options);
2594 };
2595
2596 ApolloClient.prototype.readQuery = function (options, optimistic) {
2597 if (optimistic === void 0) {
2598 optimistic = false;
2599 }
2600
2601 return this.cache.readQuery(options, optimistic);
2602 };
2603
2604 ApolloClient.prototype.readFragment = function (options, optimistic) {
2605 if (optimistic === void 0) {
2606 optimistic = false;
2607 }
2608
2609 return this.cache.readFragment(options, optimistic);
2610 };
2611
2612 ApolloClient.prototype.writeQuery = function (options) {
2613 var result = this.cache.writeQuery(options);
2614 this.queryManager.broadcastQueries();
2615 return result;
2616 };
2617
2618 ApolloClient.prototype.writeFragment = function (options) {
2619 var result = this.cache.writeFragment(options);
2620 this.queryManager.broadcastQueries();
2621 return result;
2622 };
2623
2624 ApolloClient.prototype.writeData = function (options) {
2625 var result = this.cache.writeData(options);
2626 this.queryManager.broadcastQueries();
2627 return result;
2628 };
2629
2630 ApolloClient.prototype.__actionHookForDevTools = function (cb) {
2631 this.devToolsHookCb = cb;
2632 };
2633
2634 ApolloClient.prototype.__requestRaw = function (payload) {
2635 return (0, _apolloLink.execute)(this.link, payload);
2636 };
2637
2638 ApolloClient.prototype.initQueryManager = function () {
2639 process.env.NODE_ENV === "production" || _tsInvariant.invariant.warn('Calling the initQueryManager method is no longer necessary, ' + 'and it will be removed from ApolloClient in version 3.0.');
2640 return this.queryManager;
2641 };
2642
2643 ApolloClient.prototype.resetStore = function () {
2644 var _this = this;
2645
2646 return Promise.resolve().then(function () {
2647 return _this.queryManager.clearStore();
2648 }).then(function () {
2649 return Promise.all(_this.resetStoreCallbacks.map(function (fn) {
2650 return fn();
2651 }));
2652 }).then(function () {
2653 return _this.reFetchObservableQueries();
2654 });
2655 };
2656
2657 ApolloClient.prototype.clearStore = function () {
2658 var _this = this;
2659
2660 return Promise.resolve().then(function () {
2661 return _this.queryManager.clearStore();
2662 }).then(function () {
2663 return Promise.all(_this.clearStoreCallbacks.map(function (fn) {
2664 return fn();
2665 }));
2666 });
2667 };
2668
2669 ApolloClient.prototype.onResetStore = function (cb) {
2670 var _this = this;
2671
2672 this.resetStoreCallbacks.push(cb);
2673 return function () {
2674 _this.resetStoreCallbacks = _this.resetStoreCallbacks.filter(function (c) {
2675 return c !== cb;
2676 });
2677 };
2678 };
2679
2680 ApolloClient.prototype.onClearStore = function (cb) {
2681 var _this = this;
2682
2683 this.clearStoreCallbacks.push(cb);
2684 return function () {
2685 _this.clearStoreCallbacks = _this.clearStoreCallbacks.filter(function (c) {
2686 return c !== cb;
2687 });
2688 };
2689 };
2690
2691 ApolloClient.prototype.reFetchObservableQueries = function (includeStandby) {
2692 return this.queryManager.reFetchObservableQueries(includeStandby);
2693 };
2694
2695 ApolloClient.prototype.extract = function (optimistic) {
2696 return this.cache.extract(optimistic);
2697 };
2698
2699 ApolloClient.prototype.restore = function (serializedState) {
2700 return this.cache.restore(serializedState);
2701 };
2702
2703 ApolloClient.prototype.addResolvers = function (resolvers) {
2704 this.localState.addResolvers(resolvers);
2705 };
2706
2707 ApolloClient.prototype.setResolvers = function (resolvers) {
2708 this.localState.setResolvers(resolvers);
2709 };
2710
2711 ApolloClient.prototype.getResolvers = function () {
2712 return this.localState.getResolvers();
2713 };
2714
2715 ApolloClient.prototype.setLocalStateFragmentMatcher = function (fragmentMatcher) {
2716 this.localState.setFragmentMatcher(fragmentMatcher);
2717 };
2718
2719 return ApolloClient;
2720 }();
2721
2722 _exports.ApolloClient = ApolloClient;
2723 var _default = ApolloClient;
2724
2725 _exports.default = _default;
2726});