import { getShellOutput, rmRf } from "@ark/fs" import { execFileSync } from "node:child_process" import { existsSync, mkdtempSync } from "node:fs" import { createRequire } from "node:module" import { tmpdir } from "node:os" import { dirname, join } from "node:path" import { isTs7 } from "../utils.ts" const diagnosticTscFlags = [ "--noEmit", "--extendedDiagnostics", "--incremental", // parallel checkers each instantiate their own copies of types ...(isTs7 ? ["--singleThreaded"] : []) ] // resolve tsc's JS bin directly so diagnostic runs avoid npm exec .cmd shims on Windows const resolveTscBin = (cwd: string): string | undefined => { for (const from of [join(cwd, "package.json"), import.meta.url]) { try { const pkgPath = createRequire(from).resolve("typescript/package.json") const binPath = join(dirname(pkgPath), "bin", "tsc") if (existsSync(binPath)) return binPath } catch { // try next resolution root } } return undefined } export const getDiagnosticTscOutput = ( cwd: string, args: readonly string[] = [] ): string => { // composite projects can't disable incremental, so a fresh build info file // keeps stale state from skipping the check const buildInfoDir = mkdtempSync(join(tmpdir(), "attest-")) const buildInfoFile = join(buildInfoDir, "tsconfig.tsbuildinfo") const tscBin = resolveTscBin(cwd) try { if (tscBin) { return execFileSync( process.execPath, [ tscBin, ...diagnosticTscFlags, "--tsBuildInfoFile", buildInfoFile, ...args ], { cwd, encoding: "utf8" } ) } const formattedArgs = args.map(arg => JSON.stringify(arg)).join(" ") return getShellOutput( `npm exec -- tsc ${diagnosticTscFlags.join(" ")} --tsBuildInfoFile ${JSON.stringify(buildInfoFile)} ${formattedArgs}`, { cwd } ) } finally { rmRf(buildInfoDir) } }