Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
5 changes: 5 additions & 0 deletions .changeset/polite-beds-doubt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"hardhat": patch
---

Accept relative paths to node_modules in npm remappings [#8007](https://github.com/NomicFoundation/hardhat/pull/8007)
Comment thread
kanej marked this conversation as resolved.
Outdated
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,32 @@ import { UserRemappingType } from "./types.js";

const HARDHAT_PROJECT_INPUT_SOURCE_NAME_ROOT = "project";

/**
* Returns a normalized version of the path if it refers to a node_modules in
* the root directory (i.e. node_modules/...), or a `node_modules` directory
* in a parent directory (i.e. ../../node_modules/...).
*
* Otherwise returns `undefined`.
*
* @param pathToNormalize The path to normalize.
* @returns The normalized path (node_modules/...), or `undefined`.
*/
export function getNormalizeNodeModulesPath(
pathToNormalize: string,
): string | undefined {
if (pathToNormalize.startsWith("node_modules/")) {
return pathToNormalize;
}

const normalized = path.posix.normalize(pathToNormalize);

if (!/^(?:\.\.\/)*node_modules\//.test(normalized)) {
return undefined;
}

return normalized.substring(normalized.indexOf("node_modules/"));
}

export type RemappingsReaderFunction = (
packageName: string,
packageVersion: string,
Expand Down Expand Up @@ -559,7 +585,7 @@ export class RemappedNpmPackagesGraphImplementation
const prefix = remapping.prefix.endsWith("/")
? remapping.prefix
: remapping.prefix + "/";
const target = remapping.target.endsWith("/")
let target = remapping.target.endsWith("/")
? remapping.target
: remapping.target + "/";

Expand All @@ -568,12 +594,13 @@ export class RemappedNpmPackagesGraphImplementation
path.dirname(sourceOfTheRemapping),
);

// If the remapping's target starts with `node_modules/`, we treat
// it as trying to load an npm dependency, otherwise we treat it as a local
// If the remapping's target starts with `node_modules/`, we treat it as
// trying to load an npm dependency, otherwise we treat it as a local
// remapping.
const normalizedNodeModulesTarget = getNormalizeNodeModulesPath(target);

// Local remapping case
if (!target.startsWith("node_modules/")) {
if (normalizedNodeModulesTarget === undefined) {
return {
success: true,
value: {
Expand All @@ -593,6 +620,9 @@ export class RemappedNpmPackagesGraphImplementation
source: sourceOfTheRemapping,
},
};
} else {
// We update the target to the normalized version
target = normalizedNodeModulesTarget;
}

// If we are here the remapping is a npm remapping.
Expand Down
Loading