text: 'use strict';
  
  Object.defineProperty(exports, '__esModule', { value: true });
  
  function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  
  var graphql = require('graphql');
  var tsInvariant = require('ts-invariant');
  var tslib = require('tslib');
  var stringify = _interopDefault(require('fast-json-stable-stringify'));
  var Observable = _interopDefault(require('zen-observable'));
  require('symbol-observable');
  
  function shouldInclude(_a, variables) {
      var directives = _a.directives;
      if (!directives || !directives.length) {
          return true;
      }
      return getInclusionDirectives(directives).every(function (_a) {
          var directive = _a.directive, ifArgument = _a.ifArgument;
          var evaledValue = false;
          if (ifArgument.value.kind === 'Variable') {
              evaledValue = variables && variables[ifArgument.value.name.value];
              process.env.NODE_ENV === "production" ? tsInvariant.invariant(evaledValue !== void 0, 38) : tsInvariant.invariant(evaledValue !== void 0, "Invalid variable referenced in @" + directive.name.value + " directive.");
          }
          else {
              evaledValue = ifArgument.value.value;
          }
          return directive.name.value === 'skip' ? !evaledValue : evaledValue;
      });
  }
  function getDirectiveNames(root) {
      var names = [];
      graphql.visit(root, {
          Directive: function (node) {
              names.push(node.name.value);
          },
      });
      return names;
  }
  function hasDirectives(names, root) {
      return getDirectiveNames(root).some(function (name) { return names.indexOf(name) > -1; });
  }
  function hasClientExports(document) {
      return (document &&
          hasDirectives(['client'], document) &&
          hasDirectives(['export'], document));
  }
  function isInclusionDirective(_a) {
      var value = _a.name.value;
      return value === 'skip' || value === 'include';
  }
  function getInclusionDirectives(directives) {
      var result = [];
      if (directives && directives.length) {
          directives.forEach(function (directive) {
              if (!isInclusionDirective(directive))
                  return;
              var directiveArguments = directive.arguments;
              var directiveName = directive.name.value;
              process.env.NODE_ENV === "production" ? tsInvariant.invariant(directiveArguments && directiveArguments.length === 1, 39) : tsInvariant.invariant(directiveArguments && directiveArguments.length === 1, "Incorrect number of arguments for the @" + directiveName + " directive.");
              var ifArgument = directiveArguments[0];
              process.env.NODE_ENV === "production" ? tsInvariant.invariant(ifArgument.name && ifArgument.name.value === 'if', 40) : tsInvariant.invariant(ifArgument.name && ifArgument.name.value === 'if', "Invalid argument for the @" + directiveName + " directive.");
              var ifValue = ifArgument.value;
              process.env.NODE_ENV === "production" ? tsInvariant.invariant(ifValue &&
                  (ifValue.kind === 'Variable' || ifValue.kind === 'BooleanValue'), 41) : tsInvariant.invariant(ifValue &&
                  (ifValue.kind === 'Variable' || ifValue.kind === 'BooleanValue'), "Argument for the @" + directiveName + " directive must be a variable or a boolean value.");
              result.push({ directive: directive, ifArgument: ifArgument });
          });
      }
      return result;
  }
  
  function getFragmentQueryDocument(document, fragmentName) {
      var actualFragmentName = fragmentName;
      var fragments = [];
      document.definitions.forEach(function (definition) {
          if (definition.kind === 'OperationDefinition') {
              throw process.env.NODE_ENV === "production" ? new tsInvariant.InvariantError(42) : new tsInvariant.InvariantError("Found a " + definition.operation + " operation" + (definition.name ? " named '" + definition.name.value + "'" : '') + ". " +
                  'No operations are allowed when using a fragment as a query. Only fragments are allowed.');
          }
          if (definition.kind === 'FragmentDefinition') {
              fragments.push(definition);
          }
      });
      if (typeof actualFragmentName === 'undefined') {
          process.env.NODE_ENV === "production" ? tsInvariant.invariant(fragments.length === 1, 43) : tsInvariant.invariant(fragments.length === 1, "Found " + fragments.length + " fragments. `fragmentName` must be provided when there is not exactly 1 fragment.");
          actualFragmentName = fragments[0].name.value;
      }
      var query = tslib.__assign(tslib.__assign({}, document), { definitions: tslib.__spreadArrays([
              {
                  kind: 'OperationDefinition',
                  operation: 'query',
                  selectionSet: {
                      kind: 'SelectionSet',
                      selections: [
                          {
                              kind: 'FragmentSpread',
                              name: {
                                  kind: 'Name',
                                  value: actualFragmentName,
                              },
                          },
                      ],
                  },
              }
          ], document.definitions) });
      return query;
  }
  function createFragmentMap(fragments) {
      if (fragments === void 0) { fragments = []; }
      var symTable = {};
      fragments.forEach(function (fragment) {
          symTable[fragment.name.value] = fragment;
      });
      return symTable;
  }
  function getFragmentFromSelection(selection, fragmentMap) {
      switch (selection.kind) {
          case 'InlineFragment':
              return selection;
          case 'FragmentSpread': {
              var fragment = fragmentMap && fragmentMap[selection.name.value];
              process.env.NODE_ENV === "production" ? tsInvariant.invariant(fragment, 44) : tsInvariant.invariant(fragment, "No fragment named " + selection.name.value + ".");
              return fragment;
          }
          default:
              return null;
      }
  }
  
  function makeReference(id) {
      return { __ref: String(id) };
  }
  function isReference(obj) {
      return Boolean(obj && typeof obj === 'object' && typeof obj.__ref === 'string');
  }
  function isStringValue(value) {
      return value.kind === 'StringValue';
  }
  function isBooleanValue(value) {
      return value.kind === 'BooleanValue';
  }
  function isIntValue(value) {
      return value.kind === 'IntValue';
  }
  function isFloatValue(value) {
      return value.kind === 'FloatValue';
  }
  function isVariable(value) {
      return value.kind === 'Variable';
  }
  function isObjectValue(value) {
      return value.kind === 'ObjectValue';
  }
  function isListValue(value) {
      return value.kind === 'ListValue';
  }
  function isEnumValue(value) {
      return value.kind === 'EnumValue';
  }
  function isNullValue(value) {
      return value.kind === 'NullValue';
  }
  function valueToObjectRepresentation(argObj, name, value, variables) {
      if (isIntValue(value) || isFloatValue(value)) {
          argObj[name.value] = Number(value.value);
      }
      else if (isBooleanValue(value) || isStringValue(value)) {
          argObj[name.value] = value.value;
      }
      else if (isObjectValue(value)) {
          var nestedArgObj_1 = {};
          value.fields.map(function (obj) {
              return valueToObjectRepresentation(nestedArgObj_1, obj.name, obj.value, variables);
          });
          argObj[name.value] = nestedArgObj_1;
      }
      else if (isVariable(value)) {
          var variableValue = (variables || {})[value.name.value];
          argObj[name.value] = variableValue;
      }
      else if (isListValue(value)) {
          argObj[name.value] = value.values.map(function (listValue) {
              var nestedArgArrayObj = {};
              valueToObjectRepresentation(nestedArgArrayObj, name, listValue, variables);
              return nestedArgArrayObj[name.value];
          });
      }
      else if (isEnumValue(value)) {
          argObj[name.value] = value.value;
      }
      else if (isNullValue(value)) {
          argObj[name.value] = null;
      }
      else {
          throw process.env.NODE_ENV === "production" ? new tsInvariant.InvariantError(53) : new tsInvariant.InvariantError("The inline argument \"" + name.value + "\" of kind \"" + value.kind + "\"" +
              'is not supported. Use variables instead of inline arguments to ' +
              'overcome this limitation.');
      }
  }
  function storeKeyNameFromField(field, variables) {
      var directivesObj = null;
      if (field.directives) {
          directivesObj = {};
          field.directives.forEach(function (directive) {
              directivesObj[directive.name.value] = {};
              if (directive.arguments) {
                  directive.arguments.forEach(function (_a) {
                      var name = _a.name, value = _a.value;
                      return valueToObjectRepresentation(directivesObj[directive.name.value], name, value, variables);
                  });
              }
          });
      }
      var argObj = null;
      if (field.arguments && field.arguments.length) {
          argObj = {};
          field.arguments.forEach(function (_a) {
              var name = _a.name, value = _a.value;
              return valueToObjectRepresentation(argObj, name, value, variables);
          });
      }
      return getStoreKeyName(field.name.value, argObj, directivesObj);
  }
  var KNOWN_DIRECTIVES = [
      'connection',
      'include',
      'skip',
      'client',
      'rest',
      'export',
  ];
  function getStoreKeyName(fieldName, args, directives) {
      if (args &&
          directives &&
          directives['connection'] &&
          directives['connection']['key']) {
          if (directives['connection']['filter'] &&
              directives['connection']['filter'].length > 0) {
              var filterKeys = directives['connection']['filter']
                  ? directives['connection']['filter']
                  : [];
              filterKeys.sort();
              var filteredArgs_1 = {};
              filterKeys.forEach(function (key) {
                  filteredArgs_1[key] = args[key];
              });
              return directives['connection']['key'] + "(" + JSON.stringify(filteredArgs_1) + ")";
          }
          else {
              return directives['connection']['key'];
          }
      }
      var completeFieldName = fieldName;
      if (args) {
          var stringifiedArgs = stringify(args);
          completeFieldName += "(" + stringifiedArgs + ")";
      }
      if (directives) {
          Object.keys(directives).forEach(function (key) {
              if (KNOWN_DIRECTIVES.indexOf(key) !== -1)
                  return;
              if (directives[key] && Object.keys(directives[key]).length) {
                  completeFieldName += "@" + key + "(" + JSON.stringify(directives[key]) + ")";
              }
              else {
                  completeFieldName += "@" + key;
              }
          });
      }
      return completeFieldName;
  }
  function argumentsObjectFromField(field, variables) {
      if (field.arguments && field.arguments.length) {
          var argObj_1 = {};
          field.arguments.forEach(function (_a) {
              var name = _a.name, value = _a.value;
              return valueToObjectRepresentation(argObj_1, name, value, variables);
          });
          return argObj_1;
      }
      return null;
  }
  function resultKeyNameFromField(field) {
      return field.alias ? field.alias.value : field.name.value;
  }
  function getTypenameFromResult(result, selectionSet, fragmentMap) {
      if (typeof result.__typename === 'string') {
          return result.__typename;
      }
      for (var _i = 0, _a = selectionSet.selections; _i < _a.length; _i++) {
          var selection = _a[_i];
          if (isField(selection)) {
              if (selection.name.value === '__typename') {
                  return result[resultKeyNameFromField(selection)];
              }
          }
          else {
              var typename = getTypenameFromResult(result, getFragmentFromSelection(selection, fragmentMap).selectionSet, fragmentMap);
              if (typeof typename === 'string') {
                  return typename;
              }
          }
      }
  }
  function isField(selection) {
      return selection.kind === 'Field';
  }
  function isInlineFragment(selection) {
      return selection.kind === 'InlineFragment';
  }
  
  function checkDocument(doc) {
      process.env.NODE_ENV === "production" ? tsInvariant.invariant(doc && doc.kind === 'Document', 45) : tsInvariant.invariant(doc && doc.kind === 'Document', "Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql");
      var operations = doc.definitions
          .filter(function (d) { return d.kind !== 'FragmentDefinition'; })
          .map(function (definition) {
          if (definition.kind !== 'OperationDefinition') {
              throw process.env.NODE_ENV === "production" ? new tsInvariant.InvariantError(46) : new tsInvariant.InvariantError("Schema type definitions not allowed in queries. Found: \"" + definition.kind + "\"");
          }
          return definition;
      });
      process.env.NODE_ENV === "production" ? tsInvariant.invariant(operations.length <= 1, 47) : tsInvariant.invariant(operations.length <= 1, "Ambiguous GraphQL document: contains " + operations.length + " operations");
      return doc;
  }
  function getOperationDefinition(doc) {
      checkDocument(doc);
      return doc.definitions.filter(function (definition) { return definition.kind === 'OperationDefinition'; })[0];
  }
  function getOperationName(doc) {
      return (doc.definitions
          .filter(function (definition) {
          return definition.kind === 'OperationDefinition' && definition.name;
      })
          .map(function (x) { return x.name.value; })[0] || null);
  }
  function getFragmentDefinitions(doc) {
      return doc.definitions.filter(function (definition) { return definition.kind === 'FragmentDefinition'; });
  }
  function getQueryDefinition(doc) {
      var queryDef = getOperationDefinition(doc);
      process.env.NODE_ENV === "production" ? tsInvariant.invariant(queryDef && queryDef.operation === 'query', 48) : tsInvariant.invariant(queryDef && queryDef.operation === 'query', 'Must contain a query definition.');
      return queryDef;
  }
  function getFragmentDefinition(doc) {
      process.env.NODE_ENV === "production" ? tsInvariant.invariant(doc.kind === 'Document', 49) : tsInvariant.invariant(doc.kind === 'Document', "Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql");
      process.env.NODE_ENV === "production" ? tsInvariant.invariant(doc.definitions.length <= 1, 50) : tsInvariant.invariant(doc.definitions.length <= 1, 'Fragment must have exactly one definition.');
      var fragmentDef = doc.definitions[0];
      process.env.NODE_ENV === "production" ? tsInvariant.invariant(fragmentDef.kind === 'FragmentDefinition', 51) : tsInvariant.invariant(fragmentDef.kind === 'FragmentDefinition', 'Must be a fragment definition.');
      return fragmentDef;
  }
  function getMainDefinition(queryDoc) {
      checkDocument(queryDoc);
      var fragmentDefinition;
      for (var _i = 0, _a = queryDoc.definitions; _i < _a.length; _i++) {
          var definition = _a[_i];
          if (definition.kind === 'OperationDefinition') {
              var operation = definition.operation;
              if (operation === 'query' ||
                  operation === 'mutation' ||
                  operation === 'subscription') {
                  return definition;
              }
          }
          if (definition.kind === 'FragmentDefinition' && !fragmentDefinition) {
              fragmentDefinition = definition;
          }
      }
      if (fragmentDefinition) {
          return fragmentDefinition;
      }
      throw process.env.NODE_ENV === "production" ? new tsInvariant.InvariantError(52) : new tsInvariant.InvariantError('Expected a parsed GraphQL query with a query, mutation, subscription, or a fragment.');
  }
  function getDefaultValues(definition) {
      var defaultValues = Object.create(null);
      var defs = definition && definition.variableDefinitions;
      if (defs && defs.length) {
          defs.forEach(function (def) {
              if (def.defaultValue) {
                  valueToObjectRepresentation(defaultValues, def.variable.name, def.defaultValue);
              }
          });
      }
      return defaultValues;
  }
  
  function filterInPlace(array, test, context) {
      var target = 0;
      array.forEach(function (elem, i) {
          if (test.call(this, elem, i, array)) {
              array[target++] = elem;
          }
      }, context);
      array.length = target;
      return array;
  }
  
  var TYPENAME_FIELD = {
      kind: 'Field',
      name: {
          kind: 'Name',
          value: '__typename',
      },
  };
  function isEmpty(op, fragments) {
      return op.selectionSet.selections.every(function (selection) {
          return selection.kind === 'FragmentSpread' &&
              isEmpty(fragments[selection.name.value], fragments);
      });
  }
  function nullIfDocIsEmpty(doc) {
      return isEmpty(getOperationDefinition(doc) || getFragmentDefinition(doc), createFragmentMap(getFragmentDefinitions(doc)))
          ? null
          : doc;
  }
  function getDirectiveMatcher(directives) {
      return function directiveMatcher(directive) {
          return directives.some(function (dir) {
              return (dir.name && dir.name === directive.name.value) ||
                  (dir.test && dir.test(directive));
          });
      };
  }
  function removeDirectivesFromDocument(directives, doc) {
      var variablesInUse = Object.create(null);
      var variablesToRemove = [];
      var fragmentSpreadsInUse = Object.create(null);
      var fragmentSpreadsToRemove = [];
      var modifiedDoc = nullIfDocIsEmpty(graphql.visit(doc, {
          Variable: {
              enter: function (node, _key, parent) {
                  if (parent.kind !== 'VariableDefinition') {
                      variablesInUse[node.name.value] = true;
                  }
              },
          },
          Field: {
              enter: function (node) {
                  if (directives && node.directives) {
                      var shouldRemoveField = directives.some(function (directive) { return directive.remove; });
                      if (shouldRemoveField &&
                          node.directives &&
                          node.directives.some(getDirectiveMatcher(directives))) {
                          if (node.arguments) {
                              node.arguments.forEach(function (arg) {
                                  if (arg.value.kind === 'Variable') {
                                      variablesToRemove.push({
                                          name: arg.value.name.value,
                                      });
                                  }
                              });
                          }
                          if (node.selectionSet) {
                              getAllFragmentSpreadsFromSelectionSet(node.selectionSet).forEach(function (frag) {
                                  fragmentSpreadsToRemove.push({
                                      name: frag.name.value,
                                  });
                              });
                          }
                          return null;
                      }
                  }
              },
          },
          FragmentSpread: {
              enter: function (node) {
                  fragmentSpreadsInUse[node.name.value] = true;
              },
          },
          Directive: {
              enter: function (node) {
                  if (getDirectiveMatcher(directives)(node)) {
                      return null;
                  }
              },
          },
      }));
      if (modifiedDoc &&
          filterInPlace(variablesToRemove, function (v) { return !!v.name && !variablesInUse[v.name]; }).length) {
          modifiedDoc = removeArgumentsFromDocument(variablesToRemove, modifiedDoc);
      }
      if (modifiedDoc &&
          filterInPlace(fragmentSpreadsToRemove, function (fs) { return !!fs.name && !fragmentSpreadsInUse[fs.name]; })
              .length) {
          modifiedDoc = removeFragmentSpreadFromDocument(fragmentSpreadsToRemove, modifiedDoc);
      }
      return modifiedDoc;
  }
  function addTypenameToDocument(doc) {
      return graphql.visit(checkDocument(doc), {
          SelectionSet: {
              enter: function (node, _key, parent) {
                  if (parent &&
                      parent.kind === 'OperationDefinition') {
                      return;
                  }
                  var selections = node.selections;
                  if (!selections) {
                      return;
                  }
                  var skip = selections.some(function (selection) {
                      return (isField(selection) &&
                          (selection.name.value === '__typename' ||
                              selection.name.value.lastIndexOf('__', 0) === 0));
                  });
                  if (skip) {
                      return;
                  }
                  var field = parent;
                  if (isField(field) &&
                      field.directives &&
                      field.directives.some(function (d) { return d.name.value === 'export'; })) {
                      return;
                  }
                  return tslib.__assign(tslib.__assign({}, node), { selections: tslib.__spreadArrays(selections, [TYPENAME_FIELD]) });
              },
          },
      });
  }
  addTypenameToDocument.added = function (field) {
      return field === TYPENAME_FIELD;
  };
  var connectionRemoveConfig = {
      test: function (directive) {
          var willRemove = directive.name.value === 'connection';
          if (willRemove) {
              if (!directive.arguments ||
                  !directive.arguments.some(function (arg) { return arg.name.value === 'key'; })) {
                  process.env.NODE_ENV === "production" || tsInvariant.invariant.warn('Removing an @connection directive even though it does not have a key. ' +
                      'You may want to use the key parameter to specify a store key.');
              }
          }
          return willRemove;
      },
  };
  function removeConnectionDirectiveFromDocument(doc) {
      return removeDirectivesFromDocument([connectionRemoveConfig], checkDocument(doc));
  }
  function getArgumentMatcher(config) {
      return function argumentMatcher(argument) {
          return config.some(function (aConfig) {
              return argument.value &&
                  argument.value.kind === 'Variable' &&
                  argument.value.name &&
                  (aConfig.name === argument.value.name.value ||
                      (aConfig.test && aConfig.test(argument)));
          });
      };
  }
  function removeArgumentsFromDocument(config, doc) {
      var argMatcher = getArgumentMatcher(config);
      return nullIfDocIsEmpty(graphql.visit(doc, {
          OperationDefinition: {
              enter: function (node) {
                  return tslib.__assign(tslib.__assign({}, node), { variableDefinitions: node.variableDefinitions ? node.variableDefinitions.filter(function (varDef) {
                          return !config.some(function (arg) { return arg.name === varDef.variable.name.value; });
                      }) : [] });
              },
          },
          Field: {
              enter: function (node) {
                  var shouldRemoveField = config.some(function (argConfig) { return argConfig.remove; });
                  if (shouldRemoveField) {
                      var argMatchCount_1 = 0;
                      if (node.arguments) {
                          node.arguments.forEach(function (arg) {
                              if (argMatcher(arg)) {
                                  argMatchCount_1 += 1;
                              }
                          });
                      }
                      if (argMatchCount_1 === 1) {
                          return null;
                      }
                  }
              },
          },
          Argument: {
              enter: function (node) {
                  if (argMatcher(node)) {
                      return null;
                  }
              },
          },
      }));
  }
  function removeFragmentSpreadFromDocument(config, doc) {
      function enter(node) {
          if (config.some(function (def) { return def.name === node.name.value; })) {
              return null;
          }
      }
      return nullIfDocIsEmpty(graphql.visit(doc, {
          FragmentSpread: { enter: enter },
          FragmentDefinition: { enter: enter },
      }));
  }
  function getAllFragmentSpreadsFromSelectionSet(selectionSet) {
      var allFragments = [];
      selectionSet.selections.forEach(function (selection) {
          if ((isField(selection) || isInlineFragment(selection)) &&
              selection.selectionSet) {
              getAllFragmentSpreadsFromSelectionSet(selection.selectionSet).forEach(function (frag) { return allFragments.push(frag); });
          }
          else if (selection.kind === 'FragmentSpread') {
              allFragments.push(selection);
          }
      });
      return allFragments;
  }
  function buildQueryFromSelectionSet(document) {
      var definition = getMainDefinition(document);
      var definitionOperation = definition.operation;
      if (definitionOperation === 'query') {
          return document;
      }
      var modifiedDoc = graphql.visit(document, {
          OperationDefinition: {
              enter: function (node) {
                  return tslib.__assign(tslib.__assign({}, node), { operation: 'query' });
              },
          },
      });
      return modifiedDoc;
  }
  function removeClientSetsFromDocument(document) {
      checkDocument(document);
      var modifiedDoc = removeDirectivesFromDocument([
          {
              test: function (directive) { return directive.name.value === 'client'; },
              remove: true,
          },
      ], document);
      if (modifiedDoc) {
          modifiedDoc = graphql.visit(modifiedDoc, {
              FragmentDefinition: {
                  enter: function (node) {
                      if (node.selectionSet) {
                          var isTypenameOnly = node.selectionSet.selections.every(function (selection) {
                              return isField(selection) && selection.name.value === '__typename';
                          });
                          if (isTypenameOnly) {
                              return null;
                          }
                      }
                  },
              },
          });
      }
      return modifiedDoc;
  }
  
  var hasOwnProperty = Object.prototype.hasOwnProperty;
  function mergeDeep() {
      var sources = [];
      for (var _i = 0; _i < arguments.length; _i++) {
          sources[_i] = arguments[_i];
      }
      return mergeDeepArray(sources);
  }
  function mergeDeepArray(sources) {
      var target = sources[0] || {};
      var count = sources.length;
      if (count > 1) {
          var merger = new DeepMerger();
          for (var i = 1; i < count; ++i) {
              target = merger.merge(target, sources[i]);
          }
      }
      return target;
  }
  function isObject(obj) {
      return obj !== null && typeof obj === 'object';
  }
  var defaultReconciler = function (target, source, property) {
      return this.merge(target[property], source[property]);
  };
  var DeepMerger = (function () {
      function DeepMerger(reconciler) {
          if (reconciler === void 0) { reconciler = defaultReconciler; }
          this.reconciler = reconciler;
          this.isObject = isObject;
          this.pastCopies = new Set();
      }
      DeepMerger.prototype.merge = function (target, source) {
          var _this = this;
          var context = [];
          for (var _i = 2; _i < arguments.length; _i++) {
              context[_i - 2] = arguments[_i];
          }
          if (isObject(source) && isObject(target)) {
              Object.keys(source).forEach(function (sourceKey) {
                  if (hasOwnProperty.call(target, sourceKey)) {
                      var targetValue = target[sourceKey];
                      if (source[sourceKey] !== targetValue) {
                          var result = _this.reconciler.apply(_this, tslib.__spreadArrays([target, source, sourceKey], context));
                          if (result !== targetValue) {
                              target = _this.shallowCopyForMerge(target);
                              target[sourceKey] = result;
                          }
                      }
                  }
                  else {
                      target = _this.shallowCopyForMerge(target);
                      target[sourceKey] = source[sourceKey];
                  }
              });
              return target;
          }
          return source;
      };
      DeepMerger.prototype.shallowCopyForMerge = function (value) {
          if (isObject(value) && !this.pastCopies.has(value)) {
              if (Array.isArray(value)) {
                  value = value.slice(0);
              }
              else {
                  value = tslib.__assign({ __proto__: Object.getPrototypeOf(value) }, value);
              }
              this.pastCopies.add(value);
          }
          return value;
      };
      return DeepMerger;
  }());
  
  function concatPagination(keyArgs) {
      if (keyArgs === void 0) { keyArgs = false; }
      return {
          keyArgs: keyArgs,
          merge: function (existing, incoming) {
              return existing ? tslib.__spreadArrays(existing, incoming) : incoming;
          },
      };
  }
  function offsetLimitPagination(keyArgs) {
      if (keyArgs === void 0) { keyArgs = false; }
      return {
          keyArgs: keyArgs,
          merge: function (existing, incoming, _a) {
              var args = _a.args;
              var merged = existing ? existing.slice(0) : [];
              if (args) {
                  var _b = args.offset, offset = _b === void 0 ? 0 : _b;
                  for (var i = 0; i < incoming.length; ++i) {
                      merged[offset + i] = incoming[i];
                  }
              }
              else {
                  merged.push.apply(merged, incoming);
              }
              return merged;
          },
      };
  }
  function relayStylePagination(keyArgs) {
      if (keyArgs === void 0) { keyArgs = false; }
      return {
          keyArgs: keyArgs,
          read: function (existing, _a) {
              var canRead = _a.canRead, readField = _a.readField;
              if (!existing)
                  return;
              var edges = [];
              var firstEdgeCursor = "";
              var lastEdgeCursor = "";
              existing.edges.forEach(function (edge) {
                  if (canRead(readField("node", edge))) {
                      edges.push(edge);
                      if (edge.cursor) {
                          firstEdgeCursor = firstEdgeCursor || edge.cursor || "";
                          lastEdgeCursor = edge.cursor || lastEdgeCursor;
                      }
                  }
              });
              var _b = existing.pageInfo || {}, startCursor = _b.startCursor, endCursor = _b.endCursor;
              return tslib.__assign(tslib.__assign({}, getExtras(existing)), { edges: edges, pageInfo: tslib.__assign(tslib.__assign({}, existing.pageInfo), { startCursor: startCursor || firstEdgeCursor, endCursor: endCursor || lastEdgeCursor }) });
          },
          merge: function (existing, incoming, _a) {
              if (existing === void 0) { existing = makeEmptyData(); }
              var args = _a.args, isReference = _a.isReference, readField = _a.readField;
              var incomingEdges = incoming.edges ? incoming.edges.map(function (edge) {
                  if (isReference(edge = tslib.__assign({}, edge))) {
                      edge.cursor = readField("cursor", edge);
                  }
                  return edge;
              }) : [];
              if (incoming.pageInfo) {
                  var pageInfo_1 = incoming.pageInfo;
                  var startCursor = pageInfo_1.startCursor, endCursor = pageInfo_1.endCursor;
                  var firstEdge = incomingEdges[0];
                  var lastEdge = incomingEdges[incomingEdges.length - 1];
                  if (firstEdge && startCursor) {
                      firstEdge.cursor = startCursor;
                  }
                  if (lastEdge && endCursor) {
                      lastEdge.cursor = endCursor;
                  }
                  var firstCursor = firstEdge && firstEdge.cursor;
                  if (firstCursor && !startCursor) {
                      incoming = mergeDeep(incoming, {
                          pageInfo: {
                              startCursor: firstCursor,
                          },
                      });
                  }
                  var lastCursor = lastEdge && lastEdge.cursor;
                  if (lastCursor && !endCursor) {
                      incoming = mergeDeep(incoming, {
                          pageInfo: {
                              endCursor: lastCursor,
                          },
                      });
                  }
              }
              var prefix = existing.edges;
              var suffix = [];
              if (args && args.after) {
                  var index = prefix.findIndex(function (edge) { return edge.cursor === args.after; });
                  if (index >= 0) {
                      prefix = prefix.slice(0, index + 1);
                  }
              }
              else if (args && args.before) {
                  var index = prefix.findIndex(function (edge) { return edge.cursor === args.before; });
                  suffix = index < 0 ? prefix : prefix.slice(index);
                  prefix = [];
              }
              else if (incoming.edges) {
                  prefix = [];
              }
              var edges = tslib.__spreadArrays(prefix, incomingEdges, suffix);
              var pageInfo = tslib.__assign(tslib.__assign({}, incoming.pageInfo), existing.pageInfo);
              if (incoming.pageInfo) {
                  var _b = incoming.pageInfo, hasPreviousPage = _b.hasPreviousPage, hasNextPage = _b.hasNextPage, startCursor = _b.startCursor, endCursor = _b.endCursor, extras = tslib.__rest(_b, ["hasPreviousPage", "hasNextPage", "startCursor", "endCursor"]);
                  Object.assign(pageInfo, extras);
                  if (!prefix.length) {
                      if (void 0 !== hasPreviousPage)
                          pageInfo.hasPreviousPage = hasPreviousPage;
                      if (void 0 !== startCursor)
                          pageInfo.startCursor = startCursor;
                  }
                  if (!suffix.length) {
                      if (void 0 !== hasNextPage)
                          pageInfo.hasNextPage = hasNextPage;
                      if (void 0 !== endCursor)
                          pageInfo.endCursor = endCursor;
                  }
              }
              return tslib.__assign(tslib.__assign(tslib.__assign({}, getExtras(existing)), getExtras(incoming)), { edges: edges,
                  pageInfo: pageInfo });
          },
      };
  }
  var getExtras = function (obj) { return tslib.__rest(obj, notExtras); };
  var notExtras = ["edges", "pageInfo"];
  function makeEmptyData() {
      return {
          edges: [],
          pageInfo: {
              hasPreviousPage: false,
              hasNextPage: true,
              startCursor: "",
              endCursor: "",
          },
      };
  }
  
  var toString = Object.prototype.toString;
  function cloneDeep(value) {
      return cloneDeepHelper(value);
  }
  function cloneDeepHelper(val, seen) {
      switch (toString.call(val)) {
          case "[object Array]": {
              seen = seen || new Map;
              if (seen.has(val))
                  return seen.get(val);
              var copy_1 = val.slice(0);
              seen.set(val, copy_1);
              copy_1.forEach(function (child, i) {
                  copy_1[i] = cloneDeepHelper(child, seen);
              });
              return copy_1;
          }
          case "[object Object]": {
              seen = seen || new Map;
              if (seen.has(val))
                  return seen.get(val);
              var copy_2 = Object.create(Object.getPrototypeOf(val));
              seen.set(val, copy_2);
              Object.keys(val).forEach(function (key) {
                  copy_2[key] = cloneDeepHelper(val[key], seen);
              });
              return copy_2;
          }
          default:
              return val;
      }
  }
  
  function getEnv() {
      if (typeof process !== 'undefined' && process.env.NODE_ENV) {
          return process.env.NODE_ENV;
      }
      return 'development';
  }
  function isEnv(env) {
      return getEnv() === env;
  }
  function isDevelopment() {
      return isEnv('development') === true;
  }
  function isTest() {
      return isEnv('test') === true;
  }
  
  function isObject$1(value) {
      return value !== null && typeof value === "object";
  }
  function deepFreeze(value) {
      var workSet = new Set([value]);
      workSet.forEach(function (obj) {
          if (isObject$1(obj)) {
              if (!Object.isFrozen(obj))
                  Object.freeze(obj);
              Object.getOwnPropertyNames(obj).forEach(function (name) {
                  if (isObject$1(obj[name]))
                      workSet.add(obj[name]);
              });
          }
      });
      return value;
  }
  function maybeDeepFreeze(obj) {
      if (process.env.NODE_ENV !== "production" && (isDevelopment() || isTest())) {
          deepFreeze(obj);
      }
      return obj;
  }
  
  function iterateObserversSafely(observers, method, argument) {
      var observersWithMethod = [];
      observers.forEach(function (obs) { return obs[method] && observersWithMethod.push(obs); });
      observersWithMethod.forEach(function (obs) { return obs[method](argument); });
  }
  
  function asyncMap(observable, mapFn, catchFn) {
      return new Observable(function (observer) {
          var next = observer.next, error = observer.error, complete = observer.complete;
          var activeCallbackCount = 0;
          var completed = false;
          var promiseQueue = {
              then: function (callback) {
                  return new Promise(function (resolve) { return resolve(callback()); });
              },
          };
          function makeCallback(examiner, delegate) {
              if (examiner) {
                  return function (arg) {
                      ++activeCallbackCount;
                      var both = function () { return examiner(arg); };
                      promiseQueue = promiseQueue.then(both, both).then(function (result) {
                          --activeCallbackCount;
                          next && next.call(observer, result);
                          if (completed) {
                              handler.complete();
                          }
                      }, function (error) {
                          --activeCallbackCount;
                          throw error;
                      }).catch(function (caught) {
                          error && error.call(observer, caught);
                      });
                  };
              }
              else {
                  return function (arg) { return delegate && delegate.call(observer, arg); };
              }
          }
          var handler = {
              next: makeCallback(mapFn, next),
              error: makeCallback(catchFn, error),
              complete: function () {
                  completed = true;
                  if (!activeCallbackCount) {
                      complete && complete.call(observer);
                  }
              },
          };
          var sub = observable.subscribe(handler);
          return function () { return sub.unsubscribe(); };
      });
  }
  
  function fixObservableSubclass(subclass) {
      function set(key) {
          Object.defineProperty(subclass, key, { value: Observable });
      }
      if (typeof Symbol === "function" && Symbol.species) {
          set(Symbol.species);
      }
      set("@@species");
      return subclass;
  }
  
  function isPromiseLike(value) {
      return value && typeof value.then === "function";
  }
  var Concast = (function (_super) {
      tslib.__extends(Concast, _super);
      function Concast(sources) {
          var _this = _super.call(this, function (observer) {
              _this.addObserver(observer);
              return function () { return _this.removeObserver(observer); };
          }) || this;
          _this.observers = new Set();
          _this.addCount = 0;
          _this.promise = new Promise(function (resolve, reject) {
              _this.resolve = resolve;
              _this.reject = reject;
          });
          _this.handlers = {
              next: function (result) {
                  if (_this.sub !== null) {
                      _this.latest = ["next", result];
                      iterateObserversSafely(_this.observers, "next", result);
                  }
              },
              error: function (error) {
                  var sub = _this.sub;
                  if (sub !== null) {
                      if (sub)
                          Promise.resolve().then(function () { return sub.unsubscribe(); });
                      _this.sub = null;
                      _this.latest = ["error", error];
                      _this.reject(error);
                      iterateObserversSafely(_this.observers, "error", error);
                  }
              },
              complete: function () {
                  if (_this.sub !== null) {
                      var value = _this.sources.shift();
                      if (!value) {
                          _this.sub = null;
                          if (_this.latest &&
                              _this.latest[0] === "next") {
                              _this.resolve(_this.latest[1]);
                          }
                          else {
                              _this.resolve();
                          }
                          iterateObserversSafely(_this.observers, "complete");
                      }
                      else if (isPromiseLike(value)) {
                          value.then(function (obs) { return _this.sub = obs.subscribe(_this.handlers); });
                      }
                      else {
                          _this.sub = value.subscribe(_this.handlers);
                      }
                  }
              },
          };
          _this.cancel = function (reason) {
              _this.reject(reason);
              _this.sources = [];
              _this.handlers.complete();
          };
          _this.promise.catch(function (_) { });
          if (typeof sources === "function") {
              sources = [new Observable(sources)];
          }
          if (isPromiseLike(sources)) {
              sources.then(function (iterable) { return _this.start(iterable); }, _this.handlers.error);
          }
          else {
              _this.start(sources);
          }
          return _this;
      }
      Concast.prototype.start = function (sources) {
          if (this.sub !== void 0)
              return;
          this.sources = Array.from(sources);
          this.handlers.complete();
      };
      Concast.prototype.deliverLastMessage = function (observer) {
          if (this.latest) {
              var nextOrError = this.latest[0];
              var method = observer[nextOrError];
              if (method) {
                  method.call(observer, this.latest[1]);
              }
              if (this.sub === null &&
                  nextOrError === "next" &&
                  observer.complete) {
                  observer.complete();
              }
          }
      };
      Concast.prototype.addObserver = function (observer) {
          if (!this.observers.has(observer)) {
              this.deliverLastMessage(observer);
              this.observers.add(observer);
              ++this.addCount;
          }
      };
      Concast.prototype.removeObserver = function (observer, quietly) {
          if (this.observers.delete(observer) &&
              --this.addCount < 1 &&
              !quietly) {
              this.handlers.error(new Error("Observable cancelled prematurely"));
          }
      };
      Concast.prototype.cleanup = function (callback) {
          var _this = this;
          var called = false;
          var once = function () {
              if (!called) {
                  called = true;
                  _this.observers.delete(observer);
                  callback();
              }
          };
          var observer = {
              next: once,
              error: once,
              complete: once,
          };
          var count = this.addCount;
          this.addObserver(observer);
          this.addCount = count;
      };
      return Concast;
  }(Observable));
  fixObservableSubclass(Concast);
  
  function isNonEmptyArray(value) {
      return Array.isArray(value) && value.length > 0;
  }
  
  function graphQLResultHasError(result) {
      return (result.errors && result.errors.length > 0) || false;
  }
  
  var canUseWeakMap = typeof WeakMap === 'function' && !(typeof navigator === 'object' &&
      navigator.product === 'ReactNative');
  
  function compact() {
      var objects = [];
      for (var _i = 0; _i < arguments.length; _i++) {
          objects[_i] = arguments[_i];
      }
      var result = Object.create(null);
      objects.forEach(function (obj) {
          if (!obj)
              return;
          Object.keys(obj).forEach(function (key) {
              var value = obj[key];
              if (value !== void 0) {
                  result[key] = value;
              }
          });
      });
      return result;
  }
  
  exports.Observable = Observable;
  exports.Concast = Concast;
  exports.DeepMerger = DeepMerger;
  exports.addTypenameToDocument = addTypenameToDocument;
  exports.argumentsObjectFromField = argumentsObjectFromField;
  exports.asyncMap = asyncMap;
  exports.buildQueryFromSelectionSet = buildQueryFromSelectionSet;
  exports.canUseWeakMap = canUseWeakMap;
  exports.checkDocument = checkDocument;
  exports.cloneDeep = cloneDeep;
  exports.compact = compact;
  exports.concatPagination = concatPagination;
  exports.createFragmentMap = createFragmentMap;
  exports.fixObservableSubclass = fixObservableSubclass;
  exports.getDefaultValues = getDefaultValues;
  exports.getDirectiveNames = getDirectiveNames;
  exports.getFragmentDefinition = getFragmentDefinition;
  exports.getFragmentDefinitions = getFragmentDefinitions;
  exports.getFragmentFromSelection = getFragmentFromSelection;
  exports.getFragmentQueryDocument = getFragmentQueryDocument;
  exports.getInclusionDirectives = getInclusionDirectives;
  exports.getMainDefinition = getMainDefinition;
  exports.getOperationDefinition = getOperationDefinition;
  exports.getOperationName = getOperationName;
  exports.getQueryDefinition = getQueryDefinition;
  exports.getStoreKeyName = getStoreKeyName;
  exports.getTypenameFromResult = getTypenameFromResult;
  exports.graphQLResultHasError = graphQLResultHasError;
  exports.hasClientExports = hasClientExports;
  exports.hasDirectives = hasDirectives;
  exports.isField = isField;
  exports.isInlineFragment = isInlineFragment;
  exports.isNonEmptyArray = isNonEmptyArray;
  exports.isReference = isReference;
  exports.iterateObserversSafely = iterateObserversSafely;
  exports.makeReference = makeReference;
  exports.maybeDeepFreeze = maybeDeepFreeze;
  exports.mergeDeep = mergeDeep;
  exports.mergeDeepArray = mergeDeepArray;
  exports.offsetLimitPagination = offsetLimitPagination;
  exports.relayStylePagination = relayStylePagination;
  exports.removeArgumentsFromDocument = removeArgumentsFromDocument;
  exports.removeClientSetsFromDocument = removeClientSetsFromDocument;
  exports.removeConnectionDirectiveFromDocument = removeConnectionDirectiveFromDocument;
  exports.removeDirectivesFromDocument = removeDirectivesFromDocument;
  exports.removeFragmentSpreadFromDocument = removeFragmentSpreadFromDocument;
  exports.resultKeyNameFromField = resultKeyNameFromField;
  exports.shouldInclude = shouldInclude;
  exports.storeKeyNameFromField = storeKeyNameFromField;
  exports.valueToObjectRepresentation = valueToObjectRepresentation;
  //# sourceMappingURL=utilities.cjs.js.map
  