targets-parser.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. 'use strict';
  2. const browserslist = require('browserslist');
  3. const { compare, has } = require('./helpers');
  4. const external = require('./external');
  5. const aliases = new Map([
  6. ['and_chr', 'chrome'],
  7. ['and_ff', 'firefox'],
  8. ['ie_mob', 'ie'],
  9. ['ios_saf', 'ios'],
  10. ['op_mob', 'opera_mobile'],
  11. ]);
  12. const validTargets = new Set([
  13. 'android',
  14. 'chrome',
  15. 'deno',
  16. 'edge',
  17. 'electron',
  18. 'firefox',
  19. 'ie',
  20. 'ios',
  21. 'node',
  22. 'opera',
  23. 'opera_mobile',
  24. 'phantom',
  25. 'rhino',
  26. 'safari',
  27. 'samsung',
  28. ]);
  29. const toLowerKeys = function (object) {
  30. return Object.entries(object).reduce((accumulator, [key, value]) => {
  31. accumulator[key.toLowerCase()] = value;
  32. return accumulator;
  33. }, {});
  34. };
  35. module.exports = function (targets) {
  36. const { browsers, esmodules, node, ...rest } = (typeof targets != 'object' || Array.isArray(targets))
  37. ? { browsers: targets } : toLowerKeys(targets);
  38. const list = Object.entries(rest);
  39. if (browsers) {
  40. if (typeof browsers == 'string' || Array.isArray(browsers)) {
  41. list.push(...browserslist(browsers).map(it => it.split(' ')));
  42. } else {
  43. list.push(...Object.entries(browsers));
  44. }
  45. }
  46. if (esmodules) {
  47. list.push(...Object.entries(external.modules));
  48. }
  49. if (node) {
  50. list.push(['node', node === 'current' ? process.versions.node : node]);
  51. }
  52. const normalized = list.map(([engine, version]) => {
  53. if (has(browserslist.aliases, engine)) {
  54. engine = browserslist.aliases[engine];
  55. }
  56. if (aliases.has(engine)) {
  57. engine = aliases.get(engine);
  58. }
  59. return [engine, String(version)];
  60. }).filter(([engine]) => {
  61. return validTargets.has(engine);
  62. }).sort(([a], [b]) => {
  63. return a < b ? -1 : a > b ? 1 : 0;
  64. });
  65. const reducedByMinVersion = new Map();
  66. for (const [engine, version] of normalized) {
  67. if (!reducedByMinVersion.has(engine) || compare(version, '<=', reducedByMinVersion.get(engine))) {
  68. reducedByMinVersion.set(engine, version);
  69. }
  70. }
  71. return reducedByMinVersion;
  72. };