i18n.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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
  102. ? this.locales[this.defaultLang]
  103. : null;
  104. const colons = defaultData && !/^(ja|ko|zh)/.test(lang);
  105. Object.keys(this.data).forEach(key => {
  106. if (options.touchedOnly && !this.data[key].touched) return;
  107. const msg = langData.getMessage(key) || defaultData?.getMessage(key) || '';
  108. data[key] = {
  109. description: this.data[key].description || this.newLocaleItem,
  110. message: colons
  111. ? normalizeTrailingColon(msg, defaultData.getMessage(key))
  112. : msg,
  113. };
  114. if (options.markUntouched && !this.data[key].touched) data[key].touched = false;
  115. });
  116. return data;
  117. }
  118. dump(options) {
  119. options = { ...this.options, ...options };
  120. return this.langs.map(lang => {
  121. const data = this.getData(lang, options);
  122. const locale = this.locales[lang];
  123. return locale.dump(data, options);
  124. });
  125. }
  126. touch(key) {
  127. let item = this.data[key];
  128. if (!item) item = this.data[key] = {
  129. description: this.newLocaleItem,
  130. };
  131. item.touched = true;
  132. }
  133. }
  134. function extract(options) {
  135. const keys = new Set();
  136. const patterns = {
  137. default: ['\\b(?:i18n\\(\'|i18n-key=")(\\w+)[\'"]', 1],
  138. json: ['__MSG_(\\w+)__', 1],
  139. };
  140. const typePatternMap = {
  141. '.js': 'default',
  142. '.json': 'json',
  143. '.html': 'default',
  144. '.vue': 'default',
  145. };
  146. const locales = new Locales(options);
  147. function extractFile(data, types) {
  148. if (!Array.isArray(types)) types = [types];
  149. data = String(data);
  150. types.forEach(function (type) {
  151. const patternData = patterns[type];
  152. const pattern = new RegExp(patternData[0], 'g');
  153. const groupId = patternData[1];
  154. let groups;
  155. while ((groups = pattern.exec(data))) {
  156. keys.add(groups[groupId]);
  157. }
  158. });
  159. }
  160. function bufferContents(file, enc, cb) {
  161. if (file.isNull()) return cb();
  162. if (file.isStream()) return this.emit('error', new PluginError('VM-i18n', 'Stream is not supported.'));
  163. const extname = path.extname(file.path);
  164. const type = typePatternMap[extname];
  165. if (type) extractFile(file.contents, type);
  166. cb();
  167. }
  168. function endStream(cb) {
  169. locales.load()
  170. .then(() => {
  171. keys.forEach(key => {
  172. locales.touch(key);
  173. });
  174. return locales.dump()
  175. .map(out => new Vinyl({
  176. path: out.path,
  177. contents: Buffer.from(out.data),
  178. }));
  179. })
  180. .then(files => {
  181. files.forEach(file => {
  182. this.push(file);
  183. });
  184. cb();
  185. })
  186. .catch(cb);
  187. }
  188. if (options.manifest) {
  189. const mf = require('fs').readFileSync(options.manifest, 'utf8');
  190. extractFile(mf, 'json');
  191. }
  192. return through.obj(bufferContents, endStream);
  193. }
  194. function read(options) {
  195. const stream = extract(options);
  196. process.nextTick(() => stream.end());
  197. return stream;
  198. }
  199. function normalizeTrailingColon(str, sourceStr = '') {
  200. if (sourceStr.endsWith(': ') && str.endsWith(':')) {
  201. return str + ' ';
  202. }
  203. if (sourceStr.endsWith(':') && str.endsWith(': ')) {
  204. return str.slice(0, -1);
  205. }
  206. return str;
  207. }
  208. module.exports = {
  209. extract,
  210. read,
  211. };