inject.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. const fs = require('node:fs')
  2. const path = require('node:path')
  3. const chalk = require('chalk')
  4. const { spawn } = require('node:child_process')
  5. const readline = require('node:readline')
  6. const YAML = require('js-yaml')
  7. const gzipSize = require('gzip-size')
  8. const prettierBytes = require('@transloadit/prettier-bytes')
  9. const esbuild = require('esbuild')
  10. const touch = require('touch')
  11. const glob = require('glob')
  12. const webRoot = __dirname
  13. const uppyRoot = path.join(__dirname, '../packages/uppy')
  14. const localesRoot = path.join(__dirname, '../packages/@uppy/locales')
  15. const configPath = path.join(webRoot, '/themes/uppy/_config.yml')
  16. // eslint-disable-next-line import/no-dynamic-require
  17. const { version } = require(path.join(uppyRoot, '/package.json'))
  18. const regionalDisplayNames = new Intl.DisplayNames('en-US', { type: 'region' })
  19. const languageDisplayNames = new Intl.DisplayNames('en-US', { type: 'language' })
  20. const defaultConfig = {
  21. comment: 'Auto updated by inject.js',
  22. uppy_version_anchor: '001',
  23. uppy_version: '0.0.1',
  24. uppy_bundle_kb_sizes: {},
  25. config: {},
  26. }
  27. // Keeping a whitelist so utils etc are excluded
  28. // It may be easier to maintain a blacklist instead
  29. const packages = [
  30. // Bundles
  31. 'uppy',
  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/image-editor',
  49. '@uppy/progress-bar',
  50. '@uppy/screen-capture',
  51. '@uppy/status-bar',
  52. '@uppy/thumbnail-generator',
  53. '@uppy/transloadit',
  54. '@uppy/tus',
  55. '@uppy/url',
  56. '@uppy/webcam',
  57. '@uppy/xhr-upload',
  58. '@uppy/drop-target',
  59. // Stores
  60. '@uppy/store-default',
  61. '@uppy/store-redux',
  62. ]
  63. const excludes = {
  64. '@uppy/react': ['react'],
  65. }
  66. // eslint-disable-next-line no-use-before-define
  67. inject().catch((err) => {
  68. console.error(err)
  69. process.exit(1)
  70. })
  71. async function getMinifiedSize (pkg, name) {
  72. const packageJSON = fs.readFileSync(path.join(pkg, 'package.json'))
  73. // eslint-disable-next-line no-shadow
  74. const { main, version } = JSON.parse(packageJSON)
  75. const external = excludes[name] ?? []
  76. if (name !== '@uppy/core' && name !== 'uppy') {
  77. // Preact is already unconditionally included through @uppy/core
  78. external.unshift('@uppy/core', 'preact')
  79. }
  80. const { outputFiles:[{ contents: bundle }] } = await esbuild.build({
  81. write: false,
  82. bundle: true,
  83. entryPoints: [path.resolve(pkg, main)],
  84. minify: true,
  85. external,
  86. })
  87. const gzipped = await gzipSize(bundle)
  88. return {
  89. minified: bundle.length,
  90. gzipped,
  91. version,
  92. }
  93. }
  94. async function injectSizes (config) {
  95. console.info(chalk.grey('Generating bundle sizes…'))
  96. const padTarget = Math.max(...packages.map((cur) => cur.length)) + 2
  97. const sizesPromise = Promise.all(
  98. packages.map(async (pkg) => {
  99. const result = await getMinifiedSize(path.join(__dirname, '../packages', pkg), pkg)
  100. console.info(chalk.green(
  101. // ✓ @uppy/pkgname: 10.0 kB min / 2.0 kB gz
  102. ` ✓ ${pkg}: ${' '.repeat(padTarget - pkg.length)}${
  103. `${prettierBytes(result.minified)} min`.padEnd(10)
  104. } / ${prettierBytes(result.gzipped)} gz`,
  105. ))
  106. return [pkg, {
  107. ...result,
  108. prettyMinified: prettierBytes(result.minified),
  109. prettyGzipped: prettierBytes(result.gzipped),
  110. }]
  111. }),
  112. ).then(Object.fromEntries)
  113. // eslint-disable-next-line no-param-reassign
  114. config.uppy_bundle_kb_sizes = await sizesPromise
  115. }
  116. const sourceUppy = path.join(webRoot, '/themes/uppy/source/uppy/')
  117. const sourceUppyLocales = path.join(sourceUppy, 'locales')
  118. async function injectBundles () {
  119. await Promise.all([
  120. fs.promises.mkdir(sourceUppy, { recursive:true }),
  121. fs.promises.mkdir(sourceUppyLocales, { recursive:true }),
  122. ])
  123. const cmds = [
  124. `cp -vfR ${path.join(uppyRoot, '/dist/*')} ${sourceUppy}`,
  125. `cp -vfR ${path.join(localesRoot, '/dist/*')} ${sourceUppyLocales}`,
  126. ].join(' && ')
  127. const cp = spawn(cmds, { stdio:['ignore', 'pipe', 'inherit'], shell: true })
  128. await Promise.race([
  129. new Promise((resolve, reject) => cp.on('error', reject)),
  130. (async () => {
  131. const stdout = readline.createInterface({
  132. input: cp.stdout,
  133. })
  134. for await (const line of stdout) {
  135. console.info(chalk.green('✓ injected: '), chalk.grey(line))
  136. }
  137. })(),
  138. ])
  139. }
  140. // re-enable after rate limiter issue is fixed
  141. //
  142. async function injectGhStars () {
  143. const opts = {}
  144. if ('GITHUB_TOKEN' in process.env) {
  145. opts.auth = process.env.GITHUB_TOKEN
  146. }
  147. // eslint-disable-next-line global-require
  148. const { Octokit } = require('@octokit/rest')
  149. const octokit = new Octokit(opts)
  150. const { headers, data } = await octokit.repos.get({
  151. owner: 'transloadit',
  152. repo: 'uppy',
  153. })
  154. console.log(`${headers['x-ratelimit-remaining']} requests remaining until we hit GitHub ratelimiter`)
  155. const dstpath = path.join(webRoot, 'themes', 'uppy', 'layout', 'partials', 'generated_stargazers.ejs')
  156. fs.writeFileSync(dstpath, String(data.stargazers_count), 'utf-8')
  157. console.log(`${data.stargazers_count} stargazers written to '${dstpath}'`)
  158. }
  159. async function injectMarkdown () {
  160. const sources = {
  161. '.github/CONTRIBUTING.md': 'src/_template/contributing.md',
  162. }
  163. for (const src of Object.keys(sources)) {
  164. const dst = sources[src]
  165. // strip yaml frontmatter:
  166. const srcpath = path.join(uppyRoot, `/../../${src}`)
  167. const dstpath = path.join(webRoot, dst)
  168. const parts = fs.readFileSync(srcpath, 'utf-8').split(/---\s*\n/)
  169. if (parts.length >= 3) {
  170. parts.shift()
  171. parts.shift()
  172. }
  173. let content = `<!-- WARNING! This file was injected. Please edit in "${src}" instead and run "${path.basename(__filename)}" -->\n\n`
  174. content += parts.join('---\n')
  175. fs.writeFileSync(dstpath, content, 'utf-8')
  176. console.info(chalk.green('✓ injected: '), chalk.grey(srcpath))
  177. }
  178. touch(path.join(webRoot, '/src/support.md'))
  179. }
  180. function injectLocaleList () {
  181. const mdTable = [
  182. `<!-- WARNING! This file was automatically injected. Please run "${path.basename(__filename)}" to re-generate -->\n\n`,
  183. '| %count% Locales | NPM | CDN | Source on GitHub |',
  184. '| --------------- | ------------------ | ------------------- | ---------------- |',
  185. ]
  186. const mdRows = []
  187. const localeList = {}
  188. const localePackagePath = path.join(localesRoot, 'src', '*.js')
  189. // eslint-disable-next-line import/no-dynamic-require, global-require
  190. const localePackageVersion = require(path.join(localesRoot, 'package.json')).version
  191. glob.sync(localePackagePath).forEach((localePath) => {
  192. const localeName = path.basename(localePath, '.js')
  193. const [languageCode, regionCode, variant] = localeName.split(/[-_]/)
  194. const languageName = languageDisplayNames.of(languageCode)
  195. const regionName = regionalDisplayNames.of(regionCode)
  196. const npmPath = `<code class="raw"><a href="https://www.npmjs.com/package/@uppy/locales">@uppy/locales</a>/lib/${localeName}</code>`
  197. const cdnPath = `[\`${localeName}.min.js\`](https://releases.transloadit.com/uppy/locales/v${localePackageVersion}/${localeName}.min.js)`
  198. const githubSource = `[\`${localeName}.js\`](https://github.com/transloadit/uppy/blob/main/packages/%40uppy/locales/src/${localeName}.js)`
  199. const mdTableRow = `| ${languageName}<br/> <small>${regionName}</small>${variant ? `<br /><small>(${variant})</small>` : ''} | ${npmPath} | ${cdnPath} | ✏️ ${githubSource} |`
  200. mdRows.push(mdTableRow)
  201. localeList[localeName] = `${languageName} (${regionName}${variant ? `, ${variant}` : ''})`
  202. })
  203. const resultingMdTable = mdTable.concat(mdRows.sort()).join('\n').replace('%count%', mdRows.length)
  204. const dstpath = path.join(webRoot, 'src', '_template', 'list_of_locale_packs.md')
  205. const localeListDstPath = path.join(webRoot, 'src', 'examples', 'locale_list.json')
  206. fs.writeFileSync(dstpath, `${resultingMdTable}\n`, 'utf-8')
  207. console.info(chalk.green('✓ injected: '), chalk.grey(dstpath))
  208. fs.writeFileSync(localeListDstPath, JSON.stringify(localeList), 'utf-8')
  209. console.info(chalk.green('✓ injected: '), chalk.grey(localeListDstPath))
  210. }
  211. async function readConfig () {
  212. try {
  213. const buf = await fs.promises.readFile(configPath, 'utf8')
  214. return YAML.safeLoad(buf)
  215. } catch (err) {
  216. return {}
  217. }
  218. }
  219. async function inject () {
  220. const config = await readConfig()
  221. await injectGhStars()
  222. await injectMarkdown()
  223. injectLocaleList()
  224. config.uppy_version = version
  225. config.uppy_version_anchor = version.replace(/[^\d]+/g, '')
  226. await injectSizes(config)
  227. const saveConfig = { ...defaultConfig, ...config }
  228. await fs.promises.writeFile(configPath, YAML.safeDump(saveConfig), 'utf-8')
  229. console.info(chalk.green('✓ rewritten: '), chalk.grey(configPath))
  230. try {
  231. await injectBundles()
  232. } catch (error) {
  233. console.error(
  234. chalk.red('x failed to inject: '),
  235. chalk.grey(`uppy bundle into site, because: ${error}`),
  236. )
  237. process.exit(1)
  238. }
  239. }