module: refactor ts parser loading

PR-URL: https://github.com/nodejs/node/pull/54243
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Tierney Cyren <hello@bnb.im>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Jake Yuesong Li <jake.yuesong@gmail.com>
This commit is contained in:
Marco Ippolito 2024-08-09 08:46:58 +02:00 committed by GitHub
parent 30f6c56e03
commit 3cbeed88d9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -300,11 +300,29 @@ function getBuiltinModule(id) {
return normalizedId ? require(normalizedId) : undefined;
}
let parseTS;
let typeScriptParser;
function lazyLoadTSParser() {
parseTS ??= require('internal/deps/amaro/dist/index').transformSync;
return parseTS;
/**
* Load the TypeScript parser.
* @param {Function} parser - A function that takes a string of TypeScript code
* and returns an object with a `code` property.
* @returns {Function} The TypeScript parser function.
*/
function loadTypeScriptParser(parser) {
if (typeScriptParser) {
return typeScriptParser;
}
if (parser) {
typeScriptParser = parser;
} else {
const amaro = require('internal/deps/amaro/dist/index');
// Default option for Amaro is to perform Type Stripping only.
const defaultOptions = { __proto__: null, mode: 'strip-only' };
// Curry the transformSync function with the default options.
typeScriptParser = (source) => amaro.transformSync(source, defaultOptions);
}
return typeScriptParser;
}
/**
@ -313,9 +331,10 @@ function lazyLoadTSParser() {
* @returns {string} JavaScript code.
*/
function tsParse(source) {
// TODO(@marco-ippolito) Checking empty string or non string input should be handled in Amaro.
if (!source || typeof source !== 'string') { return ''; }
const transformSync = lazyLoadTSParser();
const { code } = transformSync(source, { __proto__: null, mode: 'strip-only' });
const parse = loadTypeScriptParser();
const { code } = parse(source);
return code;
}