Debian Codegraph @

packages/babel-core/src/config/files/import-meta-resolve.ts

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import { createRequire } from "module";
2 import { resolve as polyfill } from "../../vendor/import-meta-resolve";
3
4 const require = createRequire(import.meta.url);
5
6 let import_;
7 try {
8 // Node < 13.3 doesn't support import() syntax.
9 import_ = require("./import.cjs");
10 } catch {}
11
12 // import.meta.resolve is only available in ESM, but this file is compiled to CJS.
13 // We can extract it using dynamic import.
14 const importMetaResolveP: Promise<ImportMeta["resolve"]> =
15 import_ &&
16 // Due to a Node.js/V8 bug (https://github.com/nodejs/node/issues/35889), we cannot
17 // use always dynamic import because it segfaults when running in a Node.js `vm` context,
18 // which is used by the default Jest environment and by webpack-cli.
19 //
20 // However, import.meta.resolve is experimental and only enabled when Node.js is run
21 // with the `--experimental-import-meta-resolve` flag: we can avoid calling import()
22 // when that flag is not enabled, so that the default behavior never segfaults.
23 //
24 // Hopefully, before Node.js unflags import.meta.resolve, either:
25 // - we will move to ESM, so that we have direct access to import.meta.resolve, or
26 // - the V8 bug will be fixed so that we can safely use dynamic import by default.
27 //
28 // I (@nicolo-ribaudo) am really anoyed by this bug, because there is no known
29 // work-around other than "don't use dynamic import if you are running in a `vm` context",
30 // but there is no reliable way to detect it (you cannot try/catch segfaults).
31 //
32 // This is the only place where we *need* to use dynamic import because we need to access
33 // an ES module. All the other places will first try using require() and *then*, if
34 // it throws because it's a module, will fallback to import().
35 process.execArgv.includes("--experimental-import-meta-resolve")
36 ? import_("data:text/javascript,export default import.meta.resolve").then(
37 (m: { default: ImportMeta["resolve"] | undefined }) =>
38 m.default || polyfill,
39 () => polyfill,
40 )
41 : Promise.resolve(polyfill);
42
43 export default async function resolve(
44 specifier: Parameters<ImportMeta["resolve"]>[0],
45 parent?: Parameters<ImportMeta["resolve"]>[1],
46 ): ReturnType<ImportMeta["resolve"]> {
47 return (await importMetaResolveP)(specifier, parent);
48 }