@vocab/phrase 0.0.0-phrase-pull-dev-language-202281412540 → 0.0.0-rate-limit-seconds-20230314015727

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