From 7964fe8d1a8cb943d264c5d88f70e97ff733d98c Mon Sep 17 00:00:00 2001 From: Geoffrey Booth Date: Sun, 23 Jun 2024 16:42:43 -0700 Subject: [PATCH] add test that detection doesn't interfere with hooks --- test/es-module/test-esm-detect-ambiguous.mjs | 19 +++++++++++++++++++ .../transpile-esm-to-cjs.mjs | 16 ++++++++++++++++ .../package-without-type/esm-with-check.js | 2 ++ 3 files changed, 37 insertions(+) create mode 100644 test/fixtures/es-module-loaders/transpile-esm-to-cjs.mjs create mode 100644 test/fixtures/es-modules/package-without-type/esm-with-check.js diff --git a/test/es-module/test-esm-detect-ambiguous.mjs b/test/es-module/test-esm-detect-ambiguous.mjs index a7676c228d68f44..00db0cf90f60bf4 100644 --- a/test/es-module/test-esm-detect-ambiguous.mjs +++ b/test/es-module/test-esm-detect-ambiguous.mjs @@ -400,6 +400,25 @@ describe('--experimental-detect-module', { concurrency: !process.env.TEST_PARALL strictEqual(code, 0); strictEqual(signal, null); }); + + it('should detect the syntax of the source as returned by a custom load hook', async () => { + const { code, signal, stdout, stderr } = await spawnPromisified(process.execPath, [ + '--no-warnings', + '--experimental-detect-module', + '--import', + `data:text/javascript,${encodeURIComponent( + 'import { register } from "node:module";' + + 'import { pathToFileURL } from "node:url";' + + 'register("./transpile-esm-to-cjs.mjs", pathToFileURL("./"));' + )}`, + fixtures.path('es-modules/package-without-type/esm-with-check.js'), + ], { cwd: fixtures.fileURL('es-module-loaders/') }); + + strictEqual(stderr, ''); + strictEqual(stdout, 'commonjs\ntransformed!\n'); + strictEqual(code, 0); + strictEqual(signal, null); + }); }); }); diff --git a/test/fixtures/es-module-loaders/transpile-esm-to-cjs.mjs b/test/fixtures/es-module-loaders/transpile-esm-to-cjs.mjs new file mode 100644 index 000000000000000..42be3172e33c9ad --- /dev/null +++ b/test/fixtures/es-module-loaders/transpile-esm-to-cjs.mjs @@ -0,0 +1,16 @@ +export async function load(url, context, next) { + const output = await next(url, context); + let source = `${output.source}` + + // This is a very naive implementation for testing purposes only + if (source?.includes('import')) { + source = source.replace(/import\s+{\s*([^;]+)\s*}\s+from\s+(['"])(.*?)\2;/g, 'const { $1 } = require($2$3$2);') + + source += '\nconsole.log("transformed!");'; // To verify the hook ran + + output.source = source; + output.format = 'commonjs'; + } + + return output; +} diff --git a/test/fixtures/es-modules/package-without-type/esm-with-check.js b/test/fixtures/es-modules/package-without-type/esm-with-check.js new file mode 100644 index 000000000000000..06e8a16a67cc9fe --- /dev/null +++ b/test/fixtures/es-modules/package-without-type/esm-with-check.js @@ -0,0 +1,2 @@ +import { version } from 'node:process'; +console.log(this === undefined ? 'module' : 'commonjs');