sucrase
Version:
Super-fast alternative to Babel for when you can target modern JS runtimes
48 lines (47 loc) • 1.87 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const parser_1 = require("./parser");
require("./tokenizer/context");
const flow_1 = require("./plugins/flow");
const jsx_1 = require("./plugins/jsx");
const typescript_1 = require("./plugins/typescript");
parser_1.plugins.flow = flow_1.default;
parser_1.plugins.jsx = jsx_1.default;
parser_1.plugins.typescript = typescript_1.default;
function parse(input, options) {
return getParser(options, input).parse();
}
exports.parse = parse;
function getParser(options, input) {
const Cls = options && options.plugins ? getParserClass(options.plugins) : parser_1.default;
return new Cls(options || null, input);
}
const parserClassCache = {};
/** Get a Parser class with plugins applied. */
function getParserClass(pluginsFromOptions) {
// Filter out just the plugins that have an actual mixin associated with them.
let pluginList = pluginsFromOptions.filter((p) => p === "flow" || p === "jsx" || p === "typescript");
if (pluginList.indexOf("flow") >= 0) {
// ensure flow plugin loads last
pluginList = pluginList.filter((plugin) => plugin !== "flow");
pluginList.push("flow");
}
if (pluginList.indexOf("flow") >= 0 && pluginList.indexOf("typescript") >= 0) {
throw new Error("Cannot combine flow and typescript plugins.");
}
if (pluginList.indexOf("typescript") >= 0) {
// ensure typescript plugin loads last
pluginList = pluginList.filter((plugin) => plugin !== "typescript");
pluginList.push("typescript");
}
const key = pluginList.join("/");
let cls = parserClassCache[key];
if (!cls) {
cls = parser_1.default;
for (const plugin of pluginList) {
cls = parser_1.plugins[plugin](cls);
}
parserClassCache[key] = cls;
}
return cls;
}