@vocab/phrase 0.0.0-add-support-for-vocab-cjs-20231109235141

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ ### MIT License
2
+
3
+ Copyright (c) 2020 SEEK
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 all
13
+ 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 THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ export { pull } from "./pull-translations.js";
2
+ export { push } from "./push-translations.js";
@@ -0,0 +1,8 @@
1
+ import { type UserConfig } from '@vocab/core';
2
+ interface PullOptions {
3
+ branch?: string;
4
+ deleteUnusedKeys?: boolean;
5
+ errorOnNoGlobalKeyTranslation?: boolean;
6
+ }
7
+ export declare function pull({ branch, errorOnNoGlobalKeyTranslation }: PullOptions, config: UserConfig): Promise<void>;
8
+ export {};
@@ -0,0 +1,11 @@
1
+ import { type UserConfig } from '@vocab/core';
2
+ interface PushOptions {
3
+ branch: string;
4
+ deleteUnusedKeys?: boolean;
5
+ }
6
+ /**
7
+ * Uploads translations to the Phrase API for each language.
8
+ * A unique namespace is appended to each key using the file path the key came from.
9
+ */
10
+ export declare function push({ branch, deleteUnusedKeys }: PushOptions, config: UserConfig): Promise<void>;
11
+ export {};
@@ -0,0 +1,2 @@
1
+ export * from "./declarations/src/index";
2
+ //# sourceMappingURL=vocab-phrase.cjs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vocab-phrase.cjs.d.ts","sourceRoot":"","sources":["./declarations/src/index.d.ts"],"names":[],"mappings":"AAAA"}
@@ -0,0 +1,357 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var fs = require('fs');
6
+ var path = require('path');
7
+ var core = require('@vocab/core');
8
+ var FormData = require('form-data');
9
+ var fetch = require('node-fetch');
10
+ var chalk = require('chalk');
11
+ var debug = require('debug');
12
+ var sync = require('csv-stringify/sync');
13
+
14
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
15
+
16
+ var path__default = /*#__PURE__*/_interopDefault(path);
17
+ var FormData__default = /*#__PURE__*/_interopDefault(FormData);
18
+ var fetch__default = /*#__PURE__*/_interopDefault(fetch);
19
+ var chalk__default = /*#__PURE__*/_interopDefault(chalk);
20
+ var debug__default = /*#__PURE__*/_interopDefault(debug);
21
+
22
+ const mkdir = fs.promises.mkdir;
23
+ const writeFile = fs.promises.writeFile;
24
+
25
+ const trace = debug__default["default"](`vocab:phrase`);
26
+ const log = (...params) => {
27
+ // eslint-disable-next-line no-console
28
+ console.log(chalk__default["default"].yellow('Vocab'), ...params);
29
+ };
30
+
31
+ function translationsToCsv(translations, devLanguage) {
32
+ const languages = Object.keys(translations);
33
+ const altLanguages = languages.filter(language => language !== devLanguage);
34
+ const devLanguageTranslations = translations[devLanguage];
35
+ const csvFilesByLanguage = Object.fromEntries(languages.map(language => [language, []]));
36
+ Object.entries(devLanguageTranslations).map(([key, {
37
+ message,
38
+ description,
39
+ tags
40
+ }]) => {
41
+ const sharedData = [key, description, tags === null || tags === void 0 ? void 0 : tags.join(',')];
42
+ const devLanguageRow = [...sharedData, message];
43
+ csvFilesByLanguage[devLanguage].push(devLanguageRow);
44
+ altLanguages.map(language => {
45
+ var _translations$languag;
46
+ const altTranslationMessage = (_translations$languag = translations[language]) === null || _translations$languag === void 0 || (_translations$languag = _translations$languag[key]) === null || _translations$languag === void 0 ? void 0 : _translations$languag.message;
47
+ if (altTranslationMessage) {
48
+ csvFilesByLanguage[language].push([...sharedData, altTranslationMessage]);
49
+ }
50
+ });
51
+ });
52
+ const csvFileStrings = Object.fromEntries(Object.entries(csvFilesByLanguage)
53
+ // Ensure CSV files are only created if the language has at least 1 translation
54
+ .filter(([_, csvFile]) => csvFile.length > 0).map(([language, csvFile]) => {
55
+ const csvFileString = sync.stringify(csvFile, {
56
+ delimiter: ',',
57
+ header: false
58
+ });
59
+ return [language, csvFileString];
60
+ }));
61
+
62
+ // Column indices start at 1
63
+ const keyIndex = 1;
64
+ const commentIndex = keyIndex + 1;
65
+ const tagColumn = commentIndex + 1;
66
+ const messageIndex = tagColumn + 1;
67
+ return {
68
+ csvFileStrings,
69
+ keyIndex,
70
+ messageIndex,
71
+ commentIndex,
72
+ tagColumn
73
+ };
74
+ }
75
+
76
+ /* eslint-disable no-console */
77
+ function _callPhrase(path, options = {}) {
78
+ const phraseApiToken = process.env.PHRASE_API_TOKEN;
79
+ if (!phraseApiToken) {
80
+ throw new Error('Missing PHRASE_API_TOKEN');
81
+ }
82
+ return fetch__default["default"](path, {
83
+ ...options,
84
+ headers: {
85
+ Authorization: `token ${phraseApiToken}`,
86
+ // Provide identification via User Agent as requested in https://developers.phrase.com/api/#overview--identification-via-user-agent
87
+ 'User-Agent': 'SEEK Demo Candidate App (jhope@seek.com.au)',
88
+ ...options.headers
89
+ }
90
+ }).then(async response => {
91
+ console.log(`${path}: ${response.status} - ${response.statusText}`);
92
+ const secondsUntilLimitReset = Math.ceil(Number.parseFloat(response.headers.get('X-Rate-Limit-Reset') || '0') - Date.now() / 1000);
93
+ console.log(`Rate Limit: ${response.headers.get('X-Rate-Limit-Remaining')} of ${response.headers.get('X-Rate-Limit-Limit')} remaining. (${secondsUntilLimitReset} seconds remaining)`);
94
+ trace('\nLink:', response.headers.get('Link'), '\n');
95
+ // Print All Headers:
96
+ // console.log(Array.from(r.headers.entries()));
97
+
98
+ try {
99
+ var _response$headers$get;
100
+ const result = await response.json();
101
+ trace(`Internal Result (Length: ${result.length})\n`);
102
+ if ((!options.method || options.method === 'GET') && (_response$headers$get = response.headers.get('Link')) !== null && _response$headers$get !== void 0 && _response$headers$get.includes('rel=next')) {
103
+ var _response$headers$get2, _response$headers$get3;
104
+ const [, nextPageUrl] = (_response$headers$get2 = (_response$headers$get3 = response.headers.get('Link')) === null || _response$headers$get3 === void 0 ? void 0 : _response$headers$get3.match(/<([^>]*)>; rel=next/)) !== null && _response$headers$get2 !== void 0 ? _response$headers$get2 : [];
105
+ if (!nextPageUrl) {
106
+ throw new Error("Can't parse next page URL");
107
+ }
108
+ console.log('Results received with next page: ', nextPageUrl);
109
+ const nextPageResult = await _callPhrase(nextPageUrl, options);
110
+ return [...result, ...nextPageResult];
111
+ }
112
+ return result;
113
+ } catch (e) {
114
+ console.error('Unable to parse response as JSON', e);
115
+ return response.text();
116
+ }
117
+ });
118
+ }
119
+ async function callPhrase(relativePath, options = {}) {
120
+ const projectId = process.env.PHRASE_PROJECT_ID;
121
+ if (!projectId) {
122
+ throw new Error('Missing PHRASE_PROJECT_ID');
123
+ }
124
+ return _callPhrase(`https://api.phrase.com/v2/projects/${projectId}/${relativePath}`, options).then(result => {
125
+ if (Array.isArray(result)) {
126
+ console.log('Result length:', result.length);
127
+ }
128
+ return result;
129
+ }).catch(error => {
130
+ console.error(`Error calling phrase for ${relativePath}:`, error);
131
+ throw Error;
132
+ });
133
+ }
134
+ async function pullAllTranslations(branch) {
135
+ const phraseResult = await callPhrase(`translations?branch=${branch}&per_page=100`);
136
+ const translations = {};
137
+ for (const r of phraseResult) {
138
+ if (!translations[r.locale.code]) {
139
+ translations[r.locale.code] = {};
140
+ }
141
+ translations[r.locale.code][r.key.name] = {
142
+ message: r.content
143
+ };
144
+ }
145
+ return translations;
146
+ }
147
+ async function pushTranslations(translationsByLanguage, {
148
+ devLanguage,
149
+ branch
150
+ }) {
151
+ const {
152
+ csvFileStrings,
153
+ keyIndex,
154
+ commentIndex,
155
+ tagColumn,
156
+ messageIndex
157
+ } = translationsToCsv(translationsByLanguage, devLanguage);
158
+ let devLanguageUploadId = '';
159
+ for (const [language, csvFileString] of Object.entries(csvFileStrings)) {
160
+ const formData = new FormData__default["default"]();
161
+ const fileContents = Buffer.from(csvFileString);
162
+ formData.append('file', fileContents, {
163
+ contentType: 'text/csv',
164
+ filename: `${language}.translations.csv`
165
+ });
166
+ formData.append('file_format', 'csv');
167
+ formData.append('branch', branch);
168
+ formData.append('update_translations', 'true');
169
+ formData.append('update_descriptions', 'true');
170
+ formData.append(`locale_mapping[${language}]`, messageIndex);
171
+ formData.append('format_options[key_index]', keyIndex);
172
+ formData.append('format_options[comment_index]', commentIndex);
173
+ formData.append('format_options[tag_column]', tagColumn);
174
+ formData.append('format_options[enable_pluralization]', 'false');
175
+ log(`Uploading translations for language ${language}`);
176
+ const result = await callPhrase(`uploads`, {
177
+ method: 'POST',
178
+ body: formData
179
+ });
180
+ trace('Upload result:\n', result);
181
+ if (result && 'id' in result) {
182
+ log('Upload ID:', result.id, '\n');
183
+ log('Successfully Uploaded\n');
184
+ } else {
185
+ log(`Error uploading: ${result === null || result === void 0 ? void 0 : result.message}\n`);
186
+ log('Response:', result);
187
+ throw new Error('Error uploading');
188
+ }
189
+ if (language === devLanguage) {
190
+ devLanguageUploadId = result.id;
191
+ }
192
+ }
193
+ return {
194
+ devLanguageUploadId
195
+ };
196
+ }
197
+ async function deleteUnusedKeys(uploadId, branch) {
198
+ const query = `unmentioned_in_upload:${uploadId}`;
199
+ const {
200
+ records_affected
201
+ } = await callPhrase('keys', {
202
+ method: 'DELETE',
203
+ headers: {
204
+ 'Content-Type': 'application/json'
205
+ },
206
+ body: JSON.stringify({
207
+ branch,
208
+ q: query
209
+ })
210
+ });
211
+ log('Successfully deleted', records_affected, 'unused keys from branch', branch);
212
+ }
213
+ async function ensureBranch(branch) {
214
+ await callPhrase(`branches`, {
215
+ method: 'POST',
216
+ headers: {
217
+ 'Content-Type': 'application/json'
218
+ },
219
+ body: JSON.stringify({
220
+ name: branch
221
+ })
222
+ });
223
+ log('Created branch:', branch);
224
+ }
225
+
226
+ async function pull({
227
+ branch = 'local-development',
228
+ errorOnNoGlobalKeyTranslation
229
+ }, config) {
230
+ trace(`Pulling translations from branch ${branch}`);
231
+ await ensureBranch(branch);
232
+ const alternativeLanguages = core.getAltLanguages(config);
233
+ const allPhraseTranslations = await pullAllTranslations(branch);
234
+ trace(`Pulling translations from Phrase for languages ${config.devLanguage} and ${alternativeLanguages.join(', ')}`);
235
+ const phraseLanguages = Object.keys(allPhraseTranslations);
236
+ trace(`Found Phrase translations for languages ${phraseLanguages.join(', ')}`);
237
+ if (!phraseLanguages.includes(config.devLanguage)) {
238
+ throw new Error(`Phrase did not return any translations for the configured development language "${config.devLanguage}".\nPlease ensure this language is present in your Phrase project's configuration.`);
239
+ }
240
+ const allVocabTranslations = await core.loadAllTranslations({
241
+ fallbacks: 'none',
242
+ includeNodeModules: false,
243
+ withTags: true
244
+ }, config);
245
+ for (const loadedTranslation of allVocabTranslations) {
246
+ const devTranslations = loadedTranslation.languages[config.devLanguage];
247
+ if (!devTranslations) {
248
+ throw new Error('No dev language translations loaded');
249
+ }
250
+ const defaultValues = {
251
+ ...devTranslations
252
+ };
253
+ const localKeys = Object.keys(defaultValues);
254
+ for (const key of localKeys) {
255
+ var _defaultValues$key$gl;
256
+ defaultValues[key] = {
257
+ ...defaultValues[key],
258
+ ...allPhraseTranslations[config.devLanguage][(_defaultValues$key$gl = defaultValues[key].globalKey) !== null && _defaultValues$key$gl !== void 0 ? _defaultValues$key$gl : core.getUniqueKey(key, loadedTranslation.namespace)]
259
+ };
260
+ }
261
+
262
+ // Only write a `_meta` field if necessary
263
+ if (Object.keys(loadedTranslation.metadata).length > 0) {
264
+ defaultValues._meta = loadedTranslation.metadata;
265
+ }
266
+ await writeFile(loadedTranslation.filePath, `${JSON.stringify(defaultValues, null, 2)}\n`);
267
+ for (const alternativeLanguage of alternativeLanguages) {
268
+ if (alternativeLanguage in allPhraseTranslations) {
269
+ const altTranslations = {
270
+ ...loadedTranslation.languages[alternativeLanguage]
271
+ };
272
+ const phraseAltTranslations = allPhraseTranslations[alternativeLanguage];
273
+ for (const key of localKeys) {
274
+ var _defaultValues$key$gl2, _phraseAltTranslation;
275
+ const phraseKey = (_defaultValues$key$gl2 = defaultValues[key].globalKey) !== null && _defaultValues$key$gl2 !== void 0 ? _defaultValues$key$gl2 : core.getUniqueKey(key, loadedTranslation.namespace);
276
+ const phraseTranslationMessage = (_phraseAltTranslation = phraseAltTranslations[phraseKey]) === null || _phraseAltTranslation === void 0 ? void 0 : _phraseAltTranslation.message;
277
+ if (!phraseTranslationMessage) {
278
+ trace(`Missing translation. No translation for key ${key} in phrase as ${phraseKey} in language ${alternativeLanguage}.`);
279
+ if (errorOnNoGlobalKeyTranslation && defaultValues[key].globalKey) {
280
+ throw new Error(`Missing translation for global key ${key} in language ${alternativeLanguage}`);
281
+ }
282
+ continue;
283
+ }
284
+ altTranslations[key] = {
285
+ ...altTranslations[key],
286
+ message: phraseTranslationMessage
287
+ };
288
+ }
289
+ const altTranslationFilePath = core.getAltLanguageFilePath(loadedTranslation.filePath, alternativeLanguage);
290
+ await mkdir(path__default["default"].dirname(altTranslationFilePath), {
291
+ recursive: true
292
+ });
293
+ await writeFile(altTranslationFilePath, `${JSON.stringify(altTranslations, null, 2)}\n`);
294
+ }
295
+ }
296
+ }
297
+ }
298
+
299
+ /**
300
+ * Uploads translations to the Phrase API for each language.
301
+ * A unique namespace is appended to each key using the file path the key came from.
302
+ */
303
+ async function push({
304
+ branch,
305
+ deleteUnusedKeys: deleteUnusedKeys$1
306
+ }, config) {
307
+ const allLanguageTranslations = await core.loadAllTranslations({
308
+ fallbacks: 'none',
309
+ includeNodeModules: false,
310
+ withTags: true
311
+ }, config);
312
+ trace(`Pushing translations to branch ${branch}`);
313
+ const allLanguages = config.languages.map(v => v.name);
314
+ await ensureBranch(branch);
315
+ trace(`Pushing translations to phrase for languages ${allLanguages.join(', ')}`);
316
+ const phraseTranslations = {};
317
+ for (const loadedTranslation of allLanguageTranslations) {
318
+ for (const language of allLanguages) {
319
+ const localTranslations = loadedTranslation.languages[language];
320
+ if (!localTranslations) {
321
+ continue;
322
+ }
323
+ if (!phraseTranslations[language]) {
324
+ phraseTranslations[language] = {};
325
+ }
326
+ const {
327
+ metadata: {
328
+ tags: sharedTags = []
329
+ }
330
+ } = loadedTranslation;
331
+ for (const localKey of Object.keys(localTranslations)) {
332
+ const {
333
+ tags = [],
334
+ ...localTranslation
335
+ } = localTranslations[localKey];
336
+ if (language === config.devLanguage) {
337
+ localTranslation.tags = [...tags, ...sharedTags];
338
+ }
339
+ const globalKey = loadedTranslation.languages[config.devLanguage][localKey].globalKey;
340
+ const phraseKey = globalKey !== null && globalKey !== void 0 ? globalKey : core.getUniqueKey(localKey, loadedTranslation.namespace);
341
+ phraseTranslations[language][phraseKey] = localTranslation;
342
+ }
343
+ }
344
+ }
345
+ const {
346
+ devLanguageUploadId
347
+ } = await pushTranslations(phraseTranslations, {
348
+ devLanguage: config.devLanguage,
349
+ branch
350
+ });
351
+ if (deleteUnusedKeys$1) {
352
+ await deleteUnusedKeys(devLanguageUploadId, branch);
353
+ }
354
+ }
355
+
356
+ exports.pull = pull;
357
+ exports.push = push;
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ if (process.env.NODE_ENV === "production") {
4
+ module.exports = require("./vocab-phrase.cjs.prod.js");
5
+ } else {
6
+ module.exports = require("./vocab-phrase.cjs.dev.js");
7
+ }
@@ -0,0 +1,357 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var fs = require('fs');
6
+ var path = require('path');
7
+ var core = require('@vocab/core');
8
+ var FormData = require('form-data');
9
+ var fetch = require('node-fetch');
10
+ var chalk = require('chalk');
11
+ var debug = require('debug');
12
+ var sync = require('csv-stringify/sync');
13
+
14
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
15
+
16
+ var path__default = /*#__PURE__*/_interopDefault(path);
17
+ var FormData__default = /*#__PURE__*/_interopDefault(FormData);
18
+ var fetch__default = /*#__PURE__*/_interopDefault(fetch);
19
+ var chalk__default = /*#__PURE__*/_interopDefault(chalk);
20
+ var debug__default = /*#__PURE__*/_interopDefault(debug);
21
+
22
+ const mkdir = fs.promises.mkdir;
23
+ const writeFile = fs.promises.writeFile;
24
+
25
+ const trace = debug__default["default"](`vocab:phrase`);
26
+ const log = (...params) => {
27
+ // eslint-disable-next-line no-console
28
+ console.log(chalk__default["default"].yellow('Vocab'), ...params);
29
+ };
30
+
31
+ function translationsToCsv(translations, devLanguage) {
32
+ const languages = Object.keys(translations);
33
+ const altLanguages = languages.filter(language => language !== devLanguage);
34
+ const devLanguageTranslations = translations[devLanguage];
35
+ const csvFilesByLanguage = Object.fromEntries(languages.map(language => [language, []]));
36
+ Object.entries(devLanguageTranslations).map(([key, {
37
+ message,
38
+ description,
39
+ tags
40
+ }]) => {
41
+ const sharedData = [key, description, tags === null || tags === void 0 ? void 0 : tags.join(',')];
42
+ const devLanguageRow = [...sharedData, message];
43
+ csvFilesByLanguage[devLanguage].push(devLanguageRow);
44
+ altLanguages.map(language => {
45
+ var _translations$languag;
46
+ const altTranslationMessage = (_translations$languag = translations[language]) === null || _translations$languag === void 0 || (_translations$languag = _translations$languag[key]) === null || _translations$languag === void 0 ? void 0 : _translations$languag.message;
47
+ if (altTranslationMessage) {
48
+ csvFilesByLanguage[language].push([...sharedData, altTranslationMessage]);
49
+ }
50
+ });
51
+ });
52
+ const csvFileStrings = Object.fromEntries(Object.entries(csvFilesByLanguage)
53
+ // Ensure CSV files are only created if the language has at least 1 translation
54
+ .filter(([_, csvFile]) => csvFile.length > 0).map(([language, csvFile]) => {
55
+ const csvFileString = sync.stringify(csvFile, {
56
+ delimiter: ',',
57
+ header: false
58
+ });
59
+ return [language, csvFileString];
60
+ }));
61
+
62
+ // Column indices start at 1
63
+ const keyIndex = 1;
64
+ const commentIndex = keyIndex + 1;
65
+ const tagColumn = commentIndex + 1;
66
+ const messageIndex = tagColumn + 1;
67
+ return {
68
+ csvFileStrings,
69
+ keyIndex,
70
+ messageIndex,
71
+ commentIndex,
72
+ tagColumn
73
+ };
74
+ }
75
+
76
+ /* eslint-disable no-console */
77
+ function _callPhrase(path, options = {}) {
78
+ const phraseApiToken = process.env.PHRASE_API_TOKEN;
79
+ if (!phraseApiToken) {
80
+ throw new Error('Missing PHRASE_API_TOKEN');
81
+ }
82
+ return fetch__default["default"](path, {
83
+ ...options,
84
+ headers: {
85
+ Authorization: `token ${phraseApiToken}`,
86
+ // Provide identification via User Agent as requested in https://developers.phrase.com/api/#overview--identification-via-user-agent
87
+ 'User-Agent': 'SEEK Demo Candidate App (jhope@seek.com.au)',
88
+ ...options.headers
89
+ }
90
+ }).then(async response => {
91
+ console.log(`${path}: ${response.status} - ${response.statusText}`);
92
+ const secondsUntilLimitReset = Math.ceil(Number.parseFloat(response.headers.get('X-Rate-Limit-Reset') || '0') - Date.now() / 1000);
93
+ console.log(`Rate Limit: ${response.headers.get('X-Rate-Limit-Remaining')} of ${response.headers.get('X-Rate-Limit-Limit')} remaining. (${secondsUntilLimitReset} seconds remaining)`);
94
+ trace('\nLink:', response.headers.get('Link'), '\n');
95
+ // Print All Headers:
96
+ // console.log(Array.from(r.headers.entries()));
97
+
98
+ try {
99
+ var _response$headers$get;
100
+ const result = await response.json();
101
+ trace(`Internal Result (Length: ${result.length})\n`);
102
+ if ((!options.method || options.method === 'GET') && (_response$headers$get = response.headers.get('Link')) !== null && _response$headers$get !== void 0 && _response$headers$get.includes('rel=next')) {
103
+ var _response$headers$get2, _response$headers$get3;
104
+ const [, nextPageUrl] = (_response$headers$get2 = (_response$headers$get3 = response.headers.get('Link')) === null || _response$headers$get3 === void 0 ? void 0 : _response$headers$get3.match(/<([^>]*)>; rel=next/)) !== null && _response$headers$get2 !== void 0 ? _response$headers$get2 : [];
105
+ if (!nextPageUrl) {
106
+ throw new Error("Can't parse next page URL");
107
+ }
108
+ console.log('Results received with next page: ', nextPageUrl);
109
+ const nextPageResult = await _callPhrase(nextPageUrl, options);
110
+ return [...result, ...nextPageResult];
111
+ }
112
+ return result;
113
+ } catch (e) {
114
+ console.error('Unable to parse response as JSON', e);
115
+ return response.text();
116
+ }
117
+ });
118
+ }
119
+ async function callPhrase(relativePath, options = {}) {
120
+ const projectId = process.env.PHRASE_PROJECT_ID;
121
+ if (!projectId) {
122
+ throw new Error('Missing PHRASE_PROJECT_ID');
123
+ }
124
+ return _callPhrase(`https://api.phrase.com/v2/projects/${projectId}/${relativePath}`, options).then(result => {
125
+ if (Array.isArray(result)) {
126
+ console.log('Result length:', result.length);
127
+ }
128
+ return result;
129
+ }).catch(error => {
130
+ console.error(`Error calling phrase for ${relativePath}:`, error);
131
+ throw Error;
132
+ });
133
+ }
134
+ async function pullAllTranslations(branch) {
135
+ const phraseResult = await callPhrase(`translations?branch=${branch}&per_page=100`);
136
+ const translations = {};
137
+ for (const r of phraseResult) {
138
+ if (!translations[r.locale.code]) {
139
+ translations[r.locale.code] = {};
140
+ }
141
+ translations[r.locale.code][r.key.name] = {
142
+ message: r.content
143
+ };
144
+ }
145
+ return translations;
146
+ }
147
+ async function pushTranslations(translationsByLanguage, {
148
+ devLanguage,
149
+ branch
150
+ }) {
151
+ const {
152
+ csvFileStrings,
153
+ keyIndex,
154
+ commentIndex,
155
+ tagColumn,
156
+ messageIndex
157
+ } = translationsToCsv(translationsByLanguage, devLanguage);
158
+ let devLanguageUploadId = '';
159
+ for (const [language, csvFileString] of Object.entries(csvFileStrings)) {
160
+ const formData = new FormData__default["default"]();
161
+ const fileContents = Buffer.from(csvFileString);
162
+ formData.append('file', fileContents, {
163
+ contentType: 'text/csv',
164
+ filename: `${language}.translations.csv`
165
+ });
166
+ formData.append('file_format', 'csv');
167
+ formData.append('branch', branch);
168
+ formData.append('update_translations', 'true');
169
+ formData.append('update_descriptions', 'true');
170
+ formData.append(`locale_mapping[${language}]`, messageIndex);
171
+ formData.append('format_options[key_index]', keyIndex);
172
+ formData.append('format_options[comment_index]', commentIndex);
173
+ formData.append('format_options[tag_column]', tagColumn);
174
+ formData.append('format_options[enable_pluralization]', 'false');
175
+ log(`Uploading translations for language ${language}`);
176
+ const result = await callPhrase(`uploads`, {
177
+ method: 'POST',
178
+ body: formData
179
+ });
180
+ trace('Upload result:\n', result);
181
+ if (result && 'id' in result) {
182
+ log('Upload ID:', result.id, '\n');
183
+ log('Successfully Uploaded\n');
184
+ } else {
185
+ log(`Error uploading: ${result === null || result === void 0 ? void 0 : result.message}\n`);
186
+ log('Response:', result);
187
+ throw new Error('Error uploading');
188
+ }
189
+ if (language === devLanguage) {
190
+ devLanguageUploadId = result.id;
191
+ }
192
+ }
193
+ return {
194
+ devLanguageUploadId
195
+ };
196
+ }
197
+ async function deleteUnusedKeys(uploadId, branch) {
198
+ const query = `unmentioned_in_upload:${uploadId}`;
199
+ const {
200
+ records_affected
201
+ } = await callPhrase('keys', {
202
+ method: 'DELETE',
203
+ headers: {
204
+ 'Content-Type': 'application/json'
205
+ },
206
+ body: JSON.stringify({
207
+ branch,
208
+ q: query
209
+ })
210
+ });
211
+ log('Successfully deleted', records_affected, 'unused keys from branch', branch);
212
+ }
213
+ async function ensureBranch(branch) {
214
+ await callPhrase(`branches`, {
215
+ method: 'POST',
216
+ headers: {
217
+ 'Content-Type': 'application/json'
218
+ },
219
+ body: JSON.stringify({
220
+ name: branch
221
+ })
222
+ });
223
+ log('Created branch:', branch);
224
+ }
225
+
226
+ async function pull({
227
+ branch = 'local-development',
228
+ errorOnNoGlobalKeyTranslation
229
+ }, config) {
230
+ trace(`Pulling translations from branch ${branch}`);
231
+ await ensureBranch(branch);
232
+ const alternativeLanguages = core.getAltLanguages(config);
233
+ const allPhraseTranslations = await pullAllTranslations(branch);
234
+ trace(`Pulling translations from Phrase for languages ${config.devLanguage} and ${alternativeLanguages.join(', ')}`);
235
+ const phraseLanguages = Object.keys(allPhraseTranslations);
236
+ trace(`Found Phrase translations for languages ${phraseLanguages.join(', ')}`);
237
+ if (!phraseLanguages.includes(config.devLanguage)) {
238
+ throw new Error(`Phrase did not return any translations for the configured development language "${config.devLanguage}".\nPlease ensure this language is present in your Phrase project's configuration.`);
239
+ }
240
+ const allVocabTranslations = await core.loadAllTranslations({
241
+ fallbacks: 'none',
242
+ includeNodeModules: false,
243
+ withTags: true
244
+ }, config);
245
+ for (const loadedTranslation of allVocabTranslations) {
246
+ const devTranslations = loadedTranslation.languages[config.devLanguage];
247
+ if (!devTranslations) {
248
+ throw new Error('No dev language translations loaded');
249
+ }
250
+ const defaultValues = {
251
+ ...devTranslations
252
+ };
253
+ const localKeys = Object.keys(defaultValues);
254
+ for (const key of localKeys) {
255
+ var _defaultValues$key$gl;
256
+ defaultValues[key] = {
257
+ ...defaultValues[key],
258
+ ...allPhraseTranslations[config.devLanguage][(_defaultValues$key$gl = defaultValues[key].globalKey) !== null && _defaultValues$key$gl !== void 0 ? _defaultValues$key$gl : core.getUniqueKey(key, loadedTranslation.namespace)]
259
+ };
260
+ }
261
+
262
+ // Only write a `_meta` field if necessary
263
+ if (Object.keys(loadedTranslation.metadata).length > 0) {
264
+ defaultValues._meta = loadedTranslation.metadata;
265
+ }
266
+ await writeFile(loadedTranslation.filePath, `${JSON.stringify(defaultValues, null, 2)}\n`);
267
+ for (const alternativeLanguage of alternativeLanguages) {
268
+ if (alternativeLanguage in allPhraseTranslations) {
269
+ const altTranslations = {
270
+ ...loadedTranslation.languages[alternativeLanguage]
271
+ };
272
+ const phraseAltTranslations = allPhraseTranslations[alternativeLanguage];
273
+ for (const key of localKeys) {
274
+ var _defaultValues$key$gl2, _phraseAltTranslation;
275
+ const phraseKey = (_defaultValues$key$gl2 = defaultValues[key].globalKey) !== null && _defaultValues$key$gl2 !== void 0 ? _defaultValues$key$gl2 : core.getUniqueKey(key, loadedTranslation.namespace);
276
+ const phraseTranslationMessage = (_phraseAltTranslation = phraseAltTranslations[phraseKey]) === null || _phraseAltTranslation === void 0 ? void 0 : _phraseAltTranslation.message;
277
+ if (!phraseTranslationMessage) {
278
+ trace(`Missing translation. No translation for key ${key} in phrase as ${phraseKey} in language ${alternativeLanguage}.`);
279
+ if (errorOnNoGlobalKeyTranslation && defaultValues[key].globalKey) {
280
+ throw new Error(`Missing translation for global key ${key} in language ${alternativeLanguage}`);
281
+ }
282
+ continue;
283
+ }
284
+ altTranslations[key] = {
285
+ ...altTranslations[key],
286
+ message: phraseTranslationMessage
287
+ };
288
+ }
289
+ const altTranslationFilePath = core.getAltLanguageFilePath(loadedTranslation.filePath, alternativeLanguage);
290
+ await mkdir(path__default["default"].dirname(altTranslationFilePath), {
291
+ recursive: true
292
+ });
293
+ await writeFile(altTranslationFilePath, `${JSON.stringify(altTranslations, null, 2)}\n`);
294
+ }
295
+ }
296
+ }
297
+ }
298
+
299
+ /**
300
+ * Uploads translations to the Phrase API for each language.
301
+ * A unique namespace is appended to each key using the file path the key came from.
302
+ */
303
+ async function push({
304
+ branch,
305
+ deleteUnusedKeys: deleteUnusedKeys$1
306
+ }, config) {
307
+ const allLanguageTranslations = await core.loadAllTranslations({
308
+ fallbacks: 'none',
309
+ includeNodeModules: false,
310
+ withTags: true
311
+ }, config);
312
+ trace(`Pushing translations to branch ${branch}`);
313
+ const allLanguages = config.languages.map(v => v.name);
314
+ await ensureBranch(branch);
315
+ trace(`Pushing translations to phrase for languages ${allLanguages.join(', ')}`);
316
+ const phraseTranslations = {};
317
+ for (const loadedTranslation of allLanguageTranslations) {
318
+ for (const language of allLanguages) {
319
+ const localTranslations = loadedTranslation.languages[language];
320
+ if (!localTranslations) {
321
+ continue;
322
+ }
323
+ if (!phraseTranslations[language]) {
324
+ phraseTranslations[language] = {};
325
+ }
326
+ const {
327
+ metadata: {
328
+ tags: sharedTags = []
329
+ }
330
+ } = loadedTranslation;
331
+ for (const localKey of Object.keys(localTranslations)) {
332
+ const {
333
+ tags = [],
334
+ ...localTranslation
335
+ } = localTranslations[localKey];
336
+ if (language === config.devLanguage) {
337
+ localTranslation.tags = [...tags, ...sharedTags];
338
+ }
339
+ const globalKey = loadedTranslation.languages[config.devLanguage][localKey].globalKey;
340
+ const phraseKey = globalKey !== null && globalKey !== void 0 ? globalKey : core.getUniqueKey(localKey, loadedTranslation.namespace);
341
+ phraseTranslations[language][phraseKey] = localTranslation;
342
+ }
343
+ }
344
+ }
345
+ const {
346
+ devLanguageUploadId
347
+ } = await pushTranslations(phraseTranslations, {
348
+ devLanguage: config.devLanguage,
349
+ branch
350
+ });
351
+ if (deleteUnusedKeys$1) {
352
+ await deleteUnusedKeys(devLanguageUploadId, branch);
353
+ }
354
+ }
355
+
356
+ exports.pull = pull;
357
+ exports.push = push;
@@ -0,0 +1,344 @@
1
+ import { promises } from 'fs';
2
+ import path from 'path';
3
+ import { getAltLanguages, loadAllTranslations, getUniqueKey, getAltLanguageFilePath } from '@vocab/core';
4
+ import FormData from 'form-data';
5
+ import fetch from 'node-fetch';
6
+ import chalk from 'chalk';
7
+ import debug from 'debug';
8
+ import { stringify } from 'csv-stringify/sync';
9
+
10
+ const mkdir = promises.mkdir;
11
+ const writeFile = promises.writeFile;
12
+
13
+ const trace = debug(`vocab:phrase`);
14
+ const log = (...params) => {
15
+ // eslint-disable-next-line no-console
16
+ console.log(chalk.yellow('Vocab'), ...params);
17
+ };
18
+
19
+ function translationsToCsv(translations, devLanguage) {
20
+ const languages = Object.keys(translations);
21
+ const altLanguages = languages.filter(language => language !== devLanguage);
22
+ const devLanguageTranslations = translations[devLanguage];
23
+ const csvFilesByLanguage = Object.fromEntries(languages.map(language => [language, []]));
24
+ Object.entries(devLanguageTranslations).map(([key, {
25
+ message,
26
+ description,
27
+ tags
28
+ }]) => {
29
+ const sharedData = [key, description, tags === null || tags === void 0 ? void 0 : tags.join(',')];
30
+ const devLanguageRow = [...sharedData, message];
31
+ csvFilesByLanguage[devLanguage].push(devLanguageRow);
32
+ altLanguages.map(language => {
33
+ var _translations$languag;
34
+ const altTranslationMessage = (_translations$languag = translations[language]) === null || _translations$languag === void 0 || (_translations$languag = _translations$languag[key]) === null || _translations$languag === void 0 ? void 0 : _translations$languag.message;
35
+ if (altTranslationMessage) {
36
+ csvFilesByLanguage[language].push([...sharedData, altTranslationMessage]);
37
+ }
38
+ });
39
+ });
40
+ const csvFileStrings = Object.fromEntries(Object.entries(csvFilesByLanguage)
41
+ // Ensure CSV files are only created if the language has at least 1 translation
42
+ .filter(([_, csvFile]) => csvFile.length > 0).map(([language, csvFile]) => {
43
+ const csvFileString = stringify(csvFile, {
44
+ delimiter: ',',
45
+ header: false
46
+ });
47
+ return [language, csvFileString];
48
+ }));
49
+
50
+ // Column indices start at 1
51
+ const keyIndex = 1;
52
+ const commentIndex = keyIndex + 1;
53
+ const tagColumn = commentIndex + 1;
54
+ const messageIndex = tagColumn + 1;
55
+ return {
56
+ csvFileStrings,
57
+ keyIndex,
58
+ messageIndex,
59
+ commentIndex,
60
+ tagColumn
61
+ };
62
+ }
63
+
64
+ /* eslint-disable no-console */
65
+ function _callPhrase(path, options = {}) {
66
+ const phraseApiToken = process.env.PHRASE_API_TOKEN;
67
+ if (!phraseApiToken) {
68
+ throw new Error('Missing PHRASE_API_TOKEN');
69
+ }
70
+ return fetch(path, {
71
+ ...options,
72
+ headers: {
73
+ Authorization: `token ${phraseApiToken}`,
74
+ // Provide identification via User Agent as requested in https://developers.phrase.com/api/#overview--identification-via-user-agent
75
+ 'User-Agent': 'SEEK Demo Candidate App (jhope@seek.com.au)',
76
+ ...options.headers
77
+ }
78
+ }).then(async response => {
79
+ console.log(`${path}: ${response.status} - ${response.statusText}`);
80
+ const secondsUntilLimitReset = Math.ceil(Number.parseFloat(response.headers.get('X-Rate-Limit-Reset') || '0') - Date.now() / 1000);
81
+ console.log(`Rate Limit: ${response.headers.get('X-Rate-Limit-Remaining')} of ${response.headers.get('X-Rate-Limit-Limit')} remaining. (${secondsUntilLimitReset} seconds remaining)`);
82
+ trace('\nLink:', response.headers.get('Link'), '\n');
83
+ // Print All Headers:
84
+ // console.log(Array.from(r.headers.entries()));
85
+
86
+ try {
87
+ var _response$headers$get;
88
+ const result = await response.json();
89
+ trace(`Internal Result (Length: ${result.length})\n`);
90
+ if ((!options.method || options.method === 'GET') && (_response$headers$get = response.headers.get('Link')) !== null && _response$headers$get !== void 0 && _response$headers$get.includes('rel=next')) {
91
+ var _response$headers$get2, _response$headers$get3;
92
+ const [, nextPageUrl] = (_response$headers$get2 = (_response$headers$get3 = response.headers.get('Link')) === null || _response$headers$get3 === void 0 ? void 0 : _response$headers$get3.match(/<([^>]*)>; rel=next/)) !== null && _response$headers$get2 !== void 0 ? _response$headers$get2 : [];
93
+ if (!nextPageUrl) {
94
+ throw new Error("Can't parse next page URL");
95
+ }
96
+ console.log('Results received with next page: ', nextPageUrl);
97
+ const nextPageResult = await _callPhrase(nextPageUrl, options);
98
+ return [...result, ...nextPageResult];
99
+ }
100
+ return result;
101
+ } catch (e) {
102
+ console.error('Unable to parse response as JSON', e);
103
+ return response.text();
104
+ }
105
+ });
106
+ }
107
+ async function callPhrase(relativePath, options = {}) {
108
+ const projectId = process.env.PHRASE_PROJECT_ID;
109
+ if (!projectId) {
110
+ throw new Error('Missing PHRASE_PROJECT_ID');
111
+ }
112
+ return _callPhrase(`https://api.phrase.com/v2/projects/${projectId}/${relativePath}`, options).then(result => {
113
+ if (Array.isArray(result)) {
114
+ console.log('Result length:', result.length);
115
+ }
116
+ return result;
117
+ }).catch(error => {
118
+ console.error(`Error calling phrase for ${relativePath}:`, error);
119
+ throw Error;
120
+ });
121
+ }
122
+ async function pullAllTranslations(branch) {
123
+ const phraseResult = await callPhrase(`translations?branch=${branch}&per_page=100`);
124
+ const translations = {};
125
+ for (const r of phraseResult) {
126
+ if (!translations[r.locale.code]) {
127
+ translations[r.locale.code] = {};
128
+ }
129
+ translations[r.locale.code][r.key.name] = {
130
+ message: r.content
131
+ };
132
+ }
133
+ return translations;
134
+ }
135
+ async function pushTranslations(translationsByLanguage, {
136
+ devLanguage,
137
+ branch
138
+ }) {
139
+ const {
140
+ csvFileStrings,
141
+ keyIndex,
142
+ commentIndex,
143
+ tagColumn,
144
+ messageIndex
145
+ } = translationsToCsv(translationsByLanguage, devLanguage);
146
+ let devLanguageUploadId = '';
147
+ for (const [language, csvFileString] of Object.entries(csvFileStrings)) {
148
+ const formData = new FormData();
149
+ const fileContents = Buffer.from(csvFileString);
150
+ formData.append('file', fileContents, {
151
+ contentType: 'text/csv',
152
+ filename: `${language}.translations.csv`
153
+ });
154
+ formData.append('file_format', 'csv');
155
+ formData.append('branch', branch);
156
+ formData.append('update_translations', 'true');
157
+ formData.append('update_descriptions', 'true');
158
+ formData.append(`locale_mapping[${language}]`, messageIndex);
159
+ formData.append('format_options[key_index]', keyIndex);
160
+ formData.append('format_options[comment_index]', commentIndex);
161
+ formData.append('format_options[tag_column]', tagColumn);
162
+ formData.append('format_options[enable_pluralization]', 'false');
163
+ log(`Uploading translations for language ${language}`);
164
+ const result = await callPhrase(`uploads`, {
165
+ method: 'POST',
166
+ body: formData
167
+ });
168
+ trace('Upload result:\n', result);
169
+ if (result && 'id' in result) {
170
+ log('Upload ID:', result.id, '\n');
171
+ log('Successfully Uploaded\n');
172
+ } else {
173
+ log(`Error uploading: ${result === null || result === void 0 ? void 0 : result.message}\n`);
174
+ log('Response:', result);
175
+ throw new Error('Error uploading');
176
+ }
177
+ if (language === devLanguage) {
178
+ devLanguageUploadId = result.id;
179
+ }
180
+ }
181
+ return {
182
+ devLanguageUploadId
183
+ };
184
+ }
185
+ async function deleteUnusedKeys(uploadId, branch) {
186
+ const query = `unmentioned_in_upload:${uploadId}`;
187
+ const {
188
+ records_affected
189
+ } = await callPhrase('keys', {
190
+ method: 'DELETE',
191
+ headers: {
192
+ 'Content-Type': 'application/json'
193
+ },
194
+ body: JSON.stringify({
195
+ branch,
196
+ q: query
197
+ })
198
+ });
199
+ log('Successfully deleted', records_affected, 'unused keys from branch', branch);
200
+ }
201
+ async function ensureBranch(branch) {
202
+ await callPhrase(`branches`, {
203
+ method: 'POST',
204
+ headers: {
205
+ 'Content-Type': 'application/json'
206
+ },
207
+ body: JSON.stringify({
208
+ name: branch
209
+ })
210
+ });
211
+ log('Created branch:', branch);
212
+ }
213
+
214
+ async function pull({
215
+ branch = 'local-development',
216
+ errorOnNoGlobalKeyTranslation
217
+ }, config) {
218
+ trace(`Pulling translations from branch ${branch}`);
219
+ await ensureBranch(branch);
220
+ const alternativeLanguages = getAltLanguages(config);
221
+ const allPhraseTranslations = await pullAllTranslations(branch);
222
+ trace(`Pulling translations from Phrase for languages ${config.devLanguage} and ${alternativeLanguages.join(', ')}`);
223
+ const phraseLanguages = Object.keys(allPhraseTranslations);
224
+ trace(`Found Phrase translations for languages ${phraseLanguages.join(', ')}`);
225
+ if (!phraseLanguages.includes(config.devLanguage)) {
226
+ throw new Error(`Phrase did not return any translations for the configured development language "${config.devLanguage}".\nPlease ensure this language is present in your Phrase project's configuration.`);
227
+ }
228
+ const allVocabTranslations = await loadAllTranslations({
229
+ fallbacks: 'none',
230
+ includeNodeModules: false,
231
+ withTags: true
232
+ }, config);
233
+ for (const loadedTranslation of allVocabTranslations) {
234
+ const devTranslations = loadedTranslation.languages[config.devLanguage];
235
+ if (!devTranslations) {
236
+ throw new Error('No dev language translations loaded');
237
+ }
238
+ const defaultValues = {
239
+ ...devTranslations
240
+ };
241
+ const localKeys = Object.keys(defaultValues);
242
+ for (const key of localKeys) {
243
+ var _defaultValues$key$gl;
244
+ defaultValues[key] = {
245
+ ...defaultValues[key],
246
+ ...allPhraseTranslations[config.devLanguage][(_defaultValues$key$gl = defaultValues[key].globalKey) !== null && _defaultValues$key$gl !== void 0 ? _defaultValues$key$gl : getUniqueKey(key, loadedTranslation.namespace)]
247
+ };
248
+ }
249
+
250
+ // Only write a `_meta` field if necessary
251
+ if (Object.keys(loadedTranslation.metadata).length > 0) {
252
+ defaultValues._meta = loadedTranslation.metadata;
253
+ }
254
+ await writeFile(loadedTranslation.filePath, `${JSON.stringify(defaultValues, null, 2)}\n`);
255
+ for (const alternativeLanguage of alternativeLanguages) {
256
+ if (alternativeLanguage in allPhraseTranslations) {
257
+ const altTranslations = {
258
+ ...loadedTranslation.languages[alternativeLanguage]
259
+ };
260
+ const phraseAltTranslations = allPhraseTranslations[alternativeLanguage];
261
+ for (const key of localKeys) {
262
+ var _defaultValues$key$gl2, _phraseAltTranslation;
263
+ const phraseKey = (_defaultValues$key$gl2 = defaultValues[key].globalKey) !== null && _defaultValues$key$gl2 !== void 0 ? _defaultValues$key$gl2 : getUniqueKey(key, loadedTranslation.namespace);
264
+ const phraseTranslationMessage = (_phraseAltTranslation = phraseAltTranslations[phraseKey]) === null || _phraseAltTranslation === void 0 ? void 0 : _phraseAltTranslation.message;
265
+ if (!phraseTranslationMessage) {
266
+ trace(`Missing translation. No translation for key ${key} in phrase as ${phraseKey} in language ${alternativeLanguage}.`);
267
+ if (errorOnNoGlobalKeyTranslation && defaultValues[key].globalKey) {
268
+ throw new Error(`Missing translation for global key ${key} in language ${alternativeLanguage}`);
269
+ }
270
+ continue;
271
+ }
272
+ altTranslations[key] = {
273
+ ...altTranslations[key],
274
+ message: phraseTranslationMessage
275
+ };
276
+ }
277
+ const altTranslationFilePath = getAltLanguageFilePath(loadedTranslation.filePath, alternativeLanguage);
278
+ await mkdir(path.dirname(altTranslationFilePath), {
279
+ recursive: true
280
+ });
281
+ await writeFile(altTranslationFilePath, `${JSON.stringify(altTranslations, null, 2)}\n`);
282
+ }
283
+ }
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Uploads translations to the Phrase API for each language.
289
+ * A unique namespace is appended to each key using the file path the key came from.
290
+ */
291
+ async function push({
292
+ branch,
293
+ deleteUnusedKeys: deleteUnusedKeys$1
294
+ }, config) {
295
+ const allLanguageTranslations = await loadAllTranslations({
296
+ fallbacks: 'none',
297
+ includeNodeModules: false,
298
+ withTags: true
299
+ }, config);
300
+ trace(`Pushing translations to branch ${branch}`);
301
+ const allLanguages = config.languages.map(v => v.name);
302
+ await ensureBranch(branch);
303
+ trace(`Pushing translations to phrase for languages ${allLanguages.join(', ')}`);
304
+ const phraseTranslations = {};
305
+ for (const loadedTranslation of allLanguageTranslations) {
306
+ for (const language of allLanguages) {
307
+ const localTranslations = loadedTranslation.languages[language];
308
+ if (!localTranslations) {
309
+ continue;
310
+ }
311
+ if (!phraseTranslations[language]) {
312
+ phraseTranslations[language] = {};
313
+ }
314
+ const {
315
+ metadata: {
316
+ tags: sharedTags = []
317
+ }
318
+ } = loadedTranslation;
319
+ for (const localKey of Object.keys(localTranslations)) {
320
+ const {
321
+ tags = [],
322
+ ...localTranslation
323
+ } = localTranslations[localKey];
324
+ if (language === config.devLanguage) {
325
+ localTranslation.tags = [...tags, ...sharedTags];
326
+ }
327
+ const globalKey = loadedTranslation.languages[config.devLanguage][localKey].globalKey;
328
+ const phraseKey = globalKey !== null && globalKey !== void 0 ? globalKey : getUniqueKey(localKey, loadedTranslation.namespace);
329
+ phraseTranslations[language][phraseKey] = localTranslation;
330
+ }
331
+ }
332
+ }
333
+ const {
334
+ devLanguageUploadId
335
+ } = await pushTranslations(phraseTranslations, {
336
+ devLanguage: config.devLanguage,
337
+ branch
338
+ });
339
+ if (deleteUnusedKeys$1) {
340
+ await deleteUnusedKeys(devLanguageUploadId, branch);
341
+ }
342
+ }
343
+
344
+ export { pull, push };
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@vocab/phrase",
3
+ "version": "0.0.0-add-support-for-vocab-cjs-20231109235141",
4
+ "main": "dist/vocab-phrase.cjs.js",
5
+ "module": "dist/vocab-phrase.esm.js",
6
+ "author": "SEEK",
7
+ "license": "MIT",
8
+ "dependencies": {
9
+ "@vocab/core": "0.0.0-add-support-for-vocab-cjs-20231109235141",
10
+ "chalk": "^4.1.0",
11
+ "csv-stringify": "^6.2.3",
12
+ "debug": "^4.3.1",
13
+ "form-data": "^3.0.0",
14
+ "node-fetch": "^2.6.1"
15
+ },
16
+ "devDependencies": {
17
+ "@types/debug": "^4.1.5",
18
+ "@types/node-fetch": "^2.5.7"
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ]
23
+ }