-
Notifications
You must be signed in to change notification settings - Fork 20
/
transform-tree.js
executable file
·47 lines (41 loc) · 1.28 KB
/
transform-tree.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
'use strict';
const recast = require('recast');
const rewritePattern = require('regexpu-core');
const types = recast.types;
module.exports = function(node, rewritePatternOptions) {
return types.visit(node, types.PathVisitor.fromMethodsObject({
// This method is called for any AST node whose `type` is `Literal`.
'visitLiteral': function(path) {
const node = path.value;
if (!node.regex) {
return false;
}
const flags = node.regex.flags;
const useDotAll = rewritePatternOptions.dotAllFlag === 'transform' && flags.includes('s');
if (!flags.includes('u') && !useDotAll) {
return false;
}
const newPattern = rewritePattern(
node.regex.pattern,
flags,
rewritePatternOptions
);
const filteredFlags = useDotAll ? flags.replace('s', '') : flags;
const newFlags = rewritePatternOptions.unicodeFlag === 'transform' ?
filteredFlags :
filteredFlags.replace('u', '');
const result = `/${ newPattern }/${ newFlags }`;
node.regex = {
'pattern': newPattern,
'flags': newFlags
};
node.raw = result;
node.value = {
'toString': () => result
};
// Return `false` to indicate that the traversal need not continue any
// further down this subtree. (`Literal`s don’t have descendants anyway.)
return false;
}
}));
};