index.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. let childProcess = require('child_process')
  2. let escalade = require('escalade/sync')
  3. let pico = require('picocolors')
  4. let path = require('path')
  5. let fs = require('fs')
  6. const { detectIndent, detectEOL } = require('./utils')
  7. function BrowserslistUpdateError(message) {
  8. this.name = 'BrowserslistUpdateError'
  9. this.message = message
  10. this.browserslist = true
  11. if (Error.captureStackTrace) {
  12. Error.captureStackTrace(this, BrowserslistUpdateError)
  13. }
  14. }
  15. BrowserslistUpdateError.prototype = Error.prototype
  16. /* c8 ignore next 3 */
  17. function defaultPrint(str) {
  18. process.stdout.write(str)
  19. }
  20. function detectLockfile() {
  21. let packageDir = escalade('.', (dir, names) => {
  22. return names.indexOf('package.json') !== -1 ? dir : ''
  23. })
  24. if (!packageDir) {
  25. throw new BrowserslistUpdateError(
  26. 'Cannot find package.json. ' +
  27. 'Is this the right directory to run `npx update-browserslist-db` in?'
  28. )
  29. }
  30. let lockfileNpm = path.join(packageDir, 'package-lock.json')
  31. let lockfileShrinkwrap = path.join(packageDir, 'npm-shrinkwrap.json')
  32. let lockfileYarn = path.join(packageDir, 'yarn.lock')
  33. let lockfilePnpm = path.join(packageDir, 'pnpm-lock.yaml')
  34. if (fs.existsSync(lockfilePnpm)) {
  35. return { mode: 'pnpm', file: lockfilePnpm }
  36. } else if (fs.existsSync(lockfileNpm)) {
  37. return { mode: 'npm', file: lockfileNpm }
  38. } else if (fs.existsSync(lockfileYarn)) {
  39. let lock = { mode: 'yarn', file: lockfileYarn }
  40. lock.content = fs.readFileSync(lock.file).toString()
  41. lock.version = /# yarn lockfile v1/.test(lock.content) ? 1 : 2
  42. return lock
  43. } else if (fs.existsSync(lockfileShrinkwrap)) {
  44. return { mode: 'npm', file: lockfileShrinkwrap }
  45. }
  46. throw new BrowserslistUpdateError(
  47. 'No lockfile found. Run "npm install", "yarn install" or "pnpm install"'
  48. )
  49. }
  50. function getLatestInfo(lock) {
  51. if (lock.mode === 'yarn') {
  52. if (lock.version === 1) {
  53. return JSON.parse(
  54. childProcess.execSync('yarn info caniuse-lite --json').toString()
  55. ).data
  56. } else {
  57. return JSON.parse(
  58. childProcess.execSync('yarn npm info caniuse-lite --json').toString()
  59. )
  60. }
  61. }
  62. if (lock.mode === 'pnpm') {
  63. return JSON.parse(
  64. childProcess.execSync('pnpm info caniuse-lite --json').toString()
  65. )
  66. }
  67. return JSON.parse(
  68. childProcess.execSync('npm show caniuse-lite --json').toString()
  69. )
  70. }
  71. function getBrowsers() {
  72. let browserslist = require('browserslist')
  73. return browserslist().reduce((result, entry) => {
  74. if (!result[entry[0]]) {
  75. result[entry[0]] = []
  76. }
  77. result[entry[0]].push(entry[1])
  78. return result
  79. }, {})
  80. }
  81. function diffBrowsers(old, current) {
  82. let browsers = Object.keys(old).concat(
  83. Object.keys(current).filter(browser => old[browser] === undefined)
  84. )
  85. return browsers
  86. .map(browser => {
  87. let oldVersions = old[browser] || []
  88. let currentVersions = current[browser] || []
  89. let common = oldVersions.filter(v => currentVersions.includes(v))
  90. let added = currentVersions.filter(v => !common.includes(v))
  91. let removed = oldVersions.filter(v => !common.includes(v))
  92. return removed
  93. .map(v => pico.red('- ' + browser + ' ' + v))
  94. .concat(added.map(v => pico.green('+ ' + browser + ' ' + v)))
  95. })
  96. .reduce((result, array) => result.concat(array), [])
  97. .join('\n')
  98. }
  99. function updateNpmLockfile(lock, latest) {
  100. let metadata = { latest, versions: [] }
  101. let content = deletePackage(JSON.parse(lock.content), metadata)
  102. metadata.content = JSON.stringify(content, null, detectIndent(lock.content))
  103. return metadata
  104. }
  105. function deletePackage(node, metadata) {
  106. if (node.dependencies) {
  107. if (node.dependencies['caniuse-lite']) {
  108. let version = node.dependencies['caniuse-lite'].version
  109. metadata.versions[version] = true
  110. delete node.dependencies['caniuse-lite']
  111. }
  112. for (let i in node.dependencies) {
  113. node.dependencies[i] = deletePackage(node.dependencies[i], metadata)
  114. }
  115. }
  116. return node
  117. }
  118. let yarnVersionRe = /version "(.*?)"/
  119. function updateYarnLockfile(lock, latest) {
  120. let blocks = lock.content.split(/(\n{2,})/).map(block => {
  121. return block.split('\n')
  122. })
  123. let versions = {}
  124. blocks.forEach(lines => {
  125. if (lines[0].indexOf('caniuse-lite@') !== -1) {
  126. let match = yarnVersionRe.exec(lines[1])
  127. versions[match[1]] = true
  128. if (match[1] !== latest.version) {
  129. lines[1] = lines[1].replace(
  130. /version "[^"]+"/,
  131. 'version "' + latest.version + '"'
  132. )
  133. lines[2] = lines[2].replace(
  134. /resolved "[^"]+"/,
  135. 'resolved "' + latest.dist.tarball + '"'
  136. )
  137. if (lines.length === 4) {
  138. lines[3] = latest.dist.integrity
  139. ? lines[3].replace(
  140. /integrity .+/,
  141. 'integrity ' + latest.dist.integrity
  142. )
  143. : ''
  144. }
  145. }
  146. }
  147. })
  148. let content = blocks.map(lines => lines.join('\n')).join('')
  149. return { content, versions }
  150. }
  151. function updateLockfile(lock, latest) {
  152. if (!lock.content) lock.content = fs.readFileSync(lock.file).toString()
  153. let updatedLockFile
  154. if (lock.mode === 'yarn') {
  155. updatedLockFile = updateYarnLockfile(lock, latest)
  156. } else {
  157. updatedLockFile = updateNpmLockfile(lock, latest)
  158. }
  159. updatedLockFile.content = updatedLockFile.content.replace(
  160. /\n/g,
  161. detectEOL(lock.content)
  162. )
  163. return updatedLockFile
  164. }
  165. function updatePackageManually(print, lock, latest) {
  166. let lockfileData = updateLockfile(lock, latest)
  167. let caniuseVersions = Object.keys(lockfileData.versions).sort()
  168. if (caniuseVersions.length === 1 && caniuseVersions[0] === latest.version) {
  169. print(
  170. 'Installed version: ' +
  171. pico.bold(pico.green(latest.version)) +
  172. '\n' +
  173. pico.bold(pico.green('caniuse-lite is up to date')) +
  174. '\n'
  175. )
  176. return
  177. }
  178. if (caniuseVersions.length === 0) {
  179. caniuseVersions[0] = 'none'
  180. }
  181. print(
  182. 'Installed version' +
  183. (caniuseVersions.length === 1 ? ': ' : 's: ') +
  184. pico.bold(pico.red(caniuseVersions.join(', '))) +
  185. '\n' +
  186. 'Removing old caniuse-lite from lock file\n'
  187. )
  188. fs.writeFileSync(lock.file, lockfileData.content)
  189. let install = lock.mode === 'yarn' ? 'yarn add -W' : lock.mode + ' install'
  190. print(
  191. 'Installing new caniuse-lite version\n' +
  192. pico.yellow('$ ' + install + ' caniuse-lite') +
  193. '\n'
  194. )
  195. try {
  196. childProcess.execSync(install + ' caniuse-lite')
  197. } catch (e) /* c8 ignore start */ {
  198. print(
  199. pico.red(
  200. '\n' +
  201. e.stack +
  202. '\n\n' +
  203. 'Problem with `' +
  204. install +
  205. ' caniuse-lite` call. ' +
  206. 'Run it manually.\n'
  207. )
  208. )
  209. process.exit(1)
  210. } /* c8 ignore end */
  211. let del = lock.mode === 'yarn' ? 'yarn remove -W' : lock.mode + ' uninstall'
  212. print(
  213. 'Cleaning package.json dependencies from caniuse-lite\n' +
  214. pico.yellow('$ ' + del + ' caniuse-lite') +
  215. '\n'
  216. )
  217. childProcess.execSync(del + ' caniuse-lite')
  218. }
  219. function updateWith(print, cmd) {
  220. print('Updating caniuse-lite version\n' + pico.yellow('$ ' + cmd) + '\n')
  221. try {
  222. childProcess.execSync(cmd)
  223. } catch (e) /* c8 ignore start */ {
  224. print(pico.red(e.stdout.toString()))
  225. print(
  226. pico.red(
  227. '\n' +
  228. e.stack +
  229. '\n\n' +
  230. 'Problem with `' +
  231. cmd +
  232. '` call. ' +
  233. 'Run it manually.\n'
  234. )
  235. )
  236. process.exit(1)
  237. } /* c8 ignore end */
  238. }
  239. module.exports = function updateDB(print = defaultPrint) {
  240. let lock = detectLockfile()
  241. let latest = getLatestInfo(lock)
  242. let listError
  243. let oldList
  244. try {
  245. oldList = getBrowsers()
  246. } catch (e) {
  247. listError = e
  248. }
  249. print('Latest version: ' + pico.bold(pico.green(latest.version)) + '\n')
  250. if (lock.mode === 'yarn' && lock.version !== 1) {
  251. updateWith(print, 'yarn up -R caniuse-lite')
  252. } else if (lock.mode === 'pnpm') {
  253. updateWith(print, 'pnpm up caniuse-lite')
  254. } else {
  255. updatePackageManually(print, lock, latest)
  256. }
  257. print('caniuse-lite has been successfully updated\n')
  258. let newList
  259. if (!listError) {
  260. try {
  261. newList = getBrowsers()
  262. } catch (e) /* c8 ignore start */ {
  263. listError = e
  264. } /* c8 ignore end */
  265. }
  266. if (listError) {
  267. print(
  268. pico.red(
  269. '\n' +
  270. listError.stack +
  271. '\n\n' +
  272. 'Problem with browser list retrieval.\n' +
  273. 'Target browser changes won’t be shown.\n'
  274. )
  275. )
  276. } else {
  277. let changes = diffBrowsers(oldList, newList)
  278. if (changes) {
  279. print('\nTarget browser changes:\n')
  280. print(changes + '\n')
  281. } else {
  282. print('\n' + pico.green('No target browser changes') + '\n')
  283. }
  284. }
  285. }