Debian Codegraph @

packages/babel-preset-env/src/normalize-options.ts

raw symbols SCIP
1 import semver, { type SemVer } from "semver";
2 import corejs2Polyfills from "@babel/compat-data/corejs2-built-ins";
3 // @ts-expect-error Fixme: TS can not infer types from ../data/core-js-compat.js
4 // but we can't import core-js-compat/data.json because JSON imports do
5 // not work on Node 14
6 import corejs3Polyfills from "../data/core-js-compat";
7 import { plugins as pluginsList } from "./plugins-compat-data";
8 import moduleTransformations from "./module-transformations";
9 import { TopLevelOptions, ModulesOption, UseBuiltInsOption } from "./options";
10 import { OptionValidator } from "@babel/helper-validator-option";
11
12 const corejs2DefaultWebIncludes = [
13 "web.timers",
14 "web.immediate",
15 "web.dom.iterable",
16 ];
17
18 import type {
19 BuiltInsOption,
20 CorejsOption,
21 ModuleOption,
22 Options,
23 PluginListOption,
24 } from "./types";
25
26 declare const PACKAGE_JSON: { name: string; version: string };
27
28 const v = new OptionValidator(PACKAGE_JSON.name);
29
30 const allPluginsList = Object.keys(pluginsList);
31
32 // NOTE: Since module plugins are handled separately compared to other plugins (via the "modules" option) it
33 // should only be possible to exclude and not include module plugins, otherwise it's possible that preset-env
34 // will add a module plugin twice.
35 const modulePlugins = [
36 "transform-dynamic-import",
37 ...Object.keys(moduleTransformations).map(m => moduleTransformations[m]),
38 ];
39
40 const getValidIncludesAndExcludes = (
41 type: "include" | "exclude",
42 corejs: number | false,
43 ) =>
44 Array.from(
45 new Set([
46 ...allPluginsList,
47 ...(type === "exclude" ? modulePlugins : []),
48 ...(corejs
49 ? corejs == 2
50 ? [...Object.keys(corejs2Polyfills), ...corejs2DefaultWebIncludes]
51 : Object.keys(corejs3Polyfills)
52 : []),
53 ]),
54 );
55
56 function flatMap<T, U>(array: Array<T>, fn: (item: T) => Array<U>): Array<U> {
57 return Array.prototype.concat.apply([], array.map(fn));
58 }
59
60 export const normalizePluginName = (plugin: string) =>
61 plugin.replace(/^(@babel\/|babel-)(plugin-)?/, "");
62
63 const expandIncludesAndExcludes = (
64 filterList: PluginListOption = [],
65 type: "include" | "exclude",
66 corejs: number | false,
67 ) => {
68 if (filterList.length === 0) return [];
69
70 const filterableItems = getValidIncludesAndExcludes(type, corejs);
71
72 const invalidFilters: PluginListOption = [];
73 const selectedPlugins = flatMap(filterList, filter => {
74 let re: RegExp;
75 if (typeof filter === "string") {
76 try {
77 re = new RegExp(`^${normalizePluginName(filter)}$`);
78 } catch (e) {
79 invalidFilters.push(filter);
80 return [];
81 }
82 } else {
83 re = filter;
84 }
85 const items = filterableItems.filter(
86 item =>
87 re.test(item) ||
88 // For backwards compatibility, we also support matching against the
89 // proposal- name.
90 // TODO(Babel 8): Remove this.
91 re.test(item.replace(/^transform-/, "proposal-")),
92 );
93 if (items.length === 0) invalidFilters.push(filter);
94 return items;
95 });
96
97 v.invariant(
98 invalidFilters.length === 0,
99 `The plugins/built-ins '${invalidFilters.join(
100 ", ",
101 )}' passed to the '${type}' option are not
102 valid. Please check data/[plugin-features|built-in-features].js in babel-preset-env`,
103 );
104
105 return selectedPlugins;
106 };
107
108 export const checkDuplicateIncludeExcludes = (
109 include: Array<string> = [],
110 exclude: Array<string> = [],
111 ) => {
112 const duplicates = include.filter(opt => exclude.indexOf(opt) >= 0);
113
114 v.invariant(
115 duplicates.length === 0,
116 `The plugins/built-ins '${duplicates.join(
117 ", ",
118 )}' were found in both the "include" and
119 "exclude" options.`,
120 );
121 };
122
123 const normalizeTargets = (
124 targets: string | string[] | Options["targets"],
125 ): Options["targets"] => {
126 // TODO: Allow to use only query or strings as a targets from next breaking change.
127 if (typeof targets === "string" || Array.isArray(targets)) {
128 return { browsers: targets };
129 }
130 return { ...targets };
131 };
132
133 export const validateModulesOption = (
134 modulesOpt: ModuleOption = ModulesOption.auto,
135 ) => {
136 v.invariant(
137 // @ts-expect-error we have provided fallback for undefined keys
138 ModulesOption[modulesOpt.toString()] || modulesOpt === ModulesOption.false,
139 `The 'modules' option must be one of \n` +
140 ` - 'false' to indicate no module processing\n` +
141 ` - a specific module type: 'commonjs', 'amd', 'umd', 'systemjs'` +
142 ` - 'auto' (default) which will automatically select 'false' if the current\n` +
143 ` process is known to support ES module syntax, or "commonjs" otherwise\n`,
144 );
145
146 return modulesOpt;
147 };
148
149 export const validateUseBuiltInsOption = (
150 builtInsOpt: BuiltInsOption = false,
151 ) => {
152 v.invariant(
153 // @ts-expect-error we have provided fallback for undefined keys
154 UseBuiltInsOption[builtInsOpt.toString()] ||
155 builtInsOpt === UseBuiltInsOption.false,
156 `The 'useBuiltIns' option must be either
157 'false' (default) to indicate no polyfill,
158 '"entry"' to indicate replacing the entry polyfill, or
159 '"usage"' to import only used polyfills per file`,
160 );
161
162 return builtInsOpt;
163 };
164
165 export type NormalizedCorejsOption = {
166 proposals: boolean;
167 version: SemVer | null | false;
168 };
169
170 export function normalizeCoreJSOption(
171 corejs: CorejsOption | undefined | null,
172 useBuiltIns: BuiltInsOption,
173 ): NormalizedCorejsOption {
174 let proposals = false;
175 let rawVersion;
176
177 if (useBuiltIns && corejs === undefined) {
178 rawVersion = 2;
179 console.warn(
180 "\nWARNING (@babel/preset-env): We noticed you're using the `useBuiltIns` option without declaring a " +
181 "core-js version. Currently, we assume version 2.x when no version " +
182 "is passed. Since this default version will likely change in future " +
183 "versions of Babel, we recommend explicitly setting the core-js version " +
184 "you are using via the `corejs` option.\n" +
185 "\nYou should also be sure that the version you pass to the `corejs` " +
186 "option matches the version specified in your `package.json`'s " +
187 "`dependencies` section. If it doesn't, you need to run one of the " +
188 "following commands:\n\n" +
189 " npm install --save core-js@2 npm install --save core-js@3\n" +
190 " yarn add core-js@2 yarn add core-js@3\n\n" +
191 "More info about useBuiltIns: https://babeljs.io/docs/en/babel-preset-env#usebuiltins\n" +
192 "More info about core-js: https://babeljs.io/docs/en/babel-preset-env#corejs",
193 );
194 } else if (typeof corejs === "object" && corejs !== null) {
195 rawVersion = corejs.version;
196 proposals = Boolean(corejs.proposals);
197 } else {
198 rawVersion = corejs;
199 }
200
201 const version = rawVersion ? semver.coerce(String(rawVersion)) : false;
202
203 if (!useBuiltIns && version) {
204 console.warn(
205 "\nWARNING (@babel/preset-env): The `corejs` option only has an effect when the `useBuiltIns` option is not `false`\n",
206 );
207 }
208
209 if (useBuiltIns && (!version || version.major < 2 || version.major > 3)) {
210 throw new RangeError(
211 "Invalid Option: The version passed to `corejs` is invalid. Currently, " +
212 "only core-js@2 and core-js@3 are supported.",
213 );
214 }
215
216 return { version, proposals };
217 }
218
219 export default function normalizeOptions(opts: Options) {
220 v.validateTopLevelOptions(opts, TopLevelOptions);
221
222 const useBuiltIns = validateUseBuiltInsOption(opts.useBuiltIns);
223
224 const corejs = normalizeCoreJSOption(opts.corejs, useBuiltIns);
225
226 const include = expandIncludesAndExcludes(
227 opts.include,
228 TopLevelOptions.include,
229 !!corejs.version && corejs.version.major,
230 );
231
232 const exclude = expandIncludesAndExcludes(
233 opts.exclude,
234 TopLevelOptions.exclude,
235 !!corejs.version && corejs.version.major,
236 );
237
238 checkDuplicateIncludeExcludes(include, exclude);
239
240 return {
241 bugfixes: v.validateBooleanOption(
242 TopLevelOptions.bugfixes,
243 opts.bugfixes,
244 process.env.BABEL_8_BREAKING ? true : false,
245 ),
246 configPath: v.validateStringOption(
247 TopLevelOptions.configPath,
248 opts.configPath,
249 process.cwd(),
250 ),
251 corejs,
252 debug: v.validateBooleanOption(TopLevelOptions.debug, opts.debug, false),
253 include,
254 exclude,
255 forceAllTransforms: v.validateBooleanOption(
256 TopLevelOptions.forceAllTransforms,
257 opts.forceAllTransforms,
258 false,
259 ),
260 ignoreBrowserslistConfig: v.validateBooleanOption(
261 TopLevelOptions.ignoreBrowserslistConfig,
262 opts.ignoreBrowserslistConfig,
263 false,
264 ),
265 loose: v.validateBooleanOption<boolean>(TopLevelOptions.loose, opts.loose),
266 modules: validateModulesOption(opts.modules),
267 shippedProposals: v.validateBooleanOption(
268 TopLevelOptions.shippedProposals,
269 opts.shippedProposals,
270 false,
271 ),
272 spec: v.validateBooleanOption(TopLevelOptions.spec, opts.spec, false),
273 targets: normalizeTargets(opts.targets),
274 useBuiltIns: useBuiltIns,
275 browserslistEnv: v.validateStringOption<string>(
276 TopLevelOptions.browserslistEnv,
277 opts.browserslistEnv,
278 ),
279 };
280 }