locale-packs.js 8.8 KB

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