Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

jeffsee55
Copy link
Contributor

…ach module

Copy link

changeset-bot bot commented Aug 20, 2025

⚠️ No Changeset found

Latest commit: bf034f9

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@@ -1,5 +1,5 @@
import { createRequire } from 'module';
import { relative, basename, dirname } from 'path';
import { basename, dirname } from 'path';
Copy link
Contributor

@vercel vercel bot Aug 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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
Copy link
Contributor

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:

  1. Diagnostics are checked against the file system version via ts.getPreEmitDiagnostics(program)
  2. 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:

  1. 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
);
  1. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant