index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. "use strict";
  2. exports.__esModule = true;
  3. exports.default = definePolyfillProvider;
  4. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  5. var _helperCompilationTargets = _interopRequireWildcard(require("@babel/helper-compilation-targets"));
  6. var _utils = require("./utils");
  7. var _importsCache = _interopRequireDefault(require("./imports-cache"));
  8. var _debugUtils = require("./debug-utils");
  9. var _normalizeOptions = require("./normalize-options");
  10. var v = _interopRequireWildcard(require("./visitors"));
  11. var deps = _interopRequireWildcard(require("./node/dependencies"));
  12. var _metaResolver = _interopRequireDefault(require("./meta-resolver"));
  13. const _excluded = ["method", "targets", "ignoreBrowserslistConfig", "configPath", "debug", "shouldInjectPolyfill", "absoluteImports"];
  14. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  15. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  16. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  17. function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
  18. const getTargets = _helperCompilationTargets.default.default || _helperCompilationTargets.default;
  19. function resolveOptions(options, babelApi) {
  20. const {
  21. method,
  22. targets: targetsOption,
  23. ignoreBrowserslistConfig,
  24. configPath,
  25. debug,
  26. shouldInjectPolyfill,
  27. absoluteImports
  28. } = options,
  29. providerOptions = _objectWithoutPropertiesLoose(options, _excluded);
  30. if (isEmpty(options)) {
  31. throw new Error(`\
  32. This plugin requires options, for example:
  33. {
  34. "plugins": [
  35. ["<plugin name>", { method: "usage-pure" }]
  36. ]
  37. }
  38. See more options at https://github.com/babel/babel-polyfills/blob/main/docs/usage.md`);
  39. }
  40. let methodName;
  41. if (method === "usage-global") methodName = "usageGlobal";else if (method === "entry-global") methodName = "entryGlobal";else if (method === "usage-pure") methodName = "usagePure";else if (typeof method !== "string") {
  42. throw new Error(".method must be a string");
  43. } else {
  44. throw new Error(`.method must be one of "entry-global", "usage-global"` + ` or "usage-pure" (received ${JSON.stringify(method)})`);
  45. }
  46. if (typeof shouldInjectPolyfill === "function") {
  47. if (options.include || options.exclude) {
  48. throw new Error(`.include and .exclude are not supported when using the` + ` .shouldInjectPolyfill function.`);
  49. }
  50. } else if (shouldInjectPolyfill != null) {
  51. throw new Error(`.shouldInjectPolyfill must be a function, or undefined` + ` (received ${JSON.stringify(shouldInjectPolyfill)})`);
  52. }
  53. if (absoluteImports != null && typeof absoluteImports !== "boolean" && typeof absoluteImports !== "string") {
  54. throw new Error(`.absoluteImports must be a boolean, a string, or undefined` + ` (received ${JSON.stringify(absoluteImports)})`);
  55. }
  56. let targets;
  57. if ( // If any browserslist-related option is specified, fallback to the old
  58. // behavior of not using the targets specified in the top-level options.
  59. targetsOption || configPath || ignoreBrowserslistConfig) {
  60. const targetsObj = typeof targetsOption === "string" || Array.isArray(targetsOption) ? {
  61. browsers: targetsOption
  62. } : targetsOption;
  63. targets = getTargets(targetsObj, {
  64. ignoreBrowserslistConfig,
  65. configPath
  66. });
  67. } else {
  68. targets = babelApi.targets();
  69. }
  70. return {
  71. method,
  72. methodName,
  73. targets,
  74. absoluteImports: absoluteImports != null ? absoluteImports : false,
  75. shouldInjectPolyfill,
  76. debug: !!debug,
  77. providerOptions: providerOptions
  78. };
  79. }
  80. function instantiateProvider(factory, options, missingDependencies, dirname, debugLog, babelApi) {
  81. const {
  82. method,
  83. methodName,
  84. targets,
  85. debug,
  86. shouldInjectPolyfill,
  87. providerOptions,
  88. absoluteImports
  89. } = resolveOptions(options, babelApi);
  90. const getUtils = (0, _utils.createUtilsGetter)(new _importsCache.default(moduleName => deps.resolve(dirname, moduleName, absoluteImports))); // eslint-disable-next-line prefer-const
  91. let include, exclude;
  92. let polyfillsSupport;
  93. let polyfillsNames;
  94. let filterPolyfills;
  95. const depsCache = new Map();
  96. const api = {
  97. babel: babelApi,
  98. getUtils,
  99. method: options.method,
  100. targets,
  101. createMetaResolver: _metaResolver.default,
  102. shouldInjectPolyfill(name) {
  103. if (polyfillsNames === undefined) {
  104. throw new Error(`Internal error in the ${factory.name} provider: ` + `shouldInjectPolyfill() can't be called during initialization.`);
  105. }
  106. if (!polyfillsNames.has(name)) {
  107. console.warn(`Internal error in the ${provider.name} provider: ` + `unknown polyfill "${name}".`);
  108. }
  109. if (filterPolyfills && !filterPolyfills(name)) return false;
  110. let shouldInject = (0, _helperCompilationTargets.isRequired)(name, targets, {
  111. compatData: polyfillsSupport,
  112. includes: include,
  113. excludes: exclude
  114. });
  115. if (shouldInjectPolyfill) {
  116. shouldInject = shouldInjectPolyfill(name, shouldInject);
  117. if (typeof shouldInject !== "boolean") {
  118. throw new Error(`.shouldInjectPolyfill must return a boolean.`);
  119. }
  120. }
  121. return shouldInject;
  122. },
  123. debug(name) {
  124. var _debugLog, _debugLog$polyfillsSu;
  125. debugLog().found = true;
  126. if (!debug || !name) return;
  127. if (debugLog().polyfills.has(provider.name)) return;
  128. debugLog().polyfills.add(name);
  129. (_debugLog$polyfillsSu = (_debugLog = debugLog()).polyfillsSupport) != null ? _debugLog$polyfillsSu : _debugLog.polyfillsSupport = polyfillsSupport;
  130. },
  131. assertDependency(name, version = "*") {
  132. if (missingDependencies === false) return;
  133. if (absoluteImports) {
  134. // If absoluteImports is not false, we will try resolving
  135. // the dependency and throw if it's not possible. We can
  136. // skip the check here.
  137. return;
  138. }
  139. const dep = version === "*" ? name : `${name}@^${version}`;
  140. const found = missingDependencies.all ? false : mapGetOr(depsCache, `${name} :: ${dirname}`, () => deps.has(dirname, name));
  141. if (!found) {
  142. debugLog().missingDeps.add(dep);
  143. }
  144. }
  145. };
  146. const provider = factory(api, providerOptions, dirname);
  147. if (typeof provider[methodName] !== "function") {
  148. throw new Error(`The "${provider.name || factory.name}" provider doesn't ` + `support the "${method}" polyfilling method.`);
  149. }
  150. if (Array.isArray(provider.polyfills)) {
  151. polyfillsNames = new Set(provider.polyfills);
  152. filterPolyfills = provider.filterPolyfills;
  153. } else if (provider.polyfills) {
  154. polyfillsNames = new Set(Object.keys(provider.polyfills));
  155. polyfillsSupport = provider.polyfills;
  156. filterPolyfills = provider.filterPolyfills;
  157. } else {
  158. polyfillsNames = new Set();
  159. }
  160. ({
  161. include,
  162. exclude
  163. } = (0, _normalizeOptions.validateIncludeExclude)(provider.name || factory.name, polyfillsNames, providerOptions.include || [], providerOptions.exclude || []));
  164. return {
  165. debug,
  166. method,
  167. targets,
  168. provider,
  169. callProvider(payload, path) {
  170. const utils = getUtils(path);
  171. provider[methodName](payload, utils, path);
  172. }
  173. };
  174. }
  175. function definePolyfillProvider(factory) {
  176. return (0, _helperPluginUtils.declare)((babelApi, options, dirname) => {
  177. babelApi.assertVersion(7);
  178. const {
  179. traverse
  180. } = babelApi;
  181. let debugLog;
  182. const missingDependencies = (0, _normalizeOptions.applyMissingDependenciesDefaults)(options, babelApi);
  183. const {
  184. debug,
  185. method,
  186. targets,
  187. provider,
  188. callProvider
  189. } = instantiateProvider(factory, options, missingDependencies, dirname, () => debugLog, babelApi);
  190. const createVisitor = method === "entry-global" ? v.entry : v.usage;
  191. const visitor = provider.visitor ? traverse.visitors.merge([createVisitor(callProvider), provider.visitor]) : createVisitor(callProvider);
  192. if (debug && debug !== _debugUtils.presetEnvSilentDebugHeader) {
  193. console.log(`${provider.name}: \`DEBUG\` option`);
  194. console.log(`\nUsing targets: ${(0, _debugUtils.stringifyTargetsMultiline)(targets)}`);
  195. console.log(`\nUsing polyfills with \`${method}\` method:`);
  196. }
  197. return {
  198. name: "inject-polyfills",
  199. visitor,
  200. pre() {
  201. var _provider$pre;
  202. debugLog = {
  203. polyfills: new Set(),
  204. polyfillsSupport: undefined,
  205. found: false,
  206. providers: new Set(),
  207. missingDeps: new Set()
  208. };
  209. (_provider$pre = provider.pre) == null ? void 0 : _provider$pre.apply(this, arguments);
  210. },
  211. post() {
  212. var _provider$post;
  213. (_provider$post = provider.post) == null ? void 0 : _provider$post.apply(this, arguments);
  214. if (missingDependencies !== false) {
  215. if (missingDependencies.log === "per-file") {
  216. deps.logMissing(debugLog.missingDeps);
  217. } else {
  218. deps.laterLogMissing(debugLog.missingDeps);
  219. }
  220. }
  221. if (!debug) return;
  222. if (this.filename) console.log(`\n[${this.filename}]`);
  223. if (debugLog.polyfills.size === 0) {
  224. console.log(method === "entry-global" ? debugLog.found ? `Based on your targets, the ${provider.name} polyfill did not add any polyfill.` : `The entry point for the ${provider.name} polyfill has not been found.` : `Based on your code and targets, the ${provider.name} polyfill did not add any polyfill.`);
  225. return;
  226. }
  227. if (method === "entry-global") {
  228. console.log(`The ${provider.name} polyfill entry has been replaced with ` + `the following polyfills:`);
  229. } else {
  230. console.log(`The ${provider.name} polyfill added the following polyfills:`);
  231. }
  232. for (const name of debugLog.polyfills) {
  233. var _debugLog$polyfillsSu2;
  234. if ((_debugLog$polyfillsSu2 = debugLog.polyfillsSupport) != null && _debugLog$polyfillsSu2[name]) {
  235. const filteredTargets = (0, _helperCompilationTargets.getInclusionReasons)(name, targets, debugLog.polyfillsSupport);
  236. const formattedTargets = JSON.stringify(filteredTargets).replace(/,/g, ", ").replace(/^\{"/, '{ "').replace(/"\}$/, '" }');
  237. console.log(` ${name} ${formattedTargets}`);
  238. } else {
  239. console.log(` ${name}`);
  240. }
  241. }
  242. }
  243. };
  244. });
  245. }
  246. function mapGetOr(map, key, getDefault) {
  247. let val = map.get(key);
  248. if (val === undefined) {
  249. val = getDefault();
  250. map.set(key, val);
  251. }
  252. return val;
  253. }
  254. function isEmpty(obj) {
  255. return Object.keys(obj).length === 0;
  256. }