• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const common = require('../common');
3const assert = require('assert');
4
5const relativePath = '../fixtures/es-modules/test-esm-ok.mjs';
6const absolutePath = require.resolve('../fixtures/es-modules/test-esm-ok.mjs');
7const targetURL = new URL('file:///');
8targetURL.pathname = absolutePath;
9
10function expectModuleError(result, code, message) {
11  Promise.resolve(result).catch(common.mustCall((error) => {
12    assert.strictEqual(error.code, code);
13    if (message) assert.strictEqual(error.message, message);
14  }));
15}
16
17function expectOkNamespace(result) {
18  Promise.resolve(result)
19    .then(common.mustCall((ns) => {
20      const expected = { default: true };
21      Object.defineProperty(expected, Symbol.toStringTag, {
22        value: 'Module'
23      });
24      Object.setPrototypeOf(expected, Object.getPrototypeOf(ns));
25      assert.deepStrictEqual(ns, expected);
26    }));
27}
28
29function expectFsNamespace(result) {
30  Promise.resolve(result)
31    .then(common.mustCall((ns) => {
32      assert.strictEqual(typeof ns.default.writeFile, 'function');
33      assert.strictEqual(typeof ns.writeFile, 'function');
34    }));
35}
36
37// For direct use of import expressions inside of CJS or ES modules, including
38// via eval, all kinds of specifiers should work without issue.
39(function testScriptOrModuleImport() {
40  // Importing another file, both direct & via eval
41  // expectOkNamespace(import(relativePath));
42  expectOkNamespace(eval(`import("${relativePath}")`));
43  expectOkNamespace(eval(`import("${relativePath}")`));
44  expectOkNamespace(eval(`import("${targetURL}")`));
45
46  // Importing a built-in, both direct & via eval
47  expectFsNamespace(import('fs'));
48  expectFsNamespace(eval('import("fs")'));
49  expectFsNamespace(eval('import("fs")'));
50  expectFsNamespace(import('node:fs'));
51
52  expectModuleError(import('node:unknown'),
53                    'ERR_UNKNOWN_BUILTIN_MODULE');
54  expectModuleError(import('node:internal/test/binding'),
55                    'ERR_UNKNOWN_BUILTIN_MODULE');
56  expectModuleError(import('./not-an-existing-module.mjs'),
57                    'ERR_MODULE_NOT_FOUND');
58  expectModuleError(import('http://example.com/foo.js'),
59                    'ERR_UNSUPPORTED_ESM_URL_SCHEME');
60  if (common.isWindows) {
61    const msg =
62      'Only file and data URLs are supported by the default ESM loader. ' +
63      'On Windows, absolute paths must be valid file:// URLs. ' +
64      "Received protocol 'c:'";
65    expectModuleError(import('C:\\example\\foo.mjs'),
66                      'ERR_UNSUPPORTED_ESM_URL_SCHEME',
67                      msg);
68  }
69})();
70