node.js 11 KB

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