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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- In JavaScript, a call to a member a required module of your project doesn't have, like `utils.missing()` after `const utils = require('./utils')`, no longer links to an unrelated class's method of that name. Thanks @inth3shadows for the report and @johnhldiver-beep. (#3272)
- A `fetch` or HTTP-client call to another company's API, like `fetch('https://api.github.com/users/…')`, no longer links to your own server's route with the same path; a call to localhost, to a host your code fills in, or through a client's base URL still links. Thanks @inth3shadows for the report and @johnhldiver-beep. (#2974)
- In JavaScript and TypeScript, a call or `new` of a global, like `parseInt(…)`, `new Response(…)` or `new URL(…)`, in a module that doesn't import that name no longer links to a same-named export of another file in your project. Thanks @inth3shadows for the report. (#3238)
- 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)

## [1.6.3] - 2026-11-17

Expand Down
76 changes: 76 additions & 0 deletions __tests__/require-directory-package-main.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* 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() }
`,
'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("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']);
});
});
28 changes: 28 additions & 0 deletions src/resolution/import-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1381,8 +1381,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) {
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 @@ -1397,6 +1405,26 @@ function resolveRelativeImport(
return findSourceForEmittedSpecifier(relativePath, language, context);
}

/**
* 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.
*/
function relativeDirectoryMain(dir: string, language: Language, context: ResolutionContext): string | null {
const manifest = context.readFile(dir === '' ? 'package.json' : `${dir}/package.json`);
if (!manifest) return null;
let main: unknown;
try {
main = (JSON.parse(manifest) as { main?: unknown } | null)?.main;
} catch {
return null;
}
if (typeof main !== 'string' || !main.trim()) return null;
const entry = path.posix.normalize(path.posix.join(dir, main.trim()));
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