-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
69 lines (55 loc) · 1.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
'use strict';
var Rx = require('rx');
var squery = require('grasp-squery');
var Map = require('es6-map');
var traverse = require('estraverse').replace;
var estemplate = require('estemplate');
module.exports = function (options) {
var replaces = Rx.Observable.fromArray(Object.keys(options)).map(function (selector) {
var handler = options[selector];
if (typeof handler === 'string') {
var canBeExprStmt = handler.slice(-1) === ';';
var tmpl = estemplate.compile(handler, {tolerant: true});
handler = function (node) {
var ast = tmpl(node);
switch (ast.body.length) {
case 0:
ast = null;
break;
case 1:
ast = ast.body[0];
if (ast.type === 'ExpressionStatement' && !canBeExprStmt) {
ast = ast.expression;
}
break;
default:
ast.type = 'BlockStatement';
}
return ast;
};
}
return {
selector: squery.parse(selector),
handler: handler
};
});
return function (files) {
return files.flatMap(function (file) {
return replaces
.flatMap(function (replace) {
var handler = replace.handler;
return Rx.Observable.fromArray(squery.queryParsed(replace.selector, file.program)).map(function (node) {
return [node, handler(node)];
});
})
.filter(function (replace) { return replace[1] !== undefined })
.toArray()
.map(function (replaces) {
file.program = traverse(file.program, {
leave: Map.prototype.get.bind(new Map(replaces))
});
return file;
});
});
}
};