Skip to content
Closed
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

### Fixes

- In JavaScript, a `require()` of a folder by a relative path, like `require('..')` from a package's tests, now loads the file the folder's `package.json` names as `main`, as Node does, so calls through it link to the function that file exports. Before, a folder without an `index.js` wasn't followed, and the call linked to the variable holding the `require()` result; on fastify, every test's `Fastify()` linked to its own test file. Thanks @inth3shadows for the report. (#2964)
- In Python, `import time` no longer links the importing file to a project function that happens to be named `time`, so such a function stops listing every file that imports the standard library module among its callers and in its impact. The same goes for `json`, `copy`, `random`, `logging` and any other module, and for a fallback variable like `brotli = None` beside a guarded `import brotli`. Thanks @inth3shadows for the report. (#3239)
- In Rust, a call through a module that a glob `use` brings in, like `gzip::write()` in a test module with `use super::*`, or that a `use` inside the function names, now links to that module's function again. Thanks @Egrn for the report and @mohitdixit02. (#3253)
- CodeGraph no longer takes git's index lock while it checks your repository for changes, so a `git add` in a pre-commit hook, a commit or a checkout that runs while CodeGraph syncs no longer fails with "index.lock: File exists". Thanks @iamclaudia-ai for the report. (#3295)
Expand Down
105 changes: 105 additions & 0 deletions __tests__/require-directory-package-main.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/**
* A relative require of a directory loads the file its `package.json` names
* as `main`, as Node does before trying `index.js` (#2964): every fastify test
* starts with `const Fastify = require('..')` for the root's
* `"main": "fastify.js"`, and the call linked to the test file's own `Fastify`
* constant instead of the `fastify()` the package exports.
*/
import { describe, it, expect, afterAll, beforeAll } from 'vitest';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { CodeGraph } from '../src';

let root = '';
let cg: CodeGraph;

beforeAll(async () => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-require-dir-main-'));
const files: Record<string, string> = {
'package.json': JSON.stringify({ name: 'srv', main: 'srv.js' }),
'srv.js': `'use strict'
function srv (opts) { return build(opts) }
function build (o) { return o }
module.exports = srv
`,
'lib/index.js': `function helper () { return 1 }
module.exports = helper
`,
'lib/inner/package.json': JSON.stringify({ main: 'entry.js' }),
'lib/inner/entry.js': `function inner () { return 2 }
module.exports = inner
`,
'lib/bare/package.json': JSON.stringify({ main: './main' }),
'lib/bare/main.js': `function bare () { return 3 }
module.exports = bare
`,
'test/a.test.js': `'use strict'
const Srv = require('..')
const Srv2 = require('../')
const Srv3 = require('../srv')
function t () { Srv(); Srv2(); Srv3() }
`,
// A package.json a Windows editor saved with a byte-order mark.
'lib/bom/package.json': '\uFEFF' + JSON.stringify({ main: 'entry.js' }),
'lib/bom/entry.js': `function bom () { return 4 }
module.exports = bom
`,
'c.js': `const bom = require('./lib/bom')
function v () { bom() }
`,
// Nix imports a folder's default.nix, whatever else the folder holds.
'default.nix': `{ pkgs ? import <nixpkgs> {} }:
let web = import ./web { inherit pkgs; };
in web
`,
'web/default.nix': `{ pkgs }: pkgs.hello
`,
'web/package.json': JSON.stringify({ main: 'index.js' }),
'web/index.js': `function web () { return 5 }
module.exports = web
`,
'b.js': `const helper = require('./lib')
const inner = require('./lib/inner')
const bare = require('./lib/bare')
function u () { helper(); inner(); bare() }
`,
};
for (const [rel, content] of Object.entries(files)) {
fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true });
fs.writeFileSync(path.join(root, rel), content);
}
cg = await CodeGraph.init(root, { index: true });
});

afterAll(() => {
cg?.close();
if (root) fs.rmSync(root, { recursive: true, force: true });
});

/** `name file` of what a function calls. */
const callsOf = (file: string, name: string) => {
const fn = cg.getNodesInFile(file).find((n) => n.name === name)!;
return cg.getOutgoingEdges(fn.id).filter((e) => e.kind === 'calls').map((e) => cg.getNode(e.target)!)
.map((t) => `${t.name} ${t.filePath}`).sort();
};

