Skip to content

Commit

Permalink
Updated dependencies and replaced outdated escodegen package by astri…
Browse files Browse the repository at this point in the history
…ng for now
  • Loading branch information
palant committed Jan 27, 2025
1 parent f6d9559 commit 8c10e7b
Show file tree
Hide file tree
Showing 3 changed files with 631 additions and 377 deletions.
43 changes: 33 additions & 10 deletions lib/io.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
import fs from "fs";
import path from "path";

import {generate as astToCode} from "escodegen";
import {traverse} from "estraverse";
import {generate as astToCode} from "astring";
import {parse as codeToAst} from "acorn";

function ensureParentDirExists(filepath)
Expand Down Expand Up @@ -37,7 +38,7 @@ function removeLocations(ast)
export function parseScript(contents)
{
let ast = codeToAst(contents, {
ecmaVersion: 2021,
ecmaVersion: "latest",
sourceType: "module",
allowReturnOutsideFunction: true
});
Expand All @@ -62,15 +63,37 @@ export function saveScript(ast, filepath)
return;
}

// Make sure to wrap any single-statement blocks in block statements, otherwise astring will put
// everything in one line.
function wrap(node)
{
if (!node || node.type == "BlockStatement")
return node;
else
{
return {
type: "BlockStatement",
body: [node],
};
}
}

traverse(ast, {
enter(node)
{
if (node.type == "IfStatement")
{
node.consequent = wrap(node.consequent);
node.alternate = wrap(node.alternate);
}
else if (["WithStatement", "WhileStatement", "DoWhileStatement", "ForStatement", "ForInStatement", "ForOfStatement"].includes(node.type))
node.body = wrap(node.body);
}
});

let code = astToCode(ast, {
format: {
indent: {
style: " "
},
quotes: "double",
escapeless: true
},
comment: true
indent: " ",
comments: true
});

fs.writeFileSync(filepath, code, {encoding: "utf-8"});
Expand Down
Loading

0 comments on commit 8c10e7b

Please sign in to comment.