Skip to content

Commit

Permalink
module: refactor ts parser loading
Browse files Browse the repository at this point in the history
PR-URL: #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>
  • Loading branch information
marco-ippolito authored Aug 9, 2024
1 parent 30f6c56 commit 3cbeed8
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions lib/internal/modules/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand All @@ -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;
}

Expand Down

0 comments on commit 3cbeed8

Please sign in to comment.