-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.ts
More file actions
296 lines (251 loc) · 10.1 KB
/
Copy pathindex.ts
File metadata and controls
296 lines (251 loc) · 10.1 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#!/usr/bin/env node
/**
* DeepL CLI Entry Point
* Main command-line interface
*/
import { Command } from 'commander';
import chalk from 'chalk';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join, resolve, isAbsolute, extname } from 'path';
import { ConfigService } from '../storage/config.js';
import type { CacheService } from '../storage/cache.js';
import { resolvePaths } from '../utils/paths.js';
import type { DeepLClient } from '../api/deepl-client.js';
import { Logger } from '../utils/logger.js';
import { DeepLCLIError } from '../utils/errors.js';
import { ExitCode, getExitCodeFromError } from '../utils/exit-codes.js';
import { isSymlink } from '../utils/safe-read-file.js';
import { setNoInput } from '../utils/confirm.js';
import { registerAuth } from './commands/register-auth.js';
import { registerUsage } from './commands/register-usage.js';
import { registerLanguages } from './commands/register-languages.js';
import { registerTranslate } from './commands/register-translate.js';
import { registerWatch } from './commands/register-watch.js';
import { registerWrite } from './commands/register-write.js';
import { registerConfig } from './commands/register-config.js';
import { registerCache } from './commands/register-cache.js';
import { registerGlossary } from './commands/register-glossary.js';
import { registerHooks } from './commands/register-hooks.js';
import { registerStyleRules } from './commands/register-style-rules.js';
import { registerAdmin } from './commands/register-admin.js';
import { registerCompletion } from './commands/register-completion.js';
import { registerVoice } from './commands/register-voice.js';
import { registerInit } from './commands/register-init.js';
import { registerDetect } from './commands/register-detect.js';
// Get __dirname equivalent in ESM
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Read version from package.json
const packageJsonPath = join(__dirname, '../../package.json');
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as { version: string };
const { version } = packageJson;
// Initialize services
const paths = resolvePaths();
// Create config service - can be overridden by --config flag
let configService = new ConfigService(paths.configFile);
let cacheService: CacheService | null = null;
async function getCacheService(): Promise<CacheService> {
if (!cacheService) {
const { CacheService: CacheSvc } = await import('../storage/cache.js');
const configTtl = configService.getValue<number>('cache.ttl');
const configMaxSize = configService.getValue<number>('cache.maxSize');
cacheService = CacheSvc.getInstance({
dbPath: paths.cacheFile,
// Config TTL is in seconds, CacheService expects milliseconds
ttl: configTtl !== undefined ? configTtl * 1000 : undefined,
maxSize: configMaxSize,
});
}
return cacheService;
}
/**
* Handle error and exit with appropriate exit code
*/
function handleError(error: unknown): never {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
const exitCode = error instanceof Error ? getExitCodeFromError(error) : ExitCode.GeneralError;
Logger.error(chalk.red('Error:'), errorMessage);
if (error instanceof DeepLCLIError && error.suggestion) {
Logger.error(chalk.yellow('Suggestion:'), error.suggestion);
}
process.exit(exitCode);
}
/**
* Create DeepL client with API key from config or env
*/
async function createDeepLClient(overrideBaseUrl?: string): Promise<DeepLClient> {
const apiKey = configService.getValue<string>('auth.apiKey');
const envKey = process.env['DEEPL_API_KEY'];
const key = apiKey ?? envKey;
if (!key) {
Logger.error(chalk.red('Error: API key not set'));
Logger.warn(chalk.yellow('Run: deepl init (setup wizard) or deepl auth set-key <your-api-key>'));
process.exit(ExitCode.AuthError);
}
if (overrideBaseUrl) {
const { validateApiUrl } = await import('../utils/validate-url.js');
validateApiUrl(overrideBaseUrl);
}
const { DeepLClient: Client } = await import('../api/deepl-client.js');
return new Client(key, { baseUrl: overrideBaseUrl });
}
// Create program
const program = new Command();
program.showSuggestionAfterError(true);
program
.name('deepl')
.description('DeepL CLI - Next-generation translation tool powered by DeepL API')
.version(version)
.option('-q, --quiet', 'Suppress all non-essential output (errors and results only)')
.option('-v, --verbose', 'Show extra information (source language, timing, cache status)')
.option('-c, --config <file>', 'Use alternate configuration file')
.option('--no-input', 'Disable all interactive prompts (abort instead of prompting)')
.hook('preAction', (thisCommand) => {
const options = thisCommand.opts();
// Handle --config flag - reinitialize config service with custom path
// SECURITY: Validate path to prevent traversal attacks
if (options['config']) {
const customConfigPath = options['config'] as string;
// Resolve to absolute path (handles both relative and absolute paths)
// resolve() automatically normalizes and resolves '..' sequences safely
const safePath = isAbsolute(customConfigPath)
? resolve(customConfigPath)
: resolve(process.cwd(), customConfigPath);
// SECURITY: Require .json extension to prevent overwriting arbitrary files
if (extname(safePath).toLowerCase() !== '.json') {
Logger.error(chalk.red('Error: --config path must have a .json extension'));
process.exit(ExitCode.InvalidInput);
}
// SECURITY: Reject symlinks to prevent path traversal
if (isSymlink(safePath)) {
Logger.error(chalk.red('Error: --config path must not be a symlink'));
process.exit(ExitCode.InvalidInput);
}
configService = new ConfigService(safePath);
}
// Set quiet mode before any command runs
if (options['quiet']) {
Logger.setQuiet(true);
}
// Set verbose mode: --verbose flag takes precedence over config
if (options['verbose']) {
Logger.setVerbose(true);
} else {
const configVerbose = configService.getValue<boolean>('output.verbose');
if (configVerbose === true) {
Logger.setVerbose(true);
}
}
// Disable colors if output.color is false in config
const colorEnabled = configService.getValue<boolean>('output.color');
if (colorEnabled === false) {
chalk.level = 0;
}
// Set non-interactive mode
if (options['input'] === false) {
setNoInput(true);
}
});
/**
* Get raw API key and client options without constructing a client.
* Used by VoiceClient which needs direct access to create its own client.
*/
function getApiKeyAndOptions(): { apiKey: string; options: import('../api/http-client.js').DeepLClientOptions } {
const apiKey = configService.getValue<string>('auth.apiKey');
const envKey = process.env['DEEPL_API_KEY'];
const key = apiKey ?? envKey;
if (!key) {
Logger.error(chalk.red('Error: API key not set'));
Logger.warn(chalk.yellow('Run: deepl init (setup wizard) or deepl auth set-key <your-api-key>'));
process.exit(ExitCode.AuthError);
}
return { apiKey: key, options: {} };
}
// Shared dependencies passed to register functions
// Use a getter for configService because the preAction hook may reassign it
const deps = {
getConfigService: () => configService,
getCacheService,
createDeepLClient,
getApiKeyAndOptions,
handleError,
};
// Register all command groups, organized by help category
program.commandsGroup('Core Commands:');
registerTranslate(program, deps);
registerWrite(program, deps);
registerVoice(program, deps);
program.commandsGroup('Resources:');
registerGlossary(program, deps);
program.commandsGroup('Workflow:');
registerWatch(program, deps);
registerHooks(program, deps);
program.commandsGroup('Configuration:');
registerInit(program, deps);
registerAuth(program, deps);
registerConfig(program, deps);
registerCache(program, deps);
registerStyleRules(program, deps);
program.commandsGroup('Information:');
registerUsage(program, deps);
registerLanguages(program, deps);
registerDetect(program, deps);
registerCompletion(program, deps);
program.commandsGroup('Administration:');
registerAdmin(program, deps);
// Show Getting Started hint when no API key is configured
const savedApiKey = configService.getValue<string>('auth.apiKey');
const envApiKey = process.env['DEEPL_API_KEY'];
if (!savedApiKey && !envApiKey) {
program.addHelpText('beforeAll', chalk.yellow('Getting Started: Run deepl init to set up your API key.\n'));
}
// Did-you-mean suggestion for unknown commands
function levenshtein(a: string, b: string): number {
const m = a.length;
const n = b.length;
const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0) as number[]);
for (let i = 0; i <= m; i++) { dp[i]![0] = i; }
for (let j = 0; j <= n; j++) { dp[0]![j] = j; }
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
dp[i]![j] = a[i - 1] === b[j - 1]
? dp[i - 1]![j - 1]!
: 1 + Math.min(dp[i - 1]![j]!, dp[i]![j - 1]!, dp[i - 1]![j - 1]!);
}
}
return dp[m]![n]!;
}
program.on('command:*', (operands: string[]) => {
const unknown = operands[0];
if (!unknown) {
program.outputHelp();
process.exit(0);
return;
}
const commandNames = program.commands.map((cmd) => cmd.name());
let bestMatch = '';
let bestDistance = Infinity;
for (const name of commandNames) {
const d = levenshtein(unknown, name);
if (d < bestDistance) {
bestDistance = d;
bestMatch = name;
}
}
Logger.error(chalk.red(`Unknown command: ${unknown}`));
const maxDistance = Math.max(2, Math.floor(unknown.length / 2));
if (bestMatch && bestDistance <= maxDistance) {
Logger.error(chalk.yellow(`Did you mean: deepl ${bestMatch}?`));
}
Logger.error('');
Logger.error(`Run ${chalk.bold('deepl --help')} to see available commands.`);
process.exit(ExitCode.InvalidInput);
});
// Show help and exit 0 if no arguments provided
if (!process.argv.slice(2).length) {
program.outputHelp();
process.exit(0);
}
// Parse arguments
program.parse(process.argv);