index.js 8.8 KB

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