@parity/resolc fix sol file resolutions (#343)

second take on #339 

turns out that the resolve-pkg npm package was also failing to properly
resolve package with an exports field define in the package.json.

This fixes it and add a test case with such a package
This commit is contained in:
PG Herveou
2025-06-05 10:05:53 +02:00
committed by GitHub
parent e94432eaa0
commit 63f0266fff
4 changed files with 1424 additions and 42 deletions
+19 -6
View File
@@ -68,6 +68,16 @@ test('resolve import', () => {
file: './fixtures/storage.sol',
expected: resolve('fixtures/storage.sol'),
},
// package with exports
{
file: '@redstone-finance/evm-connector/contracts/data-services/PrimaryProdDataServiceConsumerBase.sol',
expected: resolve(
__dirname,
'../../..',
'node_modules/@redstone-finance/evm-connector/contracts/data-services/PrimaryProdDataServiceConsumerBase.sol'
),
},
// scopped module with version
{
file: '@openzeppelin/contracts@5.1.0/token/ERC20/ERC20.sol',
@@ -100,16 +110,19 @@ test('resolve import', () => {
]
for (const { file, expected } of cases) {
let resolved
try {
const resolved = tryResolveImport(file)
assert(
resolved === expected,
`\nGot:\n${resolved}\nExpected:\n${expected}`
)
resolved = tryResolveImport(file)
} catch (error) {
assert(
String(error) == expected,
`\nGot:\n${String(error)}\nExpected:\n${expected}`
`\nExpected:\n${expected}\nGot:\n${String(error)}\n`
)
}
if (resolved) {
assert(
resolved === expected,
`\nExpected:\n${expected}\nGot:\n${resolved}`
)
}
}
+21 -1
View File
@@ -129,6 +129,26 @@ export async function compile(
return resolc(input)
}
/**
* resolve the package root
* use resolve-pkg to find the package root, and fallback to using require.resolve if the package defines an exports field
* see https://github.com/sindresorhus/resolve-pkg/issues/9
**/
function resolvePkgRoot(basePackage: string) {
const packageRoot = resolvePkg(basePackage)
if (packageRoot) {
return packageRoot
}
try {
const packageExport = require.resolve(basePackage)
const endIndex = packageExport.indexOf(basePackage) + basePackage.length
return packageExport.substring(0, endIndex)
} catch {}
return undefined
}
/**
* Resolve an import path to a file path.
* @param importPath - The import path to resolve.
@@ -150,7 +170,7 @@ export function tryResolveImport(importPath: string) {
const specifiedVersion = match[2] // "1.2.3" (optional)
const relativePath = match[3] // "/path/to/file.sol"
const packageRoot = resolvePkg(basePackage)
const packageRoot = resolvePkgRoot(basePackage)
if (!packageRoot) {
throw new Error(`Package ${basePackage} not found.`)
}