From a6cfea3f749ff2db9d5dc8968eb698f1281ac316 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Sun, 20 Aug 2023 07:08:22 +0200 Subject: [PATCH] esm: align sync and async load implementations Refs: https://github.com/nodejs/node/pull/48272 PR-URL: https://github.com/nodejs/node/pull/49152 Refs: https://github.com/nodejs/node/pull/47999 Reviewed-By: Geoffrey Booth Reviewed-By: Jacob Smith --- lib/internal/modules/esm/load.js | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/lib/internal/modules/esm/load.js b/lib/internal/modules/esm/load.js index 1998ed1dab67fb..d064296d11c463 100644 --- a/lib/internal/modules/esm/load.js +++ b/lib/internal/modules/esm/load.js @@ -70,25 +70,30 @@ async function getSource(url, context) { return { __proto__: null, responseURL, source }; } +/** + * @param {URL} url URL to the module + * @param {ESModuleContext} context used to decorate error messages + * @returns {{ responseURL: string, source: string | BufferView }} + */ function getSourceSync(url, context) { - const parsed = new URL(url); - const responseURL = url; + const { protocol, href } = url; + const responseURL = href; let source; - if (parsed.protocol === 'file:') { - source = readFileSync(parsed); - } else if (parsed.protocol === 'data:') { - const match = RegExpPrototypeExec(DATA_URL_PATTERN, parsed.pathname); + if (protocol === 'file:') { + source = readFileSync(url); + } else if (protocol === 'data:') { + const match = RegExpPrototypeExec(DATA_URL_PATTERN, url.pathname); if (!match) { - throw new ERR_INVALID_URL(url); + throw new ERR_INVALID_URL(responseURL); } const { 1: base64, 2: body } = match; source = BufferFrom(decodeURIComponent(body), base64 ? 'base64' : 'utf8'); } else { const supportedSchemes = ['file', 'data']; - throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(parsed, supportedSchemes); + throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(url, supportedSchemes); } if (policy?.manifest) { - policy.manifest.assertIntegrity(parsed, source); + policy.manifest.assertIntegrity(url, source); } return { __proto__: null, responseURL, source }; } @@ -159,14 +164,18 @@ function defaultLoadSync(url, context = kEmptyObject) { source, } = context; - format ??= defaultGetFormat(new URL(url), context); + const urlInstance = new URL(url); + + throwIfUnsupportedURLScheme(urlInstance, false); + + format ??= defaultGetFormat(urlInstance, context); validateAssertions(url, format, importAssertions); if (format === 'builtin') { source = null; } else if (source == null) { - ({ responseURL, source } = getSourceSync(url, context)); + ({ responseURL, source } = getSourceSync(urlInstance, context)); } return {