Replace function calls using esprima.
static-method
lets you easily replace specific function calls without messing around
with the syntax tree. It exists as a nice middle ground between running a regex over your entire codebase
and defining a complicated AST transform.
var staticMethod = require('static-method');
var sm = staticMethod({
parseInt: function(src, node) {
if (node.arguments.length === 1) {
return 'parseInt(' + node.arguments[0].raw + ', 10)';
}
}
});
process.stdin.pipe(sm).pipe(process.stdout);
- Replace all calls to
foo()
with calls tobar()
- Comment out all calls to
eval
and add an alert - Add the radix to
parseInt
npm install --save static-method
Returns a transform stream that transforms javascript source code according to each property in the methods configuration object.
methods
is a configuration object. The keys are the function names you'd like to
replace. The value is a function that defines the transform you'd like to perform
on that function call.
Each transform function receives two arguments. The first is the source of the function call. The second is a falafel AST node that you can modify directly, use to extract arguments, etc.
The easiest way to replace the call is to return a string from the transform function that contains the replacement code.
Ex: This replaces all calls to foo()
with the string "bar"
:
var sm = staticMethod({
foo: function() {
return '"bar"';
}
});
var staticMethod = require('static-method');
var sm = staticMethod({
foo: function(src, node) {
return src.replace(/^foo/, 'bar');
}
});
process.stdin.pipe(sm).pipe(process.stdout);
input:
$ cat source.js
foo();
foo(1, 2);
foo(a, function(err, data) {
if (err) throw(err);
console.log(data);
});
output:
$ node replace.js < source.js
bar();
bar(1, 2);
bar(a, function(err, data) {
if (err) throw(err);
console.log(data);
});
var staticMethod = require('static-method');
var sm = staticMethod({
eval: function(src, node) {
return 'alert("Think about what you\'ve done"); /*' + src + '*/';
}
});
process.stdin.pipe(sm).pipe(process.stdout);
input:
$ cat source.js
console.log(eval("2 + 2"));
output:
$ node replace.js < source.js
console.log(alert("Think hard about what you're doing") /*eval("2 + 2")*/);
It's best practice to always include the optional radix parameter in parseInt
calls. Let's enforce this.
var staticMethod = require('static-method');
var sm = staticMethod({
parseInt: function(src, node) {
if (node.arguments.length === 1) {
return 'parseInt(' + node.arguments[0].raw + ', 10)';
}
}
});
process.stdin.pipe(sm).pipe(process.stdout);
input:
$ cat source.js
parseInt();
parseInt('5');
parseInt('5', 10);
output:
$ node replace.js < source.js
parseInt();
parseInt('5', 10);
parseInt('5', 10);
Inspired by static-module by substack.
If your needs are more sophisticated then you should look at jstransform, falafel, or go straight for esprima.
MIT