traverse.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.traverse = traverse;
  6. var _nodePath = require("./node-path");
  7. var _nodes = require("./nodes");
  8. // recursively walks the AST starting at the given node. The callback is invoked for
  9. // and object that has a 'type' property.
  10. function walk(context, callback) {
  11. var stop = false;
  12. function innerWalk(context, callback) {
  13. if (stop) {
  14. return;
  15. }
  16. var node = context.node;
  17. if (node === undefined) {
  18. console.warn("traversing with an empty context");
  19. return;
  20. }
  21. if (node._deleted === true) {
  22. return;
  23. }
  24. var path = (0, _nodePath.createPath)(context);
  25. callback(node.type, path);
  26. if (path.shouldStop) {
  27. stop = true;
  28. return;
  29. }
  30. Object.keys(node).forEach(function (prop) {
  31. var value = node[prop];
  32. if (value === null || value === undefined) {
  33. return;
  34. }
  35. var valueAsArray = Array.isArray(value) ? value : [value];
  36. valueAsArray.forEach(function (childNode) {
  37. if (typeof childNode.type === "string") {
  38. var childContext = {
  39. node: childNode,
  40. parentKey: prop,
  41. parentPath: path,
  42. shouldStop: false,
  43. inList: Array.isArray(value)
  44. };
  45. innerWalk(childContext, callback);
  46. }
  47. });
  48. });
  49. }
  50. innerWalk(context, callback);
  51. }
  52. var noop = function noop() {};
  53. function traverse(node, visitors) {
  54. var before = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : noop;
  55. var after = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : noop;
  56. Object.keys(visitors).forEach(function (visitor) {
  57. if (!_nodes.nodeAndUnionTypes.includes(visitor)) {
  58. throw new Error("Unexpected visitor ".concat(visitor));
  59. }
  60. });
  61. var context = {
  62. node: node,
  63. inList: false,
  64. shouldStop: false,
  65. parentPath: null,
  66. parentKey: null
  67. };
  68. walk(context, function (type, path) {
  69. if (typeof visitors[type] === "function") {
  70. before(type, path);
  71. visitors[type](path);
  72. after(type, path);
  73. }
  74. var unionTypes = _nodes.unionTypesMap[type];
  75. if (!unionTypes) {
  76. throw new Error("Unexpected node type ".concat(type));
  77. }
  78. unionTypes.forEach(function (unionType) {
  79. if (typeof visitors[unionType] === "function") {
  80. before(unionType, path);
  81. visitors[unionType](path);
  82. after(unionType, path);
  83. }
  84. });
  85. });
  86. }