Skip to content

module: improve error message for top-level await in CommonJS #55874

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: main
Choose a base branch
from

Conversation

mertcanaltin
Copy link
Member

Added a specific error message for using top-level await in CommonJS modules. The error now suggests using ESM or wrapping await in an async function for clarity.

Fixes: #55776

@nodejs-github-bot nodejs-github-bot added c++ Issues and PRs that require attention from people who are familiar with C++. needs-ci PRs that need a full CI run. vm Issues and PRs related to the vm subsystem. labels Nov 15, 2024
Copy link

codecov bot commented Nov 15, 2024

Codecov Report

Attention: Patch coverage is 83.33333% with 4 lines in your changes missing coverage. Please review.

Project coverage is 90.21%. Comparing base (968e2f4) to head (811e9c5).
Report is 22 commits behind head on main.

Files with missing lines Patch % Lines
src/module_wrap.cc 71.42% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #55874      +/-   ##
==========================================
- Coverage   90.21%   90.21%   -0.01%     
==========================================
  Files         635      635              
  Lines      187580   187460     -120     
  Branches    36853    36831      -22     
==========================================
- Hits       169231   169112     -119     
- Misses      11108    11146      +38     
+ Partials     7241     7202      -39     
Files with missing lines Coverage Δ
lib/internal/modules/esm/module_job.js 97.25% <100.00%> (+0.03%) ⬆️
src/module_wrap.h 0.00% <ø> (ø)
src/module_wrap.cc 72.54% <71.42%> (+0.10%) ⬆️

... and 44 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Member

@GeoffreyBooth GeoffreyBooth left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for tackling this! I’d love to see this issue addressed.

@mertcanaltin mertcanaltin added the help wanted Issues that need assistance from volunteers or PRs that need help to proceed. label Nov 27, 2024
@mertcanaltin mertcanaltin force-pushed the dev-55776 branch 3 times, most recently from 76f87e4 to c9531ef Compare November 29, 2024 21:21
@mertcanaltin mertcanaltin added review wanted PRs that need reviews. and removed help wanted Issues that need assistance from volunteers or PRs that need help to proceed. labels Nov 30, 2024
Copy link
Member

@GeoffreyBooth GeoffreyBooth left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for taking another pass at this. I mention this in the particular notes, but in general:

  1. Please don't change lines based on personal preference or readability. We value the ability for git blame to point directly to the commit/PR that added or meaningfully changed a particular line, and that ability is diluted when unrelated PRs rewrite lines of code.

  2. Very few, if any, tests should change as a result of your PR: only tests specifically related to top-level await in CommonJS. Any other tests that fail as a result of your changes mean that there's a bug in the implementation that needs to be addressed. My guess is that the bug is that the new code isn't checking that the error message being thrown is specifically about top-level await. If there aren't currently tests for top-level await in CommonJS and your new error message, one or more should be added.

This is close; another pass and I think you may get it there. Thanks for your effort!

@mertcanaltin
Copy link
Member Author

Thanks for taking another pass at this. I mention this in the particular notes, but in general:

  1. Please don't change lines based on personal preference or readability. We value the ability for git blame to point directly to the commit/PR that added or meaningfully changed a particular line, and that ability is diluted when unrelated PRs rewrite lines of code.
  2. Very few, if any, tests should change as a result of your PR: only tests specifically related to top-level await in CommonJS. Any other tests that fail as a result of your changes mean that there's a bug in the implementation that needs to be addressed. My guess is that the bug is that the new code isn't checking that the error message being thrown is specifically about top-level await. If there aren't currently tests for top-level await in CommonJS and your new error message, one or more should be added.

This is close; another pass and I think you may get it there. Thanks for your effort!

thank you very much for the review, I will be sending a new commit following what you said

@mertcanaltin
Copy link
Member Author

Greetings, when I did as you suggested to cover only the top level error, I saw that all tests passed except 1 test

Copy link
Member

@GeoffreyBooth GeoffreyBooth left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is much better. What’s the one test that is failing?

