@vocab/phrase 0.0.0-compiled-translation-import-order-20230328231631

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