@nodesecure/js-x-ray
Version:
JavaScript AST XRay analysis
41 lines • 1.22 kB
JavaScript
// Import Third-party Dependencies
import { parseModule, parse } from "meriyah";
// CONSTANTS
const kParsingOptions = {
next: true,
loc: true,
raw: true,
jsx: true
};
export class JsSourceParser {
static FileExtensions = new Set([
".js",
".cjs",
".mjs",
".jsx"
]);
#stripTypeScriptTypes;
constructor(options = {}) {
this.#stripTypeScriptTypes = options.stripTypeScriptTypes;
}
parse(source) {
const cleanedSource = this.#stripTypeScriptTypes ? this.#stripTypeScriptTypes(source) : source;
try {
const { body } = parseModule(cleanedSource, structuredClone(kParsingOptions));
return body;
}
catch (error) {
const syntaxError = error;
const isIllegalReturn = syntaxError.description.includes("Illegal return statement");
if (isIllegalReturn) {
const { body } = parse(cleanedSource, {
...structuredClone(kParsingOptions),
sourceType: "commonjs"
});
return body;
}
throw error;
}
}
}
//# sourceMappingURL=JsSourceParser.js.map