browsers.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. let browserslist = require('browserslist')
  2. let agents = require('caniuse-lite').agents
  3. let utils = require('./utils')
  4. class Browsers {
  5. /**
  6. * Return all prefixes for default browser data
  7. */
  8. static prefixes() {
  9. if (this.prefixesCache) {
  10. return this.prefixesCache
  11. }
  12. this.prefixesCache = []
  13. for (let name in agents) {
  14. this.prefixesCache.push(`-${agents[name].prefix}-`)
  15. }
  16. this.prefixesCache = utils
  17. .uniq(this.prefixesCache)
  18. .sort((a, b) => b.length - a.length)
  19. return this.prefixesCache
  20. }
  21. /**
  22. * Check is value contain any possible prefix
  23. */
  24. static withPrefix(value) {
  25. if (!this.prefixesRegexp) {
  26. this.prefixesRegexp = new RegExp(this.prefixes().join('|'))
  27. }
  28. return this.prefixesRegexp.test(value)
  29. }
  30. constructor(data, requirements, options, browserslistOpts) {
  31. this.data = data
  32. this.options = options || {}
  33. this.browserslistOpts = browserslistOpts || {}
  34. this.selected = this.parse(requirements)
  35. }
  36. /**
  37. * Return browsers selected by requirements
  38. */
  39. parse(requirements) {
  40. let opts = {}
  41. for (let i in this.browserslistOpts) {
  42. opts[i] = this.browserslistOpts[i]
  43. }
  44. opts.path = this.options.from
  45. return browserslist(requirements, opts)
  46. }
  47. /**
  48. * Return prefix for selected browser
  49. */
  50. prefix(browser) {
  51. let [name, version] = browser.split(' ')
  52. let data = this.data[name]
  53. let prefix = data.prefix_exceptions && data.prefix_exceptions[version]
  54. if (!prefix) {
  55. prefix = data.prefix
  56. }
  57. return `-${prefix}-`
  58. }
  59. /**
  60. * Is browser is selected by requirements
  61. */
  62. isSelected(browser) {
  63. return this.selected.includes(browser)
  64. }
  65. }
  66. module.exports = Browsers