@GeoffreyBooth GeoffreyBooth added module Issues and PRs related to the module subsystem. esm Issues and PRs related to the ECMAScript Modules implementation. labels Dec 2, 2024
@mertcanaltin
Copy link
Member Author

Thanks, this is much better. What’s the one test that is failing?

I saw wrong, all the tests passed my local. 🙏

@GeoffreyBooth
Copy link
Member

I saw wrong, all the tests passed my local. 🙏

There’s a test failing in here, in the relevant file: https://github.com/nodejs/node/actions/runs/12133213207/job/33828380981?pr=55874

@cjihrig why isn’t the CI output showing me which test is failing within that file?

@cjihrig
Copy link
Contributor

cjihrig commented Dec 3, 2024

why isn’t the CI output showing me which test is failing within that file?

No clue. But the output is incomplete. There is no summary at the end either. It looks like maybe the Python runner killed the Node process or otherwise truncated its output.

@cjihrig
Copy link
Contributor

cjihrig commented Dec 3, 2024

@GeoffreyBooth just FYI - IIRC, you asked me a similar question in Slack last year. There was output truncated only in GitHub Actions. Then you asked me to find a test run where truncation was happening without the use of node:test, and I did. I believe @MoLow was a part of that thread as well.

@GeoffreyBooth
Copy link
Member

IIRC, you asked me a similar question in Slack last year.

Yes, last August: https://openjs-foundation.slack.com/archives/C019Y2T6STH/p1691860008875109. I’m lucky if I can remember last month, much less last year. Sorry to repeat. I also opened #49120 but that got closed.

@mertcanaltin
Copy link
Member Author

I saw wrong, all the tests passed my local. 🙏

There’s a test failing in here, in the relevant file: https://github.com/nodejs/node/actions/runs/12133213207/job/33828380981?pr=55874

@cjihrig why isn’t the CI output showing me which test is failing within that file?

yes, ı view my local enviorement this test is fail

