upload-to-cdn.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. #!/usr/bin/env node
  2. // Upload Uppy releases to Edgly.net CDN. Copyright (c) 2018, Transloadit Ltd.
  3. //
  4. // This file:
  5. //
  6. // - Assumes EDGLY_KEY and EDGLY_SECRET are available (e.g. set via Travis secrets)
  7. // - Assumes a fully built uppy is in root dir (unless a specific tag was specified, then it's fetched from npm)
  8. // - Collects dist/ files that would be in an npm package release, and uploads to
  9. // eg. https://releases.transloadit.com/uppy/v1.0.1/uppy.css
  10. // - Uses local package by default, if [version] argument was specified, takes package from npm
  11. //
  12. // Run as:
  13. //
  14. // npm run uploadcdn <package-name> [version]
  15. //
  16. // To override an existing release (DANGER!)
  17. //
  18. // npm run uploadcdn <package-name> [version] -- --force
  19. //
  20. // Authors:
  21. //
  22. // - Kevin van Zonneveld <kevin@transloadit.com>
  23. const path = require('path')
  24. const AWS = require('aws-sdk')
  25. const packlist = require('npm-packlist')
  26. const tar = require('tar')
  27. const pacote = require('pacote')
  28. const concat = require('concat-stream')
  29. const mime = require('mime-types')
  30. const { promisify } = require('util')
  31. const readFile = promisify(require('fs').readFile)
  32. const finished = promisify(require('stream').finished)
  33. const AdmZip = require('adm-zip')
  34. function delay (ms) {
  35. return new Promise(resolve => setTimeout(resolve, ms))
  36. }
  37. const AWS_REGION = 'us-east-1'
  38. const AWS_BUCKET = 'releases.transloadit.com'
  39. /**
  40. * Get remote dist/ files by fetching the tarball for the given version
  41. from npm and filtering it down to package/dist/ files.
  42. *
  43. * @param {string} packageName eg. @uppy/robodog
  44. * @param {string} version eg. 1.8.0
  45. * @returns a Map<string, Buffer>, filename → content
  46. */
  47. async function getRemoteDistFiles (packageName, version) {
  48. const files = new Map()
  49. const tarball = pacote.tarball.stream(`${packageName}@${version}`)
  50. .pipe(new tar.Parse())
  51. tarball.on('entry', (readEntry) => {
  52. if (readEntry.path.startsWith('package/dist/')) {
  53. readEntry
  54. .pipe(concat((buf) => {
  55. files.set(readEntry.path.replace(/^package\/dist\//, ''), buf)
  56. }))
  57. .on('error', (err) => {
  58. tarball.emit('error', err)
  59. })
  60. } else {
  61. readEntry.resume()
  62. }
  63. })
  64. await finished(tarball)
  65. return files
  66. }
  67. /**
  68. * Get local dist/ files by asking npm-packlist what files would be added
  69. * to an npm package during publish, and filtering those down to just dist/ files.
  70. *
  71. * @param {string} packagePath Base file path of the package, eg. ./packages/@uppy/locales
  72. * @returns a Map<string, Buffer>, filename → content
  73. */
  74. async function getLocalDistFiles (packagePath) {
  75. const files = (await packlist({ path: packagePath }))
  76. .filter(f => f.startsWith('dist/'))
  77. .map(f => f.replace(/^dist\//, ''))
  78. const entries = await Promise.all(
  79. files.map(async (f) => [
  80. f,
  81. await readFile(path.join(packagePath, 'dist', f)),
  82. ])
  83. )
  84. return new Map(entries)
  85. }
  86. async function main (packageName, version) {
  87. if (!packageName) {
  88. console.error('usage: upload-to-cdn <packagename> [version]')
  89. console.error('Must provide a package name')
  90. process.exit(1)
  91. }
  92. if (!process.env.EDGLY_KEY || !process.env.EDGLY_SECRET) {
  93. console.error('Missing EDGLY_KEY or EDGLY_SECRET env variables, bailing')
  94. process.exit(1)
  95. }
  96. // version should only be a positional arg and semver string
  97. // this deals with usage like `npm run uploadcdn uppy -- --force`
  98. // where we force push a local build
  99. if (version && version.startsWith('-')) version = undefined
  100. const s3 = new AWS.S3({
  101. credentials: new AWS.Credentials({
  102. accessKeyId: process.env.EDGLY_KEY,
  103. secretAccessKey: process.env.EDGLY_SECRET,
  104. }),
  105. region: AWS_REGION,
  106. })
  107. const remote = !!version
  108. if (!remote) {
  109. version = require(`../packages/${packageName}/package.json`).version
  110. }
  111. // Warn if uploading a local build not from CI:
  112. // - If we're on CI, this should be a release commit.
  113. // - If we're local, normally we should upload a released version, not a local build.
  114. if (!remote && !process.env.CI) {
  115. console.log('Warning, writing a local build to the CDN, this is usually not what you want. Sleeping 3s. Press CTRL+C!')
  116. await delay(3000)
  117. }
  118. const packagePath = remote
  119. ? `${packageName}@${version}`
  120. : path.join(__dirname, '..', 'packages', packageName)
  121. // uppy → releases/uppy/
  122. // @uppy/robodog → releases/uppy/robodog/
  123. // @uppy/locales → releases/uppy/locales/
  124. const dirName = packageName.startsWith('@uppy/')
  125. ? packageName.replace(/^@/, '')
  126. : 'uppy'
  127. const outputPath = path.posix.join(dirName, `v${version}`)
  128. const { Contents: existing } = await s3.listObjects({
  129. Bucket: AWS_BUCKET,
  130. Prefix: outputPath,
  131. }).promise()
  132. if (existing.length > 0) {
  133. if (process.argv.includes('--force')) {
  134. console.warn(`WARN Release files for ${dirName} v${version} already exist, overwriting...`)
  135. } else {
  136. console.error(`Release files for ${dirName} v${version} already exist, exiting...`)
  137. process.exit(1)
  138. }
  139. }
  140. const files = remote
  141. ? await getRemoteDistFiles(packageName, version)
  142. : await getLocalDistFiles(packagePath)
  143. if (packageName === 'uppy') {
  144. // Create downloadable zip archive
  145. const zip = new AdmZip()
  146. for (const [filename, buffer] of files.entries()) {
  147. zip.addFile(filename, buffer)
  148. }
  149. files.set(`uppy-v${version}.zip`, zip.toBuffer())
  150. }
  151. for (const [filename, buffer] of files.entries()) {
  152. const key = path.posix.join(outputPath, filename)
  153. console.log(`pushing s3://${AWS_BUCKET}/${key}`)
  154. await s3.putObject({
  155. Bucket: AWS_BUCKET,
  156. Key: key,
  157. ContentType: mime.lookup(filename),
  158. Body: buffer,
  159. }).promise()
  160. }
  161. }
  162. main(...process.argv.slice(2)).catch((err) => {
  163. console.error(err.stack)
  164. process.exit(1)
  165. })