@vocab/phrase 0.0.0-phrase-pull-dev-language-202281412540

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.
@@ -0,0 +1,250 @@
1
+ import path from 'path';
2
+ import { pull } from './pull-translations';
3
+ import { pullAllTranslations } from './phrase-api';
4
+ import { writeFile } from './file';
5
+ import { GeneratedLanguageTarget, LanguageTarget } from '@vocab/types';
6
+
7
+ jest.mock('./file', () => ({
8
+ writeFile: jest.fn(() => Promise.resolve),
9
+ mkdir: jest.fn(() => Promise.resolve),
10
+ }));
11
+
12
+ jest.mock('./phrase-api', () => ({
13
+ ensureBranch: jest.fn(() => Promise.resolve()),
14
+ pullAllTranslations: jest.fn(() => Promise.resolve({ en: {}, fr: {} })),
15
+ }));
16
+
17
+ const devLanguage = 'en';
18
+
19
+ function runPhrase(options: {
20
+ languages: LanguageTarget[];
21
+ generatedLanguages: GeneratedLanguageTarget[];
22
+ }) {
23
+ return pull(
24
+ { branch: 'tester' },
25
+ {
26
+ ...options,
27
+ devLanguage,
28
+ projectRoot: path.resolve(__dirname, '..', '..', '..', 'fixtures/phrase'),
29
+ },
30
+ );
31
+ }
32
+
33
+ describe('pull translations', () => {
34
+ describe('when pulling translations for languages that already have translations', () => {
35
+ beforeEach(() => {
36
+ (pullAllTranslations as jest.Mock).mockClear();
37
+ (writeFile as jest.Mock).mockClear();
38
+ (pullAllTranslations as jest.Mock).mockImplementation(() =>
39
+ Promise.resolve({
40
+ en: {
41
+ 'hello.mytranslations': {
42
+ message: 'Hi there',
43
+ },
44
+ },
45
+ fr: {
46
+ 'hello.mytranslations': {
47
+ message: 'merci',
48
+ },
49
+ },
50
+ }),
51
+ );
52
+ });
53
+
54
+ const options = {
55
+ languages: [{ name: 'en' }, { name: 'fr' }],
56
+ generatedLanguages: [
57
+ {
58
+ name: 'generatedLanguage',
59
+ extends: 'en',
60
+ generator: {
61
+ transformMessage: (message: string) => `[${message}]`,
62
+ },
63
+ },
64
+ ],
65
+ };
66
+
67
+ it('should resolve', async () => {
68
+ await expect(runPhrase(options)).resolves.toBeUndefined();
69
+
70
+ expect(writeFile as jest.Mock).toHaveBeenCalledTimes(2);
71
+ });
72
+
73
+ it('should update keys', async () => {
74
+ await expect(runPhrase(options)).resolves.toBeUndefined();
75
+
76
+ expect(
77
+ (writeFile as jest.Mock).mock.calls.map(
78
+ ([_filePath, contents]: [string, string]) => JSON.parse(contents),
79
+ ),
80
+ ).toMatchInlineSnapshot(`
81
+ Array [
82
+ Object {
83
+ "hello": Object {
84
+ "message": "Hi there",
85
+ },
86
+ "world": Object {
87
+ "message": "world",
88
+ },
89
+ },
90
+ Object {
91
+ "hello": Object {
92
+ "message": "merci",
93
+ },
94
+ "world": Object {
95
+ "message": "monde",
96
+ },
97
+ },
98
+ ]
99
+ `);
100
+ });
101
+ });
102
+
103
+ describe('when pulling translations and some languages do not have any translations', () => {
104
+ beforeEach(() => {
105
+ (pullAllTranslations as jest.Mock).mockClear();
106
+ (writeFile as jest.Mock).mockClear();
107
+ (pullAllTranslations as jest.Mock).mockImplementation(() =>
108
+ Promise.resolve({
109
+ en: {
110
+ 'hello.mytranslations': {
111
+ message: 'Hi there',
112
+ },
113
+ },
114
+ fr: {
115
+ 'hello.mytranslations': {
116
+ message: 'merci',
117
+ },
118
+ },
119
+ }),
120
+ );
121
+ });
122
+
123
+ const options = {
124
+ languages: [{ name: 'en' }, { name: 'fr' }, { name: 'ja' }],
125
+ generatedLanguages: [
126
+ {
127
+ name: 'generatedLanguage',
128
+ extends: 'en',
129
+ generator: {
130
+ transformMessage: (message: string) => `[${message}]`,
131
+ },
132
+ },
133
+ ],
134
+ };
135
+
136
+ it('should resolve', async () => {
137
+ await expect(runPhrase(options)).resolves.toBeUndefined();
138
+
139
+ expect(writeFile as jest.Mock).toHaveBeenCalledTimes(2);
140
+ });
141
+
142
+ it('should update keys', async () => {
143
+ await expect(runPhrase(options)).resolves.toBeUndefined();
144
+
145
+ expect(
146
+ (writeFile as jest.Mock).mock.calls.map(
147
+ ([_filePath, contents]: [string, string]) => JSON.parse(contents),
148
+ ),
149
+ ).toMatchInlineSnapshot(`
150
+ Array [
151
+ Object {
152
+ "hello": Object {
153
+ "message": "Hi there",
154
+ },
155
+ "world": Object {
156
+ "message": "world",
157
+ },
158
+ },
159
+ Object {
160
+ "hello": Object {
161
+ "message": "merci",
162
+ },
163
+ "world": Object {
164
+ "message": "monde",
165
+ },
166
+ },
167
+ ]
168
+ `);
169
+ });
170
+ });
171
+
172
+ describe('when pulling translations and the project has not configured translations for the dev language', () => {
173
+ beforeEach(() => {
174
+ (pullAllTranslations as jest.Mock).mockClear();
175
+ (writeFile as jest.Mock).mockClear();
176
+ (pullAllTranslations as jest.Mock).mockImplementation(() =>
177
+ Promise.resolve({
178
+ fr: {
179
+ 'hello.mytranslations': {
180
+ message: 'merci',
181
+ },
182
+ },
183
+ }),
184
+ );
185
+ });
186
+
187
+ const options = {
188
+ languages: [{ name: 'en' }, { name: 'fr' }],
189
+ generatedLanguages: [
190
+ {
191
+ name: 'generatedLanguage',
192
+ extends: 'en',
193
+ generator: {
194
+ transformMessage: (message: string) => `[${message}]`,
195
+ },
196
+ },
197
+ ],
198
+ };
199
+
200
+ it('should throw an error', async () => {
201
+ await expect(runPhrase(options)).rejects.toThrowError(
202
+ new Error(
203
+ 'Phrase did not return any translations for dev language "en".\nEnsure you have configured your Phrase project for your dev language, and have pushed your translations.',
204
+ ),
205
+ );
206
+
207
+ expect(writeFile as jest.Mock).toHaveBeenCalledTimes(0);
208
+ });
209
+ });
210
+
211
+ describe('when pulling translations and there are no translations for the dev language', () => {
212
+ beforeEach(() => {
213
+ (pullAllTranslations as jest.Mock).mockClear();
214
+ (writeFile as jest.Mock).mockClear();
215
+ (pullAllTranslations as jest.Mock).mockImplementation(() =>
216
+ Promise.resolve({
217
+ en: {},
218
+ fr: {
219
+ 'hello.mytranslations': {
220
+ message: 'merci',
221
+ },
222
+ },
223
+ }),
224
+ );
225
+ });
226
+
227
+ const options = {
228
+ languages: [{ name: 'en' }, { name: 'fr' }],
229
+ generatedLanguages: [
230
+ {
231
+ name: 'generatedLanguage',
232
+ extends: 'en',
233
+ generator: {
234
+ transformMessage: (message: string) => `[${message}]`,
235
+ },
236
+ },
237
+ ],
238
+ };
239
+
240
+ it('should throw an error', async () => {
241
+ await expect(runPhrase(options)).rejects.toThrowError(
242
+ new Error(
243
+ 'Phrase did not return any translations for dev language "en".\nEnsure you have configured your Phrase project for your dev language, and have pushed your translations.',
244
+ ),
245
+ );
246
+
247
+ expect(writeFile as jest.Mock).toHaveBeenCalledTimes(0);
248
+ });
249
+ });
250
+ });
@@ -0,0 +1,119 @@
1
+ import { writeFile, mkdir } from './file';
2
+ import path from 'path';
3
+
4
+ import {
5
+ loadAllTranslations,
6
+ getAltLanguageFilePath,
7
+ getAltLanguages,
8
+ getUniqueKey,
9
+ } from '@vocab/core';
10
+ import type { UserConfig } from '@vocab/types';
11
+
12
+ import { pullAllTranslations, ensureBranch } from './phrase-api';
13
+ import { trace } from './logger';
14
+
15
+ interface PullOptions {
16
+ branch?: string;
17
+ }
18
+
19
+ export async function pull(
20
+ { branch = 'local-development' }: PullOptions,
21
+ config: UserConfig,
22
+ ) {
23
+ trace(`Pulling translations from branch ${branch}`);
24
+ await ensureBranch(branch);
25
+ const alternativeLanguages = getAltLanguages(config);
26
+ const allPhraseTranslations = await pullAllTranslations(branch);
27
+ trace(
28
+ `Pulling translations from Phrase for languages ${
29
+ config.devLanguage
30
+ } and ${alternativeLanguages.join(', ')}`,
31
+ );
32
+
33
+ const phraseLanguages = Object.keys(allPhraseTranslations);
34
+ const phraseLanguagesWithTranslations = phraseLanguages.filter((language) => {
35
+ const phraseTranslationsForLanguage = allPhraseTranslations[language];
36
+ return Object.keys(phraseTranslationsForLanguage).length > 0;
37
+ });
38
+
39
+ trace(
40
+ `Found Phrase translations for languages ${phraseLanguagesWithTranslations.join(
41
+ ', ',
42
+ )}`,
43
+ );
44
+ if (!phraseLanguagesWithTranslations.includes(config.devLanguage)) {
45
+ throw new Error(
46
+ `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.`,
47
+ );
48
+ }
49
+
50
+ const allVocabTranslations = await loadAllTranslations(
51
+ { fallbacks: 'none', includeNodeModules: false },
52
+ config,
53
+ );
54
+
55
+ for (const loadedTranslation of allVocabTranslations) {
56
+ const devTranslations = loadedTranslation.languages[config.devLanguage];
57
+
58
+ if (!devTranslations) {
59
+ throw new Error('No dev language translations loaded');
60
+ }
61
+
62
+ const defaultValues = { ...devTranslations };
63
+ const localKeys = Object.keys(defaultValues);
64
+
65
+ for (const key of localKeys) {
66
+ defaultValues[key] = {
67
+ ...defaultValues[key],
68
+ ...allPhraseTranslations[config.devLanguage][
69
+ getUniqueKey(key, loadedTranslation.namespace)
70
+ ],
71
+ };
72
+ }
73
+ await writeFile(
74
+ loadedTranslation.filePath,
75
+ `${JSON.stringify(defaultValues, null, 2)}\n`,
76
+ );
77
+
78
+ for (const alternativeLanguage of alternativeLanguages) {
79
+ if (alternativeLanguage in allPhraseTranslations) {
80
+ const altTranslations = {
81
+ ...loadedTranslation.languages[alternativeLanguage],
82
+ };
83
+ const phraseAltTranslations =
84
+ allPhraseTranslations[alternativeLanguage];
85
+
86
+ for (const key of localKeys) {
87
+ const phraseKey = getUniqueKey(key, loadedTranslation.namespace);
88
+ const phraseTranslationMessage =
89
+ phraseAltTranslations[phraseKey]?.message;
90
+
91
+ if (!phraseTranslationMessage) {
92
+ trace(
93
+ `Missing translation. No translation for key ${key} in phrase as ${phraseKey} in language ${alternativeLanguage}.`,
94
+ );
95
+ continue;
96
+ }
97
+
98
+ altTranslations[key] = {
99
+ ...altTranslations[key],
100
+ message: phraseTranslationMessage,
101
+ };
102
+ }
103
+
104
+ const altTranslationFilePath = getAltLanguageFilePath(
105
+ loadedTranslation.filePath,
106
+ alternativeLanguage,
107
+ );
108
+
109
+ await mkdir(path.dirname(altTranslationFilePath), {
110
+ recursive: true,
111
+ });
112
+ await writeFile(
113
+ altTranslationFilePath,
114
+ `${JSON.stringify(altTranslations, null, 2)}\n`,
115
+ );
116
+ }
117
+ }
118
+ }
119
+ }
@@ -0,0 +1,77 @@
1
+ import path from 'path';
2
+ import { push } from './push-translations';
3
+ import { pushTranslationsByLocale } from './phrase-api';
4
+ import { writeFile } from './file';
5
+
6
+ jest.mock('./file', () => ({
7
+ writeFile: jest.fn(() => Promise.resolve),
8
+ mkdir: jest.fn(() => Promise.resolve),
9
+ }));
10
+
11
+ jest.mock('./phrase-api', () => ({
12
+ ensureBranch: jest.fn(() => Promise.resolve()),
13
+ pushTranslationsByLocale: jest.fn(() => Promise.resolve({ en: {}, fr: {} })),
14
+ }));
15
+
16
+ function runPhrase() {
17
+ return push(
18
+ { branch: 'tester' },
19
+ {
20
+ devLanguage: 'en',
21
+ languages: [{ name: 'en' }, { name: 'fr' }],
22
+ generatedLanguages: [
23
+ {
24
+ name: 'generatedLanguage',
25
+ extends: 'en',
26
+ generator: {
27
+ transformMessage: (message: string) => `[${message}]`,
28
+ },
29
+ },
30
+ ],
31
+ projectRoot: path.resolve(__dirname, '..', '..', '..', 'fixtures/phrase'),
32
+ },
33
+ );
34
+ }
35
+
36
+ describe('push', () => {
37
+ beforeEach(() => {
38
+ (pushTranslationsByLocale as jest.Mock).mockClear();
39
+ (writeFile as jest.Mock).mockClear();
40
+ });
41
+
42
+ it('should resolve', async () => {
43
+ await expect(runPhrase()).resolves.toBeUndefined();
44
+
45
+ expect(pushTranslationsByLocale as jest.Mock).toHaveBeenCalledTimes(2);
46
+ });
47
+
48
+ it('should update keys', async () => {
49
+ await expect(runPhrase()).resolves.toBeUndefined();
50
+
51
+ expect(pushTranslationsByLocale as jest.Mock).toHaveBeenCalledWith(
52
+ {
53
+ 'hello.mytranslations': {
54
+ message: 'Hello',
55
+ },
56
+ 'world.mytranslations': {
57
+ message: 'world',
58
+ },
59
+ },
60
+ 'en',
61
+ 'tester',
62
+ );
63
+
64
+ expect(pushTranslationsByLocale as jest.Mock).toHaveBeenCalledWith(
65
+ {
66
+ 'hello.mytranslations': {
67
+ message: 'Bonjour',
68
+ },
69
+ 'world.mytranslations': {
70
+ message: 'monde',
71
+ },
72
+ },
73
+ 'fr',
74
+ 'tester',
75
+ );
76
+ });
77
+ });
@@ -0,0 +1,55 @@
1
+ import { TranslationsByLanguage } from './../../types/src/index';
2
+
3
+ import { ensureBranch, pushTranslationsByLocale } from './phrase-api';
4
+ import { trace } from './logger';
5
+ import { loadAllTranslations, getUniqueKey } from '@vocab/core';
6
+ import { UserConfig } from '@vocab/types';
7
+
8
+ interface PushOptions {
9
+ branch: string;
10
+ }
11
+
12
+ /**
13
+ * Uploading to the Phrase API for each language. Adding a unique namespace to each key using file path they key came from
14
+ */
15
+ export async function push({ branch }: PushOptions, config: UserConfig) {
16
+ const allLanguageTranslations = await loadAllTranslations(
17
+ { fallbacks: 'none', includeNodeModules: false },
18
+ config,
19
+ );
20
+ trace(`Pushing translations to branch ${branch}`);
21
+ const allLanguages = config.languages.map((v) => v.name);
22
+ await ensureBranch(branch);
23
+
24
+ trace(
25
+ `Pushing translations to phrase for languages ${allLanguages.join(', ')}`,
26
+ );
27
+
28
+ const phraseTranslations: TranslationsByLanguage = {};
29
+
30
+ for (const loadedTranslation of allLanguageTranslations) {
31
+ for (const language of allLanguages) {
32
+ const localTranslations = loadedTranslation.languages[language];
33
+ if (!localTranslations) {
34
+ continue;
35
+ }
36
+ if (!phraseTranslations[language]) {
37
+ phraseTranslations[language] = {};
38
+ }
39
+ for (const localKey of Object.keys(localTranslations)) {
40
+ const phraseKey = getUniqueKey(localKey, loadedTranslation.namespace);
41
+ phraseTranslations[language][phraseKey] = localTranslations[localKey];
42
+ }
43
+ }
44
+ }
45
+
46
+ for (const language of allLanguages) {
47
+ if (phraseTranslations[language]) {
48
+ await pushTranslationsByLocale(
49
+ phraseTranslations[language],
50
+ language,
51
+ branch,
52
+ );
53
+ }
54
+ }
55
+ }