compat.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. 'use strict';
  2. const { compare, filterOutStabilizedProposals, has, intersection } = require('./helpers');
  3. const data = require('./data');
  4. const entries = require('./entries');
  5. const getModulesListForTargetVersion = require('./get-modules-list-for-target-version');
  6. const allModules = require('./modules');
  7. const targetsParser = require('./targets-parser');
  8. function throwInvalidFilter(filter) {
  9. throw new TypeError(`Specified invalid module name or pattern: ${ filter }`);
  10. }
  11. function atLeastSomeModules(modules, filter) {
  12. if (!modules.length) throwInvalidFilter(filter);
  13. return modules;
  14. }
  15. function getModules(filter) {
  16. if (typeof filter == 'string') {
  17. if (has(entries, filter)) return entries[filter];
  18. return atLeastSomeModules(allModules.filter(it => it.startsWith(filter)), filter);
  19. }
  20. if (filter instanceof RegExp) return atLeastSomeModules(allModules.filter(it => filter.test(it)), filter);
  21. throwInvalidFilter(filter);
  22. }
  23. function normalizeModules(option) {
  24. // TODO: use `.flatMap` in core-js@4
  25. return new Set(Array.isArray(option) ? [].concat(...option.map(getModules)) : getModules(option));
  26. }
  27. function checkModule(name, targets) {
  28. const result = {
  29. required: !targets,
  30. targets: {},
  31. };
  32. if (!targets) return result;
  33. const requirements = data[name];
  34. for (const [engine, version] of targets) {
  35. if (!has(requirements, engine) || compare(version, '<', requirements[engine])) {
  36. result.required = true;
  37. result.targets[engine] = version;
  38. }
  39. }
  40. return result;
  41. }
  42. module.exports = function ({
  43. filter = null, // TODO: Obsolete, remove from `core-js@4`
  44. modules = null,
  45. exclude = [],
  46. targets = null,
  47. version = null,
  48. inverse = false,
  49. } = {}) {
  50. if (modules === null || modules === undefined) modules = filter;
  51. inverse = !!inverse;
  52. const parsedTargets = targets ? targetsParser(targets) : null;
  53. const result = {
  54. list: [],
  55. targets: {},
  56. };
  57. exclude = normalizeModules(exclude);
  58. modules = modules ? [...normalizeModules(modules)] : allModules;
  59. if (exclude.size) modules = modules.filter(it => !exclude.has(it));
  60. modules = intersection(modules, version ? getModulesListForTargetVersion(version) : allModules);
  61. if (!inverse) modules = filterOutStabilizedProposals(modules);
  62. for (const key of modules) {
  63. const check = checkModule(key, parsedTargets);
  64. if (check.required ^ inverse) {
  65. result.list.push(key);
  66. result.targets[key] = check.targets;
  67. }
  68. }
  69. return result;
  70. };