locale-packs.js 9.5 KB

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