node/lib/internal/modules/esm/initialize_import_meta.js
Bradley Farias ceadb473e6 esm: support https remotely and http locally under flag
Co-authored-by: Jacob Smith <3012099+JakobJingleheimer@users.noreply.github.com>
Co-authored-by: James M Snell <jasnell@gmail.com>
Co-authored-by: Jordan Harband <ljharb@gmail.com>
Co-authored-by: James Sumners <james@sumners.email>
PR-URL: https://github.com/nodejs/node/pull/36328
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2022-02-09 19:47:12 -08:00

50 lines
1.3 KiB
JavaScript

'use strict';
const { getOptionValue } = require('internal/options');
const experimentalImportMetaResolve =
getOptionValue('--experimental-import-meta-resolve');
const { fetchModule } = require('internal/modules/esm/fetch_module');
const { URL } = require('internal/url');
const {
PromisePrototypeThen,
PromiseReject,
StringPrototypeStartsWith,
} = primordials;
const asyncESM = require('internal/process/esm_loader');
function createImportMetaResolve(defaultParentUrl) {
return async function resolve(specifier, parentUrl = defaultParentUrl) {
return PromisePrototypeThen(
asyncESM.esmLoader.resolve(specifier, parentUrl),
({ url }) => url,
(error) => (
error.code === 'ERR_UNSUPPORTED_DIR_IMPORT' ?
error.url : PromiseReject(error))
);
};
}
function initializeImportMeta(meta, context) {
let url = context.url;
// Alphabetical
if (experimentalImportMetaResolve) {
meta.resolve = createImportMetaResolve(url);
}
if (
StringPrototypeStartsWith(url, 'http:') ||
StringPrototypeStartsWith(url, 'https:')
) {
// The request & response have already settled, so they are in fetchModule's
// cache, in which case, fetchModule returns immediately and synchronously
url = fetchModule(new URL(url), context).resolvedHREF;
}
meta.url = url;
}
module.exports = {
initializeImportMeta
};