auto-translate-json-library 1.0.2 → 1.0.3

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/deepl.ts DELETED
@@ -1,80 +0,0 @@
1
- import FormData = require('form-data');
2
- import { ITranslate } from './translate.interface';
3
-
4
- const axios = require('axios').default;
5
- import { Util } from './util';
6
-
7
- const supportedLanguages = [
8
- 'BG',
9
- 'CS',
10
- 'DA',
11
- 'DE',
12
- 'EL',
13
- 'EN-GB',
14
- 'EN-US',
15
- 'EN',
16
- 'ES',
17
- 'ET',
18
- 'FI',
19
- 'FR',
20
- 'HU',
21
- 'IT',
22
- 'JA',
23
- 'LT',
24
- 'LV',
25
- 'NL',
26
- 'PL',
27
- 'PT-PT',
28
- 'PT-BR',
29
- 'PT',
30
- 'RO',
31
- 'RU',
32
- 'SK',
33
- 'SL',
34
- 'SV',
35
- 'ZH'
36
- ];
37
-
38
- export class DeepLTranslate implements ITranslate {
39
- private endpoint = 'https://api.deepl.com';
40
- constructor(private subscriptionKey: string, private type: 'free' | 'pro') {
41
- if (this.type === 'free') {
42
- this.endpoint = 'https://api.free.deepl.com';
43
- }
44
- }
45
- isValidLocale(targetLocale: string): boolean {
46
- return supportedLanguages.includes(targetLocale.toUpperCase());
47
- }
48
- async translateText(
49
- text: string,
50
- sourceLocale: string,
51
- targetLocale: string
52
- ): Promise<string> {
53
- let args;
54
- ({ args, text } = Util.replaceContextVariables(text));
55
-
56
- let result = '';
57
-
58
- const formData = new FormData();
59
- formData.append('auth_key', this.subscriptionKey);
60
- formData.append('text', text);
61
- formData.append('source_lang', sourceLocale.toUpperCase());
62
- formData.append('target_lang', targetLocale.toUpperCase());
63
-
64
- const response = await axios({
65
- baseURL: this.endpoint,
66
- url: 'v2/translate',
67
- method: 'post',
68
- data: formData,
69
- responseType: 'json'
70
- });
71
-
72
- result = response.translations[1].text;
73
-
74
- result = Util.replaceArgumentsWithNumbers(args, result);
75
-
76
- return result;
77
- }
78
- }
79
-
80
- // https://www.deepl.com/docs-api/translating-text/example/
package/src/files.ts DELETED
@@ -1,79 +0,0 @@
1
- import * as path from 'path';
2
- import * as fs from 'fs';
3
-
4
- export interface IFiles {
5
- sourceLocale: string;
6
- targetLocales: Array<string>;
7
- loadJsonFromLocale(locale: string): Promise<any>;
8
- saveJsonToLocale(locale: string, file: any): void;
9
- }
10
-
11
- export const readFileAsync: (filename: string) => Promise<string> = (
12
- filename: string
13
- ) =>
14
- new Promise((resolve, reject) => {
15
- fs.readFile(filename, (error, data) => {
16
- error ? reject(error) : resolve(data.toString());
17
- });
18
- });
19
-
20
- export const loadJsonFromLocale: (fileName: string) => Promise<any> = async (
21
- fileName: string
22
- ) => {
23
- let data = await readFileAsync(fileName);
24
- // handle empty files
25
- if (!data) {
26
- data = '{}';
27
- }
28
-
29
- return JSON.parse(data);
30
- };
31
-
32
- export const saveJsonToLocale = (filename: string, file: any) => {
33
- let data = JSON.stringify(file, null, ' ');
34
-
35
- fs.writeFileSync(filename, data, 'utf8');
36
- };
37
-
38
- export class Files implements IFiles {
39
- folderPath: string;
40
- sourceLocale: string;
41
- targetLocales: Array<string>;
42
-
43
- constructor(filePath: string) {
44
- this.folderPath = path.dirname(filePath);
45
- let fileName = path.basename(filePath);
46
- this.sourceLocale = this.getLocaleFromFilename(fileName);
47
- this.targetLocales = this.getTargetLocales();
48
- }
49
-
50
- private getLocaleFromFilename(fileName: string): string {
51
- return fileName.replace('.json', '');
52
- }
53
-
54
- private getTargetLocales(): string[] {
55
- let locales = new Array();
56
-
57
- let files = fs.readdirSync(this.folderPath);
58
-
59
- files.forEach((file) => {
60
- let locale = this.getLocaleFromFilename(file);
61
- if (locale !== this.sourceLocale) {
62
- locales.push(locale);
63
- }
64
- });
65
-
66
- return locales;
67
- }
68
-
69
- loadJsonFromLocale(locale: string): Promise<any> {
70
- let filename = this.folderPath + '/' + locale + '.json';
71
- return loadJsonFromLocale(filename);
72
- }
73
-
74
- saveJsonToLocale(locale: string, file: any) {
75
- let filename = this.folderPath + '/' + locale + '.json';
76
-
77
- saveJsonToLocale(filename, file);
78
- }
79
- }
@@ -1,47 +0,0 @@
1
- import * as path from 'path';
2
- import * as fs from 'fs';
3
- import { IFiles, loadJsonFromLocale, saveJsonToLocale } from './files';
4
-
5
- export class FolderFiles implements IFiles {
6
- folderPath: string;
7
- sourceLocale: string;
8
- targetLocales: Array<string>;
9
- fileName: string;
10
-
11
- constructor(filePath: string) {
12
- const localeDir = path.dirname(filePath);
13
- this.folderPath = path.dirname(localeDir);
14
- this.fileName = path.basename(filePath);
15
- this.sourceLocale = path.basename(localeDir);
16
- this.targetLocales = this.getTargetLocales();
17
-
18
- console.log(
19
- this.folderPath,
20
- this.fileName,
21
- this.sourceLocale,
22
- this.targetLocales
23
- );
24
- }
25
-
26
- private getTargetLocales(): string[] {
27
- let files = fs
28
- .readdirSync(this.folderPath)
29
- .map((folder) => path.basename(folder))
30
- .map((locale) => (locale !== this.sourceLocale ? locale : ''))
31
- .filter((x) => x); // do not want empty strings
32
-
33
- return files;
34
- }
35
-
36
- private createFileName(locale: string): string {
37
- return `${this.folderPath}/${locale}/${this.fileName}`;
38
- }
39
-
40
- loadJsonFromLocale(locale: string) {
41
- return loadJsonFromLocale(this.createFileName(locale));
42
- }
43
-
44
- saveJsonToLocale(locale: string, file: any) {
45
- saveJsonToLocale(this.createFileName(locale), file);
46
- }
47
- }
package/src/google.ts DELETED
@@ -1,162 +0,0 @@
1
- import { ITranslate } from './translate.interface';
2
-
3
- //const {Translate} = require('@google-cloud/translate').v2;
4
- import { Translate } from '@google-cloud/translate/build/src/v2';
5
- import { Util } from './util';
6
- const supportedLanguages = [
7
- 'af',
8
- 'sq',
9
- 'am',
10
- 'ar',
11
- 'hy',
12
- 'az',
13
- 'eu',
14
- 'be',
15
- 'bn',
16
- 'bs',
17
- 'bg',
18
- 'ca',
19
- 'ceb',
20
- 'zh-CN',
21
- 'zh',
22
- 'zh-TW',
23
- 'co',
24
- 'hr',
25
- 'cs',
26
- 'da',
27
- 'nl',
28
- 'en',
29
- 'eo',
30
- 'et',
31
- 'fi',
32
- 'fr',
33
- 'fy',
34
- 'gl',
35
- 'ka',
36
- 'de',
37
- 'el',
38
- 'gu',
39
- 'ht',
40
- 'ha',
41
- 'haw',
42
- 'he',
43
- 'iw',
44
- 'hi',
45
- 'hmn',
46
- 'hu',
47
- 'is',
48
- 'ig',
49
- 'id',
50
- 'ga',
51
- 'it',
52
- 'ja',
53
- 'jv',
54
- 'kn',
55
- 'kk',
56
- 'km',
57
- 'rw',
58
- 'ko',
59
- 'ku',
60
- 'ky',
61
- 'lo',
62
- 'lv',
63
- 'lt',
64
- 'lb',
65
- 'mk',
66
- 'mg',
67
- 'ms',
68
- 'ml',
69
- 'mt',
70
- 'mi',
71
- 'mr',
72
- 'mn',
73
- 'my',
74
- 'ne',
75
- 'no',
76
- 'ny',
77
- 'or',
78
- 'ps',
79
- 'fa',
80
- 'pl',
81
- 'pt',
82
- 'pa',
83
- 'ro',
84
- 'ru',
85
- 'sm',
86
- 'gd',
87
- 'sr',
88
- 'st',
89
- 'sn',
90
- 'sd',
91
- 'si',
92
- 'sk',
93
- 'sl',
94
- 'so',
95
- 'es',
96
- 'su',
97
- 'sw',
98
- 'sv',
99
- 'tl',
100
- 'tg',
101
- 'ta',
102
- 'tt',
103
- 'te',
104
- 'th',
105
- 'tr',
106
- 'tk',
107
- 'uk',
108
- 'ur',
109
- 'ug',
110
- 'uz',
111
- 'vi',
112
- 'cy',
113
- 'xh',
114
- 'yi',
115
- 'yo',
116
- 'zu'
117
- ];
118
- export class GoogleTranslate implements ITranslate {
119
- private apikey: string;
120
- private googleTranslate: Translate;
121
-
122
- constructor(apikey: string) {
123
- this.apikey = apikey;
124
- this.googleTranslate = new Translate({ key: this.apikey });
125
- // this.googleTranslate.getSupportedLanguages();
126
- }
127
-
128
- isValidLocale(targetLocale: string): boolean {
129
- return supportedLanguages.includes(targetLocale);
130
- }
131
-
132
- async translateText(
133
- text: string,
134
- _sourceLocale: string,
135
- targetLocale: string
136
- ): Promise<string> {
137
- let args;
138
- ({ args, text } = Util.replaceContextVariables(text));
139
-
140
- let result = '';
141
-
142
- try {
143
- const response = await this.googleTranslate.translate(text, targetLocale);
144
- result = response[0];
145
- } catch (error) {
146
- if (error instanceof Error) {
147
- let message = error.message;
148
- if (error.message === 'Invalid Value') {
149
- message = 'Invalid Locale ' + targetLocale;
150
- }
151
- console.log(message);
152
- return message;
153
- }
154
- return 'error';
155
- }
156
-
157
- // replace arguments with numbers
158
- result = Util.replaceArgumentsWithNumbers(args, result);
159
-
160
- return result;
161
- }
162
- }
package/src/index.ts DELETED
@@ -1,95 +0,0 @@
1
- import { Configuration } from './config';
2
- import { translate } from './lib';
3
-
4
- export { Configuration, translate };
5
-
6
- let config: Configuration = {} as Configuration;
7
- require('dotenv').config();
8
- if (process.env.ATJ_GOOGLE_API_KEY) {
9
- config.translationKeyInfo = {
10
- kind: 'google',
11
- apiKey: process.env.ATJ_GOOGLE_API_KEY,
12
- };
13
- }
14
- if (
15
- process.env.ATJ_AWS_ACCESS_KEY_ID &&
16
- process.env.ATJ_AWS_SECRET_ACCESS_KEY &&
17
- process.env.ATJ_AWS_REGION
18
- ) {
19
- config.translationKeyInfo = {
20
- kind: 'aws',
21
- accessKeyId: process.env.ATJ_AWS_ACCESS_KEY_ID,
22
- secretAccessKey: process.env.ATJ_AWS_SECRET_ACCESS_KEY,
23
- region: process.env.ATJ_AWS_REGION,
24
- };
25
- }
26
- if (process.env.ATJ_AZURE_SECRET_KEY && process.env.ATJ_AZURE_REGION) {
27
- config.translationKeyInfo = {
28
- kind: 'azure',
29
- secretKey: process.env.ATJ_AZURE_SECRET_KEY,
30
- region: process.env.ATJ_AZURE_REGION,
31
- };
32
- }
33
-
34
- if (process.env.ATJ_DEEPL_PRO_SECRET_KEY) {
35
- config.translationKeyInfo = {
36
- kind: 'deepLPro',
37
- secretKey: process.env.ATJ_DEEPL_PRO_SECRET_KEY,
38
- };
39
- }
40
-
41
- if (process.env.ATJ_DEEPL_FREE_SECRET_KEY) {
42
- config.translationKeyInfo = {
43
- kind: 'deepLFree',
44
- secretKey: process.env.ATJ_DEEPL_FREE_SECRET_KEY,
45
- };
46
- }
47
-
48
- if (process.env.ATJ_START_DELIMITER) {
49
- config.startDelimiter = process.env.ATJ_START_DELIMITER;
50
- }
51
-
52
- if (process.env.ATJ_END_DELIMITER) {
53
- config.endDelimiter = process.env.ATJ_END_DELIMITER;
54
- }
55
-
56
- if (process.env.ATJ_END_DELIMITER) {
57
- config.endDelimiter = process.env.ATJ_END_DELIMITER;
58
- }
59
-
60
- if (
61
- process.env.ATJ_MODE &&
62
- (process.env.ATJ_MODE === 'file' || process.env.ATJ_MODE === 'folder')
63
- ) {
64
- config.mode = process.env.ATJ_MODE;
65
- }
66
-
67
- if (process.env.ATJ_SOURCE_LOCALE) {
68
- config.sourceLocale = process.env.ATJ_SOURCE_LOCALE;
69
- }
70
-
71
- if (
72
- process.env.ATJ_KEEP_TRANSLATIONS &&
73
- (process.env.ATJ_KEEP_TRANSLATIONS === 'keep' ||
74
- process.env.ATJ_KEEP_TRANSLATIONS === 'retranslate')
75
- ) {
76
- config.keepTranslations = process.env.ATJ_KEEP_TRANSLATIONS;
77
- }
78
-
79
- if (
80
- process.env.ATJ_KEEP_EXTRA_TRANSLATIONS &&
81
- (process.env.ATJ_KEEP_EXTRA_TRANSLATIONS === 'keep' ||
82
- process.env.ATJ_KEEP_EXTRA_TRANSLATIONS === 'remove')
83
- ) {
84
- config.keepExtraTranslations = process.env.ATJ_KEEP_EXTRA_TRANSLATIONS;
85
- }
86
-
87
- console.log(config);
88
- var args = process.argv.slice(2);
89
- console.log(args);
90
- console.log(__dirname);
91
-
92
- console.log(process.cwd());
93
- if (args.length > 0) {
94
- translate(args[0], config);
95
- }
package/src/lib.ts DELETED
@@ -1,204 +0,0 @@
1
- // The module 'vscode' contains the VS Code extensibility API
2
- // Import the module and reference it with the alias vscode in your code below
3
- import { Files, IFiles } from './files';
4
- import { FolderFiles } from './folderFiles';
5
-
6
- import { AWSTranslate } from './aws';
7
- import { AzureTranslate } from './azure';
8
- import { GoogleTranslate } from './google';
9
- import { ITranslate } from './translate.interface';
10
- import { Util } from './util';
11
- import { DeepLTranslate } from './deepl';
12
- import { Configuration } from './config';
13
-
14
- const NAME = 'AutoTranslateJSON';
15
-
16
- export async function translate(sourceFile: string ,config: Configuration ): Promise<void> {
17
-
18
-
19
- // set the delimiters for named arguments
20
- const startDelimiter = config.startDelimiter || '{';
21
- if (startDelimiter) {
22
- Util.startDelimiter = startDelimiter;
23
- }
24
-
25
- const endDelimiter = config.endDelimiter || '}';
26
- if (endDelimiter) {
27
- Util.endDelimiter = endDelimiter;
28
- }
29
-
30
- let translateEngine: ITranslate;
31
-
32
- if (config.translationKeyInfo.kind === 'google') {
33
- translateEngine = new GoogleTranslate(config.translationKeyInfo.apiKey);
34
- } else if (config.translationKeyInfo.kind === 'aws') {
35
- translateEngine = new AWSTranslate(
36
- config.translationKeyInfo.accessKeyId,
37
- config.translationKeyInfo.secretAccessKey,
38
- config.translationKeyInfo.region
39
- );
40
- } else if (config.translationKeyInfo.kind==='azure') {
41
- translateEngine = new AzureTranslate(config.translationKeyInfo.secretKey, config.translationKeyInfo.region);
42
- } else if (config.translationKeyInfo.kind==='deepLFree') {
43
- translateEngine = new DeepLTranslate(config.translationKeyInfo.secretKey, 'free');
44
- } else if (config.translationKeyInfo.kind==='deepLPro') {
45
- translateEngine = new DeepLTranslate(config.translationKeyInfo.secretKey, 'pro');
46
- } else {
47
- console.warn(
48
- 'You must provide a Google, AWS or Azure parameters first in the extension settings.'
49
- );
50
- return;
51
- }
52
-
53
-
54
- const fileMode =config.mode;
55
- const files = readFiles(sourceFile, fileMode);
56
- if (files === null) {
57
- return;
58
- }
59
-
60
- // enforce source locale if provided in settings
61
- if (config.sourceLocale !== files.sourceLocale) {
62
- console.log(
63
- 'You must use the ' +
64
- config.sourceLocale +
65
- '.json file due to your Source Locale setting.'
66
- );
67
- return;
68
- }
69
-
70
- const keepTranslations = config.keepTranslations === 'keep';
71
- const keepExtras = config.keepExtraTranslations === 'keep';
72
-
73
- // load source JSON
74
- let source: any;
75
- try {
76
- source = await files.loadJsonFromLocale(files.sourceLocale);
77
- } catch (error) {
78
- if (error instanceof Error) {
79
- console.log(error, 'Source file malformed');
80
- }
81
- return;
82
- }
83
-
84
- // Iterate target Locales
85
- files.targetLocales.forEach(async (targetLocale) => {
86
- try {
87
- const isValid = await translateEngine.isValidLocale(targetLocale);
88
- if (!isValid) {
89
- throw Error(targetLocale + ' is not supported. Skipping.');
90
- }
91
-
92
- const targetOriginal = await files.loadJsonFromLocale(targetLocale);
93
-
94
- // Iterate source terms
95
- const targetNew = await recurseNode(
96
- source,
97
- targetOriginal,
98
- keepTranslations,
99
- keepExtras,
100
- files.sourceLocale,
101
- targetLocale,
102
- translateEngine
103
- );
104
-
105
- // save target
106
- files.saveJsonToLocale(targetLocale, targetNew);
107
-
108
- const feedback = "Translated locale '" + targetLocale + "'";
109
- console.log(feedback);
110
-
111
- } catch (error) {
112
- if (error instanceof Error) {
113
- console.error(error);
114
- }
115
- return;
116
- }
117
- });
118
- }
119
-
120
-
121
- const readFiles: (
122
- filePath: string,
123
- mode: 'file' | 'folder'
124
- ) => IFiles | null = (filePath: string, mode: string) => {
125
- try {
126
- const files: IFiles =
127
- mode === 'file' ? new Files(filePath) : new FolderFiles(filePath);
128
-
129
- // log locale info
130
- console.log('Source locale = ' + files.sourceLocale);
131
- console.log('Target locales = ' + files.targetLocales);
132
-
133
- return files;
134
- } catch (error) {
135
- if (error instanceof Error) {
136
- console.error(error);
137
- }
138
- return null;
139
- }
140
- };
141
-
142
- async function recurseNode(
143
- source: any,
144
- original: any,
145
- keepTranslations: boolean | null,
146
- keepExtras: boolean | null,
147
- sourceLocale: string,
148
- locale: string,
149
- translateEngine: ITranslate,
150
- isArray: boolean = false
151
- ): Promise<any> {
152
- const destination: any = isArray ? [] : {};
153
-
154
- // defaults
155
- if (keepTranslations === null) {
156
- keepTranslations = true;
157
- }
158
- if (keepExtras === null) {
159
- keepExtras = true;
160
- }
161
-
162
- for (const term in source) {
163
- const node = source[term];
164
-
165
- if (node instanceof Object && node !== null) {
166
- destination[term] = await recurseNode(
167
- node,
168
- original[term] ?? {},
169
- keepTranslations,
170
- keepExtras,
171
- sourceLocale,
172
- locale,
173
- translateEngine,
174
- node instanceof Array
175
- );
176
- } else {
177
- // if we already have a translation, keep it
178
- if (keepTranslations && original[term]) {
179
- destination[term] = original[term];
180
- } else if (typeof node === 'number' || typeof node === 'boolean') {
181
- // numbers and booleans do not need translations
182
- destination[term] = node;
183
- } else {
184
- const translation = await translateEngine
185
- .translateText(node, sourceLocale, locale)
186
- .catch((err) =>console.error(err));
187
- destination[term] = translation;
188
- }
189
- }
190
- }
191
-
192
- if (keepExtras) {
193
- // add back in any terms that were not in source
194
- for (const term in original) {
195
- if (!destination[term]) {
196
- destination[term] = original[term];
197
- }
198
- }
199
- }
200
-
201
- return destination;
202
- }
203
-
204
-
@@ -1,8 +0,0 @@
1
- export interface ITranslate {
2
- isValidLocale(targetLocale: string): boolean;
3
- translateText(
4
- text: string,
5
- sourceLocale: string,
6
- targetLocale: string
7
- ): Promise<string>;
8
- }