Skip to content

Commit

Permalink
fix(typescript): resolve the shim used for tsc in Typescript v5.7 and up
Browse files Browse the repository at this point in the history
  • Loading branch information
kitsune7 committed Dec 6, 2024
1 parent 3e996b3 commit 7880fab
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion packages/typescript/lib/quickstart/runTsc.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as fs from 'fs';
import * as path from 'path';
import type * as ts from 'typescript';
import type { Language, LanguagePlugin } from '@volar/language-core';

Expand All @@ -17,13 +18,29 @@ export function runTsc(
) {
getLanguagePlugins = _getLanguagePlugins;

const proxyApiPath = require.resolve('../node/proxyCreateProgram');
const proxyApiPath = path.resolve(__dirname, '../node/proxyCreateProgram');
const readFileSync = fs.readFileSync;

(fs as any).readFileSync = (...args: any[]) => {
if (args[0] === tscPath) {
let tsc = (readFileSync as any)(...args) as string;

// Support the tsc shim used in Typescript v5.7 and up
if (!isMainTsc(tsc)) {
const requireRegex = /module\.exports\s*=\s*require\((?:"|')(?<path>\.\/\w+\.js)(?:"|')\)/;
const requirePath = requireRegex.exec(tsc)?.groups?.path;
if (requirePath) {
const tscContent: string = ((readFileSync as any)(path.join(path.dirname(tscPath), requirePath)))?.toString?.() ?? '';
if (isMainTsc(tscContent)) {
tsc = tscContent;
} else {
throw new Error('Failed to find resolve main tsc module from shim');
}
} else {
throw new Error('Failed to locate tsc module path from shim');
}
}

let extraSupportedExtensions: string[];
let extraExtensionsToRemove: string[];
if (Array.isArray(options)) {
Expand Down Expand Up @@ -104,6 +121,12 @@ export function transformTscContent(
return tsc;
}

function isMainTsc(tsc: string) {
// We assume it's the main tsc module if it has a `version` variable defined with a semver string
const versionRegex = /(?:var|const|let)\s+version\s*=\s*(?:"|')\d+\.\d+\.\d+(?:"|')/;
return versionRegex.test(tsc);
}

function replace(text: string, ...[search, replace]: Parameters<String['replace']>) {
const before = text;
text = text.replace(search, replace);
Expand Down

0 comments on commit 7880fab

Please sign in to comment.