-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathinline.ts
More file actions
206 lines (191 loc) · 6.56 KB
/
inline.ts
File metadata and controls
206 lines (191 loc) · 6.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import { Command } from 'commander';
import { BaseCLI } from './base.js';
import { SupportedLibraries, TranslateFlags, Options } from '../types/index.js';
import {
attachInlineTranslateFlags,
attachTranslateFlags,
attachValidateFlags,
} from './flags.js';
import { displayHeader, exitSync } from '../console/logging.js';
import { logger } from '../console/logger.js';
import { intro } from '@clack/prompts';
import chalk from 'chalk';
import { resolveLocaleFiles } from '../fs/config/parseFilesConfig.js';
import { noFilesError } from '../console/index.js';
import { saveJSON } from '../fs/saveJSON.js';
import loadJSON from '../fs/loadJSON.js';
import { generateSettings } from '../config/generateSettings.js';
import { aggregateInlineTranslations } from '../translation/stage.js';
import { validateConfigExists } from '../config/validateSettings.js';
import { validateProject } from '../translation/validate.js';
import { Libraries, InlineLibrary } from '../types/libraries.js';
/**
* Stand in for a CLI tool that does any sort of inline content translations
*/
export class InlineCLI extends BaseCLI {
constructor(
command: Command,
library: InlineLibrary,
additionalModules?: SupportedLibraries[]
) {
super(command, library, additionalModules);
}
public init() {
this.setupStageCommand();
this.setupTranslateCommand();
this.setupGenerateSourceCommand();
this.setupValidateCommand();
this.setupDownloadCommand();
this.setupEnqueueCommand();
}
protected setupStageCommand(): void {
attachInlineTranslateFlags(
attachTranslateFlags(
this.program
.command('stage')
.description(
'Submits the project to the General Translation API for translation. Translations created using this command will require human approval.'
)
)
).action(async (options: TranslateFlags) => {
displayHeader(
'Staging project for translation with approval required...'
);
await this.handleStage(options);
logger.endCommand('Done!');
});
}
protected setupTranslateCommand(): void {
attachInlineTranslateFlags(
attachTranslateFlags(
this.program
.command('translate')
.description(
'Scans the project for a dictionary and inline translations and sends the updates to the General Translation API for translation.'
)
)
).action(async (options: TranslateFlags) => {
displayHeader('Translating project...');
await this.handleTranslate(options);
logger.endCommand('Done!');
});
}
protected setupValidateCommand(): void {
attachValidateFlags(
this.program
.command('validate [files...]')
.description(
'Scans the project for a dictionary and/or inline content and validates the project for errors.'
)
).action(async (files: string[], options: Options) => {
// intro here since we don't want to show the ascii title
intro(chalk.cyan('Validating project...'));
await this.handleValidate(options, files);
logger.endCommand('Done!');
});
}
protected setupGenerateSourceCommand(): void {
attachInlineTranslateFlags(
attachTranslateFlags(
this.program
.command('generate')
.description(
'Generate a translation file for the source locale. This command should be used if you are handling your own translations.'
)
)
).action(async (initOptions: TranslateFlags) => {
displayHeader('Generating source templates...');
await this.handleGenerateSourceCommand(initOptions);
logger.endCommand('Done!');
});
}
protected async handleGenerateSourceCommand(
initOptions: TranslateFlags
): Promise<void> {
const settings = await generateSettings(initOptions);
const updates = await aggregateInlineTranslations(
initOptions,
settings,
fallbackToGtReact(this.library)
);
// Convert updates to the proper data format
const newData: Record<string, any> = {};
for (const update of updates) {
const { source, metadata } = update;
const { hash, id } = metadata;
if (id) {
newData[id] = source;
} else {
newData[hash] = source;
}
}
// Save source file if files.json is provided
if (settings.files && settings.files.placeholderPaths.gt) {
const translationFiles = resolveLocaleFiles(
settings.files.placeholderPaths,
settings.defaultLocale
);
if (!translationFiles.gt) {
logger.error(noFilesError);
exitSync(1);
}
await saveJSON(translationFiles.gt, newData);
logger.step('Source file saved successfully!');
// Also save translations (after merging with existing translations)
for (const locale of settings.locales) {
const translationsFile = resolveLocaleFiles(
settings.files.placeholderPaths,
locale
);
if (!translationsFile.gt) {
continue;
}
const existingTranslations = loadJSON(translationsFile.gt);
const mergedTranslations = {
...newData,
...existingTranslations,
};
// Filter out keys that don't exist in newData
const filteredTranslations = Object.fromEntries(
Object.entries(mergedTranslations).filter(([key]) => newData[key])
);
await saveJSON(translationsFile.gt, filteredTranslations);
}
logger.step('Merged translations successfully!');
}
}
protected async handleValidate(
initOptions: Options,
files?: string[]
): Promise<void> {
validateConfigExists();
const settings = await generateSettings(initOptions);
// First run the base class's handleTranslate method
const options = { ...initOptions, ...settings };
// Fallback to gt-react
const pkg = fallbackToGtReact(this.library);
if (files && files.length > 0) {
// Validate specific files using createInlineUpdates
await validateProject(options, pkg, files);
} else {
// Validate whole project as before
await validateProject(options, pkg);
}
}
}
function fallbackToGtReact(library: SupportedLibraries): InlineLibrary {
return [
Libraries.GT_NEXT,
Libraries.GT_NODE,
Libraries.GT_REACT_NATIVE,
Libraries.GT_FLASK,
Libraries.GT_FASTAPI,
].includes(library as Libraries)
? (library as
| typeof Libraries.GT_NEXT
| typeof Libraries.GT_NODE
| typeof Libraries.GT_REACT_NATIVE
| typeof Libraries.GT_FLASK
| typeof Libraries.GT_FASTAPI)
: Libraries.GT_REACT;
}