compat.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 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. } else if (filter instanceof RegExp) return atLeastSomeModules(allModules.filter(it => filter.test(it)), filter);
  20. throwInvalidFilter(filter);
  21. }
  22. function normalizeModules(option) {
  23. // TODO: use `.flatMap` in core-js@4
  24. return new Set(Array.isArray(option) ? [].concat.apply([], option.map(getModules)) : getModules(option));
  25. }
  26. function checkModule(name, targets) {
  27. const result = {
  28. required: !targets,
  29. targets: {},
  30. };
  31. if (!targets) return result;
  32. const requirements = data[name];
  33. for (const [engine, version] of targets) {
  34. if (!has(requirements, engine) || compare(version, '<', requirements[engine])) {
  35. result.required = true;
  36. result.targets[engine] = version;
  37. }
  38. }
  39. return result;
  40. }
  41. module.exports = function ({
  42. filter = null, // TODO: Obsolete, remove from `core-js@4`
  43. modules = null,
  44. exclude = [],
  45. targets = null,
  46. version = null,
  47. } = {}) {
  48. if (modules == null) modules = filter;
  49. const parsedTargets = targets ? targetsParser(targets) : null;
  50. const result = {
  51. list: [],
  52. targets: {},
  53. };
  54. exclude = normalizeModules(exclude);
  55. modules = modules ? [...normalizeModules(modules)] : allModules;
  56. if (exclude.size) modules = modules.filter(it => !exclude.has(it));
  57. modules = intersection(modules, version ? getModulesListForTargetVersion(version) : allModules);
  58. modules = filterOutStabilizedProposals(modules);
  59. for (const key of modules) {
  60. const check = checkModule(key, parsedTargets);
  61. if (check.required) {
  62. result.list.push(key);
  63. result.targets[key] = check.targets;
  64. }
  65. }
  66. return result;
  67. };