Debian Codegraph @

packages/babel-core/src/config/files/plugins.ts

raw ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 /**
2 * This file handles all logic for converting string-based configuration references into loaded objects.
3 */
4
5 import buildDebug from "debug";
6 import path from "path";
7 import gensync, { type Handler } from "gensync";
8 import { isAsync } from "../../gensync-utils/async";
9 import loadCjsOrMjsDefault, { supportsESM } from "./module-types";
10 import { fileURLToPath, pathToFileURL } from "url";
11
12 import importMetaResolve from "./import-meta-resolve";
13
14 import { createRequire } from "module";
15 const require = createRequire(import.meta.url);
16
17 const debug = buildDebug("babel:config:loading:files:plugins");
18
19 const EXACT_RE = /^module:/;
20 const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/;
21 const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/;
22 const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/;
23 const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/;
24 const OTHER_PLUGIN_ORG_RE =
25 /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/;
26 const OTHER_PRESET_ORG_RE =
27 /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/;
28 const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/;
29
30 export function* resolvePlugin(name: string, dirname: string): Handler<string> {
31 // eslint-disable-next-line @typescript-eslint/no-use-before-define
32 return yield* resolveStandardizedName("plugin", name, dirname);
33 }
34
35 export function* resolvePreset(name: string, dirname: string): Handler<string> {
36 // eslint-disable-next-line @typescript-eslint/no-use-before-define
37 return yield* resolveStandardizedName("preset", name, dirname);
38 }
39
40 export function* loadPlugin(
41 name: string,
42 dirname: string,
43 ): Handler<{ filepath: string; value: unknown }> {
44 const filepath = yield* resolvePlugin(name, dirname);
45
46 const value = yield* requireModule("plugin", filepath);
47 debug("Loaded plugin %o from %o.", name, dirname);
48
49 return { filepath, value };
50 }
51
52 export function* loadPreset(
53 name: string,
54 dirname: string,
55 ): Handler<{ filepath: string; value: unknown }> {
56 const filepath = yield* resolvePreset(name, dirname);
57
58 const value = yield* requireModule("preset", filepath);
59
60 debug("Loaded preset %o from %o.", name, dirname);
61
62 return { filepath, value };
63 }
64
65 function standardizeName(type: "plugin" | "preset", name: string) {
66 // Let absolute and relative paths through.
67 if (path.isAbsolute(name)) return name;
68
69 const isPreset = type === "preset";
70
71 return (
72 name
73 // foo -> babel-preset-foo
74 .replace(
75 isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE,
76 `babel-${type}-`,
77 )
78 // @babel/es2015 -> @babel/preset-es2015
79 .replace(
80 isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE,
81 `$1${type}-`,
82 )
83 // @foo/mypreset -> @foo/babel-preset-mypreset
84 .replace(
85 isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE,
86 `$1babel-${type}-`,
87 )
88 // @foo -> @foo/babel-preset
89 .replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`)
90 // module:mypreset -> mypreset
91 .replace(EXACT_RE, "")
92 );
93 }
94
95 type Result<T> = { error: Error; value: null } | { error: null; value: T };
96
97 function* resolveAlternativesHelper(
98 type: "plugin" | "preset",
99 name: string,
100 ): Iterator<string, string, Result<string>> {
101 const standardizedName = standardizeName(type, name);
102 const { error, value } = yield standardizedName;
103 if (!error) return value;
104
105 // @ts-expect-error code may not index error
106 if (error.code !== "MODULE_NOT_FOUND") throw error;
107
108 if (standardizedName !== name && !(yield name).error) {
109 error.message += `\n- If you want to resolve "${name}", use "module:${name}"`;
110 }
111
112 if (!(yield standardizeName(type, "@babel/" + name)).error) {
113 error.message += `\n- Did you mean "@babel/${name}"?`;
114 }
115
116 const oppositeType = type === "preset" ? "plugin" : "preset";
117 if (!(yield standardizeName(oppositeType, name)).error) {
118 error.message += `\n- Did you accidentally pass a ${oppositeType} as a ${type}?`;
119 }
120
121 throw error;
122 }
123
124 function tryRequireResolve(
125 id: Parameters<RequireResolve>[0],
126 { paths: [dirname] }: Parameters<RequireResolve>[1],
127 ): Result<string> {
128 try {
129 return { error: null, value: require.resolve(id, { paths: [dirname] }) };
130 } catch (error) {
131 return { error, value: null };
132 }
133 }
134
135 async function tryImportMetaResolve(
136 id: Parameters<ImportMeta["resolve"]>[0],
137 options: Parameters<ImportMeta["resolve"]>[1],
138 ): Promise<Result<string>> {
139 try {
140 return { error: null, value: await importMetaResolve(id, options) };
141 } catch (error) {
142 return { error, value: null };
143 }
144 }
145
146 function resolveStandardizedNameForRequire(
147 type: "plugin" | "preset",
148 name: string,
149 dirname: string,
150 ) {
151 const it = resolveAlternativesHelper(type, name);
152 let res = it.next();
153 while (!res.done) {
154 res = it.next(tryRequireResolve(res.value, { paths: [dirname] }));
155 }
156 return res.value;
157 }
158 async function resolveStandardizedNameForImport(
159 type: "plugin" | "preset",
160 name: string,
161 dirname: string,
162 ) {
163 const parentUrl = pathToFileURL(
164 path.join(dirname, "./babel-virtual-resolve-base.js"),
165 ).href;
166
167 const it = resolveAlternativesHelper(type, name);
168 let res = it.next();
169 while (!res.done) {
170 res = it.next(await tryImportMetaResolve(res.value, parentUrl));
171 }
172 return fileURLToPath(res.value);
173 }
174
175 const resolveStandardizedName = gensync<
176 [type: "plugin" | "preset", name: string, dirname?: string],
177 string
178 >({
179 sync(type, name, dirname = process.cwd()) {
180 return resolveStandardizedNameForRequire(type, name, dirname);
181 },
182 async async(type, name, dirname = process.cwd()) {
183 if (!supportsESM) {
184 return resolveStandardizedNameForRequire(type, name, dirname);
185 }
186
187 try {
188 return await resolveStandardizedNameForImport(type, name, dirname);
189 } catch (e) {
190 try {
191 return resolveStandardizedNameForRequire(type, name, dirname);
192 } catch (e2) {
193 if (e.type === "MODULE_NOT_FOUND") throw e;
194 if (e2.type === "MODULE_NOT_FOUND") throw e2;
195 throw e;
196 }
197 }
198 },
199 });
200
201 if (!process.env.BABEL_8_BREAKING) {
202 // eslint-disable-next-line no-var
203 var LOADING_MODULES = new Set();
204 }
205 function* requireModule(type: string, name: string): Handler<unknown> {
206 if (!process.env.BABEL_8_BREAKING) {
207 if (!(yield* isAsync()) && LOADING_MODULES.has(name)) {
208 throw new Error(
209 `Reentrant ${type} detected trying to load "${name}". This module is not ignored ` +
210 "and is trying to load itself while compiling itself, leading to a dependency cycle. " +
211 'We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.',
212 );
213 }
214 }
215
216 try {
217 if (!process.env.BABEL_8_BREAKING) {
218 LOADING_MODULES.add(name);
219 }
220 return yield* loadCjsOrMjsDefault(
221 name,
222 `You appear to be using a native ECMAScript module ${type}, ` +
223 "which is only supported when running Babel asynchronously.",
224 // For backward compatibility, we need to support malformed presets
225 // defined as separate named exports rather than a single default
226 // export.
227 // See packages/babel-core/test/fixtures/option-manager/presets/es2015_named.js
228 true,
229 );
230 } catch (err) {
231 err.message = `[BABEL]: ${err.message} (While processing: ${name})`;
232 throw err;
233 } finally {
234 if (!process.env.BABEL_8_BREAKING) {
235 LOADING_MODULES.delete(name);
236 }
237 }
238 }