test at test/es-module/test-esm-detect-ambiguous.mjs:367:5
 does not warn when there are no package.json (63.625667ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
  + actual - expected
  
  + "(node:18411) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///Users/mert/Desktop/openSource/node/test/fixtures/es-modules/loose.js is not specified and it doesn't parse as CommonJS.\n" +
  +   'Reparsing as ES module because module syntax was detected. This incurs a performance overhead.\n' +
  +   'To eliminate this warning, add "type": "module" to /Users/mert/package.json.\n' +
  +   '(Use `node --trace-warnings ...` to show where the warning was created)\n'
  - ''
  
      at TestContext.<anonymous> (file:///Users/mert/Desktop/openSource/node/test/es-module/test-esm-detect-ambiguous.mjs:372:7)
      at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
      at async Test.run (node:internal/test_runner/test:932:9)
      at async Promise.all (index 3)
      at async Suite.run (node:internal/test_runner/test:1310:7)
      at async Promise.all (index 6)
      at async Suite.run (node:internal/test_runner/test:1310:7)
      at async startSubtestAfterBootstrap (node:internal/test_runner/harness:297:3) {
    generatedMessage: true,
    code: 'ERR_ASSERTION',
    actual: '(node:18411) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///Users/mert/Desktop/openSource/node/test/fixtures/es-modules/loose.js is not specified and it doesn\'t parse as CommonJS.\nReparsing as ES module because module syntax was detected. This incurs a performance overhead.\nTo eliminate this warning, add "type": "module" to /Users/mert/package.json.\n(Use `node --trace-warnings ...` to show where the warning was created)\n',
    expected: '',
    operator: 'strictEqual'
  }

@mertcanaltin
Copy link
Member Author

greetings I tried to make the error message more descriptive, in addition I tried to throw it when there is a file that cannot be successfully parsed as ESM

@mertcanaltin
Copy link
Member Author

hello, I would be very grateful if you could look here when you are available, thank you very much @GeoffreyBooth

@nodejs-github-bot
Copy link
Collaborator

@nodejs-github-bot
Copy link
Collaborator

Copy link
Member

@GeoffreyBooth GeoffreyBooth left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mertcanaltin Thank you for your persistence. I think the approach of “a test is failing, so I’ll update the test” isn’t serving us well here; most of these updated tests shouldn’t need updating to achieve the goals of this PR, and the fact that they’re failing is an indicator that there are bugs in the implementation.

@mertcanaltin
Copy link
Member Author

@mertcanaltin Thank you for your persistence. I think the approach of “a test is failing, so I’ll update the test” isn’t serving us well here; most of these updated tests shouldn’t need updating to achieve the goals of this PR, and the fact that they’re failing is an indicator that there are bugs in the implementation.

many thanks for your answers I will improve this place

@joyeecheung
Copy link
Member

joyeecheung commented Jan 20, 2025

I feel for the specific case mentioned in #55776, merely amending the error message is not good enough. It would've been clearer to either completely revert to the CJS exception (i.e. even the source line should be where the top-level await is at, not where require is at), or show both the exception that would be thrown if it's parsed as CJS, and the exception that would be thrown if it's parsed as ESM, to make it clear to the users that it cannot be parsed as neither, and print solution for each one as a warning (if they meant to use CJS, wrap the await in async function; if they meant to use ESM, do not use require).

@mertcanaltin
Copy link
Member Author

I feel for the specific case mentioned in #55776, merely amending the error message is not good enough. It would've been clearer to either completely revert to the CJS exception (i.e. even the source line should be where the top-level await is at, not where require is at), or show both the exception that would be thrown if it's parsed as CJS, and the exception that would be thrown if it's parsed as ESM, to make it clear to the users that it cannot be parsed as neither, and print solution for each one as a warning (if they meant to use CJS, wrap the await in async function; if they meant to use ESM, do not use require).

Hello, now I tried to highlight both errors that can occur as you said

Comment on lines 77 to 79
isCommonJSGlobalLikeNotDefinedError(e.message)) {

if (e.message.includes('require is not defined')) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checking for require is not defined seems like it belongs within isCommonJSGlobalLikeNotDefinedError.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I've removed it, thank you.

Comment on lines 81 to 85
'ERR_AMBIGUOUS_MODULE_SYNTAX: This file cannot be parsed as either CommonJS or ES Module.',
'- CommonJS error: await is only valid in async functions.',
'- ES Module error: require is not defined in ES module scope.',
'If you meant to use CommonJS, wrap top-level await in async function.',
'If you meant to use ESM, do not use require().',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This error message assumes that a top-level await is present, but simply checking for require is not defined wouldn’t necessarily imply that, would it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're absolutely right! My current implementation only checks for the "require is not defined" error but doesn't verify that top-level await is actually present. This could show misleading error messages for files that only use require() without any await.
I should add an additional check to detect top-level await in the source code before showing this specific error message.

'- ES Module error: require is not defined in ES module scope.',
'If you meant to use CommonJS, wrap top-level await in async function.',
'If you meant to use ESM, do not use require().',
].join('\n');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Creating an array of strings and joining them is unnecessary processing to do at runtime. It would be more performant to just define a single string in the first place.

Also I can't think of other instances where we return multiline error messages. Unless this is a pattern we already use elsewhere, this should be rephrased to be one line. It doesn't need to be a single sentence, but it shouldn't include a newline.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I absolutely agree, I have updated this as a single line

@@ -38,5 +38,5 @@ assert.rejects(

assert.rejects(
import('data:text/javascript,require;//.js'),
/^(?!use the '\.cjs' file extension).*$/
/^(?:(?!use the '\.cjs' file extension)[\s\S])*$/
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this change?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the regex here was broken at first so I updated it, but now the Asis version seems healthy, so I reverted it

Copy link
Member Author

@mertcanaltin mertcanaltin Jun 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I looked here, I got an error for an unspelled period character in a regular expression, so I updated it
https://github.com/nodejs/node/actions/runs/15426765636/job/43415537965?pr=55874

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
c++ Issues and PRs that require attention from people who are familiar with C++. esm Issues and PRs related to the ECMAScript Modules implementation. module Issues and PRs related to the module subsystem. needs-ci PRs that need a full CI run. review wanted PRs that need reviews. vm Issues and PRs related to the vm subsystem.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

detect-module: confusing error when parsing a CommonJS module with top-level await
5 participants