scraipt
Version:
Scrape away inefficient code during compile-time using AI
93 lines (92 loc) • 3.06 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createFunction = exports.isValidJavaScript = exports.parseSource = exports.isTypeScriptCode = exports.getSourceAtLine = void 0;
const core_1 = require("@babel/core");
/**
Get the source code at the given line number.
* @param source The source code.
* @param line The line number.
* @returns The source code at the given line number.
*/
const getSourceAtLine = (source, line) => {
const lines = source.split('\n');
const lineNumber = line - 1;
if (lineNumber < 0) {
return '';
}
if (lineNumber >= lines.length) {
return '';
}
return lines[lineNumber];
};
exports.getSourceAtLine = getSourceAtLine;
/**
Check if the given source code is TypeScript.
* @param source The source code to check.
* @returns True if the source code is TypeScript, false otherwise.
*/
const isTypeScriptCode = (source) => {
try {
const AST = (0, core_1.parse)(source, {
sourceType: 'module',
plugins: ['@babel/plugin-syntax-jsx'],
});
return !AST;
}
catch (error) {
return true;
}
};
exports.isTypeScriptCode = isTypeScriptCode;
/**
Parse the given source code into an AST.
* @param source The source code to parse.
* @returns The parse result.
*/
const parseSource = (source) => {
const isTypeScript = (0, exports.isTypeScriptCode)(source);
const plugins = ['@babel/plugin-syntax-jsx'];
if (isTypeScript) {
plugins.push('@babel/plugin-transform-typescript');
}
// TODO: Add return type
return (0, core_1.parse)(source, {
sourceType: 'module',
plugins,
});
};
exports.parseSource = parseSource;
/**
Check if the given source code is valid JavaScript.
* @param source The source code to check.
* @returns True if the source code is valid JavaScript, false otherwise.
*/
const isValidJavaScript = (source) => {
try {
(0, exports.parseSource)(source);
}
catch (error) {
return false;
}
return true;
};
exports.isValidJavaScript = isValidJavaScript;
/**
Create a function with the given name, parameters, transformed body, and original body.
* @param name The name of the function.
* @param params The parameters of the function.
* @param transformedBody The transformed body of the function.
* @param originalBody The original body of the function.
* @returns The function as a string.
*/
const createFunction = (name, params, transformedBody, originalBody, isArrowFunction) => {
// TODO: Function type (const, let, etc)
if (isArrowFunction) {
return `(${params}) => {\ntry\n${transformedBody}\ncatch (error)\n${originalBody}\n}`;
}
if (name) {
return `function ${name}(${params}) {\ntry\n${transformedBody}\ncatch (error)\n${originalBody}\n}`;
}
return `function (${params}) {\ntry\n${transformedBody}\ncatch (error)\n${originalBody}\n}`;
};
exports.createFunction = createFunction;