@vocab/phrase 1.0.1 → 1.2.0

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/src/file.ts DELETED
@@ -1,4 +0,0 @@
1
- import { promises as fs } from 'fs';
2
-
3
- export const mkdir = fs.mkdir;
4
- export const writeFile = fs.writeFile;
package/src/index.ts DELETED
@@ -1,2 +0,0 @@
1
- export { pull } from './pull-translations';
2
- export { push } from './push-translations';
package/src/logger.ts DELETED
@@ -1,9 +0,0 @@
1
- import chalk from 'chalk';
2
- import debug from 'debug';
3
-
4
- export const trace = debug(`vocab:phrase`);
5
-
6
- export const log = (...params: unknown[]) => {
7
- // eslint-disable-next-line no-console
8
- console.log(chalk.yellow('Vocab'), ...params);
9
- };
package/src/phrase-api.ts DELETED
@@ -1,147 +0,0 @@
1
- import FormData from 'form-data';
2
- import { TranslationsByKey } from './../../types/src/index';
3
- /* eslint-disable no-console */
4
- import type { TranslationsByLanguage } from '@vocab/types';
5
- import fetch from 'node-fetch';
6
- import { log, trace } from './logger';
7
-
8
- function _callPhrase(path: string, options: Parameters<typeof fetch>[1] = {}) {
9
- const phraseApiToken = process.env.PHRASE_API_TOKEN;
10
-
11
- if (!phraseApiToken) {
12
- throw new Error('Missing PHRASE_API_TOKEN');
13
- }
14
-
15
- return fetch(path, {
16
- ...options,
17
- headers: {
18
- Authorization: `token ${phraseApiToken}`,
19
- // Provide identification via User Agent as requested in https://developers.phrase.com/api/#overview--identification-via-user-agent
20
- 'User-Agent': 'SEEK Demo Candidate App (jhope@seek.com.au)',
21
- ...options.headers,
22
- },
23
- }).then(async (response) => {
24
- console.log(`${path}: ${response.status} - ${response.statusText}`);
25
- console.log(
26
- `Rate Limit: ${response.headers.get(
27
- 'X-Rate-Limit-Remaining',
28
- )} of ${response.headers.get(
29
- 'X-Rate-Limit-Limit',
30
- )} remaining. (${response.headers.get(
31
- 'X-Rate-Limit-Reset',
32
- )} seconds remaining})`,
33
- );
34
- console.log('\nLink:', response.headers.get('Link'), '\n');
35
- // Print All Headers:
36
- // console.log(Array.from(r.headers.entries()));
37
-
38
- try {
39
- const result = await response.json();
40
-
41
- console.log(`Internal Result (Length: ${result.length})\n`);
42
-
43
- if (
44
- (!options.method || options.method === 'GET') &&
45
- response.headers.get('Link')?.includes('rel=next')
46
- ) {
47
- const [, nextPageUrl] =
48
- response.headers.get('Link')?.match(/<([^>]*)>; rel=next/) ?? [];
49
-
50
- if (!nextPageUrl) {
51
- throw new Error('Cant parse next page URL');
52
- }
53
-
54
- console.log('Results recieved with next page: ', nextPageUrl);
55
-
56
- const nextPageResult = (await _callPhrase(nextPageUrl, options)) as any;
57
-
58
- return [...result, ...nextPageResult];
59
- }
60
-
61
- return result;
62
- } catch (e) {
63
- console.error('Unable to parse response as JSON', e);
64
- return response.text();
65
- }
66
- });
67
- }
68
-
69
- export async function callPhrase(
70
- relativePath: string,
71
- options: Parameters<typeof fetch>[1] = {},
72
- ) {
73
- const projectId = process.env.PHRASE_PROJECT_ID;
74
-
75
- if (!projectId) {
76
- throw new Error('Missing PHRASE_PROJECT_ID');
77
- }
78
- return _callPhrase(
79
- `https://api.phrase.com/v2/projects/${projectId}/${relativePath}`,
80
- options,
81
- )
82
- .then((result) => {
83
- if (Array.isArray(result)) {
84
- console.log('Result length:', result.length);
85
- }
86
- return result;
87
- })
88
- .catch((error) => {
89
- console.error(`Error calling phrase for ${relativePath}:`, error);
90
- throw Error;
91
- });
92
- }
93
-
94
- export async function pullAllTranslations(
95
- branch: string,
96
- ): Promise<TranslationsByLanguage> {
97
- const phraseResult: Array<{
98
- key: { name: string };
99
- locale: { code: string };
100
- content: string;
101
- }> = await callPhrase(`translations?branch=${branch}&per_page=100`);
102
- const translations: TranslationsByLanguage = {};
103
- for (const r of phraseResult) {
104
- if (!translations[r.locale.code]) {
105
- translations[r.locale.code] = {};
106
- }
107
- translations[r.locale.code][r.key.name] = { message: r.content };
108
- }
109
- return translations;
110
- }
111
-
112
- export async function pushTranslationsByLocale(
113
- contents: TranslationsByKey,
114
- locale: string,
115
- branch: string,
116
- ) {
117
- const formData = new FormData();
118
- const fileContents = Buffer.from(JSON.stringify(contents));
119
- formData.append('file', fileContents, {
120
- contentType: 'application/json',
121
- filename: `${locale}.json`,
122
- });
123
-
124
- formData.append('file_format', 'json');
125
- formData.append('locale_id', locale);
126
- formData.append('branch', branch);
127
- formData.append('update_translations', 'true');
128
-
129
- trace('Starting to upload:', locale);
130
-
131
- await callPhrase(`uploads`, {
132
- method: 'POST',
133
- body: formData,
134
- });
135
- log('Successfully Uploaded:', locale, '\n');
136
- }
137
-
138
- export async function ensureBranch(branch: string) {
139
- await callPhrase(`branches`, {
140
- method: 'POST',
141
- headers: {
142
- 'Content-Type': 'application/json',
143
- },
144
- body: JSON.stringify({ name: branch }),
145
- });
146
- trace('Created branch:', branch);
147
- }
@@ -1,148 +0,0 @@
1
- import path from 'path';
2
- import { pull } from './pull-translations';
3
- import { pullAllTranslations } from './phrase-api';
4
- import { writeFile } from './file';
5
- import { 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
- function runPhrase(options: { languages: LanguageTarget[] }) {
18
- return pull(
19
- { branch: 'tester' },
20
- {
21
- ...options,
22
- devLanguage: 'en',
23
- projectRoot: path.resolve(__dirname, '..', '..', '..', 'fixtures/phrase'),
24
- },
25
- );
26
- }
27
-
28
- describe('pull translations', () => {
29
- describe('when pulling translations for languages that already have translations', () => {
30
- beforeEach(() => {
31
- (pullAllTranslations as jest.Mock).mockClear();
32
- (writeFile as jest.Mock).mockClear();
33
- });
34
- (pullAllTranslations as jest.Mock).mockImplementation(() =>
35
- Promise.resolve({
36
- en: {
37
- 'hello.mytranslations': {
38
- message: 'Hi there',
39
- },
40
- },
41
- fr: {
42
- 'hello.mytranslations': {
43
- message: 'merci',
44
- },
45
- },
46
- }),
47
- );
48
-
49
- const options = {
50
- languages: [{ name: 'en' }, { name: 'fr' }],
51
- };
52
-
53
- it('should resolve', async () => {
54
- await expect(runPhrase(options)).resolves.toBeUndefined();
55
-
56
- expect(writeFile as jest.Mock).toHaveBeenCalledTimes(2);
57
- });
58
-
59
- it('should update keys', async () => {
60
- await expect(runPhrase(options)).resolves.toBeUndefined();
61
-
62
- expect(
63
- (writeFile as jest.Mock).mock.calls.map(
64
- ([_filePath, contents]: [string, string]) => JSON.parse(contents),
65
- ),
66
- ).toMatchInlineSnapshot(`
67
- Array [
68
- Object {
69
- "hello": Object {
70
- "message": "Hi there",
71
- },
72
- "world": Object {
73
- "message": "world",
74
- },
75
- },
76
- Object {
77
- "hello": Object {
78
- "message": "merci",
79
- },
80
- "world": Object {
81
- "message": "monde",
82
- },
83
- },
84
- ]
85
- `);
86
- });
87
- });
88
-
89
- describe('when pulling translations and some languages do not have any translations', () => {
90
- beforeEach(() => {
91
- (pullAllTranslations as jest.Mock).mockClear();
92
- (writeFile as jest.Mock).mockClear();
93
- });
94
- (pullAllTranslations as jest.Mock).mockImplementation(() =>
95
- Promise.resolve({
96
- en: {
97
- 'hello.mytranslations': {
98
- message: 'Hi there',
99
- },
100
- },
101
- fr: {
102
- 'hello.mytranslations': {
103
- message: 'merci',
104
- },
105
- },
106
- }),
107
- );
108
-
109
- const options = {
110
- languages: [{ name: 'en' }, { name: 'fr' }, { name: 'ja' }],
111
- };
112
-
113
- it('should resolve', async () => {
114
- await expect(runPhrase(options)).resolves.toBeUndefined();
115
-
116
- expect(writeFile as jest.Mock).toHaveBeenCalledTimes(2);
117
- });
118
-
119
- it('should update keys', async () => {
120
- await expect(runPhrase(options)).resolves.toBeUndefined();
121
-
122
- expect(
123
- (writeFile as jest.Mock).mock.calls.map(
124
- ([_filePath, contents]: [string, string]) => JSON.parse(contents),
125
- ),
126
- ).toMatchInlineSnapshot(`
127
- Array [
128
- Object {
129
- "hello": Object {
130
- "message": "Hi there",
131
- },
132
- "world": Object {
133
- "message": "world",
134
- },
135
- },
136
- Object {
137
- "hello": Object {
138
- "message": "merci",
139
- },
140
- "world": Object {
141
- "message": "monde",
142
- },
143
- },
144
- ]
145
- `);
146
- });
147
- });
148
- });
@@ -1,102 +0,0 @@
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 allVocabTranslations = await loadAllTranslations(
34
- { fallbacks: 'none', includeNodeModules: false },
35
- config,
36
- );
37
-
38
- for (const loadedTranslation of allVocabTranslations) {
39
- const devTranslations = loadedTranslation.languages[config.devLanguage];
40
-
41
- if (!devTranslations) {
42
- throw new Error('No dev language translations loaded');
43
- }
44
-
45
- const defaultValues = { ...devTranslations };
46
- const localKeys = Object.keys(defaultValues);
47
-
48
- for (const key of localKeys) {
49
- defaultValues[key] = {
50
- ...defaultValues[key],
51
- ...allPhraseTranslations[config.devLanguage][
52
- getUniqueKey(key, loadedTranslation.namespace)
53
- ],
54
- };
55
- }
56
- await writeFile(
57
- loadedTranslation.filePath,
58
- `${JSON.stringify(defaultValues, null, 2)}\n`,
59
- );
60
-
61
- for (const alternativeLanguage of alternativeLanguages) {
62
- if (alternativeLanguage in allPhraseTranslations) {
63
- const altTranslations = {
64
- ...loadedTranslation.languages[alternativeLanguage],
65
- };
66
- const phraseAltTranslations =
67
- allPhraseTranslations[alternativeLanguage];
68
-
69
- for (const key of localKeys) {
70
- const phraseKey = getUniqueKey(key, loadedTranslation.namespace);
71
- const phraseTranslationMessage =
72
- phraseAltTranslations[phraseKey]?.message;
73
-
74
- if (!phraseTranslationMessage) {
75
- trace(
76
- `Missing translation. No translation for key ${key} in phrase as ${phraseKey} in language ${alternativeLanguage}.`,
77
- );
78
- continue;
79
- }
80
-
81
- altTranslations[key] = {
82
- ...altTranslations[key],
83
- message: phraseTranslationMessage,
84
- };
85
- }
86
-
87
- const altTranslationFilePath = getAltLanguageFilePath(
88
- loadedTranslation.filePath,
89
- alternativeLanguage,
90
- );
91
-
92
- await mkdir(path.dirname(altTranslationFilePath), {
93
- recursive: true,
94
- });
95
- await writeFile(
96
- altTranslationFilePath,
97
- `${JSON.stringify(altTranslations, null, 2)}\n`,
98
- );
99
- }
100
- }
101
- }
102
- }
@@ -1,65 +0,0 @@
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
- projectRoot: path.resolve(__dirname, '..', '..', '..', 'fixtures/phrase'),
23
- },
24
- );
25
- }
26
-
27
- describe('push', () => {
28
- beforeEach(() => {
29
- (pushTranslationsByLocale as jest.Mock).mockClear();
30
- (writeFile as jest.Mock).mockClear();
31
- });
32
- it('should resolve', async () => {
33
- await expect(runPhrase()).resolves.toBeUndefined();
34
-
35
- expect(pushTranslationsByLocale as jest.Mock).toHaveBeenCalledTimes(2);
36
- });
37
- it('should update keys', async () => {
38
- await expect(runPhrase()).resolves.toBeUndefined();
39
-
40
- expect(pushTranslationsByLocale as jest.Mock).toHaveBeenCalledWith(
41
- {
42
- 'hello.mytranslations': {
43
- message: 'Hello',
44
- },
45
- 'world.mytranslations': {
46
- message: 'world',
47
- },
48
- },
49
- 'en',
50
- 'tester',
51
- );
52
- expect(pushTranslationsByLocale as jest.Mock).toHaveBeenCalledWith(
53
- {
54
- 'hello.mytranslations': {
55
- message: 'Bonjour',
56
- },
57
- 'world.mytranslations': {
58
- message: 'monde',
59
- },
60
- },
61
- 'fr',
62
- 'tester',
63
- );
64
- });
65
- });
@@ -1,55 +0,0 @@
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
- }