node.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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(
  87. fs
  88. .readFileSync(file)
  89. .toString()
  90. .replace(/^\uFEFF/m, '')
  91. )
  92. if (config.browserlist && !config.browserslist) {
  93. throw new BrowserslistError(
  94. '`browserlist` key instead of `browserslist` in ' + file
  95. )
  96. }
  97. var list = config.browserslist
  98. if (Array.isArray(list) || typeof list === 'string') {
  99. list = { defaults: list }
  100. }
  101. for (var i in list) {
  102. check(list[i])
  103. }
  104. return list
  105. }
  106. function latestReleaseTime(agents) {
  107. var latest = 0
  108. for (var name in agents) {
  109. var dates = agents[name].releaseDate || {}
  110. for (var key in dates) {
  111. if (latest < dates[key]) {
  112. latest = dates[key]
  113. }
  114. }
  115. }
  116. return latest * 1000
  117. }
  118. function normalizeStats(data, stats) {
  119. if (!data) {
  120. data = {}
  121. }
  122. if (stats && 'dataByBrowser' in stats) {
  123. stats = stats.dataByBrowser
  124. }
  125. if (typeof stats !== 'object') return undefined
  126. var normalized = {}
  127. for (var i in stats) {
  128. var versions = Object.keys(stats[i])
  129. if (versions.length === 1 && data[i] && data[i].versions.length === 1) {
  130. var normal = data[i].versions[0]
  131. normalized[i] = {}
  132. normalized[i][normal] = stats[i][versions[0]]
  133. } else {
  134. normalized[i] = stats[i]
  135. }
  136. }
  137. return normalized
  138. }
  139. function normalizeUsageData(usageData, data) {
  140. for (var browser in usageData) {
  141. var browserUsage = usageData[browser]
  142. // eslint-disable-next-line max-len
  143. // https://github.com/browserslist/browserslist/issues/431#issuecomment-565230615
  144. // caniuse-db returns { 0: "percentage" } for `and_*` regional stats
  145. if ('0' in browserUsage) {
  146. var versions = data[browser].versions
  147. browserUsage[versions[versions.length - 1]] = browserUsage[0]
  148. delete browserUsage[0]
  149. }
  150. }
  151. }
  152. module.exports = {
  153. loadQueries: function loadQueries(ctx, name) {
  154. if (!ctx.dangerousExtend && !process.env.BROWSERSLIST_DANGEROUS_EXTEND) {
  155. checkExtend(name)
  156. }
  157. var queries = require(require.resolve(name, { paths: ['.', ctx.path] }))
  158. if (queries) {
  159. if (Array.isArray(queries)) {
  160. return queries
  161. } else if (typeof queries === 'object') {
  162. if (!queries.defaults) queries.defaults = []
  163. return pickEnv(queries, ctx, name)
  164. }
  165. }
  166. throw new BrowserslistError(
  167. '`' +
  168. name +
  169. '` config exports not an array of queries' +
  170. ' or an object of envs'
  171. )
  172. },
  173. loadStat: function loadStat(ctx, name, data) {
  174. if (!ctx.dangerousExtend && !process.env.BROWSERSLIST_DANGEROUS_EXTEND) {
  175. checkExtend(name)
  176. }
  177. var stats = require(require.resolve(
  178. path.join(name, 'browserslist-stats.json'),
  179. { paths: ['.'] }
  180. ))
  181. return normalizeStats(data, stats)
  182. },
  183. getStat: function getStat(opts, data) {
  184. var stats
  185. if (opts.stats) {
  186. stats = opts.stats
  187. } else if (process.env.BROWSERSLIST_STATS) {
  188. stats = process.env.BROWSERSLIST_STATS
  189. } else if (opts.path && path.resolve && fs.existsSync) {
  190. stats = eachParent(opts.path, function (dir) {
  191. var file = path.join(dir, 'browserslist-stats.json')
  192. return isFile(file) ? file : undefined
  193. })
  194. }
  195. if (typeof stats === 'string') {
  196. try {
  197. stats = JSON.parse(fs.readFileSync(stats))
  198. } catch (e) {
  199. throw new BrowserslistError("Can't read " + stats)
  200. }
  201. }
  202. return normalizeStats(data, stats)
  203. },
  204. loadConfig: function loadConfig(opts) {
  205. if (process.env.BROWSERSLIST) {
  206. return process.env.BROWSERSLIST
  207. } else if (opts.config || process.env.BROWSERSLIST_CONFIG) {
  208. var file = opts.config || process.env.BROWSERSLIST_CONFIG
  209. if (path.basename(file) === 'package.json') {
  210. return pickEnv(parsePackage(file), opts)
  211. } else {
  212. return pickEnv(module.exports.readConfig(file), opts)
  213. }
  214. } else if (opts.path) {
  215. return pickEnv(module.exports.findConfig(opts.path), opts)
  216. } else {
  217. return undefined
  218. }
  219. },
  220. loadCountry: function loadCountry(usage, country, data) {
  221. var code = country.replace(/[^\w-]/g, '')
  222. if (!usage[code]) {
  223. var compressed
  224. try {
  225. compressed = require('caniuse-lite/data/regions/' + code + '.js')
  226. } catch (e) {
  227. throw new BrowserslistError("Unknown region name `" + code + "`.")
  228. }
  229. var usageData = region(compressed)
  230. normalizeUsageData(usageData, data)
  231. usage[country] = {}
  232. for (var i in usageData) {
  233. for (var j in usageData[i]) {
  234. usage[country][i + ' ' + j] = usageData[i][j]
  235. }
  236. }
  237. }
  238. },
  239. loadFeature: function loadFeature(features, name) {
  240. name = name.replace(/[^\w-]/g, '')
  241. if (features[name]) return
  242. var compressed
  243. try {
  244. compressed = require('caniuse-lite/data/features/' + name + '.js')
  245. } catch (e) {
  246. throw new BrowserslistError("Unknown feature name `" + name + "`.")
  247. }
  248. var stats = feature(compressed).stats
  249. features[name] = {}
  250. for (var i in stats) {
  251. for (var j in stats[i]) {
  252. features[name][i + ' ' + j] = stats[i][j]
  253. }
  254. }
  255. },
  256. parseConfig: function parseConfig(string) {
  257. var result = { defaults: [] }
  258. var sections = ['defaults']
  259. string
  260. .toString()
  261. .replace(/#[^\n]*/g, '')
  262. .split(/\n|,/)
  263. .map(function (line) {
  264. return line.trim()
  265. })
  266. .filter(function (line) {
  267. return line !== ''
  268. })
  269. .forEach(function (line) {
  270. if (IS_SECTION.test(line)) {
  271. sections = line.match(IS_SECTION)[1].trim().split(' ')
  272. sections.forEach(function (section) {
  273. if (result[section]) {
  274. throw new BrowserslistError(
  275. 'Duplicate section ' + section + ' in Browserslist config'
  276. )
  277. }
  278. result[section] = []
  279. })
  280. } else {
  281. sections.forEach(function (section) {
  282. result[section].push(line)
  283. })
  284. }
  285. })
  286. return result
  287. },
  288. readConfig: function readConfig(file) {
  289. if (!isFile(file)) {
  290. throw new BrowserslistError("Can't read " + file + ' config')
  291. }
  292. return module.exports.parseConfig(fs.readFileSync(file))
  293. },
  294. findConfig: function findConfig(from) {
  295. from = path.resolve(from)
  296. var passed = []
  297. var resolved = eachParent(from, function (dir) {
  298. if (dir in configCache) {
  299. return configCache[dir]
  300. }
  301. passed.push(dir)
  302. var config = path.join(dir, 'browserslist')
  303. var pkg = path.join(dir, 'package.json')
  304. var rc = path.join(dir, '.browserslistrc')
  305. var pkgBrowserslist
  306. if (isFile(pkg)) {
  307. try {
  308. pkgBrowserslist = parsePackage(pkg)
  309. } catch (e) {
  310. if (e.name === 'BrowserslistError') throw e
  311. console.warn(
  312. '[Browserslist] Could not parse ' + pkg + '. Ignoring it.'
  313. )
  314. }
  315. }
  316. if (isFile(config) && pkgBrowserslist) {
  317. throw new BrowserslistError(
  318. dir + ' contains both browserslist and package.json with browsers'
  319. )
  320. } else if (isFile(rc) && pkgBrowserslist) {
  321. throw new BrowserslistError(
  322. dir + ' contains both .browserslistrc and package.json with browsers'
  323. )
  324. } else if (isFile(config) && isFile(rc)) {
  325. throw new BrowserslistError(
  326. dir + ' contains both .browserslistrc and browserslist'
  327. )
  328. } else if (isFile(config)) {
  329. return module.exports.readConfig(config)
  330. } else if (isFile(rc)) {
  331. return module.exports.readConfig(rc)
  332. } else {
  333. return pkgBrowserslist
  334. }
  335. })
  336. if (!process.env.BROWSERSLIST_DISABLE_CACHE) {
  337. passed.forEach(function (dir) {
  338. configCache[dir] = resolved
  339. })
  340. }
  341. return resolved
  342. },
  343. clearCaches: function clearCaches() {
  344. dataTimeChecked = false
  345. filenessCache = {}
  346. configCache = {}
  347. this.cache = {}
  348. },
  349. oldDataWarning: function oldDataWarning(agentsObj) {
  350. if (dataTimeChecked) return
  351. dataTimeChecked = true
  352. if (process.env.BROWSERSLIST_IGNORE_OLD_DATA) return
  353. var latest = latestReleaseTime(agentsObj)
  354. var halfYearAgo = Date.now() - TIME_TO_UPDATE_CANIUSE
  355. if (latest !== 0 && latest < halfYearAgo) {
  356. console.warn(
  357. 'Browserslist: caniuse-lite is outdated. Please run:\n' +
  358. ' npx update-browserslist-db@latest\n' +
  359. ' Why you should do it regularly: ' +
  360. 'https://github.com/browserslist/update-db#readme'
  361. )
  362. }
  363. },
  364. currentNode: function currentNode() {
  365. return 'node ' + process.versions.node
  366. }
  367. }