Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@ updates:
directory: "/"
schedule:
interval: "weekly"
ignore:
# TypeScript 7.x replaced the classic in-process Program/TypeChecker
# API (createProgram, TypeChecker, ts.sys, forEachChild, ...) with an
# out-of-process client-server model under typescript/unstable/sync|async.
# src/domain/graph/resolver/ts-resolver.ts is built entirely around the
# old synchronous API (~70 call sites) and breaks at compile time and
# silently no-ops at runtime under v7 (issue #2106) — needs its own
# redesign project before this repo can move off the 6.x line, not a
# routine dependency-bump PR. Remove this ignore once that redesign
# lands.
- dependency-name: "typescript"
update-types: ["version-update:semver-major"]

- package-ecosystem: "github-actions"
directory: "/"
Expand Down
61 changes: 57 additions & 4 deletions src/domain/graph/resolver/ts-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,74 @@
* unaffected.
*/
import fs from 'node:fs';
import { createRequire } from 'node:module';
import path from 'node:path';
import { debug } from '../../../infrastructure/logger.js';
import { pathToFileURL } from 'node:url';
import { debug, warn } from '../../../infrastructure/logger.js';
import type { CallAssignment, ExtractorOutput, TypeMapEntry } from '../../../types.js';

const _require = createRequire(import.meta.url);

// typescript is not a hard dependency — lazy-load it so JS-only projects
// and environments without typescript installed work without error.
type TsModule = typeof import('typescript');
let _ts: TsModule | null | undefined; // undefined = not yet tried; null = unavailable

