-
Notifications
You must be signed in to change notification settings - Fork 0
/
babel-sync-me.js
65 lines (56 loc) · 1.62 KB
/
babel-sync-me.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
// All credit goes to https://github.com/egoist/babel-plugin-sync
// Copied here to tweak further
const MAKE_ME_SYNC = '$MakeMeSync';
const shouldMakeSync = (comments) => {
return (
comments &&
comments.find((comment) => {
return comment.value.trim() === MAKE_ME_SYNC;
})
);
};
const markAsSynced = (node) => {
node.leadingComments = node.leadingComments.map((c) => {
if (c.value.trim() === MAKE_ME_SYNC) {
c.value = ' __SYNCED__';
}
return c;
});
};
const syncCallee = (callee) => {
if (callee.type === 'MemberExpression') {
callee.property.name += 'Sync';
} else {
callee.name += 'Sync';
}
};
module.exports = function ({ types: t }) {
return {
name: 'sync',
visitor: {
ClassMethod(path) {
if (path.node.async && shouldMakeSync(path.node.leadingComments)) {
markAsSynced(path.node);
const originalNode = t.cloneDeep(path.node);
path.node.trailingComments = originalNode.trailingComments;
originalNode.trailingComments = [];
path.insertBefore(originalNode);
path.node.async = false;
path.node.key.name += 'Sync';
path.traverse({
AwaitExpression(path) {
const { callee } = path.node.argument;
syncCallee(callee);
path.replaceWith(path.node.argument);
},
CallExpression(path) {
if (path.parent.type === 'ReturnStatement' && shouldMakeSync(path.parent.trailingComments)) {
syncCallee(path.node.callee);
}
},
});
}
},
},
};
};