i18n.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. const fs = require('fs').promises;
  2. const path = require('path');
  3. const Vinyl = require('vinyl');
  4. const PluginError = require('plugin-error');
  5. const through = require('through2');
  6. const yaml = require('js-yaml');
  7. const transformers = {
  8. '.yml': data => yaml.load(data),
  9. '.json': data => JSON.parse(data),
  10. };
  11. class Locale {
  12. constructor(lang, base) {
  13. this.defaultLocale = 'messages.yml';
  14. this.lang = lang;
  15. this.base = base;
  16. this.data = {};
  17. this.desc = {};
  18. }
  19. async load() {
  20. const localeDir = `${this.base}/${this.lang}`;
  21. let files = await fs.readdir(localeDir);
  22. files = [this.defaultLocale].concat(files.filter(file => file !== this.defaultLocale));
  23. for (const file of files) {
  24. const ext = path.extname(file);
  25. const transformer = transformers[ext];
  26. if (transformer) {
  27. try {
  28. const res = await fs.readFile(`${localeDir}/${file}`, 'utf8');
  29. Object.assign(this.data, transformer(res));
  30. } catch (err) {
  31. if (err.code !== 'ENOENT') {
  32. throw err;
  33. }
  34. }
  35. }
  36. }
  37. Object.keys(this.data)
  38. .forEach(key => {
  39. this.desc[key] = this.desc[key] || this.data[key].description;
  40. });
  41. }
  42. getMessage(key, def) {
  43. const item = this.data[key];
  44. return item && item.message || def;
  45. }
  46. get(key) {
  47. return this.data[key];
  48. }
  49. dump(data, { extension, stripDescriptions }) {
  50. if (extension === '.json') {
  51. if (stripDescriptions) {
  52. data = Object.entries(data).reduce((res, [key, value]) => {
  53. // eslint-disable-next-line no-unused-vars
  54. const { description, ...stripped } = value;
  55. res[key] = stripped;
  56. return res;
  57. }, {});
  58. }
  59. data = JSON.stringify(data, null, 2);
  60. } else if (extension === '.yml') {
  61. data = yaml.dump(data, { sortKeys: true });
  62. } else {
  63. throw 'Unknown extension name!';
  64. }
  65. return {
  66. path: `${this.lang}/messages${extension}`,
  67. data,
  68. };
  69. }
  70. }
  71. class Locales {
  72. constructor(options) {
  73. this.options = options;
  74. this.defaultLang = 'en';
  75. this.newLocaleItem = 'NEW_LOCALE_ITEM';
  76. this.base = options.base || '.';
  77. this.langs = [];
  78. this.locales = {};
  79. this.data = {};
  80. }
  81. async load() {
  82. const langs = await fs.readdir(this.base);
  83. this.langs = langs;
  84. await Promise.all(langs.map(async lang => {
  85. const locale = new Locale(lang, this.base);
  86. await locale.load();
  87. this.locales[lang] = locale;
  88. }));
  89. const defaultData = this.locales[this.defaultLang];
  90. Object.keys(defaultData.desc).forEach(key => {
  91. this.data[key] = {
  92. ...defaultData.data[key],
  93. touched: this.options.markUntouched ? false : defaultData.get(key).touched !== false,
  94. };
  95. });
  96. }
  97. getData(lang, options) {
  98. options = options || {};
  99. const data = {};
  100. const langData = this.locales[lang];
  101. const defaultData = options.useDefaultLang && lang != this.defaultLang && this.locales[this.defaultLang];
  102. Object.keys(this.data).forEach(key => {
  103. if (options.touchedOnly && !this.data[key].touched) return;
  104. data[key] = {
  105. description: this.data[key].description || this.newLocaleItem,
  106. message: langData.getMessage(key) || defaultData && defaultData.getMessage(key) || '',
  107. };
  108. if (options.markUntouched && !this.data[key].touched) data[key].touched = false;
  109. });
  110. return data;
  111. }
  112. dump(options) {
  113. options = { ...this.options, ...options };
  114. return this.langs.map(lang => {
  115. const data = this.getData(lang, options);
  116. const locale = this.locales[lang];
  117. return locale.dump(data, options);
  118. });
  119. }
  120. touch(key) {
  121. let item = this.data[key];
  122. if (!item) item = this.data[key] = {
  123. description: this.newLocaleItem,
  124. };
  125. item.touched = true;
  126. }
  127. }
  128. function extract(options) {
  129. const keys = new Set();
  130. const patterns = {
  131. default: ['\\b(?:i18n\\(\'|i18n-key=")(\\w+)[\'"]', 1],
  132. json: ['__MSG_(\\w+)__', 1],
  133. };
  134. const typePatternMap = {
  135. '.js': 'default',
  136. '.json': 'json',
  137. '.html': 'default',
  138. '.vue': 'default',
  139. };
  140. const locales = new Locales(options);
  141. function extractFile(data, types) {
  142. if (!Array.isArray(types)) types = [types];
  143. data = String(data);
  144. types.forEach(function (type) {
  145. const patternData = patterns[type];
  146. const pattern = new RegExp(patternData[0], 'g');
  147. const groupId = patternData[1];
  148. let groups;
  149. while ((groups = pattern.exec(data))) {
  150. keys.add(groups[groupId]);
  151. }
  152. });
  153. }
  154. function bufferContents(file, enc, cb) {
  155. if (file.isNull()) return cb();
  156. if (file.isStream()) return this.emit('error', new PluginError('VM-i18n', 'Stream is not supported.'));
  157. const extname = path.extname(file.path);
  158. const type = typePatternMap[extname];
  159. if (type) extractFile(file.contents, type);
  160. cb();
  161. }
  162. function endStream(cb) {
  163. locales.load()
  164. .then(() => {
  165. keys.forEach(key => {
  166. locales.touch(key);
  167. });
  168. return locales.dump()
  169. .map(out => new Vinyl({
  170. path: out.path,
  171. contents: Buffer.from(out.data),
  172. }));
  173. })
  174. .then(files => {
  175. files.forEach(file => {
  176. this.push(file);
  177. });
  178. cb();
  179. })
  180. .catch(cb);
  181. }
  182. return through.obj(bufferContents, endStream);
  183. }
  184. function read(options) {
  185. const stream = extract(options);
  186. process.nextTick(() => stream.end());
  187. return stream;
  188. }
  189. module.exports = {
  190. extract,
  191. read,
  192. };