text: 'use strict';
  
  Object.defineProperty(exports, '__esModule', { value: true });
  
  function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  
  var tslib = require('tslib');
  var tsInvariant = require('ts-invariant');
  var core = require('../link/core');
  var utilities = require('../utilities');
  var http = require('../link/http');
  var equality = require('@wry/equality');
  var errors = require('../errors');
  var visitor = require('graphql/language/visitor');
  var cache = require('../cache');
  var utils = require('../link/utils');
  var gql = _interopDefault(require('graphql-tag'));
  
  var version = 'local';
  
  var MutationStore = (function () {
      function MutationStore() {
          this.store = {};
      }
      MutationStore.prototype.getStore = function () {
          return this.store;
      };
      MutationStore.prototype.get = function (mutationId) {
          return this.store[mutationId];
      };
      MutationStore.prototype.initMutation = function (mutationId, mutation, variables) {
          this.store[mutationId] = {
              mutation: mutation,
              variables: variables || {},
              loading: true,
              error: null,
          };
      };
      MutationStore.prototype.markMutationError = function (mutationId, error) {
          var mutation = this.store[mutationId];
          if (mutation) {
              mutation.loading = false;
              mutation.error = error;
          }
      };
      MutationStore.prototype.markMutationResult = function (mutationId) {
          var mutation = this.store[mutationId];
          if (mutation) {
              mutation.loading = false;
              mutation.error = null;
          }
      };
      MutationStore.prototype.reset = function () {
          this.store = {};
      };
      return MutationStore;
  }());
  
  (function (NetworkStatus) {
      NetworkStatus[NetworkStatus["loading"] = 1] = "loading";
      NetworkStatus[NetworkStatus["setVariables"] = 2] = "setVariables";
      NetworkStatus[NetworkStatus["fetchMore"] = 3] = "fetchMore";
      NetworkStatus[NetworkStatus["refetch"] = 4] = "refetch";
      NetworkStatus[NetworkStatus["poll"] = 6] = "poll";
      NetworkStatus[NetworkStatus["ready"] = 7] = "ready";
      NetworkStatus[NetworkStatus["error"] = 8] = "error";
  })(exports.NetworkStatus || (exports.NetworkStatus = {}));
  function isNetworkRequestInFlight(networkStatus) {
      return networkStatus ? networkStatus < 7 : false;
  }
  
  var Reobserver = (function () {
      function Reobserver(observer, options, fetch, shouldFetch) {
          this.observer = observer;
          this.options = options;
          this.fetch = fetch;
          this.shouldFetch = shouldFetch;
      }
      Reobserver.prototype.reobserve = function (newOptions, newNetworkStatus) {
          if (newOptions) {
              this.updateOptions(newOptions);
          }
          else {
              this.updatePolling();
          }
          var concast = this.fetch(this.options, newNetworkStatus);
          if (this.concast) {
              this.concast.removeObserver(this.observer, true);
          }
          concast.addObserver(this.observer);
          return (this.concast = concast).promise;
      };
      Reobserver.prototype.updateOptions = function (newOptions) {
          Object.assign(this.options, utilities.compact(newOptions));
          this.updatePolling();
          return this;
      };
      Reobserver.prototype.stop = function () {
          if (this.concast) {
              this.concast.removeObserver(this.observer);
              delete this.concast;
          }
          if (this.pollingInfo) {
              clearTimeout(this.pollingInfo.timeout);
              this.options.pollInterval = 0;
              this.updatePolling();
          }
      };
      Reobserver.prototype.updatePolling = function () {
          var _this = this;
          var _a = this, pollingInfo = _a.pollingInfo, pollInterval = _a.options.pollInterval;
          if (!pollInterval) {
              if (pollingInfo) {
                  clearTimeout(pollingInfo.timeout);
                  delete this.pollingInfo;
              }
              return;
          }
          if (pollingInfo &&
              pollingInfo.interval === pollInterval) {
              return;
          }
          process.env.NODE_ENV === "production" ? tsInvariant.invariant(pollInterval, 20) : tsInvariant.invariant(pollInterval, 'Attempted to start a polling query without a polling interval.');
          if (this.shouldFetch === false) {
              return;
          }
          var info = pollingInfo || (this.pollingInfo = {});
          info.interval = pollInterval;
          var maybeFetch = function () {
              if (_this.pollingInfo) {
                  if (_this.shouldFetch && _this.shouldFetch()) {
                      _this.reobserve({
                          fetchPolicy: "network-only",
                          nextFetchPolicy: _this.options.fetchPolicy || "cache-first",
                      }, exports.NetworkStatus.poll).then(poll, poll);
                  }
                  else {
                      poll();
                  }
              }
          };
          var poll = function () {
              var info = _this.pollingInfo;
              if (info) {
                  clearTimeout(info.timeout);
                  info.timeout = setTimeout(maybeFetch, info.interval);
              }
          };
          poll();
      };
      return Reobserver;
  }());
  
  var warnedAboutUpdateQuery = false;
  var ObservableQuery = (function (_super) {
      tslib.__extends(ObservableQuery, _super);
      function ObservableQuery(_a) {
          var queryManager = _a.queryManager, queryInfo = _a.queryInfo, options = _a.options;
          var _this = _super.call(this, function (observer) {
              return _this.onSubscribe(observer);
          }) || this;
          _this.observers = new Set();
          _this.subscriptions = new Set();
          _this.observer = {
              next: function (result) {
                  if (_this.lastError || _this.isDifferentFromLastResult(result)) {
                      _this.updateLastResult(result);
                      utilities.iterateObserversSafely(_this.observers, 'next', result);
                  }
              },
              error: function (error) {
                  _this.updateLastResult(tslib.__assign(tslib.__assign({}, _this.lastResult), { error: error, errors: error.graphQLErrors, networkStatus: exports.NetworkStatus.error, loading: false }));
                  utilities.iterateObserversSafely(_this.observers, 'error', _this.lastError = error);
              },
          };
          _this.isTornDown = false;
          _this.options = options;
          _this.queryId = queryManager.generateQueryId();
          var opDef = utilities.getOperationDefinition(options.query);
          _this.queryName = opDef && opDef.name && opDef.name.value;
          _this.queryManager = queryManager;
          _this.queryInfo = queryInfo;
          return _this;
      }
      Object.defineProperty(ObservableQuery.prototype, "variables", {
          get: function () {
              return this.options.variables;
          },
          enumerable: false,
          configurable: true
      });
      ObservableQuery.prototype.result = function () {
          var _this = this;
          return new Promise(function (resolve, reject) {
              var observer = {
                  next: function (result) {
                      resolve(result);
                      _this.observers.delete(observer);
                      if (!_this.observers.size) {
                          _this.queryManager.removeQuery(_this.queryId);
                      }
                      setTimeout(function () {
                          subscription.unsubscribe();
                      }, 0);
                  },
                  error: reject,
              };
              var subscription = _this.subscribe(observer);
          });
      };
      ObservableQuery.prototype.getCurrentResult = function (saveAsLastResult) {
          if (saveAsLastResult === void 0) { saveAsLastResult = true; }
          var lastResult = this.lastResult;
          var networkStatus = this.queryInfo.networkStatus ||
              (lastResult && lastResult.networkStatus) ||
              exports.NetworkStatus.ready;
          var result = tslib.__assign(tslib.__assign({}, lastResult), { loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus });
          if (this.isTornDown) {
              return result;
          }
          var _a = this.options.fetchPolicy, fetchPolicy = _a === void 0 ? 'cache-first' : _a;
          if (fetchPolicy === 'no-cache' ||
              fetchPolicy === 'network-only') {
              delete result.partial;
          }
          else if (!result.data ||
              !this.queryManager.transform(this.options.query).hasForcedResolvers) {
              var diff = this.queryInfo.getDiff();
              result.data = (diff.complete ||
                  this.options.returnPartialData) ? diff.result : void 0;
              if (diff.complete) {
                  if (result.networkStatus === exports.NetworkStatus.loading &&
                      (fetchPolicy === 'cache-first' ||
                          fetchPolicy === 'cache-only')) {
                      result.networkStatus = exports.NetworkStatus.ready;
                      result.loading = false;
                  }
                  delete result.partial;
              }
              else {
                  result.partial = true;
              }
          }
          if (saveAsLastResult) {
              this.updateLastResult(result);
          }
          return result;
      };
      ObservableQuery.prototype.isDifferentFromLastResult = function (newResult) {
          return !equality.equal(this.lastResultSnapshot, newResult);
      };
      ObservableQuery.prototype.getLastResult = function () {
          return this.lastResult;
      };
      ObservableQuery.prototype.getLastError = function () {
          return this.lastError;
      };
      ObservableQuery.prototype.resetLastResults = function () {
          delete this.lastResult;
          delete this.lastResultSnapshot;
          delete this.lastError;
          this.isTornDown = false;
      };
      ObservableQuery.prototype.resetQueryStoreErrors = function () {
          this.queryManager.resetErrors(this.queryId);
      };
      ObservableQuery.prototype.refetch = function (variables) {
          var reobserveOptions = {
              pollInterval: 0,
          };
          var fetchPolicy = this.options.fetchPolicy;
          if (fetchPolicy !== 'no-cache' &&
              fetchPolicy !== 'cache-and-network') {
              reobserveOptions.fetchPolicy = 'network-only';
              reobserveOptions.nextFetchPolicy = fetchPolicy || "cache-first";
          }
          if (variables && !equality.equal(this.options.variables, variables)) {
              reobserveOptions.variables = this.options.variables = tslib.__assign(tslib.__assign({}, this.options.variables), variables);
          }
          return this.newReobserver(false).reobserve(reobserveOptions, exports.NetworkStatus.refetch);
      };
      ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {
          var _this = this;
          var combinedOptions = tslib.__assign(tslib.__assign({}, (fetchMoreOptions.query ? fetchMoreOptions : tslib.__assign(tslib.__assign(tslib.__assign({}, this.options), fetchMoreOptions), { variables: tslib.__assign(tslib.__assign({}, this.options.variables), fetchMoreOptions.variables) }))), { fetchPolicy: "no-cache" });
          var qid = this.queryManager.generateQueryId();
          if (combinedOptions.notifyOnNetworkStatusChange) {
              this.queryInfo.networkStatus = exports.NetworkStatus.fetchMore;
              this.observe();
          }
          return this.queryManager.fetchQuery(qid, combinedOptions, exports.NetworkStatus.fetchMore).then(function (fetchMoreResult) {
              var data = fetchMoreResult.data;
              var updateQuery = fetchMoreOptions.updateQuery;
              if (updateQuery) {
                  if (process.env.NODE_ENV !== "production" &&
                      !warnedAboutUpdateQuery) {
                      process.env.NODE_ENV === "production" || tsInvariant.invariant.warn("The updateQuery callback for fetchMore is deprecated, and will be removed\nin the next major version of Apollo Client.\n\nPlease convert updateQuery functions to field policies with appropriate\nread and merge functions, or use/adapt a helper function (such as\nconcatPagination, offsetLimitPagination, or relayStylePagination) from\n@apollo/client/utilities.\n\nThe field policy system handles pagination more effectively than a\nhand-written updateQuery function, and you only need to define the policy\nonce, rather than every time you call fetchMore.");
                      warnedAboutUpdateQuery = true;
                  }
                  _this.updateQuery(function (previous) { return updateQuery(previous, {
                      fetchMoreResult: data,
                      variables: combinedOptions.variables,
                  }); });
              }
              else {
                  _this.queryManager.cache.writeQuery({
                      query: combinedOptions.query,
                      variables: combinedOptions.variables,
                      data: data,
                  });
              }
              return fetchMoreResult;
          }).finally(function () {
              _this.queryManager.stopQuery(qid);
              _this.reobserve();
          });
      };
      ObservableQuery.prototype.subscribeToMore = function (options) {
          var _this = this;
          var subscription = this.queryManager
              .startGraphQLSubscription({
              query: options.document,
              variables: options.variables,
              context: options.context,
          })
              .subscribe({
              next: function (subscriptionData) {
                  var updateQuery = options.updateQuery;
                  if (updateQuery) {
                      _this.updateQuery(function (previous, _a) {
                          var variables = _a.variables;
                          return updateQuery(previous, {
                              subscriptionData: subscriptionData,
                              variables: variables,
                          });
                      });
                  }
              },
              error: function (err) {
                  if (options.onError) {
                      options.onError(err);
                      return;
                  }
                  process.env.NODE_ENV === "production" || tsInvariant.invariant.error('Unhandled GraphQL subscription error', err);
              },
          });
          this.subscriptions.add(subscription);
          return function () {
              if (_this.subscriptions.delete(subscription)) {
                  subscription.unsubscribe();
              }
          };
      };
      ObservableQuery.prototype.setOptions = function (newOptions) {
          return this.reobserve(newOptions);
      };
      ObservableQuery.prototype.setVariables = function (variables) {
          if (equality.equal(this.variables, variables)) {
              return this.observers.size
                  ? this.result()
                  : Promise.resolve();
          }
          this.options.variables = variables;
          if (!this.observers.size) {
              return Promise.resolve();
          }
          var _a = this.options.fetchPolicy, fetchPolicy = _a === void 0 ? 'cache-first' : _a;
          var reobserveOptions = {
              fetchPolicy: fetchPolicy,
              variables: variables,
          };
          if (fetchPolicy !== 'cache-first' &&
              fetchPolicy !== 'no-cache' &&
              fetchPolicy !== 'network-only') {
              reobserveOptions.fetchPolicy = 'cache-and-network';
              reobserveOptions.nextFetchPolicy = fetchPolicy;
          }
          return this.reobserve(reobserveOptions, exports.NetworkStatus.setVariables);
      };
      ObservableQuery.prototype.updateQuery = function (mapFn) {
          var _a;
          var queryManager = this.queryManager;
          var result = queryManager.cache.diff({
              query: this.options.query,
              variables: this.variables,
              previousResult: (_a = this.lastResult) === null || _a === void 0 ? void 0 : _a.data,
              returnPartialData: true,
              optimistic: false,
          }).result;
          var newResult = mapFn(result, {
              variables: this.variables,
          });
          if (newResult) {
              queryManager.cache.writeQuery({
                  query: this.options.query,
                  data: newResult,
                  variables: this.variables,
              });
              queryManager.broadcastQueries();
          }
      };
      ObservableQuery.prototype.startPolling = function (pollInterval) {
          this.getReobserver().updateOptions({ pollInterval: pollInterval });
      };
      ObservableQuery.prototype.stopPolling = function () {
          if (this.reobserver) {
              this.reobserver.updateOptions({ pollInterval: 0 });
          }
      };
      ObservableQuery.prototype.updateLastResult = function (newResult) {
          var previousResult = this.lastResult;
          this.lastResult = newResult;
          this.lastResultSnapshot = this.queryManager.assumeImmutableResults
              ? newResult
              : utilities.cloneDeep(newResult);
          if (!utilities.isNonEmptyArray(newResult.errors)) {
              delete this.lastError;
          }
          return previousResult;
      };
      ObservableQuery.prototype.onSubscribe = function (observer) {
          var _this = this;
          if (observer === this.observer) {
              return function () { };
          }
          try {
              var subObserver = observer._subscription._observer;
              if (subObserver && !subObserver.error) {
                  subObserver.error = defaultSubscriptionObserverErrorCallback;
              }
          }
          catch (_a) { }
          var first = !this.observers.size;
          this.observers.add(observer);
          if (this.lastError) {
              observer.error && observer.error(this.lastError);
          }
          else if (this.lastResult) {
              observer.next && observer.next(this.lastResult);
          }
          if (first) {
              this.reobserve().catch(function (_) {
              });
          }
          return function () {
              if (_this.observers.delete(observer) && !_this.observers.size) {
                  _this.tearDownQuery();
              }
          };
      };
      ObservableQuery.prototype.getReobserver = function () {
          return this.reobserver || (this.reobserver = this.newReobserver(true));
      };
      ObservableQuery.prototype.newReobserver = function (shareOptions) {
          var _this = this;
          var _a = this, queryManager = _a.queryManager, queryId = _a.queryId;
          queryManager.setObservableQuery(this);
          return new Reobserver(this.observer, shareOptions ? this.options : tslib.__assign({}, this.options), function (currentOptions, newNetworkStatus) {
              queryManager.setObservableQuery(_this);
              return queryManager.fetchQueryObservable(queryId, currentOptions, newNetworkStatus);
          }, !queryManager.ssrMode && (function () { return !isNetworkRequestInFlight(_this.queryInfo.networkStatus); }));
      };
      ObservableQuery.prototype.reobserve = function (newOptions, newNetworkStatus) {
          this.isTornDown = false;
          return this.getReobserver().reobserve(newOptions, newNetworkStatus);
      };
      ObservableQuery.prototype.observe = function () {
          this.observer.next(this.getCurrentResult(false));
      };
      ObservableQuery.prototype.tearDownQuery = function () {
          var queryManager = this.queryManager;
          if (this.reobserver) {
              this.reobserver.stop();
              delete this.reobserver;
          }
          this.isTornDown = true;
          this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });
          this.subscriptions.clear();
          queryManager.stopQuery(this.queryId);
          this.observers.clear();
      };
      return ObservableQuery;
  }(utilities.Observable));
  function defaultSubscriptionObserverErrorCallback(error) {
      process.env.NODE_ENV === "production" || tsInvariant.invariant.error('Unhandled error', error.message, error.stack);
  }
  
  var LocalState = (function () {
      function LocalState(_a) {
          var cache = _a.cache, client = _a.client, resolvers = _a.resolvers, fragmentMatcher = _a.fragmentMatcher;
          this.cache = cache;
          if (client) {
              this.client = client;
          }
          if (resolvers) {
              this.addResolvers(resolvers);
          }
          if (fragmentMatcher) {
              this.setFragmentMatcher(fragmentMatcher);
          }
      }
      LocalState.prototype.addResolvers = function (resolvers) {
          var _this = this;
          this.resolvers = this.resolvers || {};
          if (Array.isArray(resolvers)) {
              resolvers.forEach(function (resolverGroup) {
                  _this.resolvers = utilities.mergeDeep(_this.resolvers, resolverGroup);
              });
          }
          else {
              this.resolvers = utilities.mergeDeep(this.resolvers, resolvers);
          }
      };
      LocalState.prototype.setResolvers = function (resolvers) {
          this.resolvers = {};
          this.addResolvers(resolvers);
      };
      LocalState.prototype.getResolvers = function () {
          return this.resolvers || {};
      };
      LocalState.prototype.runResolvers = function (_a) {
          var document = _a.document, remoteResult = _a.remoteResult, context = _a.context, variables = _a.variables, _b = _a.onlyRunForcedResolvers, onlyRunForcedResolvers = _b === void 0 ? false : _b;
          return tslib.__awaiter(this, void 0, void 0, function () {
              return tslib.__generator(this, function (_c) {
                  if (document) {
                      return [2, this.resolveDocument(document, remoteResult.data, context, variables, this.fragmentMatcher, onlyRunForcedResolvers).then(function (localResult) { return (tslib.__assign(tslib.__assign({}, remoteResult), { data: localResult.result })); })];
                  }
                  return [2, remoteResult];
              });
          });
      };
      LocalState.prototype.setFragmentMatcher = function (fragmentMatcher) {
          this.fragmentMatcher = fragmentMatcher;
      };
      LocalState.prototype.getFragmentMatcher = function () {
          return this.fragmentMatcher;
      };
      LocalState.prototype.clientQuery = function (document) {
          if (utilities.hasDirectives(['client'], document)) {
              if (this.resolvers) {
                  return document;
              }
          }
          return null;
      };
      LocalState.prototype.serverQuery = function (document) {
          return utilities.removeClientSetsFromDocument(document);
      };
      LocalState.prototype.prepareContext = function (context) {
          var cache = this.cache;
          return tslib.__assign(tslib.__assign({}, context), { cache: cache,
              getCacheKey: function (obj) {
                  return cache.identify(obj);
              } });
      };
      LocalState.prototype.addExportedVariables = function (document, variables, context) {
          if (variables === void 0) { variables = {}; }
          if (context === void 0) { context = {}; }
          return tslib.__awaiter(this, void 0, void 0, function () {
              return tslib.__generator(this, function (_a) {
                  if (document) {
                      return [2, this.resolveDocument(document, this.buildRootValueFromCache(document, variables) || {}, this.prepareContext(context), variables).then(function (data) { return (tslib.__assign(tslib.__assign({}, variables), data.exportedVariables)); })];
                  }
                  return [2, tslib.__assign({}, variables)];
              });
          });
      };
      LocalState.prototype.shouldForceResolvers = function (document) {
          var forceResolvers = false;
          visitor.visit(document, {
              Directive: {
                  enter: function (node) {
                      if (node.name.value === 'client' && node.arguments) {
                          forceResolvers = node.arguments.some(function (arg) {
                              return arg.name.value === 'always' &&
                                  arg.value.kind === 'BooleanValue' &&
                                  arg.value.value === true;
                          });
                          if (forceResolvers) {
                              return visitor.BREAK;
                          }
                      }
                  },
              },
          });
          return forceResolvers;
      };
      LocalState.prototype.buildRootValueFromCache = function (document, variables) {
          return this.cache.diff({
              query: utilities.buildQueryFromSelectionSet(document),
              variables: variables,
              returnPartialData: true,
              optimistic: false,
          }).result;
      };
      LocalState.prototype.resolveDocument = function (document, rootValue, context, variables, fragmentMatcher, onlyRunForcedResolvers) {
          if (context === void 0) { context = {}; }
          if (variables === void 0) { variables = {}; }
          if (fragmentMatcher === void 0) { fragmentMatcher = function () { return true; }; }
          if (onlyRunForcedResolvers === void 0) { onlyRunForcedResolvers = false; }
          return tslib.__awaiter(this, void 0, void 0, function () {
              var mainDefinition, fragments, fragmentMap, definitionOperation, defaultOperationType, _a, cache, client, execContext;
              return tslib.__generator(this, function (_b) {
                  mainDefinition = utilities.getMainDefinition(document);
                  fragments = utilities.getFragmentDefinitions(document);
                  fragmentMap = utilities.createFragmentMap(fragments);
                  definitionOperation = mainDefinition
                      .operation;
                  defaultOperationType = definitionOperation
                      ? definitionOperation.charAt(0).toUpperCase() +
                          definitionOperation.slice(1)
                      : 'Query';
                  _a = this, cache = _a.cache, client = _a.client;
                  execContext = {
                      fragmentMap: fragmentMap,
                      context: tslib.__assign(tslib.__assign({}, context), { cache: cache,
                          client: client }),
                      variables: variables,
                      fragmentMatcher: fragmentMatcher,
                      defaultOperationType: defaultOperationType,
                      exportedVariables: {},
                      onlyRunForcedResolvers: onlyRunForcedResolvers,
                  };
                  return [2, this.resolveSelectionSet(mainDefinition.selectionSet, rootValue, execContext).then(function (result) { return ({
                          result: result,
                          exportedVariables: execContext.exportedVariables,
                      }); })];
              });
          });
      };
      LocalState.prototype.resolveSelectionSet = function (selectionSet, rootValue, execContext) {
          return tslib.__awaiter(this, void 0, void 0, function () {
              var fragmentMap, context, variables, resultsToMerge, execute;
              var _this = this;
              return tslib.__generator(this, function (_a) {
                  fragmentMap = execContext.fragmentMap, context = execContext.context, variables = execContext.variables;
                  resultsToMerge = [rootValue];
                  execute = function (selection) { return tslib.__awaiter(_this, void 0, void 0, function () {
                      var fragment, typeCondition;
                      return tslib.__generator(this, function (_a) {
                          if (!utilities.shouldInclude(selection, variables)) {
                              return [2];
                          }
                          if (utilities.isField(selection)) {
                              return [2, this.resolveField(selection, rootValue, execContext).then(function (fieldResult) {
                                      var _a;
                                      if (typeof fieldResult !== 'undefined') {
                                          resultsToMerge.push((_a = {},
                                              _a[utilities.resultKeyNameFromField(selection)] = fieldResult,
                                              _a));
                                      }
                                  })];
                          }
                          if (utilities.isInlineFragment(selection)) {
                              fragment = selection;
                          }
                          else {
                              fragment = fragmentMap[selection.name.value];
                              process.env.NODE_ENV === "production" ? tsInvariant.invariant(fragment, 11) : tsInvariant.invariant(fragment, "No fragment named " + selection.name.value);
                          }
                          if (fragment && fragment.typeCondition) {
                              typeCondition = fragment.typeCondition.name.value;
                              if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {
                                  return [2, this.resolveSelectionSet(fragment.selectionSet, rootValue, execContext).then(function (fragmentResult) {
                                          resultsToMerge.push(fragmentResult);
                                      })];
                              }
                          }
                          return [2];
                      });
                  }); };
                  return [2, Promise.all(selectionSet.selections.map(execute)).then(function () {
                          return utilities.mergeDeepArray(resultsToMerge);
                      })];
              });
          });
      };
      LocalState.prototype.resolveField = function (field, rootValue, execContext) {
          return tslib.__awaiter(this, void 0, void 0, function () {
              var variables, fieldName, aliasedFieldName, aliasUsed, defaultResult, resultPromise, resolverType, resolverMap, resolve;
              var _this = this;
              return tslib.__generator(this, function (_a) {
                  variables = execContext.variables;
                  fieldName = field.name.value;
                  aliasedFieldName = utilities.resultKeyNameFromField(field);
                  aliasUsed = fieldName !== aliasedFieldName;
                  defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];
                  resultPromise = Promise.resolve(defaultResult);
                  if (!execContext.onlyRunForcedResolvers ||
                      this.shouldForceResolvers(field)) {
                      resolverType = rootValue.__typename || execContext.defaultOperationType;
                      resolverMap = this.resolvers && this.resolvers[resolverType];
                      if (resolverMap) {
                          resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];
                          if (resolve) {
                              resultPromise = Promise.resolve(cache.cacheSlot.withValue(this.cache, resolve, [
                                  rootValue,
                                  utilities.argumentsObjectFromField(field, variables),
                                  execContext.context,
                                  { field: field, fragmentMap: execContext.fragmentMap },
                              ]));
                          }
                      }
                  }
                  return [2, resultPromise.then(function (result) {
                          if (result === void 0) { result = defaultResult; }
                          if (field.directives) {
                              field.directives.forEach(function (directive) {
                                  if (directive.name.value === 'export' && directive.arguments) {
                                      directive.arguments.forEach(function (arg) {
                                          if (arg.name.value === 'as' && arg.value.kind === 'StringValue') {
                                              execContext.exportedVariables[arg.value.value] = result;
                                          }
                                      });
                                  }
                              });
                          }
                          if (!field.selectionSet) {
                              return result;
                          }
                          if (result == null) {
                              return result;
                          }
                          if (Array.isArray(result)) {
                              return _this.resolveSubSelectedArray(field, result, execContext);
                          }
                          if (field.selectionSet) {
                              return _this.resolveSelectionSet(field.selectionSet, result, execContext);
                          }
                      })];
              });
          });
      };
      LocalState.prototype.resolveSubSelectedArray = function (field, result, execContext) {
          var _this = this;
          return Promise.all(result.map(function (item) {
              if (item === null) {
                  return null;
              }
              if (Array.isArray(item)) {
                  return _this.resolveSubSelectedArray(field, item, execContext);
              }
              if (field.selectionSet) {
                  return _this.resolveSelectionSet(field.selectionSet, item, execContext);
              }
          }));
      };
      return LocalState;
  }());
  
  var destructiveMethodCounts = new (utilities.canUseWeakMap ? WeakMap : Map)();
  function wrapDestructiveCacheMethod(cache, methodName) {
      var original = cache[methodName];
      if (typeof original === "function") {
          cache[methodName] = function () {
              destructiveMethodCounts.set(cache, (destructiveMethodCounts.get(cache) + 1) % 1e15);
              return original.apply(this, arguments);
          };
      }
  }
  var QueryInfo = (function () {
      function QueryInfo(cache) {
          this.cache = cache;
          this.listeners = new Set();
          this.document = null;
          this.lastRequestId = 1;
          this.subscriptions = new Set();
          this.dirty = false;
          this.diff = null;
          this.observableQuery = null;
          if (!destructiveMethodCounts.has(cache)) {
              destructiveMethodCounts.set(cache, 0);
              wrapDestructiveCacheMethod(cache, "evict");
              wrapDestructiveCacheMethod(cache, "modify");
          }
      }
      QueryInfo.prototype.init = function (query) {
          var networkStatus = query.networkStatus || exports.NetworkStatus.loading;
          if (this.variables &&
              this.networkStatus !== exports.NetworkStatus.loading &&
              !equality.equal(this.variables, query.variables)) {
              networkStatus = exports.NetworkStatus.setVariables;
          }
          if (!equality.equal(query.variables, this.variables)) {
              this.diff = null;
          }
          Object.assign(this, {
              document: query.document,
              variables: query.variables,
              networkError: null,
              graphQLErrors: this.graphQLErrors || [],
              networkStatus: networkStatus,
          });
          if (query.observableQuery) {
              this.setObservableQuery(query.observableQuery);
          }
          if (query.lastRequestId) {
              this.lastRequestId = query.lastRequestId;
          }
          return this;
      };
      QueryInfo.prototype.getDiff = function (variables) {
          if (variables === void 0) { variables = this.variables; }
          if (this.diff && equality.equal(variables, this.variables)) {
              return this.diff;
          }
          this.updateWatch(this.variables = variables);
          return this.diff = this.cache.diff({
              query: this.document,
              variables: variables,
              returnPartialData: true,
              optimistic: true,
          });
      };
      QueryInfo.prototype.setDiff = function (diff) {
          var _this = this;
          var oldDiff = this.diff;
          this.diff = diff;
          if (!this.dirty &&
              (diff && diff.result) !== (oldDiff && oldDiff.result)) {
              this.dirty = true;
              if (!this.notifyTimeout) {
                  this.notifyTimeout = setTimeout(function () { return _this.notify(); }, 0);
              }
          }
      };
      QueryInfo.prototype.setObservableQuery = function (oq) {
          var _this = this;
          if (oq === this.observableQuery)
              return;
          if (this.oqListener) {
              this.listeners.delete(this.oqListener);
          }
          this.observableQuery = oq;
          if (oq) {
              oq["queryInfo"] = this;
              this.listeners.add(this.oqListener = function () {
                  if (_this.getDiff().fromOptimisticTransaction) {
                      oq["observe"]();
                  }
                  else {
                      oq.reobserve();
                  }
              });
          }
          else {
              delete this.oqListener;
          }
      };
      QueryInfo.prototype.notify = function () {
          var _this = this;
          if (this.notifyTimeout) {
              clearTimeout(this.notifyTimeout);
              this.notifyTimeout = void 0;
          }
          if (this.shouldNotify()) {
              this.listeners.forEach(function (listener) { return listener(_this); });
          }
          this.dirty = false;
      };
      QueryInfo.prototype.shouldNotify = function () {
          if (!this.dirty || !this.listeners.size) {
              return false;
          }
          if (isNetworkRequestInFlight(this.networkStatus) &&
              this.observableQuery) {
              var fetchPolicy = this.observableQuery.options.fetchPolicy;
              if (fetchPolicy !== "cache-only" &&
                  fetchPolicy !== "cache-and-network") {
                  return false;
              }
          }
          return true;
      };
      QueryInfo.prototype.stop = function () {
          this.cancel();
          delete this.cancel;
          var oq = this.observableQuery;
          if (oq)
              oq.stopPolling();
      };
      QueryInfo.prototype.cancel = function () { };
      QueryInfo.prototype.updateWatch = function (variables) {
          var _this = this;
          if (variables === void 0) { variables = this.variables; }
          var oq = this.observableQuery;
          if (oq && oq.options.fetchPolicy === "no-cache") {
              return;
          }
          if (!this.lastWatch ||
              this.lastWatch.query !== this.document ||
              !equality.equal(variables, this.lastWatch.variables)) {
              this.cancel();
              this.cancel = this.cache.watch(this.lastWatch = {
                  query: this.document,
                  variables: variables,
                  optimistic: true,
                  callback: function (diff) { return _this.setDiff(diff); },
              });
          }
      };
      QueryInfo.prototype.shouldWrite = function (result, variables) {
          var lastWrite = this.lastWrite;
          return !(lastWrite &&
              lastWrite.dmCount === destructiveMethodCounts.get(this.cache) &&
              equality.equal(variables, lastWrite.variables) &&
              equality.equal(result.data, lastWrite.result.data));
      };
      QueryInfo.prototype.markResult = function (result, options, allowCacheWrite) {
          var _this = this;
          this.graphQLErrors = utilities.isNonEmptyArray(result.errors) ? result.errors : [];
          if (options.fetchPolicy === 'no-cache') {
              this.diff = { result: result.data, complete: true };
          }
          else if (allowCacheWrite) {
              if (shouldWriteResult(result, options.errorPolicy)) {
                  this.cache.performTransaction(function (cache) {
                      if (_this.shouldWrite(result, options.variables)) {
                          cache.writeQuery({
                              query: _this.document,
                              data: result.data,
                              variables: options.variables,
                          });
                          _this.lastWrite = {
                              result: result,
                              variables: options.variables,
                              dmCount: destructiveMethodCounts.get(_this.cache),
                          };
                      }
                      else {
                          if (_this.diff && _this.diff.complete) {
                              result.data = _this.diff.result;
                              return;
                          }
                      }
                      var diff = cache.diff({
                          query: _this.document,
                          variables: options.variables,
                          returnPartialData: true,
                          optimistic: true,
                      });
                      _this.updateWatch(options.variables);
                      _this.diff = diff;
                      if (diff.complete) {
                          result.data = diff.result;
                      }
                  });
              }
              else {
                  this.lastWrite = void 0;
              }
          }
      };
      QueryInfo.prototype.markReady = function () {
          this.networkError = null;
          return this.networkStatus = exports.NetworkStatus.ready;
      };
      QueryInfo.prototype.markError = function (error) {
          this.networkStatus = exports.NetworkStatus.error;
          this.lastWrite = void 0;
          if (error.graphQLErrors) {
              this.graphQLErrors = error.graphQLErrors;
          }
          if (error.networkError) {
              this.networkError = error.networkError;
          }
          return error;
      };
      return QueryInfo;
  }());
  function shouldWriteResult(result, errorPolicy) {
      if (errorPolicy === void 0) { errorPolicy = "none"; }
      var ignoreErrors = errorPolicy === "ignore" ||
          errorPolicy === "all";
      var writeWithErrors = !utilities.graphQLResultHasError(result);
      if (!writeWithErrors && ignoreErrors && result.data) {
          writeWithErrors = true;
      }
      return writeWithErrors;
  }
  
  var hasOwnProperty = Object.prototype.hasOwnProperty;
  var QueryManager = (function () {
      function QueryManager(_a) {
          var cache = _a.cache, link = _a.link, _b = _a.queryDeduplication, queryDeduplication = _b === void 0 ? false : _b, _c = _a.onBroadcast, onBroadcast = _c === void 0 ? function () { return undefined; } : _c, _d = _a.ssrMode, ssrMode = _d === void 0 ? false : _d, _e = _a.clientAwareness, clientAwareness = _e === void 0 ? {} : _e, localState = _a.localState, assumeImmutableResults = _a.assumeImmutableResults;
          this.mutationStore = new MutationStore();
          this.clientAwareness = {};
          this.queries = new Map();
          this.fetchCancelFns = new Map();
          this.transformCache = new (utilities.canUseWeakMap ? WeakMap : Map)();
          this.queryIdCounter = 1;
          this.requestIdCounter = 1;
          this.mutationIdCounter = 1;
          this.inFlightLinkObservables = new Map();
          this.cache = cache;
          this.link = link;
          this.queryDeduplication = queryDeduplication;
          this.onBroadcast = onBroadcast;
          this.clientAwareness = clientAwareness;
          this.localState = localState || new LocalState({ cache: cache });
          this.ssrMode = ssrMode;
          this.assumeImmutableResults = !!assumeImmutableResults;
      }
      QueryManager.prototype.stop = function () {
          var _this = this;
          this.queries.forEach(function (_info, queryId) {
              _this.stopQueryNoBroadcast(queryId);
          });
          this.cancelPendingFetches(process.env.NODE_ENV === "production" ? new tsInvariant.InvariantError(12) : new tsInvariant.InvariantError('QueryManager stopped while query was in flight'));
      };
      QueryManager.prototype.cancelPendingFetches = function (error) {
          this.fetchCancelFns.forEach(function (cancel) { return cancel(error); });
          this.fetchCancelFns.clear();
      };
      QueryManager.prototype.mutate = function (_a) {
          var mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, updateQueriesByName = _a.updateQueries, _b = _a.refetchQueries, refetchQueries = _b === void 0 ? [] : _b, _c = _a.awaitRefetchQueries, awaitRefetchQueries = _c === void 0 ? false : _c, updateWithProxyFn = _a.update, _d = _a.errorPolicy, errorPolicy = _d === void 0 ? 'none' : _d, fetchPolicy = _a.fetchPolicy, _e = _a.context, context = _e === void 0 ? {} : _e;
          return tslib.__awaiter(this, void 0, void 0, function () {
              var mutationId, generateUpdateQueriesInfo, optimistic_1, self;
              var _this = this;
              return tslib.__generator(this, function (_f) {
                  switch (_f.label) {
                      case 0:
                          process.env.NODE_ENV === "production" ? tsInvariant.invariant(mutation, 13) : tsInvariant.invariant(mutation, 'mutation option is required. You must specify your GraphQL document in the mutation option.');
                          process.env.NODE_ENV === "production" ? tsInvariant.invariant(!fetchPolicy || fetchPolicy === 'no-cache', 14) : tsInvariant.invariant(!fetchPolicy || fetchPolicy === 'no-cache', "Mutations only support a 'no-cache' fetchPolicy. If you don't want to disable the cache, remove your fetchPolicy setting to proceed with the default mutation behavior.");
                          mutationId = this.generateMutationId();
                          mutation = this.transform(mutation).document;
                          variables = this.getVariables(mutation, variables);
                          if (!this.transform(mutation).hasClientExports) return [3, 2];
                          return [4, this.localState.addExportedVariables(mutation, variables, context)];
                      case 1:
                          variables = _f.sent();
                          _f.label = 2;
                      case 2:
                          generateUpdateQueriesInfo = function () {
                              var ret = {};
                              if (updateQueriesByName) {
                                  _this.queries.forEach(function (_a, queryId) {
                                      var observableQuery = _a.observableQuery;
                                      if (observableQuery) {
                                          var queryName = observableQuery.queryName;
                                          if (queryName &&
                                              hasOwnProperty.call(updateQueriesByName, queryName)) {
                                              ret[queryId] = {
                                                  updater: updateQueriesByName[queryName],
                                                  queryInfo: _this.queries.get(queryId),
                                              };
                                          }
                                      }
                                  });
                              }
                              return ret;
                          };
                          this.mutationStore.initMutation(mutationId, mutation, variables);
                          if (optimisticResponse) {
                              optimistic_1 = typeof optimisticResponse === 'function'
                                  ? optimisticResponse(variables)
                                  : optimisticResponse;
                              this.cache.recordOptimisticTransaction(function (cache) {
                                  try {
                                      markMutationResult({
                                          mutationId: mutationId,
                                          result: { data: optimistic_1 },
                                          document: mutation,
                                          variables: variables,
                                          errorPolicy: errorPolicy,
                                          queryUpdatersById: generateUpdateQueriesInfo(),
                                          update: updateWithProxyFn,
                                      }, cache);
                                  }
                                  catch (error) {
                                      process.env.NODE_ENV === "production" || tsInvariant.invariant.error(error);
                                  }
                              }, mutationId);
                          }
                          this.broadcastQueries();
                          self = this;
                          return [2, new Promise(function (resolve, reject) {
                                  var storeResult;
                                  var error;
                                  self.getObservableFromLink(mutation, tslib.__assign(tslib.__assign({}, context), { optimisticResponse: optimisticResponse }), variables, false).subscribe({
                                      next: function (result) {
                                          if (utilities.graphQLResultHasError(result) && errorPolicy === 'none') {
                                              error = new errors.ApolloError({
                                                  graphQLErrors: result.errors,
                                              });
                                              return;
                                          }
                                          self.mutationStore.markMutationResult(mutationId);
                                          if (fetchPolicy !== 'no-cache') {
                                              try {
                                                  markMutationResult({
                                                      mutationId: mutationId,
                                                      result: result,
                                                      document: mutation,
                                                      variables: variables,
                                                      errorPolicy: errorPolicy,
                                                      queryUpdatersById: generateUpdateQueriesInfo(),
                                                      update: updateWithProxyFn,
                                                  }, self.cache);
                                              }
                                              catch (e) {
                                                  error = new errors.ApolloError({
                                                      networkError: e,
                                                  });
                                                  return;
                                              }
                                          }
                                          storeResult = result;
                                      },
                                      error: function (err) {
                                          self.mutationStore.markMutationError(mutationId, err);
                                          if (optimisticResponse) {
                                              self.cache.removeOptimistic(mutationId);
                                          }
                                          self.broadcastQueries();
                                          reject(new errors.ApolloError({
                                              networkError: err,
                                          }));
                                      },
                                      complete: function () {
                                          if (error) {
                                              self.mutationStore.markMutationError(mutationId, error);
                                          }
                                          if (optimisticResponse) {
                                              self.cache.removeOptimistic(mutationId);
                                          }
                                          self.broadcastQueries();
                                          if (error) {
                                              reject(error);
                                              return;
                                          }
                                          if (typeof refetchQueries === 'function') {
                                              refetchQueries = refetchQueries(storeResult);
                                          }
                                          var refetchQueryPromises = [];
                                          if (utilities.isNonEmptyArray(refetchQueries)) {
                                              refetchQueries.forEach(function (refetchQuery) {
                                                  if (typeof refetchQuery === 'string') {
                                                      self.queries.forEach(function (_a) {
                                                          var observableQuery = _a.observableQuery;
                                                          if (observableQuery &&
                                                              observableQuery.queryName === refetchQuery) {
                                                              refetchQueryPromises.push(observableQuery.refetch());
                                                          }
                                                      });
                                                  }
                                                  else {
                                                      var queryOptions = {
                                                          query: refetchQuery.query,
                                                          variables: refetchQuery.variables,
                                                          fetchPolicy: 'network-only',
                                                      };
                                                      if (refetchQuery.context) {
                                                          queryOptions.context = refetchQuery.context;
                                                      }
                                                      refetchQueryPromises.push(self.query(queryOptions));
                                                  }
                                              });
                                          }
                                          Promise.all(awaitRefetchQueries ? refetchQueryPromises : []).then(function () {
                                              if (errorPolicy === 'ignore' &&
                                                  storeResult &&
                                                  utilities.graphQLResultHasError(storeResult)) {
                                                  delete storeResult.errors;
                                              }
                                              resolve(storeResult);
                                          }, reject);
                                      },
                                  });
                              })];
                  }
              });
          });
      };
      QueryManager.prototype.fetchQuery = function (queryId, options, networkStatus) {
          return this.fetchQueryObservable(queryId, options, networkStatus).promise;
      };
      QueryManager.prototype.getQueryStore = function () {
          var store = Object.create(null);
          this.queries.forEach(function (info, queryId) {
              store[queryId] = {
                  variables: info.variables,
                  networkStatus: info.networkStatus,
                  networkError: info.networkError,
                  graphQLErrors: info.graphQLErrors,
              };
          });
          return store;
      };
      QueryManager.prototype.resetErrors = function (queryId) {
          var queryInfo = this.queries.get(queryId);
          if (queryInfo) {
              queryInfo.networkError = undefined;
              queryInfo.graphQLErrors = [];
          }
      };
      QueryManager.prototype.transform = function (document) {
          var transformCache = this.transformCache;
          if (!transformCache.has(document)) {
              var transformed = this.cache.transformDocument(document);
              var forLink = utilities.removeConnectionDirectiveFromDocument(this.cache.transformForLink(transformed));
              var clientQuery = this.localState.clientQuery(transformed);
              var serverQuery = forLink && this.localState.serverQuery(forLink);
              var cacheEntry_1 = {
                  document: transformed,
                  hasClientExports: utilities.hasClientExports(transformed),
                  hasForcedResolvers: this.localState.shouldForceResolvers(transformed),
                  clientQuery: clientQuery,
                  serverQuery: serverQuery,
                  defaultVars: utilities.getDefaultValues(utilities.getOperationDefinition(transformed)),
              };
              var add = function (doc) {
                  if (doc && !transformCache.has(doc)) {
                      transformCache.set(doc, cacheEntry_1);
                  }
              };
              add(document);
              add(transformed);
              add(clientQuery);
              add(serverQuery);
          }
          return transformCache.get(document);
      };
      QueryManager.prototype.getVariables = function (document, variables) {
          return tslib.__assign(tslib.__assign({}, this.transform(document).defaultVars), variables);
      };
      QueryManager.prototype.watchQuery = function (options) {
          options = tslib.__assign(tslib.__assign({}, options), { variables: this.getVariables(options.query, options.variables) });
          if (typeof options.notifyOnNetworkStatusChange === 'undefined') {
              options.notifyOnNetworkStatusChange = false;
          }
          var queryInfo = new QueryInfo(this.cache);
          var observable = new ObservableQuery({
              queryManager: this,
              queryInfo: queryInfo,
              options: options,
          });
          this.queries.set(observable.queryId, queryInfo);
          queryInfo.init({
              document: options.query,
              observableQuery: observable,
              variables: options.variables,
          });
          return observable;
      };
      QueryManager.prototype.query = function (options) {
          var _this = this;
          process.env.NODE_ENV === "production" ? tsInvariant.invariant(options.query, 15) : tsInvariant.invariant(options.query, 'query option is required. You must specify your GraphQL document ' +
              'in the query option.');
          process.env.NODE_ENV === "production" ? tsInvariant.invariant(options.query.kind === 'Document', 16) : tsInvariant.invariant(options.query.kind === 'Document', 'You must wrap the query string in a "gql" tag.');
          process.env.NODE_ENV === "production" ? tsInvariant.invariant(!options.returnPartialData, 17) : tsInvariant.invariant(!options.returnPartialData, 'returnPartialData option only supported on watchQuery.');
          process.env.NODE_ENV === "production" ? tsInvariant.invariant(!options.pollInterval, 18) : tsInvariant.invariant(!options.pollInterval, 'pollInterval option only supported on watchQuery.');
          var queryId = this.generateQueryId();
          return this.fetchQuery(queryId, options).finally(function () { return _this.stopQuery(queryId); });
      };
      QueryManager.prototype.generateQueryId = function () {
          return String(this.queryIdCounter++);
      };
      QueryManager.prototype.generateRequestId = function () {
          return this.requestIdCounter++;
      };
      QueryManager.prototype.generateMutationId = function () {
          return String(this.mutationIdCounter++);
      };
      QueryManager.prototype.stopQueryInStore = function (queryId) {
          this.stopQueryInStoreNoBroadcast(queryId);
          this.broadcastQueries();
      };
      QueryManager.prototype.stopQueryInStoreNoBroadcast = function (queryId) {
          var queryInfo = this.queries.get(queryId);
          if (queryInfo)
              queryInfo.stop();
      };
      QueryManager.prototype.clearStore = function () {
          this.cancelPendingFetches(process.env.NODE_ENV === "production" ? new tsInvariant.InvariantError(19) : new tsInvariant.InvariantError('Store reset while query was in flight (not completed in link chain)'));
          this.queries.forEach(function (queryInfo) {
              if (queryInfo.observableQuery) {
                  queryInfo.networkStatus = exports.NetworkStatus.loading;
              }
              else {
                  queryInfo.stop();
              }
          });
          this.mutationStore.reset();
          return this.cache.reset();
      };
      QueryManager.prototype.resetStore = function () {
          var _this = this;
          return this.clearStore().then(function () {
              return _this.reFetchObservableQueries();
          });
      };
      QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {
          var _this = this;
          if (includeStandby === void 0) { includeStandby = false; }
          var observableQueryPromises = [];
          this.queries.forEach(function (_a, queryId) {
              var observableQuery = _a.observableQuery;
              if (observableQuery) {
                  var fetchPolicy = observableQuery.options.fetchPolicy;
                  observableQuery.resetLastResults();
                  if (fetchPolicy !== 'cache-only' &&
                      (includeStandby || fetchPolicy !== 'standby')) {
                      observableQueryPromises.push(observableQuery.refetch());
                  }
                  _this.getQuery(queryId).setDiff(null);
              }
          });
          this.broadcastQueries();
          return Promise.all(observableQueryPromises);
      };
      QueryManager.prototype.setObservableQuery = function (observableQuery) {
          this.getQuery(observableQuery.queryId).setObservableQuery(observableQuery);
      };
      QueryManager.prototype.startGraphQLSubscription = function (_a) {
          var _this = this;
          var query = _a.query, fetchPolicy = _a.fetchPolicy, errorPolicy = _a.errorPolicy, variables = _a.variables, _b = _a.context, context = _b === void 0 ? {} : _b;
          query = this.transform(query).document;
          variables = this.getVariables(query, variables);
          var makeObservable = function (variables) {
              return _this.getObservableFromLink(query, context, variables, false).map(function (result) {
                  if (fetchPolicy !== 'no-cache') {
                      if (shouldWriteResult(result, errorPolicy)) {
                          _this.cache.write({
                              query: query,
                              result: result.data,
                              dataId: 'ROOT_SUBSCRIPTION',
                              variables: variables,
                          });
                      }
                      _this.broadcastQueries();
                  }
                  if (utilities.graphQLResultHasError(result)) {
                      throw new errors.ApolloError({
                          graphQLErrors: result.errors,
                      });
                  }
                  return result;
              });
          };
          if (this.transform(query).hasClientExports) {
              var observablePromise_1 = this.localState.addExportedVariables(query, variables, context).then(makeObservable);
              return new utilities.Observable(function (observer) {
                  var sub = null;
                  observablePromise_1.then(function (observable) { return sub = observable.subscribe(observer); }, observer.error);
                  return function () { return sub && sub.unsubscribe(); };
              });
          }
          return makeObservable(variables);
      };
      QueryManager.prototype.stopQuery = function (queryId) {
          this.stopQueryNoBroadcast(queryId);
          this.broadcastQueries();
      };
      QueryManager.prototype.stopQueryNoBroadcast = function (queryId) {
          this.stopQueryInStoreNoBroadcast(queryId);
          this.removeQuery(queryId);
      };
      QueryManager.prototype.removeQuery = function (queryId) {
          this.fetchCancelFns.delete(queryId);
          this.getQuery(queryId).subscriptions.forEach(function (x) { return x.unsubscribe(); });
          this.queries.delete(queryId);
      };
      QueryManager.prototype.broadcastQueries = function () {
          this.onBroadcast();
          this.queries.forEach(function (info) { return info.notify(); });
      };
      QueryManager.prototype.getLocalState = function () {
          return this.localState;
      };
      QueryManager.prototype.getObservableFromLink = function (query, context, variables, deduplication) {
          var _this = this;
          var _a;
          if (deduplication === void 0) { deduplication = (_a = context === null || context === void 0 ? void 0 : context.queryDeduplication) !== null && _a !== void 0 ? _a : this.queryDeduplication; }
          var observable;
          var serverQuery = this.transform(query).serverQuery;
          if (serverQuery) {
              var _b = this, inFlightLinkObservables_1 = _b.inFlightLinkObservables, link = _b.link;
              var operation = {
                  query: serverQuery,
                  variables: variables,
                  operationName: utilities.getOperationName(serverQuery) || void 0,
                  context: this.prepareContext(tslib.__assign(tslib.__assign({}, context), { forceFetch: !deduplication })),
              };
              context = operation.context;
              if (deduplication) {
                  var byVariables_1 = inFlightLinkObservables_1.get(serverQuery) || new Map();
                  inFlightLinkObservables_1.set(serverQuery, byVariables_1);
                  var varJson_1 = JSON.stringify(variables);
                  observable = byVariables_1.get(varJson_1);
                  if (!observable) {
                      var concast = new utilities.Concast([
                          core.execute(link, operation)
                      ]);
                      byVariables_1.set(varJson_1, observable = concast);
                      concast.cleanup(function () {
                          if (byVariables_1.delete(varJson_1) &&
                              byVariables_1.size < 1) {
                              inFlightLinkObservables_1.delete(serverQuery);
                          }
                      });
                  }
              }
              else {
                  observable = new utilities.Concast([
                      core.execute(link, operation)
                  ]);
              }
          }
          else {
              observable = new utilities.Concast([
                  utilities.Observable.of({ data: {} })
              ]);
              context = this.prepareContext(context);
          }
          var clientQuery = this.transform(query).clientQuery;
          if (clientQuery) {
              observable = utilities.asyncMap(observable, function (result) {
                  return _this.localState.runResolvers({
                      document: clientQuery,
                      remoteResult: result,
                      context: context,
                      variables: variables,
                  });
              });
          }
          return observable;
      };
      QueryManager.prototype.getResultsFromLink = function (queryInfo, allowCacheWrite, options) {
          var lastRequestId = queryInfo.lastRequestId;
          return utilities.asyncMap(this.getObservableFromLink(queryInfo.document, options.context, options.variables), function (result) {
              var hasErrors = utilities.isNonEmptyArray(result.errors);
              if (lastRequestId >= queryInfo.lastRequestId) {
                  if (hasErrors && options.errorPolicy === "none") {
                      throw queryInfo.markError(new errors.ApolloError({
                          graphQLErrors: result.errors,
                      }));
                  }
                  queryInfo.markResult(result, options, allowCacheWrite);
                  queryInfo.markReady();
              }
              var aqr = {
                  data: result.data,
                  loading: false,
                  networkStatus: queryInfo.networkStatus || exports.NetworkStatus.ready,
              };
              if (hasErrors && options.errorPolicy !== "ignore") {
                  aqr.errors = result.errors;
              }
              return aqr;
          }, function (networkError) {
              var error = errors.isApolloError(networkError)
                  ? networkError
                  : new errors.ApolloError({ networkError: networkError });
              if (lastRequestId >= queryInfo.lastRequestId) {
                  queryInfo.markError(error);
              }
              throw error;
          });
      };
      QueryManager.prototype.fetchQueryObservable = function (queryId, options, networkStatus) {
          var _this = this;
          if (networkStatus === void 0) { networkStatus = exports.NetworkStatus.loading; }
          var query = this.transform(options.query).document;
          var variables = this.getVariables(query, options.variables);
          var queryInfo = this.getQuery(queryId);
          var oldNetworkStatus = queryInfo.networkStatus;
          var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? "cache-first" : _a, _b = options.errorPolicy, errorPolicy = _b === void 0 ? "none" : _b, _c = options.returnPartialData, returnPartialData = _c === void 0 ? false : _c, _d = options.notifyOnNetworkStatusChange, notifyOnNetworkStatusChange = _d === void 0 ? false : _d, _e = options.context, context = _e === void 0 ? {} : _e;
          var mightUseNetwork = fetchPolicy === "cache-first" ||
              fetchPolicy === "cache-and-network" ||
              fetchPolicy === "network-only" ||
              fetchPolicy === "no-cache";
          if (mightUseNetwork &&
              notifyOnNetworkStatusChange &&
              typeof oldNetworkStatus === "number" &&
              oldNetworkStatus !== networkStatus &&
              isNetworkRequestInFlight(networkStatus)) {
              if (fetchPolicy !== "cache-first") {
                  fetchPolicy = "cache-and-network";
              }
              returnPartialData = true;
          }
          var normalized = Object.assign({}, options, {
              query: query,
              variables: variables,
              fetchPolicy: fetchPolicy,
              errorPolicy: errorPolicy,
              returnPartialData: returnPartialData,
              notifyOnNetworkStatusChange: notifyOnNetworkStatusChange,
              context: context,
          });
          var fromVariables = function (variables) {
              normalized.variables = variables;
              return _this.fetchQueryByPolicy(queryInfo, normalized, networkStatus);
          };
          this.fetchCancelFns.set(queryId, function (reason) {
              Promise.resolve().then(function () { return concast.cancel(reason); });
          });
          var concast = new utilities.Concast(this.transform(normalized.query).hasClientExports
              ? this.localState.addExportedVariables(normalized.query, normalized.variables, normalized.context).then(fromVariables)
              : fromVariables(normalized.variables));
          concast.cleanup(function () {
              _this.fetchCancelFns.delete(queryId);
              var nextFetchPolicy = options.nextFetchPolicy;
              if (nextFetchPolicy) {
                  options.nextFetchPolicy = void 0;
                  options.fetchPolicy = typeof nextFetchPolicy === "function"
                      ? nextFetchPolicy.call(options, options.fetchPolicy || "cache-first")
                      : nextFetchPolicy;
              }
          });
          return concast;
      };
      QueryManager.prototype.fetchQueryByPolicy = function (queryInfo, options, networkStatus) {
          var _this = this;
          var query = options.query, variables = options.variables, fetchPolicy = options.fetchPolicy, errorPolicy = options.errorPolicy, returnPartialData = options.returnPartialData, context = options.context;
          queryInfo.init({
              document: query,
              variables: variables,
              lastRequestId: this.generateRequestId(),
              networkStatus: networkStatus,
          });
          var readCache = function () { return queryInfo.getDiff(variables); };
          var resultsFromCache = function (diff, networkStatus) {
              if (networkStatus === void 0) { networkStatus = queryInfo.networkStatus || exports.NetworkStatus.loading; }
              var data = diff.result;
              if (process.env.NODE_ENV !== 'production' &&
                  utilities.isNonEmptyArray(diff.missing) &&
                  !equality.equal(data, {}) &&
                  !returnPartialData) {
                  process.env.NODE_ENV === "production" || tsInvariant.invariant.warn("Missing cache result fields: " + diff.missing.map(function (m) { return m.path.join('.'); }).join(', '), diff.missing);
              }
              var fromData = function (data) { return utilities.Observable.of(tslib.__assign({ data: data, loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus }, (diff.complete ? null : { partial: true }))); };
              if (_this.transform(query).hasForcedResolvers) {
                  return _this.localState.runResolvers({
                      document: query,
                      remoteResult: { data: data },
                      context: context,
                      variables: variables,
                      onlyRunForcedResolvers: true,
                  }).then(function (resolved) { return fromData(resolved.data); });
              }
              return fromData(data);
          };
          var resultsFromLink = function (allowCacheWrite) {
              return _this.getResultsFromLink(queryInfo, allowCacheWrite, {
                  variables: variables,
                  context: context,
                  fetchPolicy: fetchPolicy,
                  errorPolicy: errorPolicy,
              });
          };
          switch (fetchPolicy) {
              default:
              case "cache-first": {
                  var diff = readCache();
                  if (diff.complete) {
                      return [
                          resultsFromCache(diff, queryInfo.markReady()),
                      ];
                  }
                  if (returnPartialData) {
                      return [
                          resultsFromCache(diff),
                          resultsFromLink(true),
                      ];
                  }
                  return [
                      resultsFromLink(true),
                  ];
              }
              case "cache-and-network": {
                  var diff = readCache();
                  if (diff.complete || returnPartialData) {
                      return [
                          resultsFromCache(diff),
                          resultsFromLink(true),
                      ];
                  }
                  return [
                      resultsFromLink(true),
                  ];
              }
              case "cache-only":
                  return [
                      resultsFromCache(readCache(), queryInfo.markReady()),
                  ];
              case "network-only":
                  return [resultsFromLink(true)];
              case "no-cache":
                  return [resultsFromLink(false)];
              case "standby":
                  return [];
          }
      };
      QueryManager.prototype.getQuery = function (queryId) {
          if (queryId && !this.queries.has(queryId)) {
              this.queries.set(queryId, new QueryInfo(this.cache));
          }
          return this.queries.get(queryId);
      };
      QueryManager.prototype.prepareContext = function (context) {
          if (context === void 0) { context = {}; }
          var newContext = this.localState.prepareContext(context);
          return tslib.__assign(tslib.__assign({}, newContext), { clientAwareness: this.clientAwareness });
      };
      return QueryManager;
  }());
  function markMutationResult(mutation, cache) {
      if (shouldWriteResult(mutation.result, mutation.errorPolicy)) {
          var cacheWrites_1 = [{
                  result: mutation.result.data,
                  dataId: 'ROOT_MUTATION',
                  query: mutation.document,
                  variables: mutation.variables,
              }];
          var queryUpdatersById_1 = mutation.queryUpdatersById;
          if (queryUpdatersById_1) {
              Object.keys(queryUpdatersById_1).forEach(function (id) {
                  var _a = queryUpdatersById_1[id], updater = _a.updater, _b = _a.queryInfo, document = _b.document, variables = _b.variables;
                  var _c = cache.diff({
                      query: document,
                      variables: variables,
                      returnPartialData: true,
                      optimistic: false,
                  }), currentQueryResult = _c.result, complete = _c.complete;
                  if (complete && currentQueryResult) {
                      var nextQueryResult = updater(currentQueryResult, {
                          mutationResult: mutation.result,
                          queryName: utilities.getOperationName(document) || undefined,
                          queryVariables: variables,
                      });
                      if (nextQueryResult) {
                          cacheWrites_1.push({
                              result: nextQueryResult,
                              dataId: 'ROOT_QUERY',
                              query: document,
                              variables: variables,
                          });
                      }
                  }
              });
          }
          cache.performTransaction(function (c) {
              cacheWrites_1.forEach(function (write) { return c.write(write); });
              var update = mutation.update;
              if (update) {
                  update(c, mutation.result);
              }
          }, null);
      }
  }
  
  var hasSuggestedDevtools = false;
  var ApolloClient = (function () {
      function ApolloClient(options) {
          var _this = this;
          this.defaultOptions = {};
          this.resetStoreCallbacks = [];
          this.clearStoreCallbacks = [];
          var uri = options.uri, credentials = options.credentials, headers = options.headers, cache = options.cache, _a = options.ssrMode, ssrMode = _a === void 0 ? false : _a, _b = options.ssrForceFetchDelay, ssrForceFetchDelay = _b === void 0 ? 0 : _b, connectToDevTools = options.connectToDevTools, _c = options.queryDeduplication, queryDeduplication = _c === void 0 ? true : _c, defaultOptions = options.defaultOptions, _d = options.assumeImmutableResults, assumeImmutableResults = _d === void 0 ? false : _d, resolvers = options.resolvers, typeDefs = options.typeDefs, fragmentMatcher = options.fragmentMatcher, clientAwarenessName = options.name, clientAwarenessVersion = options.version;
          var link = options.link;
          if (!link) {
              link = uri
                  ? new http.HttpLink({ uri: uri, credentials: credentials, headers: headers })
                  : core.ApolloLink.empty();
          }
          if (!cache) {
              throw process.env.NODE_ENV === "production" ? new tsInvariant.InvariantError(9) : new tsInvariant.InvariantError("To initialize Apollo Client, you must specify a 'cache' property " +
                  "in the options object. \n" +
                  "For more information, please visit: https://go.apollo.dev/c/docs");
          }
          this.link = link;
          this.cache = cache;
          this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
          this.queryDeduplication = queryDeduplication;
          this.defaultOptions = defaultOptions || {};
          this.typeDefs = typeDefs;
          if (ssrForceFetchDelay) {
              setTimeout(function () { return (_this.disableNetworkFetches = false); }, ssrForceFetchDelay);
          }
          this.watchQuery = this.watchQuery.bind(this);
          this.query = this.query.bind(this);
          this.mutate = this.mutate.bind(this);
          this.resetStore = this.resetStore.bind(this);
          this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);
          var defaultConnectToDevTools = process.env.NODE_ENV !== 'production' &&
              typeof window !== 'undefined' &&
              !window.__APOLLO_CLIENT__;
          if (typeof connectToDevTools === 'undefined'
              ? defaultConnectToDevTools
              : connectToDevTools && typeof window !== 'undefined') {
              window.__APOLLO_CLIENT__ = this;
          }
          if (!hasSuggestedDevtools && process.env.NODE_ENV !== 'production') {
              hasSuggestedDevtools = true;
              if (typeof window !== 'undefined' &&
                  window.document &&
                  window.top === window.self) {
                  if (typeof window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
                      if (window.navigator &&
                          window.navigator.userAgent &&
                          window.navigator.userAgent.indexOf('Chrome') > -1) {
                          console.debug('Download the Apollo DevTools ' +
                              'for a better development experience: ' +
                              'https://chrome.google.com/webstore/detail/apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm');
                      }
                  }
              }
          }
          this.version = version;
          this.localState = new LocalState({
              cache: cache,
              client: this,
              resolvers: resolvers,
              fragmentMatcher: fragmentMatcher,
          });
          this.queryManager = new QueryManager({
              cache: this.cache,
              link: this.link,
              queryDeduplication: queryDeduplication,
              ssrMode: ssrMode,
              clientAwareness: {
                  name: clientAwarenessName,
                  version: clientAwarenessVersion,
              },
              localState: this.localState,
              assumeImmutableResults: assumeImmutableResults,
              onBroadcast: function () {
                  if (_this.devToolsHookCb) {
                      _this.devToolsHookCb({
                          action: {},
                          state: {
                              queries: _this.queryManager.getQueryStore(),
                              mutations: _this.queryManager.mutationStore.getStore(),
                          },
                          dataWithOptimisticResults: _this.cache.extract(true),
                      });
                  }
              },
          });
      }
      ApolloClient.prototype.stop = function () {
          this.queryManager.stop();
      };
      ApolloClient.prototype.watchQuery = function (options) {
          if (this.defaultOptions.watchQuery) {
              options = utilities.compact(this.defaultOptions.watchQuery, options);
          }
          if (this.disableNetworkFetches &&
              (options.fetchPolicy === 'network-only' ||
                  options.fetchPolicy === 'cache-and-network')) {
              options = tslib.__assign(tslib.__assign({}, options), { fetchPolicy: 'cache-first' });
          }
          return this.queryManager.watchQuery(options);
      };
      ApolloClient.prototype.query = function (options) {
          if (this.defaultOptions.query) {
              options = utilities.compact(this.defaultOptions.query, options);
          }
          process.env.NODE_ENV === "production" ? tsInvariant.invariant(options.fetchPolicy !== 'cache-and-network', 10) : 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.');
          if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') {
              options = tslib.__assign(tslib.__assign({}, options), { fetchPolicy: 'cache-first' });
          }
          return this.queryManager.query(options);
      };
      ApolloClient.prototype.mutate = function (options) {
          if (this.defaultOptions.mutate) {
              options = utilities.compact(this.defaultOptions.mutate, options);
          }
          return this.queryManager.mutate(options);
      };
      ApolloClient.prototype.subscribe = function (options) {
          return this.queryManager.startGraphQLSubscription(options);
      };
      ApolloClient.prototype.readQuery = function (options, optimistic) {
          if (optimistic === void 0) { optimistic = false; }
          return this.cache.readQuery(options, optimistic);
      };
      ApolloClient.prototype.readFragment = function (options, optimistic) {
          if (optimistic === void 0) { optimistic = false; }
          return this.cache.readFragment(options, optimistic);
      };
      ApolloClient.prototype.writeQuery = function (options) {
          this.cache.writeQuery(options);
          this.queryManager.broadcastQueries();
      };
      ApolloClient.prototype.writeFragment = function (options) {
          this.cache.writeFragment(options);
          this.queryManager.broadcastQueries();
      };
      ApolloClient.prototype.__actionHookForDevTools = function (cb) {
          this.devToolsHookCb = cb;
      };
      ApolloClient.prototype.__requestRaw = function (payload) {
          return core.execute(this.link, payload);
      };
      ApolloClient.prototype.resetStore = function () {
          var _this = this;
          return Promise.resolve()
              .then(function () { return _this.queryManager.clearStore(); })
              .then(function () { return Promise.all(_this.resetStoreCallbacks.map(function (fn) { return fn(); })); })
              .then(function () { return _this.reFetchObservableQueries(); });
      };
      ApolloClient.prototype.clearStore = function () {
          var _this = this;
          return Promise.resolve()
              .then(function () { return _this.queryManager.clearStore(); })
              .then(function () { return Promise.all(_this.clearStoreCallbacks.map(function (fn) { return fn(); })); });
      };
      ApolloClient.prototype.onResetStore = function (cb) {
          var _this = this;
          this.resetStoreCallbacks.push(cb);
          return function () {
              _this.resetStoreCallbacks = _this.resetStoreCallbacks.filter(function (c) { return c !== cb; });
          };
      };
      ApolloClient.prototype.onClearStore = function (cb) {
          var _this = this;
          this.clearStoreCallbacks.push(cb);
          return function () {
              _this.clearStoreCallbacks = _this.clearStoreCallbacks.filter(function (c) { return c !== cb; });
          };
      };
      ApolloClient.prototype.reFetchObservableQueries = function (includeStandby) {
          return this.queryManager.reFetchObservableQueries(includeStandby);
      };
      ApolloClient.prototype.extract = function (optimistic) {
          return this.cache.extract(optimistic);
      };
      ApolloClient.prototype.restore = function (serializedState) {
          return this.cache.restore(serializedState);
      };
      ApolloClient.prototype.addResolvers = function (resolvers) {
          this.localState.addResolvers(resolvers);
      };
      ApolloClient.prototype.setResolvers = function (resolvers) {
          this.localState.setResolvers(resolvers);
      };
      ApolloClient.prototype.getResolvers = function () {
          return this.localState.getResolvers();
      };
      ApolloClient.prototype.setLocalStateFragmentMatcher = function (fragmentMatcher) {
          this.localState.setFragmentMatcher(fragmentMatcher);
      };
      ApolloClient.prototype.setLink = function (newLink) {
          this.link = this.queryManager.link = newLink;
      };
      return ApolloClient;
  }());
  
  var resetCaches = gql.resetCaches, disableFragmentWarnings = gql.disableFragmentWarnings, enableExperimentalFragmentVariables = gql.enableExperimentalFragmentVariables, disableExperimentalFragmentVariables = gql.disableExperimentalFragmentVariables;
  
  Object.keys(core).forEach(function (k) {
      if (k !== 'default') exports[k] = core[k];
  });
  Object.keys(http).forEach(function (k) {
      if (k !== 'default') exports[k] = http[k];
  });
  exports.Observable = utilities.Observable;
  exports.isReference = utilities.isReference;
  exports.makeReference = utilities.makeReference;
  exports.ApolloError = errors.ApolloError;
  exports.isApolloError = errors.isApolloError;
  exports.ApolloCache = cache.ApolloCache;
  exports.Cache = cache.Cache;
  exports.InMemoryCache = cache.InMemoryCache;
  exports.MissingFieldError = cache.MissingFieldError;
  exports.defaultDataIdFromObject = cache.defaultDataIdFromObject;
  exports.makeVar = cache.makeVar;
  exports.fromError = utils.fromError;
  exports.fromPromise = utils.fromPromise;
  exports.throwServerError = utils.throwServerError;
  exports.toPromise = utils.toPromise;
  exports.gql = gql;
  exports.ApolloClient = ApolloClient;
  exports.ObservableQuery = ObservableQuery;
  exports.disableExperimentalFragmentVariables = disableExperimentalFragmentVariables;
  exports.disableFragmentWarnings = disableFragmentWarnings;
  exports.enableExperimentalFragmentVariables = enableExperimentalFragmentVariables;
  exports.resetCaches = resetCaches;
  //# sourceMappingURL=core.cjs.js.map
  