Skip to content

Commit

Permalink
module: reduce url invocations in esm/load.js
Browse files Browse the repository at this point in the history
PR-URL: #48337
Refs: nodejs/performance#92
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Jacob Smith <jacob@frende.me>
  • Loading branch information
anonrig authored and ruyadorno committed Aug 29, 2023
1 parent 0651358 commit bf1525c
Showing 1 changed file with 18 additions and 13 deletions.
31 changes: 18 additions & 13 deletions lib/internal/modules/esm/load.js
Expand Up @@ -29,35 +29,40 @@ const {

const DATA_URL_PATTERN = /^[^/]+\/[^,;]+(?:[^,]*?)(;base64)?,([\s\S]*)$/;

/**
* @param {URL} url URL to the module
* @param {ESModuleContext} context used to decorate error messages
* @returns {{ responseURL: string, source: string | BufferView }}
*/
async function getSource(url, context) {
const parsed = new URL(url);
let responseURL = url;
const { protocol, href } = url;
let responseURL = href;
let source;
if (parsed.protocol === 'file:') {
source = await readFileAsync(parsed);
} else if (parsed.protocol === 'data:') {
const match = RegExpPrototypeExec(DATA_URL_PATTERN, parsed.pathname);
if (protocol === 'file:') {
source = await readFileAsync(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 if (experimentalNetworkImports && (
parsed.protocol === 'https:' ||
parsed.protocol === 'http:'
protocol === 'https:' ||
protocol === 'http:'
)) {
const res = await fetchModule(parsed, context);
const res = await fetchModule(url, context);
source = await res.body;
responseURL = res.resolvedHREF;
} else {
const supportedSchemes = ['file', 'data'];
if (experimentalNetworkImports) {
ArrayPrototypePush(supportedSchemes, 'http', 'https');
}
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(href, source);
}
return { __proto__: null, responseURL, source };
}
Expand Down Expand Up @@ -91,7 +96,7 @@ async function defaultLoad(url, context) {
) {
source = null;
} else if (source == null) {
({ responseURL, source } = await getSource(url, context));
({ responseURL, source } = await getSource(urlInstance, context));
}

return {
Expand Down

0 comments on commit bf1525c

Please sign in to comment.