forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinitialize_import_meta.js
60 lines (48 loc) · 1.65 KB
/
initialize_import_meta.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
'use strict';
const { getOptionValue } = require('internal/options');
const experimentalImportMetaResolve = getOptionValue('--experimental-import-meta-resolve');
let debug = require('internal/util/debuglog').debuglog('esm', (fn) => {
debug = fn;
});
/**
* Generate a function to be used as import.meta.resolve for a particular module.
* @param {string} defaultParentUrl The default base to use for resolution
* @returns {(specifier: string, parentUrl?: string) => string} Function to assign to import.meta.resolve
*/
function createImportMetaResolve(defaultParentUrl) {
debug('createImportMetaResolve(): %o', { defaultParentUrl });
return function resolve(specifier, parentUrl = defaultParentUrl) {
const moduleLoader = require('internal/process/esm_loader').esmLoader;
let url;
debug('import.meta.resolve(%o) %s', { specifier, parentUrl }, moduleLoader.constructor.name);
try {
({ url } = moduleLoader.resolve(specifier, parentUrl));
} catch (error) {
if (error?.code === 'ERR_UNSUPPORTED_DIR_IMPORT') {
({ url } = error);
} else {
throw error;
}
}
return url;
};
}
/**
* Create the `import.meta` object for a module.
* @param {object} meta
* @param {{url: string}} context
* @returns {{url: string, resolve?: Function}}
*/
function initializeImportMeta(meta, { url }) {
debug('initializeImportMeta for %s', url);
const { isLoaderWorker } = require('internal/modules/esm/utils');
// Alphabetical
if (experimentalImportMetaResolve && !isLoaderWorker()) {
meta.resolve = createImportMetaResolve(url);
}
meta.url = url;
return meta;
}
module.exports = {
initializeImportMeta,
};