@lingui/cli 4.0.0-next.4 → 4.0.0-next.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/api/catalog/extractFromFiles.js +64 -0
  2. package/dist/api/catalog/getCatalogs.js +137 -0
  3. package/dist/api/catalog/getTranslationsForCatalog.js +68 -0
  4. package/dist/api/catalog/mergeCatalog.js +86 -0
  5. package/dist/api/catalog.js +286 -0
  6. package/dist/api/compile.js +115 -0
  7. package/dist/api/extractors/babel.js +158 -0
  8. package/dist/api/extractors/index.js +44 -0
  9. package/dist/api/extractors/typescript.js +15 -0
  10. package/dist/api/formats/formatterWrapper.js +48 -0
  11. package/dist/api/formats/index.js +95 -0
  12. package/dist/api/help.js +41 -0
  13. package/dist/api/index.js +31 -0
  14. package/dist/api/pseudoLocalize.js +60 -0
  15. package/dist/api/rethrownError.js +16 -0
  16. package/dist/api/stats.js +73 -0
  17. package/{build → dist}/api/types.js +2 -3
  18. package/dist/api/utils.js +117 -0
  19. package/dist/extract-experimental/buildExternalizeFilter.js +83 -0
  20. package/dist/extract-experimental/bundleSource.js +127 -0
  21. package/dist/extract-experimental/constants.js +16 -0
  22. package/dist/extract-experimental/getEntryPoints.js +20 -0
  23. package/dist/extract-experimental/getExperimentalCatalogs.js +30 -0
  24. package/dist/extract-experimental/resolveCatalogPath.js +34 -0
  25. package/dist/extract-experimental/resolveTemplatePath.js +19 -0
  26. package/dist/extract-experimental/writeCatalogs.js +54 -0
  27. package/dist/lingui-compile.js +158 -0
  28. package/dist/lingui-extract-experimental.js +113 -0
  29. package/dist/lingui-extract-template.js +52 -0
  30. package/dist/lingui-extract.js +192 -0
  31. package/dist/lingui.js +8 -0
  32. package/dist/services/translationIO.js +261 -0
  33. package/dist/tests.js +137 -0
  34. package/package.json +19 -13
  35. package/build/LICENSE +0 -21
  36. package/build/api/catalog/extractFromFiles.js +0 -45
  37. package/build/api/catalog/getCatalogs.js +0 -138
  38. package/build/api/catalog/getTranslationsForCatalog.js +0 -77
  39. package/build/api/catalog/mergeCatalog.js +0 -44
  40. package/build/api/catalog.js +0 -245
  41. package/build/api/compile.js +0 -72
  42. package/build/api/extractors/babel.js +0 -92
  43. package/build/api/extractors/index.js +0 -36
  44. package/build/api/extractors/typescript.js +0 -14
  45. package/build/api/formats/formatterWrapper.js +0 -45
  46. package/build/api/formats/index.js +0 -57
  47. package/build/api/generateMessageId.js +0 -12
  48. package/build/api/help.js +0 -42
  49. package/build/api/index.js +0 -58
  50. package/build/api/pseudoLocalize.js +0 -60
  51. package/build/api/rethrownError.js +0 -14
  52. package/build/api/stats.js +0 -40
  53. package/build/api/utils.js +0 -117
  54. package/build/extract-experimental/buildExternalizeFilter.js +0 -39
  55. package/build/extract-experimental/bundleSource.js +0 -69
  56. package/build/extract-experimental/constants.js +0 -10
  57. package/build/extract-experimental/getEntryPoints.js +0 -14
  58. package/build/extract-experimental/getExperimentalCatalogs.js +0 -28
  59. package/build/extract-experimental/resolveCatalogPath.js +0 -23
  60. package/build/extract-experimental/resolveTemplatePath.js +0 -17
  61. package/build/extract-experimental/writeCatalogs.js +0 -59
  62. package/build/lingui-compile.js +0 -156
  63. package/build/lingui-extract-experimental.js +0 -103
  64. package/build/lingui-extract-template.js +0 -46
  65. package/build/lingui-extract.js +0 -143
  66. package/build/lingui.js +0 -6
  67. package/build/services/translationIO.js +0 -266
  68. package/build/tests.js +0 -133
