module: add support for URL to import.meta.resolve

PR-URL: https://github.com/nodejs/node/pull/38587
Refs: https://github.com/nodejs/node/pull/38585
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Antoine du Hamel
2021-05-07 19:31:57 +02:00
committed by James M Snell
parent 8886b63cf6
commit 4ebb88fea5
3 changed files with 26 additions and 4 deletions

View File

@@ -280,6 +280,15 @@ const buffer = readFileSync(new URL('./data.proto', import.meta.url));
```
### `import.meta.resolve(specifier[, parent])`
<!--
added:
- v13.9.0
- v12.16.2
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/38587
description: Add support for WHATWG `URL` object to `parentURL` parameter.
-->
> Stability: 1 - Experimental

View File

@@ -13,6 +13,7 @@ const {
} = primordials;
const {
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE,
ERR_INVALID_MODULE_SPECIFIER,
ERR_INVALID_RETURN_PROPERTY,
@@ -20,8 +21,7 @@ const {
ERR_INVALID_RETURN_VALUE,
ERR_UNKNOWN_MODULE_FORMAT
} = require('internal/errors').codes;
const { URL, pathToFileURL } = require('internal/url');
const { validateString } = require('internal/validators');
const { URL, pathToFileURL, isURLInstance } = require('internal/url');
const ModuleMap = require('internal/modules/esm/module_map');
const ModuleJob = require('internal/modules/esm/module_job');
@@ -83,8 +83,8 @@ class Loader {
async resolve(specifier, parentURL) {
const isMain = parentURL === undefined;
if (!isMain)
validateString(parentURL, 'parentURL');
if (!isMain && typeof parentURL !== 'string' && !isURLInstance(parentURL))
throw new ERR_INVALID_ARG_TYPE('parentURL', ['string', 'URL'], parentURL);
const resolveResponse = await this._resolve(
specifier, { parentURL, conditions: DEFAULT_CONDITIONS }, defaultResolve);

View File

@@ -19,6 +19,19 @@ const fixtures = dirname.slice(0, dirname.lastIndexOf('/', dirname.length - 2) +
await import.meta.resolve('../fixtures/empty-with-bom.txt'),
fixtures + 'empty-with-bom.txt');
assert.strictEqual(await import.meta.resolve('../fixtures/'), fixtures);
assert.strictEqual(
await import.meta.resolve('../fixtures/', import.meta.url),
fixtures);
assert.strictEqual(
await import.meta.resolve('../fixtures/', new URL(import.meta.url)),
fixtures);
await Promise.all(
[[], {}, Symbol(), 0, 1, 1n, 1.1, () => {}, true, false].map((arg) =>
assert.rejects(import.meta.resolve('../fixtures/', arg), {
code: 'ERR_INVALID_ARG_TYPE',
})
)
);
assert.strictEqual(await import.meta.resolve('baz/', fixtures),
fixtures + 'node_modules/baz/');
})().then(mustCall());