describe('a relative require of a directory', () => {
it("reaches the package root's main through '..' and '../'", () => {
expect(callsOf('test/a.test.js', 't')).toEqual(['srv srv.js', 'srv srv.js', 'srv srv.js']);
});

it('reads a package.json that starts with a byte-order mark, as Node does', () => {
expect(callsOf('c.js', 'v')).toEqual(['bom lib/bom/entry.js']);
});

it("leaves other languages' folder imports alone: Nix still imports the folder's default.nix", () => {
const file = cg.getNodesInFile('default.nix').find((n) => n.kind === 'file')!;
const imports = cg.getOutgoingEdges(file.id).filter((e) => e.kind === 'imports').map((e) => cg.getNode(e.target)!.filePath);
expect(imports).toEqual(['web/default.nix']);
});

it("reaches a subdirectory's main, with or without its extension, and still an index.js", () => {
expect(callsOf('b.js', 'u')).toEqual(['bare lib/bare/main.js', 'helper lib/index.js', 'inner lib/inner/entry.js']);
});
});
12 changes: 12 additions & 0 deletions __tests__/sync-module-config-change.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,18 @@ describe('a sync follows a module-config change (#2977)', () => {
expect(stateOf(root, graph)).toEqual(full);
}, 120_000);

it("a folder's package.json main retargeted, the importer untouched (#2964)", async () => {
const before: Files = {
'lib/package.json': JSON.stringify({ main: 'a.js' }),
'lib/a.js': 'function a () { return 1 }\nmodule.exports = a\n',
'lib/b.js': 'function b () { return 2 }\nmodule.exports = b\n',
'app.js': "const lib = require('./lib')\nfunction go () { return lib() }\n",
};
const { root, graph, full } = await syncEdit(before, { 'lib/package.json': JSON.stringify({ main: 'b.js' }) });
expect(callTargets(graph, 'go')).toEqual(['lib/b.js::b']);
expect(stateOf(root, graph)).toEqual(full);
}, 120_000);

