| 1 |
import { declare } from "@babel/helper-plugin-utils"; |
| 2 |
import { types as t } from "@babel/core"; |
| 3 |
|
| 4 |
export interface Options { |
| 5 |
helperVersion?: string; |
| 6 |
whitelist?: false | string[]; |
| 7 |
} |
| 8 |
|
| 9 |
export default declare((api, options: Options) => { |
| 10 |
api.assertVersion(7); |
| 11 |
|
| 12 |
const { helperVersion = "7.0.0-beta.0", whitelist = false } = options; |
| 13 |
|
| 14 |
if ( |
| 15 |
whitelist !== false && |
| 16 |
(!Array.isArray(whitelist) || whitelist.some(w => typeof w !== "string")) |
| 17 |
) { |
| 18 |
throw new Error( |
| 19 |
".whitelist must be undefined, false, or an array of strings", |
| 20 |
); |
| 21 |
} |
| 22 |
|
| 23 |
const helperWhitelist = whitelist ? new Set(whitelist) : null; |
| 24 |
|
| 25 |
return { |
| 26 |
name: "external-helpers", |
| 27 |
pre(file) { |
| 28 |
file.set("helperGenerator", (name: string) => { |
| 29 |
// If the helper didn't exist yet at the version given, we bail |
| 30 |
// out and let Babel either insert it directly, or throw an error |
| 31 |
// so that plugins can handle that case properly. |
| 32 |
if ( |
| 33 |
file.availableHelper && |
| 34 |
!file.availableHelper(name, helperVersion) |
| 35 |
) { |
| 36 |
return; |
| 37 |
} |
| 38 |
|
| 39 |
// babelCore.buildExternalHelpers() allows a whitelist of helpers that |
| 40 |
// will be inserted into the external helpers list. That same whitelist |
| 41 |
// should be passed into the plugin here in that case, so that we can |
| 42 |
// avoid referencing 'babelHelpers.XX' when the helper does not exist. |
| 43 |
if (helperWhitelist && !helperWhitelist.has(name)) return; |
| 44 |
|
| 45 |
return t.memberExpression( |
| 46 |
t.identifier("babelHelpers"), |
| 47 |
t.identifier(name), |
| 48 |
); |
| 49 |
}); |
| 50 |
}, |
| 51 |
}; |
| 52 |
}); |