locale-packs.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. const glob = require('glob')
  2. const { ESLint } = require('eslint')
  3. const chalk = require('chalk')
  4. const path = require('path')
  5. const stringifyObject = require('stringify-object')
  6. const fs = require('fs')
  7. const Uppy = require('../packages/@uppy/core')
  8. const uppy = new Uppy()
  9. let localePack = {}
  10. const plugins = {}
  11. const sources = {}
  12. console.warn('\n--> Make sure to run `npm run build:lib` for this locale script to work properly. ')
  13. const mode = process.argv[2]
  14. if (mode === 'build') {
  15. build().catch((error) => {
  16. console.error(error)
  17. process.exit(1)
  18. })
  19. } else if (mode === 'test') {
  20. test()
  21. } else {
  22. throw new Error("First argument must be either 'build' or 'test'")
  23. }
  24. function getSources (pluginName) {
  25. const dependencies = {
  26. // because 'provider-views' doesn't have its own locale, it uses Core's defaultLocale
  27. core: ['provider-views'],
  28. }
  29. const globPath = path.join(__dirname, '..', 'packages', '@uppy', pluginName, 'lib', '**', '*.js')
  30. let contents = glob.sync(globPath).map((file) => {
  31. return fs.readFileSync(file, 'utf-8')
  32. })
  33. if (dependencies[pluginName]) {
  34. dependencies[pluginName].forEach((addPlugin) => {
  35. contents = contents.concat(getSources(addPlugin))
  36. })
  37. }
  38. return contents
  39. }
  40. function buildPluginsList () {
  41. // Go over all uppy plugins, check if they are constructors
  42. // and instanciate them, check for defaultLocale property,
  43. // then add to plugins object
  44. const packagesGlobPath = path.join(__dirname, '..', 'packages', '@uppy', '*', 'package.json')
  45. const files = glob.sync(packagesGlobPath)
  46. console.log('--> Checked plugins could be instantiated and have defaultLocale in them:\n')
  47. for (const file of files) {
  48. const dirName = path.dirname(file)
  49. const pluginName = path.basename(dirName)
  50. if (pluginName === 'locales'
  51. || pluginName === 'react-native'
  52. || pluginName === 'vue'
  53. || pluginName === 'svelte') {
  54. continue
  55. }
  56. const Plugin = require(dirName)
  57. let plugin
  58. // A few hacks to emulate browser environment because e.g.:
  59. // GoldenRetrieves calls upon MetaDataStore in the constructor, which uses localStorage
  60. // @TODO Consider rewriting constructors so they don't make imperative calls that rely on
  61. // browser environment (OR: just keep this browser mocking, if it's only causing issues for this script, it doesn't matter)
  62. global.location = { protocol: 'https' }
  63. global.navigator = { userAgent: '' }
  64. global.localStorage = {
  65. key: () => { },
  66. getItem: () => { },
  67. }
  68. global.window = {
  69. indexedDB: {
  70. open: () => { return {} },
  71. },
  72. }
  73. global.document = {
  74. createElement: () => {
  75. return { style: {} }
  76. },
  77. }
  78. try {
  79. if (pluginName === 'provider-views') {
  80. plugin = new Plugin(plugins['drag-drop'], {
  81. companionPattern: '',
  82. companionUrl: 'https://companion.uppy.io',
  83. })
  84. } else if (pluginName === 'store-redux') {
  85. plugin = new Plugin({ store: { dispatch: () => { } } })
  86. } else {
  87. plugin = new Plugin(uppy, {
  88. companionPattern: '',
  89. companionUrl: 'https://companion.uppy.io',
  90. params: {
  91. auth: {
  92. key: 'x',
  93. },
  94. },
  95. })
  96. }
  97. } catch (err) {
  98. if (err.message !== 'Plugin is not a constructor') {
  99. console.error(`--> While trying to instantiate plugin: ${pluginName}, this error was thrown: `)
  100. throw err
  101. }
  102. }
  103. if (plugin && plugin.defaultLocale) {
  104. console.log(`[x] Check plugin: ${pluginName}`)
  105. plugins[pluginName] = plugin
  106. sources[pluginName] = getSources(pluginName)
  107. } else {
  108. console.log(`[ ] Check plugin: ${pluginName}`)
  109. }
  110. }
  111. console.log('')
  112. return { plugins, sources }
  113. }
  114. function addLocaleToPack (plugin, pluginName) {
  115. const localeStrings = plugin.defaultLocale.strings
  116. for (const key in localeStrings) {
  117. const valueInPlugin = JSON.stringify(localeStrings[key])
  118. const valueInPack = JSON.stringify(localePack[key])
  119. if (key in localePack && valueInPlugin !== valueInPack) {
  120. console.error(`⚠ Plugin ${chalk.magenta(pluginName)} has a duplicate key: ${chalk.magenta(key)}`)
  121. console.error(` Value in plugin: ${chalk.cyan(valueInPlugin)}`)
  122. console.error(` Value in pack : ${chalk.yellow(valueInPack)}`)
  123. console.error()
  124. }
  125. localePack[key] = localeStrings[key]
  126. }
  127. }
  128. function checkForUnused (fileContents, pluginName, localePack) {
  129. const buff = fileContents.join('\n')
  130. for (const key in localePack) {
  131. const regPat = new RegExp(`(i18n|i18nArray)\\([^\\)]*['\`"]${key}['\`"]`, 'g')
  132. if (!buff.match(regPat)) {
  133. console.error(`⚠ defaultLocale key: ${chalk.magenta(key)} not used in plugin: ${chalk.cyan(pluginName)}`)
  134. }
  135. }
  136. }
  137. function sortObjectAlphabetically (obj, sortFunc) {
  138. return Object.keys(obj).sort(sortFunc).reduce((result, key) => {
  139. result[key] = obj[key]
  140. return result
  141. }, {})
  142. }
  143. function createTypeScriptLocale (plugin, pluginName) {
  144. const allowedStringTypes = Object.keys(plugin.defaultLocale.strings)
  145. .map(key => ` | '${key}'`)
  146. .join('\n')
  147. const pluginClassName = pluginName === 'core' ? 'Core' : plugin.id
  148. const localePath = path.join(__dirname, '..', 'packages', '@uppy', pluginName, 'types', 'generatedLocale.d.ts')
  149. const localeTypes
  150. = `${'import Uppy = require(\'@uppy/core\')\n'
  151. + '\n'
  152. + `type ${pluginClassName}Locale = Uppy.Locale` + '<\n'}${
  153. allowedStringTypes}\n`
  154. + `>\n`
  155. + `\n`
  156. + `export = ${pluginClassName}Locale\n`
  157. fs.writeFileSync(localePath, localeTypes)
  158. }
  159. async function build () {
  160. const { plugins, sources } = buildPluginsList()
  161. for (const pluginName in plugins) {
  162. addLocaleToPack(plugins[pluginName], pluginName)
  163. }
  164. for (const pluginName in plugins) {
  165. createTypeScriptLocale(plugins[pluginName], pluginName)
  166. }
  167. localePack = sortObjectAlphabetically(localePack)
  168. for (const pluginName in sources) {
  169. checkForUnused(sources[pluginName], pluginName, sortObjectAlphabetically(plugins[pluginName].defaultLocale.strings))
  170. }
  171. const prettyLocale = stringifyObject(localePack, {
  172. indent: ' ',
  173. singleQuotes: true,
  174. inlineCharacterLimit: 12,
  175. })
  176. const localeTemplatePath = path.join(__dirname, '..', 'packages', '@uppy', 'locales', 'template.js')
  177. const template = fs.readFileSync(localeTemplatePath, 'utf-8')
  178. const finalLocale = template.replace('en_US.strings = {}', `en_US.strings = ${prettyLocale}`)
  179. const localePackagePath = path.join(__dirname, '..', 'packages', '@uppy', 'locales', 'src', 'en_US.js')
  180. const linter = new ESLint({
  181. fix: true,
  182. })
  183. const [lintResult] = await linter.lintText(finalLocale, {
  184. filePath: localePackagePath,
  185. })
  186. fs.writeFileSync(localePackagePath, lintResult.output, 'utf8')
  187. console.log(`✅ Written '${localePackagePath}'`)
  188. }
  189. function test () {
  190. const leadingLocaleName = 'en_US'
  191. const followerLocales = {}
  192. const followerValues = {}
  193. const localePackagePath = path.join(__dirname, '..', 'packages', '@uppy', 'locales', 'src', '*.js')
  194. glob.sync(localePackagePath).forEach((localePath) => {
  195. const localeName = path.basename(localePath, '.js')
  196. // we renamed the es_GL → gl_ES locale, and kept the old name
  197. // for backwards-compat, see https://github.com/transloadit/uppy/pull/1929
  198. if (localeName === 'es_GL') return
  199. // Builds array with items like: 'uploadingXFiles'
  200. // We do not check nested items because different languages may have different amounts of plural forms.
  201. followerValues[localeName] = require(localePath).strings
  202. followerLocales[localeName] = Object.keys(followerValues[localeName])
  203. })
  204. // Take aside our leading locale: en_US
  205. const leadingLocale = followerLocales[leadingLocaleName]
  206. const leadingValues = followerValues[leadingLocaleName]
  207. delete followerLocales[leadingLocaleName]
  208. // Compare all follower Locales (RU, DE, etc) with our leader en_US
  209. const warnings = []
  210. const fatals = []
  211. for (const followerName in followerLocales) {
  212. const followerLocale = followerLocales[followerName]
  213. const missing = leadingLocale.filter((key) => !followerLocale.includes(key))
  214. const excess = followerLocale.filter((key) => !leadingLocale.includes(key))
  215. missing.forEach((key) => {
  216. // Items missing are a non-fatal warning because we don't want CI to bum out over all languages
  217. // as soon as we add some English
  218. let value = leadingValues[key]
  219. if (typeof value === 'object') {
  220. // For values with plural forms, just take the first one right now
  221. value = value[Object.keys(value)[0]]
  222. }
  223. warnings.push(`${chalk.cyan(followerName)} locale has missing string: '${chalk.red(key)}' that is present in ${chalk.cyan(leadingLocaleName)} with value: ${chalk.yellow(leadingValues[key])}`)
  224. })
  225. excess.forEach((key) => {
  226. // Items in excess are a fatal because we should clean up follower languages once we remove English strings
  227. fatals.push(`${chalk.cyan(followerName)} locale has excess string: '${chalk.yellow(key)}' that is not present in ${chalk.cyan(leadingLocaleName)}. `)
  228. })
  229. }
  230. if (warnings.length) {
  231. console.error('--> Locale warnings: ')
  232. console.error(warnings.join('\n'))
  233. console.error('')
  234. }
  235. if (fatals.length) {
  236. console.error('--> Locale fatal warnings: ')
  237. console.error(fatals.join('\n'))
  238. console.error('')
  239. process.exit(1)
  240. }
  241. if (!warnings.length && !fatals.length) {
  242. console.log(`--> All locale strings have matching keys ${chalk.green(': )')}`)
  243. console.log('')
  244. }
  245. }