-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Try replacing typescript with program.emit and directly transpiling e… #13801
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
|
@@ -1,5 +1,5 @@ | |||
import { createRequire } from 'module'; | |||
import { relative, basename, dirname } from 'path'; | |||
import { basename, dirname } from 'path'; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
import { basename, dirname } from 'path'; | |
import { basename, dirname, relative } from 'path'; |
Commented code references relative
function that was removed from imports, which would cause a runtime error if uncommented.
View Details
Analysis
The commented code on line 236 contains ${relative(cwd, fileName)}
but the relative
import from the path
module was removed in the refactoring. If this commented code were to be uncommented in the future (which seems likely given the context about emit functionality), it would result in a ReferenceError: relative is not defined
at runtime.
While this is currently commented out, the presence of this code suggests it may be intended for future use or debugging purposes. The commented code appears to be related to error reporting when emit is skipped, which is a legitimate TypeScript compilation scenario.
Recommendation
Either add relative
back to the path imports on line 2: import { basename, dirname, relative } from 'path';
, or update the commented code to use an alternative approach like fileName.replace(cwd, '.')
or just use fileName
directly without path relativization.
const diagnostics = service | ||
.getSemanticDiagnostics(fileName) | ||
.concat(service.getSyntacticDiagnostics(fileName)); | ||
// Create a TypeScript program exactly like `tsc` does |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The type checking and transpilation are using different sources for the same file, which could lead to inconsistent results where diagnostics are checked against the file on disk but transpilation uses in-memory code.
View Details
📝 Patch Details
diff --git a/packages/node/src/typescript.ts b/packages/node/src/typescript.ts
index 98a5738f3..3a93f599d 100644
--- a/packages/node/src/typescript.ts
+++ b/packages/node/src/typescript.ts
@@ -203,7 +203,18 @@ export function register(opts: Options = {}): Register {
}
// Create a TypeScript program exactly like `tsc` does
+ // Use a custom compiler host that provides the in-memory code for consistency
const compilerHost = ts.createCompilerHost(config.options);
+ const originalReadFile = compilerHost.readFile;
+ compilerHost.readFile = (readFileName: string) => {
+ // Use in-memory code for the target file to ensure consistency
+ if (readFileName === fileName) {
+ return code;
+ }
+ // Use original readFile for all other files
+ return originalReadFile.call(compilerHost, readFileName);
+ };
+
const program = ts.createProgram(
config.fileNames,
config.options,
@@ -223,31 +234,45 @@ export function register(opts: Options = {}): Register {
reportTSError(diagnosticList, config.options.noEmitOnError);
}
- // Emit the file like `tsc` does
- // const result = program.emit(
- // program.getSourceFile(fileName),
- // undefined,
- // undefined,
- // false,
- // transformers
- // );
-
- // if (result.emitSkipped) {
- // throw new TypeError(`${relative(cwd, fileName)}: Emit skipped`);
- // }
-
- // Since program.emit() doesn't return output files, we need to transpile the specific file
- // This gives us the same result as `tsc` would produce
- const transpileResult = ts.transpileModule(code, {
- fileName,
- transformers,
- compilerOptions: config.options,
- reportDiagnostics: false, // We already checked diagnostics above
- });
+ // Use program.emit() for consistency with diagnostics
+ // Capture the output files in memory
+ const createdFiles: Record<string, string> = {};
+ const originalWriteFile = compilerHost.writeFile;
+ compilerHost.writeFile = (outputFileName: string, contents: string) => {
+ createdFiles[outputFileName] = contents;
+ };
+
+ const result = program.emit(
+ program.getSourceFile(fileName),
+ undefined,
+ undefined,
+ false,
+ transformers
+ );
+
+ // Restore original writeFile
+ compilerHost.writeFile = originalWriteFile;
+
+ if (result.emitSkipped) {
+ throw new TypeError(`Emit skipped for ${fileName}`);
+ }
+
+ // Extract the output from created files
+ let outputText = '';
+ let sourceMapText = '';
+
+ // Find the .js file and .map file in the created files
+ for (const [outputFileName, contents] of Object.entries(createdFiles)) {
+ if (outputFileName.endsWith('.map')) {
+ sourceMapText = contents;
+ } else if (outputFileName.endsWith('.js')) {
+ outputText = contents;
+ }
+ }
const file = {
- code: transpileResult.outputText,
- map: transpileResult.sourceMapText || '',
+ code: outputText,
+ map: sourceMapText,
};
outFiles.set(fileName, file);
return file;
Analysis
The getOutputTypeCheck
function has a critical logic flaw where it creates a TypeScript program using ts.createCompilerHost(config.options)
(which reads files from disk) for type checking diagnostics, but then uses ts.transpileModule(code, {...})
for transpilation (which uses the in-memory code
parameter).
This creates a mismatch where:
- Diagnostics are checked against the file system version via
ts.getPreEmitDiagnostics(program)
- Transpilation uses the in-memory version via the
code
parameter
If the in-memory code
differs from what's on disk (which is common in build tools where files are transformed in memory), this will result in:
- Type errors being reported that don't actually exist in the code being transpiled
- Missing type errors for issues that do exist in the code being transpiled
- Inconsistent behavior compared to
tsc
which operates on a single consistent source
The old implementation was consistent - it used the language service for both diagnostics and emission on the same in-memory file content via updateMemoryCache(code, fileName)
.
Recommendation
To fix this issue, you need to ensure both diagnostics and transpilation use the same source. You have two options:
- Use program.emit() instead of transpileModule (recommended):
// Create a custom compiler host that uses the in-memory code
const compilerHost = ts.createCompilerHost(config.options);
const originalReadFile = compilerHost.readFile;
compilerHost.readFile = (fileName: string) => {
if (fileName === fileName) return code; // Use in-memory code for target file
return originalReadFile.call(compilerHost, fileName);
};
const program = ts.createProgram([fileName], config.options, compilerHost);
// ... get diagnostics ...
// Use program.emit() for consistency
const result = program.emit(
program.getSourceFile(fileName),
undefined,
undefined,
false,
transformers
);
- Or use transpileModule for both diagnostics and transpilation:
// Check diagnostics using transpileModule too
const transpileResult = ts.transpileModule(code, {
fileName,
transformers,
compilerOptions: config.options,
reportDiagnostics: true, // Enable diagnostics
});
const diagnosticList = filterDiagnostics(
transpileResult.diagnostics || [],
ignoreDiagnostics
);
The first option is preferred as it maintains the full program context for cross-file type checking that the original intent seems to require.
…ach module