nodejs / node

Node.js JavaScript runtime ✨🐢🚀✨
https://nodejs.org
Other
107.08k stars 29.32k forks source link

patching Module.wrapper et al. breaks shebang stripping #36173

Open jaked opened 3 years ago

jaked commented 3 years ago

What steps will reproduce the bug?

in file test.js:

#! /foo/bar/baz
console.log('ok')

then

$ node
> const Module = require('module')
> Module.wrapper = Module.wrapper
> require('./test')
/Users/jake/test.js:1
(function (exports, require, module, __filename, __dirname) { #! /foo/bar/baz
                                                              ^

Uncaught SyntaxError: Invalid or unexpected token

How often does it reproduce? Is there a required condition?

always

What is the expected behavior?

shebang line is stripped, no syntax error

What do you see instead?

syntax error

Additional information

Shebang lines are supposed to be stripped when loading modules. This was moved from internal/modules/cjs to V8, see https://github.com/nodejs/node/commit/702331be90

Also, loaded modules are wrapped in an IIFE to provide context; this originally used Module.wrapper, but was changed to use an internal contextify module, with a fallback to the old implementation if Module.wrapper is monkey-patched, see https://github.com/nodejs/node/commit/5f8ccecaa2

(I'm using Electron, which monkey-patches Module.wrapper, see https://github.com/electron/electron/commit/a4fcc32799)

However, the shebang change seems to have broken the monkey-patching support. In this case, the shebang line is not stripped in internal/modules/cjs, but the module is wrapped in an IIFE, so the shebang is now inside the IIFE.

sseide commented 3 years ago

for us it breaks loading plant-uml package to auto-generate uml images while running jsdoc... No nice images anymore in docs, just a sea of gray :-(

Is there anyone working on it? Its not an electron only problem. We have this too without "electron" or "rewire" trying to create JSDoc documentation from source files.

pduchesne commented 1 year ago

Any news on this?

We are hitting this problem too. It happens whenever your project imports both a module that involves a shebang line, and another module that patches the module loader. In that situation, as pointed out by @jaked , the patching of the module loader causes the old implementation to kick in, resulting in the shebang line to not be removed by V8.

The stripShebang function should be reinstated in the case of a patched module loader.