You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

348 lines
9.6 KiB

4 years ago
  1. var region = require('caniuse-lite/dist/unpacker/region').default
  2. var path = require('path')
  3. var fs = require('fs')
  4. var BrowserslistError = require('./error')
  5. var IS_SECTION = /^\s*\[(.+)]\s*$/
  6. var CONFIG_PATTERN = /^browserslist-config-/
  7. var SCOPED_CONFIG__PATTERN = /@[^/]+\/browserslist-config(-|$|\/)/
  8. var TIME_TO_UPDATE_CANIUSE = 6 * 30 * 24 * 60 * 60 * 1000
  9. var FORMAT = 'Browserslist config should be a string or an array ' +
  10. 'of strings with browser queries'
  11. var dataTimeChecked = false
  12. var filenessCache = { }
  13. var configCache = { }
  14. function checkExtend (name) {
  15. var use = ' Use `dangerousExtend` option to disable.'
  16. if (!CONFIG_PATTERN.test(name) && !SCOPED_CONFIG__PATTERN.test(name)) {
  17. throw new BrowserslistError(
  18. 'Browserslist config needs `browserslist-config-` prefix. ' + use)
  19. }
  20. if (name.replace(/^@[^/]+\//, '').indexOf('.') !== -1) {
  21. throw new BrowserslistError(
  22. '`.` not allowed in Browserslist config name. ' + use)
  23. }
  24. if (name.indexOf('node_modules') !== -1) {
  25. throw new BrowserslistError(
  26. '`node_modules` not allowed in Browserslist config.' + use)
  27. }
  28. }
  29. function isFile (file) {
  30. if (file in filenessCache) {
  31. return filenessCache[file]
  32. }
  33. var result = fs.existsSync(file) && fs.statSync(file).isFile()
  34. if (!process.env.BROWSERSLIST_DISABLE_CACHE) {
  35. filenessCache[file] = result
  36. }
  37. return result
  38. }
  39. function eachParent (file, callback) {
  40. var dir = isFile(file) ? path.dirname(file) : file
  41. var loc = path.resolve(dir)
  42. do {
  43. var result = callback(loc)
  44. if (typeof result !== 'undefined') return result
  45. } while (loc !== (loc = path.dirname(loc)))
  46. return undefined
  47. }
  48. function check (section) {
  49. if (Array.isArray(section)) {
  50. for (var i = 0; i < section.length; i++) {
  51. if (typeof section[i] !== 'string') {
  52. throw new BrowserslistError(FORMAT)
  53. }
  54. }
  55. } else if (typeof section !== 'string') {
  56. throw new BrowserslistError(FORMAT)
  57. }
  58. }
  59. function pickEnv (config, opts) {
  60. if (typeof config !== 'object') return config
  61. var name
  62. if (typeof opts.env === 'string') {
  63. name = opts.env
  64. } else if (process.env.BROWSERSLIST_ENV) {
  65. name = process.env.BROWSERSLIST_ENV
  66. } else if (process.env.NODE_ENV) {
  67. name = process.env.NODE_ENV
  68. } else {
  69. name = 'production'
  70. }
  71. return config[name] || config.defaults
  72. }
  73. function parsePackage (file) {
  74. var config = JSON.parse(fs.readFileSync(file))
  75. if (config.browserlist && !config.browserslist) {
  76. throw new BrowserslistError(
  77. '`browserlist` key instead of `browserslist` in ' + file
  78. )
  79. }
  80. var list = config.browserslist
  81. if (Array.isArray(list) || typeof list === 'string') {
  82. list = { defaults: list }
  83. }
  84. for (var i in list) {
  85. check(list[i])
  86. }
  87. return list
  88. }
  89. function latestReleaseTime (agents) {
  90. var latest = 0
  91. for (var name in agents) {
  92. var dates = agents[name].releaseDate || { }
  93. for (var key in dates) {
  94. if (latest < dates[key]) {
  95. latest = dates[key]
  96. }
  97. }
  98. }
  99. return latest * 1000
  100. }
  101. function normalizeStats (data, stats) {
  102. if (stats && 'dataByBrowser' in stats) {
  103. stats = stats.dataByBrowser
  104. }
  105. if (typeof stats !== 'object') return undefined
  106. var normalized = { }
  107. for (var i in stats) {
  108. var versions = Object.keys(stats[i])
  109. if (
  110. versions.length === 1 &&
  111. data[i] &&
  112. data[i].versions.length === 1
  113. ) {
  114. var normal = Object.keys(data[i].versions)[0]
  115. normalized[i] = { }
  116. normalized[i][normal] = stats[i][versions[0]]
  117. } else {
  118. normalized[i] = stats[i]
  119. }
  120. }
  121. return normalized
  122. }
  123. module.exports = {
  124. loadQueries: function loadQueries (context, name) {
  125. if (!context.dangerousExtend) checkExtend(name)
  126. // eslint-disable-next-line security/detect-non-literal-require
  127. var queries = require(require.resolve(name, { paths: ['.'] }))
  128. if (!Array.isArray(queries)) {
  129. throw new BrowserslistError(
  130. '`' + name + '` config exports not an array of queries'
  131. )
  132. }
  133. return queries
  134. },
  135. loadStat: function loadStat (context, name, data) {
  136. if (!context.dangerousExtend) checkExtend(name)
  137. // eslint-disable-next-line security/detect-non-literal-require
  138. var stats = require(
  139. require.resolve(
  140. path.join(name, 'browserslist-stats.json'),
  141. { paths: ['.'] }
  142. )
  143. )
  144. return normalizeStats(data, stats)
  145. },
  146. getStat: function getStat (opts, data) {
  147. var stats
  148. if (opts.stats) {
  149. stats = opts.stats
  150. } else if (process.env.BROWSERSLIST_STATS) {
  151. stats = process.env.BROWSERSLIST_STATS
  152. } else if (opts.path && path.resolve && fs.existsSync) {
  153. stats = eachParent(opts.path, function (dir) {
  154. var file = path.join(dir, 'browserslist-stats.json')
  155. return isFile(file) ? file : undefined
  156. })
  157. }
  158. if (typeof stats === 'string') {
  159. try {
  160. stats = JSON.parse(fs.readFileSync(stats))
  161. } catch (e) {
  162. throw new BrowserslistError('Can\'t read ' + stats)
  163. }
  164. }
  165. return normalizeStats(data, stats)
  166. },
  167. loadConfig: function loadConfig (opts) {
  168. if (process.env.BROWSERSLIST) {
  169. return process.env.BROWSERSLIST
  170. } else if (opts.config || process.env.BROWSERSLIST_CONFIG) {
  171. var file = opts.config || process.env.BROWSERSLIST_CONFIG
  172. if (path.basename(file) === 'package.json') {
  173. return pickEnv(parsePackage(file), opts)
  174. } else {
  175. return pickEnv(module.exports.readConfig(file), opts)
  176. }
  177. } else if (opts.path) {
  178. return pickEnv(module.exports.findConfig(opts.path), opts)
  179. } else {
  180. return undefined
  181. }
  182. },
  183. loadCountry: function loadCountry (usage, country) {
  184. var code = country.replace(/[^\w-]/g, '')
  185. if (!usage[code]) {
  186. // eslint-disable-next-line security/detect-non-literal-require
  187. var compressed = require('caniuse-lite/data/regions/' + code + '.js')
  188. var data = region(compressed)
  189. usage[country] = { }
  190. for (var i in data) {
  191. for (var j in data[i]) {
  192. usage[country][i + ' ' + j] = data[i][j]
  193. }
  194. }
  195. }
  196. },
  197. parseConfig: function parseConfig (string) {
  198. var result = { defaults: [] }
  199. var sections = ['defaults']
  200. string.toString()
  201. .replace(/#[^\n]*/g, '')
  202. .split(/\n|,/)
  203. .map(function (line) {
  204. return line.trim()
  205. })
  206. .filter(function (line) {
  207. return line !== ''
  208. })
  209. .forEach(function (line) {
  210. if (IS_SECTION.test(line)) {
  211. sections = line.match(IS_SECTION)[1].trim().split(' ')
  212. sections.forEach(function (section) {
  213. if (result[section]) {
  214. throw new BrowserslistError(
  215. 'Duplicate section ' + section + ' in Browserslist config'
  216. )
  217. }
  218. result[section] = []
  219. })
  220. } else {
  221. sections.forEach(function (section) {
  222. result[section].push(line)
  223. })
  224. }
  225. })
  226. return result
  227. },
  228. readConfig: function readConfig (file) {
  229. if (!isFile(file)) {
  230. throw new BrowserslistError('Can\'t read ' + file + ' config')
  231. }
  232. return module.exports.parseConfig(fs.readFileSync(file))
  233. },
  234. findConfig: function findConfig (from) {
  235. from = path.resolve(from)
  236. var passed = []
  237. var resolved = eachParent(from, function (dir) {
  238. if (dir in configCache) {
  239. return configCache[dir]
  240. }
  241. passed.push(dir)
  242. var config = path.join(dir, 'browserslist')
  243. var pkg = path.join(dir, 'package.json')
  244. var rc = path.join(dir, '.browserslistrc')
  245. var pkgBrowserslist
  246. if (isFile(pkg)) {
  247. try {
  248. pkgBrowserslist = parsePackage(pkg)
  249. } catch (e) {
  250. if (e.name === 'BrowserslistError') throw e
  251. console.warn(
  252. '[Browserslist] Could not parse ' + pkg + '. Ignoring it.'
  253. )
  254. }
  255. }
  256. if (isFile(config) && pkgBrowserslist) {
  257. throw new BrowserslistError(
  258. dir + ' contains both browserslist and package.json with browsers'
  259. )
  260. } else if (isFile(rc) && pkgBrowserslist) {
  261. throw new BrowserslistError(
  262. dir + ' contains both .browserslistrc and package.json with browsers'
  263. )
  264. } else if (isFile(config) && isFile(rc)) {
  265. throw new BrowserslistError(
  266. dir + ' contains both .browserslistrc and browserslist'
  267. )
  268. } else if (isFile(config)) {
  269. return module.exports.readConfig(config)
  270. } else if (isFile(rc)) {
  271. return module.exports.readConfig(rc)
  272. } else {
  273. return pkgBrowserslist
  274. }
  275. })
  276. if (!process.env.BROWSERSLIST_DISABLE_CACHE) {
  277. passed.forEach(function (dir) {
  278. configCache[dir] = resolved
  279. })
  280. }
  281. return resolved
  282. },
  283. clearCaches: function clearCaches () {
  284. dataTimeChecked = false
  285. filenessCache = { }
  286. configCache = { }
  287. },
  288. oldDataWarning: function oldDataWarning (agentsObj) {
  289. if (dataTimeChecked) return
  290. dataTimeChecked = true
  291. if (process.env.BROWSERSLIST_IGNORE_OLD_DATA) return
  292. var latest = latestReleaseTime(agentsObj)
  293. var halfYearAgo = Date.now() - TIME_TO_UPDATE_CANIUSE
  294. if (latest !== 0 && latest < halfYearAgo) {
  295. var command = 'npm update'
  296. eachParent(__filename, function (dir) {
  297. var pckg = path.join(dir, 'package.json')
  298. var yarnLock = path.join(dir, 'yarn.lock')
  299. if (isFile(pckg) && isFile(yarnLock)) {
  300. command = 'yarn upgrade'
  301. }
  302. })
  303. console.warn(
  304. 'Browserslist: caniuse-lite is outdated. ' +
  305. 'Please run next command `' + command + '`'
  306. )
  307. }
  308. },
  309. currentNode: function currentNode () {
  310. return 'node ' + process.versions.node
  311. }
  312. }