modules: runtime deprecate module.parent
TL;DR: runtime warning when this module.parent
is accessed from a module that have a nullish value for their module.parent
(when a ESM imports it or when the module is run as the entry point of the process).
Currently, module.parent
provides a way for CJS users to get which CJS modules required the current module first. This feature – not very useful by itself – is also used to make assumption about the program entry point. It is not rare to find packages that wrap their test code inside a if(!module.parent)
condition, assuming that a falsy value means the module is run from CLI. The issue with this pattern is that the assumption doesn't work as soon as the module interacts with ESM or REPL.
With ESM being unflagged in current and LTS release lines, I predict this could become a real pain point for users trying to use ESM in Node.js.
Current issue
The issue I'd like to address is when a dependency is using the if(!module.parent)
pattern to run its tests, and the test code gets executed for ESM users without their knowledge; those tests that may have side effects and make the end user code fail without obvious reason.
Action taken in this PR
-
setthat was moved to https://github.com/nodejs/node/pull/37702.module.parent
to a truthy value instead ofundefined
(in this PR, I'm using a dummy classUnknownModule
). - add a runtime warning when
module.parent
is nullish, so it warns:- library authors not to use this pattern.
- end user facing the bug that it may impact their code.
Objections and alternative solutions
- Because the
UnknownModule
object created is effectively just an empty object, it doesn't have any property of the module object users may expect. If this is not acceptable, we can keep the current behaviour (module.parent
isundefined
if the module was loaded by something that is not a CommonJS module). - Some packages may use the
if(!module.parent)
pattern in their CLI exposed file. That would lead to end users seeing a warning they have no control over. I don't think there would be a lot of packages affected by this, but that's a possibility. If this is not acceptable, we can check if the file is inside anode_modules
folder (similarly to what we do forBuffer
constructor), or stick to the doc only deprecation for the time being.
Refs: #32217
Checklist
-
make -j4 test
(UNIX), orvcbuild test
(Windows) passes -
tests and/or benchmarks are included -
documentation is changed or added -
commit message follows commit guidelines