Debian Codegraph @

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

raw ◀ ▶
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 // @ts-ignore
137 id: Parameters<ImportMeta["resolve"]>[0],
•138 // @ts-ignore
139 options: Parameters<ImportMeta["resolve"]>[1],
140 ): Promise<Result<string>> {
141 try {
142 return { error: null, value: await importMetaResolve(id, options) };
143 } catch (error) {
144 return { error, value: null };
145 }
146 }
147
148 function resolveStandardizedNameForRequire(
149 type: "plugin" | "preset",
150 name: string,
151 dirname: string,
152 ) {
153 const it = resolveAlternativesHelper(type, name);
154 let res = it.next();
155 while (!res.done) {
156 res = it.next(tryRequireResolve(res.value, { paths: [dirname] }));
157 }
•158 while (!res.done) {
159 res = it.next(tryRequireResolve(res.value, { paths: ['/usr/share/nodejs'] }));
160 }
161 return res.value;
162 }
163 async function resolveStandardizedNameForImport(
164 type: "plugin" | "preset",
165 name: string,
166 dirname: string,
167 ) {
168 const parentUrl = pathToFileURL(
169 path.join(dirname, "./babel-virtual-resolve-base.js"),
170 ).href;
171
172 const it = resolveAlternativesHelper(type, name);
173 let res = it.next();
174 while (!res.done) {
175 res = it.next(await tryImportMetaResolve(res.value, parentUrl));
176 }
177 return fileURLToPath(res.value);
178 }
179
180 const resolveStandardizedName = gensync<
181 [type: "plugin" | "preset", name: string, dirname?: string],
182 string
183 >({
184 sync(type, name, dirname = process.cwd()) {
185 return resolveStandardizedNameForRequire(type, name, dirname);
186 },
187 async async(type, name, dirname = process.cwd()) {
188 if (!supportsESM) {
189 return resolveStandardizedNameForRequire(type, name, dirname);
190 }
191
192 try {
193 return await resolveStandardizedNameForImport(type, name, dirname);
194 } catch (e) {
195 try {
196 return resolveStandardizedNameForRequire(type, name, dirname);
197 } catch (e2) {
198 if (e.type === "MODULE_NOT_FOUND") throw e;
199 if (e2.type === "MODULE_NOT_FOUND") throw e2;
200 throw e;
201 }
202 }
203 },
204 });
205
206 if (!process.env.BABEL_8_BREAKING) {
207 // eslint-disable-next-line no-var
208 var LOADING_MODULES = new Set();
209 }
210 function* requireModule(type: string, name: string): Handler<unknown> {
211 if (!process.env.BABEL_8_BREAKING) {
212 if (!(yield* isAsync()) && LOADING_MODULES.has(name)) {
213 throw new Error(
214 `Reentrant ${type} detected trying to load "${name}". This module is not ignored ` +
215 "and is trying to load itself while compiling itself, leading to a dependency cycle. " +
216 'We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.',
217 );
218 }
219 }
220
221 try {
222 if (!process.env.BABEL_8_BREAKING) {
223 LOADING_MODULES.add(name);
224 }
225 return yield* loadCjsOrMjsDefault(
226 name,
227 `You appear to be using a native ECMAScript module ${type}, ` +
228 "which is only supported when running Babel asynchronously.",
229 // For backward compatibility, we need to support malformed presets
230 // defined as separate named exports rather than a single default
231 // export.
232 // See packages/babel-core/test/fixtures/option-manager/presets/es2015_named.js
233 true,
234 );
235 } catch (err) {
236 err.message = `[BABEL]: ${err.message} (While processing: ${name})`;
237 throw err;
238 } finally {
239 if (!process.env.BABEL_8_BREAKING) {
240 LOADING_MODULES.delete(name);
241 }
242 }
243 }