| 1 | import semver, { type SemVer } from "semver"; |
| 2 | import { logPlugin } from "./debug"; |
| 3 | import getOptionSpecificExcludesFor from "./get-option-specific-excludes"; |
| 4 | import { |
| 5 | addProposalSyntaxPlugins, |
| 6 | removeUnnecessaryItems, |
| 7 | removeUnsupportedItems, |
| 8 | } from "./filter-items"; |
| 9 | import moduleTransformations from "./module-transformations"; |
| 10 | import normalizeOptions from "./normalize-options"; |
| 11 | import { |
| 12 | pluginSyntaxMap, |
| 13 | proposalPlugins, |
| 14 | proposalSyntaxPlugins, |
| 15 | } from "./shipped-proposals"; |
| 16 | import { |
| 17 | plugins as pluginsList, |
| 18 | pluginsBugfixes as pluginsBugfixesList, |
| 19 | overlappingPlugins, |
| 20 | } from "./plugins-compat-data"; |
| 21 | |
| 22 | import removeRegeneratorEntryPlugin from "./polyfills/regenerator"; |
| 23 | import legacyBabelPolyfillPlugin from "./polyfills/babel-polyfill"; |
| 24 | |
| 25 | import type { CallerMetadata } from "@babel/core"; |
| 26 | |
| 27 | import _pluginCoreJS2 from "babel-plugin-polyfill-corejs2"; |
| 28 | import _pluginCoreJS3 from "babel-plugin-polyfill-corejs3"; |
| 29 | import _pluginRegenerator from "babel-plugin-polyfill-regenerator"; |
| 30 | const pluginCoreJS2 = _pluginCoreJS2.default || _pluginCoreJS2; |
| 31 | const pluginCoreJS3 = _pluginCoreJS3.default || _pluginCoreJS3; |
| 32 | const pluginRegenerator = _pluginRegenerator.default || _pluginRegenerator; |
| 33 | |
| 34 | import getTargets, { |
| 35 | prettifyTargets, |
| 36 | filterItems, |
| 37 | isRequired, |
| 38 | } from "@babel/helper-compilation-targets"; |
| 39 | import type { Targets, InputTargets } from "@babel/helper-compilation-targets"; |
| 40 | import availablePlugins from "./available-plugins"; |
| 41 | import { declarePreset } from "@babel/helper-plugin-utils"; |
| 42 | |
| 43 | type ModuleTransformationsType = |
| 44 | typeof import("./module-transformations").default; |
| 45 | import type { BuiltInsOption, ModuleOption, Options } from "./types"; |
| 46 | |
| 47 | // TODO: Remove in Babel 8 |
| 48 | export function isPluginRequired(targets: Targets, support: Targets) { |
| 49 | return isRequired("fake-name", targets, { |
| 50 | compatData: { "fake-name": support }, |
| 51 | }); |
| 52 | } |
| 53 | |
| 54 | function filterStageFromList( |
| 55 | list: { [feature: string]: Targets }, |
| 56 | stageList: Set<string>, |
| 57 | ) { |
| 58 | return Object.keys(list).reduce((result, item) => { |
| 59 | if (!stageList.has(item)) { |
| 60 | // @ts-expect-error todo: refine result types |
| 61 | result[item] = list[item]; |
| 62 | } |
| 63 | |
| 64 | return result; |
| 65 | }, {}); |
| 66 | } |
| 67 | |
| 68 | const pluginLists = { |
| 69 | withProposals: { |
| 70 | withoutBugfixes: pluginsList, |
| 71 | withBugfixes: Object.assign({}, pluginsList, pluginsBugfixesList), |
| 72 | }, |
| 73 | withoutProposals: { |
| 74 | withoutBugfixes: filterStageFromList(pluginsList, proposalPlugins), |
| 75 | withBugfixes: filterStageFromList( |
| 76 | Object.assign({}, pluginsList, pluginsBugfixesList), |
| 77 | proposalPlugins, |
| 78 | ), |
| 79 | }, |
| 80 | }; |
| 81 | |
| 82 | function getPluginList(proposals: boolean, bugfixes: boolean) { |
| 83 | if (proposals) { |
| 84 | if (bugfixes) return pluginLists.withProposals.withBugfixes; |
| 85 | else return pluginLists.withProposals.withoutBugfixes; |
| 86 | } else { |
| 87 | if (bugfixes) return pluginLists.withoutProposals.withBugfixes; |
| 88 | else return pluginLists.withoutProposals.withoutBugfixes; |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | const getPlugin = (pluginName: string) => { |
| 93 | const plugin = |
| 94 | // @ts-expect-error plugin name is constructed from available plugin list |
| 95 | availablePlugins[pluginName](); |
| 96 | |
| 97 | if (!plugin) { |
| 98 | throw new Error( |
| 99 | `Could not find plugin "${pluginName}". Ensure there is an entry in ./available-plugins.js for it.`, |
| 100 | ); |
| 101 | } |
| 102 | |
| 103 | return plugin; |
| 104 | }; |
| 105 | |
| 106 | export const transformIncludesAndExcludes = (opts: Array<string>): any => { |
| 107 | return opts.reduce( |
| 108 | (result, opt) => { |
| 109 | const target = opt.match(/^(es|es6|es7|esnext|web)\./) |
| 110 | ? "builtIns" |
| 111 | : "plugins"; |
| 112 | result[target].add(opt); |
| 113 | return result; |
| 114 | }, |
| 115 | { |
| 116 | all: opts, |
| 117 | plugins: new Set(), |
| 118 | builtIns: new Set(), |
| 119 | }, |
| 120 | ); |
| 121 | }; |
| 122 | |
| 123 | export const getModulesPluginNames = ({ |
| 124 | modules, |
| 125 | transformations, |
| 126 | shouldTransformESM, |
| 127 | shouldTransformDynamicImport, |
| 128 | shouldTransformExportNamespaceFrom, |
| 129 | shouldParseTopLevelAwait, |
| 130 | }: { |
| 131 | modules: ModuleOption; |
| 132 | transformations: ModuleTransformationsType; |
| 133 | shouldTransformESM: boolean; |
| 134 | shouldTransformDynamicImport: boolean; |
| 135 | shouldTransformExportNamespaceFrom: boolean; |
| 136 | shouldParseTopLevelAwait: boolean; |
| 137 | }) => { |
| 138 | const modulesPluginNames = []; |
| 139 | if (modules !== false && transformations[modules]) { |
| 140 | if (shouldTransformESM) { |
| 141 | modulesPluginNames.push(transformations[modules]); |
| 142 | } |
| 143 | |
| 144 | if ( |
| 145 | shouldTransformDynamicImport && |
| 146 | shouldTransformESM && |
| 147 | modules !== "umd" |
| 148 | ) { |
| 149 | modulesPluginNames.push("transform-dynamic-import"); |
| 150 | } else { |
| 151 | if (shouldTransformDynamicImport) { |
| 152 | console.warn( |
| 153 | "Dynamic import can only be supported when transforming ES modules" + |
| 154 | " to AMD, CommonJS or SystemJS. Only the parser plugin will be enabled.", |
| 155 | ); |
| 156 | } |
| 157 | modulesPluginNames.push("syntax-dynamic-import"); |
| 158 | } |
| 159 | } else { |
| 160 | modulesPluginNames.push("syntax-dynamic-import"); |
| 161 | } |
| 162 | |
| 163 | if (shouldTransformExportNamespaceFrom) { |
| 164 | modulesPluginNames.push("transform-export-namespace-from"); |
| 165 | } else { |
| 166 | modulesPluginNames.push("syntax-export-namespace-from"); |
| 167 | } |
| 168 | |
| 169 | if (shouldParseTopLevelAwait) { |
| 170 | modulesPluginNames.push("syntax-top-level-await"); |
| 171 | } |
| 172 | |
| 173 | return modulesPluginNames; |
| 174 | }; |
| 175 | |
| 176 | export const getPolyfillPlugins = ({ |
| 177 | useBuiltIns, |
| 178 | corejs, |
| 179 | polyfillTargets, |
| 180 | include, |
| 181 | exclude, |
| 182 | proposals, |
| 183 | shippedProposals, |
| 184 | regenerator, |
| 185 | debug, |
| 186 | }: { |
| 187 | useBuiltIns: BuiltInsOption; |
| 188 | corejs: SemVer | null | false; |
| 189 | polyfillTargets: Targets; |
| 190 | include: Set<string>; |
| 191 | exclude: Set<string>; |
| 192 | proposals: boolean; |
| 193 | shippedProposals: boolean; |
| 194 | regenerator: boolean; |
| 195 | debug: boolean; |
| 196 | }) => { |
| 197 | const polyfillPlugins = []; |
| 198 | if (useBuiltIns === "usage" || useBuiltIns === "entry") { |
| 199 | const pluginOptions = { |
| 200 | method: `${useBuiltIns}-global`, |
| 201 | version: corejs ? corejs.toString() : undefined, |
| 202 | targets: polyfillTargets, |
| 203 | include, |
| 204 | exclude, |
| 205 | proposals, |
| 206 | shippedProposals, |
| 207 | debug, |
| 208 | }; |
| 209 | |
| 210 | if (corejs) { |
| 211 | if (useBuiltIns === "usage") { |
| 212 | if (corejs.major === 2) { |
| 213 | polyfillPlugins.push( |
| 214 | [pluginCoreJS2, pluginOptions], |
| 215 | [legacyBabelPolyfillPlugin, { usage: true }], |
| 216 | ); |
| 217 | } else { |
| 218 | polyfillPlugins.push( |
| 219 | [pluginCoreJS3, pluginOptions], |
| 220 | [legacyBabelPolyfillPlugin, { usage: true, deprecated: true }], |
| 221 | ); |
| 222 | } |
| 223 | if (regenerator) { |
| 224 | polyfillPlugins.push([ |
| 225 | pluginRegenerator, |
| 226 | { method: "usage-global", debug }, |
| 227 | ]); |
| 228 | } |
| 229 | } else { |
| 230 | if (corejs.major === 2) { |
| 231 | polyfillPlugins.push( |
| 232 | [legacyBabelPolyfillPlugin, { regenerator }], |
| 233 | [pluginCoreJS2, pluginOptions], |
| 234 | ); |
| 235 | } else { |
| 236 | polyfillPlugins.push( |
| 237 | [pluginCoreJS3, pluginOptions], |
| 238 | [legacyBabelPolyfillPlugin, { deprecated: true }], |
| 239 | ); |
| 240 | if (!regenerator) { |
| 241 | polyfillPlugins.push([removeRegeneratorEntryPlugin, pluginOptions]); |
| 242 | } |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | return polyfillPlugins; |
| 248 | }; |
| 249 | |
| 250 | function getLocalTargets( |
| 251 | optionsTargets: Options["targets"], |
| 252 | ignoreBrowserslistConfig: boolean, |
| 253 | configPath: string, |
| 254 | browserslistEnv: string, |
| 255 | ) { |
| 256 | if (optionsTargets?.esmodules && optionsTargets.browsers) { |
| 257 | console.warn(` |
| 258 | @babel/preset-env: esmodules and browsers targets have been specified together. |
| 259 | \`browsers\` target, \`${optionsTargets.browsers.toString()}\` will be ignored. |
| 260 | `); |
| 261 | } |
| 262 | |
| 263 | return getTargets(optionsTargets as InputTargets, { |
| 264 | ignoreBrowserslistConfig, |
| 265 | configPath, |
| 266 | browserslistEnv, |
| 267 | }); |
| 268 | } |
| 269 | |
| 270 | function supportsStaticESM(caller: CallerMetadata | undefined) { |
| 271 | // @ts-expect-error supportsStaticESM is not defined in CallerMetadata |
| 272 | return !!caller?.supportsStaticESM; |
| 273 | } |
| 274 | |
| 275 | function supportsDynamicImport(caller: CallerMetadata | undefined) { |
| 276 | // @ts-expect-error supportsDynamicImport is not defined in CallerMetadata |
| 277 | return !!caller?.supportsDynamicImport; |
| 278 | } |
| 279 | |
| 280 | function supportsExportNamespaceFrom(caller: CallerMetadata | undefined) { |
| 281 | // @ts-expect-error supportsExportNamespaceFrom is not defined in CallerMetadata |
| 282 | return !!caller?.supportsExportNamespaceFrom; |
| 283 | } |
| 284 | |
| 285 | function supportsTopLevelAwait(caller: CallerMetadata | undefined) { |
| 286 | // @ts-expect-error supportsTopLevelAwait is not defined in CallerMetadata |
| 287 | return !!caller?.supportsTopLevelAwait; |
| 288 | } |
| 289 | |
| 290 | export default declarePreset((api, opts: Options) => { |
| 291 | api.assertVersion(7); |
| 292 | |
| 293 | const babelTargets = api.targets(); |
| 294 | |
| 295 | const { |
| 296 | bugfixes, |
| 297 | configPath, |
| 298 | debug, |
| 299 | exclude: optionsExclude, |
| 300 | forceAllTransforms, |
| 301 | ignoreBrowserslistConfig, |
| 302 | include: optionsInclude, |
| 303 | loose, |
| 304 | modules, |
| 305 | shippedProposals, |
| 306 | spec, |
| 307 | targets: optionsTargets, |
| 308 | useBuiltIns, |
| 309 | corejs: { version: corejs, proposals }, |
| 310 | browserslistEnv, |
| 311 | } = normalizeOptions(opts); |
| 312 | |
| 313 | let targets = babelTargets; |
| 314 | |
| 315 | if ( |
| 316 | // @babel/core < 7.13.0 doesn't load targets (api.targets() always |
| 317 | // returns {} thanks to @babel/helper-plugin-utils), so we always want |
| 318 | // to fallback to the old targets behavior in this case. |
| 319 | semver.lt(api.version, "7.13.0") || |
| 320 | // If any browserslist-related option is specified, fallback to the old |
| 321 | // behavior of not using the targets specified in the top-level options. |
| 322 | opts.targets || |
| 323 | opts.configPath || |
| 324 | opts.browserslistEnv || |
| 325 | opts.ignoreBrowserslistConfig |
| 326 | ) { |
| 327 | if (!process.env.BABEL_8_BREAKING) { |
| 328 | // eslint-disable-next-line no-var |
| 329 | var hasUglifyTarget = false; |
| 330 | |
| 331 | if (optionsTargets?.uglify) { |
| 332 | hasUglifyTarget = true; |
| 333 | delete optionsTargets.uglify; |
| 334 | |
| 335 | console.warn(` |
| 336 | The uglify target has been deprecated. Set the top level |
| 337 | option \`forceAllTransforms: true\` instead. |
| 338 | `); |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | targets = getLocalTargets( |
| 343 | optionsTargets, |
| 344 | ignoreBrowserslistConfig, |
| 345 | configPath, |
| 346 | browserslistEnv, |
| 347 | ); |
| 348 | } |
| 349 | |
| 350 | const transformTargets = ( |
| 351 | process.env.BABEL_8_BREAKING |
| 352 | ? forceAllTransforms |
| 353 | : forceAllTransforms || hasUglifyTarget |
| 354 | ) |
| 355 | ? ({} as Targets) |
| 356 | : targets; |
| 357 | |
| 358 | const include = transformIncludesAndExcludes(optionsInclude); |
| 359 | const exclude = transformIncludesAndExcludes(optionsExclude); |
| 360 | |
| 361 | const compatData = getPluginList(shippedProposals, bugfixes); |
| 362 | const shouldSkipExportNamespaceFrom = |
| 363 | (modules === "auto" && api.caller?.(supportsExportNamespaceFrom)) || |
| 364 | (modules === false && |
| 365 | !isRequired("transform-export-namespace-from", transformTargets, { |
| 366 | compatData, |
| 367 | includes: include.plugins, |
| 368 | excludes: exclude.plugins, |
| 369 | })); |
| 370 | const modulesPluginNames = getModulesPluginNames({ |
| 371 | modules, |
| 372 | transformations: moduleTransformations, |
| 373 | // TODO: Remove the 'api.caller' check eventually. Just here to prevent |
| 374 | // unnecessary breakage in the short term for users on older betas/RCs. |
| 375 | shouldTransformESM: modules !== "auto" || !api.caller?.(supportsStaticESM), |
| 376 | shouldTransformDynamicImport: |
| 377 | modules !== "auto" || !api.caller?.(supportsDynamicImport), |
| 378 | shouldTransformExportNamespaceFrom: !shouldSkipExportNamespaceFrom, |
| 379 | shouldParseTopLevelAwait: |
| 380 | !api.caller || (api.caller(supportsTopLevelAwait) as boolean), |
| 381 | }); |
| 382 | |
| 383 | const pluginNames = filterItems( |
| 384 | compatData, |
| 385 | include.plugins, |
| 386 | exclude.plugins, |
| 387 | transformTargets, |
| 388 | modulesPluginNames, |
| 389 | getOptionSpecificExcludesFor({ loose }), |
| 390 | pluginSyntaxMap, |
| 391 | ); |
| 392 | removeUnnecessaryItems(pluginNames, overlappingPlugins); |
| 393 | removeUnsupportedItems(pluginNames, api.version); |
| 394 | if (shippedProposals) { |
| 395 | addProposalSyntaxPlugins(pluginNames, proposalSyntaxPlugins); |
| 396 | } |
| 397 | |
| 398 | const polyfillPlugins = getPolyfillPlugins({ |
| 399 | useBuiltIns, |
| 400 | corejs, |
| 401 | polyfillTargets: targets, |
| 402 | include: include.builtIns, |
| 403 | exclude: exclude.builtIns, |
| 404 | proposals, |
| 405 | shippedProposals, |
| 406 | regenerator: pluginNames.has("transform-regenerator"), |
| 407 | debug, |
| 408 | }); |
| 409 | |
| 410 | const pluginUseBuiltIns = useBuiltIns !== false; |
| 411 | const plugins = Array.from(pluginNames) |
| 412 | .map(pluginName => { |
| 413 | if ( |
| 414 | pluginName === "transform-class-properties" || |
| 415 | pluginName === "transform-private-methods" || |
| 416 | pluginName === "transform-private-property-in-object" |
| 417 | ) { |
| 418 | return [ |
| 419 | getPlugin(pluginName), |
| 420 | { |
| 421 | loose: loose |
| 422 | ? "#__internal__@babel/preset-env__prefer-true-but-false-is-ok-if-it-prevents-an-error" |
| 423 | : "#__internal__@babel/preset-env__prefer-false-but-true-is-ok-if-it-prevents-an-error", |
| 424 | }, |
| 425 | ]; |
| 426 | } |
| 427 | return [ |
| 428 | getPlugin(pluginName), |
| 429 | { spec, loose, useBuiltIns: pluginUseBuiltIns }, |
| 430 | ]; |
| 431 | }) |
| 432 | .concat(polyfillPlugins); |
| 433 | |
| 434 | if (debug) { |
| 435 | console.log("@babel/preset-env: `DEBUG` option"); |
| 436 | console.log("\nUsing targets:"); |
| 437 | console.log(JSON.stringify(prettifyTargets(targets), null, 2)); |
| 438 | console.log(`\nUsing modules transform: ${modules.toString()}`); |
| 439 | console.log("\nUsing plugins:"); |
| 440 | pluginNames.forEach(pluginName => { |
| 441 | logPlugin(pluginName, targets, compatData); |
| 442 | }); |
| 443 | |
| 444 | if (!useBuiltIns) { |
| 445 | console.log( |
| 446 | "\nUsing polyfills: No polyfills were added, since the `useBuiltIns` option was not set.", |
| 447 | ); |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | return { plugins }; |
| 452 | }); |