JavaScript AST manipulation with Babel: 3 ways to create nodes and subtrees – Trickster Dev

submited by
Style Pass
2023-01-23 10:00:14

When doing Javascript deobfuscation work at AST level one will need to create new parts of AST for replacing the existing parts of AST being processed. We will go through 3 ways of doing that.

We don’t need to worry about File and Program objects and should only focus on the program body that contains the following child nodes:

In software development there is often a tradeoff to be made between simplicity of the code and it’s flexibility. We will start with the least simple, but most flexible approach - explicitly instantiating AST node objects and arranging them in a way that recreates the AST subtree above.

We need to refer to spec for Babel AST objects and their properties in Babel codebase file packages/babel-parser/ast/ Furthermore, we need to check node creation APIs in @babel/types documentation.

Note that we can build AST node objects either by using factory functions from @babel/types or by defining them as JS objects directly. Compare how debugStmt1 and debugStmt2 were created.

Leave a Comment