|
| 1 | +Fixed `require.main === module` being trivially `true` in **every** compiled |
| 2 | +CommonJS module, not just the process entry point (#10735). |
| 3 | +`cjs_wrap`'s preamble unconditionally emitted `require.main = module;`, so |
| 4 | +the standard "am I the entry, or merely imported?" idiom took its CLI |
| 5 | +branch in every dependency that used it — including bundled packages |
| 6 | +(dotenv 18.0.1's `dist/index.cjs` is a confirmed real-world example). |
| 7 | + |
| 8 | +The fix threads the compiler's existing entry-module knowledge (the same |
| 9 | +comparison `import.meta.main` uses) through `cjs_wrap`, but that alone is |
| 10 | +insufficient: `cjs_wrap` transpiles a statically-known |
| 11 | +`require('./relative')` into a hoisted ESM import, and ESM import |
| 12 | +evaluation runs a module's static-import dependencies *before* the |
| 13 | +importing module's own top-level code. So a CJS entry's own dependencies |
| 14 | +initialize before the entry's own preamble runs, which means "the entry |
| 15 | +publishes `require.main` in its own preamble" is too late for any |
| 16 | +dependency reached via a hoisted static import. Fixed by publishing a |
| 17 | +placeholder object as the shared "main module" from the program's `main()` |
| 18 | +itself, before any module's `__init` runs at all (gated on the entry being |
| 19 | +CJS-wrapped, so an ESM entry correctly leaves `require.main` `undefined` |
| 20 | +for CJS modules it imports); the entry later reclaims that exact object |
| 21 | +and fills in its real fields, preserving identity for dependencies that |
| 22 | +captured `require.main` before the entry's own code ran. |
| 23 | + |
| 24 | +The new runtime-side cache backing this (`CJS_MAIN_MODULE`) is registered |
| 25 | +with the GC's mutable-root-scanner machinery and verified under forced |
| 26 | +evacuation (`PERRY_GC_SCHEDULE_SEED`/`PERRY_GC_FORCE_EVACUATE`/ |
| 27 | +`PERRY_GC_PROTECT_FROMSPACE`): the placeholder moved, the cache followed |
| 28 | +it, and every identity assertion held across 8,006 forced collections. A |
| 29 | +new test (`gc::tests::cjs_main_module`) asserts the rewrite counter is |
| 30 | +non-zero under a real evacuating minor, so a future regression that stops |
| 31 | +rewriting the cache fails a test instead of silently reintroducing this |
| 32 | +bug's failure mode. |
0 commit comments