node.js 12 KB

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