Skip to content

Commit

Permalink
Polyfill api.targets in helper-plugin-utils
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Nov 27, 2020
1 parent 7f6a7d8 commit 7bb7925
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
32 changes: 23 additions & 9 deletions packages/babel-helper-plugin-utils/src/index.js
@@ -1,19 +1,33 @@
export function declare(builder) {
return (api, options, dirname) => {
if (!api.assertVersion) {
// Inject a custom version of 'assertVersion' for Babel 6 and early
// versions of Babel 7's beta that didn't have it.
api = Object.assign(copyApiObject(api), {
assertVersion(range) {
throwVersionError(range, api.version);
},
});
let clonedApi;

for (const name of Object.keys(apiPolyfills)) {
if (api[name]) continue;

// TODO: Use ??= when flow lets us to do so
clonedApi = clonedApi ?? copyApiObject(api);
clonedApi[name] = apiPolyfills[name](clonedApi);
}

return builder(api, options || {}, dirname);
return builder(clonedApi ?? api, options || {}, dirname);
};
}

const apiPolyfills = {
// Not supported by Babel 7 and early versions of Babel 7 beta.
// It's important that this is polyfilled for older Babel versions
// since it's needed to report the version mismatch.
assertVersion: api => range => {
throwVersionError(range, api.version);
},
// This is supported starting from Babel 7.13
// TODO(Babel 8): Remove this polyfill
targets: () => () => {
return {};
},
};

function copyApiObject(api) {
// Babel >= 7 <= beta.41 passed the API as a new object that had
// babel/core as the prototype. While slightly faster, it also
Expand Down
3 changes: 1 addition & 2 deletions packages/babel-preset-env/src/index.js
Expand Up @@ -264,8 +264,7 @@ function supportsTopLevelAwait(caller) {
export default declare((api, opts) => {
api.assertVersion(7);

// TODO(Babel 8): api.targets() is always defined, no need to fallback
const babelTargets = api.targets?.() ?? {};
const babelTargets = api.targets();

const {
bugfixes,
Expand Down

0 comments on commit 7bb7925

Please sign in to comment.