@dialexjs/cli 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +86 -3
- package/dist/api.d.mts +246 -0
- package/dist/api.d.mts.map +1 -0
- package/dist/api.mjs +2 -0
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +1083 -0
- package/dist/index.mjs.map +1 -0
- package/dist/project-gkFBurqG.mjs +992 -0
- package/dist/project-gkFBurqG.mjs.map +1 -0
- package/dist/translate/index.d.mts +92 -0
- package/dist/translate/index.d.mts.map +1 -0
- package/dist/translate/index.mjs +289 -0
- package/dist/translate/index.mjs.map +1 -0
- package/package.json +50 -4
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1083 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { C as saveDictionaryFile, D as logger, E as runGenerate, T as generateDictionaries, _ as listLeaves, c as analyzeProject, d as TODO_PREFIX, f as copyLeaf, g as hasPath, h as getString, r as toKey, t as loadProject, v as listLocales, w as setString, y as loadDictionaryFile } from "./project-gkFBurqG.mjs";
|
|
3
|
+
import { Command } from "commander";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import fg from "fast-glob";
|
|
7
|
+
import { resolveI18nConfig } from "dialexjs/scanner";
|
|
8
|
+
import pc from "picocolors";
|
|
9
|
+
import * as p from "@clack/prompts";
|
|
10
|
+
import { loadFile, parseModule, writeFile } from "magicast";
|
|
11
|
+
import { addNuxtModule, addVitePlugin } from "magicast/helpers";
|
|
12
|
+
import { argumentSignature, getArguments, isIcuStructured, parseMessage } from "dialexjs/icu";
|
|
13
|
+
//#region src/utils/detector.ts
|
|
14
|
+
/**
|
|
15
|
+
* Automatically inspects package.json dependencies and configuration files
|
|
16
|
+
* to detect the active framework in the target project.
|
|
17
|
+
*/
|
|
18
|
+
function detectFramework(root) {
|
|
19
|
+
const pkgPath = path.join(root, "package.json");
|
|
20
|
+
if (fs.existsSync(pkgPath)) try {
|
|
21
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
22
|
+
const allDeps = {
|
|
23
|
+
...pkg.dependencies,
|
|
24
|
+
...pkg.devDependencies
|
|
25
|
+
};
|
|
26
|
+
if ("nuxt" in allDeps) return {
|
|
27
|
+
framework: "nuxt",
|
|
28
|
+
confidence: "high",
|
|
29
|
+
matchedRule: "package.json dependencies (nuxt)"
|
|
30
|
+
};
|
|
31
|
+
if ("@sveltejs/kit" in allDeps) return {
|
|
32
|
+
framework: "sveltekit",
|
|
33
|
+
confidence: "high",
|
|
34
|
+
matchedRule: "package.json dependencies (@sveltejs/kit)"
|
|
35
|
+
};
|
|
36
|
+
if ("astro" in allDeps) return {
|
|
37
|
+
framework: "astro",
|
|
38
|
+
confidence: "high",
|
|
39
|
+
matchedRule: "package.json dependencies (astro)"
|
|
40
|
+
};
|
|
41
|
+
if ("next" in allDeps) return {
|
|
42
|
+
framework: "next",
|
|
43
|
+
confidence: "high",
|
|
44
|
+
matchedRule: "package.json dependencies (next)"
|
|
45
|
+
};
|
|
46
|
+
if ("@nestjs/core" in allDeps || "@nestjs/common" in allDeps) return {
|
|
47
|
+
framework: "nestjs",
|
|
48
|
+
confidence: "high",
|
|
49
|
+
matchedRule: "package.json dependencies (@nestjs/core)"
|
|
50
|
+
};
|
|
51
|
+
if ("fastify" in allDeps) return {
|
|
52
|
+
framework: "fastify",
|
|
53
|
+
confidence: "high",
|
|
54
|
+
matchedRule: "package.json dependencies (fastify)"
|
|
55
|
+
};
|
|
56
|
+
if ("koa" in allDeps) return {
|
|
57
|
+
framework: "koa",
|
|
58
|
+
confidence: "high",
|
|
59
|
+
matchedRule: "package.json dependencies (koa)"
|
|
60
|
+
};
|
|
61
|
+
if ("express" in allDeps) return {
|
|
62
|
+
framework: "express",
|
|
63
|
+
confidence: "high",
|
|
64
|
+
matchedRule: "package.json dependencies (express)"
|
|
65
|
+
};
|
|
66
|
+
if ("elysia" in allDeps) return {
|
|
67
|
+
framework: "elysia",
|
|
68
|
+
confidence: "high",
|
|
69
|
+
matchedRule: "package.json dependencies (elysia)"
|
|
70
|
+
};
|
|
71
|
+
if ("hono" in allDeps) return {
|
|
72
|
+
framework: "hono",
|
|
73
|
+
confidence: "high",
|
|
74
|
+
matchedRule: "package.json dependencies (hono)"
|
|
75
|
+
};
|
|
76
|
+
if ("vue" in allDeps && !("react" in allDeps)) return {
|
|
77
|
+
framework: "vue",
|
|
78
|
+
confidence: "high",
|
|
79
|
+
matchedRule: "package.json dependencies (vue)"
|
|
80
|
+
};
|
|
81
|
+
if ("react" in allDeps || "vite" in allDeps) return {
|
|
82
|
+
framework: "react",
|
|
83
|
+
confidence: "high",
|
|
84
|
+
matchedRule: "package.json dependencies (react/vite)"
|
|
85
|
+
};
|
|
86
|
+
} catch {}
|
|
87
|
+
if (fs.existsSync(path.join(root, "next.config.js")) || fs.existsSync(path.join(root, "next.config.mjs")) || fs.existsSync(path.join(root, "next.config.ts"))) return {
|
|
88
|
+
framework: "next",
|
|
89
|
+
confidence: "medium",
|
|
90
|
+
matchedRule: "next.config file presence"
|
|
91
|
+
};
|
|
92
|
+
for (const [framework, base] of [
|
|
93
|
+
["nuxt", "nuxt.config"],
|
|
94
|
+
["sveltekit", "svelte.config"],
|
|
95
|
+
["astro", "astro.config"]
|
|
96
|
+
]) if ([
|
|
97
|
+
"js",
|
|
98
|
+
"mjs",
|
|
99
|
+
"ts"
|
|
100
|
+
].some((ext) => fs.existsSync(path.join(root, `${base}.${ext}`)))) return {
|
|
101
|
+
framework,
|
|
102
|
+
confidence: "medium",
|
|
103
|
+
matchedRule: `${base} file presence`
|
|
104
|
+
};
|
|
105
|
+
if (fs.existsSync(path.join(root, "vite.config.js")) || fs.existsSync(path.join(root, "vite.config.mjs")) || fs.existsSync(path.join(root, "vite.config.ts"))) return {
|
|
106
|
+
framework: "react",
|
|
107
|
+
confidence: "medium",
|
|
108
|
+
matchedRule: "vite.config file presence"
|
|
109
|
+
};
|
|
110
|
+
return {
|
|
111
|
+
framework: "hono",
|
|
112
|
+
confidence: "fallback",
|
|
113
|
+
matchedRule: "default fallback"
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region src/commands/init.ts
|
|
118
|
+
async function runInit(options = {}) {
|
|
119
|
+
const root = options.cwd || process.cwd();
|
|
120
|
+
const detected = detectFramework(root);
|
|
121
|
+
const isInteractive = !options.yes && process.stdin.isTTY;
|
|
122
|
+
let framework = options.framework || detected.framework;
|
|
123
|
+
let defaultLocale = options.defaultLocale || "en";
|
|
124
|
+
let localesInput = options.locales || "en,tr";
|
|
125
|
+
if (isInteractive) {
|
|
126
|
+
p.intro(pc.bgCyan(pc.black(" dialex init ")));
|
|
127
|
+
const frameworkOptions = [
|
|
128
|
+
{
|
|
129
|
+
value: "hono",
|
|
130
|
+
label: "Hono",
|
|
131
|
+
hint: detected.framework === "hono" ? "detected" : void 0
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
value: "express",
|
|
135
|
+
label: "Express",
|
|
136
|
+
hint: detected.framework === "express" ? "detected" : void 0
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
value: "fastify",
|
|
140
|
+
label: "Fastify",
|
|
141
|
+
hint: detected.framework === "fastify" ? "detected" : void 0
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
value: "koa",
|
|
145
|
+
label: "Koa",
|
|
146
|
+
hint: detected.framework === "koa" ? "detected" : void 0
|
|
147
|
+
},
|
|
148
|
+
{
|
|
149
|
+
value: "nestjs",
|
|
150
|
+
label: "NestJS",
|
|
151
|
+
hint: detected.framework === "nestjs" ? "detected" : void 0
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
value: "next",
|
|
155
|
+
label: "Next.js",
|
|
156
|
+
hint: detected.framework === "next" ? "detected" : void 0
|
|
157
|
+
},
|
|
158
|
+
{
|
|
159
|
+
value: "react",
|
|
160
|
+
label: "React / Vite",
|
|
161
|
+
hint: detected.framework === "react" ? "detected" : void 0
|
|
162
|
+
},
|
|
163
|
+
{
|
|
164
|
+
value: "elysia",
|
|
165
|
+
label: "Elysia",
|
|
166
|
+
hint: detected.framework === "elysia" ? "detected" : void 0
|
|
167
|
+
},
|
|
168
|
+
{
|
|
169
|
+
value: "sveltekit",
|
|
170
|
+
label: "SvelteKit",
|
|
171
|
+
hint: detected.framework === "sveltekit" ? "detected" : void 0
|
|
172
|
+
},
|
|
173
|
+
{
|
|
174
|
+
value: "astro",
|
|
175
|
+
label: "Astro",
|
|
176
|
+
hint: detected.framework === "astro" ? "detected" : void 0
|
|
177
|
+
},
|
|
178
|
+
{
|
|
179
|
+
value: "vue",
|
|
180
|
+
label: "Vue / Vite",
|
|
181
|
+
hint: detected.framework === "vue" ? "detected" : void 0
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
value: "nuxt",
|
|
185
|
+
label: "Nuxt",
|
|
186
|
+
hint: detected.framework === "nuxt" ? "detected" : void 0
|
|
187
|
+
}
|
|
188
|
+
];
|
|
189
|
+
const selectedFramework = await p.select({
|
|
190
|
+
message: `Framework detected as ${pc.bold(detected.framework)} (${detected.matchedRule}). Select framework:`,
|
|
191
|
+
options: frameworkOptions,
|
|
192
|
+
initialValue: detected.framework
|
|
193
|
+
});
|
|
194
|
+
if (p.isCancel(selectedFramework)) {
|
|
195
|
+
p.cancel("Operation cancelled.");
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
framework = selectedFramework;
|
|
199
|
+
const inputDefault = await p.text({
|
|
200
|
+
message: "What is your default locale?",
|
|
201
|
+
initialValue: "en",
|
|
202
|
+
validate: (v) => !v || !v.trim() ? "Default locale cannot be empty" : void 0
|
|
203
|
+
});
|
|
204
|
+
if (p.isCancel(inputDefault)) {
|
|
205
|
+
p.cancel("Operation cancelled.");
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
defaultLocale = inputDefault.trim();
|
|
209
|
+
const inputLocales = await p.text({
|
|
210
|
+
message: "Comma-separated list of supported locales:",
|
|
211
|
+
initialValue: `${defaultLocale},tr`,
|
|
212
|
+
validate: (v) => !v || !v.trim() ? "Locales list cannot be empty" : void 0
|
|
213
|
+
});
|
|
214
|
+
if (p.isCancel(inputLocales)) {
|
|
215
|
+
p.cancel("Operation cancelled.");
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
localesInput = inputLocales.trim();
|
|
219
|
+
if (options.ai === void 0 && options.noAi === void 0) {
|
|
220
|
+
const confirmAi = await p.confirm({
|
|
221
|
+
message: "Configure AI agent support (Claude/Cursor skills, .mcp.json, AGENTS.md)?",
|
|
222
|
+
initialValue: true
|
|
223
|
+
});
|
|
224
|
+
if (!p.isCancel(confirmAi)) options.ai = confirmAi;
|
|
225
|
+
}
|
|
226
|
+
} else logger.info(`Auto-detected framework: ${pc.bold(framework)} (${detected.matchedRule})`);
|
|
227
|
+
const localeList = Array.from(/* @__PURE__ */ new Set([defaultLocale, ...localesInput.split(",").map((s) => s.trim()).filter(Boolean)]));
|
|
228
|
+
const configPath = fs.existsSync(path.join(root, "dialex.config.ts")) ? path.join(root, "dialex.config.ts") : fs.existsSync(path.join(root, "i18n.config.ts")) ? path.join(root, "i18n.config.ts") : path.join(root, "dialex.config.ts");
|
|
229
|
+
const configFileName = path.basename(configPath);
|
|
230
|
+
try {
|
|
231
|
+
if (fs.existsSync(configPath)) {
|
|
232
|
+
const mod = await loadFile(configPath);
|
|
233
|
+
if (mod && mod.exports.default) {
|
|
234
|
+
if (mod.exports.default.$args && mod.exports.default.$args[0]) {
|
|
235
|
+
mod.exports.default.$args[0].defaultLocale = defaultLocale;
|
|
236
|
+
mod.exports.default.$args[0].locales = localeList;
|
|
237
|
+
}
|
|
238
|
+
await writeFile(mod, configPath);
|
|
239
|
+
logger.success(`Updated ${pc.bold(configFileName)} via Magicast`);
|
|
240
|
+
}
|
|
241
|
+
} else {
|
|
242
|
+
const mod = parseModule(`import { defineConfig } from "dialexjs";
|
|
243
|
+
|
|
244
|
+
export default defineConfig({});
|
|
245
|
+
`);
|
|
246
|
+
mod.exports.default.$args[0].defaultLocale = defaultLocale;
|
|
247
|
+
mod.exports.default.$args[0].locales = localeList;
|
|
248
|
+
await writeFile(mod, configPath);
|
|
249
|
+
logger.success(`Created ${pc.bold(configFileName)} via Magicast`);
|
|
250
|
+
}
|
|
251
|
+
} catch (err) {
|
|
252
|
+
logger.warn(`Magicast config update notice: ${err.message || String(err)}`);
|
|
253
|
+
const fallback = `import { defineConfig } from "dialexjs";
|
|
254
|
+
|
|
255
|
+
export default defineConfig({
|
|
256
|
+
defaultLocale: "${defaultLocale}",
|
|
257
|
+
locales: [${localeList.map((l) => `"${l}"`).join(", ")}],
|
|
258
|
+
});
|
|
259
|
+
`;
|
|
260
|
+
fs.writeFileSync(configPath, fallback, "utf-8");
|
|
261
|
+
}
|
|
262
|
+
if (framework === "react" || framework === "vue") {
|
|
263
|
+
const possibleViteConfigs = [
|
|
264
|
+
path.join(root, "vite.config.ts"),
|
|
265
|
+
path.join(root, "vite.config.js"),
|
|
266
|
+
path.join(root, "vite.config.mjs")
|
|
267
|
+
];
|
|
268
|
+
for (const vConfig of possibleViteConfigs) if (fs.existsSync(vConfig)) try {
|
|
269
|
+
const vMod = await loadFile(vConfig);
|
|
270
|
+
addVitePlugin(vMod, {
|
|
271
|
+
from: "dialexjs/vite",
|
|
272
|
+
imported: "i18nPlugin",
|
|
273
|
+
constructor: "i18nPlugin"
|
|
274
|
+
});
|
|
275
|
+
await writeFile(vMod, vConfig);
|
|
276
|
+
logger.success(`Injected i18nPlugin() into ${pc.bold(path.basename(vConfig))} via Magicast`);
|
|
277
|
+
break;
|
|
278
|
+
} catch {}
|
|
279
|
+
}
|
|
280
|
+
if (framework === "nuxt") {
|
|
281
|
+
const nuxtConfig = [
|
|
282
|
+
"nuxt.config.ts",
|
|
283
|
+
"nuxt.config.js",
|
|
284
|
+
"nuxt.config.mjs"
|
|
285
|
+
].map((f) => path.join(root, f)).find((f) => fs.existsSync(f));
|
|
286
|
+
if (nuxtConfig) try {
|
|
287
|
+
const nMod = await loadFile(nuxtConfig);
|
|
288
|
+
addNuxtModule(nMod, "dialexjs/nuxt", "dialex", {
|
|
289
|
+
defaultLocale,
|
|
290
|
+
locales: localeList
|
|
291
|
+
});
|
|
292
|
+
await writeFile(nMod, nuxtConfig);
|
|
293
|
+
logger.success(`Registered dialexjs/nuxt in ${pc.bold(path.basename(nuxtConfig))} via Magicast`);
|
|
294
|
+
} catch {
|
|
295
|
+
logger.warn("Could not update the Nuxt config; add the dialexjs/nuxt module manually.");
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
const targetDir = fs.existsSync(path.join(root, "src")) ? path.join(root, "src") : root;
|
|
299
|
+
const dictPath = path.join(targetDir, "home.content.ts");
|
|
300
|
+
if (!fs.existsSync(dictPath)) {
|
|
301
|
+
const dictContent = `import { defineDictionary } from "dialexjs";
|
|
302
|
+
|
|
303
|
+
export default defineDictionary("home", {
|
|
304
|
+
${localeList.map((loc) => ` ${loc}: {
|
|
305
|
+
title: "Welcome to Dialex (${loc})!",
|
|
306
|
+
description: "Type-safe internationalization.",
|
|
307
|
+
greeting: (name: string) => "Hello, " + name + "!",
|
|
308
|
+
},`).join("\n")}
|
|
309
|
+
});
|
|
310
|
+
`;
|
|
311
|
+
fs.writeFileSync(dictPath, dictContent, "utf-8");
|
|
312
|
+
logger.success(`Created starter dictionary at ${pc.bold(path.relative(root, dictPath))}`);
|
|
313
|
+
} else logger.info("home.content.ts already exists, skipping creation.");
|
|
314
|
+
generateDictionaries(root);
|
|
315
|
+
logger.success("Generated types and standalone dictionary registry!");
|
|
316
|
+
const pkgPath = path.join(root, "package.json");
|
|
317
|
+
if (fs.existsSync(pkgPath)) try {
|
|
318
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
319
|
+
pkg.scripts = pkg.scripts || {};
|
|
320
|
+
if (!pkg.scripts["i18n:generate"]) {
|
|
321
|
+
pkg.scripts["i18n:generate"] = "dialex generate";
|
|
322
|
+
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf-8");
|
|
323
|
+
logger.success("Added \"i18n:generate\" script to package.json");
|
|
324
|
+
}
|
|
325
|
+
} catch {}
|
|
326
|
+
if (options.ai === true || options.yes && options.ai !== false && options.noAi !== true) try {
|
|
327
|
+
const claudeSkillDir = path.join(root, ".claude/skills/dialex");
|
|
328
|
+
fs.mkdirSync(claudeSkillDir, { recursive: true });
|
|
329
|
+
fs.writeFileSync(path.join(claudeSkillDir, "SKILL.md"), `---
|
|
330
|
+
name: dialex
|
|
331
|
+
description: Guide for internationalizing JavaScript and TypeScript apps with Dialex. Use when adding translations, creating content dictionaries, configuring locales, or using Dialex with frameworks like Next.js, React, Express, Hono, Fastify, SvelteKit, and Nuxt.
|
|
332
|
+
---
|
|
333
|
+
|
|
334
|
+
# Dialex Internationalization
|
|
335
|
+
|
|
336
|
+
Dialex is a high-performance, type-safe internationalization toolchain for JavaScript and TypeScript.
|
|
337
|
+
|
|
338
|
+
## Core Concepts
|
|
339
|
+
- Dictionaries are defined with \`defineDictionary("name", { ... })\` in \`*.content.ts\` files.
|
|
340
|
+
- Keys must match across all locales.
|
|
341
|
+
- ICU message syntax is supported for plurals and selects.
|
|
342
|
+
- Parity is validated at compile time with \`dialex check\`.
|
|
343
|
+
|
|
344
|
+
## Useful Commands
|
|
345
|
+
- \`dialex check --json\`: Check dictionary parity and references.
|
|
346
|
+
- \`dialex check --fix\`: Automatically insert missing keys marked with [TODO].
|
|
347
|
+
- \`dialex generate\`: Rebuild standalone dictionary bundle and types.
|
|
348
|
+
- \`dialex translate --locale <locale>\`: Automatically translate missing keys.
|
|
349
|
+
`, "utf-8");
|
|
350
|
+
const mcpConfigPath = path.join(root, ".mcp.json");
|
|
351
|
+
let mcpConfig = {};
|
|
352
|
+
if (fs.existsSync(mcpConfigPath)) try {
|
|
353
|
+
mcpConfig = JSON.parse(fs.readFileSync(mcpConfigPath, "utf-8"));
|
|
354
|
+
} catch {
|
|
355
|
+
mcpConfig = {};
|
|
356
|
+
}
|
|
357
|
+
mcpConfig.mcpServers = mcpConfig.mcpServers || {};
|
|
358
|
+
mcpConfig.mcpServers.dialex = mcpConfig.mcpServers.dialex || {
|
|
359
|
+
command: "npx",
|
|
360
|
+
args: ["@dialexjs/mcp"]
|
|
361
|
+
};
|
|
362
|
+
fs.writeFileSync(mcpConfigPath, JSON.stringify(mcpConfig, null, 2) + "\n", "utf-8");
|
|
363
|
+
const agentsMdPath = path.join(root, "AGENTS.md");
|
|
364
|
+
const dialexAgentSnippet = `
|
|
365
|
+
## Internationalization (Dialex)
|
|
366
|
+
|
|
367
|
+
This project uses [Dialex](https://github.com/awaiden/dialex) for type-safe internationalization.
|
|
368
|
+
- Dictionaries are in \`*.content.ts\` files using \`defineDictionary\`.
|
|
369
|
+
- Run \`dialex check --json\` to verify parity.
|
|
370
|
+
- Run \`dialex check --fix\` to insert missing keys marked with \`[TODO]\`.
|
|
371
|
+
- Run \`dialex generate\` or \`npm run i18n:generate\` to compile dictionary bundles and update types.
|
|
372
|
+
`;
|
|
373
|
+
if (!fs.existsSync(agentsMdPath)) fs.writeFileSync(agentsMdPath, dialexAgentSnippet.trimStart(), "utf-8");
|
|
374
|
+
else {
|
|
375
|
+
const existing = fs.readFileSync(agentsMdPath, "utf-8");
|
|
376
|
+
if (!existing.includes("Dialex")) fs.writeFileSync(agentsMdPath, existing.trimEnd() + "\n" + dialexAgentSnippet, "utf-8");
|
|
377
|
+
}
|
|
378
|
+
logger.success("Configured AI assistant support (.claude/skills, .mcp.json, AGENTS.md)");
|
|
379
|
+
} catch (err) {
|
|
380
|
+
logger.warn(`Could not finish AI configuration: ${err.message || String(err)}`);
|
|
381
|
+
}
|
|
382
|
+
logger.log("");
|
|
383
|
+
logger.info(pc.bold(`Quick start for ${framework.toUpperCase()}:`));
|
|
384
|
+
switch (framework) {
|
|
385
|
+
case "hono":
|
|
386
|
+
logger.log(`
|
|
387
|
+
import { Hono } from "hono";
|
|
388
|
+
import { i18n } from "dialexjs/hono";
|
|
389
|
+
import dictionaries from "./src/i18n.generated.js";
|
|
390
|
+
|
|
391
|
+
const app = new Hono();
|
|
392
|
+
app.use("*", i18n({ dictionaries }));
|
|
393
|
+
|
|
394
|
+
app.get("/", (c) => {
|
|
395
|
+
const dict = c.var.getDictionary("home");
|
|
396
|
+
return c.json({ title: dict.title });
|
|
397
|
+
});
|
|
398
|
+
`);
|
|
399
|
+
break;
|
|
400
|
+
case "fastify":
|
|
401
|
+
logger.log(`
|
|
402
|
+
import Fastify from "fastify";
|
|
403
|
+
import { i18nPlugin } from "dialexjs/fastify";
|
|
404
|
+
import dictionaries from "./src/i18n.generated.js";
|
|
405
|
+
|
|
406
|
+
const app = Fastify();
|
|
407
|
+
await app.register(i18nPlugin, { dictionaries });
|
|
408
|
+
|
|
409
|
+
app.get("/", (req) => {
|
|
410
|
+
const dict = req.getDictionary("home");
|
|
411
|
+
return { title: dict.title };
|
|
412
|
+
});
|
|
413
|
+
`);
|
|
414
|
+
break;
|
|
415
|
+
case "express":
|
|
416
|
+
logger.log(`
|
|
417
|
+
import express from "express";
|
|
418
|
+
import { i18n } from "dialexjs/express";
|
|
419
|
+
import dictionaries from "./src/i18n.generated.js";
|
|
420
|
+
|
|
421
|
+
const app = express();
|
|
422
|
+
app.use(i18n({ dictionaries }));
|
|
423
|
+
|
|
424
|
+
app.get("/", (req, res) => {
|
|
425
|
+
const dict = req.getDictionary("home");
|
|
426
|
+
res.json({ title: dict.title });
|
|
427
|
+
});
|
|
428
|
+
`);
|
|
429
|
+
break;
|
|
430
|
+
case "koa":
|
|
431
|
+
logger.log(`
|
|
432
|
+
import Koa from "koa";
|
|
433
|
+
import { i18n } from "dialexjs/koa";
|
|
434
|
+
import dictionaries from "./src/i18n.generated.js";
|
|
435
|
+
|
|
436
|
+
const app = new Koa();
|
|
437
|
+
app.use(i18n({ dictionaries }));
|
|
438
|
+
|
|
439
|
+
app.use((ctx) => {
|
|
440
|
+
const dict = ctx.getDictionary("home");
|
|
441
|
+
ctx.body = { title: dict.title };
|
|
442
|
+
});
|
|
443
|
+
`);
|
|
444
|
+
break;
|
|
445
|
+
case "nestjs":
|
|
446
|
+
logger.log(`
|
|
447
|
+
import { Module } from "@nestjs/common";
|
|
448
|
+
import { I18nModule } from "dialexjs/nestjs";
|
|
449
|
+
import dictionaries from "./src/i18n.generated.js";
|
|
450
|
+
|
|
451
|
+
@Module({
|
|
452
|
+
imports: [I18nModule.forRoot({ dictionaries })],
|
|
453
|
+
})
|
|
454
|
+
export class AppModule {}
|
|
455
|
+
`);
|
|
456
|
+
break;
|
|
457
|
+
case "next":
|
|
458
|
+
logger.log(`
|
|
459
|
+
import { getDictionary } from "dialexjs/server";
|
|
460
|
+
|
|
461
|
+
export default async function Page({ params }: { params: Promise<{ locale: string }> }) {
|
|
462
|
+
const { locale = "en" } = await params;
|
|
463
|
+
const dict = getDictionary("home", locale);
|
|
464
|
+
return <h1>{dict.title}</h1>;
|
|
465
|
+
}
|
|
466
|
+
`);
|
|
467
|
+
break;
|
|
468
|
+
case "elysia":
|
|
469
|
+
logger.log(`
|
|
470
|
+
import { Elysia } from "elysia";
|
|
471
|
+
import { i18n } from "dialexjs/elysia";
|
|
472
|
+
import dictionaries from "./src/i18n.generated.js";
|
|
473
|
+
|
|
474
|
+
new Elysia()
|
|
475
|
+
.use(i18n({ dictionaries }))
|
|
476
|
+
.get("/", ({ getDictionary }) => ({ title: getDictionary("home").title }))
|
|
477
|
+
.listen(3000);
|
|
478
|
+
`);
|
|
479
|
+
break;
|
|
480
|
+
case "sveltekit":
|
|
481
|
+
logger.log(`
|
|
482
|
+
// src/hooks.server.ts
|
|
483
|
+
import { i18nHandle } from "dialexjs/sveltekit";
|
|
484
|
+
import dictionaries from "./i18n.generated.js";
|
|
485
|
+
|
|
486
|
+
export const handle = i18nHandle({ dictionaries });
|
|
487
|
+
|
|
488
|
+
// src/app.html: <html lang="%dialex.lang%">
|
|
489
|
+
// In load functions: locals.getDictionary("home")
|
|
490
|
+
`);
|
|
491
|
+
break;
|
|
492
|
+
case "astro":
|
|
493
|
+
logger.log(`
|
|
494
|
+
// src/middleware.ts
|
|
495
|
+
import { i18n } from "dialexjs/astro";
|
|
496
|
+
import dictionaries from "./i18n.generated.js";
|
|
497
|
+
|
|
498
|
+
export const onRequest = i18n({ dictionaries });
|
|
499
|
+
|
|
500
|
+
// In pages: Astro.locals.getDictionary("home")
|
|
501
|
+
`);
|
|
502
|
+
break;
|
|
503
|
+
case "vue":
|
|
504
|
+
logger.log(`
|
|
505
|
+
// src/main.ts
|
|
506
|
+
import { createApp } from "vue";
|
|
507
|
+
import { createI18n } from "dialexjs/vue";
|
|
508
|
+
import App from "./App.vue";
|
|
509
|
+
|
|
510
|
+
createApp(App).use(createI18n()).mount("#app");
|
|
511
|
+
|
|
512
|
+
// In components: const dict = useDictionary("home")
|
|
513
|
+
`);
|
|
514
|
+
break;
|
|
515
|
+
case "nuxt":
|
|
516
|
+
logger.log(`
|
|
517
|
+
// nuxt.config.ts
|
|
518
|
+
export default defineNuxtConfig({
|
|
519
|
+
modules: ["dialexjs/nuxt"],
|
|
520
|
+
});
|
|
521
|
+
|
|
522
|
+
// In components: const dict = useDictionary("home")
|
|
523
|
+
`);
|
|
524
|
+
break;
|
|
525
|
+
default: logger.log(`
|
|
526
|
+
Import dictionaries and register your framework middleware to begin!
|
|
527
|
+
Run \`npm run i18n:generate\` whenever you add new dictionary files.
|
|
528
|
+
`);
|
|
529
|
+
}
|
|
530
|
+
if (isInteractive) p.outro(pc.green("✔ dialex is configured and ready to go!"));
|
|
531
|
+
}
|
|
532
|
+
//#endregion
|
|
533
|
+
//#region src/commands/check.ts
|
|
534
|
+
const DICTIONARY_IGNORE = [
|
|
535
|
+
"**/node_modules/**",
|
|
536
|
+
"**/dist/**",
|
|
537
|
+
"**/.next/**"
|
|
538
|
+
];
|
|
539
|
+
function addIssue(diag, issue) {
|
|
540
|
+
const level = issue.level === "error" ? "error" : "warning";
|
|
541
|
+
(level === "error" ? diag.errors : diag.warnings).push(issue.message);
|
|
542
|
+
diag.annotations.push({
|
|
543
|
+
level,
|
|
544
|
+
message: issue.message,
|
|
545
|
+
line: issue.range ? issue.range.start.line + 1 : void 0
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* Inserts keys that exist in one locale but not in another, copying the default-locale value
|
|
550
|
+
* (strings get a `[TODO]` prefix). Returns how many keys were inserted.
|
|
551
|
+
*/
|
|
552
|
+
async function applyFixes(files, configuredLocales, defaultLocale) {
|
|
553
|
+
let fixed = 0;
|
|
554
|
+
for (const file of files) {
|
|
555
|
+
const df = await loadDictionaryFile(file);
|
|
556
|
+
if (!df?.complete) continue;
|
|
557
|
+
const present = listLocales(df);
|
|
558
|
+
const targets = Array.from(/* @__PURE__ */ new Set([...present, ...configuredLocales]));
|
|
559
|
+
const sourceOrder = [defaultLocale, ...present.filter((l) => l !== defaultLocale)].filter((l) => present.includes(l));
|
|
560
|
+
const allPaths = /* @__PURE__ */ new Map();
|
|
561
|
+
for (const locale of present) for (const leaf of listLeaves(df, locale)) allPaths.set(leaf.path.join("\0"), leaf.path);
|
|
562
|
+
let changed = false;
|
|
563
|
+
for (const target of targets) for (const leafPath of allPaths.values()) {
|
|
564
|
+
if (hasPath(df, target, leafPath)) continue;
|
|
565
|
+
const source = sourceOrder.find((l) => l !== target && hasPath(df, l, leafPath));
|
|
566
|
+
if (source && copyLeaf(df, source, target, leafPath, (v) => `[TODO] ${v}`)) {
|
|
567
|
+
fixed++;
|
|
568
|
+
changed = true;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
if (changed) await saveDictionaryFile(df);
|
|
572
|
+
}
|
|
573
|
+
return fixed;
|
|
574
|
+
}
|
|
575
|
+
function escapeAnnotation(value) {
|
|
576
|
+
return value.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
|
|
577
|
+
}
|
|
578
|
+
async function runCheck(options = {}) {
|
|
579
|
+
const root = options.cwd || process.cwd();
|
|
580
|
+
const quiet = options.json === true;
|
|
581
|
+
const inlineConfig = options.config ? { configFile: options.config } : {};
|
|
582
|
+
const config = resolveI18nConfig(root, inlineConfig);
|
|
583
|
+
const include = config.include || "**/*.content.ts";
|
|
584
|
+
const configuredLocales = config.locales || [];
|
|
585
|
+
const defaultLocale = config.defaultLocale || "en";
|
|
586
|
+
const files = fg.sync(include, {
|
|
587
|
+
cwd: root,
|
|
588
|
+
absolute: true,
|
|
589
|
+
ignore: DICTIONARY_IGNORE
|
|
590
|
+
});
|
|
591
|
+
if (files.length === 0) {
|
|
592
|
+
if (!quiet) {
|
|
593
|
+
const patternStr = Array.isArray(include) ? include.join(", ") : include;
|
|
594
|
+
logger.warn(`No dictionary files found matching "${patternStr}".`);
|
|
595
|
+
}
|
|
596
|
+
const empty = {
|
|
597
|
+
success: true,
|
|
598
|
+
diagnostics: [],
|
|
599
|
+
totalIssues: 0,
|
|
600
|
+
totalWarnings: 0,
|
|
601
|
+
fixed: 0
|
|
602
|
+
};
|
|
603
|
+
if (quiet) console.log(JSON.stringify(empty, null, 2));
|
|
604
|
+
return empty;
|
|
605
|
+
}
|
|
606
|
+
let fixed = 0;
|
|
607
|
+
if (options.fix) {
|
|
608
|
+
fixed = await applyFixes(files, configuredLocales, defaultLocale);
|
|
609
|
+
if (fixed > 0 && !quiet) logger.success(`Inserted ${fixed} missing key${fixed === 1 ? "" : "s"} marked ${TODO_PREFIX.trim()}`);
|
|
610
|
+
}
|
|
611
|
+
const analysis = await analyzeProject({
|
|
612
|
+
root,
|
|
613
|
+
config,
|
|
614
|
+
src: options.src && options.src.length > 0 ? options.src : void 0,
|
|
615
|
+
runtime: true
|
|
616
|
+
});
|
|
617
|
+
const byFile = /* @__PURE__ */ new Map();
|
|
618
|
+
const dictionaryFiles = new Set(analysis.files);
|
|
619
|
+
for (const issue of analysis.issues) {
|
|
620
|
+
if (issue.level === "info") continue;
|
|
621
|
+
const rel = path.relative(root, issue.file);
|
|
622
|
+
let diag = byFile.get(rel);
|
|
623
|
+
if (!diag) {
|
|
624
|
+
diag = {
|
|
625
|
+
file: rel,
|
|
626
|
+
errors: [],
|
|
627
|
+
warnings: [],
|
|
628
|
+
annotations: []
|
|
629
|
+
};
|
|
630
|
+
byFile.set(rel, diag);
|
|
631
|
+
}
|
|
632
|
+
if (dictionaryFiles.has(issue.file) && issue.dictionary && !diag.name) diag.name = issue.dictionary;
|
|
633
|
+
addIssue(diag, issue);
|
|
634
|
+
}
|
|
635
|
+
const diagnostics = [...byFile.values()];
|
|
636
|
+
const totalIssues = diagnostics.reduce((n, d) => n + d.errors.length, 0);
|
|
637
|
+
const totalWarnings = diagnostics.reduce((n, d) => n + d.warnings.length, 0);
|
|
638
|
+
const reported = diagnostics.filter((d) => d.errors.length > 0 || d.warnings.length > 0);
|
|
639
|
+
const result = {
|
|
640
|
+
success: totalIssues === 0,
|
|
641
|
+
diagnostics: reported,
|
|
642
|
+
totalIssues,
|
|
643
|
+
totalWarnings,
|
|
644
|
+
fixed
|
|
645
|
+
};
|
|
646
|
+
if (options.github) for (const d of reported) for (const a of d.annotations) {
|
|
647
|
+
const location = `file=${d.file}${a.line ? `,line=${a.line}` : ""}`;
|
|
648
|
+
console.log(`::${a.level} ${location},title=dialex::${escapeAnnotation(a.message)}`);
|
|
649
|
+
}
|
|
650
|
+
if (quiet) console.log(JSON.stringify(result, null, 2));
|
|
651
|
+
else if (reported.length > 0) {
|
|
652
|
+
logger.log("");
|
|
653
|
+
if (totalIssues > 0) logger.error(`Found ${totalIssues} issue${totalIssues === 1 ? "" : "s"} across ${reported.filter((d) => d.errors.length > 0).length} file${reported.length === 1 ? "" : "s"}:`);
|
|
654
|
+
logger.log("");
|
|
655
|
+
for (const d of reported) {
|
|
656
|
+
logger.log(` ${pc.underline(pc.bold(d.file))} ${d.name ? pc.dim(`(${d.name})`) : ""}:`);
|
|
657
|
+
for (const a of d.annotations) {
|
|
658
|
+
const where = a.line ? pc.dim(`:${a.line}`) : "";
|
|
659
|
+
const mark = a.level === "error" ? pc.red("✖") : pc.yellow("⚠");
|
|
660
|
+
logger.log(` ${mark} ${a.message}${where}`);
|
|
661
|
+
}
|
|
662
|
+
logger.log("");
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
if (totalIssues > 0) {
|
|
666
|
+
if (options.exitOnError !== false) process.exit(1);
|
|
667
|
+
return result;
|
|
668
|
+
}
|
|
669
|
+
if (!quiet) {
|
|
670
|
+
const warningNote = totalWarnings > 0 ? ` (${totalWarnings} warning${totalWarnings === 1 ? "" : "s"})` : "";
|
|
671
|
+
logger.success(`All ${files.length} dictionary file${files.length === 1 ? "" : "s"} passed checks with 0 issues${warningNote}!`);
|
|
672
|
+
}
|
|
673
|
+
return result;
|
|
674
|
+
}
|
|
675
|
+
//#endregion
|
|
676
|
+
//#region src/commands/export.ts
|
|
677
|
+
const escapeXml = (value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
678
|
+
const csvCell = (value) => /[",\r\n]/.test(value) ? `"${value.replace(/"/g, "\"\"")}"` : value;
|
|
679
|
+
async function runExport(options = {}) {
|
|
680
|
+
const root = options.cwd || process.cwd();
|
|
681
|
+
const format = options.format || "json";
|
|
682
|
+
if (![
|
|
683
|
+
"json",
|
|
684
|
+
"csv",
|
|
685
|
+
"xliff"
|
|
686
|
+
].includes(format)) throw new Error(`Unsupported format "${format}". Use json, csv, or xliff.`);
|
|
687
|
+
const outDir = path.resolve(root, options.out || "i18n-export");
|
|
688
|
+
const project = await loadProject(root, options.config);
|
|
689
|
+
const defaultLocale = project.config.defaultLocale || "en";
|
|
690
|
+
const table = /* @__PURE__ */ new Map();
|
|
691
|
+
const orderedKeys = /* @__PURE__ */ new Set();
|
|
692
|
+
let skippedFunctions = 0;
|
|
693
|
+
const localeSet = new Set(project.config.locales || []);
|
|
694
|
+
for (const { df } of project.dictionaries) listLocales(df).forEach((l) => localeSet.add(l));
|
|
695
|
+
let locales = Array.from(localeSet);
|
|
696
|
+
if (options.locale && options.locale.length > 0) locales = locales.filter((l) => options.locale.includes(l) || l === defaultLocale);
|
|
697
|
+
for (const locale of locales) table.set(locale, /* @__PURE__ */ new Map());
|
|
698
|
+
for (const { name, df } of project.dictionaries) for (const locale of listLocales(df)) {
|
|
699
|
+
if (!table.has(locale)) continue;
|
|
700
|
+
for (const leaf of listLeaves(df, locale)) if (leaf.kind === "string" && leaf.value !== void 0) {
|
|
701
|
+
const key = toKey(name, leaf.path);
|
|
702
|
+
table.get(locale).set(key, leaf.value);
|
|
703
|
+
orderedKeys.add(key);
|
|
704
|
+
} else if (locale === defaultLocale) skippedFunctions++;
|
|
705
|
+
}
|
|
706
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
707
|
+
const files = [];
|
|
708
|
+
const write = (name, content) => {
|
|
709
|
+
const file = path.join(outDir, name);
|
|
710
|
+
fs.writeFileSync(file, content, "utf-8");
|
|
711
|
+
files.push(path.relative(root, file));
|
|
712
|
+
};
|
|
713
|
+
if (format === "json") for (const [locale, values] of table) write(`${locale}.json`, JSON.stringify(Object.fromEntries(values), null, 2) + "\n");
|
|
714
|
+
else if (format === "csv") write("translations.csv", [["key", ...table.keys()].map(csvCell).join(","), ...[...orderedKeys].map((key) => [key, ...[...table.values()].map((v) => v.get(key) ?? "")].map(csvCell).join(","))].join("\n") + "\n");
|
|
715
|
+
else {
|
|
716
|
+
const source = table.get(defaultLocale);
|
|
717
|
+
for (const [locale, values] of table) {
|
|
718
|
+
if (locale === defaultLocale) continue;
|
|
719
|
+
const units = [...orderedKeys].map((key) => {
|
|
720
|
+
const src = source?.get(key) ?? "";
|
|
721
|
+
const target = values.get(key);
|
|
722
|
+
const targetXml = target === void 0 ? "" : `<target>${escapeXml(target)}</target>`;
|
|
723
|
+
return ` <trans-unit id="${escapeXml(key)}"><source>${escapeXml(src)}</source>${targetXml}</trans-unit>`;
|
|
724
|
+
});
|
|
725
|
+
write(`${locale}.xlf`, `<?xml version="1.0" encoding="UTF-8"?>
|
|
726
|
+
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
|
|
727
|
+
<file original="dialex" source-language="${escapeXml(defaultLocale)}" target-language="${escapeXml(locale)}" datatype="plaintext">
|
|
728
|
+
<body>
|
|
729
|
+
${units.join("\n")}
|
|
730
|
+
</body>
|
|
731
|
+
</file>
|
|
732
|
+
</xliff>
|
|
733
|
+
`);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
const quiet = options.json === true;
|
|
737
|
+
const result = {
|
|
738
|
+
success: true,
|
|
739
|
+
files,
|
|
740
|
+
keys: orderedKeys.size,
|
|
741
|
+
skippedFunctions,
|
|
742
|
+
skippedFiles: project.unsupported
|
|
743
|
+
};
|
|
744
|
+
if (quiet) console.log(JSON.stringify(result, null, 2));
|
|
745
|
+
else {
|
|
746
|
+
logger.success(`Exported ${orderedKeys.size} key${orderedKeys.size === 1 ? "" : "s"} to ${files.length} ${format} file${files.length === 1 ? "" : "s"} in ${path.relative(root, outDir) || "."}`);
|
|
747
|
+
if (skippedFunctions > 0) logger.warn(`${skippedFunctions} function value${skippedFunctions === 1 ? "" : "s"} skipped (not translatable as text)`);
|
|
748
|
+
for (const file of project.unsupported) logger.warn(`Skipped ${file}: unsupported dictionary shape`);
|
|
749
|
+
}
|
|
750
|
+
return result;
|
|
751
|
+
}
|
|
752
|
+
//#endregion
|
|
753
|
+
//#region src/commands/import.ts
|
|
754
|
+
const unescapeXml = (value) => value.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, "\"").replace(/'/g, "'").replace(/&/g, "&");
|
|
755
|
+
function parseCsv(text) {
|
|
756
|
+
const rows = [];
|
|
757
|
+
let row = [];
|
|
758
|
+
let cell = "";
|
|
759
|
+
let quoted = false;
|
|
760
|
+
for (let i = 0; i < text.length; i++) {
|
|
761
|
+
const ch = text[i];
|
|
762
|
+
if (quoted) {
|
|
763
|
+
if (ch === "\"" && text[i + 1] === "\"") {
|
|
764
|
+
cell += "\"";
|
|
765
|
+
i++;
|
|
766
|
+
} else if (ch === "\"") quoted = false;
|
|
767
|
+
else cell += ch;
|
|
768
|
+
} else if (ch === "\"") quoted = true;
|
|
769
|
+
else if (ch === ",") {
|
|
770
|
+
row.push(cell);
|
|
771
|
+
cell = "";
|
|
772
|
+
} else if (ch === "\n" || ch === "\r") {
|
|
773
|
+
if (ch === "\r" && text[i + 1] === "\n") i++;
|
|
774
|
+
row.push(cell);
|
|
775
|
+
rows.push(row);
|
|
776
|
+
row = [];
|
|
777
|
+
cell = "";
|
|
778
|
+
} else cell += ch;
|
|
779
|
+
}
|
|
780
|
+
if (cell !== "" || row.length > 0) {
|
|
781
|
+
row.push(cell);
|
|
782
|
+
rows.push(row);
|
|
783
|
+
}
|
|
784
|
+
return rows.filter((r) => r.some((c) => c !== ""));
|
|
785
|
+
}
|
|
786
|
+
function parseEntries(content, format, fallbackLocale) {
|
|
787
|
+
const entries = [];
|
|
788
|
+
if (format === "json") {
|
|
789
|
+
const data = JSON.parse(content);
|
|
790
|
+
if (Object.keys(data).length > 0 && Object.values(data).every((v) => v && typeof v === "object" && !Array.isArray(v))) {
|
|
791
|
+
for (const [locale, values] of Object.entries(data)) for (const [key, value] of Object.entries(values)) if (typeof value === "string") entries.push({
|
|
792
|
+
locale,
|
|
793
|
+
key,
|
|
794
|
+
value
|
|
795
|
+
});
|
|
796
|
+
} else {
|
|
797
|
+
if (!fallbackLocale) throw new Error("Cannot infer the locale; pass --locale.");
|
|
798
|
+
for (const [key, value] of Object.entries(data)) if (typeof value === "string") entries.push({
|
|
799
|
+
locale: fallbackLocale,
|
|
800
|
+
key,
|
|
801
|
+
value
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
} else if (format === "csv") {
|
|
805
|
+
const [header, ...rows] = parseCsv(content);
|
|
806
|
+
if (!header || header[0] !== "key") throw new Error("CSV must start with a \"key\" column.");
|
|
807
|
+
for (const row of rows) header.slice(1).forEach((locale, i) => {
|
|
808
|
+
const value = row[i + 1];
|
|
809
|
+
if (value !== void 0 && value !== "") entries.push({
|
|
810
|
+
locale,
|
|
811
|
+
key: row[0],
|
|
812
|
+
value
|
|
813
|
+
});
|
|
814
|
+
});
|
|
815
|
+
} else {
|
|
816
|
+
const locale = /target-language="([^"]*)"/.exec(content)?.[1] ?? fallbackLocale;
|
|
817
|
+
if (!locale) throw new Error("Cannot infer the locale; pass --locale.");
|
|
818
|
+
for (const match of content.matchAll(/<trans-unit\b[^>]*\bid="([^"]*)"[^>]*>([\s\S]*?)<\/trans-unit>/g)) {
|
|
819
|
+
const target = /<target\b[^>]*>([\s\S]*?)<\/target>/.exec(match[2])?.[1];
|
|
820
|
+
if (target !== void 0 && target !== "") entries.push({
|
|
821
|
+
locale,
|
|
822
|
+
key: unescapeXml(match[1]),
|
|
823
|
+
value: unescapeXml(target)
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
return entries;
|
|
828
|
+
}
|
|
829
|
+
function inferFormat(file) {
|
|
830
|
+
const ext = path.extname(file).toLowerCase();
|
|
831
|
+
if (ext === ".json") return "json";
|
|
832
|
+
if (ext === ".csv") return "csv";
|
|
833
|
+
if (ext === ".xlf" || ext === ".xliff") return "xliff";
|
|
834
|
+
throw new Error(`Cannot infer format from "${ext}". Pass --format json|csv|xliff.`);
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* Why `value` must not replace the current text, if it is an ICU message that is invalid or uses
|
|
838
|
+
* different arguments than the same key in another locale.
|
|
839
|
+
*/
|
|
840
|
+
function icuProblem(df, defaultLocale, locale, keyPath, value) {
|
|
841
|
+
if (!value.includes("{")) return void 0;
|
|
842
|
+
let signature;
|
|
843
|
+
try {
|
|
844
|
+
signature = argumentSignature(parseMessage(value));
|
|
845
|
+
} catch (error) {
|
|
846
|
+
return `invalid ICU: ${error.message}`;
|
|
847
|
+
}
|
|
848
|
+
const locales = listLocales(df);
|
|
849
|
+
for (const other of [defaultLocale, ...locales.filter((l) => l !== defaultLocale)]) {
|
|
850
|
+
if (other === locale) continue;
|
|
851
|
+
const reference = getString(df, other, keyPath);
|
|
852
|
+
if (!reference?.includes("{")) continue;
|
|
853
|
+
try {
|
|
854
|
+
const expected = argumentSignature(parseMessage(reference));
|
|
855
|
+
return expected === signature ? void 0 : `arguments differ from "${other}": expected ${expected || "none"}, found ${signature || "none"}`;
|
|
856
|
+
} catch {
|
|
857
|
+
continue;
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
async function runImport(options) {
|
|
862
|
+
const root = options.cwd || process.cwd();
|
|
863
|
+
const file = path.resolve(root, options.file);
|
|
864
|
+
const format = options.format || inferFormat(file);
|
|
865
|
+
const fallbackLocale = options.locale ?? path.basename(file, path.extname(file));
|
|
866
|
+
const entries = parseEntries(fs.readFileSync(file, "utf-8"), format, options.locale ?? fallbackLocale);
|
|
867
|
+
const project = await loadProject(root, options.config);
|
|
868
|
+
const byName = new Map(project.dictionaries.map((d) => [d.name, d]));
|
|
869
|
+
const quiet = options.json === true;
|
|
870
|
+
const result = {
|
|
871
|
+
success: true,
|
|
872
|
+
created: 0,
|
|
873
|
+
updated: 0,
|
|
874
|
+
skipped: [],
|
|
875
|
+
rejected: [],
|
|
876
|
+
unknown: [],
|
|
877
|
+
errors: []
|
|
878
|
+
};
|
|
879
|
+
const touched = /* @__PURE__ */ new Set();
|
|
880
|
+
for (const { locale, key, value } of entries) {
|
|
881
|
+
const [name, ...keyPath] = key.split(".");
|
|
882
|
+
const dict = byName.get(name);
|
|
883
|
+
if (!dict || keyPath.length === 0) {
|
|
884
|
+
result.unknown.push(key);
|
|
885
|
+
continue;
|
|
886
|
+
}
|
|
887
|
+
if (!listLocales(dict.df).some((l) => hasPath(dict.df, l, keyPath)) && !options.allowNew) {
|
|
888
|
+
result.unknown.push(key);
|
|
889
|
+
continue;
|
|
890
|
+
}
|
|
891
|
+
const problem = icuProblem(dict.df, project.config.defaultLocale ?? "en", locale, keyPath, value);
|
|
892
|
+
if (problem) {
|
|
893
|
+
result.rejected.push(`${locale}:${key} (${problem})`);
|
|
894
|
+
continue;
|
|
895
|
+
}
|
|
896
|
+
const outcome = setString(dict.df, locale, keyPath, value);
|
|
897
|
+
if (outcome === "skipped") result.skipped.push(`${locale}:${key}`);
|
|
898
|
+
else {
|
|
899
|
+
result[outcome]++;
|
|
900
|
+
touched.add(dict.rel);
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
for (const dict of project.dictionaries) if (touched.has(dict.rel)) await saveDictionaryFile(dict.df);
|
|
904
|
+
if (result.rejected.length > 0) result.success = false;
|
|
905
|
+
if (quiet) console.log(JSON.stringify(result, null, 2));
|
|
906
|
+
else {
|
|
907
|
+
logger.success(`Imported ${result.created + result.updated} value${result.created + result.updated === 1 ? "" : "s"} (${result.created} added, ${result.updated} updated)`);
|
|
908
|
+
if (result.unknown.length > 0) logger.warn(`${result.unknown.length} unknown key${result.unknown.length === 1 ? "" : "s"} ignored (use --allow-new to add): ${result.unknown.slice(0, 5).join(", ")}${result.unknown.length > 5 ? ", ..." : ""}`);
|
|
909
|
+
if (result.rejected.length > 0) logger.warn(`${result.rejected.length} value${result.rejected.length === 1 ? "" : "s"} rejected: ${result.rejected.slice(0, 5).join("; ")}`);
|
|
910
|
+
if (result.skipped.length > 0) logger.warn(`${result.skipped.length} non-text value${result.skipped.length === 1 ? "" : "s"} left unchanged: ${result.skipped.slice(0, 5).join(", ")}`);
|
|
911
|
+
}
|
|
912
|
+
return result;
|
|
913
|
+
}
|
|
914
|
+
//#endregion
|
|
915
|
+
//#region src/translate/placeholders.ts
|
|
916
|
+
/** `{name}`, `%s` / `%1$d`, and HTML/XML tags: text that must survive translation unchanged. */
|
|
917
|
+
const PLACEHOLDER = /\{[^{}]+\}|%\d*\$?[sdif]|<\/?[A-Za-z][^<>]*>/g;
|
|
918
|
+
function extractPlaceholders(text) {
|
|
919
|
+
return text.match(PLACEHOLDER) ?? [];
|
|
920
|
+
}
|
|
921
|
+
/**
|
|
922
|
+
* ICU plural/select messages put translatable text inside `{...}` branches, so brace matching
|
|
923
|
+
* is meaningless for them. Compare the structure instead: the same arguments with the same
|
|
924
|
+
* types, every `select` key and every exact `=N` plural match preserved. A translation may
|
|
925
|
+
* add or drop plural categories (`one`, `few`, ...), because languages need different ones.
|
|
926
|
+
*/
|
|
927
|
+
function preservesIcuStructure(source, translated) {
|
|
928
|
+
try {
|
|
929
|
+
const before = getArguments(parseMessage(source));
|
|
930
|
+
const after = getArguments(parseMessage(translated));
|
|
931
|
+
if (!(before.length === after.length && before.every((a) => after.some((b) => a.name === b.name && a.type === b.type)))) return false;
|
|
932
|
+
return before.every((a) => {
|
|
933
|
+
const other = after.find((b) => b.name === a.name && b.type === a.type);
|
|
934
|
+
return (a.type === "select" ? a.selectors ?? [] : (a.selectors ?? []).filter((selector) => selector.startsWith("="))).every((selector) => other.selectors?.includes(selector));
|
|
935
|
+
});
|
|
936
|
+
} catch {
|
|
937
|
+
return false;
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
/** True when every placeholder of `source` appears in `translated` (as many times as in the source). */
|
|
941
|
+
function preservesPlaceholders(source, translated) {
|
|
942
|
+
if (isIcuStructured(source)) return preservesIcuStructure(source, translated);
|
|
943
|
+
const remaining = extractPlaceholders(translated);
|
|
944
|
+
for (const placeholder of extractPlaceholders(source)) {
|
|
945
|
+
const index = remaining.indexOf(placeholder);
|
|
946
|
+
if (index === -1) return false;
|
|
947
|
+
remaining.splice(index, 1);
|
|
948
|
+
}
|
|
949
|
+
return true;
|
|
950
|
+
}
|
|
951
|
+
//#endregion
|
|
952
|
+
//#region src/commands/translate.ts
|
|
953
|
+
async function runTranslate(options = {}) {
|
|
954
|
+
const root = options.cwd || process.cwd();
|
|
955
|
+
const project = await loadProject(root, options.config);
|
|
956
|
+
const settings = project.config.translate;
|
|
957
|
+
const provider = options.provider ?? settings?.provider;
|
|
958
|
+
if (!provider && !options.dryRun) throw new Error("No translate provider configured. Add `translate: { provider: claudeProvider() }` to dialex.config.ts (import it from \"@dialexjs/cli/translate\").");
|
|
959
|
+
const source = options.source ?? settings?.sourceLocale ?? project.config.defaultLocale ?? "en";
|
|
960
|
+
const everyLocale = new Set(project.config.locales ?? []);
|
|
961
|
+
for (const { df } of project.dictionaries) listLocales(df).forEach((l) => everyLocale.add(l));
|
|
962
|
+
const targets = (options.locale?.length ? options.locale : [...everyLocale]).filter((l) => l !== source);
|
|
963
|
+
const tasks = [];
|
|
964
|
+
for (const dict of project.dictionaries) {
|
|
965
|
+
const sourceLeaves = listLeaves(dict.df, source).filter((leaf) => leaf.kind === "string" && leaf.value !== void 0);
|
|
966
|
+
for (const locale of targets) {
|
|
967
|
+
const existing = new Map(listLeaves(dict.df, locale).map((leaf) => [leaf.path.join("\0"), leaf]));
|
|
968
|
+
for (const leaf of sourceLeaves) {
|
|
969
|
+
const current = existing.get(leaf.path.join("\0"));
|
|
970
|
+
if (!current || current.kind === "string" && current.value?.startsWith("[TODO] ")) tasks.push({
|
|
971
|
+
dict,
|
|
972
|
+
path: leaf.path,
|
|
973
|
+
file: dict.rel,
|
|
974
|
+
locale,
|
|
975
|
+
key: toKey(dict.name, leaf.path),
|
|
976
|
+
source: leaf.value
|
|
977
|
+
});
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
const quiet = options.json === true;
|
|
982
|
+
const result = {
|
|
983
|
+
success: true,
|
|
984
|
+
dryRun: options.dryRun === true,
|
|
985
|
+
pending: tasks,
|
|
986
|
+
translated: 0,
|
|
987
|
+
rejected: []
|
|
988
|
+
};
|
|
989
|
+
if (tasks.length === 0) {
|
|
990
|
+
if (quiet) console.log(JSON.stringify(result, null, 2));
|
|
991
|
+
else logger.success(`Nothing to translate from "${source}".`);
|
|
992
|
+
return result;
|
|
993
|
+
}
|
|
994
|
+
if (options.dryRun) {
|
|
995
|
+
if (quiet) console.log(JSON.stringify(result, null, 2));
|
|
996
|
+
else {
|
|
997
|
+
logger.info(`Would translate ${tasks.length} string${tasks.length === 1 ? "" : "s"} from "${source}":`);
|
|
998
|
+
for (const t of tasks) logger.log(` ${pc.dim(t.locale)} ${t.key} ${pc.dim(JSON.stringify(t.source))}`);
|
|
999
|
+
}
|
|
1000
|
+
return result;
|
|
1001
|
+
}
|
|
1002
|
+
const touched = /* @__PURE__ */ new Set();
|
|
1003
|
+
for (const locale of targets) {
|
|
1004
|
+
const localeTasks = tasks.filter((t) => t.locale === locale);
|
|
1005
|
+
if (localeTasks.length === 0) continue;
|
|
1006
|
+
const sendable = provider.supportsIcu ? localeTasks : localeTasks.filter((task) => {
|
|
1007
|
+
if (!isIcuStructured(task.source)) return true;
|
|
1008
|
+
result.rejected.push(`${locale}:${task.key} (provider does not support ICU plural/select messages)`);
|
|
1009
|
+
return false;
|
|
1010
|
+
});
|
|
1011
|
+
if (sendable.length === 0) continue;
|
|
1012
|
+
const unique = [...new Set(sendable.map((t) => t.source))];
|
|
1013
|
+
if (!quiet) logger.info(`Translating ${unique.length} string${unique.length === 1 ? "" : "s"} to "${locale}" with ${provider.name ?? "provider"}...`);
|
|
1014
|
+
const translations = await provider.translate(unique, source, locale);
|
|
1015
|
+
if (translations.length !== unique.length) throw new Error(`Provider returned ${translations.length} translations for ${unique.length} strings.`);
|
|
1016
|
+
const byText = new Map(unique.map((text, i) => [text, translations[i]]));
|
|
1017
|
+
for (const task of sendable) {
|
|
1018
|
+
const translated = byText.get(task.source);
|
|
1019
|
+
if (typeof translated !== "string" || translated.trim() === "") {
|
|
1020
|
+
result.rejected.push(`${locale}:${task.key} (empty translation)`);
|
|
1021
|
+
continue;
|
|
1022
|
+
}
|
|
1023
|
+
if (!preservesPlaceholders(task.source, translated)) {
|
|
1024
|
+
result.rejected.push(`${locale}:${task.key} (placeholders changed)`);
|
|
1025
|
+
continue;
|
|
1026
|
+
}
|
|
1027
|
+
if (setString(task.dict.df, locale, task.path, translated) === "skipped") {
|
|
1028
|
+
result.rejected.push(`${locale}:${task.key} (not a text value)`);
|
|
1029
|
+
continue;
|
|
1030
|
+
}
|
|
1031
|
+
task.translated = translated;
|
|
1032
|
+
result.translated++;
|
|
1033
|
+
touched.add(task.dict);
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
for (const dict of touched) await saveDictionaryFile(dict.df);
|
|
1037
|
+
if (result.rejected.length > 0) result.success = false;
|
|
1038
|
+
if (quiet) console.log(JSON.stringify(result, null, 2));
|
|
1039
|
+
else {
|
|
1040
|
+
logger.success(`Translated ${result.translated} of ${tasks.length} string${tasks.length === 1 ? "" : "s"}.`);
|
|
1041
|
+
if (result.rejected.length > 0) logger.warn(`${result.rejected.length} left unchanged: ${result.rejected.slice(0, 5).join("; ")}${result.rejected.length > 5 ? "; ..." : ""}`);
|
|
1042
|
+
}
|
|
1043
|
+
return result;
|
|
1044
|
+
}
|
|
1045
|
+
//#endregion
|
|
1046
|
+
//#region src/index.ts
|
|
1047
|
+
const program = new Command();
|
|
1048
|
+
program.name("dialex").description("Dialex CLI - High-performance, type-safe internationalization compiler and tooling").version("0.2.0");
|
|
1049
|
+
program.command("generate").alias("gen").description("Generate standalone dictionary bundle and TypeScript declarations").option("-w, --watch", "Watch dictionary files for changes").option("-o, --output <path>", "Custom output file path for generated dictionaries").option("-c, --config <path>", "Custom config path").option("--json", "Print machine-readable JSON").action(async (opts) => {
|
|
1050
|
+
await runGenerate(opts);
|
|
1051
|
+
});
|
|
1052
|
+
program.command("init").description("Initialize Dialex in the current project").option("-f, --framework <framework>", "Target framework (hono, express, fastify, koa, nestjs, next, react)").option("-d, --default-locale <locale>", "Default locale (e.g. en)").option("-l, --locales <locales>", "Comma-separated supported locales (e.g. en,tr)").option("-y, --yes", "Skip prompts and use defaults").option("--ai", "Configure AI agent support (.claude/skills, .mcp.json, AGENTS.md)").option("--no-ai", "Skip AI agent configuration").action(async (opts) => {
|
|
1053
|
+
await runInit(opts);
|
|
1054
|
+
});
|
|
1055
|
+
program.command("check").alias("lint").description("Verify dictionary key parity and locale completeness").option("-c, --config <path>", "Custom config path").option("--json", "Print machine-readable JSON").option("--github", "Print GitHub Actions annotations").option("--fix", "Insert missing keys marked with [TODO]").option("--src <globs...>", "Source globs to scan for dictionary references").action(async (opts) => {
|
|
1056
|
+
await runCheck(opts);
|
|
1057
|
+
});
|
|
1058
|
+
program.command("export").description("Export dictionary strings for translators (json, csv, or xliff)").option("-f, --format <format>", "Output format: json, csv, xliff", "json").option("-o, --out <dir>", "Output directory", "i18n-export").option("-l, --locale <locales...>", "Limit to these locales").option("-c, --config <path>", "Custom config path").option("--json", "Print machine-readable JSON").action(async (opts) => {
|
|
1059
|
+
await runExport(opts);
|
|
1060
|
+
});
|
|
1061
|
+
program.command("import <file>").description("Write translated strings from a json, csv, or xliff file back into dictionaries").option("-f, --format <format>", "Input format (inferred from the extension)").option("-l, --locale <locale>", "Locale for single-locale files").option("--allow-new", "Add keys that do not exist in any locale yet").option("-c, --config <path>", "Custom config path").option("--json", "Print machine-readable JSON").action(async (file, opts) => {
|
|
1062
|
+
await runImport({
|
|
1063
|
+
file,
|
|
1064
|
+
...opts
|
|
1065
|
+
});
|
|
1066
|
+
});
|
|
1067
|
+
program.command("translate").description("Fill missing translations with the provider configured in dialex.config.ts").option("-l, --locale <locales...>", "Target locales (default: all configured)").option("-s, --source <locale>", "Source locale (default: translate.sourceLocale or defaultLocale)").option("--dry-run", "List what would be translated without calling the provider").option("-c, --config <path>", "Custom config path").option("--json", "Print machine-readable JSON").action(async (opts) => {
|
|
1068
|
+
try {
|
|
1069
|
+
await runTranslate(opts);
|
|
1070
|
+
} catch (err) {
|
|
1071
|
+
if (opts.json) console.log(JSON.stringify({
|
|
1072
|
+
success: false,
|
|
1073
|
+
error: err.message || String(err)
|
|
1074
|
+
}, null, 2));
|
|
1075
|
+
else logger.error(err.message || String(err));
|
|
1076
|
+
process.exit(1);
|
|
1077
|
+
}
|
|
1078
|
+
});
|
|
1079
|
+
program.parse();
|
|
1080
|
+
//#endregion
|
|
1081
|
+
export {};
|
|
1082
|
+
|
|
1083
|
+
//# sourceMappingURL=index.mjs.map
|