Skip to content

Commit dc63d3c

Browse files
committed
fix(contracts): guard module path resolution without import.meta.url
1 parent 447cc0b commit dc63d3c

File tree

1 file changed

+37
-5
lines changed

1 file changed

+37
-5
lines changed

packages/contracts/src/custom-network-signatures.ts

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,30 @@ export interface BuildSignaturesFromContextResult {
5252
baseDirectory: string;
5353
}
5454

55+
/**
56+
* Resolves the on-disk path of this module in both ESM and CJS bundles.
57+
* Falls back to __filename when bundlers strip import.meta.url.
58+
*/
59+
function getCurrentModulePath(): string | undefined {
60+
const moduleUrl = (
61+
import.meta as unknown as { url?: string } | undefined
62+
)?.url;
63+
64+
if (moduleUrl) {
65+
try {
66+
return fileURLToPath(moduleUrl);
67+
} catch (error) {
68+
console.warn('Failed to resolve fileURLToPath from import.meta.url:', error);
69+
}
70+
}
71+
72+
if (typeof __filename === 'string') {
73+
return __filename;
74+
}
75+
76+
return undefined;
77+
}
78+
5579
/**
5680
* Gets the base directory for resolving paths
5781
* @param useScriptDirectory - Whether to use script's directory or current working directory
@@ -75,9 +99,14 @@ function getBaseDirectory(
7599
return __dirname;
76100
}
77101
// When running as module without callerPath
78-
const moduleDir = dirname(fileURLToPath(import.meta.url));
79-
console.log('Using module directory:', moduleDir);
80-
return moduleDir;
102+
const modulePath = getCurrentModulePath();
103+
if (modulePath) {
104+
const moduleDir = dirname(modulePath);
105+
console.log('Using module directory:', moduleDir);
106+
return moduleDir;
107+
}
108+
console.log('Using current working directory:', process.cwd());
109+
return process.cwd();
81110
}
82111
// Use current working directory
83112
const cwd = process.cwd();
@@ -308,9 +337,12 @@ module.exports = {
308337
// process.argv[0] is the bun executable
309338
// process.argv[1] is the script being run
310339
const mainScriptPath = path.resolve(process.argv[1] || '');
311-
const currentScriptPath = fileURLToPath(import.meta.url);
340+
const currentModulePath = getCurrentModulePath();
341+
const resolvedModulePath = currentModulePath
342+
? path.resolve(currentModulePath)
343+
: undefined;
312344

313-
if (mainScriptPath === currentScriptPath) {
345+
if (resolvedModulePath && mainScriptPath === resolvedModulePath) {
314346
// This means custom-network-signatures.ts was the script passed to `bun run`
315347
const jsonFilePath = process.argv[2];
316348
const networkName = process.argv[3];

0 commit comments

Comments
 (0)