@localheroai/cli 0.0.1
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/LICENSE +21 -0
- package/package.json +62 -0
- package/src/api/auth.js +15 -0
- package/src/api/client.js +42 -0
- package/src/api/imports.js +20 -0
- package/src/api/projects.js +24 -0
- package/src/api/translations.js +37 -0
- package/src/cli.js +71 -0
- package/src/commands/init.js +285 -0
- package/src/commands/login.js +69 -0
- package/src/commands/translate.js +282 -0
- package/src/utils/auth.js +23 -0
- package/src/utils/config.js +96 -0
- package/src/utils/defaults.js +7 -0
- package/src/utils/files.js +139 -0
- package/src/utils/git.js +16 -0
- package/src/utils/github.js +65 -0
- package/src/utils/helpers.js +3 -0
- package/src/utils/import-service.js +146 -0
- package/src/utils/project-service.js +11 -0
- package/src/utils/prompt-service.js +51 -0
- package/src/utils/translation-updater.js +154 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 LocalHero.ai
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/package.json
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@localheroai/cli",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "CLI tool for managing translations with LocalHero.ai",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"localheroai": "./src/cli.js"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"start": "node src/cli.js",
|
|
12
|
+
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
|
|
13
|
+
"lint": "eslint .",
|
|
14
|
+
"postinstall": "chmod +x src/cli.js"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"i18n",
|
|
18
|
+
"translation",
|
|
19
|
+
"cli",
|
|
20
|
+
"localization"
|
|
21
|
+
],
|
|
22
|
+
"author": "LocalHero.ai",
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"chalk": "^5.3.0",
|
|
26
|
+
"commander": "^12.0.0",
|
|
27
|
+
"dotenv": "^16.4.5",
|
|
28
|
+
"glob": "^10.3.10",
|
|
29
|
+
"inquirer": "^12.0.1",
|
|
30
|
+
"yaml": "^2.3.4"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@inquirer/testing": "^2.1.36",
|
|
34
|
+
"@jest/globals": "^29.7.0",
|
|
35
|
+
"eslint": "^9.14.0",
|
|
36
|
+
"jest": "^29.7.0",
|
|
37
|
+
"@babel/preset-env": "^7.24.0"
|
|
38
|
+
},
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=22.11.0"
|
|
41
|
+
},
|
|
42
|
+
"files": [
|
|
43
|
+
"src",
|
|
44
|
+
"README.md",
|
|
45
|
+
"LICENSE"
|
|
46
|
+
],
|
|
47
|
+
"jest": {
|
|
48
|
+
"testEnvironment": "node",
|
|
49
|
+
"transform": {},
|
|
50
|
+
"moduleNameMapper": {
|
|
51
|
+
"^(\\.{1,2}/.*)\\.js$": "$1"
|
|
52
|
+
},
|
|
53
|
+
"testMatch": [
|
|
54
|
+
"**/tests/**/*.test.js"
|
|
55
|
+
],
|
|
56
|
+
"testEnvironmentOptions": {
|
|
57
|
+
"extensionsToTreatAsEsm": [
|
|
58
|
+
".js"
|
|
59
|
+
]
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
package/src/api/auth.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { apiRequest } from './client.js';
|
|
2
|
+
|
|
3
|
+
export async function verifyApiKey(apiKey) {
|
|
4
|
+
try {
|
|
5
|
+
return await apiRequest('/api/v1/auth/verify', {
|
|
6
|
+
apiKey
|
|
7
|
+
});
|
|
8
|
+
} catch (error) {
|
|
9
|
+
return {
|
|
10
|
+
error: {
|
|
11
|
+
message: error.message || 'Failed to verify API key'
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
const DEFAULT_API_HOST = 'https://api.localhero.ai';
|
|
2
|
+
|
|
3
|
+
export function getApiHost() {
|
|
4
|
+
return process.env.LOCALHERO_API_HOST || DEFAULT_API_HOST;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export async function apiRequest(endpoint, options = {}) {
|
|
8
|
+
const apiHost = getApiHost();
|
|
9
|
+
const url = `${apiHost}${endpoint}`;
|
|
10
|
+
const apiKey = process.env.LOCALHERO_API_KEY || options.apiKey;
|
|
11
|
+
|
|
12
|
+
const headers = {
|
|
13
|
+
'Content-Type': 'application/json',
|
|
14
|
+
...options.headers
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
if (apiKey) {
|
|
18
|
+
headers['Authorization'] = `Bearer ${apiKey}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
console.log('API Request:', url);
|
|
22
|
+
const response = await fetch(url, {
|
|
23
|
+
...options,
|
|
24
|
+
headers,
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
let data;
|
|
28
|
+
try {
|
|
29
|
+
data = await response.json();
|
|
30
|
+
} catch (error) {
|
|
31
|
+
throw new Error('Failed to parse API response', { cause: error });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (!response.ok) {
|
|
35
|
+
const errorMessage = Array.isArray(data?.errors)
|
|
36
|
+
? data.errors.map(err => typeof err === 'string' ? err : err.message).join(', ')
|
|
37
|
+
: 'API request failed';
|
|
38
|
+
throw new Error(errorMessage);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return data;
|
|
42
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { getApiKey } from '../utils/auth.js';
|
|
2
|
+
import { apiRequest } from './client.js';
|
|
3
|
+
|
|
4
|
+
export async function createImport({ projectId, translations }) {
|
|
5
|
+
const apiKey = await getApiKey();
|
|
6
|
+
const response = await apiRequest(`/api/v1/projects/${projectId}/imports`, {
|
|
7
|
+
method: 'POST',
|
|
8
|
+
body: JSON.stringify({ translations }),
|
|
9
|
+
apiKey
|
|
10
|
+
});
|
|
11
|
+
return response.import;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function checkImportStatus(projectId, importId) {
|
|
15
|
+
const apiKey = await getApiKey();
|
|
16
|
+
const response = await apiRequest(`/api/v1/projects/${projectId}/imports/${importId}`, {
|
|
17
|
+
apiKey
|
|
18
|
+
});
|
|
19
|
+
return response.import;
|
|
20
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { getApiKey } from '../utils/auth.js';
|
|
2
|
+
import { apiRequest } from './client.js';
|
|
3
|
+
|
|
4
|
+
export async function listProjects() {
|
|
5
|
+
const apiKey = await getApiKey();
|
|
6
|
+
const response = await apiRequest('/api/v1/projects', { apiKey });
|
|
7
|
+
return response.projects;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export async function createProject(data) {
|
|
11
|
+
const apiKey = await getApiKey();
|
|
12
|
+
const response = await apiRequest('/api/v1/projects', {
|
|
13
|
+
method: 'POST',
|
|
14
|
+
body: JSON.stringify({
|
|
15
|
+
project: {
|
|
16
|
+
name: data.name,
|
|
17
|
+
source_language: data.sourceLocale,
|
|
18
|
+
target_languages: data.targetLocales
|
|
19
|
+
}
|
|
20
|
+
}),
|
|
21
|
+
apiKey
|
|
22
|
+
});
|
|
23
|
+
return response.project;
|
|
24
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { getApiKey } from '../utils/auth.js';
|
|
2
|
+
import { apiRequest } from './client.js';
|
|
3
|
+
export async function createTranslationJob({ sourceFiles, targetLocales, projectId }) {
|
|
4
|
+
const apiKey = await getApiKey();
|
|
5
|
+
const response = await apiRequest(`/api/v1/projects/${projectId}/translation_jobs`, {
|
|
6
|
+
method: 'POST',
|
|
7
|
+
body: JSON.stringify({
|
|
8
|
+
target_languages: targetLocales,
|
|
9
|
+
files: sourceFiles.map(file => ({
|
|
10
|
+
path: file.path,
|
|
11
|
+
content: file.content,
|
|
12
|
+
format: file.format
|
|
13
|
+
}))
|
|
14
|
+
}),
|
|
15
|
+
apiKey
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
if (!response.jobs || !response.jobs.length) {
|
|
19
|
+
throw new Error('No translation jobs were created');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
return {
|
|
23
|
+
jobs: response.jobs,
|
|
24
|
+
totalJobs: response.jobs.length
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function checkJobStatus(jobId, includeTranslations = false) {
|
|
29
|
+
const apiKey = await getApiKey();
|
|
30
|
+
const endpoint = `/api/v1/translation_jobs/${jobId}${includeTranslations ? '?include_translations=true' : ''}`;
|
|
31
|
+
return apiRequest(endpoint, { apiKey });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function getTranslations(jobId) {
|
|
35
|
+
const apiKey = await getApiKey();
|
|
36
|
+
return apiRequest(`/api/v1/translation_jobs/${jobId}/translations`, { apiKey });
|
|
37
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { Command } from 'commander';
|
|
4
|
+
import chalk from 'chalk';
|
|
5
|
+
import { readFileSync } from 'fs';
|
|
6
|
+
import { login } from './commands/login.js';
|
|
7
|
+
import { init } from './commands/init.js';
|
|
8
|
+
import { defaultDependencies } from './utils/defaults.js';
|
|
9
|
+
import { translate } from './commands/translate.js';
|
|
10
|
+
|
|
11
|
+
const program = new Command();
|
|
12
|
+
|
|
13
|
+
function displayBanner() {
|
|
14
|
+
console.log(chalk.blue(`
|
|
15
|
+
===============================================
|
|
16
|
+
|
|
17
|
+
LocalHero.ai CLI
|
|
18
|
+
|
|
19
|
+
===============================================
|
|
20
|
+
`));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function getVersion() {
|
|
24
|
+
const packageJson = JSON.parse(
|
|
25
|
+
readFileSync(new URL('../package.json', import.meta.url))
|
|
26
|
+
);
|
|
27
|
+
return packageJson.version;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function handleApiError(error) {
|
|
31
|
+
console.error(chalk.red(`❌ ${error.message}`));
|
|
32
|
+
process.exit(1);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function wrapCommandAction(action) {
|
|
36
|
+
return function (...args) {
|
|
37
|
+
return Promise.resolve(action(...args)).catch(handleApiError);
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
program
|
|
42
|
+
.name('localhero')
|
|
43
|
+
.description('CLI tool for automatic I18n translations with LocalHero.ai')
|
|
44
|
+
.version(getVersion())
|
|
45
|
+
.addHelpText('beforeAll', displayBanner)
|
|
46
|
+
.action(() => {
|
|
47
|
+
console.log(`Version: ${getVersion()}`);
|
|
48
|
+
console.log('\nLocalHero.ai is a powerful i18n translation service');
|
|
49
|
+
console.log('that helps you manage your application translations.');
|
|
50
|
+
console.log('\n🔗 Visit https://localhero.ai for more information');
|
|
51
|
+
console.log('💡 Use --help to see available commands');
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
program
|
|
55
|
+
.command('login')
|
|
56
|
+
.description('Authenticate with LocalHero.ai using an API key')
|
|
57
|
+
.action(wrapCommandAction(() => login(defaultDependencies)));
|
|
58
|
+
|
|
59
|
+
program
|
|
60
|
+
.command('init')
|
|
61
|
+
.description('Initialize a new LocalHero.ai project')
|
|
62
|
+
.action(wrapCommandAction(() => init(defaultDependencies)));
|
|
63
|
+
|
|
64
|
+
program
|
|
65
|
+
.command('translate')
|
|
66
|
+
.description('Translate missing keys in your i18n files')
|
|
67
|
+
.option('-v, --verbose', 'Show detailed progress information')
|
|
68
|
+
.option('-c, --commit', 'Automatically commit changes (useful for CI/CD)')
|
|
69
|
+
.action(wrapCommandAction((options) => translate(options)));
|
|
70
|
+
|
|
71
|
+
program.parse();
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import { promises as fs } from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import chalk from 'chalk';
|
|
4
|
+
import { createPromptService } from '../utils/prompt-service.js';
|
|
5
|
+
import { defaultProjectService } from '../utils/project-service.js';
|
|
6
|
+
import { configService } from '../utils/config.js';
|
|
7
|
+
import { checkAuth } from '../utils/auth.js';
|
|
8
|
+
import { login } from './login.js';
|
|
9
|
+
import { importService } from '../utils/import-service.js';
|
|
10
|
+
import { createGitHubActionFile } from '../utils/github.js';
|
|
11
|
+
|
|
12
|
+
const PROJECT_TYPES = {
|
|
13
|
+
rails: {
|
|
14
|
+
indicators: ['config/application.rb', 'Gemfile'],
|
|
15
|
+
defaults: {
|
|
16
|
+
translationPath: 'config/locales/',
|
|
17
|
+
filePattern: '**/*.{yml,yaml}'
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
react: {
|
|
21
|
+
indicators: ['package.json', 'src/locales', 'public/locales'],
|
|
22
|
+
defaults: {
|
|
23
|
+
translationPath: 'src/locales/',
|
|
24
|
+
filePattern: '**/*.{json,yml}'
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
generic: {
|
|
28
|
+
indicators: [],
|
|
29
|
+
defaults: {
|
|
30
|
+
translationPath: 'locales/',
|
|
31
|
+
filePattern: '**/*.{json,yml,yaml}'
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
async function detectProjectType() {
|
|
37
|
+
for (const [type, config] of Object.entries(PROJECT_TYPES)) {
|
|
38
|
+
try {
|
|
39
|
+
for (const indicator of config.indicators) {
|
|
40
|
+
await fs.access(indicator);
|
|
41
|
+
return { type, defaults: config.defaults };
|
|
42
|
+
}
|
|
43
|
+
} catch {
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
type: 'generic',
|
|
49
|
+
defaults: PROJECT_TYPES.generic.defaults
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function checkExistingConfig() {
|
|
54
|
+
try {
|
|
55
|
+
await fs.access('localhero.json');
|
|
56
|
+
return true;
|
|
57
|
+
} catch {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function selectProject(projectService, promptService) {
|
|
63
|
+
const projects = await projectService.listProjects();
|
|
64
|
+
|
|
65
|
+
if (!projects || projects.length === 0) {
|
|
66
|
+
return { choice: 'new' };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const choices = [
|
|
70
|
+
{ name: '✨ Create new project', value: 'new' },
|
|
71
|
+
{ name: '─────────────', value: 'separator', disabled: true },
|
|
72
|
+
...projects.map(p => ({
|
|
73
|
+
name: p.name,
|
|
74
|
+
value: p.id
|
|
75
|
+
}))
|
|
76
|
+
];
|
|
77
|
+
|
|
78
|
+
const projectChoice = await promptService.select({
|
|
79
|
+
message: 'Would you like to use an existing project or create a new one?',
|
|
80
|
+
choices
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
return {
|
|
84
|
+
choice: projectChoice,
|
|
85
|
+
project: projects.find(p => p.id === projectChoice)
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function promptForConfig(projectDefaults, projectService, promptService) {
|
|
90
|
+
const { choice: projectChoice, project: existingProject } = await selectProject(projectService, promptService);
|
|
91
|
+
let projectId = projectChoice;
|
|
92
|
+
let newProject = false;
|
|
93
|
+
let config = await promptService.getProjectSetup();
|
|
94
|
+
|
|
95
|
+
if (!existingProject) {
|
|
96
|
+
config = {
|
|
97
|
+
projectName: await promptService.input({
|
|
98
|
+
message: 'Project name:',
|
|
99
|
+
default: path.basename(process.cwd()),
|
|
100
|
+
}),
|
|
101
|
+
sourceLocale: await promptService.input({
|
|
102
|
+
message: 'Source language code:',
|
|
103
|
+
default: 'en'
|
|
104
|
+
}),
|
|
105
|
+
outputLocales: (await promptService.input({
|
|
106
|
+
message: 'Target languages (comma-separated):',
|
|
107
|
+
})).split(',').map(lang => lang.trim()).filter(Boolean)
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
newProject = await projectService.createProject({
|
|
111
|
+
name: config.projectName,
|
|
112
|
+
sourceLocale: config.sourceLocale,
|
|
113
|
+
targetLocales: config.outputLocales
|
|
114
|
+
});
|
|
115
|
+
projectId = newProject.id;
|
|
116
|
+
} else {
|
|
117
|
+
config = {
|
|
118
|
+
projectName: existingProject.name,
|
|
119
|
+
sourceLocale: existingProject.source_language,
|
|
120
|
+
outputLocales: existingProject.target_languages
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const translationPath = await promptService.input({
|
|
125
|
+
message: 'Translation files path:',
|
|
126
|
+
default: projectDefaults.defaults.translationPath,
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
const ignorePaths = await promptService.input({
|
|
130
|
+
message: 'Paths to ignore (comma-separated, leave empty for none):',
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
if (newProject) {
|
|
134
|
+
console.log(chalk.green(`\n✓ Project created, view it at: ${newProject.url}`));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
...config,
|
|
139
|
+
projectId,
|
|
140
|
+
translationPath,
|
|
141
|
+
ignorePaths: ignorePaths.split(',').map(p => p.trim()).filter(Boolean)
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export async function init(deps = {}) {
|
|
146
|
+
const {
|
|
147
|
+
console = global.console,
|
|
148
|
+
basePath = process.cwd(),
|
|
149
|
+
promptService = createPromptService({ inquirer: await import('@inquirer/prompts') }),
|
|
150
|
+
projectService = defaultProjectService,
|
|
151
|
+
configUtils = configService,
|
|
152
|
+
authUtils = { checkAuth },
|
|
153
|
+
importUtils = importService
|
|
154
|
+
} = deps;
|
|
155
|
+
|
|
156
|
+
const existingConfig = await configUtils.getProjectConfig(basePath);
|
|
157
|
+
if (existingConfig) {
|
|
158
|
+
console.log(chalk.yellow('localhero.json already exists. Skipping initialization.'));
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const isAuthenticated = await authUtils.checkAuth();
|
|
163
|
+
if (!isAuthenticated) {
|
|
164
|
+
console.log(chalk.yellow('\nNo API key found. You need to authenticate first.'));
|
|
165
|
+
console.log('Please run the login command to continue.\n');
|
|
166
|
+
|
|
167
|
+
const { shouldLogin } = await promptService.confirmLogin();
|
|
168
|
+
|
|
169
|
+
if (shouldLogin) {
|
|
170
|
+
await login();
|
|
171
|
+
} else {
|
|
172
|
+
console.log('\nYou can run login later with: npx localhero login');
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
console.log(chalk.blue('\nWelcome to LocalHero.ai!'));
|
|
178
|
+
console.log('Let\'s set up configuration for your project.\n');
|
|
179
|
+
|
|
180
|
+
const projectDefaults = await detectProjectType();
|
|
181
|
+
const answers = await promptForConfig(projectDefaults, projectService, promptService);
|
|
182
|
+
|
|
183
|
+
const config = {
|
|
184
|
+
schemaVersion: '1.0',
|
|
185
|
+
projectId: answers.projectId,
|
|
186
|
+
sourceLocale: answers.sourceLocale,
|
|
187
|
+
outputLocales: answers.outputLocales,
|
|
188
|
+
translationFiles: {
|
|
189
|
+
paths: [answers.translationPath],
|
|
190
|
+
ignore: answers.ignorePaths
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
await configUtils.saveProjectConfig(config, basePath);
|
|
195
|
+
console.log(chalk.green('\n✓ Created localhero.json'));
|
|
196
|
+
console.log('Configuration:');
|
|
197
|
+
console.log(JSON.stringify(config, null, 2));
|
|
198
|
+
console.log(' ');
|
|
199
|
+
|
|
200
|
+
const shouldSetupGitHubAction = await promptService.confirm({
|
|
201
|
+
message: 'Would you like to set up GitHub Actions for automatic translations?',
|
|
202
|
+
default: true
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
if (shouldSetupGitHubAction) {
|
|
206
|
+
try {
|
|
207
|
+
const workflowFile = await createGitHubActionFile(basePath, config.translationFiles.paths);
|
|
208
|
+
console.log(chalk.green(`\n✓ Created GitHub Action workflow at ${workflowFile}`));
|
|
209
|
+
console.log('\nNext steps:');
|
|
210
|
+
console.log('1. Add your API key to your repository\'s secrets:');
|
|
211
|
+
console.log(' - Go to Settings > Secrets > Actions > New repository secret');
|
|
212
|
+
console.log(' - Name: LOCALHERO_API_KEY');
|
|
213
|
+
console.log(' - Value: [Your API Key] (find this at https://localhero.ai/api-keys or in your local .localhero_key file)');
|
|
214
|
+
console.log('\n2. Commit and push the workflow file to enable automatic translations\n');
|
|
215
|
+
} catch (error) {
|
|
216
|
+
console.log(chalk.yellow('\nFailed to create GitHub Action workflow:'), error.message);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const shouldImport = await promptService.confirm({
|
|
221
|
+
message: 'Would you like to import existing translation files? (recommended)',
|
|
222
|
+
default: true
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
if (shouldImport) {
|
|
226
|
+
console.log('\nSearching for translation files...');
|
|
227
|
+
console.log(`Looking in: ${config.translationFiles.paths.join(', ')}`);
|
|
228
|
+
if (config.translationFiles.ignore.length) {
|
|
229
|
+
console.log(`Ignoring: ${config.translationFiles.ignore.join(', ')}`);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const importResult = await importUtils.importTranslations(config, basePath);
|
|
233
|
+
|
|
234
|
+
if (importResult.status === 'no_files') {
|
|
235
|
+
console.log(chalk.yellow('\nNo translation files found.'));
|
|
236
|
+
console.log('Make sure your translation files:');
|
|
237
|
+
console.log('1. Are in the specified path(s)');
|
|
238
|
+
console.log('2. Have the correct file extensions (.json, .yml, or .yaml)');
|
|
239
|
+
console.log('3. Follow the naming convention: [language-code].[extension]');
|
|
240
|
+
console.log(`4. Include source language files (${config.sourceLocale}.[extension])`);
|
|
241
|
+
} else if (importResult.status === 'failed') {
|
|
242
|
+
console.log(chalk.red('\n✗ Failed to import translations'));
|
|
243
|
+
if (importResult.error) {
|
|
244
|
+
console.log(`Error: ${importResult.error}`);
|
|
245
|
+
}
|
|
246
|
+
} else if (importResult.status === 'completed') {
|
|
247
|
+
console.log(chalk.green('\n✓ Successfully imported translations'));
|
|
248
|
+
|
|
249
|
+
if (importResult.files) {
|
|
250
|
+
console.log('\nImported files:');
|
|
251
|
+
[...importResult.files.source, ...importResult.files.target]
|
|
252
|
+
.sort((a, b) => a.path.localeCompare(b.path))
|
|
253
|
+
.forEach(file => {
|
|
254
|
+
const isSource = importResult.files.source.includes(file);
|
|
255
|
+
console.log(`- ${file.path}${isSource ? ' [source]' : ''}`);
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
if (importResult.sourceImport) {
|
|
260
|
+
console.log(`\nImported ${importResult.sourceImport.statistics.total_keys} source language keys`);
|
|
261
|
+
|
|
262
|
+
if (importResult.sourceImport.warnings?.length) {
|
|
263
|
+
console.log(chalk.yellow('\nWarnings:'));
|
|
264
|
+
importResult.sourceImport.warnings.forEach(warning => {
|
|
265
|
+
console.log(`- ${warning.message} (${warning.language})`);
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
console.log('\nTarget Languages:');
|
|
271
|
+
importResult.statistics.languages.forEach(lang => {
|
|
272
|
+
console.log(`${lang.code.toUpperCase()}: ${lang.translated}/${importResult.statistics.total_keys} translated`);
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
if (importResult.warnings?.length) {
|
|
276
|
+
console.log(chalk.yellow('\nWarnings:'));
|
|
277
|
+
importResult.warnings.forEach(warning => {
|
|
278
|
+
console.log(`- ${warning.message} (${warning.language})`);
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
console.log('\n🚀 Done! Start translating with: npx localhero translate');
|
|
285
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { promises as fs } from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import chalk from 'chalk';
|
|
4
|
+
import { createPromptService } from '../utils/prompt-service.js';
|
|
5
|
+
import { updateGitignore } from '../utils/git.js';
|
|
6
|
+
import { defaultDependencies } from '../utils/defaults.js';
|
|
7
|
+
import { verifyApiKey as defaultVerifyApiKey } from '../api/auth.js';
|
|
8
|
+
import { configService } from '../utils/config.js';
|
|
9
|
+
|
|
10
|
+
const API_KEY_PATTERN = /^tk_[a-zA-Z0-9]{48}$/;
|
|
11
|
+
|
|
12
|
+
export async function login(deps = defaultDependencies) {
|
|
13
|
+
const {
|
|
14
|
+
console = global.console,
|
|
15
|
+
basePath = process.cwd(),
|
|
16
|
+
promptService = createPromptService({ inquirer: await import('@inquirer/prompts') }),
|
|
17
|
+
verifyApiKey = defaultVerifyApiKey,
|
|
18
|
+
gitUtils = { updateGitignore },
|
|
19
|
+
configUtils = configService
|
|
20
|
+
} = deps;
|
|
21
|
+
|
|
22
|
+
const existingConfig = await configUtils.getAuthConfig(basePath);
|
|
23
|
+
|
|
24
|
+
if (existingConfig?.api_key) {
|
|
25
|
+
console.log(chalk.yellow('\n⚠️ Warning: This will replace your existing API key configuration'));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const apiKey = process.env.LOCALHERO_API_KEY || (
|
|
29
|
+
console.log(chalk.blue('\nℹ️ Please enter your API key from https://localhero.ai/api-keys\n')),
|
|
30
|
+
await promptService.getApiKey()
|
|
31
|
+
);
|
|
32
|
+
|
|
33
|
+
if (!API_KEY_PATTERN.test(apiKey)) {
|
|
34
|
+
throw new Error('Invalid API key format');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const result = await verifyApiKey(apiKey);
|
|
38
|
+
|
|
39
|
+
if (result.error) {
|
|
40
|
+
throw new Error(result.error.message);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const config = {
|
|
44
|
+
api_key: apiKey,
|
|
45
|
+
last_verified: new Date().toISOString()
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
await configUtils.saveAuthConfig(config, basePath);
|
|
49
|
+
const gitignoreUpdated = await gitUtils.updateGitignore(basePath);
|
|
50
|
+
|
|
51
|
+
console.log(chalk.green('\n✓ API key verified and saved to .localhero_key'));
|
|
52
|
+
if (gitignoreUpdated) {
|
|
53
|
+
console.log(chalk.green('✓ Added .localhero_key to .gitignore'));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
console.log(chalk.blue(`💼️ Organization: ${result.organization.name}`));
|
|
57
|
+
console.log(chalk.blue(`📚 Projects: ${result.organization.projects.map(p => p.name).join(', ')}`));
|
|
58
|
+
|
|
59
|
+
const projectConfig = await configUtils.getProjectConfig(basePath);
|
|
60
|
+
|
|
61
|
+
if (!projectConfig) {
|
|
62
|
+
console.log(chalk.yellow('\n⚠️ Almost there! You need to set up your project configuration.'));
|
|
63
|
+
console.log(chalk.blue('Run this next:'));
|
|
64
|
+
console.log(chalk.white('\n npx localhero init\n'));
|
|
65
|
+
} else {
|
|
66
|
+
console.log('\nYou\'re ready to start translating!');
|
|
67
|
+
console.log('Try running: npx localhero translate');
|
|
68
|
+
}
|
|
69
|
+
}
|