diff --git a/src/cjs/api/module-resolve-filename.ts b/src/cjs/api/module-resolve-filename.ts index 154cf68b..f95582f3 100644 --- a/src/cjs/api/module-resolve-filename.ts +++ b/src/cjs/api/module-resolve-filename.ts @@ -169,19 +169,32 @@ export const createResolveFilename = ( request = interopCjsExports(request); - if (parent?.filename) { - const filePath = getOriginalFilePath(parent.filename); - if (filePath) { - parent.filename = filePath.split('?')[0]; - } - } - // Strip query string const requestAndQuery = request.split('?'); const searchParams = new URLSearchParams(requestAndQuery[1]); - // Inherit parent namespace if it exists if (parent?.filename) { + const filePath = getOriginalFilePath(parent.filename); + if (filePath) { + const newFilename = filePath.split('?')[0]; + + /** + * Can't delete the old cache entry because there's an assertion + * https://github.com/nodejs/node/blob/v20.15.0/lib/internal/modules/esm/translators.js#L347 + */ + // delete Module._cache[parent.filename]; + + parent.filename = newFilename; + // @ts-expect-error - private property + parent.path = path.dirname(newFilename); + // https://github.com/nodejs/node/blob/v20.15.0/lib/internal/modules/esm/translators.js#L383 + // @ts-expect-error - private property + parent.paths = Module._nodeModulePaths(parent.path); + + Module._cache[newFilename] = parent as NodeModule; + } + + // Inherit parent namespace if it exists const parentQuery = new URLSearchParams(parent.filename.split('?')[1]); const parentNamespace = parentQuery.get('namespace'); if (parentNamespace) { diff --git a/tests/specs/api.ts b/tests/specs/api.ts index fd11668c..946f07b0 100644 --- a/tests/specs/api.ts +++ b/tests/specs/api.ts @@ -27,6 +27,9 @@ const tsFiles = { `, cjs: { + node_modules: { + 'pkg/index.js': 'module.exports = 1', + }, 'exports-no.cts': ` // Supports decorators const log = (target, key, descriptor) => descriptor; @@ -36,7 +39,7 @@ const tsFiles = { } console.log("cts loaded" as string) `, - 'exports-yes.cts': 'module.exports = require("./reexport.cjs") as string', + 'exports-yes.cts': 'module.exports = require("./reexport.cjs") as string; require("pkg");', 'esm-syntax.js': 'export const esmSyntax = "esm syntax"', 'reexport.cjs': ` exports.cjsReexport = "cjsReexport";