node.js 11 KB

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