@vocab/phrase 0.0.0-phrase-pull-dev-language-202281412540 → 0.0.0-push-split-translation-files-20230508031119

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