Merge multiple regex transform plugin (#10447)
* feat: implement create-regexp-features-plugin * fix: test input is not effective * refactor: leverage create-regexp-features-plugin * test: add more test cases * test: update test fixture * chore: add type annotation to features * test: add regression test for issue 9892 * add regression test for issue 9199 * address review comments from Nicolò * address review comments from Brian * small tweaks * Enable dotAllFlag when flags includes u
This commit is contained in:
committed by
Nicolò Ribaudo
parent
ec3345bb57
commit
8ffca0475a
@@ -1,56 +1,15 @@
|
||||
import rewritePattern from "regexpu-core";
|
||||
/* eslint-disable @babel/development/plugin-name */
|
||||
import { createRegExpFeaturePlugin } from "@babel/helper-create-regexp-features-plugin";
|
||||
|
||||
export default function({ types: t }, options) {
|
||||
export default function(core, options) {
|
||||
const { runtime = true } = options;
|
||||
if (typeof runtime !== "boolean") {
|
||||
throw new Error("The 'runtime' option must be boolean");
|
||||
}
|
||||
|
||||
return {
|
||||
return createRegExpFeaturePlugin({
|
||||
name: "transform-named-capturing-groups-regex",
|
||||
|
||||
visitor: {
|
||||
RegExpLiteral(path) {
|
||||
const node = path.node;
|
||||
if (!/\(\?<(?![=!])/.test(node.pattern)) {
|
||||
// Return early if there are no named groups.
|
||||
// The .indexOf check may have false positives (e.g. /\(?</); in
|
||||
// this case we parse the regex and regexp-tree won't transform it.
|
||||
return;
|
||||
}
|
||||
|
||||
const namedCapturingGroups = {};
|
||||
const result = rewritePattern(node.pattern, node.flags, {
|
||||
namedGroup: true,
|
||||
//todo: consider refactor `lookbehind` true as modular plugin
|
||||
lookbehind: true,
|
||||
onNamedGroup(name, index) {
|
||||
namedCapturingGroups[name] = index;
|
||||
},
|
||||
});
|
||||
|
||||
if (Object.keys(namedCapturingGroups).length > 0) {
|
||||
node.pattern = result;
|
||||
|
||||
if (runtime && !isRegExpTest(path)) {
|
||||
path.replaceWith(
|
||||
t.callExpression(this.addHelper("wrapRegExp"), [
|
||||
node,
|
||||
t.valueToNode(namedCapturingGroups),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function isRegExpTest(path) {
|
||||
return (
|
||||
path.parentPath.isMemberExpression({
|
||||
object: path.node,
|
||||
computed: false,
|
||||
}) && path.parentPath.get("property").isIdentifier({ name: "test" })
|
||||
);
|
||||
feature: "namedCaptureGroups",
|
||||
options: { runtime },
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user