NoFragmentCyclesRule.mjs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { GraphQLError } from "../../error/GraphQLError.mjs";
  2. export function NoFragmentCyclesRule(context) {
  3. // Tracks already visited fragments to maintain O(N) and to ensure that cycles
  4. // are not redundantly reported.
  5. var visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors
  6. var spreadPath = []; // Position in the spread path
  7. var spreadPathIndexByName = Object.create(null);
  8. return {
  9. OperationDefinition: function OperationDefinition() {
  10. return false;
  11. },
  12. FragmentDefinition: function FragmentDefinition(node) {
  13. detectCycleRecursive(node);
  14. return false;
  15. }
  16. }; // This does a straight-forward DFS to find cycles.
  17. // It does not terminate when a cycle was found but continues to explore
  18. // the graph to find all possible cycles.
  19. function detectCycleRecursive(fragment) {
  20. if (visitedFrags[fragment.name.value]) {
  21. return;
  22. }
  23. var fragmentName = fragment.name.value;
  24. visitedFrags[fragmentName] = true;
  25. var spreadNodes = context.getFragmentSpreads(fragment.selectionSet);
  26. if (spreadNodes.length === 0) {
  27. return;
  28. }
  29. spreadPathIndexByName[fragmentName] = spreadPath.length;
  30. for (var _i2 = 0; _i2 < spreadNodes.length; _i2++) {
  31. var spreadNode = spreadNodes[_i2];
  32. var spreadName = spreadNode.name.value;
  33. var cycleIndex = spreadPathIndexByName[spreadName];
  34. spreadPath.push(spreadNode);
  35. if (cycleIndex === undefined) {
  36. var spreadFragment = context.getFragment(spreadName);
  37. if (spreadFragment) {
  38. detectCycleRecursive(spreadFragment);
  39. }
  40. } else {
  41. var cyclePath = spreadPath.slice(cycleIndex);
  42. var viaPath = cyclePath.slice(0, -1).map(function (s) {
  43. return '"' + s.name.value + '"';
  44. }).join(', ');
  45. context.reportError(new GraphQLError("Cannot spread fragment \"".concat(spreadName, "\" within itself") + (viaPath !== '' ? " via ".concat(viaPath, ".") : '.'), cyclePath));
  46. }
  47. spreadPath.pop();
  48. }
  49. spreadPathIndexByName[fragmentName] = undefined;
  50. }
  51. }