forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathesm_loader.js
More file actions
86 lines (80 loc) · 2.42 KB
/
esm_loader.js
File metadata and controls
86 lines (80 loc) · 2.42 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
'use strict';
const {
ArrayPrototypePush,
PromisePrototypeThen,
ReflectApply,
SafeMap,
} = primordials;
const assert = require('internal/assert');
const { createModuleLoader } = require('internal/modules/esm/loader');
const { getOptionValue } = require('internal/options');
const {
hasUncaughtExceptionCaptureCallback,
} = require('internal/process/execution');
const { pathToFileURL } = require('internal/url');
const { kEmptyObject, createDeferredPromise } = require('internal/util');
let esmLoader;
let init = false;
module.exports = {
get esmLoader() {
return esmLoader ??= { __proto__: null, cjsCache: new SafeMap(), import() {
const { promise, resolve, reject } = createDeferredPromise();
ArrayPrototypePush(this.importRequests, { arguments: arguments, resolve, reject });
return promise;
}, importRequests: [] };
},
initIfNeeded() {
// TODO: we could try to avoid loading ESM loader on CJS-only codebase
return module.exports.init();
},
init(loader = undefined) {
assert(!init);
init = true;
loader ??= createModuleLoader(true);
if (esmLoader != null) {
for (const { 0: key, 1: value } of esmLoader.cjsCache) {
// Getting back the values from the mocked loader.
loader.cjsCache.set(key, value);
}
for (let i = 0; i < esmLoader.importRequests.length; i++) {
PromisePrototypeThen(
ReflectApply(loader.import, loader, esmLoader.importRequests[i].arguments),
esmLoader.importRequests[i].resolve,
esmLoader.importRequests[i].reject,
);
}
}
esmLoader = loader;
},
async loadESM(callback) {
const { esmLoader } = module.exports;
try {
const userImports = getOptionValue('--import');
if (userImports.length > 0) {
let cwd;
try {
// `process.cwd()` can fail if the parent directory is deleted while the process runs.
cwd = process.cwd() + '/';
} catch {
cwd = '/';
}
const parentURL = pathToFileURL(cwd).href;
await esmLoader.import(
userImports,
parentURL,
kEmptyObject,
);
}
await callback(esmLoader);
} catch (err) {
if (hasUncaughtExceptionCaptureCallback()) {
process._fatalException(err);
return;
}
internalBinding('errors').triggerUncaughtException(
err,
true, /* fromPromise */
);
}
},
};