index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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 (
  58. // If any browserslist-related option is specified, fallback to the old
  59. // behavior of not using the targets specified in the top-level options.
  60. targetsOption || configPath || ignoreBrowserslistConfig) {
  61. const targetsObj = typeof targetsOption === "string" || Array.isArray(targetsOption) ? {
  62. browsers: targetsOption
  63. } : targetsOption;
  64. targets = getTargets(targetsObj, {
  65. ignoreBrowserslistConfig,
  66. configPath
  67. });
  68. } else {
  69. targets = babelApi.targets();
  70. }
  71. return {
  72. method,
  73. methodName,
  74. targets,
  75. absoluteImports: absoluteImports != null ? absoluteImports : false,
  76. shouldInjectPolyfill,
  77. debug: !!debug,
  78. providerOptions: providerOptions
  79. };
  80. }
  81. function instantiateProvider(factory, options, missingDependencies, dirname, debugLog, babelApi) {
  82. const {
  83. method,
  84. methodName,
  85. targets,
  86. debug,
  87. shouldInjectPolyfill,
  88. providerOptions,
  89. absoluteImports
  90. } = resolveOptions(options, babelApi);
  91. const getUtils = (0, _utils.createUtilsGetter)(new _importsCache.default(moduleName => deps.resolve(dirname, moduleName, absoluteImports)));
  92. // eslint-disable-next-line prefer-const
  93. let include, exclude;
  94. let polyfillsSupport;
  95. let polyfillsNames;
  96. let filterPolyfills;
  97. const depsCache = new Map();
  98. const api = {
  99. babel: babelApi,
  100. getUtils,
  101. method: options.method,
  102. targets,
  103. createMetaResolver: _metaResolver.default,
  104. shouldInjectPolyfill(name) {
  105. if (polyfillsNames === undefined) {
  106. throw new Error(`Internal error in the ${factory.name} provider: ` + `shouldInjectPolyfill() can't be called during initialization.`);
  107. }
  108. if (!polyfillsNames.has(name)) {
  109. console.warn(`Internal error in the ${providerName} provider: ` + `unknown polyfill "${name}".`);
  110. }
  111. if (filterPolyfills && !filterPolyfills(name)) return false;
  112. let shouldInject = (0, _helperCompilationTargets.isRequired)(name, targets, {
  113. compatData: polyfillsSupport,
  114. includes: include,
  115. excludes: exclude
  116. });
  117. if (shouldInjectPolyfill) {
  118. shouldInject = shouldInjectPolyfill(name, shouldInject);
  119. if (typeof shouldInject !== "boolean") {
  120. throw new Error(`.shouldInjectPolyfill must return a boolean.`);
  121. }
  122. }
  123. return shouldInject;
  124. },
  125. debug(name) {
  126. var _debugLog, _debugLog$polyfillsSu;
  127. debugLog().found = true;
  128. if (!debug || !name) return;
  129. if (debugLog().polyfills.has(providerName)) return;
  130. debugLog().polyfills.add(name);
  131. (_debugLog$polyfillsSu = (_debugLog = debugLog()).polyfillsSupport) != null ? _debugLog$polyfillsSu : _debugLog.polyfillsSupport = polyfillsSupport;
  132. },
  133. assertDependency(name, version = "*") {
  134. if (missingDependencies === false) return;
  135. if (absoluteImports) {
  136. // If absoluteImports is not false, we will try resolving
  137. // the dependency and throw if it's not possible. We can
  138. // skip the check here.
  139. return;
  140. }
  141. const dep = version === "*" ? name : `${name}@^${version}`;
  142. const found = missingDependencies.all ? false : mapGetOr(depsCache, `${name} :: ${dirname}`, () => deps.has(dirname, name));
  143. if (!found) {
  144. debugLog().missingDeps.add(dep);
  145. }
  146. }
  147. };
  148. const provider = factory(api, providerOptions, dirname);
  149. const providerName = provider.name || factory.name;
  150. if (typeof provider[methodName] !== "function") {
  151. throw new Error(`The "${providerName}" provider doesn't support the "${method}" polyfilling method.`);
  152. }
  153. if (Array.isArray(provider.polyfills)) {
  154. polyfillsNames = new Set(provider.polyfills);
  155. filterPolyfills = provider.filterPolyfills;
  156. } else if (provider.polyfills) {
  157. polyfillsNames = new Set(Object.keys(provider.polyfills));
  158. polyfillsSupport = provider.polyfills;
  159. filterPolyfills = provider.filterPolyfills;
  160. } else {
  161. polyfillsNames = new Set();
  162. }
  163. ({
  164. include,
  165. exclude
  166. } = (0, _normalizeOptions.validateIncludeExclude)(providerName, polyfillsNames, providerOptions.include || [], providerOptions.exclude || []));
  167. return {
  168. debug,
  169. method,
  170. targets,
  171. provider,
  172. providerName,
  173. callProvider(payload, path) {
  174. const utils = getUtils(path);
  175. provider[methodName](payload, utils, path);
  176. }
  177. };
  178. }
  179. function definePolyfillProvider(factory) {
  180. return (0, _helperPluginUtils.declare)((babelApi, options, dirname) => {
  181. babelApi.assertVersion(7);
  182. const {
  183. traverse
  184. } = babelApi;
  185. let debugLog;
  186. const missingDependencies = (0, _normalizeOptions.applyMissingDependenciesDefaults)(options, babelApi);
  187. const {
  188. debug,
  189. method,
  190. targets,
  191. provider,
  192. providerName,
  193. callProvider
  194. } = instantiateProvider(factory, options, missingDependencies, dirname, () => debugLog, babelApi);
  195. const createVisitor = method === "entry-global" ? v.entry : v.usage;
  196. const visitor = provider.visitor ? traverse.visitors.merge([createVisitor(callProvider), provider.visitor]) : createVisitor(callProvider);
  197. if (debug && debug !== _debugUtils.presetEnvSilentDebugHeader) {
  198. console.log(`${providerName}: \`DEBUG\` option`);
  199. console.log(`\nUsing targets: ${(0, _debugUtils.stringifyTargetsMultiline)(targets)}`);
  200. console.log(`\nUsing polyfills with \`${method}\` method:`);
  201. }
  202. const {
  203. runtimeName
  204. } = provider;
  205. return {
  206. name: "inject-polyfills",
  207. visitor,
  208. pre(file) {
  209. var _provider$pre;
  210. if (runtimeName) {
  211. if (file.get("runtimeHelpersModuleName") && file.get("runtimeHelpersModuleName") !== runtimeName) {
  212. console.warn(`Two different polyfill providers` + ` (${file.get("runtimeHelpersModuleProvider")}` + ` and ${providerName}) are trying to define two` + ` conflicting @babel/runtime alternatives:` + ` ${file.get("runtimeHelpersModuleName")} and ${runtimeName}.` + ` The second one will be ignored.`);
  213. } else {
  214. file.set("runtimeHelpersModuleName", runtimeName);
  215. file.set("runtimeHelpersModuleProvider", providerName);
  216. }
  217. }
  218. debugLog = {
  219. polyfills: new Set(),
  220. polyfillsSupport: undefined,
  221. found: false,
  222. providers: new Set(),
  223. missingDeps: new Set()
  224. };
  225. (_provider$pre = provider.pre) == null ? void 0 : _provider$pre.apply(this, arguments);
  226. },
  227. post() {
  228. var _provider$post;
  229. (_provider$post = provider.post) == null ? void 0 : _provider$post.apply(this, arguments);
  230. if (missingDependencies !== false) {
  231. if (missingDependencies.log === "per-file") {
  232. deps.logMissing(debugLog.missingDeps);
  233. } else {
  234. deps.laterLogMissing(debugLog.missingDeps);
  235. }
  236. }
  237. if (!debug) return;
  238. if (this.filename) console.log(`\n[${this.filename}]`);
  239. if (debugLog.polyfills.size === 0) {
  240. console.log(method === "entry-global" ? debugLog.found ? `Based on your targets, the ${providerName} polyfill did not add any polyfill.` : `The entry point for the ${providerName} polyfill has not been found.` : `Based on your code and targets, the ${providerName} polyfill did not add any polyfill.`);
  241. return;
  242. }
  243. if (method === "entry-global") {
  244. console.log(`The ${providerName} polyfill entry has been replaced with ` + `the following polyfills:`);
  245. } else {
  246. console.log(`The ${providerName} polyfill added the following polyfills:`);
  247. }
  248. for (const name of debugLog.polyfills) {
  249. var _debugLog$polyfillsSu2;
  250. if ((_debugLog$polyfillsSu2 = debugLog.polyfillsSupport) != null && _debugLog$polyfillsSu2[name]) {
  251. const filteredTargets = (0, _helperCompilationTargets.getInclusionReasons)(name, targets, debugLog.polyfillsSupport);
  252. const formattedTargets = JSON.stringify(filteredTargets).replace(/,/g, ", ").replace(/^\{"/, '{ "').replace(/"\}$/, '" }');
  253. console.log(` ${name} ${formattedTargets}`);
  254. } else {
  255. console.log(` ${name}`);
  256. }
  257. }
  258. }
  259. };
  260. });
  261. }
  262. function mapGetOr(map, key, getDefault) {
  263. let val = map.get(key);
  264. if (val === undefined) {
  265. val = getDefault();
  266. map.set(key, val);
  267. }
  268. return val;
  269. }
  270. function isEmpty(obj) {
  271. return Object.keys(obj).length === 0;
  272. }