it('a mapping declared in the extends chain', async () => {
const before: Files = {
...TS_BEFORE,
Expand Down
45 changes: 45 additions & 0 deletions src/resolution/import-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1380,8 +1380,16 @@ function resolveRelativeImport(
const relativePath = path.relative(projectRoot, basePath).replace(/\\/g, '/');

// Try each extension. `require('..')` up to the project root is its `index.js`.
let mainTried = false;
for (const ext of extensions) {
if (relativePath === '' && !ext.startsWith('/')) continue;
// A directory's `package.json` `main` comes before its index files, as
// Node loads a directory (#2964).
if (ext.startsWith('/') && !mainTried && FOLDER_MAIN_LANGUAGES.has(language)) {
mainTried = true;
const main = relativeDirectoryMain(relativePath, language, context);
if (main) return main;
}
const candidatePath = relativePath === '' ? ext.slice(1) : relativePath + ext;
if (context.fileExists(candidatePath)) {
return candidatePath;
Expand All @@ -1396,6 +1404,43 @@ function resolveRelativeImport(
return findSourceForEmittedSpecifier(relativePath, language, context);
}

/**
* The importers whose relative import of a folder reads the folder's
* `package.json` `main`, as Node and the bundlers do. Nix (`/default.nix`),
* Python (`/__init__.py`) and the rest load a folder their own way.
*/
const FOLDER_MAIN_LANGUAGES: ReadonlySet<Language> = new Set<Language>(['javascript', 'typescript', 'tsx', 'jsx']);

/** A `package.json`'s `main`, trimmed; null when it has none or doesn't parse. A leading byte-order mark is skipped, as Node skips it. */
export function packageJsonMain(text: string): string | null {
let main: unknown;
try {
main = (JSON.parse(text.replace(/^\uFEFF/, '')) as { main?: unknown } | null)?.main;
} catch {
return null;
}
return typeof main === 'string' && main.trim() ? main.trim() : null;
}

/**
* The indexed file a directory's `package.json` names as `main`: fastify's
* tests `require('..')` for the root's `"main": "fastify.js"`. Null when the
* directory has no manifest, no `main`, or one outside the project. A
* manifest it reads joins the module-config snapshot, so a sync after an
* edit to its `main` resolves the folder's importers again.
*/
function relativeDirectoryMain(dir: string, language: Language, context: ResolutionContext): string | null {
const manifestPath = dir === '' ? 'package.json' : `${dir}/package.json`;
const manifest = context.readFile(manifestPath);
if (!manifest) return null;
context.noteModuleConfigFile?.(manifestPath);
const main = packageJsonMain(manifest);
if (!main) return null;
const entry = path.posix.normalize(path.posix.join(dir, main));
if (entry.startsWith('..') || entry === '.') return null;
return indexedTarget(entry, language, context);
}

/**
* TypeScript under `moduleResolution: node16 | nodenext | bundler` writes the
* EMITTED extension in the specifier (`import x from './util.js'` for
Expand Down
15 changes: 14 additions & 1 deletion src/resolution/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import { matchShopifyThemeFile } from './shopify-themes';
import { isJsSuperCallLanguage, isJsSuperCallSite, matchJsSuperCall } from './js-super-calls';
import { CLASS_EXPRESSION_REF_LANGUAGES, isCommonJsExportedClass, isJsClassExpression, writtenIn, type ClassExpressionIndex } from './js-class-expressions';
import { clearRubyConstantPathMemos, matchRubyConstantPathRef } from './ruby-constant-paths';
import { resolveViaImport, resolvePhpImportedStaticCall, resolvePhpQualifiedClassRef, resolveTsQualifiedTypeRef, resolveJvmImport, extractImportMappings, extractReExports, CPP_COMPILE_DB_FILES, loadCppIncludeDirsFromCompileDB, loadCppIncludeDirsHeuristic, readCompileDbIncludeDirs, isPhpIncludePathRef, isCobolCopybookRef, isNixPathImportRef, isDartImportRef, isLuaRequireRef, isJsPathImportRef, isBoundToOutOfRepoImport, reachesAmbientModule, importBindingTail, clearImportResolverMemos, resolveImportPath, isExternalImport, pythonImportsInScope, ESM_IMPORT_LANGUAGES, jsModuleFile, pythonRootFingerprint, pythonReopenScope, pythonScriptModuleScope, pythonPackageImporters, moduleDefaultExport, isJsFamilyFile, isModuleBindingName } from './import-resolver';
import { resolveViaImport, resolvePhpImportedStaticCall, resolvePhpQualifiedClassRef, resolveTsQualifiedTypeRef, resolveJvmImport, extractImportMappings, extractReExports, CPP_COMPILE_DB_FILES, loadCppIncludeDirsFromCompileDB, loadCppIncludeDirsHeuristic, readCompileDbIncludeDirs, isPhpIncludePathRef, isCobolCopybookRef, isNixPathImportRef, isDartImportRef, isLuaRequireRef, isJsPathImportRef, isBoundToOutOfRepoImport, reachesAmbientModule, importBindingTail, clearImportResolverMemos, resolveImportPath, isExternalImport, pythonImportsInScope, ESM_IMPORT_LANGUAGES, jsModuleFile, pythonRootFingerprint, pythonReopenScope, pythonScriptModuleScope, pythonPackageImporters, moduleDefaultExport, isJsFamilyFile, isModuleBindingName, packageJsonMain } from './import-resolver';
import { ResolverPool, minRefsForPool, poolStartSettled, resolveWorkersWorthStarting, shouldEngageAdaptively } from './resolver-pool';
import { resolveAliasBinding } from './alias-binding';
import { readCargoWorkspaceCrateMap } from './frameworks/cargo-workspace';
Expand Down Expand Up @@ -323,10 +323,20 @@ function moduleConfigDigest(abs: string, projectRoot: string): string {
const read = file === 'go.mod' ? loadGoModule(path.dirname(abs))?.modulePath ?? ''
: file === 'Cargo.toml' ? cargoManifestDigestText(abs)
: file === 'compile_commands.json' ? (readCompileDbIncludeDirs(abs, projectRoot) ?? []).join('\n')
: file === 'package.json' ? packageJsonMainOf(abs)
: aliasConfigFields(abs) ?? '';
return createHash('sha256').update(read).digest('hex').slice(0, 16);
}

/** A folder's `package.json` `main`, which a relative import of the folder loads (see `relativeDirectoryMain`). */
function packageJsonMainOf(abs: string): string {
try {
return packageJsonMain(fs.readFileSync(abs, 'utf-8')) ?? '';
} catch {
return '';
}
}

function cargoManifestDigestText(abs: string): string {
try {
return cargoManifestFields(fs.readFileSync(abs, 'utf-8'));
Expand Down Expand Up @@ -1061,6 +1071,9 @@ export class ReferenceResolver {
},

readFile: (filePath: string) => this.readFileCached(filePath),
noteModuleConfigFile: (filePath: string) => {
this.moduleConfigFiles.add(path.join(this.projectRoot, filePath));
},

fileContains: (filePath: string, needle: string) => this.fileContains(filePath, needle),
scanFile: (filePath: string) => this.scanFile(filePath),
Expand Down
2 changes: 2 additions & 0 deletions src/resolution/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ export interface ResolutionContext {
fileExists(filePath: string): boolean;
/** Read file content */
readFile(filePath: string): string | null;
/** Record a project-relative file resolution read its answer from, for sync to watch (see `getModuleConfigSnapshot`). */
noteModuleConfigFile?(filePath: string): void;
/** `readFile(filePath)?.includes(needle) ?? false` for an ASCII `needle`, without decoding a file that lacks it. */
fileContains?(filePath: string, needle: string): boolean;
/**
Expand Down