MCPcopy Create free account
hub / github.com/colbymchenry/codegraph / resolveRelativeImport

Function resolveRelativeImport

src/resolution/import-resolver.ts:1633–1669  ·  view source on GitHub ↗

* Resolve a relative import

(
  importPath: string,
  fromDir: string,
  language: Language,
  context: ResolutionContext
)

Source from the content-addressed store, hash-verified

1631 * Resolve a relative import
1632 */
1633function resolveRelativeImport(
1634 importPath: string,
1635 fromDir: string,
1636 language: Language,
1637 context: ResolutionContext
1638): string | null {
1639 const projectRoot = context.getProjectRoot();
1640 const extensions = EXTENSION_RESOLUTION[language] || [];
1641
1642 // Try the path as-is first
1643 const basePath = path.resolve(fromDir, importPath);
1644 const relativePath = path.relative(projectRoot, basePath).replace(/\\/g, '/');
1645
1646 // Try each extension. `require('..')` up to the project root is its `index.js`.
1647 let mainTried = false;
1648 for (const ext of extensions) {
1649 if (relativePath === '' && !ext.startsWith('/')) continue;
1650 // A directory's `package.json` `main` comes before its index files, as
1651 // Node loads a directory (#2964).
1652 if (ext.startsWith('/') && !mainTried && FOLDER_MAIN_LANGUAGES.has(language)) {
1653 mainTried = true;
1654 const main = relativeDirectoryMain(relativePath, language, context);
1655 if (main) return main;
1656 }
1657 const candidatePath = relativePath === '' ? ext.slice(1) : relativePath + ext;
1658 if (context.fileExists(candidatePath)) {
1659 return candidatePath;
1660 }
1661 }
1662
1663 // Try without extension (might already have one)
1664 if (context.fileExists(relativePath)) {
1665 return relativePath;
1666 }
1667
1668 return findSourceForEmittedSpecifier(relativePath, language, context);
1669}
1670
1671/**
1672 * The importers whose relative import of a folder reads the folder's

Callers 1

Calls 6

relativeDirectoryMainFunction · 0.85
hasMethod · 0.80
fileExistsMethod · 0.80
getProjectRootMethod · 0.65
resolveMethod · 0.65

Tested by

no test coverage detected