1"use strict"; 2 3var t = require("@babel/types"); 4var convertComments = require("./convertComments"); 5 6module.exports = function(ast, traverse, code) { 7 var state = { source: code }; 8 9 // Monkey patch visitor keys in order to be able to traverse the estree nodes 10 t.VISITOR_KEYS.Property = t.VISITOR_KEYS.ObjectProperty; 11 t.VISITOR_KEYS.MethodDefinition = [ 12 "key", 13 "value", 14 "decorators", 15 "returnType", 16 "typeParameters", 17 ]; 18 19 traverse(ast, astTransformVisitor, null, state); 20 21 delete t.VISITOR_KEYS.Property; 22 delete t.VISITOR_KEYS.MethodDefinition; 23}; 24 25var astTransformVisitor = { 26 noScope: true, 27 enter(path) { 28 var node = path.node; 29 30 // private var to track original node type 31 node._babelType = node.type; 32 33 if (node.innerComments) { 34 node.trailingComments = node.innerComments; 35 delete node.innerComments; 36 } 37 38 if (node.trailingComments) { 39 convertComments(node.trailingComments); 40 } 41 42 if (node.leadingComments) { 43 convertComments(node.leadingComments); 44 } 45 }, 46 exit(path) { 47 var node = path.node; 48 49 if (path.isJSXText()) { 50 node.type = "Literal"; 51 } 52 53 if ( 54 path.isRestElement() && 55 path.parent && 56 path.parent.type === "ObjectPattern" 57 ) { 58 node.type = "ExperimentalRestProperty"; 59 } 60 61 if ( 62 path.isSpreadElement() && 63 path.parent && 64 path.parent.type === "ObjectExpression" 65 ) { 66 node.type = "ExperimentalSpreadProperty"; 67 } 68 69 if (path.isTypeParameter()) { 70 node.type = "Identifier"; 71 node.typeAnnotation = node.bound; 72 delete node.bound; 73 } 74 75 // flow: prevent "no-undef" 76 // for "Component" in: "let x: React.Component" 77 if (path.isQualifiedTypeIdentifier()) { 78 delete node.id; 79 } 80 // for "b" in: "var a: { b: Foo }" 81 if (path.isObjectTypeProperty()) { 82 delete node.key; 83 } 84 // for "indexer" in: "var a: {[indexer: string]: number}" 85 if (path.isObjectTypeIndexer()) { 86 delete node.id; 87 } 88 // for "param" in: "var a: { func(param: Foo): Bar };" 89 if (path.isFunctionTypeParam()) { 90 delete node.name; 91 } 92 93 // modules 94 95 if (path.isImportDeclaration()) { 96 delete node.isType; 97 } 98 99 // template string range fixes 100 if (path.isTemplateLiteral()) { 101 for (var j = 0; j < node.quasis.length; j++) { 102 var q = node.quasis[j]; 103 q.range[0] -= 1; 104 if (q.tail) { 105 q.range[1] += 1; 106 } else { 107 q.range[1] += 2; 108 } 109 q.loc.start.column -= 1; 110 if (q.tail) { 111 q.loc.end.column += 1; 112 } else { 113 q.loc.end.column += 2; 114 } 115 } 116 } 117 }, 118}; 119