async function loadTs(): Promise<TsModule | null> {
/**
* True when `mod` still exposes the classic in-process Program/TypeChecker
* API this whole module is built around. TypeScript 7.x replaced it with an
* out-of-process client-server model — `.` no longer exports
* readConfigFile/createProgram/sys at all (issue #2106). Exported as a pure
* check (rather than inlined in loadTs) so it's testable without mocking the
* real `typescript` module import.
*/
export function hasClassicCompilerApi(mod: Partial<TsModule> | null | undefined): boolean {
return typeof mod?.readConfigFile === 'function';
}

/**
* Resolve the `typescript` module path starting from `rootDir` — the
* analyzed project's own directory — before falling back to resolution from
* codegraph's own module location. A bare `import('typescript')` resolves
* via Node's module search from *this file's* location, which finds the
* analyzed project's own install only by hoisting coincidence; a globally
* installed codegraph CLI (a documented, supported install mode) analyzing
* a project with its own `typescript` — of any version — would otherwise
* never see it at all (#2106 review), silently and incorrectly falling back
* to whatever (or no) `typescript` codegraph itself happens to resolve.
*/
export function resolveTsModulePath(rootDir: string): string {
try {
return _require.resolve('typescript', { paths: [rootDir] });
} catch {
return _require.resolve('typescript');
}
}

async function loadTs(rootDir: string): Promise<TsModule | null> {
if (_ts !== undefined) return _ts;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Project compiler cache crosses roots

When branch comparison builds its base and target directories sequentially, loadTs returns the compiler or null cached for the base directory without resolving TypeScript against the target directory. The target consequently uses the wrong compiler or loses compiler-based type enrichment entirely.

Fix in Claude Code

try {
const resolvedPath = resolveTsModulePath(rootDir);
// TypeScript 6+ ships dual CJS/ESM exports; `.default` is the CJS interop
// namespace and is present and non-null in both TS 5.x and TS 6.x.
_ts = (await import('typescript')).default as TsModule;
const mod = (await import(pathToFileURL(resolvedPath).href)).default as TsModule;
// Detected explicitly (rather than letting createProgram's TypeError
// propagate into its own catch, indistinguishable from an ordinary
// per-project tsconfig failure) so this specific, permanent
// incompatibility gets a visible warn() instead of silently degrading
// with only a debug()-level trace — this pass' compiler-verified type
// enrichment is being skipped entirely, not just for one file.
if (!hasClassicCompilerApi(mod)) {
_ts = null;
warn(
'ts-resolver: installed typescript package is v7+ and no longer exposes the ' +
'classic Program/TypeChecker API (readConfigFile is undefined) — skipping ' +
'TSC type enrichment for this build. See ' +
'https://github.com/optave/ops-codegraph-tool/issues/2106',
);
return _ts;
}
_ts = mod;
} catch {
_ts = null;
debug('ts-resolver: typescript package not available — skipping TSC type enrichment');
Expand Down Expand Up @@ -89,7 +142,7 @@ export async function enrichTypeMapWithTsc(
const tsRelPaths = [...fileSymbols.keys()].filter(isTsFile);
if (tsRelPaths.length === 0) return;

const ts = await loadTs();
const ts = await loadTs(rootDir);
if (!ts) return;

const tsconfigPath = findTsconfig(rootDir);
Expand Down
66 changes: 65 additions & 1 deletion tests/unit/ts-resolver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { enrichTypeMapWithTsc } from '../../src/domain/graph/resolver/ts-resolver.js';
import {
enrichTypeMapWithTsc,
hasClassicCompilerApi,
resolveTsModulePath,
} from '../../src/domain/graph/resolver/ts-resolver.js';
import type { ExtractorOutput } from '../../src/types.js';

function makeTmpDir(): string {
Expand Down Expand Up @@ -544,3 +548,63 @@ function getCount(): number { return 42; }
expect(symbols.returnTypeMap!.has('getCount')).toBe(false);
});
});

describe('hasClassicCompilerApi (#2106)', () => {
it('returns true for a TS 5.x/6.x-shaped module (readConfigFile present)', () => {
expect(hasClassicCompilerApi({ readConfigFile: () => undefined } as never)).toBe(true);
});

it('returns false for a TS 7.x-shaped module (only version/versionMajorMinor exported)', () => {
expect(hasClassicCompilerApi({ version: '7.0.2', versionMajorMinor: '7.0' } as never)).toBe(
false,
);
});

it('returns false for null/undefined', () => {
expect(hasClassicCompilerApi(null)).toBe(false);
expect(hasClassicCompilerApi(undefined)).toBe(false);
});

it('returns false when readConfigFile exists but is not a function', () => {
expect(hasClassicCompilerApi({ readConfigFile: 'not-a-function' } as never)).toBe(false);
});
});

describe('resolveTsModulePath project-relative resolution (#2106 review)', () => {
let tmpDir: string;

beforeEach(() => {
tmpDir = makeTmpDir();
});

afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});

it("resolves the analyzed project's own typescript install over an ambient one", () => {
// A globally installed codegraph analyzing this project must find THIS
// typescript, not whatever codegraph itself happens to resolve — a bare
// `import('typescript')` from within ts-resolver.ts would never see it,
// since Node's module search starts from codegraph's own location, not
// rootDir (the bug Greptile flagged).
const tsPkgDir = path.join(tmpDir, 'node_modules', 'typescript');
fs.mkdirSync(tsPkgDir, { recursive: true });
fs.writeFileSync(
path.join(tsPkgDir, 'package.json'),
JSON.stringify({ name: 'typescript', version: '0.0.0-project-local', main: 'index.js' }),
);
fs.writeFileSync(path.join(tsPkgDir, 'index.js'), 'module.exports = {};');

const resolved = resolveTsModulePath(tmpDir);
expect(fs.realpathSync(resolved)).toBe(fs.realpathSync(path.join(tsPkgDir, 'index.js')));
});

it("falls back to resolving from codegraph's own location when the project has no local typescript", () => {
// tmpDir has no node_modules/typescript at all — must not throw, and
// must resolve to *some* real typescript install (codegraph's own dev
// dependency in this test environment).
const resolved = resolveTsModulePath(tmpDir);
expect(fs.existsSync(resolved)).toBe(true);
expect(resolved).toContain('typescript');
});
});
Loading