NoFragmentCyclesRule.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true,
  4. });
  5. exports.NoFragmentCyclesRule = NoFragmentCyclesRule;
  6. var _GraphQLError = require('../../error/GraphQLError.js');
  7. /**
  8. * No fragment cycles
  9. *
  10. * The graph of fragment spreads must not form any cycles including spreading itself.
  11. * Otherwise an operation could infinitely spread or infinitely execute on cycles in the underlying data.
  12. *
  13. * See https://spec.graphql.org/draft/#sec-Fragment-spreads-must-not-form-cycles
  14. */
  15. function NoFragmentCyclesRule(context) {
  16. // Tracks already visited fragments to maintain O(N) and to ensure that cycles
  17. // are not redundantly reported.
  18. const visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors
  19. const spreadPath = []; // Position in the spread path
  20. const spreadPathIndexByName = Object.create(null);
  21. return {
  22. OperationDefinition: () => false,
  23. FragmentDefinition(node) {
  24. detectCycleRecursive(node);
  25. return false;
  26. },
  27. }; // This does a straight-forward DFS to find cycles.
  28. // It does not terminate when a cycle was found but continues to explore
  29. // the graph to find all possible cycles.
  30. function detectCycleRecursive(fragment) {
  31. if (visitedFrags[fragment.name.value]) {
  32. return;
  33. }
  34. const fragmentName = fragment.name.value;
  35. visitedFrags[fragmentName] = true;
  36. const spreadNodes = context.getFragmentSpreads(fragment.selectionSet);
  37. if (spreadNodes.length === 0) {
  38. return;
  39. }
  40. spreadPathIndexByName[fragmentName] = spreadPath.length;
  41. for (const spreadNode of spreadNodes) {
  42. const spreadName = spreadNode.name.value;
  43. const cycleIndex = spreadPathIndexByName[spreadName];
  44. spreadPath.push(spreadNode);
  45. if (cycleIndex === undefined) {
  46. const spreadFragment = context.getFragment(spreadName);
  47. if (spreadFragment) {
  48. detectCycleRecursive(spreadFragment);
  49. }
  50. } else {
  51. const cyclePath = spreadPath.slice(cycleIndex);
  52. const viaPath = cyclePath
  53. .slice(0, -1)
  54. .map((s) => '"' + s.name.value + '"')
  55. .join(', ');
  56. context.reportError(
  57. new _GraphQLError.GraphQLError(
  58. `Cannot spread fragment "${spreadName}" within itself` +
  59. (viaPath !== '' ? ` via ${viaPath}.` : '.'),
  60. {
  61. nodes: cyclePath,
  62. },
  63. ),
  64. );
  65. }
  66. spreadPath.pop();
  67. }
  68. spreadPathIndexByName[fragmentName] = undefined;
  69. }
  70. }