node.js 11 KB

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