inject.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. const fs = require('fs')
  2. const path = require('path')
  3. const chalk = require('chalk')
  4. const { spawn } = require('child_process')
  5. const readline = require('readline')
  6. const YAML = require('js-yaml')
  7. const { promisify } = require('util')
  8. const gzipSize = require('gzip-size')
  9. const prettierBytes = require('@transloadit/prettier-bytes')
  10. const browserify = require('browserify')
  11. const touch = require('touch')
  12. const glob = require('glob')
  13. const { minify } = require('terser')
  14. const webRoot = __dirname
  15. const uppyRoot = path.join(__dirname, '../packages/uppy')
  16. const robodogRoot = path.join(__dirname, '../packages/@uppy/robodog')
  17. const localesRoot = path.join(__dirname, '../packages/@uppy/locales')
  18. const configPath = path.join(webRoot, '/themes/uppy/_config.yml')
  19. const { version } = require(path.join(uppyRoot, '/package.json'))
  20. const regionalDisplayNames = new Intl.DisplayNames('en-US', { type: 'region' })
  21. const languageDisplayNames = new Intl.DisplayNames('en-US', { type: 'language' })
  22. const defaultConfig = {
  23. comment: 'Auto updated by inject.js',
  24. uppy_version_anchor: '001',
  25. uppy_version: '0.0.1',
  26. uppy_bundle_kb_sizes: {},
  27. config: {},
  28. }
  29. // Keeping a whitelist so utils etc are excluded
  30. // It may be easier to maintain a blacklist instead
  31. const packages = [
  32. // Bundles
  33. 'uppy',
  34. '@uppy/robodog',
  35. // Integrations
  36. '@uppy/react',
  37. // Core
  38. '@uppy/core',
  39. // Plugins -- please keep these sorted alphabetically
  40. '@uppy/aws-s3',
  41. '@uppy/aws-s3-multipart',
  42. '@uppy/dashboard',
  43. '@uppy/drag-drop',
  44. '@uppy/dropbox',
  45. '@uppy/file-input',
  46. '@uppy/form',
  47. '@uppy/golden-retriever',
  48. '@uppy/google-drive',
  49. '@uppy/informer',
  50. '@uppy/instagram',
  51. '@uppy/image-editor',
  52. '@uppy/progress-bar',
  53. '@uppy/screen-capture',
  54. '@uppy/status-bar',
  55. '@uppy/thumbnail-generator',
  56. '@uppy/transloadit',
  57. '@uppy/tus',
  58. '@uppy/url',
  59. '@uppy/webcam',
  60. '@uppy/xhr-upload',
  61. '@uppy/drop-target',
  62. // Stores
  63. '@uppy/store-default',
  64. '@uppy/store-redux',
  65. ]
  66. const excludes = {
  67. '@uppy/react': ['react'],
  68. }
  69. inject().catch((err) => {
  70. console.error(err)
  71. process.exit(1)
  72. })
  73. async function getMinifiedSize (pkg, name) {
  74. const b = browserify(pkg)
  75. const packageJSON = fs.readFileSync(path.join(pkg, 'package.json'))
  76. const { version } = JSON.parse(packageJSON)
  77. if (name !== '@uppy/core' && name !== 'uppy') {
  78. b.exclude('@uppy/core')
  79. // Already unconditionally included through @uppy/core
  80. b.exclude('preact')
  81. }
  82. if (excludes[name]) {
  83. b.exclude(excludes[name])
  84. }
  85. const { code:bundle } = await promisify(b.bundle).call(b).then(buf => minify(buf.toString(), { toplevel: true }))
  86. const gzipped = await gzipSize(bundle)
  87. return {
  88. minified: bundle.length,
  89. gzipped,
  90. version,
  91. }
  92. }
  93. async function injectSizes (config) {
  94. console.info(chalk.grey('Generating bundle sizes…'))
  95. const padTarget = Math.max(...packages.map((cur) => cur.length)) + 2
  96. const sizesPromise = Promise.all(
  97. packages.map(async (pkg) => {
  98. const result = await getMinifiedSize(path.join(__dirname, '../packages', pkg), pkg)
  99. console.info(chalk.green(
  100. // ✓ @uppy/pkgname: 10.0 kB min / 2.0 kB gz
  101. ` ✓ ${pkg}: ${' '.repeat(padTarget - pkg.length)}${
  102. `${prettierBytes(result.minified)} min`.padEnd(10)
  103. } / ${prettierBytes(result.gzipped)} gz`
  104. ))
  105. return [pkg, {
  106. ...result,
  107. prettyMinified: prettierBytes(result.minified),
  108. prettyGzipped: prettierBytes(result.gzipped),
  109. }]
  110. })
  111. ).then(Object.fromEntries)
  112. config.uppy_bundle_kb_sizes = await sizesPromise
  113. }
  114. const sourceUppy = path.join(webRoot, '/themes/uppy/source/uppy/')
  115. const sourceUppyLocales = path.join(sourceUppy, 'locales')
  116. async function injectBundles () {
  117. await Promise.all([
  118. fs.promises.mkdir(sourceUppy, { recursive:true }),
  119. fs.promises.mkdir(sourceUppyLocales, { recursive:true }),
  120. ])
  121. const cmds = [
  122. `cp -vfR ${path.join(uppyRoot, '/dist/*')} ${sourceUppy}`,
  123. `cp -vfR ${path.join(robodogRoot, '/dist/*')} ${sourceUppy}`,
  124. `cp -vfR ${path.join(localesRoot, '/dist/*')} ${sourceUppyLocales}`,
  125. ].join(' && ')
  126. const cp = spawn(cmds, { stdio:['ignore', 'pipe', 'inherit'], shell: true })
  127. await Promise.race([
  128. new Promise((resolve, reject) => cp.on('error', reject)),
  129. (async () => {
  130. const stdout = readline.createInterface({
  131. input: cp.stdout,
  132. })
  133. for await (const line of stdout) {
  134. console.info(chalk.green('✓ injected: '), chalk.grey(line))
  135. }
  136. })(),
  137. ])
  138. }
  139. // re-enable after rate limiter issue is fixed
  140. //
  141. async function injectGhStars () {
  142. const opts = {}
  143. if ('GITHUB_TOKEN' in process.env) {
  144. opts.auth = process.env.GITHUB_TOKEN
  145. }
  146. const { Octokit } = require('@octokit/rest')
  147. const octokit = new Octokit(opts)
  148. const { headers, data } = await octokit.repos.get({
  149. owner: 'transloadit',
  150. repo: 'uppy',
  151. })
  152. console.log(`${headers['x-ratelimit-remaining']} requests remaining until we hit GitHub ratelimiter`)
  153. const dstpath = path.join(webRoot, 'themes', 'uppy', 'layout', 'partials', 'generated_stargazers.ejs')
  154. fs.writeFileSync(dstpath, String(data.stargazers_count), 'utf-8')
  155. console.log(`${data.stargazers_count} stargazers written to '${dstpath}'`)
  156. }
  157. async function injectMarkdown () {
  158. const sources = {
  159. '.github/ISSUE_TEMPLATE/integration_help.md': 'src/_template/integration_help.md',
  160. '.github/CONTRIBUTING.md': 'src/_template/contributing.md',
  161. }
  162. for (const src in sources) {
  163. const dst = sources[src]
  164. // strip yaml frontmatter:
  165. const srcpath = path.join(uppyRoot, `/../../${src}`)
  166. const dstpath = path.join(webRoot, dst)
  167. const parts = fs.readFileSync(srcpath, 'utf-8').split(/---\s*\n/)
  168. if (parts.length >= 3) {
  169. parts.shift()
  170. parts.shift()
  171. }
  172. let content = `<!-- WARNING! This file was injected. Please edit in "${src}" instead and run "${path.basename(__filename)}" -->\n\n`
  173. content += parts.join('---\n')
  174. fs.writeFileSync(dstpath, content, 'utf-8')
  175. console.info(chalk.green('✓ injected: '), chalk.grey(srcpath))
  176. }
  177. touch(path.join(webRoot, '/src/support.md'))
  178. }
  179. function injectLocaleList () {
  180. const mdTable = [
  181. `<!-- WARNING! This file was automatically injected. Please run "${path.basename(__filename)}" to re-generate -->\n\n`,
  182. '| %count% Locales | NPM | CDN | Source on GitHub |',
  183. '| --------------- | ------------------ | ------------------- | ---------------- |',
  184. ]
  185. const mdRows = []
  186. const localeList = {}
  187. const localePackagePath = path.join(localesRoot, 'src', '*.js')
  188. const localePackageVersion = require(path.join(localesRoot, 'package.json')).version
  189. glob.sync(localePackagePath).forEach((localePath) => {
  190. const localeName = path.basename(localePath, '.js')
  191. const [languageCode, regionCode, variant] = localeName.split(/[-_]/)
  192. const languageName = languageDisplayNames.of(languageCode)
  193. const regionName = regionalDisplayNames.of(regionCode)
  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://releases.transloadit.com/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>${regionName}</small>${variant ? `<br /><small>(${variant})</small>` : ''} | ${npmPath} | ${cdnPath} | ✏️ ${githubSource} |`
  198. mdRows.push(mdTableRow)
  199. localeList[localeName] = `${languageName} (${regionName}${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 fs.promises.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 = { ...defaultConfig, ...config }
  226. await fs.promises.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. }