@@ -0,0 +1,261 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, // Main sync method, call "Init" or "Sync" depending on the project context
6
+ "default", {
7
+ enumerable: true,
8
+ get: ()=>syncProcess
9
+ });
10
+ const _fs = /*#__PURE__*/ _interopRequireDefault(require("fs"));
11
+ const _path = require("path");
12
+ const _pofile = /*#__PURE__*/ _interopRequireDefault(require("pofile"));
13
+ const _https = /*#__PURE__*/ _interopRequireDefault(require("https"));
14
+ const _glob = /*#__PURE__*/ _interopRequireDefault(require("glob"));
15
+ const _dateFns = require("date-fns");
16
+ function _interopRequireDefault(obj) {
17
+ return obj && obj.__esModule ? obj : {
18
+ default: obj
19
+ };
20
+ }
21
+ const getCreateHeaders = (language)=>({
22
+ "POT-Creation-Date": (0, _dateFns.format)(new Date(), "yyyy-MM-dd HH:mmxxxx"),
23
+ "MIME-Version": "1.0",
24
+ "Content-Type": "text/plain; charset=utf-8",
25
+ "Content-Transfer-Encoding": "8bit",
26
+ "X-Generator": "@lingui/cli",
27
+ Language: language
28
+ });
29
+ const getTargetLocales = (config)=>{
30
+ const sourceLocale = config.sourceLocale || "en";
31
+ const pseudoLocale = config.pseudoLocale || "pseudo";
32
+ return config.locales.filter((value)=>value != sourceLocale && value != pseudoLocale);
33
+ };
34
+ function syncProcess(config, options) {
35
+ if (config.format != "po") {
36
+ console.error(`\n----------\nTranslation.io service is only compatible with the "po" format. Please update your Lingui configuration accordingly.\n----------`);
37
+ process.exit(1);
38
+ }
39
+ const successCallback = (project)=>{
40
+ console.log(`\n----------\nProject successfully synchronized. Please use this URL to translate: ${project.url}\n----------`);
41
+ };
42
+ const failCallback = (errors)=>{
43
+ console.error(`\n----------\nSynchronization with Translation.io failed: ${errors.join(", ")}\n----------`);
44
+ };
45
+ init(config, options, successCallback, (errors)=>{
46
+ if (errors.length && errors[0] === "This project has already been initialized.") {
47
+ sync(config, options, successCallback, failCallback);
48
+ } else {
49
+ failCallback(errors);
50
+ }
51
+ });
52
+ }
53
+ // Initialize project with source and existing translations (only first time!)
54
+ // Cf. https://translation.io/docs/create-library#initialization
55
+ function init(config, options, successCallback, failCallback) {
56
+ const sourceLocale = config.sourceLocale || "en";
57
+ const targetLocales = getTargetLocales(config);
58
+ const paths = poPathsPerLocale(config);
59
+ const segments = {};
60
+ targetLocales.forEach((targetLocale)=>{
61
+ segments[targetLocale] = [];
62
+ });
63
+ // Create segments from source locale PO items
64
+ paths[sourceLocale].forEach((path)=>{
65
+ const raw = _fs.default.readFileSync(path).toString();
66
+ const po = _pofile.default.parse(raw);
67
+ po.items.filter((item)=>!item["obsolete"]).forEach((item)=>{
68
+ targetLocales.forEach((targetLocale)=>{
69
+ const newSegment = createSegmentFromPoItem(item);
70
+ segments[targetLocale].push(newSegment);
71
+ });
72
+ });
73
+ });
74
+ // Add translations to segments from target locale PO items
75
+ targetLocales.forEach((targetLocale)=>{
76
+ paths[targetLocale].forEach((path)=>{
77
+ const raw = _fs.default.readFileSync(path).toString();
78
+ const po = _pofile.default.parse(raw);
79
+ po.items.filter((item)=>!item["obsolete"]).forEach((item, index)=>{
80
+ segments[targetLocale][index].target = item.msgstr[0];
81
+ });
82
+ });
83
+ });
84
+ const request = {
85
+ client: "lingui",
86
+ version: require("@lingui/core/package.json").version,
87
+ source_language: sourceLocale,
88
+ target_languages: targetLocales,
89
+ segments: segments
90
+ };
91
+ postTio("init", request, config.service.apiKey, (response)=>{
92
+ if (response.errors) {
93
+ failCallback(response.errors);
94
+ } else {
95
+ saveSegmentsToTargetPos(config, paths, response.segments);
96
+ successCallback(response.project);
97
+ }
98
+ }, (error)=>{
99
+ console.error(`\n----------\nSynchronization with Translation.io failed: ${error}\n----------`);
100
+ });
101
+ }
102
+ // Send all source text from PO to Translation.io and create new PO based on received translations
103
+ // Cf. https://translation.io/docs/create-library#synchronization
104
+ function sync(config, options, successCallback, failCallback) {
105
+ const sourceLocale = config.sourceLocale || "en";
106
+ const targetLocales = getTargetLocales(config);
107
+ const paths = poPathsPerLocale(config);
108
+ const segments = [];
109
+ // Create segments with correct source
110
+ paths[sourceLocale].forEach((path)=>{
111
+ const raw = _fs.default.readFileSync(path).toString();
112
+ const po = _pofile.default.parse(raw);
113
+ po.items.filter((item)=>!item["obsolete"]).forEach((item)=>{
114
+ const newSegment = createSegmentFromPoItem(item);
115
+ segments.push(newSegment);
116
+ });
117
+ });
118
+ const request = {
119
+ client: "lingui",
120
+ version: require("@lingui/core/package.json").version,
121
+ source_language: sourceLocale,
122
+ target_languages: targetLocales,
123
+ segments: segments,
124
+ // Sync and then remove unused segments (not present in the local application) from Translation.io
125
+ purge: Boolean(options.clean)
126
+ };
127
+ postTio("sync", request, config.service.apiKey, (response)=>{
128
+ if (response.errors) {
129
+ failCallback(response.errors);
130
+ } else {
131
+ saveSegmentsToTargetPos(config, paths, response.segments);
132
+ successCallback(response.project);
133
+ }
134
+ }, (error)=>{
135
+ console.error(`\n----------\nSynchronization with Translation.io failed: ${error}\n----------`);
136
+ });
137
+ }
138
+ function createSegmentFromPoItem(item) {
139
+ const itemHasId = item.msgid != item.msgstr[0] && item.msgstr[0].length;
140
+ const segment = {
141
+ type: "source",
142
+ source: itemHasId ? item.msgstr[0] : item.msgid,
143
+ context: "",
144
+ references: [],
145
+ comment: ""
146
+ };
147
+ if (itemHasId) {
148
+ segment.context = item.msgid;
149
+ }
150
+ if (item.references.length) {
151
+ segment.references = item.references;
152
+ }
153
+ if (item.extractedComments.length) {
154
+ segment.comment = item.extractedComments.join(" | ");
155
+ }
156
+ return segment;
157
+ }
158
+ function createPoItemFromSegment(segment) {
159
+ const item = new _pofile.default.Item();
160
+ item.msgid = segment.context ? segment.context : segment.source;
161
+ item.msgstr = [
162
+ segment.target
163
+ ];
164
+ item.references = segment.references && segment.references.length ? segment.references : [];
165
+ item.extractedComments = segment.comment ? segment.comment.split(" | ") : [];
166
+ return item;
167
+ }
168
+ function saveSegmentsToTargetPos(config, paths, segmentsPerLocale) {
169
+ Object.keys(segmentsPerLocale).forEach((targetLocale)=>{
170
+ // Remove existing target POs and JS for this target locale
171
+ paths[targetLocale].forEach((path)=>{
172
+ const jsPath = path.replace(/\.po?$/, "") + ".js";
173
+ const dirPath = (0, _path.dirname)(path);
174
+ // Remove PO, JS and empty dir
175
+ if (_fs.default.existsSync(path)) {
176
+ _fs.default.unlinkSync(path);
177
+ }
178
+ if (_fs.default.existsSync(jsPath)) {
179
+ _fs.default.unlinkSync(jsPath);
180
+ }
181
+ if (_fs.default.existsSync(dirPath) && _fs.default.readdirSync(dirPath).length === 0) {
182
+ _fs.default.rmdirSync(dirPath);
183
+ }
184
+ });
185
+ // Find target path (ignoring {name})
186
+ const localePath = "".concat(config.catalogs[0].path.replace(/{locale}/g, targetLocale).replace(/{name}/g, ""), ".po");
187
+ const segments = segmentsPerLocale[targetLocale];
188
+ const po = new _pofile.default();
189
+ po.headers = getCreateHeaders(targetLocale);
190
+ const items = [];
191
+ segments.forEach((segment)=>{
192
+ const item = createPoItemFromSegment(segment);
193
+ items.push(item);
194
+ });
195
+ // Sort items by messageId
196
+ po.items = items.sort((a, b)=>{
197
+ if (a.msgid < b.msgid) {
198
+ return -1;
199
+ }
200
+ if (a.msgid > b.msgid) {
201
+ return 1;
202
+ }
203
+ return 0;
204
+ });
205
+ // Check that localePath directory exists and save PO file
206
+ _fs.default.promises.mkdir((0, _path.dirname)(localePath), {
207
+ recursive: true
208
+ }).then(()=>{
209
+ po.save(localePath, (err)=>{
210
+ if (err) {
211
+ console.error("Error while saving target PO files:");
212
+ console.error(err);
213
+ process.exit(1);
214
+ }
215
+ });
216
+ });
217
+ });
218
+ }
219
+ function poPathsPerLocale(config) {
220
+ const paths = {};
221
+ config.locales.forEach((locale)=>{
222
+ paths[locale] = [];
223
+ config.catalogs.forEach((catalog)=>{
224
+ const path = "".concat(catalog.path.replace(/{locale}/g, locale).replace(/{name}/g, "*"), ".po");
225
+ // If {name} is present (replaced by *), list all the existing POs
226
+ if (path.includes("*")) {
227
+ paths[locale] = paths[locale].concat(_glob.default.sync(path));
228
+ } else {
229
+ paths[locale].push(path);
230
+ }
231
+ });
232
+ });
233
+ return paths;
234
+ }
235
+ function postTio(action, request, apiKey, successCallback, failCallback) {
236
+ const jsonRequest = JSON.stringify(request);
237
+ const options = {
238
+ hostname: "translation.io",
239
+ path: `/api/v1/segments/${action}.json?api_key=${apiKey}`,
240
+ method: "POST",
241
+ headers: {
242
+ "Content-Type": "application/json"
243
+ }
244
+ };
245
+ const req = _https.default.request(options, (res)=>{
246
+ res.setEncoding("utf8");
247
+ let body = "";
248
+ res.on("data", (chunk)=>{
249
+ body = body.concat(chunk);
250
+ });
251
+ res.on("end", ()=>{
252
+ const response = JSON.parse(body);
253
+ successCallback(response);
254
+ });
255
+ });
256
+ req.on("error", (e)=>{
257
+ failCallback(e);
258
+ });
259
+ req.write(jsonRequest);
260
+ req.end();
261
+ }
package/dist/tests.js ADDED
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ copyFixture: ()=>copyFixture,
13
+ defaultMakeOptions: ()=>defaultMakeOptions,
14
+ defaultMakeTemplateOptions: ()=>defaultMakeTemplateOptions,
15
+ defaultMergeOptions: ()=>defaultMergeOptions,
16
+ normalizeLineEndings: ()=>normalizeLineEndings,
17
+ makeCatalog: ()=>makeCatalog,
18
+ makePrevMessage: ()=>makePrevMessage,
19
+ makeNextMessage: ()=>makeNextMessage,
20
+ listingToHumanReadable: ()=>listingToHumanReadable,
21
+ createFixtures: ()=>createFixtures,
22
+ readFsToJson: ()=>readFsToJson
23
+ });
24
+ const _os = /*#__PURE__*/ _interopRequireDefault(require("os"));
25
+ const _path = /*#__PURE__*/ _interopRequireDefault(require("path"));
26
+ const _fs = /*#__PURE__*/ _interopRequireDefault(require("fs"));
27
+ const _catalog = require("./api/catalog");
28
+ const _conf = require("@lingui/conf");
29
+ const _api = require("./api");
30
+ function _interopRequireDefault(obj) {
31
+ return obj && obj.__esModule ? obj : {
32
+ default: obj
33
+ };
34
+ }
35
+ async function copyFixture(fixtureDir) {
36
+ const tmpDir = await _fs.default.promises.mkdtemp(_path.default.join(_os.default.tmpdir(), `lingui-test-${process.pid}`));
37
+ try {
38
+ await _fs.default.promises.cp(fixtureDir, tmpDir, {
39
+ recursive: true
40
+ });
41
+ } catch (err) {
42
+ if (err.code != "ENOENT") {
43
+ throw err;
44
+ }
45
+ }
46
+ return tmpDir;
47
+ }
48
+ const defaultMakeOptions = {
49
+ verbose: false,
50
+ clean: false,
51
+ overwrite: false,
52
+ locale: null,
53
+ prevFormat: null,
54
+ orderBy: "messageId"
55
+ };
56
+ const defaultMakeTemplateOptions = {
57
+ verbose: false,
58
+ orderBy: "messageId"
59
+ };
60
+ const defaultMergeOptions = {
61
+ overwrite: false
62
+ };
63
+ const normalizeLineEndings = (str)=>str.replace(/\r?\n/g, "\r\n");
64
+ const makeCatalog = async (_config = {})=>{
65
+ const config = (0, _conf.makeConfig)(_config, {
66
+ skipValidation: true
67
+ });
68
+ return new _catalog.Catalog({
69
+ name: "messages",
70
+ path: "{locale}/messages",
71
+ include: [],
72
+ exclude: [],
73
+ format: await (0, _api.getFormat)(config.format, config.formatOptions, config.sourceLocale)
74
+ }, config);
75
+ };
76
+ function makePrevMessage(message = {}) {
77
+ return {
78
+ translation: "",
79
+ ...makeNextMessage(message)
80
+ };
81
+ }
82
+ function makeNextMessage(message = {}) {
83
+ return {
84
+ origin: [
85
+ [
86
+ "catalog.test.ts",
87
+ 1
88
+ ]
89
+ ],
90
+ obsolete: false,
91
+ ...message
92
+ };
93
+ }
94
+ function listingToHumanReadable(listing) {
95
+ const output = [];
96
+ Object.entries(listing).forEach(([filename, value])=>{
97
+ if (typeof value === "string") {
98
+ output.push("#######################");
99
+ output.push(`Filename: ${filename}`);
100
+ output.push("#######################");
101
+ output.push("");
102
+ output.push(normalizeLineEndings(value));
103
+ output.push("");
104
+ } else {
105
+ output.push(...listingToHumanReadable(value));
106
+ }
107
+ });
108
+ return output.join("\n");
109
+ }
110
+ async function createFixtures(listing) {
111
+ const tmpDir = await _fs.default.promises.mkdtemp(_path.default.join(_os.default.tmpdir(), `lingui-test-${process.pid}`));
112
+ async function create(listing) {
113
+ for (const [filename, value] of Object.entries(listing)){
114
+ if (typeof value === "string") {
115
+ await _fs.default.promises.writeFile(_path.default.join(tmpDir, filename), value);
116
+ } else {
117
+ await create(value);
118
+ }
119
+ }
120
+ }
121
+ await create(listing);
122
+ return tmpDir;
123
+ }
124
+ function readFsToJson(directory, filter) {
125
+ const out = {};
126
+ _fs.default.readdirSync(directory).map((filename)=>{
127
+ const filepath = _path.default.join(directory, filename);
128
+ if (_fs.default.lstatSync(filepath).isDirectory()) {
129
+ out[filename] = readFsToJson(filepath);
130
+ return out;
131
+ }
132
+ if (!filter || filter(filename)) {
133
+ out[filename] = _fs.default.readFileSync(filepath).toString();
134
+ }
135
+ });
136
+ return out;
137
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lingui/cli",
3
- "version": "4.0.0-next.4",
3
+ "version": "4.0.0-next.5",
4
4
  "description": "CLI for working wit message catalogs",
5
5
  "keywords": [
6
6
  "cli",
@@ -18,31 +18,34 @@
18
18
  "name": "Tomáš Ehrlich",
19
19
  "email": "tomas.ehrlich@gmail.com"
20
20
  },
21
- "main": "./build/lingui.js",
21
+ "main": "./dist/lingui.js",
22
22
  "bin": {
23
- "lingui": "./build/lingui.js"
23
+ "lingui": "./dist/lingui.js"
24
24
  },
25
25
  "exports": {
26
26
  ".": {
27
- "require": "./build/lingui.js"
27
+ "require": "./dist/lingui.js"
28
28
  },
29
29
  "./api": {
30
- "require": "./build/api/index.js"
30
+ "require": "./dist/api/index.js"
31
31
  },
32
32
  "./api/extractors/babel": {
33
- "require": "./build/api/extractors/babel.js"
33
+ "require": "./dist/api/extractors/babel.js"
34
34
  },
35
35
  "./api/extractors/typescript": {
36
- "require": "./build/api/extractors/typescript.js"
36
+ "require": "./dist/api/extractors/typescript.js"
37
37
  }
38
38
  },
39
+ "scripts": {
40
+ "build": "rimraf ./dist && swc ./src -d dist"
41
+ },
39
42
  "engines": {
40
43
  "node": ">=16.0.0"
41
44
  },
42
45
  "files": [
43
46
  "LICENSE",
44
47
  "README.md",
45
- "build/"
48
+ "dist/"
46
49
  ],
47
50
  "dependencies": {
48
51
  "@babel/core": "^7.21.0",
@@ -50,10 +53,11 @@
50
53
  "@babel/parser": "^7.21.2",
51
54
  "@babel/runtime": "^7.21.0",
52
55
  "@babel/types": "^7.21.2",
53
- "@lingui/babel-plugin-extract-messages": "^4.0.0-next.4",
54
- "@lingui/conf": "^4.0.0-next.4",
55
- "@lingui/core": "^4.0.0-next.4",
56
- "@lingui/format-po": "^4.0.0-next.4",
56
+ "@lingui/babel-plugin-extract-messages": "^4.0.0-next.5",
57
+ "@lingui/conf": "^4.0.0-next.5",
58
+ "@lingui/core": "^4.0.0-next.5",
59
+ "@lingui/format-po": "^4.0.0-next.5",
60
+ "@lingui/message-utils": "^4.0.0-next.5",
57
61
  "babel-plugin-macros": "^3.0.1",
58
62
  "chalk": "^4.1.0",
59
63
  "chokidar": "3.5.1",
@@ -75,11 +79,13 @@
75
79
  },
76
80
  "devDependencies": {
77
81
  "@lingui/jest-mocks": "^3.0.3",
82
+ "@swc/cli": "^0.1.62",
83
+ "@swc/core": "^1.3.42",
78
84
  "@types/convert-source-map": "^2.0.0",
79
85
  "@types/micromatch": "^4.0.1",
80
86
  "@types/normalize-path": "^3.0.0",
81
87
  "mock-fs": "^5.2.0",
82
88
  "mockdate": "^3.0.5"
83
89
  },
84
- "gitHead": "3b999e35d26e67dec7cf0591f794be782e11022c"
90
+ "gitHead": "bdbd6cf310cbcf09e1fe288f20ef530c28de481d"
85
91
  }
