i18n.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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.safeLoad(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 {
  31. // ignore
  32. }
  33. }
  34. }
  35. Object.keys(this.data)
  36. .forEach(key => {
  37. this.desc[key] = this.desc[key] || this.data[key].description;
  38. });
  39. }
  40. getMessage(key, def) {
  41. const item = this.data[key];
  42. return item && item.message || def;
  43. }
  44. get(key) {
  45. return this.data[key];
  46. }
  47. dump(data, { extension }) {
  48. if (extension === '.json') {
  49. data = JSON.stringify(data, null, 2);
  50. } else if (extension === '.yml') {
  51. data = yaml.safeDump(data, { sortKeys: true });
  52. } else {
  53. throw 'Unknown extension name!';
  54. }
  55. return {
  56. path: `${this.lang}/messages${extension}`,
  57. data,
  58. };
  59. }
  60. }
  61. class Locales {
  62. constructor(options) {
  63. this.options = options;
  64. this.defaultLang = 'en';
  65. this.newLocaleItem = 'NEW_LOCALE_ITEM';
  66. this.base = options.base || '.';
  67. this.langs = [];
  68. this.locales = {};
  69. this.data = {};
  70. }
  71. async load() {
  72. const langs = await fs.readdir(this.base);
  73. this.langs = langs;
  74. await Promise.all(langs.map(async lang => {
  75. const locale = new Locale(lang, this.base);
  76. await locale.load();
  77. this.locales[lang] = locale;
  78. }));
  79. const defaultData = this.locales[this.defaultLang];
  80. Object.keys(defaultData.desc).forEach(key => {
  81. this.data[key] = {
  82. ...defaultData.data[key],
  83. touched: this.options.markUntouched ? false : defaultData.get(key).touched !== false,
  84. };
  85. });
  86. }
  87. getData(lang, options) {
  88. options = options || {};
  89. const data = {};
  90. const langData = this.locales[lang];
  91. const defaultData = options.useDefaultLang && lang != this.defaultLang && this.locales[this.defaultLang];
  92. Object.keys(this.data).forEach(key => {
  93. if (options.touchedOnly && !this.data[key].touched) return;
  94. data[key] = {
  95. description: this.data[key].description || this.newLocaleItem,
  96. message: langData.getMessage(key) || defaultData && defaultData.getMessage(key) || '',
  97. };
  98. if (options.markUntouched && !this.data[key].touched) data[key].touched = false;
  99. });
  100. return data;
  101. }
  102. dump(options) {
  103. options = { ...this.options, ...options };
  104. return this.langs.map(lang => {
  105. const data = this.getData(lang, options);
  106. const locale = this.locales[lang];
  107. return locale.dump(data, options);
  108. });
  109. }
  110. touch(key) {
  111. let item = this.data[key];
  112. if (!item) item = this.data[key] = {
  113. description: this.newLocaleItem,
  114. };
  115. item.touched = true;
  116. }
  117. }
  118. function extract(options) {
  119. const keys = new Set();
  120. const patterns = {
  121. default: ['\\b(?:i18n\\(\'|i18n-key=")(\\w+)[\'"]', 1],
  122. json: ['__MSG_(\\w+)__', 1],
  123. };
  124. const types = {
  125. '.js': 'default',
  126. '.json': 'json',
  127. '.html': 'default',
  128. '.vue': 'default',
  129. };
  130. const locales = new Locales(options);
  131. function extractFile(data, types) {
  132. if (!Array.isArray(types)) types = [types];
  133. data = String(data);
  134. types.forEach(function (type) {
  135. const patternData = patterns[type];
  136. const pattern = new RegExp(patternData[0], 'g');
  137. const groupId = patternData[1];
  138. let groups;
  139. while (groups = pattern.exec(data)) {
  140. keys.add(groups[groupId]);
  141. }
  142. });
  143. }
  144. function bufferContents(file, enc, cb) {
  145. if (file.isNull()) return cb();
  146. if (file.isStream()) return this.emit('error', new PluginError('VM-i18n', 'Stream is not supported.'));
  147. const extname = path.extname(file.path);
  148. const type = types[extname];
  149. if (type) extractFile(file.contents, type);
  150. cb();
  151. }
  152. function endStream(cb) {
  153. locales.load()
  154. .then(() => {
  155. keys.forEach(key => {
  156. locales.touch(key);
  157. });
  158. return locales.dump()
  159. .map(out => new Vinyl({
  160. path: out.path,
  161. contents: new Buffer(out.data),
  162. }));
  163. })
  164. .then(files => {
  165. files.forEach(file => {
  166. this.push(file);
  167. });
  168. cb();
  169. })
  170. .catch(cb);
  171. }
  172. return through.obj(bufferContents, endStream);
  173. }
  174. function read(options) {
  175. const stream = extract(options);
  176. process.nextTick(() => stream.end());
  177. return stream;
  178. }
  179. module.exports = {
  180. extract,
  181. read,
  182. };