|
| 1 | +import { spawnPromisified } from '../common/index.mjs'; |
| 2 | +import * as fixtures from '../common/fixtures.js'; |
| 3 | +import assert from 'node:assert/strict'; |
| 4 | +import { describe, it } from 'node:test'; |
| 5 | + |
| 6 | +const importMetaMainScript = ` |
| 7 | +import assert from 'node:assert/strict'; |
| 8 | +
|
| 9 | +assert.strictEqual(import.meta.main, true, 'import.meta.main should evaluate true in main module'); |
| 10 | +
|
| 11 | +const { isMain: importedModuleIsMain } = await import( |
| 12 | + ${JSON.stringify(fixtures.fileURL('es-modules/import-meta-main.mjs'))} |
| 13 | +); |
| 14 | +assert.strictEqual(importedModuleIsMain, false, 'import.meta.main should evaluate false in imported module'); |
| 15 | +`; |
| 16 | + |
| 17 | +function wrapScriptInEvalWorker(script) { |
| 18 | + return ` |
| 19 | + import { Worker } from 'node:worker_threads'; |
| 20 | + new Worker(${JSON.stringify(script)}, { eval: true }); |
| 21 | + `; |
| 22 | +} |
| 23 | + |
| 24 | +function convertScriptSourceToDataUrl(script) { |
| 25 | + return new URL(`data:text/javascript,${encodeURIComponent(script)}`); |
| 26 | +} |
| 27 | + |
| 28 | +function wrapScriptInUrlWorker(script) { |
| 29 | + return ` |
| 30 | + import { Worker } from 'node:worker_threads'; |
| 31 | + new Worker(new URL(${JSON.stringify(convertScriptSourceToDataUrl(script))})); |
| 32 | + `; |
| 33 | +} |
| 34 | + |
| 35 | +describe('import.meta.main in evaluated scripts', () => { |
| 36 | + it('should evaluate true in evaluated script', async () => { |
| 37 | + const result = await spawnPromisified( |
| 38 | + process.execPath, |
| 39 | + ['--input-type=module', '--eval', importMetaMainScript], |
| 40 | + ); |
| 41 | + assert.deepStrictEqual(result, { |
| 42 | + stderr: '', |
| 43 | + stdout: '', |
| 44 | + code: 0, |
| 45 | + signal: null, |
| 46 | + }); |
| 47 | + }); |
| 48 | + |
| 49 | + it('should evaluate true in worker instantiated with module source by evaluated script', async () => { |
| 50 | + const result = await spawnPromisified( |
| 51 | + process.execPath, |
| 52 | + ['--input-type=module', '--eval', wrapScriptInEvalWorker(importMetaMainScript)], |
| 53 | + ); |
| 54 | + assert.deepStrictEqual(result, { |
| 55 | + stderr: '', |
| 56 | + stdout: '', |
| 57 | + code: 0, |
| 58 | + signal: null, |
| 59 | + }); |
| 60 | + }); |
| 61 | + |
| 62 | + it('should evaluate true in worker instantiated with `data:` URL by evaluated script', async () => { |
| 63 | + const result = await spawnPromisified( |
| 64 | + process.execPath, |
| 65 | + ['--input-type=module', '--eval', wrapScriptInUrlWorker(importMetaMainScript)], |
| 66 | + ); |
| 67 | + assert.deepStrictEqual(result, { |
| 68 | + stderr: '', |
| 69 | + stdout: '', |
| 70 | + code: 0, |
| 71 | + signal: null, |
| 72 | + }); |
| 73 | + }); |
| 74 | +}); |
0 commit comments