NoFragmentCycles.mjs 2.2 KB

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