package/build/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- The MIT License (MIT)
2
-
3
- Copyright (c) 2017-2022 Tomáš Ehrlich, (c) 2022-2023 Crowdin.
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in
13
- all copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
- THE SOFTWARE.
@@ -1,45 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.extractFromFiles = extractFromFiles;
7
- var _extractors = _interopRequireDefault(require("../extractors"));
8
- var _path = _interopRequireDefault(require("path"));
9
- var _chalk = _interopRequireDefault(require("chalk"));
10
- var _utils = require("../utils");
11
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
- async function extractFromFiles(paths, config) {
13
- const messages = {};
14
- let catalogSuccess = true;
15
- for (let filename of paths) {
16
- const fileSuccess = await (0, _extractors.default)(filename, next => {
17
- if (!messages[next.id]) {
18
- messages[next.id] = {
19
- message: next.message,
20
- context: next.context,
21
- comments: [],
22
- origin: []
23
- };
24
- }
25
- const prev = messages[next.id];
26
-
27
- // there might be a case when filename was not mapped from sourcemaps
28
- const filename = next.origin[0] ? _path.default.relative(config.rootDir, next.origin[0]).replace(/\\/g, "/") : "";
29
- const origin = [filename, next.origin[1]];
30
- if (prev.message && next.message && prev.message !== next.message) {
31
- throw new Error(`Encountered different default translations for message ${_chalk.default.yellow(next.id)}` + `\n${_chalk.default.yellow((0, _utils.prettyOrigin)(prev.origin))} ${prev.message}` + `\n${_chalk.default.yellow((0, _utils.prettyOrigin)([origin]))} ${next.message}`);
32
- }
33
- messages[next.id] = {
34
- ...prev,
35
- comments: next.comment ? [...prev.comments, next.comment] : prev.comments,
36
- origin: [...prev.origin, [filename, next.origin[1]]]
37
- };
38
- }, config, {
39
- extractors: config.extractors
40
- });
41
- catalogSuccess && (catalogSuccess = fileSuccess);
42
- }
43
- if (!catalogSuccess) return undefined;
44
- return messages;
45
- }
@@ -1,138 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.getCatalogForFile = getCatalogForFile;
7
- exports.getCatalogForMerge = getCatalogForMerge;
8
- exports.getCatalogs = getCatalogs;
9
- var _glob = _interopRequireDefault(require("glob"));
10
- var _path = _interopRequireDefault(require("path"));
11
- var _catalog = require("../catalog");
12
- var _utils = require("../utils");
13
- var _micromatch = _interopRequireDefault(require("micromatch"));
14
- var _formats = require("../formats");
15
- var _getExperimentalCatalogs = require("../../extract-experimental/getExperimentalCatalogs");
16
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
- const NAME_PH = "{name}";
18
- const LOCALE_PH = "{locale}";
19
-
20
- /**
21
- * Parse `config.catalogs` and return a list of configured Catalog instances.
22
- */
23
- async function getCatalogs(config) {
24
- var _config$experimental, _config$experimental$;
25
- const catalogsConfig = config.catalogs;
26
- const catalogs = [];
27
- const format = await (0, _formats.getFormat)(config.format, config.formatOptions, config.sourceLocale);
28
- catalogsConfig.forEach(catalog => {
29
- validateCatalogPath(catalog.path, format.getCatalogExtension());
30
- const include = ensureArray(catalog.include).map(_utils.normalizeRelativePath);
31
- const exclude = ensureArray(catalog.exclude).map(_utils.normalizeRelativePath);
32
-
33
- // catalog.path without {name} pattern -> always refers to a single catalog
34
- if (!catalog.path.includes(NAME_PH)) {
35
- // Validate that sourcePaths doesn't use {name} pattern either
36
- const invalidSource = include.find(path => path.includes(NAME_PH));
37
- if (invalidSource !== undefined) {
38
- throw new Error(`Catalog with path "${catalog.path}" doesn't have a {name} pattern` + ` in it, but one of source directories uses it: "${invalidSource}".` + ` Either add {name} pattern to "${catalog.path}" or remove it` + ` from all source directories.`);
39
- }
40
- catalogs.push(new _catalog.Catalog({
41
- name: getCatalogName(catalog.path),
42
- path: (0, _utils.normalizeRelativePath)(catalog.path),
43
- include,
44
- exclude,
45
- format
46
- }, config));
47
- return;
48
- }
49
- const patterns = include.map(path => (0, _utils.replacePlaceholders)(path, {
50
- name: "*"
51
- }));
52
- const candidates = _glob.default.sync(patterns.length > 1 ? `{${patterns.join(",")}}` : patterns[0], {
53
- ignore: exclude,
54
- mark: true
55
- });
56
- candidates.forEach(catalogDir => {
57
- const name = _path.default.basename(catalogDir);
58
- catalogs.push(new _catalog.Catalog({
59
- name,
60
- path: (0, _utils.normalizeRelativePath)((0, _utils.replacePlaceholders)(catalog.path, {
61
- name
62
- })),
63
- include: include.map(path => (0, _utils.replacePlaceholders)(path, {
64
- name
65
- })),
66
- exclude: exclude.map(path => (0, _utils.replacePlaceholders)(path, {
67
- name
68
- })),
69
- format
70
- }, config));
71
- });
72
- });
73
- if ((_config$experimental = config.experimental) !== null && _config$experimental !== void 0 && (_config$experimental$ = _config$experimental.extractor) !== null && _config$experimental$ !== void 0 && _config$experimental$.entries.length) {
74
- catalogs.push(...(await (0, _getExperimentalCatalogs.getExperimentalCatalogs)(config)));
75
- }
76
- return catalogs;
77
- }
78
-
79
- /**
80
- * Ensure that value is always array. If not, turn it into an array of one element.
81
- */
82
- const ensureArray = value => {
83
- if (value == null) return [];
84
- return Array.isArray(value) ? value : [value];
85
- };
86
-
87
- /**
88
- * Create catalog for merged messages.
89
- */
90
- async function getCatalogForMerge(config) {
91
- const format = await (0, _formats.getFormat)(config.format, config.formatOptions, config.sourceLocale);
92
- validateCatalogPath(config.catalogsMergePath, format.getCatalogExtension());
93
- return new _catalog.Catalog({
94
- name: getCatalogName(config.catalogsMergePath),
95
- path: (0, _utils.normalizeRelativePath)(config.catalogsMergePath),
96
- include: [],
97
- exclude: [],
98
- format
99
- }, config);
100
- }
101
- function getCatalogForFile(file, catalogs) {
102
- for (const catalog of catalogs) {
103
- const catalogFile = `${catalog.path}${catalog.format.getCatalogExtension()}`;
104
- const catalogGlob = (0, _utils.replacePlaceholders)(catalogFile, {
105
- locale: "*"
106
- });
107
- const match = _micromatch.default.capture((0, _utils.normalizeRelativePath)(_path.default.relative(catalog.config.rootDir, catalogGlob)), (0, _utils.normalizeRelativePath)(file));
108
- if (match) {
109
- return {
110
- locale: match[0],
111
- catalog
112
- };
113
- }
114
- }
115
- return null;
116
- }
117
-
118
- /**
119
- * Validate that `catalogPath` doesn't end with trailing slash
120
- */
121
- function validateCatalogPath(path, extension) {
122
- if (!path.endsWith(_utils.PATHSEP)) {
123
- return;
124
- }
125
- const correctPath = path.slice(0, -1);
126
- const examplePath = (0, _utils.replacePlaceholders)(correctPath, {
127
- locale: "en"
128
- }) + extension;
129
- throw new Error(
130
- // prettier-ignore
131
- `Remove trailing slash from "${path}". Catalog path isn't a directory,` + ` but translation file without extension. For example, catalog path "${correctPath}"` + ` results in translation file "${examplePath}".`);
132
- }
133
- function getCatalogName(filePath) {
134
- // catalog name is the last directory of catalogPath.
135
- // If the last part is {locale}, then catalog doesn't have an explicit name
136
- const _name = _path.default.basename((0, _utils.normalizeRelativePath)(filePath));
137
- return _name !== LOCALE_PH ? _name : null;
138
- }