inject.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. const fs = require('fs')
  2. const path = require('path')
  3. const chalk = require('chalk')
  4. const { exec } = require('child_process')
  5. const YAML = require('js-yaml')
  6. const { promisify } = require('util')
  7. const gzipSize = require('gzip-size')
  8. const prettierBytes = require('@transloadit/prettier-bytes')
  9. const browserify = require('browserify')
  10. const touch = require('touch')
  11. const glob = require('glob')
  12. const LocaleCode = require('locale-code')
  13. const webRoot = __dirname
  14. const uppyRoot = path.join(__dirname, '../packages/uppy')
  15. const robodogRoot = path.join(__dirname, '../packages/@uppy/robodog')
  16. const localesRoot = path.join(__dirname, '../packages/@uppy/locales')
  17. const configPath = path.join(webRoot, '/themes/uppy/_config.yml')
  18. const { version } = require(path.join(uppyRoot, '/package.json'))
  19. const defaultConfig = {
  20. comment: 'Auto updated by inject.js',
  21. uppy_version_anchor: '001',
  22. uppy_version: '0.0.1',
  23. uppy_bundle_kb_sizes: {},
  24. config: {}
  25. }
  26. // Keeping a whitelist so utils etc are excluded
  27. // It may be easier to maintain a blacklist instead
  28. const packages = [
  29. // Bundles
  30. 'uppy',
  31. '@uppy/robodog',
  32. // Integrations
  33. '@uppy/react',
  34. // Core
  35. '@uppy/core',
  36. // Plugins -- please keep these sorted alphabetically
  37. '@uppy/aws-s3',
  38. '@uppy/aws-s3-multipart',
  39. '@uppy/dashboard',
  40. '@uppy/drag-drop',
  41. '@uppy/dropbox',
  42. '@uppy/file-input',
  43. '@uppy/form',
  44. '@uppy/golden-retriever',
  45. '@uppy/google-drive',
  46. '@uppy/informer',
  47. '@uppy/instagram',
  48. '@uppy/progress-bar',
  49. '@uppy/screen-capture',
  50. '@uppy/status-bar',
  51. '@uppy/thumbnail-generator',
  52. '@uppy/transloadit',
  53. '@uppy/tus',
  54. '@uppy/url',
  55. '@uppy/webcam',
  56. '@uppy/xhr-upload',
  57. // Stores
  58. '@uppy/store-default',
  59. '@uppy/store-redux'
  60. ]
  61. const excludes = {
  62. '@uppy/react': ['react']
  63. }
  64. inject().catch((err) => {
  65. console.error(err)
  66. process.exit(1)
  67. })
  68. async function getMinifiedSize (pkg, name) {
  69. const b = browserify(pkg)
  70. const packageJSON = fs.readFileSync(path.join(pkg, 'package.json'))
  71. const version = JSON.parse(packageJSON).version
  72. if (name !== '@uppy/core' && name !== 'uppy') {
  73. b.exclude('@uppy/core')
  74. // Already unconditionally included through @uppy/core
  75. b.exclude('preact')
  76. }
  77. if (excludes[name]) {
  78. b.exclude(excludes[name])
  79. }
  80. b.plugin('tinyify')
  81. const bundle = await promisify(b.bundle).call(b)
  82. const gzipped = await gzipSize(bundle)
  83. return {
  84. minified: bundle.length,
  85. gzipped,
  86. version
  87. }
  88. }
  89. async function injectSizes (config) {
  90. console.info(chalk.grey('Generating bundle sizes…'))
  91. const padTarget = packages.reduce((max, cur) => Math.max(max, cur.length), 0) + 2
  92. const sizesPromise = Promise.all(
  93. packages.map(async (pkg) => {
  94. const result = await getMinifiedSize(path.join(__dirname, '../packages', pkg), pkg)
  95. console.info(chalk.green(
  96. // ✓ @uppy/pkgname: 10.0 kB min / 2.0 kB gz
  97. ` ✓ ${pkg}: ${' '.repeat(padTarget - pkg.length)}` +
  98. `${prettierBytes(result.minified)} min`.padEnd(10) +
  99. ` / ${prettierBytes(result.gzipped)} gz`
  100. ))
  101. return Object.assign(result, {
  102. prettyMinified: prettierBytes(result.minified),
  103. prettyGzipped: prettierBytes(result.gzipped)
  104. })
  105. })
  106. ).then((list) => {
  107. const map = {}
  108. list.forEach((size, i) => {
  109. map[packages[i]] = size
  110. })
  111. return map
  112. })
  113. config.uppy_bundle_kb_sizes = await sizesPromise
  114. }
  115. async function injectBundles () {
  116. const cmds = [
  117. `mkdir -p ${path.join(webRoot, '/themes/uppy/source/uppy')}`,
  118. `mkdir -p ${path.join(webRoot, '/themes/uppy/source/uppy/locales')}`,
  119. `cp -vfR ${path.join(uppyRoot, '/dist/*')} ${path.join(webRoot, '/themes/uppy/source/uppy/')}`,
  120. `cp -vfR ${path.join(robodogRoot, '/dist/*')} ${path.join(webRoot, '/themes/uppy/source/uppy/')}`,
  121. `cp -vfR ${path.join(localesRoot, '/dist/*')} ${path.join(webRoot, '/themes/uppy/source/uppy/locales')}`
  122. ].join(' && ')
  123. const { stdout } = await promisify(exec)(cmds)
  124. stdout.trim().split('\n').forEach(function (line) {
  125. console.info(chalk.green('✓ injected: '), chalk.grey(line))
  126. })
  127. }
  128. // re-enable after rate limiter issue is fixed
  129. //
  130. async function injectGhStars () {
  131. const opts = {}
  132. if ('GITHUB_TOKEN' in process.env) {
  133. opts.auth = process.env.GITHUB_TOKEN
  134. }
  135. const { Octokit } = require('@octokit/rest')
  136. const octokit = new Octokit(opts)
  137. const { headers, data } = await octokit.repos.get({
  138. owner: 'transloadit',
  139. repo: 'uppy'
  140. })
  141. console.log(`${headers['x-ratelimit-remaining']} requests remaining until we hit GitHub ratelimiter`)
  142. const dstpath = path.join(webRoot, 'themes', 'uppy', 'layout', 'partials', 'generated_stargazers.ejs')
  143. fs.writeFileSync(dstpath, String(data.stargazers_count), 'utf-8')
  144. console.log(`${data.stargazers_count} stargazers written to '${dstpath}'`)
  145. }
  146. async function injectMarkdown () {
  147. const sources = {
  148. '.github/ISSUE_TEMPLATE/integration_help.md': 'src/_template/integration_help.md',
  149. '.github/CONTRIBUTING.md': 'src/_template/contributing.md'
  150. }
  151. for (const src in sources) {
  152. const dst = sources[src]
  153. // strip yaml frontmatter:
  154. const srcpath = path.join(uppyRoot, `/../../${src}`)
  155. const dstpath = path.join(webRoot, dst)
  156. const parts = fs.readFileSync(srcpath, 'utf-8').split(/---\s*\n/)
  157. if (parts.length >= 3) {
  158. parts.shift()
  159. parts.shift()
  160. }
  161. let content = `<!-- WARNING! This file was injected. Please edit in "${src}" instead and run "${path.basename(__filename)}" -->\n\n`
  162. content += parts.join('---\n')
  163. fs.writeFileSync(dstpath, content, 'utf-8')
  164. console.info(chalk.green('✓ injected: '), chalk.grey(srcpath))
  165. }
  166. touch(path.join(webRoot, '/src/support.md'))
  167. }
  168. function injectLocaleList () {
  169. const mdTable = [
  170. `<!-- WARNING! This file was automatically injected. Please run "${path.basename(__filename)}" to re-generate -->\n\n`,
  171. '| %count% Locales | NPM | CDN | Source on GitHub |',
  172. '| --------------- | ------------------ | ------------------- | ---------------- |'
  173. ]
  174. const mdRows = []
  175. const localeList = {}
  176. const localePackagePath = path.join(localesRoot, 'src', '*.js')
  177. const localePackageVersion = require(path.join(localesRoot, 'package.json')).version
  178. glob.sync(localePackagePath).forEach((localePath) => {
  179. const localeName = path.basename(localePath, '.js')
  180. // we renamed the es_GL → gl_ES locale, and kept the old name
  181. // for backwards-compat, see https://github.com/transloadit/uppy/pull/1929
  182. if (localeName === 'es_GL') return
  183. let localeNameWithDash = localeName.replace(/_/g, '-')
  184. const parts = localeNameWithDash.split('-')
  185. let variant = ''
  186. if (parts.length > 2) {
  187. const lang = parts.shift()
  188. const country = parts.shift()
  189. variant = parts.join(', ')
  190. localeNameWithDash = `${lang}-${country}`
  191. }
  192. const languageName = LocaleCode.getLanguageName(localeNameWithDash)
  193. const countryName = LocaleCode.getCountryName(localeNameWithDash)
  194. const npmPath = `<code class="raw"><a href="https://www.npmjs.com/package/@uppy/locales">@uppy/locales</a>/lib/${localeName}</code>`
  195. const cdnPath = `[\`${localeName}.min.js\`](https://transloadit.edgly.net/releases/uppy/locales/v${localePackageVersion}/${localeName}.min.js)`
  196. const githubSource = `[\`${localeName}.js\`](https://github.com/transloadit/uppy/blob/master/packages/%40uppy/locales/src/${localeName}.js)`
  197. const mdTableRow = `| ${languageName}<br/> <small>${countryName}</small>${variant ? `<br /><small>(${variant})</small>` : ''} | ${npmPath} | ${cdnPath} | ✏️ ${githubSource} |`
  198. mdRows.push(mdTableRow)
  199. localeList[localeName] = `${languageName} (${countryName}${variant ? ` ${variant}` : ''})`
  200. })
  201. const resultingMdTable = mdTable.concat(mdRows.sort()).join('\n').replace('%count%', mdRows.length)
  202. const dstpath = path.join(webRoot, 'src', '_template', 'list_of_locale_packs.md')
  203. const localeListDstPath = path.join(webRoot, 'src', 'examples', 'locale_list.json')
  204. fs.writeFileSync(dstpath, resultingMdTable, 'utf-8')
  205. console.info(chalk.green('✓ injected: '), chalk.grey(dstpath))
  206. fs.writeFileSync(localeListDstPath, JSON.stringify(localeList), 'utf-8')
  207. console.info(chalk.green('✓ injected: '), chalk.grey(localeListDstPath))
  208. }
  209. async function readConfig () {
  210. try {
  211. const buf = await promisify(fs.readFile)(configPath, 'utf8')
  212. return YAML.safeLoad(buf)
  213. } catch (err) {
  214. return {}
  215. }
  216. }
  217. async function inject () {
  218. const config = await readConfig()
  219. await injectGhStars()
  220. await injectMarkdown()
  221. injectLocaleList()
  222. config.uppy_version = version
  223. config.uppy_version_anchor = version.replace(/[^\d]+/g, '')
  224. await injectSizes(config)
  225. const saveConfig = Object.assign({}, defaultConfig, config)
  226. await promisify(fs.writeFile)(configPath, YAML.safeDump(saveConfig), 'utf-8')
  227. console.info(chalk.green('✓ rewritten: '), chalk.grey(configPath))
  228. try {
  229. await injectBundles()
  230. } catch (error) {
  231. console.error(
  232. chalk.red('x failed to inject: '),
  233. chalk.grey('uppy bundle into site, because: ' + error)
  234. )
  235. process.exit(1)
  236. }
  237. }